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