1use anyhow::{anyhow, Result};
2use async_trait::async_trait;
3use collections::HashMap;
4use futures::{
5 future::{self, BoxFuture},
6 FutureExt, StreamExt,
7};
8use gpui::AppContext;
9use language::{LanguageServerName, LspAdapter, LspAdapterDelegate};
10use lsp::LanguageServerBinary;
11use node_runtime::NodeRuntime;
12use serde_json::{json, Value};
13use smol::fs;
14use std::{
15 any::Any,
16 ffi::OsString,
17 path::{Path, PathBuf},
18 sync::Arc,
19};
20use util::ResultExt;
21
22const SERVER_PATH: &'static str = "node_modules/.bin/tailwindcss-language-server";
23
24fn server_binary_arguments(server_path: &Path) -> Vec<OsString> {
25 vec![server_path.into(), "--stdio".into()]
26}
27
28pub struct TailwindLspAdapter {
29 node: Arc<dyn NodeRuntime>,
30}
31
32impl TailwindLspAdapter {
33 pub fn new(node: Arc<dyn NodeRuntime>) -> Self {
34 TailwindLspAdapter { node }
35 }
36}
37
38#[async_trait]
39impl LspAdapter for TailwindLspAdapter {
40 async fn name(&self) -> LanguageServerName {
41 LanguageServerName("tailwindcss-language-server".into())
42 }
43
44 fn short_name(&self) -> &'static str {
45 "tailwind"
46 }
47
48 async fn fetch_latest_server_version(
49 &self,
50 _: &dyn LspAdapterDelegate,
51 ) -> Result<Box<dyn 'static + Any + Send>> {
52 Ok(Box::new(
53 self.node
54 .npm_package_latest_version("@tailwindcss/language-server")
55 .await?,
56 ) as Box<_>)
57 }
58
59 async fn fetch_server_binary(
60 &self,
61 version: Box<dyn 'static + Send + Any>,
62 container_dir: PathBuf,
63 _: &dyn LspAdapterDelegate,
64 ) -> Result<LanguageServerBinary> {
65 let version = version.downcast::<String>().unwrap();
66 let server_path = container_dir.join(SERVER_PATH);
67
68 if fs::metadata(&server_path).await.is_err() {
69 self.node
70 .npm_install_packages(
71 &container_dir,
72 &[("@tailwindcss/language-server", version.as_str())],
73 )
74 .await?;
75 }
76
77 Ok(LanguageServerBinary {
78 path: self.node.binary_path().await?,
79 arguments: server_binary_arguments(&server_path),
80 })
81 }
82
83 async fn cached_server_binary(
84 &self,
85 container_dir: PathBuf,
86 _: &dyn LspAdapterDelegate,
87 ) -> Option<LanguageServerBinary> {
88 get_cached_server_binary(container_dir, &*self.node).await
89 }
90
91 async fn installation_test_binary(
92 &self,
93 container_dir: PathBuf,
94 ) -> Option<LanguageServerBinary> {
95 get_cached_server_binary(container_dir, &*self.node).await
96 }
97
98 async fn initialization_options(&self) -> Option<serde_json::Value> {
99 Some(json!({
100 "provideFormatter": true,
101 "userLanguages": {
102 "html": "html",
103 "css": "css",
104 "javascript": "javascript",
105 "typescriptreact": "typescriptreact",
106 },
107 }))
108 }
109
110 fn workspace_configuration(
111 &self,
112 _workspace_root: &Path,
113 _: &mut AppContext,
114 ) -> BoxFuture<'static, Value> {
115 future::ready(json!({
116 "tailwindCSS": {
117 "emmetCompletions": true,
118 }
119 }))
120 .boxed()
121 }
122
123 async fn language_ids(&self) -> HashMap<String, String> {
124 HashMap::from_iter([
125 ("HTML".to_string(), "html".to_string()),
126 ("CSS".to_string(), "css".to_string()),
127 ("JavaScript".to_string(), "javascript".to_string()),
128 ("TSX".to_string(), "typescriptreact".to_string()),
129 ("Svelte".to_string(), "svelte".to_string()),
130 ("Elixir".to_string(), "phoenix-heex".to_string()),
131 ("HEEX".to_string(), "phoenix-heex".to_string()),
132 ("ERB".to_string(), "erb".to_string()),
133 ("PHP".to_string(), "php".to_string()),
134 ])
135 }
136
137 fn prettier_plugins(&self) -> &[&'static str] {
138 &["prettier-plugin-tailwindcss"]
139 }
140}
141
142async fn get_cached_server_binary(
143 container_dir: PathBuf,
144 node: &dyn NodeRuntime,
145) -> Option<LanguageServerBinary> {
146 (|| async move {
147 let mut last_version_dir = None;
148 let mut entries = fs::read_dir(&container_dir).await?;
149 while let Some(entry) = entries.next().await {
150 let entry = entry?;
151 if entry.file_type().await?.is_dir() {
152 last_version_dir = Some(entry.path());
153 }
154 }
155 let last_version_dir = last_version_dir.ok_or_else(|| anyhow!("no cached binary"))?;
156 let server_path = last_version_dir.join(SERVER_PATH);
157 if server_path.exists() {
158 Ok(LanguageServerBinary {
159 path: node.binary_path().await?,
160 arguments: server_binary_arguments(&server_path),
161 })
162 } else {
163 Err(anyhow!(
164 "missing executable in directory {:?}",
165 last_version_dir
166 ))
167 }
168 })()
169 .await
170 .log_err()
171}