Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
chore(skills): document CKEditor major upgrades and compare stylesheets across versions
Elian Doran3f702b1e5fa5
diff --git a/.claude/skills/ckeditor5-plugin-development/SKILL.md b/.claude/skills/ckeditor5-plugin-development/SKILL.mdindex eaee99e459..a0bb989257 100644--- a/.claude/skills/ckeditor5-plugin-development/SKILL.md+++ b/.claude/skills/ckeditor5-plugin-development/SKILL.md@@ -11,9 +11,12 @@ description: >-(block/inline, toWidget, nested editables), keystrokes, localization (t()),registering a plugin into plugins.ts / the editor classes / toolbar.ts, persisting a`data-trilium-*` attribute through the model→view→data→markdown→share pipeline, or- adding a new plugin folder under src/plugins/. Covers the architecture,- idiomatic patterns, Trilium packaging/registration, code-style conventions,- and a review checklist.+ adding a new plugin folder under src/plugins/, or upgrading `ckeditor5` to a+ new major version (Renovate's major-ckeditor-monorepo branch, broken editor+ styling after a bump, `--ck-*` variables that stopped applying). Covers the+ architecture, idiomatic patterns, Trilium packaging/registration, code-style+ conventions, a review checklist, and ck_css.mjs, which compares CKEditor's+ stylesheets between two versions under Trilium's own CSS.---# CKEditor 5 plugin development (Trilium monorepo)@@ -256,6 +259,17 @@ converters instead of `attributeToElement`; see `references/widgets.md`.only when the editor is *built*, so do a **full page reload** (or close/reopen the note) to get afresh editor instance that picks up your change — otherwise you're testing the old code.+## Upgrading CKEditor++A major bump breaks more than APIs: CKEditor 49 replaced its flat `--ck-*` variables with design+tokens resolved at `:root`, which silently detached many of our scoped overrides (dropdown font+sizes, focus rings, radii, the color picker layout). Before calling an upgrade done, run+`node .claude/skills/ckeditor5-plugin-development/ck_css.mjs audit`, then stage the previous version+and diff it (`stage <version>`, `run all`, `clean`) — the harnesses render the editor UI and every+content element in Chromium under both stylesheets with Trilium's CSS loaded, and print what changed.+The procedure, the token model, the traps and the v49 mapping are in+`references/upgrading-ckeditor.md`.+## Reference mapLoad the focused reference for the task at hand:@@ -268,7 +282,8 @@ Load the focused reference for the task at hand:| `references/ui-and-localization.md` | Views & templates, component catalog (buttons, inputs, dropdowns, dialogs/modals, balloons, toolbars), icons, `componentFactory`, focus/keystroke management, and `t()` localization. || `references/widgets.md` | Block & inline widgets: `toWidget`/`toWidgetEditable`, nested editables, `insertObject`, widget toolbars, view↔model position mapping, custom properties, and external/async-rendered widgets (UI-element render callbacks, re-render on change, stale-render guard, lazy-load). || `references/conventions.md` | Trilium conventions: imports from `ckeditor5`/`@triliumnext` + required file extensions, per-package license/headers (not uniform), `@triliumnext` scope + `workspace:*`, per-package tsconfig, `?raw` icons, localization via `editor.t()` message ids, `declare module 'ckeditor5'` augmentation, plus the upstream naming/CSS/BEM/JSDoc/TypeScript rules inherited via `eslint-config-ckeditor5`. For writing idiomatic code and reviewing. |-| `references/tooling-and-packaging.md` | Trilium packaging & wiring: the `@triliumnext/ckeditor5-<feature>` package layout, `workspace:*` deps, `main: src/index.ts` (no per-package dist), tsconfig/eslint/stylelint setup, the full registration flow (`plugins.ts` arrays → editor classes `builtinPlugins` → `toolbar.ts`), the three editor classes, the Vite build, how `apps/client` creates the editor (config, watchdog, lazy premium), the Inspector, and how to read CKEditor's own source (via bundle sourcemaps) and trace its runtime decisions. |+| `references/upgrading-ckeditor.md` | Major-version upgrades: the procedure (changelog, CI cascades, local suite, CSS audit, version diff), CKEditor 49's token layers and why scoped legacy overrides stopped reaching components, the legacy→v49 variable mapping, where we now set component tokens, traps (`--x: inherit`, nested selectors), where CKEditor's CSS reaches (editor, print, share, exports), and `ck_css.mjs` with its `content`/`ui` harnesses. |+| `references/tooling-and-packaging.md` | Trilium packaging & wiring: the `@triliumnext/ckeditor5-<feature>` package layout, `workspace:*` deps, `main: src/index.ts` (no per-package dist), tsconfig/eslint/stylelint setup, the full registration flow (`plugins.ts` arrays → editor classes `builtinPlugins` → `toolbar.ts`), the three editor classes, the Vite build, how `apps/client` creates the editor (config, rebuilds, error reporting), the Inspector, and how to read CKEditor's own source (via bundle sourcemaps) and trace its runtime decisions. || `references/persisted-attributes.md` | Persisting a `data-trilium-*` attribute end to end: schema → both conversion directions → the **deliberate** markdown export/import decision (collapsed is DROPPED, task-state is KEPT) → editing-view-only CSS so read-only and share rendering stay correct. Read it before storing plugin state in the saved note content. || `references/review-checklist.md` | A structured checklist for reviewing an existing plugin (architecture, schema, conversion, commands, UI, a11y, conventions). || `references/recipes.md` | Task-oriented how-tos: insert content, find/iterate nodes, custom observers, place caret, extend other plugins' UI, etc. |diff --git a/.claude/skills/ckeditor5-plugin-development/ck_css.mjs b/.claude/skills/ckeditor5-plugin-development/ck_css.mjsnew file mode 100644index 0000000000..8ea7c65e97--- /dev/null+++ b/.claude/skills/ckeditor5-plugin-development/ck_css.mjs@@ -0,0 +1,145 @@+#!/usr/bin/env node+/**+ * Compares CKEditor 5's stylesheets between two versions and audits Trilium's CSS against the+ * installed one. See references/upgrading-ckeditor.md.+ *+ * node ck_css.mjs fetch <version> download that version's dist CSS (cached)+ * node ck_css.mjs stage <old-version> copy it and the harnesses into packages/ckeditor5/src+ * node ck_css.mjs run [content|ui|all] run the staged harnesses, print their findings+ * node ck_css.mjs clean remove everything `stage` wrote+ * node ck_css.mjs audit our reads of --ck-* variables nothing declares+ * node ck_css.mjs readers <css> <name...> selectors that read var(--ck-<name>)+ * node ck_css.mjs props <css> <prop> [regex] selectors that set <prop>, optionally filtered+ *+ * <css> is `new` (the installed ckeditor5.css), a version number (fetched first), or a path.+ */+import { execFileSync, execSync } from "node:child_process";+import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync } from "node:fs";+import { tmpdir } from "node:os";+import { dirname, join, relative, resolve } from "node:path";+import { fileURLToPath } from "node:url";++const SKILL_DIR = dirname(fileURLToPath(import.meta.url));+const REPO = resolve(SKILL_DIR, "../../..");+const PKG_SRC = join(REPO, "packages/ckeditor5/src");+const CACHE = join(tmpdir(), "trilium-ck-css");+const STAGED_PREFIX = "zz_ckcss_";+const OUR_CSS_DIRS = [ "apps/client/src", "packages/ckeditor5/src", "packages/share-theme/src" ];++const [ command, ...args ] = process.argv.slice(2);+const commands = { fetch, stage, run, clean, audit, readers, props };+if (!commands[command]) {+ console.log(readFileSync(fileURLToPath(import.meta.url), "utf8").match(/\/\*\*([\s\S]*?)\*\//)[1]+ .replace(/^ \* ?/gm, ""));+ process.exit(command ? 1 : 0);+}+commands[command](...args);++function fetch(version) {+ if (!version) throw new Error("fetch <version>");+ const dir = join(CACHE, version);+ const full = join(dir, "package/dist/ckeditor5.css");+ if (!existsSync(full)) {+ mkdirSync(dir, { recursive: true });+ execSync(`npm pack ckeditor5@${version} --silent`, { cwd: dir, stdio: "ignore" });+ const tarball = readdirSync(dir).find((f) => f.endsWith(".tgz"));+ execFileSync("tar", [ "-xzf", tarball, "package/dist/ckeditor5.css", "package/dist/ckeditor5-content.css" ], { cwd: dir });+ }+ const content = join(dir, "package/dist/ckeditor5-content.css");+ if (command === "fetch") console.log(`${full}\n${content}`);+ return { full, content };+}++function stage(version) {+ const { full, content } = fetch(version);+ copyFileSync(full, join(PKG_SRC, `${STAGED_PREFIX}old.css`));+ copyFileSync(content, join(PKG_SRC, `${STAGED_PREFIX}old_content.css`));+ for (const harness of readdirSync(join(SKILL_DIR, "harness"))) {+ copyFileSync(join(SKILL_DIR, "harness", harness), join(PKG_SRC, `${STAGED_PREFIX}${harness}`));+ }+ console.log(`Staged ckeditor5@${version} as the old side in ${relative(REPO, PKG_SRC)}; run, then clean.`);+}++function run(which = "all") {+ const names = which === "all" ? [ "content", "ui" ] : [ which ];+ for (const name of names) {+ const spec = `src/${STAGED_PREFIX}${name}.spec.ts`;+ if (!existsSync(join(REPO, "packages/ckeditor5", spec))) throw new Error(`${spec} is not staged`);+ let output;+ try {+ output = execSync(`pnpm --filter @triliumnext/ckeditor5 exec vitest run ${spec}`,+ { cwd: REPO, encoding: "utf8", stdio: [ "ignore", "pipe", "pipe" ] });+ } catch (e) {+ output = `${e.stdout}\n${e.stderr}`;+ }+ const lines = output.replace(/\x1b\[[0-9;]*m/g, "").split("\n");+ const findings = lines.filter((l) => /^(DIFF|SAME|RULE) /.test(l));+ const failures = lines.filter((l) => /FAIL|Error:|×/.test(l) && !/map file|ENOENT/.test(l));+ console.log(`=== ${name}`);+ console.log(findings.length ? findings.join("\n") : "(no findings)");+ if (failures.length) console.log(`--- failures\n${failures.join("\n")}`);+ }+}++function clean() {+ for (const f of readdirSync(PKG_SRC).filter((f) => f.startsWith(STAGED_PREFIX))) rmSync(join(PKG_SRC, f));+ console.log("Removed the staged files.");+}++/** Our `var(--ck-x)` reads with no fallback, where neither CKEditor nor our CSS declares `--ck-x`. */+function audit() {+ const installed = readFileSync(join(REPO, "node_modules/ckeditor5/dist/ckeditor5.css"), "utf8");+ const declared = new Set(installed.match(/--ck-[\w-]+(?=\s*:)/g));+ const ours = OUR_CSS_DIRS.flatMap((dir) => walk(join(REPO, dir)).filter((f) => f.endsWith(".css")));+ for (const file of ours) for (const name of readFileSync(file, "utf8").match(/--ck-[\w-]+(?=\s*:)/g) ?? []) declared.add(name);+ let count = 0;+ for (const file of ours) {+ for (const [ index, line ] of readFileSync(file, "utf8").split("\n").entries()) {+ for (const [ , name ] of line.matchAll(/var\((--ck-[\w-]+)\)/g)) {+ if (declared.has(name)) continue;+ console.log(`${relative(REPO, file)}:${index + 1} ${name}`);+ count++;+ }+ }+ }+ console.log(count ? `\n${count} read(s) of undeclared variables.` : "No reads of undeclared --ck-* variables.");+ console.log("A name also set by our CSS counts as declared: check that its scope covers the reader.");+}++function readers(css, ...names) {+ for (const { selector, line } of declarations(css)) {+ for (const name of names) {+ if (line.includes(`var(--ck-${name})`) || line.includes(`var(--ck-${name},`)) console.log(`--ck-${name}\t${selector}\t${line}`);+ }+ }+}++function props(css, prop, filter) {+ const regex = filter ? new RegExp(filter) : null;+ for (const { selector, line } of declarations(css)) {+ if (line.startsWith(`${prop}:`) && (!regex || regex.test(selector))) console.log(`${selector}\t${line}`);+ }+}++/** Every declaration of a multi-line, natively nested stylesheet, with its resolved selector chain. */+function declarations(css) {+ const file = css === "new" ? join(REPO, "node_modules/ckeditor5/dist/ckeditor5.css")+ : /^\d+\.\d+\.\d+$/.test(css) ? fetch(css).full : resolve(css);+ const stack = [];+ const result = [];+ for (const raw of readFileSync(file, "utf8").split("\n")) {+ const line = raw.trim();+ if (line.endsWith("{")) stack.push(line.slice(0, -1).trim());+ else if (line.includes(":") && !line.startsWith("}")) result.push({ selector: `[${stack.join(" > ")}]`, line });+ for (const c of line) if (c === "}") stack.pop();+ }+ return result;+}++function walk(dir) {+ return readdirSync(dir).flatMap((entry) => {+ const path = join(dir, entry);+ if (entry === "node_modules" || entry === "dist") return [];+ return statSync(path).isDirectory() ? walk(path) : [ path ];+ });+}diff --git a/.claude/skills/ckeditor5-plugin-development/harness/content.spec.ts b/.claude/skills/ckeditor5-plugin-development/harness/content.spec.tsnew file mode 100644index 0000000000..b0bf41ecc5--- /dev/null+++ b/.claude/skills/ckeditor5-plugin-development/harness/content.spec.ts@@ -0,0 +1,63 @@+/**+ * Renders one note holding every kind of content element under the old and the new CKEditor+ * stylesheet, in each context of `CONTEXTS`, and prints what changed.+ */+import { it } from "vitest";++import { computed, CONTEXTS, mountStyles, probe, report, type Side } from "./zz_ckcss_kit";++const IMAGE = "data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='40' height='20'/>";+const FIXTURE = `+<h2 data-k="h2">Heading 2</h2>+<h3 data-k="h3">Heading 3</h3>+<p data-k="p">Text <code data-k="code-inline">inline</code> <mark class="marker-yellow" data-k="marker">mark</mark>+ <a href="#x" data-k="link">link</a> <span class="text-tiny" data-k="text-tiny">t</span><span class="text-huge" data-k="text-huge">h</span>+ <span class="mention" data-k="mention">@m</span> <kbd data-k="kbd">Ctrl</kbd></p>+<blockquote data-k="blockquote"><p data-k="blockquote-p">Quote</p></blockquote>+<pre data-k="pre"><code class="language-plaintext" data-k="pre-code">code</code></pre>+<hr data-k="hr">+<figure class="table" data-k="figure-table"><table data-k="table"><thead><tr><th data-k="th">h</th></tr></thead>+ <tbody><tr><td data-k="td">a</td></tr></tbody></table><figcaption data-k="table-caption">Table caption</figcaption></figure>+<figure class="image" data-k="figure-image"><img src="${IMAGE}" data-k="img"><figcaption data-k="image-caption">Image caption</figcaption></figure>+<ul class="todo-list" data-k="todo-list"><li><label class="todo-list__label"><input type="checkbox" disabled checked data-k="todo-checkbox">+ <span class="todo-list__label__description" data-k="todo-text">todo</span></label></li></ul>+<ul data-k="ul"><li data-k="ul-li">bullet</li></ul>+<ol data-k="ol"><li data-k="ol-li">number</li></ol>+<div class="page-break" data-k="page-break"><span class="page-break__label" data-k="page-break-label">Page break</span></div>+<aside class="admonition note" data-k="admonition"><p>adm</p></aside>+`;+const PROPS = [ "color", "background-color", "border-top", "border-right", "border-bottom", "border-left", "border-radius",+ "padding", "margin", "font-size", "font-family", "font-style", "font-weight", "line-height", "height", "opacity",+ "box-shadow", "list-style-type", "text-decoration-line" ];+/** The editable a note renders in, in the app; elsewhere content sits in a plain `.ck-content`. */+const APP_WRAPPER = "note-detail-editable-text-editor ck ck-content ck-editor__editable ck-editor__editable_inline ck-rounded-corners ck-blurred";+/** Elements whose rules to list in the app context, by `data-k` (`editable` is the wrapper). */+const PROBE: Record<string, string[]> = {};++function measure(context: string, side: Side) {+ const unmount = mountStyles(CONTEXTS[context](side));+ const host = document.body.appendChild(document.createElement("div"));+ host.style.width = "700px";+ const wrapper = host.appendChild(document.createElement("div"));+ wrapper.className = context.startsWith("app") ? APP_WRAPPER : "ck-content";+ if (context === "share") wrapper.id = "content";+ wrapper.dataset.k = "editable";+ wrapper.innerHTML = FIXTURE;+ const elements = [ wrapper, ...wrapper.querySelectorAll<HTMLElement>("[data-k]") ];+ const result = Object.fromEntries(elements.map((e) => [ e.dataset.k as string, computed(e, PROPS) ]));+ if (context === "app") {+ for (const [ key, props ] of Object.entries(PROBE)) {+ const element = elements.find((e) => e.dataset.k === key);+ if (element) probe(`${side} ${key}`, element, props);+ }+ }+ host.remove();+ unmount();+ return result;+}++for (const context of Object.keys(CONTEXTS)) {+ it(`content in ${context}`, () => {+ report(context, measure(context, "old"), measure(context, "new"));+ });+}diff --git a/.claude/skills/ckeditor5-plugin-development/harness/kit.ts b/.claude/skills/ckeditor5-plugin-development/harness/kit.tsnew file mode 100644index 0000000000..63e92ee612--- /dev/null+++ b/.claude/skills/ckeditor5-plugin-development/harness/kit.ts@@ -0,0 +1,112 @@+/**+ * Shared by the staged CKEditor CSS comparison harnesses (see `ck_css.mjs stage`). Both sides load+ * today's Trilium stylesheets; only CKEditor's own stylesheet differs, so every difference is one+ * the upgrade causes.+ */+import newFull from "ckeditor5/ckeditor5.css?inline";+import newContent from "ckeditor5/ckeditor5-content.css?inline";++import bootstrap from "../../../node_modules/bootstrap/dist/css/bootstrap.min.css?inline";+import ckTheme from "../../../apps/client/src/stylesheets/ckeditor-theme.css?inline";+import style from "../../../apps/client/src/stylesheets/style.css?inline";+import themeLight from "../../../apps/client/src/stylesheets/theme-light.css?inline";+import themeNextDark from "../../../apps/client/src/stylesheets/theme-next-dark.css?inline";+import themeNextLight from "../../../apps/client/src/stylesheets/theme-next-light.css?inline";+import shareBase from "../../share-theme/src/base.css?inline";+import shareAdaptive from "../../share-theme/src/content/adaptive_colors.css?inline";+import shareContent from "../../share-theme/src/content/content.css?inline";+import shareFootnotes from "../../share-theme/src/content/footnotes.css?inline";+import shareTasks from "../../share-theme/src/content/task_states.css?inline";+import admonitions from "./theme/admonitions.css?inline";+import blockquote from "./theme/blockquote.css?inline";+import ckContentRaw from "./theme/ck-content.css?raw";+import codeBlockToolbar from "./theme/code_block_toolbar.css?inline";+import contentColors from "./theme/content_colors.css?inline";+import linkEmbedForm from "./theme/link_embed_form.css?inline";+import todoLists from "./theme/todo_lists.css?inline";+import oldFull from "./zz_ckcss_old.css?inline";+import oldContent from "./zz_ckcss_old_content.css?inline";++export type Side = "old" | "new";++/** What `src/index.ts` imports after `ckeditor5/ckeditor5.css`. Keep in step with it. */+const PACKAGE_LAYER = [ blockquote, contentColors, codeBlockToolbar, linkEmbedForm ];+/** `ck-content.css` without its `@import`s, which the share and export contexts load explicitly. */+const CK_CONTENT_REST = ckContentRaw.replace(/@import[^;]*;/g, "");++/** The stylesheets of each place CKEditor's CSS reaches, in the order the real page loads them. */+export const CONTEXTS: Record<string, (side: Side) => string[]> = {+ /** The client, in the order `apps/client/src/index.ts` appends them, light Next theme. */+ app: (side) => [ full(side), ...PACKAGE_LAYER, bootstrap, ckTheme, themeLight, themeNextLight, style ],+ "app-dark": (side) => [ full(side), ...PACKAGE_LAYER, bootstrap, ckTheme, themeLight, themeNextDark, style ],+ /** A shared page: `ck-content.css` and the share theme's content stylesheets. */+ share: (side) => [ content(side), contentColors, CK_CONTENT_REST, admonitions, todoLists,+ shareBase, shareContent, shareFootnotes, shareTasks, shareAdaptive ],+ /** An HTML export: what `apps/server/src/services/export/zip/factory.ts` concatenates. */+ export: (side) => [ content(side), contentColors ]+};++function full(side: Side) { return side === "old" ? oldFull : newFull; }+function content(side: Side) { return side === "old" ? oldContent : newContent; }++/** Mounts stylesheets (transitions off, so computed values are final) and returns their remover. */+export function mountStyles(css: string[]) {+ const elements = [ ...css, "* { transition: none !important; }" ].map((text) => {+ const element = document.createElement("style");+ element.textContent = text;+ document.head.appendChild(element);+ return element;+ });+ return () => { for (const element of elements) element.remove(); };+}++export function computed(element: Element, props: string[]) {+ const cs = getComputedStyle(element);+ return Object.fromEntries(props.map((p) => [ p, cs.getPropertyValue(p) ]));+}++/** Prints `DIFF <context> | <key> | <prop>: <old> → <new>` for every value that changed. */+export function report(context: string, before: Record<string, Record<string, string>>, after: Record<string, Record<string, string>>) {+ let changes = 0;+ for (const key of Object.keys(before)) {+ for (const prop of Object.keys(before[key])) {+ if (before[key][prop] === after[key]?.[prop]) continue;+ console.log(`DIFF ${context} | ${key} | ${prop}: ${before[key][prop]} → ${after[key]?.[prop]}`);+ changes++;+ }+ }+ if (!changes) console.log(`SAME ${context} | ${Object.keys(before).length} element(s) unchanged`);+}++/**+ * Prints `RULE` for every rule that matches `element` and sets one of `props`, with nested+ * selectors resolved against their parents. Answers "which rule produced this value".+ */+export function probe(label: string, element: Element, props: string[]) {+ for (const [ index, sheet ] of [ ...document.styleSheets ].entries()) {+ const walk = (rules: CSSRuleList, parentSelector: string | null) => {+ for (const rule of [ ...rules ]) {+ if (rule instanceof CSSStyleRule) {+ const selector = resolveNested(rule.selectorText, parentSelector);+ let matches = false;+ try { matches = element.matches(selector); } catch { /* an unsupported selector */ }+ const set = props.filter((p) => rule.style.getPropertyValue(p))+ .map((p) => `${p}: ${rule.style.getPropertyValue(p)}`);+ if (matches && set.length) console.log(`RULE ${label} | sheet ${index} | ${selector} | ${set.join("; ")}`);+ if (rule.cssRules.length) walk(rule.cssRules, selector);+ } else if ("cssRules" in rule) {+ walk((rule as CSSGroupingRule).cssRules, parentSelector);+ }+ }+ };+ walk(sheet.cssRules, null);+ }+}++function resolveNested(selector: string, parent: string | null) {+ if (!parent) return selector;+ return selector.split(",").map((part) => {+ const trimmed = part.trim();+ return trimmed.includes("&") ? trimmed.replaceAll("&", `:is(${parent})`) : `:is(${parent}) ${trimmed}`;+ }).join(", ");+}diff --git a/.claude/skills/ckeditor5-plugin-development/harness/ui.spec.ts b/.claude/skills/ckeditor5-plugin-development/harness/ui.spec.tsnew file mode 100644index 0000000000..b2990eb9f7--- /dev/null+++ b/.claude/skills/ckeditor5-plugin-development/harness/ui.spec.ts@@ -0,0 +1,116 @@+/**+ * Builds a real editor with a toolbar under the old and the new CKEditor stylesheet, in the app's+ * light and dark themes, and prints what changed in its controls: size, radius, padding, font,+ * icon size and focus ring.+ */+import {+ BalloonPanelView, Bold, ButtonView, ClassicEditor, Essentials, FontColor, Heading, InputTextView, Locale, Paragraph,+ Table, TableToolbar+} from "ckeditor5";+import { it } from "vitest";++import { computed, CONTEXTS, mountStyles, probe, report, type Side } from "./zz_ckcss_kit";++const PROPS = [ "width", "height", "padding", "margin", "border-radius", "font-size", "line-height", "column-gap", "row-gap" ];+const FOCUS_PROPS = [ "border-top-color", "border-top-width", "box-shadow", "outline-style", "outline-color" ];+/** The swatches `apps/client/.../text/color_palette.ts` configures: four greys, then the note colors. */+const COLORS = [ "#000000", "#555555", "#aaaaaa", "#ffffff", "#e64d4d", "#e6994d", "#e5e64d", "#99e64d", "#4de64d",+ "#4de699", "#4de5e6", "#4d99e6", "#4d4de6", "#994de6", "#e64db3" ].map((color) => ({ color, label: color }));+/** Keys of measured elements whose rules to list, with the properties to look for. */+const PROBE: Record<string, string[]> = {};++async function measure(context: string, side: Side) {+ const unmount = mountStyles(CONTEXTS[context](side));+ const result: Record<string, Record<string, string>> = {};+ const elements: Record<string, HTMLElement> = {};+ const record = (key: string, element: Element | null | undefined, focus = false) => {+ if (!element) { result[key] = { missing: "true" }; return; }+ elements[key] = element as HTMLElement;+ result[key] = computed(element, PROPS);+ const icon = element.querySelector(":scope > .ck-icon, :scope > .ck-button__icon, .ck-icon");+ if (icon) {+ const { width, height } = icon.getBoundingClientRect();+ result[key]["icon"] = `${width.toFixed(1)}x${height.toFixed(1)}`;+ }+ if (focus) {+ (element as HTMLElement).focus();+ Object.assign(result[key], Object.fromEntries(Object.entries(computed(element, FOCUS_PROPS))+ .map(([ p, v ]) => [ `:focus ${p}`, v ])));+ }+ };++ const host = document.body.appendChild(document.createElement("div"));+ const editor = await ClassicEditor.create(host, {+ licenseKey: "GPL",+ plugins: [ Essentials, Paragraph, Bold, Heading, FontColor, Table, TableToolbar ],+ toolbar: [ "bold", "heading", "fontColor", "insertTable" ],+ fontColor: { colors: COLORS, columns: 4 }+ });+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ const items = editor.ui.view.toolbar.items as any;+ record("toolbar button", items.get(0).element, true);++ const heading = items.get(1);+ record("heading dropdown button", heading.buttonView.element);+ heading.isOpen = true;+ record("heading panel", heading.panelView.element);+ record("heading item", heading.panelView.element.querySelector(".ck-list__item .ck-button"), true);+ record("heading item label", heading.panelView.element.querySelector(".ck-list__item .ck-button__label"));+ heading.isOpen = false;++ const color = items.get(2);+ color.isOpen = true;+ const panel = color.panelView.element as HTMLElement;+ record("color panel", panel);+ record("color grid", panel.querySelector(".ck-color-grid"));+ record("color tile", panel.querySelector(".ck-color-grid__tile"), true);+ record("color remove button", panel.querySelector(".ck-color-selector__remove-color"), true);+ record("color picker button", panel.querySelector(".ck-color-selector__color-picker"), true);+ color.isOpen = false;++ const table = items.get(3);+ table.isOpen = true;+ record("insert table panel", table.panelView.element);+ record("insert table box", table.panelView.element.querySelector(".ck-insert-table-dropdown-grid-box"));+ table.isOpen = false;++ const locale = new Locale();+ for (const [ name, className ] of [ [ "dialog", "ck ck-reset_all ck-dialog" ], [ "floating", "ck ck-reset_all ck-body-wrapper" ] ]) {+ const wrapper = document.body.appendChild(document.createElement("div"));+ wrapper.className = className;+ const button = new ButtonView(locale);+ button.set({ label: "Button", withText: true });+ button.render();+ const input = new InputTextView(locale);+ input.render();+ if (name === "floating") {+ const balloon = new BalloonPanelView(locale);+ balloon.render();+ balloon.isVisible = true;+ balloon.content.add(button);+ balloon.content.add(input);+ wrapper.appendChild(balloon.element as HTMLElement);+ record("balloon", balloon.element);+ } else {+ wrapper.append(button.element as HTMLElement, input.element as HTMLElement);+ record("dialog", wrapper);+ }+ record(`${name} button`, button.element, true);+ record(`${name} input`, input.element, true);+ }++ for (const [ key, props ] of Object.entries(PROBE)) {+ if (elements[key]) probe(`${context} ${side} ${key}`, elements[key], props);+ }+ await editor.destroy();+ host.remove();+ for (const wrapper of document.querySelectorAll(".ck-dialog, .ck-body-wrapper")) wrapper.remove();+ unmount();+ return result;+}++for (const context of [ "app", "app-dark" ]) {+ it(`editor UI in ${context}`, async () => {+ report(context, await measure(context, "old"), await measure(context, "new"));+ });+}diff --git a/.claude/skills/ckeditor5-plugin-development/references/recipes.md b/.claude/skills/ckeditor5-plugin-development/references/recipes.mdindex 47c56d55f5..7214dceced 100644--- a/.claude/skills/ckeditor5-plugin-development/references/recipes.md+++ b/.claude/skills/ckeditor5-plugin-development/references/recipes.md@@ -9,8 +9,8 @@ content of a single text note, so these recipes operate over that note's model rInside plugin code you already have it: `this.editor` (in a `Plugin`/`Command` subclass) or the`editor` argument of a function plugin / converter / `componentFactory` callback. You don't fetch-it from the DOM — in Trilium the editor is created and owned by the React watchdog component-(`apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsx`), not by plugin code.+it from the DOM — in Trilium the editor is created and owned by the Preact component+`apps/client/src/widgets/type_widgets/text/CKEditor.tsx`, not by plugin code.```jsclass MyPlugin extends Plugin {diff --git a/.claude/skills/ckeditor5-plugin-development/references/tooling-and-packaging.md b/.claude/skills/ckeditor5-plugin-development/references/tooling-and-packaging.mdindex 1d6f95354e..4c36ba4315 100644--- a/.claude/skills/ckeditor5-plugin-development/references/tooling-and-packaging.md+++ b/.claude/skills/ckeditor5-plugin-development/references/tooling-and-packaging.md@@ -17,7 +17,7 @@ Separate workspace packages are no longer the pattern (see "Where a new plugin gNothing sits outside it any more: `mathlive` and the other former plugin-package dependenciesare declared on the aggregate itself.- `apps/client/src/widgets/type_widgets/text/` — the rich-text note widget that instantiates the- editor (`config.ts`, `CKEditorWithWatchdog.tsx`, `toolbar.ts`).+ editor (`config.ts`, `CKEditor.tsx`, `toolbar.ts`).The library's own packages (basic-styles, link, image, engine, ui, core, widget, typing, …) are**upstream** and not present in this repo — they ship inside the `ckeditor5` npm aggregate.@@ -156,9 +156,15 @@ keep in sync. `src/index.ts` imports `ckeditor5/ckeditor5.css` and the Trilium t- `config.ts` builds the `EditorConfig` (toolbar from `toolbar.ts`, language, feature config such as`syntaxHighlighting`, `moveBlockUp/Down`, the `mention.hostedFeeds` whose lists`mention_list_view.tsx` draws, etc.).-- `CKEditorWithWatchdog.tsx` wraps editor creation in the **custom `EditorWatchdog`**- (`packages/ckeditor5/src/custom_watchdog.ts`, re-exported from `@triliumnext/ckeditor5`), which- recreates the editor on a crash while preserving data.+- `CKEditor.tsx` creates the editor, rebuilds it when an option it bakes in at creation changes+ (content language, transformations, HTML support, …), and serializes builds on one container.+ CKEditor 49 removed the Watchdog, so nothing restarts the editor after an unhandled error: the+ editor keeps running, and `onTextEditorError(editor, callback)` from `@triliumnext/ckeditor5`+ (`src/editor_errors.ts`, over CKEditor's page-wide `onEditorError()`) reports the errors of one+ editor, minus the known harmless ones in its `IGNORED_ERRORS`. `EditableText.tsx` turns each into+ the `editor-error` toast with a copyable details dialog (`reportEditorError()`). A new ignored+ error goes into `IGNORED_ERRORS` — it matches on substrings of the message, which for a native+ error is CKEditor's `unexpected-error … Original error: TypeError: …` wrapping.- The client picks `ClassicEditor` (fixed toolbar) or `PopupEditor` (floating) per the note'sediting mode; `AttributeEditor` is used elsewhere for attribute/relation inputs.@@ -238,5 +244,5 @@ For test setup, model/view assertions, and command/UI test patterns, use the sepPaths here (`packages/ckeditor5`, `packages/ckeditor5/src/plugins/<name>/`, `apps/client/...`) are **thisTrilium repository**. The CKEditor 5 library mechanics referenced (editor bases `BalloonEditor`/-`DecoupledEditor`, `EditorConfig`, the watchdog) come from the external `ckeditor5` package,+`DecoupledEditor`, `EditorConfig`, `onEditorError()`) come from the external `ckeditor5` package,**48 or later**.diff --git a/.claude/skills/ckeditor5-plugin-development/references/upgrading-ckeditor.md b/.claude/skills/ckeditor5-plugin-development/references/upgrading-ckeditor.mdnew file mode 100644index 0000000000..c05a2b59b5--- /dev/null+++ b/.claude/skills/ckeditor5-plugin-development/references/upgrading-ckeditor.md@@ -0,0 +1,141 @@+# Upgrading CKEditor (major versions)++Renovate opens a `renovate/major-ckeditor-monorepo` branch for each major `ckeditor5` release. The+bump itself is two version strings and a lockfile; the work is what the release breaks around it. This+page is the procedure, the CSS model CKEditor 49 introduced (the source of most visual breakage),+the traps already hit, and `ck_css.mjs`, which measures a stylesheet change instead of guessing at it.++## Procedure++1. **Read the release's breaking changes** from the installed changelog rather than the web:+ `awk '/^## \[49.0.0\]/{f=1} /^## \[48/{f=0} f' node_modules/ckeditor5/CHANGELOG.md`. Grep the repo+ for every removed or renamed API it names (`apps/client/src`, `packages/*/src`).+2. **Read CI on the Renovate PR, but find the root.** One missing export fails the build, every E2E+ job and the Docker image at once (`gh run view --job <id> --log-failed`, look for+ `MISSING_EXPORT`). The typecheck cascades too: once `apps/client` stops compiling, projects that+ read its declarations (share-theme, client specs, build-docs) report errors about exports that do+ exist. Fix the root errors first; the rest vanish. The CKEditor test job writes a blob report, so+ its log never names the failing spec — run the suite locally instead.+3. **Run the CKEditor suite locally** (`pnpm exec playwright install chromium` once in+ `packages/ckeditor5`, then `pnpm --filter @triliumnext/ckeditor5 exec vitest run`). Layout specs+ that measure real CSS (`tile_row_view`, `multicolumn_layout`) catch stylesheet breakage.+4. **Audit our CSS:** `node .claude/skills/ckeditor5-plugin-development/ck_css.mjs audit` lists every+ `var(--ck-…)` read, without a fallback, of a name neither CKEditor nor our CSS declares.+5. **Compare against the previous version** with the harnesses (below) until the only differences+ left are ones you decided to keep.+6. **Regenerate the `cke` icon font** (see SKILL.md, "The `cke` icon pack") — every bump.++## CKEditor 49's CSS model++v49 replaced the flat set of CSS variables with three layers: **foundation** scales+(`--ck-spacing-sm`, `--ck-radius-base`, `--ck-font-size-md`), **semantic** roles+(`--ck-spacing-padding-compact`, `--ck-border-radius-control`, `--ck-color-interactive-focus-border`),+and **component** tokens (`--ck-button-font-size`, `--ck-color-grid-gap`). Three consequences+account for nearly every regression the v49 upgrade caused:++- **Legacy names are no longer declared.** `--ck-spacing-small`, `--ck-font-size-small` and the rest+ are gone, so a bare `var(--ck-spacing-small)` resolves to nothing and a `calc()` around it becomes+ invalid (the tile row lost its 20px group gap that way). v49's own feature CSS reads them with the+ new name as fallback, and so do we: `var(--ck-spacing-small, var(--ck-spacing-sm))`. That keeps+ any scoped legacy override of ours working (snippet items set `--ck-spacing-large: 8px`, read by+ `snippets.css`). The mapping, from v49's own fallbacks:++ | Legacy | v49 | Legacy | v49 |+ |---|---|---|---|+ | `--ck-spacing-tiny` | `--ck-spacing-xs` | `--ck-spacing-large` | `--ck-spacing-lg` |+ | `--ck-spacing-small` | `--ck-spacing-sm` | `--ck-spacing-medium-small` | `--ck-spacing-md` |+ | `--ck-spacing-medium` | `--ck-spacing-base` | `--ck-font-size-small` | `--ck-font-size-sm` |+ | `--ck-spacing-standard` | `--ck-spacing-base` | `--ck-color-error-text` | `--ck-color-feedback-error` |++- **Component tokens are computed at `:root`.** `--ck-button-font-size: var(--ck-font-size-md)` is+ declared on `:root`, so it is resolved there and inherited as a value. A scoped override of the+ name it reads — our dropdown panels' `--ck-font-size-base: 0.9rem`, the toolbar's+ `--ck-border-radius: 6px`, its `--ck-color-focus-border` — no longer reaches the component. The+ override goes on the **component token** at the same scope instead:++ | Where | Legacy override (kept, still read by some rules) | Component tokens set beside it |+ |---|---|---|+ | `div.ck.ck-dropdown__panel` (`ckeditor-theme.css`) | `--ck-font-size-base: 0.9rem` | `--ck-button-font-size`, `--ck-input-font-size`, `--ck-labeled-field-label-font-size`, `--ck-toolbar-text-font-size` |+ | `.ck.ck-toolbar` (`theme-next/notes/text.css`) | `--ck-focus-ring: 1px solid transparent` | `--ck-button-focus-border-color: transparent`, `--ck-toolbar-text-font-size: 13px` |+ | toolbar `:focus-visible`, `div.ck.ck-dialog` | `--ck-focus-ring: 1px solid <focus color>` | `--ck-button-focus-border-color: <focus color>` |+ | `.ck.ck-color-selector` | `--ck-border-radius` (via the toolbar) | `--ck-color-selector-padding`, `--ck-color-selector-grids-fragment-padding`, `--ck-button-border-radius`, `--ck-color-grid-*`, `--ck-color-interactive-focus-border` |+ | `.ck.ck-list-styles-list` | `--ck-spacing-large` (no longer read there) | `--ck-list-styles-list-padding` |+ | `.ck.ck-editor__editable_inline` (`ckeditor-theme.css`) | — | `--ck-editor-editable-padding: 0 .6em`, plus `.9em` first/last-child margins |++ To find what a component reads: `ck_css.mjs props new font-size 'button'` (which rule sets the+ property) and `ck_css.mjs readers new button-font-size` (who reads a token).++- **The focus color chain is inverted.** v48 derived the ring from `--ck-color-focus-border`; v49+ declares `--ck-color-focus-border: var(--ck-color-interactive-focus-border)`, which reads+ `--ck-focus-border-color` (CKEditor's blue). Our `body`-level `--ck-color-focus-border` therefore+ colors nothing that reads the new names; a focused button's border is+ `--ck-button-focus-border-color`, a color tile's ring `--ck-color-interactive-focus-border`.++### Traps++- **`--x: inherit` is the custom property's own inheritance.** It copies the parent's `--x`, not+ "inherit the font size". To undo `--ck-toolbar-text-font-size: 13px` inside toolbar dropdowns the+ panel sets it to `var(--ck-font-size-base)`, not `inherit`.+- **Nested selectors reach further than they read.** v49 ships native CSS nesting;+ `.ck.ck-toolbar { & .ck-button__label { … } }` is a descendant selector, and a toolbar dropdown's+ panel is a descendant of the toolbar — so toolbar text rules also hit menu items.+- **A `var()` of an undefined name invalidates the whole declaration**, so a `box-shadow` reading one+ missing color renders as `none`, not as a partial shadow.++## Where CKEditor's CSS reaches++A content-style change shows in four places, and each loads it differently:++| Place | Loads |+|---|---|+| Editor (and read-only text) | `ckeditor5/ckeditor5.css`, then the theme files `src/index.ts` imports (`blockquote.css`, `content_colors.css`, …), then the client chain (`ckeditor-theme.css`, `theme-light.css`, the theme, `style.css`) |+| Printing, shared pages | `src/theme/ck-content.css` = `ckeditor5-content.css` + `content_colors.css` + Trilium's content rules; shared pages add the share theme, which restyles code blocks, quotes and lines itself |+| HTML export (server, desktop) | `ckeditor5-content.css`, `ckeditor5-content-colors.css`, `ckeditor5-multicolumn.css`, concatenated by `apps/server/src/services/export/zip/factory.ts`; each build script copies them |+| HTML export (standalone) | `ck-content.css?raw` — its `@import`s are left unresolved, so standalone exports carry no CKEditor content styles (predates v49) |++`src/theme/content_colors.css` keeps CKEditor 48's content colors (v49's code-block background is an+opaque `#f5f5f5`, also in the dark theme). It must load **after** CKEditor's stylesheet: same+selectors, so order decides.++## Comparing two versions: `ck_css.mjs`++```bash+S=.claude/skills/ckeditor5-plugin-development/ck_css.mjs+node $S stage 48.5.2 # the previous version becomes the "old" side; the installed one is "new"+node $S run all # DIFF lines: context | element | property: old → new+node $S clean # always — staged files sit in packages/ckeditor5/src+node $S audit # undeclared --ck-* reads in our CSS+node $S readers new spacing-large # who reads a token (new | <version> | <path>)+node $S props 48.5.2 padding 'list-styles' # who sets a property, in a version's stylesheet+```++`stage` downloads the version's `dist/ckeditor5.css` and `ckeditor5-content.css` with `npm pack`+(cached in the OS temp dir) and copies them and `harness/*` into `packages/ckeditor5/src` as+`zz_ckcss_*`, where the package's Vitest browser config runs them in Chromium. Both sides load+**today's** Trilium stylesheets (`harness/kit.ts`, `CONTEXTS`), so every difference is one the+CKEditor change causes:++- **`content`** renders one note with every content element (headings, inline code, highlight,+ link, font sizes, mention, kbd, quote, code block, line, table and image with captions, lists,+ to-do list, page break, admonition) in `app`, `app-dark`, `share` and `export`, and diffs ~20+ visual properties per element.+- **`ui`** builds a real `ClassicEditor` with a toolbar (button, heading dropdown, font color with+ Trilium's palette, insert table) plus a dialog and a balloon, and diffs size, padding, radius, font,+ icon size and the `:focus` border, shadow and outline of each.++To learn which rule produced a value, add the element's key and properties to the spec's `PROBE`+map; `RULE` lines then list every matching rule with nested selectors resolved. Extend the fixture or+`record()` calls for anything not yet covered — a difference in an element the harness does not+render goes unnoticed.++Caveats: programmatic `focus()` counts as `:focus-visible`; values are at the default 16px root+size; CSS that `?inline` imports has its `@import`s resolved, `?raw` does not; the harness cannot see+rules that depend on the app's DOM around the editor beyond the wrapper classes it sets.++## State after the v49 migration++- No watchdog: `onTextEditorError()` and the `editor-error` toast (`references/tooling-and-packaging.md`).+- Content in every context matches v48, except the editable's corner radius (2px → 0, invisible).+- Left as v49 ships them, deliberately: control sizing (toolbar buttons 32px, 4px radius, 14px text;+ inputs 32px; dialog buttons 4px radius) and the color selector's button icons (22.1px → 20.6px,+ sized from the button text).diff --git a/.claude/skills/ckeditor5-testing/SKILL.md b/.claude/skills/ckeditor5-testing/SKILL.mdindex e1971469c6..180dea62dc 100644--- a/.claude/skills/ckeditor5-testing/SKILL.md+++ b/.claude/skills/ckeditor5-testing/SKILL.md@@ -227,7 +227,7 @@ into later specs.) See `references/patterns.md` for the recipe.| File | Use it for ||------|-----------|| `references/test-utilities.md` | Testing against a real `ClassicEditor` (lifecycle, `licenseKey: 'GPL'`), and the `_setModelData`/`_getModelData`/`_getViewData` helpers from `'ckeditor5'` + the `[]`/`{}` selection syntax. |-| `references/patterns.md` | Idiomatic recipes per concern (schema, conversion round-trips, commands, UI, keystrokes, events, async), all against a real editor; the `glob`/clipboard/jQuery-`$` stubbing recipe (via the globals kit's `installGlobMock`/`mockClipboard`); note on the 100% coverage gate for browser-mode packages. |+| `references/patterns.md` | Idiomatic recipes per concern (schema, conversion round-trips, commands, UI, keystrokes, events, async), all against a real editor; the `glob`/clipboard/jQuery-`$` stubbing recipe (via the globals kit's `installGlobMock`/`mockClipboard`); testing `onEditorError()` listeners without Vitest flagging the dispatched `error` event; measuring real CSS (`?url` vs `?inline` vs `?raw`, transitions, focus); note on the 100% coverage gate for browser-mode packages. || `references/running-and-config.md` | The WebdriverIO `vitest.config.ts` shape, `pnpm --filter` commands, the debug command, `pnpm test:parallel`/`test:sequential` (ckeditor5 + math sequential), coverage thresholds, and troubleshooting a session that never starts (a missing Playwright browser build, the worktree dep-optimizer hang, orphaned headless Chromium). || `references/test-conventions.md` | Trilium test **conventions & gotchas**: real-browser event timing, real-editor teardown, the both-assertion-styles note, unreachable code vs. the 100% gate, and the pointer to `writing-unit-tests`. |diff --git a/.claude/skills/ckeditor5-testing/references/patterns.md b/.claude/skills/ckeditor5-testing/references/patterns.mdindex 67cc4d910a..dcad434ffd 100644--- a/.claude/skills/ckeditor5-testing/references/patterns.md+++ b/.claude/skills/ckeditor5-testing/references/patterns.md@@ -203,6 +203,42 @@ it( 'throws on invalid config', () => {For `CKEditorError`, match the error id substring.+### Errors that escape the editor (`onEditorError()`)++CKEditor 49 reports an escaped error from `window`'s `error` and `unhandledrejection` events, and+only a `CKEditorError` whose `context` resolves to a ready editor. Native errors arrive wrapped by+`CKEditorError.rethrowUnexpectedError(error, context)` (`unexpected-error … Original error: …`).+Test a listener by dispatching the event a thrown error would raise (`src/editor_errors.spec.ts`):++```ts+function escape( error: Error ) {+ const listener = () => {};+ window.addEventListener( 'error', listener );+ window.dispatchEvent( new ErrorEvent( 'error', { error } ) );+ window.removeEventListener( 'error', listener );+}+```++The extra listener is the point: Vitest's browser runner reports an `error` event as an+**unhandled error** (failing the run) whenever no user listener is registered on `window`, and+`preventDefault()` does not change that. Once the code under test unregisters its own listener, an+event dispatched without one fails the file even though every test passed.++## Measuring real CSS++Specs that assert layout load a stylesheet and read `getComputedStyle()` /+`getBoundingClientRect()` (`tile_row_view.spec.ts`, `multicolumn_layout.spec.ts`):++- `import url from "ckeditor5/ckeditor5.css?url"` plus a `<link>` loads CKEditor's sheet as the app+ does. `?inline` returns the CSS text with `@import`s resolved — use it to load a client+ stylesheet chain (`apps/client/src/stylesheets/style.css?inline`) into a `<style>`. `?raw` keeps+ `@import` lines as text, which the browser then cannot resolve.+- Disable transitions (`* { transition: none !important; }`) before reading `box-shadow` or+ colors of a state you just entered; otherwise you read the transition's first frame.+- `element.focus()` from a test counts as `:focus-visible`.+- To compare a stylesheet between two CKEditor versions, don't write a spec: use `ck_css.mjs` from+ the `ckeditor5-plugin-development` skill (`references/upgrading-ckeditor.md`).+## Reaching 100% coverage`ckeditor5` gates `src/**` at 100%