Skip to content

Commit 9da2b96

Browse files
authored
fix(editor): canvas theme colors for plugin themes styled in CSS (#3072)
* fix(editor): canvas theme colors for plugin themes styled in CSS Plugin themes registered with only background, foreground and syntax colors in their config style the active line, gutter, cursor and selection in their EditorView.theme. The canvas renderer, which doesn't draw from CSS, showed defaults there. getCanvasTheme now reads those colors from the theme's own style rules (once per theme, no DOM), including an outlined active line (inset box-shadow); the config still wins where it sets a color. A plugin theme registered after the editor was created kept the canvas on One Dark's colors: re-applying the same theme id was skipped. The sync key now includes the registered theme entry. * chore(deps): bump @acode.app/canvas-view to 0.0.8
1 parent 50179ac commit 9da2b96

5 files changed

Lines changed: 295 additions & 21 deletions

File tree

‎bun.lock‎

Lines changed: 2 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎package-lock.json‎

Lines changed: 4 additions & 4 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -125,7 +125,7 @@
125125
"ws": "^8.21.3"
126126
},
127127
"dependencies": {
128-
"@acode.app/canvas-view": "^0.0.7",
128+
"@acode.app/canvas-view": "^0.0.8",
129129
"@codemirror/autocomplete": "^6.20.3",
130130
"@codemirror/commands": "^6.11.0",
131131
"@codemirror/lang-angular": "^0.1.4",

‎src/cm/canvasOptions.ts‎

Lines changed: 189 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,141 @@ export function findHighlightStyle(
104104
);
105105
}
106106

