Файли
openidea/src/features/color-preview/gutter.ts
T
2026-12-05 10:32:21 +08:00

378 рядки
14 KiB
TypeScript

/**
* Color preview gutter: swatches for the color literals of a line (as IDEA's color gutter icons)
* and for the `var(--name)` usages whose value resolves to a color, all side by side in source
* 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 { 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, Range } from "@/platform/ipc";
import {
cssColor,
findColors,
formatColor,
isMarkupLanguage,
parseComputed,
type ColorMatch,
type Rgba,
} from "./colors";
import { openColorPicker } from "./ColorPicker";
import { cssVars, setVars, substitutedColor, varLocationsOf, varSwatches, varVariables, varsOf } from "./varColors";
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 = 4;
const names = new Map<string, boolean>();
function isColorName(word: string): boolean {
let known = names.get(word);
if (known === undefined) {
known = typeof CSS !== "undefined" && CSS.supports("color", word);
names.set(word, known);
}
return known;
}
let probe: HTMLElement | null = null;
/** The literal's components, as the browser parses it. */
function rgbaOf(text: string): Rgba | null {
if (!probe?.isConnected) {
probe = document.createElement("span");
probe.hidden = true;
document.body.append(probe);
}
probe.style.color = "";
probe.style.color = text;
return probe.style.color ? parseComputed(getComputedStyle(probe).color) : null;
}
/** One swatch of a line: its range, tooltip and fill; a `color` opens the picker, a `target` the declaration. */
interface SwatchSpec {
from: number;
to: number;
title: string;
fill: string;
/** The literal behind the swatch, when the picker can edit it. */
color?: ColorMatch;
/** The declaration a click opens. */
target?: Location;
}
const sameTarget = (a: Location | undefined, b: Location | undefined) =>
a === b ||
(!!a &&
!!b &&
a.path === b.path &&
a.range.start.line === b.range.start.line &&
a.range.start.col === b.range.start.col);
/**
* A literal's swatch. A function syntax with `var()` inside (`color-mix(in srgb, var(--a) 50%, red)`)
* takes the project's values: painted as written, the IDE's own custom properties would fill it.
* Unresolvable, it shows no swatch and the `var()` swatches inside it show instead.
*/
function specOf(color: ColorMatch, byName: ReadonlyMap<string, string> | undefined): SwatchSpec | null {
if (color.format !== "function")
return { from: color.from, to: color.to, title: color.text, fill: cssColor(color), color };
if (!/\bvar\(/i.test(color.text)) return { from: color.from, to: color.to, title: color.text, fill: color.text };
const fill = byName && substitutedColor(color.text, byName);
return fill ? { from: color.from, to: color.to, title: `${color.text} = ${fill}`, fill } : null;
}
class Swatch extends GutterMarker {
constructor(
readonly specs: readonly SwatchSpec[],
readonly editable: boolean,
) {
super();
}
override eq(other: GutterMarker): boolean {
return (
other instanceof Swatch &&
other.editable === this.editable &&
other.specs.length === this.specs.length &&
other.specs.every((s, i) => {
const mine = this.specs[i]!;
return (
s.from === mine.from &&
s.to === mine.to &&
s.title === mine.title &&
s.fill === mine.fill &&
!!s.color === !!mine.color &&
sameTarget(s.target, mine.target)
);
})
);
}
override toDOM() {
if (this.specs.length === 1) return this.dom(this.specs[0]!);
const group = document.createElement("span");
group.className = styles.group!;
this.specs.forEach((spec, i) => {
const el = this.dom(spec);
el.dataset.i = String(i);
group.append(el);
});
return group;
}
private dom(spec: SwatchSpec) {
const el = document.createElement("span");
const clickable = (spec.color && this.editable) || spec.target;
el.className = clickable ? `${styles.swatch} ${styles.editable}` : `${styles.swatch}`;
el.title = spec.title;
const fill = document.createElement("span");
fill.style.background = spec.fill;
el.append(fill);
return el;
}
}
/**
* All swatches of the line at `pos`: the color literals the syntax tree allows, plus the `var()`
* 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[] {
const line = state.doc.lineAt(pos);
if (line.length > MAX_LINE) return [];
const matches = findColors(line.text, language, isColorName);
const byName = varsOf(state);
const specs: SwatchSpec[] = [];
const add = (color: ColorMatch) => {
const spec = specOf(color, byName);
if (spec) specs.push(spec);
};
if (!isMarkupLanguage(language)) {
for (const color of matches) add(color);
} else {
const tree = syntaxTree(state);
let script: ColorMatch[] | undefined;
for (const color of matches) {
let node: ReturnType<typeof tree.resolveInner> | null = tree.resolveInner(line.from + color.from + 1);
let shown = false;
for (; node; node = node.parent) {
if (node.name === "StyleSheet" || node.name === "Styles") {
shown = true;
break;
}
// Embedded scripts keep the rules of a script file: quoted hex values and color functions only.
if (node.name === "Script") {
shown = (script ??= findColors(line.text, "javascript", isColorName)).some((c) => c.from === color.from);
break;
}
}
if (shown) add(color);
}
}
if (byName) specs.push(...varSwatches(line.text, byName, varLocationsOf(state)));
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);
}
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;
to: number;
original: string;
preview: string;
}
class ColorPreviewWidget extends WidgetType {
constructor(readonly text: string) {
super();
}
override eq(other: ColorPreviewWidget): boolean {
return this.text === other.text;
}
override toDOM(view: EditorView): HTMLElement {
const span = view.dom.ownerDocument.createElement("span");
span.textContent = this.text;
return span;
}
}
const setColorEdit = StateEffect.define<ColorEdit | null>();
const colorEdit = StateField.define<ColorEdit | null>({
create: () => null,
update(edit, tr) {
for (const effect of tr.effects) if (effect.is(setColorEdit)) return effect.value;
if (!edit || !tr.docChanged) return edit;
const from = tr.changes.mapPos(edit.from, 1);
const to = tr.changes.mapPos(edit.to, -1);
return from < to && tr.newDoc.sliceString(from, to) === edit.original ? { ...edit, from, to } : null;
},
provide: (field) =>
EditorView.decorations.from(field, (edit) =>
edit && edit.preview !== edit.original
? Decoration.set(Decoration.replace({ widget: new ColorPreviewWidget(edit.preview) }).range(edit.from, edit.to))
: Decoration.none,
),
});
/** Shows a local preview. The document and undo history change only when the choice is committed. */
function pickColor(view: EditorView, from: number, color: ColorMatch, at: { x: number; y: number }) {
const rgba = rgbaOf(cssColor(color));
if (!rgba) return;
const id = Symbol();
const target = () => {
const edit = view.state.field(colorEdit, false);
return view.dom.isConnected && edit?.id === id ? edit : null;
};
openColorPicker({
view,
anchor: at,
value: rgba,
onChange: (next) => {
const edit = target();
if (!edit || view.state.readOnly) return;
const preview = next.every((channel, index) => channel === rgba[index])
? edit.original
: formatColor(next, color);
if (preview !== edit.preview) view.dispatch({ effects: setColorEdit.of({ ...edit, preview }) });
},
onCommit: (next) => {
const edit = target();
if (!edit) return;
const effects = setColorEdit.of(null);
const insert = formatColor(next, color);
if (view.state.readOnly || insert === edit.original) view.dispatch({ effects });
else
view.dispatch({
changes: { from: edit.from, to: edit.to, insert },
effects,
userEvent: "input.color",
annotations: isolateHistory.of("full"),
});
},
onCancel: () => {
if (target()) view.dispatch({ effects: setColorEdit.of(null) });
},
});
view.dispatch({
effects: setColorEdit.of({ id, from, to: from + color.text.length, original: color.text, preview: color.text }),
});
}
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), colorContext.of(ctx), colorGutter];
}