feat(editor): show Tailwind class colors as swatches before the class (#8230)

Language-server colors on text that isn't a color literal (Tailwind classes) are now small swatches in the text before the class, as WebStorm shows Tailwind colors, instead of gutter icons that couldn't be told apart on a busy line. Server colors on CSS literals stay in the gutter; Gutter Icons > Color preview still turns both off.

Closes #8166
Цей коміт міститься в:
l0ng-ai authored and GitHub committed 2026-12-05 21:25:02 +08:00
1 джерело 83a3b1208a
коміт 0df4bc2289
5 files changed
+107 -17

No files matched your search

+13 -3
Переглянути файл
@@ -1,7 +1,9 @@
import { expect, stubDesktop, test } from "./fixtures";
for (const theme of ["light", "dark"]) {
test(`color previews share a column and keep its width while scrolling (${theme})`, async ({ workbench: page }) => {
test(`literal colors share a column that keeps its width; class colors sit before the class (${theme})`, async ({
workbench: page,
}) => {
await stubDesktop(page);
await page.evaluate(async (theme) => {
const backendPath = "/src/editor/core/backend.ts";
@@ -39,10 +41,18 @@ for (const theme of ["light", "dark"]) {
const column = page.locator(".cm-gutter.cm-openidea-gutter-colors");
await expect(column).toHaveCount(1);
const literals = column.locator("span[title]");
const serverColors = column.locator('button[data-color-source^="lsp:"]');
// Class colors (Tailwind) are swatches in the text before each class, as in WebStorm.
const serverColors = page.locator('.cm-content button[data-color-source^="lsp:"]');
await expect(literals).toHaveCount(4);
await expect(serverColors).toHaveCount(4);
expect((await literals.first().boundingBox())!.x).toBe((await serverColors.first().boundingBox())!.x);
await expect(column.locator('button[data-color-source^="lsp:"]')).toHaveCount(0);
const line = (await page.locator(".cm-line").nth(1).boundingBox())!;
const boxes = await Promise.all((await serverColors.all()).map(async (b) => (await b.boundingBox())!));
for (const [i, box] of boxes.entries()) {
expect(box.height).toBeLessThanOrEqual(line.height);
expect(box.y).toBeGreaterThanOrEqual(line.y);
if (i) expect(box.x).toBeGreaterThan(boxes[i - 1]!.x + box.width);
}
const width = (await column.boundingBox())!.width;
expect(width).toBeGreaterThan(0);
const scroller = page.locator(".cm-scroller");
+10
Переглянути файл
@@ -23,6 +23,16 @@
width: 100%;
height: 100%;
}
/* A server color in the text (a Tailwind class): sized to the line, before the class. */
.inline {
display: inline-block;
width: 0.8em;
height: 0.8em;
margin: 0 0.25em 0 0;
padding: 0;
vertical-align: -0.05em;
background: none;
}
.editable {
cursor: pointer;
}
+2 -2
Переглянути файл
@@ -138,7 +138,7 @@ class Swatch extends GutterMarker {
* usages resolving to a color, in source order and without overlaps (a `color-mix()` swatch covers
* the `var()` references inside it).
*/
export function lineSwatches(state: EditorState, pos: number, language: string): SwatchSpec[] {
export function lineSwatches(state: EditorState, pos: number, language: string, max = MAX_SWATCHES): SwatchSpec[] {
const line = state.doc.lineAt(pos);
if (line.length > MAX_LINE) return [];
const matches = findColors(line.text, language, isColorName);
@@ -174,7 +174,7 @@ export function lineSwatches(state: EditorState, pos: number, language: string):
specs.sort((a, b) => a.from - b.from);
const merged: SwatchSpec[] = [];
for (const s of specs) if (!merged.length || merged[merged.length - 1]!.to <= s.from) merged.push(s);
return merged.slice(0, MAX_SWATCHES);
return merged.slice(0, max);
}
export function limitSwatches<T>(
+23 -3
Переглянути файл
@@ -56,7 +56,7 @@ const swatches = (view: EditorView) => [
...view.dom.querySelectorAll<HTMLButtonElement>('button[data-color-source^="lsp:"]'),
];
it("shares the four swatch slots across built-in, plugin and server colors on each line", async () => {
it("shares the four gutter slots with server colors on literals and shows the others in the text", async () => {
vi.useFakeTimers();
ipc.pluginLanguageVisuals.mockResolvedValue({
status: "ok",
@@ -86,8 +86,14 @@ it("shares the four swatch slots across built-in, plugin and server colors on ea
const rows = [...view.dom.querySelectorAll(".cm-openidea-gutter-colors .cm-gutterElement")].filter((row) =>
row.querySelector("[title]"),
);
expect(rows.map((row) => row.querySelectorAll("[title]").length)).toEqual([4, 4, 4]);
const serverSwatch = swatches(view)[0]!;
// Line 1: its literals (built-in and server); line 2: a literal and the plugin color. The server
// colors on `p0`…`p4` aren't literals: they are swatches in the text, as WebStorm shows Tailwind
// classes' colors.
expect(rows.map((row) => row.querySelectorAll("[title]").length)).toEqual([4, 2]);
const inline = view.contentDOM.querySelectorAll('button[data-color-source^="lsp:"]');
expect(inline).toHaveLength(10);
expect(view.contentDOM.querySelectorAll(".cm-line")[2]!.firstElementChild).toBe(inline[5]);
const serverSwatch = inline[0]! as HTMLButtonElement;
await act(async () => fireEvent.mouseDown(serverSwatch, { button: 0 }));
expect(screen.queryByRole("dialog", { name: "Color picker" })).not.toBeInTheDocument();
await act(async () => fireEvent.click(serverSwatch));
@@ -112,6 +118,20 @@ it("keeps the server's swatch for the second literal on a line", () => {
expect(serverOnlyColors(state, "css", [literal, second])).toEqual([second]);
});
it("shows a Tailwind class's color in the text and a CSS value's in the gutter", async () => {
vi.useFakeTimers();
const second = color(0, 0, 1, [0, 0, 1]);
ipc.lspDocumentColors.mockResolvedValue({ status: "ok", data: [literal, tailwind, second] });
const view = open(CSS, "css");
await vi.advanceTimersByTimeAsync(300);
const inline = view.contentDOM.querySelectorAll<HTMLButtonElement>('button[data-color-source^="lsp:"]');
expect([...inline].map((b) => [view.posAtDOM(b), b.title])).toEqual([
[0, "rgba(0, 0, 255, 1)"],
[view.state.doc.line(2).from + 12, "rgba(239, 68, 68, 1)"],
]);
expect(view.dom.querySelectorAll('.cm-gutters button[data-color-source^="lsp:"]')).toHaveLength(0);
});
it("keeps valid swatches when a server reports a range outside the document", async () => {
vi.useFakeTimers();
ipc.lspDocumentColors.mockResolvedValue({ status: "ok", data: [color(2, 0, 6, [0, 1, 0]), tailwind] });
+59 -9
Переглянути файл
@@ -2,9 +2,12 @@
* Colors the language servers report (`textDocument/documentColor`: Tailwind classes, CSS values…).
* A color the built-in literal preview already shows at the same range gets no second swatch, and
* picking a color writes it the way the server presents it (`textDocument/colorPresentation`).
* A color on a literal the built-in preview recognises (a CSS value) is a gutter icon, like the
* built-in ones; any other (a Tailwind class) is a swatch in the text before it, as WebStorm shows
* Tailwind CSS colors.
*/
import { RangeSet, StateEffect, StateField, type EditorState, type Extension } from "@codemirror/state";
import { ViewPlugin, type ViewUpdate } from "@codemirror/view";
import { Decoration, EditorView, ViewPlugin, WidgetType, type ViewUpdate } from "@codemirror/view";
import {
offsetsToRange,
rangeToOffsets,
@@ -22,6 +25,7 @@ import { useProject } from "@/platform/project";
import { colorGutter, colorMarkers, limitSwatches, lineSwatches } from "./gutter";
import { pluginSwatches } from "./pluginColors";
import { ProviderSwatch, mapColors } from "./providerSwatch";
import styles from "./ColorPreview.module.css";
const setColors = StateEffect.define<DocumentColor[]>();
const colors = StateField.define<DocumentColor[]>({
@@ -62,8 +66,43 @@ export function serverOnlyColors(state: EditorState, language: string, list: Doc
});
}
/** Whether `color` covers text the built-in preview shows as a color (a literal or a variable). */
function onLiteral(state: EditorState, language: string, color: DocumentColor): boolean {
const { from, to } = rangeToOffsets(state.doc, color.range);
const line = state.doc.lineAt(from);
return lineSwatches(state, line.from, language, Infinity).some(
(s) => line.from + s.from < to && line.from + s.to > from,
);
}
/** A server color's swatch in the text, before the class or value it colors. */
class InlineSwatch extends WidgetType {
constructor(
readonly color: DocumentColor,
readonly make: (view: EditorView, color: DocumentColor) => ProviderSwatch<DocumentColor>,
) {
super();
}
override eq(other: WidgetType) {
return other instanceof InlineSwatch && JSON.stringify(this.color) === JSON.stringify(other.color);
}
override toDOM(view: EditorView) {
const el = this.make(view, this.color).toDOM();
el.classList.add(styles.inline!);
return el;
}
override ignoreEvent() {
return true;
}
}
export function lspColorPreview(ctx: EditorDocContext): Extension {
if (ctx.doc < 0) return [];
const swatch = (view: EditorView, c: DocumentColor) =>
new ProviderSwatch(`lsp:${c.server}`, c, view, async (chosen) => {
const list = await call(commands.lspColorPresentations(ctx.doc, chosen));
return list.map((p) => ({ label: p.label, changes: textEditsToChanges(view.state.doc, p.edits) }));
});
return [
colors,
colorGutter,
@@ -73,19 +112,30 @@ export function lspColorPreview(ctx: EditorDocContext): Extension {
limitSwatches(
view.state,
ctx.language,
view.state.field(colors),
view.state.field(colors).filter((c) => onLiteral(view.state, ctx.language, c)),
(c) => c.range,
pluginSwatches(view.state, ctx.language).map(([, c]) => c.range),
).map((c) =>
new ProviderSwatch(`lsp:${c.server}`, c, view, async (chosen) => {
const list = await call(commands.lspColorPresentations(ctx.doc, chosen));
return list.map((p) => ({ label: p.label, changes: textEditsToChanges(view.state.doc, p.edits) }));
}).range(view.state.doc.line(c.range.start.line + 1).from),
),
true,
).map((c) => swatch(view, c).range(view.state.doc.line(c.range.start.line + 1).from)),
)
: RangeSet.empty,
),
// Recomputed when the server answers or an edit moves the colors; hidden colors are cleared.
EditorView.decorations.compute([colors], (state) =>
Decoration.set(
state
.field(colors)
.flatMap((c) =>
onLiteral(state, ctx.language, c)
? []
: [
Decoration.widget({ widget: new InlineSwatch(c, swatch), side: -1 }).range(
rangeToOffsets(state.doc, c.range).from,
),
],
),
true,
),
),
ViewPlugin.define(
(view) =>
new (class {