From 8442c0c3390ec0d3aa34f0ebc1461ed72a9b6bce Mon Sep 17 00:00:00 2001 From: LU XIANGRUI <1078666705@qq.com> Date: Fri, 27 Nov 2026 19:00:08 +0900 Subject: [PATCH] feat(typescript): CSS Modules navigation through CSS Modules Kit (#6345) Go to Declaration, completion, Find Usages and Rename for CSS Module class names between TS/JSX and *.module.css, through the CSS Modules Kit tsserver plugin on vtsls. The plugin is an IDE-managed tool pinned to @css-modules-kit/ts-plugin@1.4.2; a project turns it on with "cmkOptions": { "enabled": true } in tsconfig.json (also inherited through a local extends), which the editor offers to add, installing the plugin if needed. CSS files reach vtsls only once the plugin is installed; references from a selector drop the CSS server's own rule, and rename takes vtsls' edit so the selector keeps its dot. CSS Modules Kit loads before the Vue tsserver plugin outside a Vue project: both are Volar plugins sharing one @volar/typescript, which decorates a project once, so with the Vue language server installed the Vue plugin had claimed every vtsls and CSS Modules Kit did nothing. Closes #6071 Co-authored-by: wildcatDownstairs <26499420+wildcatDownstairs@users.noreply.github.com> --- crates/ide-host/src/project.rs | 9 +- crates/ide-language/src/markers.rs | 62 +++++- crates/ide-lsp/src/lib.rs | 24 ++- crates/ide-lsp/tests/mock_server.rs | 51 +++++ crates/ide-lsp/tests/real_servers.rs | 113 +++++++++++ crates/ide-sdk/src/apply.rs | 45 ++++- crates/ide-sdk/src/css_modules.rs | 65 +++++++ crates/ide-sdk/src/lib.rs | 1 + crates/ide-sdk/src/tests.rs | 111 +++++++++++ crates/ide-tools/src/lib.rs | 30 +++ crates/ide-tools/src/registry.rs | 18 +- crates/ide-tools/src/tests.rs | 24 +++ languages/css.toml | 42 ++++ src/editor/lsp/codeLens.test.ts | 5 + src/editor/lsp/codeLens.ts | 3 +- src/features/tools/cssModules.test.ts | 112 +++++++++++ src/features/tools/cssModules.ts | 266 ++++++++++++++++++++++++++ src/features/tools/index.ts | 2 + src/platform/locales/text/en.json | 7 + src/platform/locales/text/zh.json | 7 + 20 files changed, 984 insertions(+), 13 deletions(-) create mode 100644 crates/ide-sdk/src/css_modules.rs create mode 100644 src/features/tools/cssModules.test.ts create mode 100644 src/features/tools/cssModules.ts diff --git a/crates/ide-host/src/project.rs b/crates/ide-host/src/project.rs index a669f9e1a9..936f4db929 100644 --- a/crates/ide-host/src/project.rs +++ b/crates/ide-host/src/project.rs @@ -211,6 +211,8 @@ impl Host { crate::ts_code_style::configure(cfg, server_root, &effective); ide_sdk::apply::configure_vue_module_resolution(cfg, &data_dir); ide_sdk::apply::configure_path_aliases(cfg, server_root, &data_dir); + let css_modules = ide_tools::managed_npm_plugin(&data_dir, "css-modules-kit"); + ide_sdk::apply::configure_css_modules(cfg, server_root, css_modules.as_deref()); // After the global plugins: they keep the IDE's copies. ide_sdk::apply::configure_tsconfig_plugins(cfg, server_root, &data_dir); let container_python = effective.languages.python.run_target().is_some(); @@ -362,8 +364,13 @@ impl Host { } { let settings = settings.clone(); + let data_dir = self.local_data_dir.clone(); lsp.set_servers_hook(Box::new(move |language, defined| { - ide_sdk::apply::language_servers(language.as_str(), defined, &settings.effective()) + let mut servers = ide_sdk::apply::language_servers(language.as_str(), defined, &settings.effective()); + if language.as_str() == "css" && ide_tools::managed_npm_plugin(&data_dir, "css-modules-kit").is_none() { + ide_sdk::apply::drop_css_modules_route(&mut servers); + } + servers })); } { diff --git a/crates/ide-language/src/markers.rs b/crates/ide-language/src/markers.rs index 752f941a70..d2af43c615 100644 --- a/crates/ide-language/src/markers.rs +++ b/crates/ide-language/src/markers.rs @@ -89,12 +89,42 @@ fn has_toml_table(file: &Path, table: &str) -> bool { table.split('.').try_fold(&value, |v, key| v.get(key)).is_some_and(toml::Value::is_table) } -/// `file` parses as JSON and has the dotted `key` with a value other than `null`: -/// an object (`eslintConfig`) or a dependency's version (`dependencies.tailwindcss`). +/// `file` parses as JSON (with comments: `tsconfig.json`) and has the dotted `key` with a value +/// other than `null` or `false`: an object (`eslintConfig`), a dependency's version +/// (`dependencies.tailwindcss`) or a switch that is on (`cmkOptions.enabled`). fn has_json_key(file: &Path, key: &str) -> bool { - let Ok(text) = std::fs::read_to_string(file) else { return false }; - let Ok(value) = serde_json::from_str::(&text) else { return false }; - key.split('.').try_fold(&value, |v, key| v.get(key)).is_some_and(|v| !v.is_null()) + json_key(file, key, 0).is_some_and(|v| !v.is_null() && v != serde_json::Value::Bool(false)) +} + +/// The dotted `key` of the JSON `file`. A tsconfig.json / jsconfig.json without it inherits it +/// through `extends` from a local file (`./base`, `../tsconfig.base.json`), the first one defining +/// it winning, as CSS Modules Kit reads `cmkOptions`. +fn json_key(file: &Path, key: &str, depth: usize) -> Option { + // ponytail: package `extends` (`@tsconfig/node20`) are not resolved; only local files. + const MAX_DEPTH: usize = 8; + let text = std::fs::read_to_string(file).ok()?; + let value = serde_json::from_str::(&ide_core::jsonc::strip(&text)).ok()?; + if let Some(v) = key.split('.').try_fold(&value, |v, key| v.get(key)) { + return Some(v.clone()); + } + let name = file.file_name()?.to_string_lossy(); + if depth >= MAX_DEPTH || !(name.starts_with("tsconfig") || name.starts_with("jsconfig")) { + return None; + } + let extends = match value.get("extends")? { + serde_json::Value::String(s) => vec![s.as_str()], + serde_json::Value::Array(a) => a.iter().filter_map(serde_json::Value::as_str).collect(), + _ => return None, + }; + extends.into_iter().filter(|e| e.starts_with("./") || e.starts_with("../")).find_map(|e| { + let base = file.parent()?.join(e); + let base = if base.is_file() { + base + } else { + base.with_file_name(format!("{}.json", base.file_name()?.to_string_lossy())) + }; + json_key(&base, key, depth + 1) + }) } /// `path` is (or, after its creation or removal, was) a root marker of the @@ -191,6 +221,28 @@ mod tests { std::fs::write(dir.join("package.json"), r#"{"eslintConfig": null}"#).unwrap(); assert!(!has_marker(dir, "package.json#eslintConfig")); assert!(is_marker_path(&dir.join("package.json"), marker)); + // tsconfig.json is JSON with comments; a switch that is off is no marker. + let cmk = "tsconfig.json#cmkOptions.enabled"; + let tsconfig = + |enabled: &str| format!("{{\n // CSS Modules Kit\n \"cmkOptions\": {{ \"enabled\": {enabled} }},\n}}"); + std::fs::write(dir.join("tsconfig.json"), tsconfig("true")).unwrap(); + assert!(has_marker(dir, cmk)); + std::fs::write(dir.join("tsconfig.json"), tsconfig("false")).unwrap(); + assert!(!has_marker(dir, cmk)); + // Inherited through a local `extends`, which the file itself can turn off. + std::fs::create_dir_all(dir.join("app")).unwrap(); + std::fs::write(dir.join("tsconfig.json"), tsconfig("true")).unwrap(); + std::fs::write(dir.join("app/tsconfig.json"), r#"{ "extends": ["@tsconfig/strictest", "../tsconfig"] }"#) + .unwrap(); + assert!(has_marker(&dir.join("app"), cmk)); + std::fs::write( + dir.join("app/tsconfig.json"), + r#"{ "extends": "../tsconfig.json", "cmkOptions": { "enabled": false } }"#, + ) + .unwrap(); + assert!(!has_marker(&dir.join("app"), cmk)); + std::fs::write(dir.join("app/tsconfig.json"), r#"{ "extends": "./tsconfig.json" }"#).unwrap(); + assert!(!has_marker(&dir.join("app"), cmk), "a cycle ends"); } #[test] diff --git a/crates/ide-lsp/src/lib.rs b/crates/ide-lsp/src/lib.rs index cf4ec2f7ac..ebdf255b10 100644 --- a/crates/ide-lsp/src/lib.rs +++ b/crates/ide-lsp/src/lib.rs @@ -352,6 +352,9 @@ fn user_did_open(server: &Server, run: &Running, path: &Path, uri: &lsp::Uri, pa /// No target for `feature`: names the running servers that lack it, so the UI can /// tell "the server can't do this" from "no server is running" (the UI's /// `unavailableText` matches the "… doesn't support …" wording). +/// vscode-css-language-server, which lists a selector's own rule among its references. +const CSS_SERVER: &str = "vscode-css-language-server"; + fn unsupported(servers: &[Arc], feature: &str) -> IdeError { let running: Vec<&str> = servers.iter().filter(|s| s.running().is_some()).map(|s| s.name.as_str()).collect(); if running.is_empty() { @@ -2332,9 +2335,13 @@ impl LspManager { } }); // The Angular server lists the declaration even when not asked to: the one - // the definition at `pos` points to is taken out of its answer. + // the definition at `pos` points to is taken out of its answer. So does the CSS server + // with a selector's own rule (`.button`), always: where CSS Modules Kit defines the class + // name (`button`), vtsls lists the declaration itself when asked. let declarations = async { - if include_declaration || !targets.iter().any(|t| t.server.name == angular::SERVER) { + let listed = + |t: &Target| (t.server.name == angular::SERVER && !include_declaration) || t.server.name == CSS_SERVER; + if !targets.iter().any(listed) { return Vec::new(); } let defining = self.ready_targets(&snap.servers, |c| c.has("definitionProvider")).await; @@ -2351,6 +2358,14 @@ impl LspManager { let mut locs: Vec = w.first.into_iter().chain(w.second.into_iter().flatten()).collect(); if t.server.name == angular::SERVER { locs.retain(|l| !declarations.contains(l)); + } else if t.server.name == CSS_SERVER { + let overlaps = |a: &Location, b: &Location| { + a.path == b.path + && a.uri == b.uri + && a.range.start <= b.range.end + && b.range.start <= a.range.end + }; + locs.retain(|l| !declarations.iter().any(|d| overlaps(d, l))); } self.note_virtual(&t.server, locs.iter().map(|l| l.uri.as_deref())); self.note_arduino_sources(&t.server, &locs); @@ -2922,6 +2937,11 @@ impl LspManager { let prepared = join_all(targets.iter().map(|t| self.prepare_rename_on(snap, t, pos))).await; let able: Vec<&Target> = targets.iter().zip(prepared).filter(|(_, r)| matches!(r, Ok(Some(_)))).map(|(t, _)| t).collect(); + // CSS Modules Kit (vtsls) renames a class in the stylesheet and its scripts; the CSS + // server's own edit replaces the whole selector (`.button`) and would drop the dot. + if able.iter().any(|t| t.server.name == "vtsls") { + return able.into_iter().filter(|t| t.server.name != CSS_SERVER).collect(); + } if !able.is_empty() { return able; } diff --git a/crates/ide-lsp/tests/mock_server.rs b/crates/ide-lsp/tests/mock_server.rs index 95043c8b9f..3ec75dbd08 100644 --- a/crates/ide-lsp/tests/mock_server.rs +++ b/crates/ide-lsp/tests/mock_server.rs @@ -4768,6 +4768,57 @@ async fn angular_references_leave_out_the_declaration_unless_asked() { assert_eq!(vtsls.requested("textDocument/definition").len(), 1); } +#[tokio::test(flavor = "multi_thread")] +async fn css_references_leave_out_the_selector_where_css_modules_kit_defines_it() { + let servers = [("vscode-css-language-server", incremental_caps()), ("vtsls", incremental_caps())]; + let h = harness_for("css", "css", &servers, &[]); + let (doc, path) = h.open("a.module.css", ".button { color: red; }\n"); + h.wait_status("vscode-css-language-server", ServerStatus::Ready).await; + h.wait_status("vtsls", ServerStatus::Ready).await; + let tsx = h.root.join("a.tsx"); + let at = |uri: &str, line: u32, from: u32, to: u32| json!({ "uri": uri, "range": {"start":{"line":line,"character":from},"end":{"line":line,"character":to}} }); + let (css, tsx_uri) = (uri_of(&path), uri_of(&tsx)); + // The CSS server lists the rule itself (`.button`) whatever `includeDeclaration` says; + // CSS Modules Kit (vtsls) defines the class at `button` and lists the TSX use. + h.launcher.state("vscode-css-language-server").respond("textDocument/references", json!([at(&css, 0, 0, 7)])); + let vtsls = h.launcher.state("vtsls"); + vtsls.respond("textDocument/references", json!([at(&tsx_uri, 4, 30, 36)])); + vtsls.respond("textDocument/definition", json!([at(&css, 0, 1, 7)])); + let mgr = &h.mgr; + let found = |include_declaration: bool| async move { + let refs = + mgr.references_streaming(doc, Pos::new(0, 3), include_declaration, false, true, Default::default(), None); + let mut v: Vec<(PathBuf, Range)> = + refs.await.unwrap().locations.iter().map(|l| (l.path.to_path_buf(), l.range)).collect(); + v.sort(); + v + }; + assert_eq!(found(false).await, [(tsx.clone(), rng(4, 30, 4, 36))]); + // Asked for the declaration, vtsls lists it once, as the class name. + vtsls.respond("textDocument/references", json!([at(&css, 0, 1, 7), at(&tsx_uri, 4, 30, 36)])); + assert_eq!(found(true).await, [(path.clone(), rng(0, 1, 0, 7)), (tsx, rng(4, 30, 4, 36))]); + + // Rename: CSS Modules Kit's edit, not the CSS server's, which would replace `.button`. + let css_server = h.launcher.state("vscode-css-language-server"); + let range = |from: u32, to: u32| json!({"start":{"line":0,"character":from},"end":{"line":0,"character":to}}); + css_server.respond("textDocument/prepareRename", range(0, 7)); + css_server.respond( + "textDocument/rename", + json!({ "changes": { css.clone(): [{ "range": range(0, 7), "newText": "primary" }] } }), + ); + vtsls.respond("textDocument/prepareRename", range(1, 7)); + vtsls.respond( + "textDocument/rename", + json!({ "changes": { css.clone(): [{ "range": range(1, 7), "newText": "primary" }] } }), + ); + let edit = h.mgr.rename(doc, Pos::new(0, 3), "primary".into(), Default::default()).await.unwrap().edit; + assert!( + matches!(&edit.files[..], [FileEdit::Edit { edits, .. }] if edits.len() == 1 && edits[0].range == rng(0, 1, 0, 7)), + "{edit:?}" + ); + assert!(css_server.requested("textDocument/rename").is_empty()); +} + #[tokio::test(flavor = "multi_thread")] async fn utf8_server_positions_are_converted() { let h = harness(&[( diff --git a/crates/ide-lsp/tests/real_servers.rs b/crates/ide-lsp/tests/real_servers.rs index 70ba79a767..438450f6a0 100644 --- a/crates/ide-lsp/tests/real_servers.rs +++ b/crates/ide-lsp/tests/real_servers.rs @@ -969,6 +969,119 @@ async fn bundler_path_aliases_resolve_below_tsconfig_paths() { tokio::time::timeout(Duration::from_secs(10), mgr.shutdown_all()).await.unwrap(); } +/// CSS Modules Kit (`@css-modules-kit/ts-plugin`) on vtsls, which serves the `.module.css` +/// files too (`languages: ["css"]`): definition and completion from TSX, references and rename +/// from the stylesheet (#6071), with the settings hook's own plugin configuration. Exactly the +/// IDE's copy loads, once: also when the project has the package in its `node_modules`, and when +/// its tsconfig declares it in `compilerOptions.plugins` (#6336's probe location leaves it out, +/// and tsserver resolves the declared name from the global plugin's location). Set +/// `OPENIDEA_TEST_NPM_TOOLS` to a dir with `npm i @vtsls/language-server typescript@6 @css-modules-kit/ts-plugin@1.4.2`. +#[tokio::test(flavor = "multi_thread")] +#[ignore = "requires @vtsls/language-server and @css-modules-kit/ts-plugin (OPENIDEA_TEST_NPM_TOOLS)"] +async fn css_modules_kit_navigates_between_tsx_and_module_css() { + let tools = std::path::PathBuf::from(std::env::var("OPENIDEA_TEST_NPM_TOOLS").expect("OPENIDEA_TEST_NPM_TOOLS")); + // (the project has its own package, its tsconfig declares the plugin) + for (project_copy, declared) in [(false, false), (true, false), (true, true)] { + let dir = tempfile::tempdir().unwrap(); + let root = dunce::canonicalize(dir.path()).unwrap(); + std::fs::create_dir_all(root.join("src")).unwrap(); + std::fs::write(root.join("package.json"), "{\"name\":\"app\",\"private\":true}").unwrap(); + if project_copy { + // Says so in every file if it is ever loaded. + let package = root.join("node_modules/@css-modules-kit/ts-plugin"); + std::fs::create_dir_all(&package).unwrap(); + std::fs::write(package.join("package.json"), r#"{"name":"@css-modules-kit/ts-plugin","version":"0.0.1"}"#) + .unwrap(); + std::fs::write(package.join("index.js"), DIAGNOSTIC_PLUGIN.replace("NAME", "'the project copy'")).unwrap(); + } + let plugins = if declared { r#", "plugins": [{ "name": "@css-modules-kit/ts-plugin" }]"# } else { "" }; + std::fs::write( + root.join("tsconfig.json"), + format!( + "{{\n // JSON with comments\n \"compilerOptions\": {{ \"strict\": true, \"jsx\": \"preserve\", \"module\": \"ESNext\", \"moduleResolution\": \"Bundler\"{plugins} }},\n \"include\": [\"src\"],\n \"cmkOptions\": {{ \"enabled\": true }}\n}}\n" + ), + ) + .unwrap(); + let css_path = root.join("src/Button.module.css"); + let css = ".button { color: red; }\n.label { color: blue; }\n"; + std::fs::write(&css_path, css).unwrap(); + let tsx_path = root.join("src/Button.tsx"); + let tsx = + "import styles from './Button.module.css';\nexport const a = styles.button;\nexport const b = styles."; + std::fs::write(&tsx_path, tsx).unwrap(); + let mut vtsls = npm_server(&tools, "vtsls", "vtsls", None); + vtsls.tsserver_project = true; + assert!(ide_sdk::apply::configure_css_modules(&mut vtsls, &root, Some(&tools))); + let data = tempfile::tempdir().unwrap(); + // The plugin is the IDE's global one: no probe location for it. + assert!(!ide_sdk::apply::configure_tsconfig_plugins(&mut vtsls, &root, data.path())); + let registry = LanguageRegistry::from_configs(vec![ + lang("typescriptreact", "tsx", vtsls.clone()), + lang("css", "css", vtsls), + ]); + let (mgr, events) = manager(&root, registry); + let tsx_doc = DocId::next(); + mgr.did_open(tsx_doc, &tsx_path, &LanguageId::new("typescriptreact"), 1, tsx); + let css_doc = DocId::next(); + mgr.did_open(css_doc, &css_path, &LanguageId::new("css"), 1, css); + assert_eq!(mgr.servers().iter().filter(|s| s.name == "vtsls").count(), 1, "one vtsls for both"); + let case = format!("project copy: {project_copy}, declared: {declared}"); + + // `styles.button` → `.button`. + let defs = retry("definition in the stylesheet", Duration::from_secs(90), || { + let (mgr, css_path) = (mgr.clone(), css_path.clone()); + async move { + let defs = mgr.goto(tsx_doc, Pos::new(1, 26), GotoKind::Definition).await.ok()?; + defs.iter().any(|d| d.path == css_path).then_some(defs) + } + }) + .await; + assert_eq!(defs.len(), 1, "{case}: {defs:?}"); + assert_eq!((defs[0].range.start.line, defs[0].range.start.col), (0, 1), "{case}"); + let list = retry("class name completion", Duration::from_secs(30), || { + let mgr = mgr.clone(); + async move { + let list = mgr.completion(tsx_doc, Pos::new(2, 24), Some(".".into()), Default::default()).await.ok()?; + list.items.iter().any(|i| i.label == "label").then_some(list) + } + }) + .await; + let labels: Vec<&str> = + list.items.iter().map(|i| i.label.as_str()).filter(|l| ["button", "label"].contains(l)).collect(); + assert_eq!(labels.len(), 2, "{case}: each class once, {labels:?}"); + + // `.button` in the stylesheet → its use in the component, once. + let refs = retry("references from the stylesheet", Duration::from_secs(30), || { + let (mgr, tsx_path) = (mgr.clone(), tsx_path.clone()); + async move { + let refs = mgr + .references_streaming(css_doc, Pos::new(0, 3), false, true, false, Default::default(), None) + .await + .ok()?; + Some(refs.locations).filter(|l| l.iter().any(|l| l.path == tsx_path)) + } + }) + .await; + assert_eq!(refs.len(), 1, "{case}: {refs:?}"); + assert_eq!((refs[0].path.to_path_buf(), refs[0].range.start.line), (tsx_path.clone(), 1), "{case}"); + let renamed = mgr.rename(css_doc, Pos::new(0, 3), "primary".into(), Default::default()).await.unwrap().edit; + assert_eq!(edited_lines(&renamed, &css_path), [0], "{case}"); + assert_eq!(edited_lines(&renamed, &tsx_path), [1], "{case}"); + // The component's diagnostics are in: the plugins have run on it. + retry("diagnostics of the component", Duration::from_secs(30), || { + let found = + events.lock().iter().any(|e| matches!(e, IdeEvent::Diagnostics { path, .. } if path == &tsx_path)); + async move { found.then_some(()) } + }) + .await; + let project_copy_loaded = events.lock().iter().any(|e| { + matches!(e, IdeEvent::Diagnostics { items, .. } if items.iter().any(|d| d.message.contains("the project copy"))) + }); + assert!(!project_copy_loaded, "{case}"); + tokio::time::timeout(Duration::from_secs(10), mgr.shutdown_all()).await.unwrap(); + } +} + const MDX_BUTTON: &str = "export function Button(props: { label: string }) {\n return ;\n}\n"; const MDX_DOC: &str = "import { Button } from \"./Button\"\n\nexport const count = 2\n\n# Hello\n\n