diff --git a/e2e/colorPreview.spec.ts b/e2e/colorPreview.spec.ts index 5a94191efb..dad9bcb637 100644 --- a/e2e/colorPreview.spec.ts +++ b/e2e/colorPreview.spec.ts @@ -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"); diff --git a/src/features/color-preview/ColorPreview.module.css b/src/features/color-preview/ColorPreview.module.css index 6f5e260942..3cbe045bee 100644 --- a/src/features/color-preview/ColorPreview.module.css +++ b/src/features/color-preview/ColorPreview.module.css @@ -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; } diff --git a/src/features/color-preview/gutter.ts b/src/features/color-preview/gutter.ts index 11c992ace5..477af162b1 100644 --- a/src/features/color-preview/gutter.ts +++ b/src/features/color-preview/gutter.ts @@ -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( diff --git a/src/features/color-preview/lspColors.test.ts b/src/features/color-preview/lspColors.test.ts index 2284b84b00..cd0b3f99ce 100644 --- a/src/features/color-preview/lspColors.test.ts +++ b/src/features/color-preview/lspColors.test.ts @@ -56,7 +56,7 @@ const swatches = (view: EditorView) => [ ...view.dom.querySelectorAll('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('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] }); diff --git a/src/features/color-preview/lspColors.ts b/src/features/color-preview/lspColors.ts index 32065e979c..570ee23fc9 100644 --- a/src/features/color-preview/lspColors.ts +++ b/src/features/color-preview/lspColors.ts @@ -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(); const colors = StateField.define({ @@ -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, + ) { + 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 {