Skip to content

Commit 2ce83c4

Browse files
committed
feat(editor): see-through canvas behind a plugin's background picture
When a plugin puts a picture behind the editor (Backdrop draws one on .cm-editor::before; the DOM editor's text has no background of its own), canvas views get a transparent background, so the picture shows through the text, gutter and sticky lines, with a translucent active line (the theme's, or the text color at 8%, like Backdrop's) and no active gutter background. Style sheets added, removed or rewritten are watched (at most once per frame), so turning the picture on or off applies live; new views are checked when created. Needs @acode.app/canvas-view 0.0.7.
1 parent 509a26a commit 2ce83c4

2 files changed

Lines changed: 102 additions & 8 deletions

File tree

‎src/cm/canvasOptions.ts‎

Lines changed: 86 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import {
33
CanvasView,
44
type CanvasViewConfig,
55
type FontSpec,
6+
parseColor,
67
type TokenStyleSpec,
78
} from "@acode.app/canvas-view";
89
import { HighlightStyle } from "@codemirror/language";
@@ -150,7 +151,10 @@ function themeClasses(config: ThemeConfig): CanvasThemeSpec["classes"] {
150151
* EditorView.theme stays in the state, where it styles the DOM UI (tooltips,
151152
* panels, autocomplete).
152153
*/
153-
export function getCanvasTheme(themeId: string): CanvasThemeSpec {
154+
export function getCanvasTheme(
155+
themeId: string,
156+
seeThrough = false,
157+
): CanvasThemeSpec {
154158
// Resolve ids like getThemeExtensions does ("one-dark" -> "one_dark").
155159
const theme =
156160
getThemeById(themeId) || getThemeById(String(themeId).replace(/-/g, "_"));
@@ -160,15 +164,22 @@ export function getCanvasTheme(themeId: string): CanvasThemeSpec {
160164
const highlight =
161165
findHighlightStyle(getThemeExtensions(themeId, [oneDark])) ||
162166
highlightFromConfig(config);
167+
const background = config.background || "#282c34";
168+
const foreground = config.foreground || "#abb2bf";
163169
return {
164170
dark: config.dark !== false,
165-
background: config.background || "#282c34",
166-
foreground: config.foreground || "#abb2bf",
171+
// With a picture behind the editor, the canvas is see-through. The
172+
// editor element keeps the theme's CSS background under the picture,
173+
// and sticky lines take it from there.
174+
background: seeThrough ? "transparent" : background,
175+
foreground,
167176
selection: config.selection,
168177
cursor: config.cursor,
169-
activeLine: config.activeLine,
178+
activeLine: seeThrough
179+
? translucentActiveLine(config.activeLine, foreground)
180+
: config.activeLine,
170181
// Like the DOM themes, which give the active gutter line no background.
171-
activeLineGutter: config.background,
182+
activeLineGutter: seeThrough ? "transparent" : background,
172183
gutterForeground: config.lineNumber,
173184
gutterActiveForeground: config.lineNumberActive,
174185
// Acode draws its own (draggable) scrollbars over the editor.
@@ -178,6 +189,71 @@ export function getCanvasTheme(themeId: string): CanvasThemeSpec {
178189
};
179190
}
180191

192+
/**
193+
* An active line that lets a picture behind the editor show: the theme's
194+
* own when it already does, otherwise the text color at 8% (what the
195+
* Backdrop plugin gives `.cm-activeLine` in the DOM editor).
196+
*/
197+
function translucentActiveLine(
198+
activeLine: string | undefined,
199+
foreground: string,
200+
): string {
201+
if (activeLine && parseColor(activeLine) >>> 24 < 255) return activeLine;
202+
const c = parseColor(foreground);
203+
return `rgba(${c & 255}, ${(c >>> 8) & 255}, ${(c >>> 16) & 255}, 0.08)`;
204+
}
205+
206+
/**
207+
* Whether something draws a picture behind the editor's text, as the
208+
* Backdrop plugin does with `.cm-editor::before` (the DOM editor's text has
209+
* no background of its own, so it shows). A canvas view then needs a
210+
* see-through background. Reads computed style: call it outside frames.
211+
*/
212+
export function hasPictureBehind(view: CanvasView): boolean {
213+
if (!view.dom.isConnected) return false;
214+
const before = getComputedStyle(view.dom, "::before");
215+
return (
216+
before.content !== "none" &&
217+
before.content !== "normal" &&
218+
before.display !== "none" &&
219+
before.backgroundImage !== "none" &&
220+
Number(before.opacity) > 0
221+
);
222+
}
223+
224+
/**
225+
* Call `onChange` (at most once per frame) when style sheets are added,
226+
* removed or rewritten, which is how plugins restyle the editor (Backdrop
227+
* keeps one `<style>` element up to date). Returns a function that stops.
228+
*/
229+
export function watchEditorStyles(onChange: () => void): () => void {
230+
let frame = 0;
231+
const isStyle = (node: Node | null) =>
232+
node instanceof HTMLStyleElement || node instanceof HTMLLinkElement;
233+
const observer = new MutationObserver((records) => {
234+
const relevant = records.some(
235+
(r) =>
236+
isStyle(r.target) ||
237+
isStyle(r.target.parentNode) ||
238+
[...r.addedNodes, ...r.removedNodes].some(isStyle),
239+
);
240+
if (!relevant || frame) return;
241+
frame = requestAnimationFrame(() => {
242+
frame = 0;
243+
onChange();
244+
});
245+
});
246+
const options = { childList: true, subtree: true, characterData: true };
247+
observer.observe(document.head, options);
248+
// Style elements put straight into <body> (not its whole subtree: the
249+
// editor's own DOM changes all the time).
250+
observer.observe(document.body, { childList: true });
251+
return () => {
252+
observer.disconnect();
253+
if (frame) cancelAnimationFrame(frame);
254+
};
255+
}
256+
181257
/** A CSS font size ("12px", "1rem", "10pt"...) in CSS pixels. */
182258
export function fontSizeToPx(value: unknown): number {
183259
const match = /^([\d.]+)\s*([a-z]*)$/i.exec(String(value ?? "").trim());
@@ -326,10 +402,12 @@ export function syncCanvasView(
326402
}
327403
}
328404
if (themeId != null) {
329-
const key = String(themeId);
405+
const id = String(themeId);
406+
const seeThrough = hasPictureBehind(view);
407+
const key = `${id}\0${seeThrough}`;
330408
if (key !== state.theme) {
331409
state.theme = key;
332-
setViewTheme.call(view, getCanvasTheme(key));
410+
setViewTheme.call(view, getCanvasTheme(id, seeThrough));
333411
}
334412
}
335413
}
@@ -346,6 +424,6 @@ export function markCanvasViewSynced(
346424
synced.set(view, {
347425
display: JSON.stringify(display),
348426
font: JSON.stringify(font),
349-
theme: String(themeId),
427+
theme: `${themeId}\0false`,
350428
});
351429
}

‎src/lib/editorManager.js‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ import {
3636
getCanvasTheme,
3737
markCanvasViewSynced,
3838
syncCanvasView,
39+
watchEditorStyles,
3940
} from "cm/canvasOptions";
4041
import {
4142
setKeyBindings as applyKeyBindings,
@@ -1448,6 +1449,18 @@ async function EditorManager($header, $body) {
14481449
}
14491450
}
14501451

1452+
/**
1453+
* A plugin's style sheet may put a picture behind the editor (Backdrop),
1454+
* which needs a see-through canvas, or take it away: check the theme of
1455+
* every canvas view again.
1456+
*/
1457+
function syncCanvasThemes() {
1458+
const themeId = appSettings.value.editorTheme || "one_dark";
1459+
for (const pane of panes) {
1460+
if (isCanvasView(pane.editor)) syncCanvasView(pane.editor, { themeId });
1461+
}
1462+
}
1463+
14511464
/**
14521465
* Taps on a canvas view's line numbers select the line, like the DOM
14531466
* editor's line number gutter. Its fold markers sit in a narrow column
@@ -1495,6 +1508,8 @@ async function EditorManager($header, $body) {
14951508
},
14961509
});
14971510
markCanvasViewSynced(view, { display, font, themeId });
1511+
// A picture behind the editor already (it's in the document now).
1512+
syncCanvasView(view, { themeId });
14981513
return view;
14991514
} catch (error) {
15001515
// Use the DOM editor for the rest of the session, with the
@@ -3820,6 +3835,7 @@ async function EditorManager($header, $body) {
38203835
appSettings.on("update:stickyScrollMaxLines", syncAllCanvasViews);
38213836
appSettings.on("update:cursorBlinkRate", syncAllCanvasViews);
38223837
appSettings.on("update:canvasGutterMarkers", syncAllCanvasViews);
3838+
if (canvasRenderer) watchEditorStyles(syncCanvasThemes);
38233839

38243840
// Keep file.session and cache in sync on every edit
38253841
function getDocSyncListener() {

0 commit comments

Comments
 (0)