1use anyhow::{anyhow, Result};
2use async_trait::async_trait;
3use collections::HashMap;
4use futures::{
5 future::{self, BoxFuture},
6 FutureExt, StreamExt,
7};
8use gpui2::AppContext;
9use language2::{LanguageServerName, LspAdapter, LspAdapterDelegate};
10use lsp2::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(&self, _: &mut AppContext) -> BoxFuture<'static, Value> {
111 future::ready(json!({
112 "tailwindCSS": {
113 "emmetCompletions": true,
114 }
115 }))
116 .boxed()
117 }
118
119 async fn language_ids(&self) -> HashMap<String, String> {
120 HashMap::from_iter([
121 ("HTML".to_string(), "html".to_string()),
122 ("CSS".to_string(), "css".to_string()),
123 ("JavaScript".to_string(), "javascript".to_string()),
124 ("TSX".to_string(), "typescriptreact".to_string()),
125 ("Svelte".to_string(), "svelte".to_string()),
126 ("Elixir".to_string(), "phoenix-heex".to_string()),
127 ("HEEX".to_string(), "phoenix-heex".to_string()),
128 ("ERB".to_string(), "erb".to_string()),
129 ("PHP".to_string(), "php".to_string()),
130 ])
131 }
132
133 fn prettier_plugins(&self) -> &[&'static str] {
134 &["prettier-plugin-tailwindcss"]
135 }
136}
137
138async fn get_cached_server_binary(
139 container_dir: PathBuf,
140 node: &dyn NodeRuntime,
141) -> Option<LanguageServerBinary> {
142 (|| async move {
143 let mut last_version_dir = None;
144 let mut entries = fs::read_dir(&container_dir).await?;
145 while let Some(entry) = entries.next().await {
146 let entry = entry?;
147 if entry.file_type().await?.is_dir() {
148 last_version_dir = Some(entry.path());
149 }
150 }
151 let last_version_dir = last_version_dir.ok_or_else(|| anyhow!("no cached binary"))?;
152 let server_path = last_version_dir.join(SERVER_PATH);
153 if server_path.exists() {
154 Ok(LanguageServerBinary {
155 path: node.binary_path().await?,
156 arguments: server_binary_arguments(&server_path),
157 })
158 } else {
159 Err(anyhow!(
160 "missing executable in directory {:?}",
161 last_version_dir
162 ))
163 }
164 })()
165 .await
166 .log_err()
167}