107+
/**
108+
* Editor surface colors a theme's own `EditorView.theme` rules set, for
109+
* the canvas renderer, which doesn't draw from CSS. Plugin themes are often
110+
* registered with only background, foreground and syntax colors in their
111+
* config, and style the active line, gutter and cursor in CSS.
112+
* Parsed from the style modules' rule strings when the canvas theme is
113+
* built (theme changes): no DOM is read, nothing runs per frame.
114+
*/
115+
interface RuleColors {
116+
activeLine?: string;
117+
activeLineBorder?: string;
118+
activeLineBorderWidth?: number;
119+
activeLineGutter?: string;
120+
gutterBackground?: string;
121+
gutterForeground?: string;
122+
gutterActiveForeground?: string;
123+
selection?: string;
124+
cursor?: string;
125+
}
126+
127+
function collectStyleRules(
128+
extension: unknown,
129+
rules: string[],
130+
seen = new Set<unknown>(),
131+
): string[] {
132+
if (!extension || typeof extension !== "object" || seen.has(extension)) {
133+
return rules;
134+
}
135+
seen.add(extension);
136+
if (Array.isArray(extension)) {
137+
for (const item of extension) collectStyleRules(item, rules, seen);
138+
return rules;
139+
}
140+
const node = extension as {
141+
getRules?: () => unknown;
142+
value?: unknown;
143+
inner?: unknown;
144+
extension?: unknown;
145+
};
146+
// A StyleModule (style-mod): one "selectors {declarations}" rule per line.
147+
if (typeof node.getRules === "function") {
148+
const text = node.getRules();
149+
if (typeof text === "string") rules.push(...text.split("\n"));
150+
return rules;
151+
}
152+
collectStyleRules(node.value, rules, seen);
153+
collectStyleRules(node.inner, rules, seen);
154+
collectStyleRules(node.extension, rules, seen);
155+
return rules;
156+
}
157+
158+
const COLOR_TOKEN =
159+
/(?:rgba?|hsla?|hwb|lab|lch|oklab|oklch|color)\([^)]*\)|#[0-9a-f]{3,8}\b|\b(?!inset\b)[a-z]+\b/i;
160+
161+
/** A color in a CSS value ("2px solid #333" -> "#333"); null for var(). */
162+
function colorIn(value: string): string | null {
163+
if (/var\(/.test(value)) return null;
164+
const m = COLOR_TOKEN.exec(
165+
value.replace(/\b(?:solid|dashed|dotted|double|none)\b/g, ""),
166+
);
167+
if (
168+
!m ||
169+
/^(?:transparent|currentcolor|inherit|initial|unset)$/i.test(m[0])
170+
) {
171+
return m && /^transparent$/i.test(m[0]) ? "transparent" : null;
172+
}
173+
return m[0];
174+
}
175+
176+
/** An inset box-shadow without offset or blur as a frame (`0 0 0 2px #333 inset`). */
177+
function insetFrame(value: string): { color: string; width: number } | null {
178+
const first = value.split(/,(?![^(]*\))/)[0];
179+
if (!/\binset\b/.test(first)) return null;
180+
const color = colorIn(first.replace(/\binset\b/, ""));
181+
const lengths = (
182+
first.replace(COLOR_TOKEN, " ").match(/-?\d*\.?\d+(?:px)?\b/g) ?? []
183+
).map(Number.parseFloat);
184+
const [x = 0, y = 0, blur = 0, spread = 0] = lengths;
185+
if (!color || color === "transparent" || x || y || blur || !(spread > 0)) {
186+
return null;
187+
}
188+
return { color, width: spread };
189+
}
190+
191+
export function themeRuleColors(extension: unknown): RuleColors {
192+
const found: RuleColors = {};
193+
let focusedSelection: string | undefined;
194+
for (const rule of collectStyleRules(extension, [])) {
195+
const m = /^([^{]+)\{([^}]*)\}\s*$/.exec(rule);
196+
if (!m) continue;
197+
const decls = new Map<string, string>();
198+
for (const decl of m[2].split(/;(?![^(]*\))/)) {
199+
const i = decl.indexOf(":");
200+
if (i > 0) decls.set(decl.slice(0, i).trim(), decl.slice(i + 1).trim());
201+
}
202+
const bg = decls.get("background-color") ?? decls.get("background");
203+
const bgColor = bg ? colorIn(bg) : null;
204+
for (const sel of m[1].split(",").map((s) => s.trim())) {
205+
// Only the element itself, not states or descendants of it.
206+
if (/:(?:hover|active|focus)|::/.test(sel)) continue;
207+
if (/\.cm-activeLine$/.test(sel)) {
208+
if (bgColor) found.activeLine = bgColor;
209+
const frame = decls.has("box-shadow")
210+
? insetFrame(decls.get("box-shadow") as string)
211+
: null;
212+
if (frame) {
213+
found.activeLineBorder = frame.color;
214+
found.activeLineBorderWidth = frame.width;
215+
}
216+
} else if (/\.cm-gutters$/.test(sel)) {
217+
if (bgColor) found.gutterBackground = bgColor;
218+
const color = decls.get("color");
219+
if (color && colorIn(color))
220+
found.gutterForeground = colorIn(color) as string;
221+
} else if (/\.cm-activeLineGutter$/.test(sel)) {
222+
if (bgColor) found.activeLineGutter = bgColor;
223+
const color = decls.get("color");
224+
if (color && colorIn(color))
225+
found.gutterActiveForeground = colorIn(color) as string;
226+
} else if (/\.cm-cursor(?:-primary)?$/.test(sel)) {
227+
const border =
228+
decls.get("border-left-color") ?? decls.get("border-left");
229+
const color = border ? colorIn(border) : null;
230+
if (color && color !== "transparent") found.cursor = color;
231+
} else if (/\.cm-selectionBackground$/.test(sel) && bgColor) {
232+
// The focused rule is what a focused editor shows.
233+
if (/\.cm-focused\b/.test(sel)) focusedSelection = bgColor;
234+
else found.selection ??= bgColor;
235+
}
236+
}
237+
}
238+
if (focusedSelection) found.selection = focusedSelection;
239+
return found;
240+
}
241+
107242
/** Token colors from a theme config, for themes without a HighlightStyle. */
108243
function highlightFromConfig(config: ThemeConfig): TokenStyleSpec[] {
109244
const color = (key: string) =>
@@ -152,6 +287,15 @@ function themeClasses(config: ThemeConfig): CanvasThemeSpec["classes"] {
152287
* EditorView.theme stays in the state, where it styles the DOM UI (tooltips,
153288
* panels, autocomplete).
154289
*/
290+
/**
291+
* The canvas theme spec with the active line frame, which canvas-view
292+
* releases before it ignore (the line is then drawn without one).
293+
*/
294+
type FramedThemeSpec = CanvasThemeSpec & {
295+
activeLineBorder?: string;
296+
activeLineBorderWidth?: number;
297+
};
298+
155299
export function getCanvasTheme(
156300
themeId: string,
157301
seeThrough = false,
@@ -162,34 +306,47 @@ export function getCanvasTheme(
162306
const config = (theme?.config ||
163307
getThemeConfig(themeId) ||
164308
{}) as ThemeConfig;
309+
const extensions = getThemeExtensions(themeId, [oneDark]);
165310
const highlight =
166-
findHighlightStyle(getThemeExtensions(themeId, [oneDark])) ||
167-
highlightFromConfig(config);
311+
findHighlightStyle(extensions) || highlightFromConfig(config);
312+
// What the config leaves out, from the theme's own CSS rules.
313+
const rules = themeRuleColors(extensions);
168314
const background = config.background || "#282c34";
169315
const foreground = config.foreground || "#abb2bf";
170-
return {
316+
// The config's active line replaces the rules' (fill and frame).
317+
const framed = !config.activeLine && rules.activeLineBorder;
318+
const activeLine = config.activeLine ?? rules.activeLine;
319+
const spec: FramedThemeSpec = {
171320
dark: config.dark !== false,
172321
// With a picture behind the editor, the canvas is see-through. The
173322
// editor element keeps the theme's CSS background under the picture,
174323
// and sticky lines take it from there.
175324
background: seeThrough ? "transparent" : background,
176325
foreground,
177-
selection: config.selection,
178-
cursor: config.cursor,
179-
activeLine: seeThrough
180-
? translucentActiveLine(config.activeLine, foreground)
181-
: config.activeLine,
326+
selection: config.selection ?? rules.selection,
327+
cursor: config.cursor ?? rules.cursor,
328+
activeLine:
329+
seeThrough && !framed
330+
? translucentActiveLine(activeLine, foreground)
331+
: (activeLine ?? (framed ? "transparent" : undefined)),
332+
activeLineBorder: framed ? rules.activeLineBorder : undefined,
333+
activeLineBorderWidth: framed ? rules.activeLineBorderWidth : undefined,
182334
// Like the DOM themes, which give the active gutter line no background.
183-
activeLineGutter: seeThrough ? "transparent" : background,
184-
gutterForeground: config.lineNumber,
185-
gutterActiveForeground: config.lineNumberActive,
335+
activeLineGutter: seeThrough
336+
? "transparent"
337+
: (rules.activeLineGutter ?? background),
338+
gutterBackground: seeThrough ? undefined : rules.gutterBackground,
339+
gutterForeground: config.lineNumber ?? rules.gutterForeground,
340+
gutterActiveForeground:
341+
config.lineNumberActive ?? rules.gutterActiveForeground,
186342
// A line between the gutter and the code, only when the theme asks.
187343
gutterBorder: config.gutterBorder,
188344
// Acode draws its own (draggable) scrollbars over the editor.
189345
scrollbar: "transparent",
190346
highlight,
191347
classes: themeClasses(config),
192348
};
349+
return spec;
193350
}
194351

195352
/**
@@ -371,6 +528,25 @@ interface CanvasSyncState {
371528
}
372529

373530
const synced = new WeakMap<CanvasView, CanvasSyncState>();
531+
532+
const themeEntryIds = new WeakMap<object, number>();
533+
let nextThemeEntryId = 1;
534+
535+
/**
536+
* Which registered theme an id resolves to, for the sync key. A plugin
537+
* theme is registered after the editor is created: until then its id falls
538+
* back to One Dark's colors, and applying the same id again once it's
539+
* registered must rebuild the canvas theme (it used to be skipped, leaving
540+
* a cold-started canvas editor in One Dark's colors).
541+
*/
542+
function themeEntryKey(themeId: string): string {
543+
const entry =
544+
getThemeById(themeId) || getThemeById(String(themeId).replace(/-/g, "_"));
545+
if (!entry) return "0";
546+
let n = themeEntryIds.get(entry);
547+
if (!n) themeEntryIds.set(entry, (n = nextThemeEntryId++));
548+
return String(n);
549+
}
374550
// Acode replaces `setTheme` on editor instances with its own (taking a theme
375551
// id), so the view's method is called through the prototype.
376552
const setViewTheme = CanvasView.prototype.setTheme;
@@ -412,7 +588,7 @@ export function syncCanvasView(
412588
if (themeId != null) {
413589
const id = String(themeId);
414590
const seeThrough = hasPictureBehind(view);
415-
const key = `${id}\0${seeThrough}`;
591+
const key = `${id}\0${seeThrough}\0${themeEntryKey(id)}`;
416592
if (key !== state.theme) {
417593
state.theme = key;
418594
setViewTheme.call(view, getCanvasTheme(id, seeThrough));
@@ -432,6 +608,6 @@ export function markCanvasViewSynced(
432608
synced.set(view, {
433609
display: JSON.stringify(display),
434610
font: JSON.stringify(font),
435-
theme: `${themeId}\0false`,
611+
theme: `${themeId}\0false\0${themeEntryKey(String(themeId))}`,
436612
});
437613
}

0 commit comments

Comments
 (0)