дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-05 09:41:34 +02:00
fix(editor): cap and stabilize color preview gutter (#8073)
Co-authored-by: l0ng-ai <[email protected]>
Цей коміт міститься в:
1 джерело
ca4644cbde
коміт
6600a06ee8
9 files changed
+309
-81
No files matched your search
@@ -0,0 +1,64 @@
|
||||
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 }) => {
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(async (theme) => {
|
||||
const backendPath = "/src/editor/core/backend.ts";
|
||||
const contributionsPath = "/src/workbench/contributions.ts";
|
||||
const themePath = "/src/workbench/theme.ts";
|
||||
const { docBackend } = await import(backendPath);
|
||||
const { editorService } = await import(contributionsPath);
|
||||
const { useThemeOverride } = await import(themePath);
|
||||
useThemeOverride.setState({ theme });
|
||||
const source = "/dev/acme-api/colors.html";
|
||||
const classes = '<div class="bg-one bg-two bg-three bg-four">Colors</div>';
|
||||
docBackend().files.set(
|
||||
source,
|
||||
[
|
||||
'<div style="background: linear-gradient(#112233, #445566, #778899, #aabbcc, #ddeeff)">Colors</div>',
|
||||
classes,
|
||||
...Array.from({ length: 200 }, (_, i) => `<p>Line ${i}</p>`),
|
||||
].join("\n"),
|
||||
);
|
||||
window.__ipc.handlers.window_is_fullscreen = () => false;
|
||||
window.__ipc.handlers.lsp_document_colors = () =>
|
||||
["bg-one", "bg-two", "bg-three", "bg-four"].map((name) => ({
|
||||
server: 7,
|
||||
range: {
|
||||
start: { line: 1, col: classes.indexOf(name) },
|
||||
end: { line: 1, col: classes.indexOf(name) + name.length },
|
||||
},
|
||||
red: 0.5,
|
||||
green: 0.25,
|
||||
blue: 1,
|
||||
alpha: 1,
|
||||
}));
|
||||
await editorService().openFile(source);
|
||||
}, theme);
|
||||
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:"]');
|
||||
await expect(literals).toHaveCount(4);
|
||||
await expect(serverColors).toHaveCount(4);
|
||||
expect((await literals.first().boundingBox())!.x).toBe((await serverColors.first().boundingBox())!.x);
|
||||
const width = (await column.boundingBox())!.width;
|
||||
expect(width).toBeGreaterThan(0);
|
||||
const scroller = page.locator(".cm-scroller");
|
||||
for (const size of [
|
||||
{ width: 1400, height: 900 },
|
||||
{ width: 800, height: 600 },
|
||||
]) {
|
||||
await page.setViewportSize(size);
|
||||
await scroller.evaluate((el) => (el.scrollTop = el.scrollHeight));
|
||||
await expect(literals).toHaveCount(0);
|
||||
await expect(serverColors).toHaveCount(0);
|
||||
await expect.poll(async () => (await column.boundingBox())!.width).toBe(width);
|
||||
await scroller.evaluate((el) => (el.scrollTop = 0));
|
||||
await expect(literals).toHaveCount(4);
|
||||
await expect(serverColors).toHaveCount(4);
|
||||
expect((await column.boundingBox())!.width).toBe(width);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
.gutter :global(.cm-gutterElement) {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
justify-content: flex-start;
|
||||
}
|
||||
/* A line with several swatches (fallback chains): the children join the gutter element's flex row. */
|
||||
.group {
|
||||
|
||||
@@ -46,7 +46,7 @@ async function openCssPicker() {
|
||||
}),
|
||||
parent: document.body,
|
||||
});
|
||||
const swatch = view.dom.querySelector(".cm-openidea-gutter-colors .cm-gutterElement span")!;
|
||||
const swatch = view.dom.querySelector(".cm-openidea-gutter-colors .cm-gutterElement span[title]")!;
|
||||
await act(async () => fireEvent.mouseDown(swatch, { button: 0 }));
|
||||
return view;
|
||||
}
|
||||
@@ -121,7 +121,7 @@ it("samples a screen color and offers it again as a recent color", async () => {
|
||||
parent: document.body,
|
||||
});
|
||||
const open = async () => {
|
||||
const swatch = view!.dom.querySelector(".cm-openidea-gutter-colors .cm-gutterElement span")!;
|
||||
const swatch = view!.dom.querySelector(".cm-openidea-gutter-colors .cm-gutterElement span[title]")!;
|
||||
await act(async () => fireEvent.mouseDown(swatch, { button: 0 }));
|
||||
};
|
||||
await open();
|
||||
@@ -223,7 +223,7 @@ it("updates a CSS literal from alpha and hex fields and ignores invalid input",
|
||||
}),
|
||||
parent: document.body,
|
||||
});
|
||||
const swatch = view.dom.querySelector(".cm-openidea-gutter-colors .cm-gutterElement span")!;
|
||||
const swatch = view.dom.querySelector(".cm-openidea-gutter-colors .cm-gutterElement span[title]")!;
|
||||
await act(async () => fireEvent.mouseDown(swatch, { button: 0 }));
|
||||
|
||||
const field = (name: string) => document.querySelector<HTMLInputElement>(`input[aria-label="${name}"]`)!;
|
||||
|
||||
@@ -4,13 +4,13 @@
|
||||
* order. Picking a color replaces the literal in its own format; a resolved variable's swatch opens
|
||||
* its declaration, and modern function syntaxes show the resolved value without a picker.
|
||||
*/
|
||||
import { StateEffect, StateField, type EditorState, type Extension } from "@codemirror/state";
|
||||
import { Facet, StateEffect, StateField, type EditorState, type Extension, type RangeSet } from "@codemirror/state";
|
||||
import { Decoration, EditorView, GutterMarker, WidgetType, gutter } from "@codemirror/view";
|
||||
import { isolateHistory } from "@codemirror/commands";
|
||||
import { syntaxTree } from "@codemirror/language";
|
||||
import type { EditorDocContext } from "@/editor/api";
|
||||
import { navigateTo } from "@/editor/lsp/navigation";
|
||||
import type { Location } from "@/platform/ipc";
|
||||
import type { Location, Range } from "@/platform/ipc";
|
||||
import {
|
||||
cssColor,
|
||||
findColors,
|
||||
@@ -27,7 +27,7 @@ import styles from "./ColorPreview.module.css";
|
||||
/** Longer lines (minified style sheets) are not scanned. */
|
||||
const MAX_LINE = 2000;
|
||||
/** Swatches per line: fallback chains are a few names; longer lists would stretch the gutter. */
|
||||
const MAX_SWATCHES = 8;
|
||||
const MAX_SWATCHES = 4;
|
||||
|
||||
const names = new Map<string, boolean>();
|
||||
function isColorName(word: string): boolean {
|
||||
@@ -177,6 +177,26 @@ export function lineSwatches(state: EditorState, pos: number, language: string):
|
||||
return merged.slice(0, MAX_SWATCHES);
|
||||
}
|
||||
|
||||
export function limitSwatches<T>(
|
||||
state: EditorState,
|
||||
language: string,
|
||||
items: readonly T[],
|
||||
rangeOf: (item: T) => Range,
|
||||
reserved: readonly Range[] = [],
|
||||
): T[] {
|
||||
const counts = new Map<number, number>();
|
||||
const take = (range: Range) => {
|
||||
const lineNo = range.start.line + 1;
|
||||
if (lineNo < 1 || lineNo > state.doc.lines) return false;
|
||||
const line = state.doc.line(lineNo);
|
||||
const count = counts.get(line.number) ?? lineSwatches(state, line.from, language).length;
|
||||
counts.set(line.number, count + 1);
|
||||
return count < MAX_SWATCHES;
|
||||
};
|
||||
reserved.forEach(take);
|
||||
return items.filter((item) => take(rangeOf(item)));
|
||||
}
|
||||
|
||||
interface ColorEdit {
|
||||
id: symbol;
|
||||
from: number;
|
||||
@@ -261,42 +281,97 @@ function pickColor(view: EditorView, from: number, color: ColorMatch, at: { x: n
|
||||
});
|
||||
}
|
||||
|
||||
const colorContext = Facet.define<EditorDocContext, EditorDocContext | null>({
|
||||
combine: (values) => values[0] ?? null,
|
||||
});
|
||||
export const colorMarkers = Facet.define<(view: EditorView) => RangeSet<GutterMarker>>();
|
||||
|
||||
class ColorSpacer extends GutterMarker {
|
||||
constructor(readonly count: number) {
|
||||
super();
|
||||
}
|
||||
override toDOM() {
|
||||
const group = document.createElement("span");
|
||||
group.className = styles.group!;
|
||||
for (let i = 0; i < this.count; i++) group.appendChild(document.createElement("span")).className = styles.swatch!;
|
||||
return group;
|
||||
}
|
||||
}
|
||||
|
||||
/** Keep the widest color row encountered in this editor so scrolling never shifts the code. */
|
||||
function swatchCount(view: EditorView, held: number): number {
|
||||
if (held === MAX_SWATCHES) return held;
|
||||
const lines = new Map<number, number>();
|
||||
for (const markers of view.state.facet(colorMarkers))
|
||||
for (const it = markers(view).iter(); it.value; it.next()) lines.set(it.from, (lines.get(it.from) ?? 0) + 1);
|
||||
for (const { from, to } of view.visibleRanges) {
|
||||
let line = view.state.doc.lineAt(from);
|
||||
for (;;) {
|
||||
if (!lines.has(line.from)) lines.set(line.from, 0);
|
||||
if (line.to >= to) break;
|
||||
line = view.state.doc.line(line.number + 1);
|
||||
}
|
||||
}
|
||||
const ctx = view.state.facet(colorContext);
|
||||
for (const [pos, count] of lines) {
|
||||
held = Math.max(held, count + (ctx ? lineSwatches(view.state, pos, ctx.language).length : 0));
|
||||
if (held >= MAX_SWATCHES) return MAX_SWATCHES;
|
||||
}
|
||||
return held;
|
||||
}
|
||||
|
||||
export const colorGutter = gutter({
|
||||
class: `${styles.gutter} cm-openidea-gutter-colors`,
|
||||
markers: (view) => view.state.facet(colorMarkers).map((markers) => markers(view)),
|
||||
initialSpacer: (view) => new ColorSpacer(swatchCount(view, 0)),
|
||||
updateSpacer: (previous, update) => {
|
||||
if (
|
||||
!update.docChanged &&
|
||||
!update.viewportChanged &&
|
||||
!update.geometryChanged &&
|
||||
update.startState.facet(colorContext) === update.state.facet(colorContext) &&
|
||||
!update.transactions.some((tr) => tr.effects.length > 0)
|
||||
)
|
||||
return previous;
|
||||
const held = previous instanceof ColorSpacer ? previous.count : 0;
|
||||
const count = swatchCount(update.view, held);
|
||||
return count === held ? previous : new ColorSpacer(count);
|
||||
},
|
||||
lineMarker: (view, block) => {
|
||||
const ctx = view.state.facet(colorContext);
|
||||
if (!ctx) return null;
|
||||
const specs = lineSwatches(view.state, block.from, ctx.language);
|
||||
return specs.length ? new Swatch(specs, !view.state.readOnly) : null;
|
||||
},
|
||||
lineMarkerChange: (update) =>
|
||||
update.docChanged ||
|
||||
update.startState.facet(colorContext) !== update.state.facet(colorContext) ||
|
||||
update.startState.readOnly !== update.state.readOnly ||
|
||||
update.transactions.some((tr) => tr.effects.some((e) => e.is(setVars))),
|
||||
domEventHandlers: {
|
||||
mousedown: (view, block, event) => {
|
||||
const ctx = view.state.facet(colorContext);
|
||||
const e = event as MouseEvent;
|
||||
const swatch = e.target instanceof Element ? e.target.closest(`.${styles.swatch}`) : null;
|
||||
if (!ctx || e.button !== 0 || swatch?.tagName !== "SPAN") return false;
|
||||
const line = view.state.doc.lineAt(block.from);
|
||||
const specs = lineSwatches(view.state, block.from, ctx.language);
|
||||
const index = swatch instanceof HTMLElement && swatch.dataset.i !== undefined ? Number(swatch.dataset.i) : 0;
|
||||
const spec = specs[index];
|
||||
if (spec?.target) {
|
||||
e.preventDefault();
|
||||
void navigateTo(spec.target);
|
||||
return true;
|
||||
}
|
||||
if (!spec?.color || view.state.readOnly) return false;
|
||||
e.preventDefault();
|
||||
const rect = swatch.getBoundingClientRect();
|
||||
pickColor(view, line.from + spec.from, spec.color, { x: rect.left, y: rect.bottom });
|
||||
return true;
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
export function colorPreviewGutter(ctx: EditorDocContext): Extension {
|
||||
return [
|
||||
colorEdit,
|
||||
cssVars,
|
||||
varVariables(ctx),
|
||||
gutter({
|
||||
class: `${styles.gutter} cm-openidea-gutter-colors`,
|
||||
lineMarker: (view, block) => {
|
||||
const specs = lineSwatches(view.state, block.from, ctx.language);
|
||||
return specs.length ? new Swatch(specs, !view.state.readOnly) : null;
|
||||
},
|
||||
lineMarkerChange: (update) =>
|
||||
update.docChanged ||
|
||||
update.startState.readOnly !== update.state.readOnly ||
|
||||
update.transactions.some((tr) => tr.effects.some((e) => e.is(setVars))),
|
||||
domEventHandlers: {
|
||||
mousedown: (view, block, event) => {
|
||||
const e = event as MouseEvent;
|
||||
const swatch = e.target instanceof Element ? e.target.closest(`.${styles.swatch}`) : null;
|
||||
if (e.button !== 0 || !swatch) return false;
|
||||
const line = view.state.doc.lineAt(block.from);
|
||||
const specs = lineSwatches(view.state, block.from, ctx.language);
|
||||
const index = swatch instanceof HTMLElement && swatch.dataset.i !== undefined ? Number(swatch.dataset.i) : 0;
|
||||
const spec = specs[index];
|
||||
if (spec?.target) {
|
||||
e.preventDefault();
|
||||
void navigateTo(spec.target);
|
||||
return true;
|
||||
}
|
||||
if (!spec?.color || view.state.readOnly) return false;
|
||||
e.preventDefault();
|
||||
const rect = swatch.getBoundingClientRect();
|
||||
pickColor(view, line.from + spec.from, spec.color, { x: rect.left, y: rect.bottom });
|
||||
return true;
|
||||
},
|
||||
},
|
||||
}),
|
||||
];
|
||||
return [colorEdit, cssVars, varVariables(ctx), colorContext.of(ctx), colorGutter];
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import type { DocumentColor } from "@/platform/ipc";
|
||||
const ipc = vi.hoisted(() => ({
|
||||
lspDocumentColors: vi.fn(),
|
||||
lspColorPresentations: vi.fn(),
|
||||
pluginLanguageVisuals: vi.fn(),
|
||||
}));
|
||||
vi.mock("@/platform/ipc", async (original) => ({
|
||||
...(await original<typeof import("@/platform/ipc")>()),
|
||||
@@ -16,6 +17,8 @@ vi.mock("@/ui", async (original) => ({ ...(await original<typeof import("@/ui")>
|
||||
const { lspColorPreview, serverOnlyColors } = await import("./lspColors");
|
||||
const { disposeColorPicker } = await import("./ColorPicker");
|
||||
const { mapColors } = await import("./providerSwatch");
|
||||
const { colorPreviewGutter } = await import("./gutter");
|
||||
const { pluginColorPreview } = await import("./pluginColors");
|
||||
const { useProject } = await import("@/platform/project");
|
||||
const views: EditorView[] = [];
|
||||
afterEach(() => {
|
||||
@@ -50,9 +53,47 @@ function open(doc: string, language: string) {
|
||||
return view;
|
||||
}
|
||||
const swatches = (view: EditorView) => [
|
||||
...view.dom.querySelectorAll<HTMLButtonElement>(".cm-lsp-color-preview button"),
|
||||
...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 () => {
|
||||
vi.useFakeTimers();
|
||||
ipc.pluginLanguageVisuals.mockResolvedValue({
|
||||
status: "ok",
|
||||
data: { version: 1, injections: [], gutterActions: [], colors: [["p", color(1, 8, 10, [1, 0, 0])]] },
|
||||
});
|
||||
ipc.lspDocumentColors.mockResolvedValue({
|
||||
status: "ok",
|
||||
data: [
|
||||
...Array.from({ length: 5 }, (_, i) => color(0, i * 8, i * 8 + 7, [1, 0, 0])),
|
||||
...Array.from({ length: 5 }, (_, i) => color(1, 11 + i * 3, 13 + i * 3, [1, 0, 0])),
|
||||
...Array.from({ length: 5 }, (_, i) => color(2, i * 3, i * 3 + 2, [1, 0, 0])),
|
||||
],
|
||||
});
|
||||
const ctx = { doc: 1, path: "/p/a.css", language: "css", uiMode: null, readOnly: false };
|
||||
const view = new EditorView({
|
||||
state: EditorState.create({
|
||||
doc: `${Array(5).fill("#112233").join(" ")}\n#112233 p0 p1 p2 p3 p4 p5\np0 p1 p2 p3 p4`,
|
||||
extensions: [colorPreviewGutter(ctx), pluginColorPreview(ctx), lspColorPreview(ctx)],
|
||||
}),
|
||||
parent: document.body,
|
||||
});
|
||||
views.push(view);
|
||||
await vi.advanceTimersByTimeAsync(300);
|
||||
expect(view.dom.querySelectorAll(".cm-openidea-gutter-colors span[title]")).toHaveLength(5);
|
||||
expect(view.dom.querySelectorAll('button[data-color-source^="plugin:"]')).toHaveLength(1);
|
||||
expect(view.dom.querySelectorAll(".cm-gutter.cm-openidea-gutter-colors")).toHaveLength(1);
|
||||
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]!;
|
||||
await act(async () => fireEvent.mouseDown(serverSwatch, { button: 0 }));
|
||||
expect(screen.queryByRole("dialog", { name: "Color picker" })).not.toBeInTheDocument();
|
||||
await act(async () => fireEvent.click(serverSwatch));
|
||||
expect(screen.getByRole("dialog", { name: "Color picker" })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("drops server colors the built-in literal preview already shows at the same range", () => {
|
||||
const state = EditorState.create({ doc: CSS });
|
||||
expect(serverOnlyColors(state, "css", [literal, tailwind])).toEqual([tailwind]);
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
* picking a color writes it the way the server presents it (`textDocument/colorPresentation`).
|
||||
*/
|
||||
import { RangeSet, StateEffect, StateField, type EditorState, type Extension } from "@codemirror/state";
|
||||
import { ViewPlugin, gutter, type ViewUpdate } from "@codemirror/view";
|
||||
import { ViewPlugin, type ViewUpdate } from "@codemirror/view";
|
||||
import {
|
||||
offsetsToRange,
|
||||
rangeToOffsets,
|
||||
@@ -19,9 +19,9 @@ import { gutterIconsOn, localAppearanceField } from "@/editor/core/cm/localAppea
|
||||
import { editorPrefs } from "@/platform/editorSettings";
|
||||
import { call, commands, type DocumentColor } from "@/platform/ipc";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { lineSwatches } from "./gutter";
|
||||
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[]>({
|
||||
@@ -66,21 +66,26 @@ export function lspColorPreview(ctx: EditorDocContext): Extension {
|
||||
if (ctx.doc < 0) return [];
|
||||
return [
|
||||
colors,
|
||||
gutter({
|
||||
class: `${styles.gutter} cm-openidea-gutter-colors cm-lsp-color-preview`,
|
||||
markers: (view) =>
|
||||
gutterIconsOn(view.state, "colors")
|
||||
? RangeSet.of(
|
||||
view.state.field(colors).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,
|
||||
)
|
||||
: RangeSet.empty,
|
||||
}),
|
||||
colorGutter,
|
||||
colorMarkers.of((view) =>
|
||||
gutterIconsOn(view.state, "colors")
|
||||
? RangeSet.of(
|
||||
limitSwatches(
|
||||
view.state,
|
||||
ctx.language,
|
||||
view.state.field(colors),
|
||||
(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,
|
||||
)
|
||||
: RangeSet.empty,
|
||||
),
|
||||
ViewPlugin.define(
|
||||
(view) =>
|
||||
new (class {
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import { afterEach, expect, it, vi } from "vitest";
|
||||
import { EditorState } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { html } from "@codemirror/lang-html";
|
||||
import { act, fireEvent, screen } from "@testing-library/react";
|
||||
import { colorPreviewGutter } from "./gutter";
|
||||
const ipc = vi.hoisted(() => ({
|
||||
pluginLanguageVisuals: vi.fn(),
|
||||
pluginColorPresentations: vi.fn(async () => ({ status: "ok", data: ["red"] })),
|
||||
@@ -19,6 +21,46 @@ afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
it.each(["css", "html", "text"])("limits combined color previews to four per line in %s", async (language) => {
|
||||
vi.useFakeTimers();
|
||||
const color = (line: number, col: number) => ({
|
||||
range: { start: { line, col }, end: { line, col: col + 7 } },
|
||||
red: 1,
|
||||
green: col / 100,
|
||||
blue: 0,
|
||||
alpha: 1,
|
||||
});
|
||||
ipc.pluginLanguageVisuals.mockResolvedValue({
|
||||
status: "ok",
|
||||
data: {
|
||||
version: 1,
|
||||
injections: [],
|
||||
gutterActions: [],
|
||||
colors: [
|
||||
...Array.from({ length: 3 }, (_, i) => ["first", color(0, i * 8)]),
|
||||
["first", color(1, 0)],
|
||||
...Array.from({ length: 5 }, (_, i) => ["second", color(0, (i + 3) * 8)]),
|
||||
["second", color(1, 8)],
|
||||
],
|
||||
},
|
||||
});
|
||||
const ctx = { doc: 1, path: `/p/a.${language}`, language, uiMode: null, readOnly: false };
|
||||
const lines = [Array(8).fill("#112233").join(" "), "#445566 #778899"];
|
||||
const view = new EditorView({
|
||||
state: EditorState.create({
|
||||
doc: lines.map((line) => (language === "html" ? `<div style="color: ${line}"></div>` : line)).join("\n"),
|
||||
extensions: [html(), colorPreviewGutter(ctx), pluginColorPreview(ctx)],
|
||||
}),
|
||||
parent: document.body,
|
||||
});
|
||||
views.push(view);
|
||||
await vi.advanceTimersByTimeAsync(300);
|
||||
const pluginRows = [...view.dom.querySelectorAll(".cm-openidea-gutter-colors .cm-gutterElement")].filter((row) =>
|
||||
row.querySelector("button"),
|
||||
);
|
||||
expect(pluginRows.map((row) => row.querySelectorAll("button").length)).toEqual(language === "text" ? [4, 2] : [2]);
|
||||
expect(view.dom.querySelectorAll(".cm-openidea-gutter-colors span[title]")).toHaveLength(language === "text" ? 0 : 6);
|
||||
});
|
||||
it.each(["Apply", "Escape"])(
|
||||
"uses plugin presentations to replace the reported range only on commit (%s)",
|
||||
async (dismissal) => {
|
||||
@@ -93,7 +135,7 @@ it("keeps plugin swatches while typing outside their range", async () => {
|
||||
await vi.advanceTimersByTimeAsync(300);
|
||||
ipc.pluginLanguageVisuals.mockReturnValue(new Promise(() => {}));
|
||||
view.dispatch({ changes: { from: 0, insert: "q" } });
|
||||
expect(view.dom.querySelectorAll(".cm-plugin-color-preview button")).toHaveLength(1);
|
||||
expect(view.dom.querySelectorAll('button[data-color-source^="plugin:"]')).toHaveLength(1);
|
||||
view.dispatch({ changes: { from: 5, to: 6, insert: "Y" } });
|
||||
expect(view.dom.querySelectorAll(".cm-plugin-color-preview button")).toHaveLength(0);
|
||||
expect(view.dom.querySelectorAll('button[data-color-source^="plugin:"]')).toHaveLength(0);
|
||||
});
|
||||
@@ -1,12 +1,12 @@
|
||||
/** Plugin colors use the shared picker and provider-supplied replacement strings. */
|
||||
import { RangeSet, StateEffect, StateField, type Extension } from "@codemirror/state";
|
||||
import { ViewPlugin, gutter, type ViewUpdate } from "@codemirror/view";
|
||||
import { RangeSet, StateEffect, StateField, type EditorState, type Extension } from "@codemirror/state";
|
||||
import { ViewPlugin, type ViewUpdate } from "@codemirror/view";
|
||||
import { onNavigationProvidersChanged, shownAgain, type EditorDocContext } from "@/editor/api";
|
||||
import { pluginVisuals } from "@/editor/lsp/pluginVisuals";
|
||||
import { CoalescedRefresh } from "@/editor/coalescedRefresh";
|
||||
import { call, commands, type ColorInfo } from "@/platform/ipc";
|
||||
import { ProviderSwatch, mapColors, replaceRange } from "./providerSwatch";
|
||||
import styles from "./ColorPreview.module.css";
|
||||
import { colorGutter, colorMarkers, limitSwatches } from "./gutter";
|
||||
const setColors = StateEffect.define<[string, ColorInfo][]>();
|
||||
const colors = StateField.define<[string, ColorInfo][]>({
|
||||
create: () => [],
|
||||
@@ -19,24 +19,24 @@ const colors = StateField.define<[string, ColorInfo][]>({
|
||||
).map(({ range, provider, color }) => [provider, { ...color, range }]);
|
||||
},
|
||||
});
|
||||
export function pluginSwatches(state: EditorState, language: string): [string, ColorInfo][] {
|
||||
return limitSwatches(state, language, state.field(colors, false) ?? [], ([, color]) => color.range);
|
||||
}
|
||||
export function pluginColorPreview(ctx: EditorDocContext): Extension {
|
||||
if (ctx.doc < 0) return [];
|
||||
return [
|
||||
colors,
|
||||
gutter({
|
||||
class: `${styles.gutter} cm-plugin-color-preview`,
|
||||
markers: (view) =>
|
||||
RangeSet.of(
|
||||
view.state
|
||||
.field(colors)
|
||||
.map(([p, c]) =>
|
||||
new ProviderSwatch(`plugin:${p}`, c, view, async (chosen) =>
|
||||
replaceRange(view, c.range, await call(commands.pluginColorPresentations(ctx.doc, p, chosen))),
|
||||
).range(view.state.doc.line(c.range.start.line + 1).from),
|
||||
),
|
||||
true,
|
||||
colorGutter,
|
||||
colorMarkers.of((view) =>
|
||||
RangeSet.of(
|
||||
pluginSwatches(view.state, ctx.language).map(([p, c]) =>
|
||||
new ProviderSwatch(`plugin:${p}`, c, view, async (chosen) =>
|
||||
replaceRange(view, c.range, await call(commands.pluginColorPresentations(ctx.doc, p, chosen))),
|
||||
).range(view.state.doc.line(c.range.start.line + 1).from),
|
||||
),
|
||||
}),
|
||||
true,
|
||||
),
|
||||
),
|
||||
ViewPlugin.define(
|
||||
(view) =>
|
||||
new (class {
|
||||
|
||||
@@ -49,6 +49,7 @@ export class ProviderSwatch<C extends ProviderColor> extends GutterMarker {
|
||||
const { red, green, blue, alpha } = this.color;
|
||||
const el = document.createElement("button");
|
||||
el.type = "button";
|
||||
el.dataset.colorSource = this.source;
|
||||
el.className = this.view.state.readOnly ? styles.swatch! : `${styles.swatch} ${styles.editable}`;
|
||||
el.title = `rgba(${byte(red)}, ${byte(green)}, ${byte(blue)}, ${Number((alpha ?? 1).toFixed(2))})`;
|
||||
el.setAttribute("aria-label", el.title);
|
||||
|
||||
Reference in new issue
Заблокувати користувача