fix(editor): complete hyphenated tokens such as Tailwind classes (#6463)

Typing a hyphenated token such as items-c never offered items-center: the server's replace range covers the whole class, but the client filtered on the last word segment (c), and CodeMirror matches a one-character pattern only at a label's start. Typing - also closed the popup and re-queried. The completion now starts where the servers' single-token replace ranges start when they reach back over hyphens (the most common start wins), and the list stays valid across - while an option still starts with the typed text. Other punctuation, and lists with no option continuing the hyphen, re-query as before. CSS properties (background-c → background-color) benefit too.

Closes #6462

Co-authored-by: FForFachriza <[email protected]>
Цей коміт міститься в:
Dimas Avrian Fachriza authored and GitHub committed 2026-11-27 19:51:26 +08:00
1 джерело 84b528f0cd
коміт 65c45ffe05
2 files changed
+163 -4

No files matched your search

+110
Переглянути файл
@@ -1123,3 +1123,113 @@ describe("`(` completion trigger", () => {
expect(await parensTypedInto("kotlin", "Kotlin", 904)).toBe(0);
});
});
describe("hyphenated completion tokens", () => {
let view: EditorView | null = null;
let calls = 0;
afterEach(() => {
view?.destroy();
view = null;
setInvokeRoute(null);
calls = 0;
});
/** A server item whose replace range covers `[0, end)` of the line. */
const ranged = (label: string, end: number, start = 0) =>
item({
label,
insertText: label,
replaceRange: { start: { line: 0, col: start }, end: { line: 0, col: end } },
});
function mount(doc: string, caret: number, reply: CompletionItem[], language = "typescriptreact") {
setInvokeRoute((cmd) => {
if (cmd === "cancel_request") return Promise.resolve(null);
if (cmd === "lsp_completion") {
calls++;
return Promise.resolve({ isIncomplete: false, items: reply });
}
return Promise.resolve(null);
});
view = new EditorView({
state: EditorState.create({
doc,
selection: { anchor: caret },
extensions: [
lspDoc.of({ doc: 950, path: "/p/a.tsx", language, uiMode: "TypeScript React", readOnly: false }),
completionExtension(),
],
}),
parent: document.body,
});
return view;
}
const labels = () => currentCompletions(view!.state).map((c) => c.label);
it("offers items-center when the caret sits after items-c", async () => {
mount("items-c", 7, [ranged("items-baseline", 7), ranged("items-center", 7)]);
startCompletion(view!);
await vi.waitFor(() => expect(labels()).toContain("items-center"));
});
it("keeps the list across the hyphen instead of asking again", async () => {
mount("items", 5, [ranged("items-baseline", 5), ranged("items-center", 5)]);
startCompletion(view!);
await vi.waitFor(() => expect(labels()).toHaveLength(2));
const at = view!.state.selection.main.head;
view!.dispatch({ changes: { from: at, insert: "-" }, selection: { anchor: at + 1 }, userEvent: "input.type" });
view!.dispatch({ changes: { from: at + 1, insert: "c" }, selection: { anchor: at + 2 }, userEvent: "input.type" });
await vi.waitFor(() => expect(labels()).toEqual(["items-center"]));
expect(completionStatus(view!.state)).toBe("active");
expect(calls).toBe(1);
});
it("ignores a stray item whose range starts later than the rest", async () => {
mount("items-c", 7, [
ranged("items-baseline", 7),
ranged("items-center", 7),
ranged("items-start", 7),
ranged("items-end", 7),
ranged("items-stretch", 7),
ranged("center", 7, 6),
]);
startCompletion(view!);
await vi.waitFor(() => expect(labels()).toContain("items-center"));
});
it("does not widen a range that is not a single token", async () => {
mount("this.foo", 8, [ranged("foobar", 8)], "javascript");
startCompletion(view!);
await vi.waitFor(() => expect(labels()).toContain("foobar"));
});
it("still re-queries when a hyphen does not continue any option", async () => {
mount("a", 1, [ranged("alpha", 1)], "javascript");
startCompletion(view!);
await vi.waitFor(() => expect(labels()).toEqual(["alpha"]));
const at = view!.state.selection.main.head;
view!.dispatch({ changes: { from: at, insert: "-b" }, selection: { anchor: at + 2 }, userEvent: "input.type" });
await vi.waitFor(() => expect(completionStatus(view!.state)).not.toBe("active"));
});
it("completes CSS properties across the hyphen too", async () => {
mount(
"background-c",
12,
[
item({
label: "background-color",
insertText: "background-color",
replaceRange: { start: { line: 0, col: 0 }, end: { line: 0, col: 12 } },
}),
],
"css",
);
startCompletion(view!);
await vi.waitFor(() => expect(labels()).toContain("background-color"));
});
});
+53 -4
Переглянути файл
@@ -613,6 +613,50 @@ const SERVER_INSERT_WAIT_MS = 1000;
const WORD_BEFORE = /[\p{L}\p{N}_$]+$/u;
const VALID_FOR = /^[\p{L}\p{N}_$]*$/u;
/** One token a server may replace whole: a Tailwind class (`items-c`), a CSS value. */
const TOKEN = /^[\p{L}\p{N}_$-]+$/u;
/**
* Start of the token the server replaces, when it reaches back past our word over
* hyphens (Tailwind's `items-c`). Items from several servers can be merged, so the
* most common start among single-token ranges ending at the caret wins.
*/
function serverTokenStart(items: readonly CompletionItem[], doc: Text, pos: number, wordFrom: number): number | null {
const votes = new Map<number, number>();
for (const it of items) {
if (!it.replaceRange) continue;
const start = posToOffset(doc, it.replaceRange.start);
const end = posToOffset(doc, it.replaceRange.end);
if (start >= wordFrom || end < pos) continue;
if (!TOKEN.test(doc.sliceString(start, pos))) continue;
votes.set(start, (votes.get(start) ?? 0) + 1);
}
let best: number | null = null;
let most = 0;
for (const [start, n] of votes) {
if (n > most) {
best = start;
most = n;
}
}
return best;
}
/**
* `validFor` for a list that may continue across a hyphen. CodeMirror re-queries
* when this returns false, so only keep the list while an option still starts
* with the typed text: `items-` continues (Tailwind), `foo-bar` in JS re-queries.
*/
function keepFiltering(items: readonly CompletionItem[]) {
let labels: string[] | null = null; // built lazily: an explicit list can hold 26k items
return (text: string): boolean => {
if (VALID_FOR.test(text)) return true;
if (!text.includes("-") || !TOKEN.test(text)) return false;
labels ??= items.map((it) => (it.filterText ?? it.label).toLowerCase());
const typed = text.toLowerCase();
return labels.some((label) => label.startsWith(typed));
};
}
let inflight: RequestId | null = null;
@@ -732,6 +776,12 @@ async function lspCompletionSource(ctx: CompletionContext): Promise<CompletionRe
if (inflight === id) inflight = null;
}
if (ctx.aborted || !list.items.length) return list.items.length || smart ? null : fallback(ctx);
const wordFrom = word?.from ?? ctx.pos;
// Tailwind's replace range covers the whole class (`items-c`) while our word is
// only the `c` after the hyphen; CodeMirror matches a one-character pattern only
// at the start of a label, so filtering on `c` drops `items-center`.
const completionFrom = serverTokenStart(list.items, ctx.state.doc, ctx.pos, wordFrom) ?? wordFrom;
const typed = ctx.state.sliceDoc(completionFrom, ctx.pos);
let lower: ReadonlySet<CompletionItem> = new Set();
if (smart) {
const expected = await expectedType(ctx, doc.doc, word?.from ?? ctx.pos);
@@ -745,7 +795,7 @@ async function lspCompletionSource(ctx: CompletionContext): Promise<CompletionRe
const bases = new Map<string, string[]>();
for (const c of graph) bases.set(c.name, [...(bases.get(c.name) ?? []), ...c.bases]);
const smartResult = await smartItems(list.items, expected, (item) => resolveItem(doc.doc, item), {
typed: word?.text ?? "",
typed,
member: ctx.state.sliceDoc(from - 1, from) === ".",
mentioned: mentionedNames(ctx.state.doc.toString()),
bases: (name) => bases.get(name) ?? [],
@@ -761,7 +811,6 @@ async function lspCompletionSource(ctx: CompletionContext): Promise<CompletionRe
}
const req: RequestContext = { doc: doc.doc, path: doc.path, language: doc.uiMode, pos: ctx.pos, text: ctx.state.doc };
const prefs = editorPrefs().completion;
const typed = word?.text ?? "";
let items = withoutDuplicates(
prefs.matchCase
? list.items.filter((it) => matchesCase(it.filterText ?? it.label, typed, prefs.caseSensitivity))
@@ -776,7 +825,7 @@ async function lspCompletionSource(ctx: CompletionContext): Promise<CompletionRe
if (names.size) items = items.filter((it) => it.kind !== "snippet" || !names.has(it.label));
}
return {
from: word ? word.from : ctx.pos,
from: completionFrom,
options: items.map((item) => {
const option = makeCompletion(item, req);
// Smart Type: an item that may fit (`Any`) follows the ones that do.
@@ -787,7 +836,7 @@ async function lspCompletionSource(ctx: CompletionContext): Promise<CompletionRe
validFor:
list.isIncomplete || (prefs.matchCase && prefs.caseSensitivity === "all") || (smart && typed)
? undefined
: VALID_FOR,
: keepFiltering(items),
filter: true,
};
}