feat(css): complete var(--…) custom properties from the whole project (#6043)

var(-- completion offered only the custom properties of the current stylesheet, because the CSS language server sees one file. The project index now stores each --name declaration's value, and a web_css_variables command returns the document's own declarations (from its unsaved text) followed by the index's. The editor uses it for completion inside var( (document's own first, value in the type column, a swatch for colors), hover and Go to Declaration across CSS, SCSS, Less and <style> blocks.

Also keeps the fallback doc comment on fallback() in completion.ts.

Co-authored-by: wildcatDownstairs <[email protected]>
Цей коміт міститься в:
LU XIANGRUIтаwildcatDownstairs authored and GitHub committed 2026-11-27 01:27:56 +08:00
1 джерело 84854bed0e
коміт ea29339b6b
14 files changed
+436 -8

No files matched your search

+49 -1
Переглянути файл
@@ -7,7 +7,7 @@ use crate::Project;
use ide_command::command;
use ide_core::{DocId, IdeResult, IpcPath, LanguageId, Location, Pos};
use ide_index::{ExtensionCount, FileMatch, IndexStatus, SymbolFilter, SymbolMatch};
use ide_language::{FileReference, WebReference};
use ide_language::{CSS_VARIABLE, FileReference, WebReference};
use ide_workspace::file_refs::{self, PathCompletion};
use serde::{Deserialize, Serialize};
use specta::Type;
@@ -25,6 +25,18 @@ pub struct WebGoto {
const MAX_WEB_TARGETS: usize = 200;
/// A custom property declaration (`--accent: #3b82f6`), for `var(--…)` completion and hover.
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct CssVariable {
pub name: String,
/// The declared value, whitespace collapsed.
pub value: Option<String>,
pub location: Location,
}
const MAX_CSS_VARIABLES: usize = 5000;
/// A Python class definition and the base names written in its source. The UI builds a
/// name → locations index from every class in the project (attached dependency roots
/// included) to compute ↑ overrides / ↓ overridden gutter markers without a language
@@ -185,6 +197,41 @@ pub async fn web_goto(host: &Host, window: &str, doc: DocId, pos: Pos) -> IdeRes
.await
}
/// Custom properties declared in `doc` (from its current text, first) and in the project's
/// other stylesheets (from the index, so kept up to date as files change).
#[command(trust = always)]
pub async fn web_css_variables(host: &Host, window: &str, doc: DocId) -> IdeResult<Vec<CssVariable>> {
let project = host.project(window)?;
let syntax = host.syntax();
blocking(move || {
let snap = project.documents.snapshot(doc)?;
let own = if snap.large { Vec::new() } else { syntax.web_definitions(&snap.language, &snap.text) };
let mut out: Vec<CssVariable> = own
.into_iter()
.filter(|t| t.kind == CSS_VARIABLE)
.map(|t| CssVariable {
name: t.name,
value: t.container,
location: Location { path: snap.path.clone(), range: t.range, uri: None },
})
.collect();
out.extend(
project
.index
.symbols_prefixed("--", CSS_VARIABLE, MAX_CSS_VARIABLES)
.into_iter()
.filter(|m| *m.path != *snap.path)
.map(|m| CssVariable {
name: m.name,
value: m.container,
location: Location { path: m.path, range: m.range, uri: None },
}),
);
Ok(out)
})
.await
}
/// The file a Python import path (`a.b.c`, or `.x` relative to `from`) names; `None` when
/// no project or content root has it.
#[command(trust = always)]
@@ -450,6 +497,7 @@ ide_command::domain!(
recent_files,
remove_recent,
scope_files,
web_css_variables,
web_goto,
web_unresolved_references,
);
+5
Переглянути файл
@@ -391,6 +391,11 @@ impl ProjectIndex {
matching::symbols_named_within(&self.shared.data.read(), name, kind, roots, limit)
}
/// Symbols of `kind` whose name starts with `prefix`, by path then position.
pub fn symbols_prefixed(&self, prefix: &str, kind: SymbolKind, limit: usize) -> Vec<SymbolMatch> {
matching::symbols_prefixed(&self.shared.data.read(), prefix, kind, limit)
}
/// Symbols named exactly one of `names` whose file is inside `root`, at most `limit` per name.
pub fn symbols_named_any(&self, names: &[String], root: &Path, limit: usize) -> Vec<SymbolMatch> {
matching::symbols_named_any(&self.shared.data.read(), names, root, limit)
+28
Переглянути файл
@@ -716,6 +716,34 @@ pub(crate) fn symbols_named_within(
out
}
/// Symbols of `kind` whose name starts with `prefix` (CSS custom properties: `--`), by path
/// then position.
pub(crate) fn symbols_prefixed(data: &IndexData, prefix: &str, kind: SymbolKind, limit: usize) -> Vec<SymbolMatch> {
let syms = &data.syms;
let mut out: Vec<SymbolMatch> = data
.files
.iter()
.flatten()
.flat_map(|e| {
(e.sym_start..e.sym_start + e.sym_len)
.filter(|&i| syms.kind(i) == kind && syms.name(i).starts_with(prefix))
.map(move |i| SymbolMatch {
name: syms.name(i).to_string(),
kind,
container: syms.container(i).map(str::to_owned),
path: e.path.clone().into(),
rel_path: e.rel.to_string(),
range: syms.range(i),
score: 0,
indices: Vec::new(),
})
})
.collect();
out.sort_by(|a, b| a.rel_path.cmp(&b.rel_path).then_with(|| a.range.cmp(&b.range)));
out.truncate(limit);
out
}
/// Symbols named exactly one of `names` whose file is inside `root`, at most `limit` per
/// name, by path then position: one walk over the index for every name an agent reply shows.
pub(crate) fn symbols_named_any(data: &IndexData, names: &[String], root: &Path, limit: usize) -> Vec<SymbolMatch> {
+31
Переглянути файл
@@ -675,6 +675,37 @@ fn css_selectors_are_found_by_exact_name() {
assert!(idx.symbols_named(".card", Some(SymbolKind::Field), 10).is_empty());
}
#[test]
fn css_custom_properties_are_listed_with_their_values_and_follow_edits() {
let f = Fixture::new(&[
("theme/light.css", ":root {\n --bg: #fff;\n --gap:\n 4px 8px;\n}\n"),
("theme/dark.scss", "[data-theme=dark] { .x { --bg: rgb(0 0 0) !important; } }\n"),
("theme/extra.less", ".a { --ring: var(--bg); color: red; }\n"),
]);
let idx = f.open();
let vars = |idx: &ProjectIndex| -> Vec<(String, String, Option<String>)> {
idx.symbols_prefixed("--", SymbolKind::Variable, 100)
.into_iter()
.map(|m| (m.rel_path, m.name, m.container))
.collect()
};
assert_eq!(
vars(&idx),
vec![
("theme/dark.scss".into(), "--bg".into(), Some("rgb(0 0 0) !important".into())),
("theme/extra.less".into(), "--ring".into(), Some("var(--bg)".into())),
("theme/light.css".into(), "--bg".into(), Some("#fff".into())),
("theme/light.css".into(), "--gap".into(), Some("4px 8px".into())),
]
);
let light = f.root.join("theme/light.css");
std::fs::write(&light, ":root { --fg: #222; }\n").unwrap();
idx.update(std::slice::from_ref(&light), &[]);
assert!(idx.wait_idle(WAIT));
let names: Vec<String> = vars(&idx).into_iter().filter(|v| v.0 == "theme/light.css").map(|v| v.1).collect();
assert_eq!(names, vec!["--fg".to_string()]);
}
#[test]
fn symbols_named_within_keeps_out_of_root_matches_from_evicting_a_root() {
let f = Fixture::new(&[
+19 -6
Переглянути файл
@@ -4,7 +4,8 @@
//!
//! Definitions (`.card`, `#main`, `--accent`) come from stylesheets and the
//! `<style>` elements of HTML documents and feed the symbol index (see
//! [`super::Syntax::tags`]), so a lookup is an exact index query.
//! [`super::Syntax::tags`]), so a lookup is an exact index query. A `--name` symbol carries
//! its declared value as its container.
use super::lines::{LineIndex, byte_at};
use super::{Grammar, parse};
@@ -119,17 +120,17 @@ pub(crate) fn definitions(g: &Grammar, css: Option<&Grammar>, tree: &Tree, text:
walk(css_tree.root_node(), &mut |n| {
let def = match n.kind() {
"class_name" if n.parent().is_some_and(|p| p.kind() == "class_selector") => {
Some((format!(".{}", text_of(n, css_text)), CSS_CLASS))
Some((format!(".{}", text_of(n, css_text)), CSS_CLASS, None))
}
"id_name" => Some((format!("#{}", text_of(n, css_text)), CSS_ID)),
"id_name" => Some((format!("#{}", text_of(n, css_text)), CSS_ID, None)),
"property_name" if text_of(n, css_text).starts_with("--") => {
Some((text_of(n, css_text).to_owned(), CSS_VARIABLE))
Some((text_of(n, css_text).to_owned(), CSS_VARIABLE, declared_value(n, css_text)))
}
_ => None,
};
if let Some((name, kind)) = def {
if let Some((name, kind, container)) = def {
let range = idx.range(base + n.start_byte(), base + n.end_byte());
out.push(SymbolTag { name, kind, container: None, range, bases: Vec::new() });
out.push(SymbolTag { name, kind, container, range, bases: Vec::new() });
}
true
});
@@ -137,6 +138,18 @@ pub(crate) fn definitions(g: &Grammar, css: Option<&Grammar>, tree: &Tree, text:
out
}
/// The value a custom property declares (`n` is its `property_name`), whitespace collapsed and
/// cut at [`MAX_VALUE_CHARS`]: the container of its `--name` symbol, so completion and hover
/// show it without reading the file.
fn declared_value(n: Node, text: &str) -> Option<String> {
let decl = n.parent().filter(|p| p.kind() == "declaration")?;
let rest = text.get(n.end_byte()..decl.end_byte())?.trim_start().strip_prefix(':')?;
let value = rest.trim().trim_end_matches(';').split_whitespace().collect::<Vec<_>>().join(" ");
(!value.is_empty()).then(|| value.chars().take(MAX_VALUE_CHARS).collect())
}
const MAX_VALUE_CHARS: usize = 120;
/// The whitespace-separated token of `value` (starting at byte `base`) around byte `at`.
fn token_at(value: &str, base: usize, at: usize) -> Option<(usize, &str)> {
let rel = at.checked_sub(base)?;
+1
Переглянути файл
@@ -833,6 +833,7 @@ vcs_worktree_include always project_host bin
vcs_worktrees always project_host bindings async
vcs_write_patch always project_host bindings async
web_browsers always desktop bindings async
web_css_variables always project_host bindings async
web_goto always project_host bindings async
web_open always desktop bindings async
web_serves_page trusted desktop bindings async
+13
Переглянути файл
@@ -2294,6 +2294,11 @@ export const commands = {
vcsWritePatch: (path: string, patch: string, encoding: string | null) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_write_patch", { path, patch, encoding })),
/** The browsers installed on this machine. */
webBrowsers: () => typedError<Browser[], IdeError>(__TAURI_INVOKE("web_browsers")),
/**
* Custom properties declared in `doc` (from its current text, first) and in the project's
* other stylesheets (from the index, so kept up to date as files change).
*/
webCssVariables: (doc: DocId) => typedError<CssVariable[], IdeError>(__TAURI_INVOKE("web_css_variables", { doc })),
/** The web reference at `pos` of `doc` and its targets; `None` when there is no reference. */
webGoto: (doc: DocId, pos: Pos) => typedError<{
reference: WebReference,
@@ -5013,6 +5018,14 @@ export type CreateRequest = {
values: { [key in string]: string },
};
/** A custom property declaration (`--accent: #3b82f6`), for `var(--…)` completion and hover. */
export type CssVariable = {
name: string,
/** The declared value, whitespace collapsed. */
value: string | null,
location: Location,
};
/**
* Payload for creating a custom ACP agent (always the ACP driver); the id
* becomes the `<config>/agents/<id>.toml` file name.
+24 -1
Переглянути файл
@@ -62,6 +62,7 @@ import { iconNode } from "@/ui/iconNode";
import { parameterInfoOrLeave, triggerSignatureHelp } from "./signature";
import { featureBackoff } from "./availability";
import { pathCompletionSource, pathContext, pathLike } from "./fileReferences";
import { cssVariablePrefix, cssVariableSource, STYLESHEETS, type VariableOption } from "./cssVariables";
import { editorPrefs } from "@/platform/editorSettings";
import { tx } from "@/platform/i18n";
import { showHint } from "./hint";
@@ -619,8 +620,17 @@ function cancelInflight() {
inflight = null;
}
/** Inside a stylesheet's `var(`, where `cssVariableSource` lists the project's custom properties instead of the server or the document's words. */
function inVarCall(ctx: CompletionContext): boolean {
const language = ctx.state.facet(lspDoc)?.language ?? "";
if (!STYLESHEETS.has(language) || !isTauri()) return false;
const line = ctx.state.doc.lineAt(ctx.pos);
return cssVariablePrefix(line.text.slice(0, ctx.pos - line.from)) !== null;
}
/** Language-data completion sources (keywords etc.), used when no server answers. */
async function fallback(ctx: CompletionContext): Promise<CompletionResult | null> {
if (inVarCall(ctx)) return null;
const sources = ctx.state.languageDataAt<CompletionSource | readonly (string | Completion)[]>(
"autocomplete",
ctx.pos,
@@ -756,6 +766,7 @@ async function lspCompletionSource(ctx: CompletionContext): Promise<CompletionRe
? list.items.filter((it) => matchesCase(it.filterText ?? it.label, typed, prefs.caseSensitivity))
: list.items,
);
if (inVarCall(ctx)) items = items.filter((it) => !it.label.startsWith("--"));
// A server snippet named like a live template (jdtls `sout`, `fori`) would be listed twice; the template wins.
if (items.some((it) => it.kind === "snippet")) {
const own = await contributedSource(ctx);
@@ -1052,6 +1063,13 @@ export function explicitCompletion(view: EditorView): boolean {
// Rendering
function kindBadge(c: Completion): Node | null {
const swatch = (c as VariableOption).swatch;
if (swatch) {
const span = document.createElement("span");
span.className = "cm-lsp-kind cm-lsp-swatch";
span.style.setProperty("--swatch", swatch);
return span;
}
if (!isLsp(c) && "icon" in c) {
const icon = (c as RichCompletion).icon;
if (icon) return iconNode(icon, 16, "cm-lsp-kind");
@@ -1185,7 +1203,12 @@ export function completionExtension() {
smartLookup,
endSmartLookup,
autocompletion({
override: [gated(claimingLspSource), gated(contributedSource), gated(pathFallbackSource)],
override: [
gated(claimingLspSource),
gated(contributedSource),
gated(pathFallbackSource),
gated(cssVariableSource),
],
icons: false,
addToOptions: [
{ render: kindBadge, position: 20 },
+73
Переглянути файл
@@ -0,0 +1,73 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import type { CssVariable } from "@/platform/ipc";
import { cssVariableAt, cssVariablePrefix, swatchColor, variableHoverMarkdown, variableOptions } from "./cssVariables";
const at = (path: string, line: number) => ({
path,
range: { start: { line, col: 2 }, end: { line, col: 6 } },
uri: null,
});
const v = (name: string, value: string | null, path: string, line = 0): CssVariable => ({
name,
value,
location: at(path, line),
});
describe("var() completion context", () => {
it("answers inside var( with the name typed so far", () => {
expect(cssVariablePrefix(".a { color: var(")).toBe("");
expect(cssVariablePrefix(".a { color: var( --ac")).toBe("--ac");
expect(cssVariablePrefix(" margin: calc(var(-")).toBe("-");
expect(cssVariablePrefix(".a { color: var(--a) ")).toBeNull();
expect(cssVariablePrefix(".a { color: avar(")).toBeNull();
expect(cssVariablePrefix(".a { color: re")).toBeNull();
});
it("finds the var(--name) under a column", () => {
const line = " border: 1px solid var(--line, red) var(--x);";
expect(cssVariableAt(line, line.indexOf("--line") + 2)).toEqual({ name: "--line", from: 24, to: 30 });
expect(cssVariableAt(line, line.indexOf("--x") + 3)?.name).toBe("--x");
expect(cssVariableAt(line, 3)).toBeNull();
expect(cssVariableAt(" --line: red;", 4)).toBeNull();
});
});
describe("custom property options", () => {
afterEach(() => vi.unstubAllGlobals());
it("lists each name once, the document's own declaration first and boosted", () => {
vi.stubGlobal("CSS", { supports: (_p: string, value: string) => /^#|^rgb/.test(value) });
const options = variableOptions(
[
v("--bg", "#fff", "/p/a.css"),
v("--bg", "#000", "/p/theme/dark.css"),
v("--gap", "4px 8px", "/p/theme/light.css"),
v("--ring", "var(--bg)", "/p/theme/light.css"),
],
"/p/a.css",
);
expect(options).toEqual([
{ label: "--bg", type: "variable", boost: 10, typeText: "#fff", swatch: "#fff" },
{ label: "--gap", type: "variable", boost: 0, typeText: "4px 8px" },
{ label: "--ring", type: "variable", boost: 0, typeText: "var(--bg)" },
]);
});
it("shows a swatch only for color values", () => {
vi.stubGlobal("CSS", { supports: () => true });
expect(swatchColor("red !important")).toBe("red");
expect(swatchColor("var(--bg)")).toBeNull();
expect(swatchColor("inherit")).toBeNull();
expect(swatchColor(null)).toBeNull();
vi.stubGlobal("CSS", { supports: () => false });
expect(swatchColor("4px")).toBeNull();
});
it("hovers every declaration of the name with its file", () => {
const vars = [v("--bg", "#fff", "/p/theme/light.css", 1), v("--bg", "#000", "/p/theme/dark.css", 4)];
expect(variableHoverMarkdown("--bg", vars)).toBe(
"```css\n--bg: #fff; /* light.css:2 */\n--bg: #000; /* dark.css:5 */\n```",
);
expect(variableHoverMarkdown("--fg", vars)).toBeNull();
});
});
+101
Переглянути файл
@@ -0,0 +1,101 @@
/**
* CSS custom properties from the whole project: `var(--…)` completion (the document's own
* declarations first, values in the type column, a swatch for colors) and the hover over
* `var(--x)`. The language server only sees the open stylesheet; declarations come from
* the backend (`web_css_variables`: the document's text plus the project index).
*/
import type { Completion, CompletionContext, CompletionResult } from "@codemirror/autocomplete";
import type { EditorView } from "@codemirror/view";
import { whenSynced } from "@/editor/api";
import { call, commands, isTauri, type CssVariable, type Hover } from "@/platform/ipc";
import { basename } from "@/platform/project";
import { lspDoc } from "./lsp";
import { offsetToPos } from "./positions";
export const STYLESHEETS = new Set(["css", "scss", "less"]);
/** The custom property name typed so far inside `var(` at the end of `before`, or null outside one. */
export function cssVariablePrefix(before: string): string | null {
const m = /\bvar\(\s*(-[\w-]*)?$/.exec(before);
return m ? (m[1] ?? "") : null;
}
/** The `--name` of a `var(--name)` on `line` that covers column `col`. */
export function cssVariableAt(line: string, col: number): { name: string; from: number; to: number } | null {
for (const m of line.matchAll(/\bvar\(\s*(--[\w-]+)/g)) {
const to = m.index + m[0].length;
const from = to - m[1]!.length;
if (col >= from && col <= to) return { name: m[1]!, from, to };
}
return null;
}
const NOT_SWATCH = /^(?:inherit|initial|unset|revert|revert-layer|currentcolor)$/i;
/** The value as a CSS color, when the browser parses it as one (not `var(…)`: that is always "valid"). */
export function swatchColor(value: string | null): string | null {
const color = value?.replace(/\s*!important$/i, "");
if (!color || /var\(/i.test(color) || NOT_SWATCH.test(color)) return null;
return typeof CSS !== "undefined" && CSS.supports?.("color", color) ? color : null;
}
/** An option with its value in the type column and, for a color, a swatch for its icon. */
export type VariableOption = Completion & { typeText?: string; swatch?: string };
/** A completion option per name, the first declaration winning (the backend lists the document's own first). */
export function variableOptions(vars: readonly CssVariable[], path: string): VariableOption[] {
const seen = new Set<string>();
const options: VariableOption[] = [];
for (const v of vars) {
if (seen.has(v.name)) continue;
seen.add(v.name);
const swatch = swatchColor(v.value);
options.push({
label: v.name,
type: "variable",
boost: v.location.path === path ? 10 : 0,
...(v.value ? { typeText: v.value } : {}),
...(swatch ? { swatch } : {}),
});
}
return options;
}
async function variablesOf(doc: number, view: EditorView | undefined): Promise<CssVariable[]> {
if (view) await whenSynced(view);
return call(commands.webCssVariables(doc)).catch(() => []);
}
export async function cssVariableSource(ctx: CompletionContext): Promise<CompletionResult | null> {
const doc = ctx.state.facet(lspDoc);
if (!doc || doc.virtual || doc.readOnly || !STYLESHEETS.has(doc.language) || !isTauri()) return null;
const line = ctx.state.doc.lineAt(ctx.pos);
const prefix = cssVariablePrefix(line.text.slice(0, ctx.pos - line.from));
if (prefix === null) return null;
const vars = await variablesOf(doc.doc, ctx.view);
if (ctx.aborted || !vars.length) return null;
return { from: ctx.pos - prefix.length, options: variableOptions(vars, doc.path), validFor: /^-[\w-]*$|^$/ };
}
/** Hover over `var(--x)`: each declaration with its value and file. */
export function variableHoverMarkdown(name: string, vars: readonly CssVariable[]): string | null {
const lines = vars
.filter((v) => v.name === name)
.map((v) => `${name}: ${v.value ?? ""}; /* ${basename(v.location.path)}:${v.location.range.start.line + 1} */`);
return lines.length ? "```css\n" + lines.join("\n") + "\n```" : null;
}
export async function cssVariableHover(view: EditorView, pos: number): Promise<Hover | null> {
const doc = view.state.facet(lspDoc);
if (!doc || doc.virtual || !STYLESHEETS.has(doc.language) || !isTauri()) return null;
const line = view.state.doc.lineAt(pos);
const at = cssVariableAt(line.text, pos - line.from);
if (!at) return null;
const value = variableHoverMarkdown(at.name, await variablesOf(doc.doc, view));
if (!value) return null;
const range = {
start: offsetToPos(view.state.doc, line.from + at.from),
end: offsetToPos(view.state.doc, line.from + at.to),
};
return { contents: { kind: "markdown", value }, range };
}
+4
Переглянути файл
@@ -47,6 +47,7 @@ import { editorPrefs } from "@/platform/editorSettings";
import { CONTRIBUTED_HOVER, contributedAtAll, type ContributedHover } from "@/editor/api";
import { navigationModifierHeld, onNavigationModifier, pointerTarget } from "@/platform/navigationModifier";
import { languageSemantics } from "./semantic";
import { cssVariableHover } from "./cssVariables";
import { tooltipBounds } from "@/editor/core/cm/setup";
let hoverRequest: RequestId | null = null;
@@ -71,6 +72,9 @@ export async function requestHover(view: EditorView, pos: number): Promise<Hover
contents: { kind: "markdown", value: construct.markdown },
range: { start: offsetToPos(view.state.doc, construct.from), end: offsetToPos(view.state.doc, construct.to) },
};
// The server would describe the property the `var(--x)` is the value of, from this file only.
const variable = await cssVariableHover(view, pos);
if (variable) return variable;
if (hoverRequest !== null && isTauri()) void commands.cancelRequest(hoverRequest);
const id = (hoverRequest = nextRequestId());
try {
+7
Переглянути файл
@@ -95,6 +95,7 @@ import { dispatchMouseShortcut, shortcutLabel } from "@/platform/keymap";
import { isNavigationGesture, onNavigationModifier, navigationModifierHeld } from "@/platform/navigationModifier";
import { create } from "zustand";
import { tx } from "@/platform/i18n";
import { cssVariableAt, STYLESHEETS } from "./cssVariables";
import {
CONFIGURATION_NAVIGATION_MAX_AGE,
configurationNavigationRevision,
@@ -505,6 +506,12 @@ async function gotoResolved(
return;
}
}
// `var(--x)`: the server only knows this stylesheet's declarations; list the project's.
if (declaration && STYLESHEETS.has(doc.language)) {
const line = view.state.doc.lineAt(offset);
if (cssVariableAt(line.text, offset - line.from) && (await gotoWebReference(view, doc, pos, offset, superseded)))
return;
}
// Python: its servers have no type hierarchy and see one root, so the IDE's inheritance
// graph answers implementations too (merged with the server's, not replacing them).
const graphTargets = kind === "implementation" ? pythonImplementations(doc, pos) : null;
+71
Переглянути файл
@@ -0,0 +1,71 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import type { commands, Location } from "@/platform/ipc";
// `var(--x)`: the CSS server only knows the open stylesheet, so a name declared here and in a
// theme file would answer just the local one; the project index lists both.
const { lspGoto, webGoto, readManyFileLines } = vi.hoisted(() => ({
lspGoto: vi.fn<typeof commands.lspGoto>(),
webGoto: vi.fn<typeof commands.webGoto>(),
readManyFileLines: vi.fn(async () => new Map<string, string[] | null>()),
}));
vi.mock("@/platform/ipc", async (orig) => {
const real = await orig<typeof import("@/platform/ipc")>();
return { ...real, isTauri: () => true, commands: { ...real.commands, lspGoto, webGoto } };
});
vi.mock("./files", async (orig) => ({ ...(await orig<typeof import("./files")>()), readManyFileLines }));
const { gotoTargets } = await import("./navigation");
const { lspDoc } = await import("./lsp");
const { closePopup, useLspPopup } = await import("./popupStore");
const { provideEditorService } = await import("@/workbench/contributions");
const openFile = vi.fn(async () => {});
provideEditorService({ openFile } as never);
const at = (path: string, line: number): Location => ({
path,
range: { start: { line, col: 2 }, end: { line, col: 6 } },
uri: null,
});
const text = ":root { --bg: #fff; }\n.a { color: var(--bg); }\n";
let view: EditorView;
beforeEach(() => {
vi.clearAllMocks();
lspGoto.mockResolvedValue({ status: "ok", data: [at("/p/a.css", 0)] });
view = new EditorView({
state: EditorState.create({
doc: text,
extensions: [lspDoc.of({ doc: 1, path: "/p/a.css", language: "css", uiMode: "CSS", readOnly: false })],
}),
parent: document.body,
});
view.dispatch({ selection: { anchor: text.lastIndexOf("--bg") + 2 } });
});
afterEach(() => {
closePopup();
view.destroy();
document.body.replaceChildren();
});
describe("go to declaration on var(--x)", () => {
it("lists the declarations in every file, not only the server's local one", async () => {
const targets = [at("/p/a.css", 0), at("/p/theme/dark.css", 4)];
webGoto.mockResolvedValue({
status: "ok",
data: { reference: { kind: "cssVariable", name: "--bg", range: at("/p/a.css", 1).range }, targets },
});
await gotoTargets(view, "declaration");
expect(webGoto).toHaveBeenCalledWith(1, { line: 1, col: 18 });
expect(lspGoto).not.toHaveBeenCalled();
const popup = useLspPopup.getState().popup;
expect(popup?.kind).toBe("list");
expect(popup && "title" in popup ? popup.title : null).toBe("Choose Declaration of '--bg' (2 found)");
expect(popup && "items" in popup ? popup.items.map((i) => i.target) : null).toEqual([
expect.objectContaining({ path: expect.stringMatching(/a\.css:1$/) }),
expect.objectContaining({ path: expect.stringMatching(/dark\.css:5$/) }),
]);
expect(openFile).not.toHaveBeenCalled();
});
});
+10
Переглянути файл
@@ -189,6 +189,16 @@ export const lspTheme = EditorView.theme({
alignItems: "center",
justifyContent: "center",
},
// A color custom property's value (`var(--…)` completion), sized like the gutter's color swatch.
".cm-lsp-completion .cm-lsp-swatch::before": {
content: '""',
width: "12px",
height: "12px",
boxSizing: "border-box",
border: "1px solid var(--border-strong)",
borderRadius: "var(--radius-small)",
background: "var(--swatch)",
},
".cm-lsp-completion .cm-completionLabel": {
flex: "none",
maxWidth: