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): tailor the CKEditor 5 skills to Trilium
Elian Doran4ac95c50d133
diff --git a/.claude/skills/ckeditor5-plugin-development/SKILL.md b/.claude/skills/ckeditor5-plugin-development/SKILL.mdindex dce2a62630..a960bb6343 100644--- a/.claude/skills/ckeditor5-plugin-development/SKILL.md+++ b/.claude/skills/ckeditor5-plugin-development/SKILL.md@@ -1,37 +1,53 @@---name: ckeditor5-plugin-developmentdescription: >-- Write, extend, and review CKEditor 5 plugins. Use when building or reviewing a- CKEditor 5 feature/plugin, or when working with the editing engine (model,- view, schema, conversion/upcast-downcast), commands, the UI library- (buttons, dropdowns, dialogs, balloons, toolbars), widgets (block/inline,- toWidget, nested editables), keystrokes, localization (t()), or scaffolding a- ckeditor5-* package. Covers the architecture, idiomatic patterns, code-style- conventions, and a review checklist distilled from the official docs.+ Write, extend, and review CKEditor 5 plugins in the Trilium (TriliumNext+ Notes) monorepo — the rich-text-note editor under packages/ckeditor5 and the+ @triliumnext/ckeditor5-<feature> plugin packages. Use when building or+ reviewing a Trilium CKEditor 5 feature/plugin, or when working with the+ editing engine (model, view, schema, conversion/upcast-downcast), commands,+ the UI library (buttons, dropdowns, dialogs, balloons, toolbars), widgets+ (block/inline, toWidget, nested editables), keystrokes, localization (t()/.po),+ registering a plugin into plugins.ts / the editor classes / toolbar.ts, or+ scaffolding a new @triliumnext/ckeditor5-* package. Covers the architecture,+ idiomatic patterns, Trilium packaging/registration, code-style conventions,+ and a review checklist.----# CKEditor 5 plugin development+# CKEditor 5 plugin development (Trilium monorepo)CKEditor 5 is **plugin-based**: every feature — even typing and `<p>` support — is a-plugin. Without plugins the editor is an empty API. This skill distills how to write-new plugins and review existing ones idiomatically.+plugin. Without plugins the editor is an empty API. This skill is specific to **Trilium+(TriliumNext Notes)**, whose rich-text note editor is built from the CKEditor 5 library+(external dep, pinned `48.2.0`) plus Trilium's own plugins. In this repo the editor build+lives in `packages/ckeditor5` (`@triliumnext/ckeditor5`) and custom features live in+sibling `packages/ckeditor5-<feature>` workspace packages (`@triliumnext/ckeditor5-<feature>`:+admonition, collapsible, footnotes, keyboard-marker, math, mermaid). The editor is consumed+by `apps/client` (the text note widget). This skill distills how to write new Trilium plugins+and review existing ones idiomatically.## When to use this skill-Use it whenever the task involves a CKEditor 5 plugin/feature: creating one, extending-one, debugging editing behavior, or reviewing plugin code for correctness and-convention compliance. Trigger concepts include: model/view/schema, conversion-(upcast/downcast), `Command`, `editor.model.change()`, `ButtonView`/`componentFactory`,-widgets (`toWidget`), `ContextualBalloon`/`Dialog`, `editor.keystrokes`, `t()`-localization, or a `ckeditor5-*` npm package.+Use it whenever the task involves a Trilium CKEditor 5 plugin/feature: creating one (a new+`@triliumnext/ckeditor5-<feature>` package or an in-repo plugin under+`packages/ckeditor5/src/plugins/`), extending one, debugging editing behavior, registering a+plugin so it reaches the editor, or reviewing plugin code for correctness and convention+compliance. Trigger concepts include: model/view/schema, conversion (upcast/downcast),+`Command`, `editor.model.change()`, `ButtonView`/`componentFactory`, widgets (`toWidget`),+`ContextualBalloon`/`Dialog`, `editor.keystrokes`, `t()` localization, the `plugins.ts`+registry / editor classes / `toolbar.ts`, or a `@triliumnext/ckeditor5-*` package.## The three pillars-1. **Core editor architecture** (`@ckeditor/ckeditor5-core`) — glue classes: `Editor`,+These are the library's internal layers (upstream packages `ckeditor5-core`/`-engine`/`-ui`);+in Trilium you never import them by those paths — everything comes from the `ckeditor5` aggregate+(see below). They describe how the engine is organized:++1. **Core editor architecture** (library `ckeditor5-core`) — glue classes: `Editor`,`Plugin`, `Command`, plus the event/observable system.-2. **Editing engine** (`@ckeditor/ckeditor5-engine`) — the custom MVC data **model**, the+2. **Editing engine** (library `ckeditor5-engine`) — the custom MVC data **model**, the**view** (virtual DOM), **schema**, and **conversion** between them. The biggest piece.-3. **UI library** (`@ckeditor/ckeditor5-ui`) — MVC views, templates, and components+3. **UI library** (library `ckeditor5-ui`) — MVC views, templates, and components(buttons, dropdowns, dialogs, toolbars).Mental model of the engine: there is **one model document** that is **converted** into two@@ -45,39 +61,48 @@ data (HTML) ──upcast──▶ MODEL ──editing downcast──▶ editing└────data downcast──────▶ data view ──▶ getData()/output HTML```-## Importing CKEditor in your project+## Importing CKEditor in Trilium-In your own project, import everything from the single **`ckeditor5`** npm package (and-`ckeditor5-premium-features` for premium plugins):+Import everything from the single **`ckeditor5`** aggregate package (pinned `48.2.0`; it is a+`peerDependency` + `devDependency` of every plugin package). Premium symbols come from+`ckeditor5-premium-features` (lazy-loaded, see `loadPremiumPlugins()`):-```js-import { Plugin, Command, ButtonView, Widget, toWidget } from 'ckeditor5';+```ts+import { Plugin, ButtonView, Command, _setModelData } from 'ckeditor5';```-The `@ckeditor/ckeditor5-*` paths you'll see in the library's own source (and cited in-`references/core-plugin-patterns.md`) resolve to the same symbols, but downstream you should import-from `ckeditor5` to avoid duplicate-module-instance problems. The routine exception is the-**CKEditor Inspector**, a separate dev-only package:-`import CKEditorInspector from '@ckeditor/ckeditor5-inspector';`.+- **Cross-plugin** imports use the workspace package name, e.g.+ `import { Kbd } from '@triliumnext/ckeditor5-keyboard-marker';`.+- **Every import includes its file extension** (`.js`/`.ts`/`.json`) — enforced by+ `eslint-config-ckeditor5` (`require-file-extensions-in-imports`), with+ `allow-imports-only-from-main-package-entry-point` and `no-legacy-imports` also active.+- The `@ckeditor/ckeditor5-*` deep paths you'll see in the library's own source (and cited in+ `references/core-plugin-patterns.md`) resolve to the same symbols, but in Trilium you always+ import from the `ckeditor5` aggregate to avoid duplicate-module-instance problems. The only+ routine exceptions are dev/debug packages: `@ckeditor/ckeditor5-icons` and the+ **CKEditor Inspector** (`import CKEditorInspector from '@ckeditor/ckeditor5-inspector';`).## Plugin anatomy-A plugin implements `PluginInterface`; the easy way is to extend `Plugin`. A plain function-`function MyPlugin( editor ) {}` also works for trivial cases.+A plugin `extends Plugin` (from `'ckeditor5'`). There is **no** `isOfficialPlugin`/`isPremiumPlugin`+flag in Trilium plugins. (License headers are not uniform across packages — some, e.g. admonition,+prefix files with a CKSource header; others don't. Match the package you're in; see+`references/conventions.md`.)-```js+```tsimport { Plugin } from 'ckeditor5';+import FooEditing from './fooediting.js';+import FooUI from './fooui.js';-export default class MyPlugin extends Plugin {+export default class Foo extends Plugin {// Dependencies — the editor loads these automatically before this plugin.static get requires() {- return [ SomeDependency ];+ return [ FooEditing, FooUI ] as const;}- // Stable name for editor.plugins.get( 'MyPlugin' ) and dependency wiring.- // In TypeScript: return 'MyPlugin' as const;+ // Stable name (PascalCase = the package/folder) for editor.plugins.get( 'Foo' ).static get pluginName() {- return 'MyPlugin';+ return 'Foo' as const;}init() {@@ -95,19 +120,30 @@ export default class MyPlugin extends Plugin {}```-Key rules (from the official conventions):+Per-package `src/` layout (e.g. `packages/ckeditor5-admonition/src/`): `{feature}.ts` glue,+`{feature}editing.ts`, `{feature}ui.ts`, optional `{feature}command.ts`, `augmentation.ts`+(the `declare module 'ckeditor5'` types), and `index.ts` (re-exports glue + sub-plugins ++command types, plus `export const icons = { fooIcon }`). Complex plugins add `constants.ts`+(`ELEMENTS`/`ATTRIBUTES`/`COMMANDS`/`CLASSES`), `utils.ts` (model-query helpers), and split+`schema.ts`/`converters.ts`. Assets: `theme/{feature}.css`, `theme/icons/*.svg`,+`lang/en.po` + `lang/contexts.json`, `tests/`. See `references/conventions.md`.++Key rules (inherited from the upstream conventions via `eslint-config-ckeditor5`):- Every feature is a plugin; plugins are **highly granular** and should know **as littleabout other plugins as possible** (communicate via commands, events, and the schema).- **Split editing from UI.** The standard pattern is three plugins:- - `Feature` — the **glue** plugin: `static get requires() { return [ FeatureEditing, FeatureUI ]; }`+ - `Feature` — the **glue** plugin: `static get requires() { return [ FeatureEditing, FeatureUI ] as const; }`- `FeatureEditing` — schema, conversion, commands (works headless / server-side).- `FeatureUI` — buttons, dropdowns, balloons registered in `componentFactory`.- This enables reuse (someone can take your editing layer and write a different UI).-- Register UI in `editor.ui.componentFactory.add( 'name', locale => view )`, then the user- adds `'name'` to their `toolbar` config.+ This enables reuse (someone can take your editing layer and write a different UI). Simple+ text-attribute features can reuse the built-in `AttributeCommand` inline (see keyboard-marker).+- Register UI in `editor.ui.componentFactory.add( 'name', locale => view )`, then the component+ `'name'` is added to Trilium's toolbar config (`apps/client/.../text/toolbar.ts`).- Make features self-configuring: pre-configure the schema and provide config defaults via`editor.config.define( 'feature', { … } )`, read with `editor.config.get( 'feature.key' )`.+- SVG icons are imported with `?raw` (`import fooIcon from '../theme/icons/foo.svg?raw';`) and+ surfaced through `export const icons = { fooIcon }` in `index.ts`.## Minimal end-to-end example (inline text attribute)@@ -175,14 +211,26 @@ converters instead of `attributeToElement`; see `references/widgets.md`.## Development workflow-- **Scaffold a distributable package** with the package generator (`npx ckeditor5-package-generator`).- See `references/tooling-and-packaging.md`. For a quick local feature you can just add a- plugin class to an existing project.+1. **Write the plugin.** Either a new `packages/ckeditor5-<feature>` workspace package+ (`@triliumnext/ckeditor5-<feature>`, `main: "src/index.ts"`, ships TS source — no per-package+ `dist` for consumers) or an in-repo plugin file under `packages/ckeditor5/src/plugins/`. See+ `references/tooling-and-packaging.md` for the package layout and config files.+2. **Register it so it reaches the editor** (full flow in `references/tooling-and-packaging.md`):+ - For a new workspace package, add `"@triliumnext/ckeditor5-<feature>": "workspace:*"` to+ `packages/ckeditor5/package.json`.+ - Import it in `packages/ckeditor5/src/plugins.ts` and add it to the right array —+ `CORE_PLUGINS` (minimal/attribute editor), `TRILIUM_PLUGINS` (in-repo `src/plugins/`), or+ `EXTERNAL_PLUGINS` (the `@triliumnext` workspace packages). These compose into+ `COMMON_PLUGINS`, which the editor classes in `packages/ckeditor5/src/index.ts` expose as+ `static builtinPlugins`.+ - Add the component name to the toolbar in `apps/client/src/widgets/type_widgets/text/toolbar.ts`.- **Always reach for the CKEditor 5 Inspector** while developing — it shows the live model,view, schema, commands, and selection. `import CKEditorInspector from '@ckeditor/ckeditor5-inspector'; CKEditorInspector.attach( editor );`- **Change the model, not the DOM.** Wrap all model mutations in `editor.model.change( writer => … )`(one block = one undo step). Use `editor.editing.view.change()` only for view-only state(e.g. focus class) that the model does not represent.+- **Lint & test per package** with pnpm workspace filters:+ `pnpm --filter @triliumnext/ckeditor5-<feature> test` (also `lint`, `stylelint`, `test:debug`).- **Verify** with `editor.getData()` / `editor.setData()` and by exercising selection edgecases (collapsed vs. ranged, inside objects/limits).@@ -197,8 +245,8 @@ Load the focused reference for the task at hand:| `references/commands.md` | `Command` patterns: `refresh()`/`execute()`, state (`value`/`isEnabled`), `forceDisabled()`, `affectsData`, command events. || `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` | Naming, file/CSS/BEM rules, imports, JSDoc/visibility, `CKEditorError`, TypeScript rules. For writing idiomatic code and reviewing. |-| `references/tooling-and-packaging.md` | Package generator, `ckeditor5-metadata.json`, build output/integration, custom editor creators, dev-repo setup, the Inspector. |+| `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, `.po` localization, `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), and the Inspector. || `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. || `references/core-plugin-patterns.md` | Canonical idioms mined from the actual `packages/*/src` source: toolbar+menu-bar button factory, plugin flags & `augmentation.ts`, `AttributeCommand`/`setAttributeProperties`, inline-attribute boundary helpers, `elementToStructure`+slots, reconversion, `BalloonToolbar`, raw-HTML widgets, clipboard pipeline, markers, post-fixers, async/upload. Each cites its source file. |@@ -218,23 +266,13 @@ trackers/handlers in `destroy()`. Full version: `references/review-checklist.md`review (workflow, CKEditor-specific defect patterns, contribution process), use the separate**`ckeditor5-reviewing`** skill, which delegates back to this checklist.-## Provenance & source references--**This skill is self-contained and library-focused, not tied to any particular project.** Every-repository path it cites — `docs/…`, `packages/ckeditor5-…/src/…`, config files, the baseline-commit — points into the **upstream CKEditor 5 repository**-([github.com/ckeditor/ckeditor5](https://github.com/ckeditor/ckeditor5)), **not the project you are-currently working in**. Those paths are for verification and deeper reading in the library's own-source. Unless you happen to be working inside the ckeditor5 repository itself, do not try to open-them as local files — your plugin lives in your own project and imports CKEditor from the-`ckeditor5` / `@ckeditor/*` npm packages.--This skill was distilled from that upstream repository at commit **`9ecca53627`** (mid-2026):-the framework docs (`docs/framework/**` — architecture, contributing/code-style, package-metadata,-deep-dive/localization, development-tools), the tutorials (`docs/tutorials/**` — crash-course,-abbreviation plugin, widgets, timestamp), and the core plugin source (`packages/ckeditor5-*/src/**`,-for `references/core-plugin-patterns.md`).--To refresh the skill, browse or clone the upstream repository and compare those paths against-commit `9ecca53627` — e.g. `git diff 9ecca53627..HEAD -- docs packages` run **inside a clone of-ckeditor5** — then fold in what changed and bump the commit reference here.+## Scope & sources++This skill is specific to the **Trilium (TriliumNext Notes) monorepo's** CKEditor 5 integration.+Repository paths it cites — `packages/ckeditor5`, `packages/ckeditor5-<feature>`, `apps/client/...` —+are **this repository**, and examples come from Trilium's own plugins (admonition, collapsible,+footnotes, keyboard-marker, math, mermaid). The CKEditor 5 **library** is an external dependency+pinned to **48.2.0**; its mechanics were distilled from the upstream docs (ckeditor.com/docs) and+source (github.com/ckeditor/ckeditor5, commit 9ecca53627). Where a snippet cites an upstream library+package (e.g. ckeditor5-basic-styles, -link, -image), that is the library's own source — not a+Trilium package.diff --git a/.claude/skills/ckeditor5-plugin-development/references/architecture.md b/.claude/skills/ckeditor5-plugin-development/references/architecture.mdindex fc3747dc36..1316f6fd40 100644--- a/.claude/skills/ckeditor5-plugin-development/references/architecture.md+++ b/.claude/skills/ckeditor5-plugin-development/references/architecture.md@@ -2,12 +2,31 @@The conceptual foundation. Read this before working on editing behavior.+> **Scope.** Everything here is engine mechanics from the **`ckeditor5` library** (the npm+> aggregate, pinned to `48.2.0` in the Trilium monorepo). The APIs (`editor.model`,+> `editor.editing`, `Plugin`, the writer, schema, conversion) are the library's, imported as+> `import { Plugin } from 'ckeditor5'` (with file extensions). Paths under+> `packages/ckeditor5-*` (admonition, collapsible, footnotes, keyboard-marker, math, mermaid)+> are **Trilium's own** plugins that consume these APIs; the editor build/aggregator lives in+> `packages/ckeditor5`. Trilium examples are cited throughout — they exercise the same library+> mechanics described below.+## Editor classes-`Editor` (`module:core/editor/editor~Editor`) is the entry point that glues everything.+`Editor` (the `Editor` base from `ckeditor5`) is the entry point that glues everything.Editors are created with the **static async** `create()` (constructors are protected).-Built-in types: `ClassicEditor`, `InlineEditor`, `BalloonEditor`, `DecoupledEditor`; you may-implement your own (see `tooling-and-packaging.md` → custom editor creators).+Built-in library types: `ClassicEditor`, `InlineEditor`, `BalloonEditor`, `DecoupledEditor`;+integrators may subclass their own (see `tooling-and-packaging.md` → custom editor creators).++Trilium defines **three editor classes** in `packages/ckeditor5/src/index.ts`, each subclassing+a built-in:+- `AttributeEditor extends BalloonEditor` — inline/balloon editing.+- `ClassicEditor extends DecoupledEditor` — toolbar + editable placed by the app (note the+ name: Trilium's `ClassicEditor` is decoupled, not the library's boxed `ClassicEditor`).+- `PopupEditor extends BalloonEditor` — balloon variant for popups.++The plugin registry lives in `packages/ckeditor5/src/plugins.ts`. Whichever class is used,+`editor.model` / `editor.editing` / `editor.conversion` etc. are the same library APIs below.Key properties:@@ -127,6 +146,12 @@ Behavior that flags produce (observable in the block-widget feature):- `isLimit` — element can't be split (Enter) or emptied/left by Backspace; good for titles.- `isObject` / `$blockObject` / `$inlineObject` — selected/deleted/copied as a unit.+Trilium's block features lean on exactly these: `ckeditor5-admonition` and+`ckeditor5-collapsible` register block elements inheriting from `$blockObject` and mark inner+title/content regions with `isLimit`, then guard structure with one or more+`registerPostFixer` invariants (see `core-plugin-patterns.md` → post-fixers). `ckeditor5-footnotes`+splits its schema across `schema.ts` / `converters.ts` with shared `constants.ts`.+Custom checks for disallowing in specific contexts:```jsdiff --git a/.claude/skills/ckeditor5-plugin-development/references/commands.md b/.claude/skills/ckeditor5-plugin-development/references/commands.mdindex fdf6d7ecca..a1e6f79e3b 100644--- a/.claude/skills/ckeditor5-plugin-development/references/commands.md+++ b/.claude/skills/ckeditor5-plugin-development/references/commands.md@@ -5,6 +5,14 @@ by `refresh()`). Commands encapsulate feature logic so UI, keystrokes, other plu`editor.execute()` can all trigger and observe it. Most editor features expose their behavioras commands.+> `Command` and `AttributeCommand` come from the **`ckeditor5` library** (`48.2.0`), imported+> as `from 'ckeditor5'` (with file extensions). In Trilium you don't always write a command+> class: simple `$text`-attribute features reuse the built-in `AttributeCommand` —+> `ckeditor5-keyboard-marker` registers `new AttributeCommand( editor, '<attr>' )` and lets the+> library handle toggle/refresh (see `core-plugin-patterns.md` → Reusable AttributeCommand).+> Features with bespoke model mutations (e.g. `ckeditor5-admonition`, `ckeditor5-footnotes`)+> write a custom `Command` subclass as below.+## Defining and registeringExtend `Command`; register in the editing plugin's `init()`:diff --git a/.claude/skills/ckeditor5-plugin-development/references/conventions.md b/.claude/skills/ckeditor5-plugin-development/references/conventions.mdindex a5ff50e5fa..d167cb045a 100644--- a/.claude/skills/ckeditor5-plugin-development/references/conventions.md+++ b/.claude/skills/ckeditor5-plugin-development/references/conventions.md@@ -1,7 +1,28 @@-# Code-style conventions+# Code-style conventions (Trilium)-The official CKEditor 5 conventions (enforced by custom ESLint rules). Use them both to write-idiomatic plugins and to review them. Items below note the enforcing ESLint rule where one exists.+Conventions for Trilium's CKEditor 5 plugins. Each `@triliumnext/ckeditor5-<feature>` package and+`packages/ckeditor5` lints with **`eslint-config-ckeditor5`** + **`eslint-plugin-ckeditor5-rules`**+(theme CSS with `stylelint-config-ckeditor5`), so Trilium inherits the upstream CKEditor naming /+CSS-BEM / JSDoc / TypeScript rules below, on top of Trilium-specific packaging rules. (The root+ESLint config **skips `packages/*`** — each package lints itself.) Use these both to write+idiomatic plugins and to review them. Items below note the enforcing rule where one exists.++## License & headers (per package — not uniform)++These are **inconsistent across the packages** — match the package you're editing, don't assume one+rule. The `package.json` `license` field varies (`GPL-2.0-or-later` for admonition/collapsible,+`ISC` for footnotes/math, `GPL-3.0` for keyboard-marker, `SEE LICENSE IN LICENSE.md` for mermaid).+The CKSource license header is present in some packages (e.g. admonition) and absent in others;+when present it's this block before imports:++```ts+/**+ * @license Copyright (c) 2003-2024, CKSource Holding sp. z o.o. All rights reserved.+ * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license+ */+```++Follow the existing files in the package you touch; don't add or strip headers wholesale.## Naming@@ -31,22 +52,65 @@ idiomatic plugins and to review them. Items below note the enforcing ESLint rule## Imports & modules-- Same package → **relative** paths (`import Position from './position';`). Other packages →- by **package name / main entry** (`import { Table } from 'ckeditor5';`), never deep relative- (`../../../ckeditor5-utils/src/...`) (`no-relative-imports`, `no-cross-package-imports`,- `no-scoped-imports-within-package`).-- All imports include file extensions (`.ts`/`.js`/`.json`) (`require-file-extensions-in-imports`).-- In `@if CK_DEBUG` blocks use `require()`, not `import` (`use-require-for-debug-mode-imports`).-- Each TS source file (in the ckeditor5 source, `packages/*/src/`) starts with a `@module path/file` JSDoc tag matching its- location (`validate-module-tag`); the package `index.ts` uses `@module <package>`.+- **Library symbols always come from the `ckeditor5` aggregate**+ (`import { Plugin, ButtonView, Command, _setModelData } from 'ckeditor5';`) — never deep+ `@ckeditor/ckeditor5-*` paths (`allow-imports-only-from-main-package-entry-point`,+ `no-legacy-imports`). The only allowed `@ckeditor/*` deep imports are the dev/debug packages+ `@ckeditor/ckeditor5-icons` and `@ckeditor/ckeditor5-inspector`.+- **Cross-plugin** imports use the workspace package name+ (`import { Kbd } from '@triliumnext/ckeditor5-keyboard-marker';`); **same-package** imports are+ relative (`import FooEditing from './fooediting.js';`).+- **All imports include file extensions** (`.ts`/`.js`/`.json`) — `import './augmentation.js';`+ even though the source is `.ts` (`require-file-extensions-in-imports`).+- SVG icons import with the `?raw` suffix (`import fooIcon from '../theme/icons/foo.svg?raw';`) and+ are surfaced via `export const icons = { fooIcon };` in `index.ts`.## Plugin specifics-- Provide `static get pluginName()` (TS: `return 'Name' as const;`) and `static get requires()`- for dependencies.-- Plugin boolean flags: set required flags with the exact literal type/value- (`static override get isFooPlugin(): true { return true; }`); never set them to `false` and- never set disallowed flags (`ckeditor-plugin-flags`).+- Provide `static get pluginName()` (`return 'Foo' as const;` — PascalCase, matching the package+ folder) and `static get requires()` returning the sub-plugins with `as const`+ (`return [ FooEditing, FooUI ] as const;`).+- **No `isOfficialPlugin`/`isPremiumPlugin` flags** — Trilium plugins do not set them.++## Type augmentation (`src/augmentation.ts`)++Register the plugin's types into the **`ckeditor5` aggregate module** (not+`@ckeditor/ckeditor5-core`). Import `./augmentation.js` for side effects from `index.ts`.++```ts+import type { Foo, FooEditing, FooUI } from './index.js';+import type FooCommand from './foocommand.js';++declare module 'ckeditor5' {+ interface PluginsMap {+ [ Foo.pluginName ]: Foo;+ [ FooEditing.pluginName ]: FooEditing;+ [ FooUI.pluginName ]: FooUI;+ }+ interface CommandsMap { foo: FooCommand; } // optional — only if the plugin adds a command+ interface EditorConfig { foo?: { /* … */ }; } // optional — only if the plugin adds config+}+```++## Package & workspace++- Scope is **`@triliumnext/`**; package name `@triliumnext/ckeditor5-<feature>`,+ `"type": "module"`, `"main": "src/index.ts"` (ships TS source — no per-package dist for+ consumers), `peerDependencies: { "ckeditor5": "48.2.0" }`.+- Cross-package deps use the **`workspace:*`** protocol; the aggregator pulls plugins in via+ `"@triliumnext/ckeditor5-<feature>": "workspace:*"`. See `references/tooling-and-packaging.md`+ for the full registration flow.++## TypeScript config++Each package has its own `tsconfig.json`: `composite: true`, `target: es2019`, `strict`,+`module`/`moduleResolution`: `NodeNext` (hence the `.js` import extensions). A `tsconfig.test.json`+extends it for tests.++## Localization++User-facing strings go through `editor.t( … )`. Translations live in `lang/en.po` (gettext PO) with+disambiguation/notes in `lang/contexts.json`.## Visibility & documentationdiff --git a/.claude/skills/ckeditor5-plugin-development/references/conversion.md b/.claude/skills/ckeditor5-plugin-development/references/conversion.mdindex 555bc7842e..c047580cb5 100644--- a/.claude/skills/ckeditor5-plugin-development/references/conversion.md+++ b/.claude/skills/ckeditor5-plugin-development/references/conversion.md@@ -5,6 +5,13 @@ of truth**; HTML/data is just I/O. That is why helper names look "reversed": con`<mark>` element ↔ `highlight` model attribute uses `attributeToElement` (you name the**model** side first).+> All helpers and writers here come from the **`ckeditor5` library** (`48.2.0`); import as+> `from 'ckeditor5'` with file extensions. Trilium's own plugins under `packages/ckeditor5-*`+> register converters via `editor.conversion`; real examples cited below are+> `ckeditor5-math` and `ckeditor5-mermaid` (external/async-rendered widgets built with+> `createUIElement` render callbacks plus a data-processor wrap) and Trilium's reference-link+> conversion.+## Pipelines- **Upcast** (`upcast`) — view → model. Used when loading data **and** when pasting.@@ -188,6 +195,9 @@ processor.toView = data => toView( preprocess( data ) ); // and mirror toDataUse sparingly — prefer real converters. It's for cases the converter layer can't reach, such aspreserving newlines inside a formula or shielding a fragment from generic HTML normalization.+This is the pattern Trilium's `ckeditor5-math` / `ckeditor5-mermaid` use: a data-processor wrap+guards the raw formula/diagram source while a `createUIElement` render callback (see the element+callbacks above) renders the external/async output into the editing view.## Where to go deeperdiff --git a/.claude/skills/ckeditor5-plugin-development/references/core-plugin-patterns.md b/.claude/skills/ckeditor5-plugin-development/references/core-plugin-patterns.mdindex e37489336a..389a14d5e1 100644--- a/.claude/skills/ckeditor5-plugin-development/references/core-plugin-patterns.md+++ b/.claude/skills/ckeditor5-plugin-development/references/core-plugin-patterns.md@@ -1,20 +1,27 @@# Canonical patterns from the core plugins-> **Source paths below (`packages/ckeditor5-…/src/…`) point into the upstream CKEditor 5 repository-> ([github.com/ckeditor/ckeditor5](https://github.com/ckeditor/ckeditor5)), not your project.** They-> show where each idiom lives in the library's own source. Your plugin imports CKEditor from the-> `ckeditor5` / `@ckeditor/*` npm packages; don't try to open these as local files.--Real-world idioms mined from the actual upstream `packages/*/src` source (verified against the-library at the baseline commit). These go beyond the tutorials and are the patterns the official-plugins actually use. Each item cites its source file in the upstream repository.--**Downstream imports.** The snippets keep the symbol names but, in your own project, import them all-from the single **`ckeditor5`** package — e.g. `import { Plugin, ButtonView,-MenuBarMenuListItemButtonView, AttributeCommand, TwoStepCaretMovement, findAttributeRange,-inlineHighlight, Widget, toWidget, WidgetToolbarRepository } from 'ckeditor5';`. Where a snippet-shows an `@ckeditor/ckeditor5-*` or relative `../utils.js` import (the library's internal style),-treat it as a pointer to where the symbol lives, not the path you'd write downstream.+> **The source paths below (`packages/ckeditor5-basic-styles`, `-link`, `-image`, `-ui`, etc.)+> point into the CKEditor 5 *library* source+> ([github.com/ckeditor/ckeditor5](https://github.com/ckeditor/ckeditor5)) — the external+> dependency Trilium pins at `48.2.0` — NOT into Trilium's monorepo.** They show where each idiom+> lives in the library's own source. These are the upstream library packages (basic-styles, link,+> image, engine, ui, core, widget, typing); do **not** confuse them with Trilium's own+> `packages/ckeditor5-*` plugins (admonition, collapsible, footnotes, keyboard-marker, math,+> mermaid), which apply these very same patterns. You can't open the upstream files as local+> Trilium files — the symbols ship inside the `ckeditor5` npm package.++Real-world idioms mined from the actual library `packages/*/src` source (verified against+`[email protected]`). These go beyond the tutorials and are the patterns the official plugins+actually use — and the patterns Trilium's plugins follow. Each item cites its source file in the+CKEditor library repository.++**Imports.** The snippets keep the symbol names but in Trilium you import them all from the single+**`ckeditor5`** package (with file extensions on relative imports) — e.g. `import { Plugin,+ButtonView, MenuBarMenuListItemButtonView, AttributeCommand, TwoStepCaretMovement,+findAttributeRange, inlineHighlight, Widget, toWidget, WidgetToolbarRepository } from 'ckeditor5';`.+Where a snippet shows an `@ckeditor/ckeditor5-*` or relative `../utils.js` import (the library's+internal style), treat it as a pointer to where the symbol lives upstream, not the path you'd write+in a Trilium plugin.## Toolbar + menu-bar button in one factory@@ -88,7 +95,9 @@ untyped. (See also `tooling-and-packaging.md`.)## Reusable AttributeCommand + setAttributePropertiesInline-style features don't hand-roll the command — they reuse `AttributeCommand` and tag the-attribute as formatting so it behaves natively (copied on Enter, replicated on paste).+attribute as formatting so it behaves natively (copied on Enter, replicated on paste). Trilium's+`ckeditor5-keyboard-marker` follows this exactly: it registers a built-in `AttributeCommand` for+its `$text` attribute rather than writing a custom command.```ts// packages/ckeditor5-basic-styles/src/bold/boldediting.ts@@ -265,6 +274,8 @@ editor.editing.view.document.registerPostFixer( writer => { /* view-side cleanupPost-fixers run after each change (model) or downcast (view) and re-run until all return `false`.Use to guarantee structure (e.g. a required paragraph inside an editable, no two adjacent X).+Trilium's `ckeditor5-admonition` and `ckeditor5-collapsible` register **multiple**+`registerPostFixer`s to keep their block structure valid (e.g. an enforced title/content region).## Inserting content — option details@@ -321,4 +332,6 @@ with `editor.config.get( 'myFeature.key' )`. `define()` only fills values the ineditable), `BalloonEditor` (selection balloon toolbar), `DecoupledEditor` (you place toolbar +editable yourself), `MultiRootEditor` (many editables, no `ElementApiMixin`; `sourceElements` map).All share the `create()` flow: `initPlugins()` → `ui.init()` → `data.init()` → fire `ready`. See-`tooling-and-packaging.md` for the custom-creator anatomy.+`tooling-and-packaging.md` for the custom-creator anatomy. Trilium subclasses these in+`packages/ckeditor5/src/index.ts`: `AttributeEditor`/`PopupEditor` extend `BalloonEditor`, and its+`ClassicEditor` extends `DecoupledEditor` (see `architecture.md` → Editor classes).diff --git a/.claude/skills/ckeditor5-plugin-development/references/recipes.md b/.claude/skills/ckeditor5-plugin-development/references/recipes.mdindex 3e8f6da715..0995300060 100644--- a/.claude/skills/ckeditor5-plugin-development/references/recipes.md+++ b/.claude/skills/ckeditor5-plugin-development/references/recipes.md@@ -1,7 +1,9 @@# Recipes (task-oriented how-tos)-Common snippets from the official how-tos. All model mutations run inside-`editor.model.change( writer => … )`.+Task-oriented snippets for Trilium's CKEditor plugins (`packages/ckeditor5-*`). All library+symbols import from `ckeditor5` (48.2.0); local imports carry file extensions. All model+mutations run inside `editor.model.change( writer => … )`. In Trilium the "document" is the+content of a single text note, so these recipes operate over that note's model root.## Get the editor instance@@ -83,10 +85,17 @@ const links = new Set();for ( const { type, item } of editor.model.createRangeIn( editor.model.document.getRoot() ).getWalker() ) {if ( type === 'text' && item.hasAttribute( 'linkHref' ) ) links.add( item.getAttribute( 'linkHref' ) );}++// Trilium: count every admonition in the current note's content:+let count = 0;+for ( const { item } of editor.model.createRangeIn( editor.model.document.getRoot() ).getWalker() ) {+ if ( item.is( 'element', 'admonition' ) ) count++;+}````item.is(...)` is the canonical type check: `is('element', 'name')`, `is('$text')`,-`is('rootElement')`, `is('element')`, etc.+`is('rootElement')`, `is('element')`, etc. This same walk powers footnotes' dynamic dropdown,+which scans the note for existing `footnote` elements each time it opens.## Set an attribute on the editable DOM root@@ -138,14 +147,21 @@ class InternalLink extends Plugin {## Widget: one view element ↔ multiple/nested model elements-Pattern from the how-tos for a form `<input>` ↔ `<forms><formName>…</formName></forms>`:-upcast builds a model sub-structure from a single view element; `editingDowncast` converts+Upcast builds a model sub-structure from a single view element; `editingDowncast` convertseach model element separately (outer → `toWidget`, inner → `toWidgetEditable`); `dataDowncast`-collapses the structure back into one view element, consuming the inner items so other-converters skip them. See the full snippet in the upstream CKEditor 5 "How-tos" docs-(ckeditor.com/docs) and `widgets.md`.+collapses the structure back into one (or a few) view elements, consuming the inner items so+other converters skip them. Trilium's admonition and collapsible plugins are exactly this+shape (a container widget wrapping nested editable content) — see their `*editing.ts` and+`widgets.md` for the full treatment.++## Extend another Trilium plugin's UI++The same `linkUI.formView` pattern above works in Trilium to add an "internal link" button to+the link balloon — Trilium uses it to inject note-link affordances into CKEditor's link form.+Get the upstream plugin via `editor.plugins.get( LinkUI )` and the shared balloon via+`editor.plugins.get( 'ContextualBalloon' )`; both come from `ckeditor5`.-## Framework-integration gotcha+## Build-time gotcha-Building large React apps may hit `JavaScript heap out of memory`; raise Node's heap:-`NODE_OPTIONS="--max-old-space-size=4096" npm run build`.+A large client build can hit `JavaScript heap out of memory`; raise Node's heap for the build+command: `NODE_OPTIONS="--max-old-space-size=4096"`.diff --git a/.claude/skills/ckeditor5-plugin-development/references/review-checklist.md b/.claude/skills/ckeditor5-plugin-development/references/review-checklist.mdindex c95fd66457..c07651ea22 100644--- a/.claude/skills/ckeditor5-plugin-development/references/review-checklist.md+++ b/.claude/skills/ckeditor5-plugin-development/references/review-checklist.md@@ -1,8 +1,9 @@-# Reviewing a CKEditor 5 plugin+# Reviewing a CKEditor 5 plugin (Trilium)-A structured checklist for reviewing existing plugin code. Pair each item with the relevant-reference file when you need the "why". Flag deviations; not every item applies to every-plugin (e.g. a UI-only or editing-only plugin).+A structured checklist for reviewing Trilium CKEditor plugin code under `packages/ckeditor5-*`.+Pair each item with the relevant reference file when you need the "why". Flag deviations; not+every item applies to every plugin (e.g. a UI-only or editing-only plugin). The Trilium+integration items at the end are specific to this monorepo.## Architecture & structure@@ -68,15 +69,42 @@ plugin (e.g. a UI-only or editing-only plugin).## Localization-- [ ] All user-facing strings go through `t()` (named exactly `t` in JS; literal first arg).- Reused strings from other packages use the `locale.t` alias, not `t()`.+- [ ] All user-facing strings go through `editor.t()` with a **literal** first argument (string+ or object literal), never a variable.+- [ ] New strings have matching entries in the plugin's `lang/en.po` (`msgctxt` + `msgid` ++ `msgstr`) **and** `lang/contexts.json` (message id → context). No upstream+ `window.CKEDITOR_TRANSLATIONS` / `add()` / webpack-language wiring.+- [ ] Plugins that accept a host `translate` config read it with the identity fallback+ (`?? ( key => key )`) so labels degrade gracefully (see collapsible).## Conventions & hygiene- [ ] Naming/imports/file names/CSS-BEM/JSDoc/TS rules per `conventions.md`; `CKEditorError`with `@error`.+- [ ] **Imports**: library symbols from `ckeditor5`; cross-package from `@triliumnext/*`; all+ local/relative imports carry **file extensions** (`./foo.js`).+- [ ] **License header** matches the package's existing convention (varies per package — some+ carry the CKSource header, some don't; don't add/strip wholesale).+- [ ] **`pluginName` / `requires`** declared `as const`; type augmentation done via+ `declare module 'ckeditor5'` (config + command/plugin maps).+- [ ] Custom SVG icons imported with `?raw` and re-exported via `export const icons = { … }`+ from `index.ts`.- [ ] Listeners use `this.listenTo()` (auto-cleaned); any other resources cleaned in `destroy()`.-- [ ] `ckeditor5-metadata.json` updated for new public plugins/UI/HTML output (for distributable- packages).+- [ ] `ckeditor5-metadata.json` updated for new public plugins/UI/HTML output.- [ ] Model is the source of truth — no view hacks standing in for model state (except genuineview-only state like focus).++## Trilium integration++- [ ] Plugin registered in `packages/ckeditor5/src/plugins.ts` in the **correct array**+ (package-level plugins like the widget features go in `EXTERNAL_PLUGINS`; in-tree glue+ plugins go in the internal list).+- [ ] Toolbar component name added to+ `apps/client/src/widgets/type_widgets/text/toolbar.ts` (registering the component-factory+ entry alone won't surface it).+- [ ] Works across all three editor classes used by Trilium — `AttributeEditor` (Balloon),+ `ClassicEditor` (Decoupled), `PopupEditor` (Balloon + `BlockToolbar`).+- [ ] Block widgets enforce structural invariants with `registerPostFixer` (admonition,+ collapsible) rather than relying on command-side cleanup.+- [ ] **Tests use the right environment**: happy-dom for unit/model logic; WebdriverIO+ (browser) only where real DOM/layout is required.diff --git a/.claude/skills/ckeditor5-plugin-development/references/tooling-and-packaging.md b/.claude/skills/ckeditor5-plugin-development/references/tooling-and-packaging.mdindex 230cb741fd..581f5534da 100644--- a/.claude/skills/ckeditor5-plugin-development/references/tooling-and-packaging.md+++ b/.claude/skills/ckeditor5-plugin-development/references/tooling-and-packaging.md@@ -1,153 +1,168 @@-# Tooling & packaging+# Tooling & packaging (Trilium)-How to scaffold, build, integrate, and debug a distributable CKEditor 5 plugin package.+How CKEditor 5 plugins are packaged, registered, built, and debugged in the **Trilium+(TriliumNext Notes)** monorepo. This is a pnpm workspace (`[email protected]`, `nodeLinker: hoisted`,+no nx/turbo) with packages under `packages/*` and apps under `apps/*`, org scope `@triliumnext/`.+The CKEditor 5 **library** is an external dependency pinned to `48.2.0`; there is no package+generator here — you add a workspace package (or an in-repo plugin) by hand following the layout+and registration flow below.-## Package generator+## Where the editor lives-Scaffold a publishable `ckeditor5-*` package:+- `packages/ckeditor5` — `@triliumnext/ckeditor5`, the **editor build / aggregator**. `src/index.ts`+ defines the editor classes; `src/plugins.ts` is the plugin registry; built with **Vite**.+- `packages/ckeditor5-{admonition,collapsible,footnotes,keyboard-marker,math,mermaid}` — Trilium's+ custom plugin packages, each `@triliumnext/ckeditor5-<feature>`.+- `apps/client/src/widgets/type_widgets/text/` — the rich-text note widget that instantiates the+ editor (`config.ts`, `CKEditorWithWatchdog.tsx`, `toolbar.ts`).-```bash-npx ckeditor5-package-generator-```+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.-Package name: `ckeditor5-<name>` or `@<scope>/ckeditor5-<name>` (chars `0-9 a-z - . _`).-Options: `--lang js|ts`, `--plugin-name <Name>`, `--global-name <CKName>` (UMD global),-`--package-manager npm|yarn|pnpm`, `--verbose`.+## Plugin package layout (`packages/ckeditor5-<feature>`)-Generated layout:+`package.json`:+```jsonc+{+ "name": "@triliumnext/ckeditor5-<feature>",+ "type": "module",+ "main": "src/index.ts", // ships TS SOURCE — no per-package dist for consumers+ "license": "GPL-2.0-or-later",+ "peerDependencies": { "ckeditor5": "48.2.0" },+ "scripts": {+ "lint": "eslint \"**/*.{js,ts}\" --quiet",+ "stylelint": "stylelint --quiet --allow-empty-input 'theme/**/*.css'",+ "test": "vitest",+ "test:debug": "vitest --inspect-brk --no-file-parallelism --browser.headless=false"+ }+}```-src/ plugin code & public exports (index, *editing, *ui, command…)-sample/ local Vite sample app (npm run start)-tests/ Vitest unit tests-theme/ icons & CSS-lang/ translation context + *.po files-scripts/ helper scripts (translation sync)-ckeditor5-metadata.json-vite.config.[js|ts]-# TS only: src/augmentation.ts, tsconfig.json, tsconfig.build.json, typings/-```-npm scripts: `start` (Vite sample + live reload), `test`, `test:debug`, `lint`, `build`-(npm + browser outputs to `dist/`), `translations:synchronize`, `translations:validate`.+The app bundles each plugin's TS source via Vite, so **there is no published `dist/` for+consumers**. An optional `dist/` "NIM build" (the upstream new-installation-method output) may be+generated for standalone use but is **gitignored and eslint-ignored** — never import from it inside+the monorepo.++Config files (one set per package):++- `tsconfig.json` — `composite: true`, `target: es2019`, `strict`, `module/moduleResolution:+ NodeNext`; plus `tsconfig.test.json` for tests.+- `vitest.config.ts` — Vitest (browser mode; see the `ckeditor5-testing` skill).+- `eslint.config.js` — `eslint-config-ckeditor5` + `eslint-plugin-ckeditor5-rules`.+- `stylelint-config-ckeditor5` for theme CSS.-## TypeScript augmentation (`src/augmentation.ts`)+`src/` files: `{feature}.ts` (glue), `{feature}editing.ts`, `{feature}ui.ts`, optional+`{feature}command.ts`, `augmentation.ts`, `index.ts`. Complex plugins add `constants.ts`+(`ELEMENTS`/`ATTRIBUTES`/`COMMANDS`/`CLASSES`), `utils.ts` (model-query helpers), and split+`schema.ts`/`converters.ts`. Assets: `theme/{feature}.css`, `theme/icons/*.svg`, `lang/en.po`+(gettext) + `lang/contexts.json`, `tests/`. License and file headers vary per package — see+`references/conventions.md`.-Register your plugin/config/commands into CKEditor's type maps so consumers get typing:+`index.ts` re-exports the glue plugin, its sub-plugins and command types, and exposes icons:```ts-import type { MyPlugin } from './index.js';-declare module '@ckeditor/ckeditor5-core' {- interface PluginsMap { [ MyPlugin.pluginName ]: MyPlugin; }- // also augment EditorConfig (for config) and CommandsMap (for typed commands)-}+import fooIcon from '../theme/icons/foo.svg?raw';+export { default as Foo } from './foo.js';+export { default as FooEditing } from './fooediting.js';+export { default as FooUI } from './fooui.js';+export const icons = { fooIcon };```-## Build output & integration+## Registration flow — how a plugin reaches the editor-`npm run build` emits:+Four steps:-```-dist/index.js npm ESM entry (ckeditor5 is external)-dist/index.css CSS for npm consumers-dist/*.d.ts type declarations-dist/browser/index.es.js browser ESM (needs ckeditor5 provided via import map)-dist/browser/index.umd.js browser UMD (exposes the --global-name; needs CKEDITOR global)-dist/browser/index.css CSS for ZIP/CDN-```+1. **Workspace dependency.** Add the package to `packages/ckeditor5/package.json`:+ `"@triliumnext/ckeditor5-<feature>": "workspace:*"`.+2. **Register in `packages/ckeditor5/src/plugins.ts`.** Import the plugin and add it to one of the+ arrays:+ - `CORE_PLUGINS` — the minimal set shared by every editor (incl. the attribute editor).+ - `TRILIUM_PLUGINS` — in-repo plugins living under `packages/ckeditor5/src/plugins/`.+ - `EXTERNAL_PLUGINS` — the workspace `@triliumnext/ckeditor5-*` packages.-Consume via npm:+ `TRILIUM_PLUGINS` + `EXTERNAL_PLUGINS` (and the rest) compose into `COMMON_PLUGINS`;+ `POPUP_EDITOR_PLUGINS` = `COMMON_PLUGINS` + `BlockToolbar`.-```js-import { ClassicEditor, Essentials, Paragraph } from 'ckeditor5';-import { MyPlugin } from '<package>';-import 'ckeditor5/ckeditor5.css';-import '<package>/index.css';-ClassicEditor.create( { /* plugins: [ Essentials, Paragraph, MyPlugin ] */ } );-```+ ```ts+ import { Footnotes } from '@triliumnext/ckeditor5-footnotes';+ const EXTERNAL_PLUGINS: typeof Plugin[] = [ Kbd, Mermaid, Admonition, Collapsible, Footnotes, Math, AutoformatMath ];+ ```+3. **Editor classes pick it up automatically.** The classes in `packages/ckeditor5/src/index.ts`+ expose those arrays via `static get builtinPlugins()`, so adding to the array is enough — no+ per-class edit needed (unless the plugin is editor-specific).+4. **Toolbar.** Add the component name (the `componentFactory` key) to Trilium's toolbar config,+ `apps/client/src/widgets/type_widgets/text/toolbar.ts`.-For browser (no bundler): use import maps with `dist/browser/index.es.js`, or UMD `<script>`-tags where the editor is on `CKEDITOR` and your plugin on its global name. CDN integration-follows the same browser patterns. (Note: CDN/commercial builds aren't GPL — they need a-commercial license key; the `'GPL'` key only works for self-hosted/source usage.)+If a plugin only contributes type augmentation (e.g. config types) it may also be `import`ed for+side effects in `packages/ckeditor5/src/index.ts` (see the math/mermaid side-effect imports).-## Package metadata (`ckeditor5-metadata.json`)+## The three editor classes (`packages/ckeditor5/src/index.ts`)-Lives at the package root; lets external tooling (CKEditor Builder, the plugins/HTML-output-pages) discover plugins, UI components, and HTML output. Document **major** plugins only (not-the internal editing/UI split classes).+| Class | Base | Plugins | Role |+|-------|------|---------|------|+| `AttributeEditor` | `BalloonEditor` | `CORE_PLUGINS` | Editing attribute/relation values (minimal). |+| `ClassicEditor` | `DecoupledEditor` | `COMMON_PLUGINS` | The main text-note editor; decoupled (fixed) toolbar. |+| `PopupEditor` | `BalloonEditor` | `POPUP_EDITOR_PLUGINS` (+`BlockToolbar`) | Floating-toolbar text editor. |-```json-{- "plugins": [ {- "name": "Display Name",- "className": "MyPlugin",- "description": "Short description.",- "docs": "path/to/docs.html",- "path": "src/index.js",- "requires": [ "OtherPlugin", [ "Plugin1", "Plugin2" ] ],- "registeredToolbars": [ "myFeature.toolbar" ],- "uiComponents": [- { "name": "myButton", "type": "Button", "iconName": "IconBold", "toolbars": [ "toolbar" ] }- ],- "htmlOutput": [- { "elements": "span", "classes": "my-class", "styles": "color", "attributes": "data-*", "implements": "$inlineObject", "isAlternative": false }- ]- } ]-}-```+Premium plugins are **not** in the static arrays — they are loaded lazily via+`loadPremiumPlugins()` (dynamic `import('ckeditor5-premium-features')` plus its CSS), which keeps+~6s of premium code out of initial startup. `_setModelData`/inspector aside, all symbols come from+the `ckeditor5` aggregate.-Field notes: `requires` nested arrays mean "at least one of"; `uiComponents[].type` is-`Button` | `SplitButton` | `Dropdown`; `iconName` is an export from `@ckeditor/ckeditor5-icons`;-`htmlOutput.implements` lists an inherited pseudo-element; `isAlternative: true` marks config--dependent (non-default) output.+## Vite build-## CKEditor 5 Inspector+`packages/ckeditor5` builds with Vite (`vite.config.ts`); `vitest.config.ts` drives tests. Because+plugin packages expose `main: src/index.ts`, the aggregator and ultimately `apps/client` compile+the plugin TS sources directly through the bundler — there is no intermediate per-package build to+keep in sync. `src/index.ts` imports `ckeditor5/ckeditor5.css` and the Trilium theme CSS.-Indispensable debugging tool — shows the live **model**, **view**, **schema**, **commands**,-and selection.+## How the client creates the editor-```bash-npm install --save-dev @ckeditor/ckeditor5-inspector-```+`apps/client/src/widgets/type_widgets/text/`:-```js-import CKEditorInspector from '@ckeditor/ckeditor5-inspector';-ClassicEditor.create( /* … */ ).then( editor => {- CKEditorInspector.attach( editor );- // or named: CKEditorInspector.attach( { 'header-editor': editor } );-} );-```--There's also a bookmarklet that injects the inspector without code changes (won't work under a-strict CSP).+- `config.ts` builds the `EditorConfig` (toolbar from `toolbar.ts`, language, feature config such as+ `syntaxHighlighting`, `moveBlockUp/Down`, mention feeds, 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.+- Premium features are pulled in lazily through `loadPremiumPlugins()` only when needed.+- The client picks `ClassicEditor` (fixed toolbar) or `PopupEditor` (floating) per the note's+ editing mode; `AttributeEditor` is used elsewhere for attribute/relation inputs.-## Custom editor creator (advanced)+## CKEditor 5 Inspector-To build a non-standard editor, implement three classes:+Indispensable debugging tool — shows the live **model**, **view**, **schema**, **commands**, and+selection. It is already a `devDependency` of the plugin packages.-- **Editor** — extends `Editor`. Protected constructor sets up roots/model; static async- `create(config)` chains `initPlugins()` → `ui.init()` → `data.init()` → fire `ready` and- resolve with the instance; `destroy()` caches data, destroys UI, restores DOM.-- **EditorUI** — extends `EditorUI`. `init()` renders the view, wires focus tracking, attaches- editables to the editing view (`attachDomRoot()`), inits placeholder + toolbar- (`_initToolbar()` → `addToolbar()`); `destroy()` calls `detachDomRoot()`.-- **EditorUIView** — extends `EditorUIView`. Builds the `ToolbarView` and one- `InlineEditableUIView` per editable; `render()` registers children.+```ts+import CKEditorInspector from '@ckeditor/ckeditor5-inspector';+// after the editor promise resolves:+CKEditorInspector.attach( editor );+// or named: CKEditorInspector.attach( { 'note-editor': editor } );+```-Helpers: `getDataFromElement()`, `setDataInElement()`, `enableViewPlaceholder()`. Most plugin-work never needs this — only when you need a fundamentally different editor shell (e.g. a-multiroot editor).+`@ckeditor/ckeditor5-inspector` (and `@ckeditor/ckeditor5-icons`) are the only `@ckeditor/*` deep+imports allowed in Trilium code; everything else imports from the `ckeditor5` aggregate. There is+also a bookmarklet that injects the inspector without code changes (blocked under a strict CSP).-## Contributing to the ckeditor5 monorepo+## Per-package commands-Requires Node ≥ 24.11.0, pnpm ≥ 10.17.0, Git.+Run scripts through the pnpm workspace filter:```bash-git clone https://github.com/ckeditor/ckeditor5.git && cd ckeditor5-pnpm install-pnpm run test -- -wcs --files=engine # watch + coverage + source-map, one package-pnpm run manual # manual test server-pnpm run docs && pnpm run docs:serve # build & serve docs-npm run clean-up-svg-icons path/to/*.svg # optimize icons (SVGO)+pnpm --filter @triliumnext/ckeditor5-<feature> test # vitest+pnpm --filter @triliumnext/ckeditor5-<feature> test:debug # vitest, headed + inspector+pnpm --filter @triliumnext/ckeditor5-<feature> lint # eslint-config-ckeditor5+pnpm --filter @triliumnext/ckeditor5-<feature> stylelint # theme CSS```++For test setup, model/view assertions, and command/UI test patterns, use the separate+**`ckeditor5-testing`** skill.++## Scope++Paths here (`packages/ckeditor5`, `packages/ckeditor5-<feature>`, `apps/client/...`) are **this+Trilium repository**. The CKEditor 5 library mechanics referenced (editor bases `BalloonEditor`/+`DecoupledEditor`, `EditorConfig`, the watchdog, premium features) come from the external `ckeditor5`+/ `ckeditor5-premium-features` packages at `48.2.0`.diff --git a/.claude/skills/ckeditor5-plugin-development/references/ui-and-localization.md b/.claude/skills/ckeditor5-plugin-development/references/ui-and-localization.mdindex 8cd5656e06..69f5292e4d 100644--- a/.claude/skills/ckeditor5-plugin-development/references/ui-and-localization.md+++ b/.claude/skills/ckeditor5-plugin-development/references/ui-and-localization.md@@ -1,8 +1,12 @@-# UI library & localization+# UI library & localization (Trilium)-The UI library (`@ckeditor/ckeditor5-ui`) is a small MVC: **Views** render DOM via-**Templates**, expose **observable** properties, and are organized into **collections** that-form the UI tree. Features talk to views through observables — never the native DOM directly.+In the Trilium monorepo every CKEditor plugin (`packages/ckeditor5-*`) builds its UI with the+library's UI layer, imported from `ckeditor5` (pinned 48.2.0). It is a small MVC: **Views**+render DOM via **Templates**, expose **observable** properties, and are organized into+**collections** that form the UI tree. Features talk to views through observables — never the+native DOM directly. Trilium's text editor runs as one of three classes — `AttributeEditor`+(Balloon), `ClassicEditor` (Decoupled), `PopupEditor` (Balloon + `BlockToolbar`) — but a+plugin's views are identical across all three; only the toolbar host differs.## Views & templates@@ -55,19 +59,25 @@ class MyPlugin extends Plugin {## Registering toolbar components-Register every toolbar/UI component in the **component factory**; the user references the name-in their `toolbar` config:+Register every toolbar/UI component in the **component factory** under a name; that name is+then listed in Trilium's toolbar config at+`apps/client/src/widgets/type_widgets/text/toolbar.ts` (not an end-user config):-```js-editor.ui.componentFactory.add( 'myButton', locale => {+```ts+editor.ui.componentFactory.add( 'admonition', locale => {const button = new ButtonView( locale );- button.set( { label: editor.t( 'My button' ), withText: true } );- button.on( 'execute', () => { editor.execute( 'myCommand' ); editor.editing.view.focus(); } );+ button.set( { label: editor.t( 'Admonition' ), icon: admonitionIcon, tooltip: true } );+ button.on( 'execute', () => { editor.execute( 'admonition' ); editor.editing.view.focus(); } );return button;} );-// user config: toolbar: [ 'myButton' ]+// toolbar.ts then references: 'admonition'```+A registered name only appears in the editor when it is added to `toolbar.ts`; registering the+component factory entry alone is not enough. Real examples: the admonition button/dropdown+(`packages/ckeditor5-admonition/src/admonitionui.ts`), the footnotes insert button + dynamic+"insert existing footnote" dropdown (`packages/ckeditor5-footnotes/src/footnote-ui.ts`).+**Best practice:** on any user action (button/dropdown execute), call`editor.editing.view.focus()` so the editor keeps focus.@@ -90,16 +100,28 @@ editor.ui.componentFactory.add( 'myButton', locale => {## Icons-Import from the bundle (sourced from `@ckeditor/ckeditor5-icons`) and assign to a view's-`icon`/`content`:+Built-in icons come from the bundle and assign to a view's `icon`/`content`:-```js+```tsimport { IconBold, IconCheck, IconCancel, IconQuote } from 'ckeditor5';button.set( { icon: IconBold } );```-Custom icons: pass the full SVG XML string. For a recolorable icon, strip `fill`/`stroke`-attributes from the SVG.+For a **custom** icon, Trilium plugins import the raw SVG XML string with the `?raw` suffix,+keep the file under `theme/icons/`, and re-export an `icons` map from `index.ts` (so the+aggregator can collect them):++```ts+// index.ts+import admonitionIcon from '../theme/icons/admonition.svg?raw';+export const icons = { admonitionIcon };++// admonitionui.ts+button.set( { icon: admonitionIcon } ); // the raw SVG string+```++`icon` accepts the full SVG XML string. For a recolorable icon, strip `fill`/`stroke`+attributes from the SVG so it inherits `currentColor`.## Dropdowns@@ -134,6 +156,12 @@ addMenuToDropdown( dropdown, editor.body.ui.view, [Even when `withText` is false, set `label` for screen readers.+In Trilium, the admonition type picker is a list dropdown built from `ADMONITION_TYPES`+(`packages/ckeditor5-admonition/src/admonitionui.ts`), and footnotes builds its list+dynamically from the footnotes already present in the note+(`packages/ckeditor5-footnotes/src/footnote-ui.ts`) — re-reading the model each time the+dropdown opens.+## Contextual balloonFor floating forms/toolbars pinned to the selection, use the `ContextualBalloon` plugin@@ -237,30 +265,60 @@ button.set( { /* … */ keystroke: 'Ctrl+Alt+H' } ); // shows in tooltiKeys map to platform conventions automatically (e.g. `Ctrl` → `Cmd` on macOS).-## Localization with `t()`+## Localization with `editor.t()`-Every user-facing string must pass through the `t()` function so it can be translated.+Every user-facing string must pass through the editor's translation function so it can be+localized. Trilium ships translations as **gettext PO files per package** — not the upstream+`window.CKEDITOR_TRANSLATIONS` / `add()` / webpack-bundled-language flow.-- Get it from the locale: `const { t } = editor.locale;` or `const t = editor.t;` or, in a- view, `const t = this.t;`. (`editor.locale.t` is also `editor.t`.)-- **Static-analysis constraints:** in **JS files** the analyzer only recognizes a function- named exactly `t()` — don't rename it or call `locale.t()` directly. In **TS files** direct- `Locale#t()` calls (`editor.t()`, `locale.t()`, `this.t()`) are also recognized. The first- arg must be a **string or object literal** — never a variable.+- Get the function from the editor/locale: `const t = editor.t;`, `const { t } = editor.locale;`,+ or in a view `const t = this.t;` (`editor.locale.t` is the same function as `editor.t`).+- **First arg must be a string or object literal**, never a variable — the build scans source+ for these literals to extract message ids.-```js-t( 'Insert emoji' ); // simple-t( 'Insert %0 emoji', emojiName ); // placeholder; array also ok-t( { string: '%0 emoji', plural: '%0 emojis', id: 'N_EMOJIS' }, quantity ); // plural; first value = quantity-t( { string: '%0 emoji', id: 'ACTION_EMOJI' }, 'insert' ); // disambiguating id+```ts+const t = editor.t;+t( 'Admonition' ); // simple+t( 'Insert %0', label ); // placeholder; array also ok+t( { string: '%0 footnote', plural: '%0 footnotes', id: 'N_FOOTNOTES' }, quantity ); // plural+t( { string: '%0', id: 'ACTION_INSERT' }, 'insert' ); // disambiguating id+```++### Where translations live++Each Trilium plugin keeps two files under `lang/`:++- **`lang/en.po`** — the gettext catalog. Each entry is `msgctxt` (translator context) ++ `msgid` (the source string passed to `t()`) + `msgstr` (the translation):++ ```po+ msgctxt "Toolbar button tooltip for the Admonition feature."+ msgid "Admonition"+ msgstr "Admonition"+ ```++- **`lang/contexts.json`** — maps each message id to a short context string for translators+ (mirrors the `msgctxt`):++ ```json+ { "Admonition": "Toolbar button tooltip for the Admonition feature." }+ ```++When you add a new `t( '…' )` string, add a matching `msgid`/`msgctxt`/`msgstr` block to+`en.po` and an entry to `contexts.json`. See `packages/ckeditor5-admonition/lang/` for the+canonical pair.++### Custom `translate` config fallback++Some Trilium plugins (e.g. collapsible) also accept a `translate` function via editor config,+falling back to the identity function so the string is used verbatim when none is supplied:++```ts+const translate = ( editor.config.get( 'translate' ) as+ ( ( key: string, params?: Record<string, unknown> ) => string ) | undefined )+ ?? ( ( key: string ) => key );```-- **Reuse a translation** from another package without creating a new source message by- aliasing the locale function: `const translateVariableKey = editor.locale.t;`- `translateVariableKey( 'Block quote' )` reuses; `t( 'Create a block quote' )` is a new message.-- Ship translations as `.po` files in `lang/translations/` (preferred for packages — bundles- only needed languages), or at runtime via the `add()` helper / `window.CKEDITOR_TRANSLATIONS`- (extend with `Object.assign` to avoid clobbering). New languages need a `getPluralForm()`.-- Limitations: language can't change at runtime without re-creating the editor; the webpack- plugin bundles one language at a time. Third-party packages localizing via `.po` must- override `sourceFilesPattern`/`packageNamePattern` so the build tool scans their code.+See `packages/ckeditor5-collapsible/src/collapsible-ui.ts` and `collapsible-editing.ts`. This+is independent of `editor.t()`/PO catalogs — it lets the host (Trilium) inject its own+translator for plugin-specific labels.diff --git a/.claude/skills/ckeditor5-plugin-development/references/widgets.md b/.claude/skills/ckeditor5-plugin-development/references/widgets.mdindex 5950afe139..2481ec02ee 100644--- a/.claude/skills/ckeditor5-plugin-development/references/widgets.md+++ b/.claude/skills/ckeditor5-plugin-development/references/widgets.md@@ -2,16 +2,26 @@A **widget** is a model element rendered in the editing view with widget behavior: clickableto select, copy/paste/delete as a unit, hover/focus outlines, and optional **nested editable**-regions. The widget system lives partly in the engine and partly in `@ckeditor/ckeditor5-widget`.+regions. The widget system ships in `ckeditor5` (engine + widget layer); import everything+from `ckeditor5`.++In the Trilium monorepo the live examples are:+- **admonition** (`packages/ckeditor5-admonition`) and **collapsible**+ (`packages/ckeditor5-collapsible`) — block widgets with nested editable content, schema+ invariants enforced by `registerPostFixer`.+- **math** (`packages/ckeditor5-math`, KaTeX) and **mermaid** (`packages/ckeditor5-mermaid`) —+ external/async-rendered widgets (see the dedicated section below).Two flavors:-- **Block widget** — `inheritAllFrom: '$blockObject'` (e.g. a box, block image, table).+- **Block widget** — `inheritAllFrom: '$blockObject'` (admonition box, collapsible, block+ image, table).- **Inline widget** — `inheritAllFrom: '$inlineObject'` (text-like; lives where `$text` isallowed, e.g. a placeholder/merge-field).Both follow the standard editing/UI/glue split (see SKILL.md). The editing plugin must`static get requires() { return [ Widget ]; }` — without the `Widget` plugin the view gets-widget classes but no behavior (clicking won't select).+widget classes but no behavior (clicking won't select). Local imports use file extensions+(`./admonitionediting.js`); library symbols come from `ckeditor5`.## Inline widget recipe (placeholder)@@ -146,6 +156,16 @@ function createSimpleBox( writer ) {// refresh(): isEnabled = schema.findAllowedParent( selection.getFirstPosition(), 'simpleBox' ) !== null;```+**Trilium block widgets — schema invariants via post-fixers.** Admonition and collapsible use+`inheritAllFrom: '$blockObject'` (+ `isLimit` on the nested editable) exactly as above, and+additionally guard structural invariants with `editor.model.document.registerPostFixer(...)` —+fixers that run after every change to repair illegal states (e.g. ensure the required child+exists, drop empties, prevent disallowed nesting). Collapsible registers several such fixers+(its `collapsible-editing.ts` wires multiple invariants); admonition does the same in+`admonitionediting.ts`. A post-fixer returns `true` if it made a change (to re-run the cycle).+Prefer post-fixers over command-side cleanup so the document stays valid no matter how the+change originated (paste, undo, collaboration).+## Widget attributes (e.g. a boolean toggle)Add to schema (`allowAttributes: [ 'secret' ]`), convert with the two-way@@ -181,14 +201,19 @@ class SimpleBoxToolbar extends Plugin {// !!viewElement.getCustomProperty('simpleBox') && isWidget(viewElement).```-This is the same mechanism images/tables use to show their contextual toolbars.+This is the same mechanism images/tables use to show their contextual toolbars. In Trilium,+mermaid registers its widget toolbar this way (`packages/ckeditor5-mermaid/src/mermaidtoolbar.ts`),+hosting the source/preview/split-mode buttons.-## External / async-rendered widgets (math, diagrams, charts)+## External / async-rendered widgets (math, mermaid)-Widgets that render the output of an external library (KaTeX, Mermaid, a charting lib, a code-highlighter) need a few patterns beyond the static-widget basics. The model stores the **source**-(e.g. a LaTeX string or diagram code) as an attribute; the **data downcast** emits that source as-plain markup (so `getData()` is clean and re-parseable), while the **editing downcast** renders it.+Trilium's **math** (KaTeX, `packages/ckeditor5-math`) and **mermaid**+(`packages/ckeditor5-mermaid`) plugins are the real-world references for this section. Widgets+that render the output of an external library need a few patterns beyond the static-widget+basics. The model stores the **source** (the LaTeX string / mermaid diagram code) as an+attribute; the **data downcast** emits that source wrapped in plain markup (so `getData()` is+clean and re-parseable — see the data-processor note below), while the **editing downcast**+renders it via KaTeX/Mermaid.**Host the rendered output in a UI element.** A `UIElement`'s render callback runs in the realDOM and is the hook for injecting external output into the editing view (UI elements are filtered@@ -238,11 +263,14 @@ async renderInto( domEl, source ) {```**Lazy-load the library once.** Cache the load promise so a heavy dependency loads on first use-and initializes a single time (drive it from config so the host app can supply the loader):--```js-this._libPromise ??= Promise.resolve( editor.config.get( 'diagram.lazyLoad' )() )- .then( lib => { lib.initialize( editor.config.get( 'diagram.config' ) ); return lib; } );+and initializes a single time, driven from config so Trilium can supply the loader. Math reads+`mathConfig.lazyLoad` (and `mathConfig.katexRenderOptions`) from `editor.config`+(`packages/ckeditor5-math/src/mathediting.ts`, `mathui.ts`); the augmentation in+`augmentation.ts` types the config shape via `declare module 'ckeditor5'`:++```ts+this._libPromise ??= Promise.resolve( editor.config.get( 'math.lazyLoad' )() )+ .then( lib => { lib.initialize( editor.config.get( 'math.config' ) ); return lib; } );const lib = await this._libPromise;```@@ -251,9 +279,17 @@ in the widget, wrap that element so the editor's own keystroke/selection handlerinput — give the container the `data-cke-ignore-events` attribute. Debounce the input handler thatwrites back to the model (`editor.model.change(...)`).-**Mode / state machine.** For source/preview/split toggles, store a `displayMode` attribute, expose-commands that set it, render different DOM per mode in the editing downcast, and bind the-widget-toolbar buttons' `isOn` to each command's value so they reflect the current mode.+**Mode / state machine.** For source/preview/split toggles, store a display-mode attribute,+expose one command per mode that sets it, render different DOM per mode in the editing+downcast, and bind the widget-toolbar buttons' `isOn` to each command's value so they reflect+the current mode. Mermaid is exactly this: separate `mermaidSourceViewCommand`,+`mermaidPreviewCommand`, and `mermaidSplitViewCommand`+(`packages/ckeditor5-mermaid/src/commands/`) drive the mode, surfaced through the widget+toolbar from `mermaidtoolbar.ts`.++**Pre-process input with a data processor.** To accept the raw source on load, wrap/transform+it in a data-processor step so upcast sees a converter-friendly shape; mermaid does this in its+editing setup so a fenced/diagram block round-trips cleanly through `getData()`.## Useful widget utilities@@ -261,8 +297,12 @@ widget-toolbar buttons' `isOn` to each command's value so they reflect the curre`WidgetToolbarRepository`, plus engine helpers `model.insertObject`, `model.insertContent`,`writer.setCustomProperty`, `selection.getSelectedElement()`, `position.findAncestor(name)`.-If you attach custom DOM event handlers inside a widget, wrap them in a container with the-`data-cke-ignore-events` attribute so the editor's default handlers skip them. Advanced-behaviors are covered by the engine's "widget internals" deep dive. There are also tutorials-for **data from an external source** and **using React in a widget** if your widget needs-async content or framework components.+If you attach custom DOM event handlers inside a widget (or an editable source field), wrap+them in a container with the `data-cke-ignore-events` attribute so the editor's default+handlers skip them — math/mermaid use this around their source inputs.++**Registering a new widget plugin in Trilium.** A new plugin is wired in two places: add it to+the correct array in `packages/ckeditor5/src/plugins.ts` (e.g. `EXTERNAL_PLUGINS` for the+package-level plugins like `Mermaid`, `Admonition`, `Collapsible`, `Footnotes`, `Math`), and+add its toolbar component name to `apps/client/src/widgets/type_widgets/text/toolbar.ts`.+Files use `declare module 'ckeditor5'` augmentation for config and command typings.diff --git a/.claude/skills/ckeditor5-reviewing/SKILL.md b/.claude/skills/ckeditor5-reviewing/SKILL.mdindex b1ad1c06c9..1b2b8984f2 100644--- a/.claude/skills/ckeditor5-reviewing/SKILL.md+++ b/.claude/skills/ckeditor5-reviewing/SKILL.md@@ -1,67 +1,105 @@---name: ckeditor5-reviewingdescription: >-- Review or audit CKEditor 5 plugin/feature code or a PR/diff. Use when checking- a CKEditor 5 plugin for correctness and idiom: schema / conversion / command /- UI / widget code, and CKEditor-specific defects (asymmetric upcast/downcast,- unconsumed upcast elements, missing inline-widget position mapping, command- refresh/isEnabled bugs, memory leaks, t() gaps, editing/UI split violations,- post-v42 import mistakes). Pairs with the ckeditor5-plugin-development and+ Review or audit CKEditor 5 plugin code in the Trilium (TriliumNext Notes)+ monorepo, or a PR/diff touching packages/ckeditor5-* or the packages/ckeditor5+ build. Use when checking a Trilium CKEditor 5 plugin for correctness and idiom:+ schema / conversion / command / UI / widget code, CKEditor-specific defects+ (asymmetric upcast/downcast, unconsumed upcast elements, missing inline-widget+ position mapping, command refresh/isEnabled bugs, memory leaks, t() gaps,+ editing/UI split violations), and Trilium integration defects (plugin not+ registered in plugins.ts, button missing from toolbar.ts, import/file-extension+ lint failures, wrong augmentation module, .po localization gaps, wrong test+ environment). Pairs with the ckeditor5-plugin-development andckeditor5-testing skills and delegates their checklists.----# Reviewing CKEditor 5 plugins+# Reviewing CKEditor 5 plugins in Trilium-A workflow and defect catalog for **reviewing** CKEditor 5 plugin/feature code — a distinct task-from writing it. This skill orchestrates the review and hunts CKEditor-specific bugs; it-**delegates the per-dimension "is this idiomatic?" checklists** to the companion skills rather-than duplicating them:+A workflow and defect catalog for **reviewing** CKEditor 5 plugin code in the Trilium monorepo — a+distinct task from writing it. This skill orchestrates the review and hunts both CKEditor-specific+and Trilium-integration bugs; it **delegates the per-dimension "is this idiomatic?" checklists** to+the companion skills rather than duplicating them:- **`ckeditor5-plugin-development`** — its `references/review-checklist.md` (architecture, schema,conversion, commands, UI, a11y) and `references/conventions.md` (naming, imports, JSDoc, TS).-- **`ckeditor5-testing`** — its review checklist and patterns for the test side.+- **`ckeditor5-testing`** — its review checklist and patterns for the test side (Vitest, happy-dom+ vs. `@vitest/browser-webdriverio` browser mode, real `ClassicEditor.create`).Use those for "does this follow the conventions"; use this skill for **how to drive the review**and **what subtle things tend to be wrong**.+## Scope & sources++This skill reviews **CKEditor 5 plugin code in the Trilium monorepo** (scope `@triliumnext/`). The+CKEditor 5 library itself is the **external `ckeditor5` dependency pinned at 48.2.0** — its docs+([ckeditor.com/docs](https://ckeditor.com/docs)) and source+([github.com/ckeditor/ckeditor5](https://github.com/ckeditor/ckeditor5)) are *external references*,+not the code under review. The Trilium plugins live in `packages/ckeditor5-{admonition,collapsible,+footnotes,keyboard-marker,math,mermaid}`; they are assembled by the build/aggregator package+`packages/ckeditor5` and wired into the editor UI from `apps/client`.+## When to use-Reviewing a PR or diff that touches a CKEditor 5 plugin; auditing an existing plugin; sanity--checking your own feature before opening a PR. For *writing* the feature, use+Reviewing a PR or diff that touches a Trilium CKEditor 5 plugin (`packages/ckeditor5-*`), the+aggregator (`packages/ckeditor5`), or the toolbar config in `apps/client`; auditing an existing+plugin; sanity-checking your own feature before opening a PR. For *writing* the feature, use`ckeditor5-plugin-development`; for *writing tests*, use `ckeditor5-testing`.## Review workflow-1. **Scope the diff.** What surface changed — editing (schema/conversion/command), UI- (componentFactory/buttons/dropdowns/balloons), a widget, an editor type, config? New plugin or- a change to an existing one? Which package(s)? This tells you which checklists and defect- groups apply.+1. **Scope the diff against Trilium's structure.** What surface changed — editing+ (schema/conversion/command), UI (componentFactory/buttons/dropdowns/balloons), a widget, config?+ Which Trilium plugin package (`packages/ckeditor5-<x>`)? Does it also touch the aggregator+ (`packages/ckeditor5/src/plugins.ts`, `src/index.ts`) or the toolbar+ (`apps/client/src/widgets/type_widgets/text/toolbar.ts`)? This tells you which checklists, defect+ groups, and integration checks apply.2. **Read model-first.** The model is the source of truth; trace the feature in order**schema → conversion → command → UI**. Confirm each layer is present and consistent (e.g. anew model element has a schema registration *and* upcast *and* downcast *and* an insertion path).-3. **Run the tests** for the affected code (see `ckeditor5-testing`). Coverage ≠ correctness:- confirm the *change itself* is tested, not just that lines are hit. A bug fix with no- new/changed test is a red flag even when coverage stays green.-4. **Observe behavior.** Attach the CKEditor Inspector (model / view / schema / commands), then:+3. **Check registration & wiring (Trilium-specific).** A correct plugin that nobody loads is still+ broken. Confirm:+ - the plugin is exported and added to the right array in `packages/ckeditor5/src/plugins.ts`+ (`CORE_PLUGINS` / `TRILIUM_PLUGINS` / `EXTERNAL_PLUGINS` → `builtinPlugins`) so it actually+ loads into the editor classes in `packages/ckeditor5/src/index.ts` (AttributeEditor[Balloon],+ ClassicEditor[Decoupled], PopupEditor[Balloon]);+ - any new toolbar component is added to `apps/client/src/widgets/type_widgets/text/toolbar.ts`,+ otherwise the button never appears even though the plugin loaded.+4. **Check conventions (Trilium-specific).** Imports come from the `ckeditor5` aggregate (or+ cross-plugin `@triliumnext/ckeditor5-<x>`) **with explicit file extensions**; augmentation uses+ `declare module 'ckeditor5'` (never `@ckeditor/ckeditor5-core`); any license header matches the+ package's existing convention (it's not uniform across packages); new UI strings are in+ `lang/en.po` + `lang/contexts.json`. These are enforced by `eslint-config-ckeditor5`+ (`require-file-extensions-in-imports`, `allow-imports-only-from-main-package-entry-point`,+ `no-legacy-imports`) and `stylelint-config-ckeditor5` — a diff that breaks them fails lint.+5. **Run the tests for the affected package.** Use Vitest via+ `pnpm --filter @triliumnext/ckeditor5-<f> test` (math + mermaid run sequentially). Note the test+ environment: admonition/collapsible use **happy-dom**; math/mermaid/footnotes/keyboard-marker use+ **`@vitest/browser-webdriverio` browser mode** (NOT Playwright). Coverage ≠ correctness: confirm+ the *change itself* is tested, not just that lines are hit. A bug fix with no new/changed test is+ a red flag even when coverage stays green.+6. **Observe behavior.** Attach the CKEditor Inspector (model / view / schema / commands), then:round-trip `editor.getData()` → `setData()` (does content survive a save?); exercise selectionedge cases (collapsed vs. ranged, inside objects/limits, at attribute boundaries); toggleread-only.-5. **Apply the dimension checklists** (delegate to the two companion skills).-6. **Hunt defects** with `references/defect-patterns.md` — the high-value, easy-to-miss failure- modes specific to CKEditor.-7. **Verify each finding before reporting it** (see below). Reproduce it, or cite the exact line+7. **Apply the dimension checklists** (delegate to the two companion skills).+8. **Hunt defects** with `references/defect-patterns.md` — the high-value, easy-to-miss failure+ modes (CKEditor-general + Trilium integration).+9. **Verify each finding before reporting it** (see below). Reproduce it, or cite the exact lineand the rule it breaks. Discard the ones that don't hold up.-8. **Report** findings: severity-tagged, `file:line`, with the concrete fix or question.+10. **Report** findings: severity-tagged, `file:line`, with the concrete fix or question.## Triage / severity- **Blocker** — data loss (content dropped on `getData()`), crashes/console errors, undo- corruption, broken collaboration (non-OT model mutation), security (unsanitized HTML/XSS),- schema corruption.+ corruption, security (unsanitized HTML/XSS), schema corruption; **plugin not registered in+ `plugins.ts`** (feature silently never loads).- **Major** — incorrect behavior in real selections, accessibility gaps (no keyboard path, missing- labels/`addKeystrokeInfos`), memory leaks, command enabled where the schema disallows it.-- **Minor** — convention/naming/import-style issues, missing `t()`, redundant converters,- non-idiomatic but working code.+ labels/`addKeystrokeInfos`), memory leaks, command enabled where the schema disallows it; **button+ missing from `toolbar.ts`**; **lint-failing imports** (missing file extension / wrong package /+ legacy `@ckeditor/*`) that block the build.+- **Minor** — convention/naming issues, missing `t()`, missing `lang/en.po` entries, redundant+ converters, non-idiomatic but working code.- **Nit** — style preferences with no behavioral impact; mark them as optional.Lead with blockers/majors; don't bury them under nits.@@ -79,6 +117,11 @@ positives** to *not* raise:- "Boolean attribute should be set to `false`" — the idiom is to **remove** it (yields `undefined`).- "Button state not updated" when it's `bind()`-ed to the command (reactive, not imperative).- "Listener never removed" when added via `this.listenTo()` (auto-cleaned in `destroy()`).+- "Plugin not registered" when it's pulled in transitively via another plugin's+ `static get requires()` rather than listed directly in `plugins.ts` — check the dependency chain+ before flagging.+- "Import should be from `@ckeditor/ckeditor5-*`" — Trilium deliberately imports from the `ckeditor5`+ aggregate (with file extensions); the deep `@ckeditor/*` path is the *lint failure*, not the fix.When unsure, phrase it as a **question** ("Is `<mark>` intended to round-trip through `getData()`?I don't see a `dataDowncast`.") rather than a false assertion.@@ -87,18 +130,14 @@ I don't see a `dataDowncast`.") rather than a false assertion.| File | Use it for ||------|-----------|-| `references/defect-patterns.md` | The CKEditor-specific bug catalog: for each, the symptom, how to spot it in a diff, why it's wrong, and the fix. The core of a correctness review. |--> **Out of scope:** the CKEditor *project's own* contribution process (the `.changelog/` entry-> system, `pnpm run nice`, CLA, signed commits, branch naming) is specific to contributing to the-> upstream ckeditor5 monorepo — not to reviewing a plugin in your own project — so this skill does-> not cover it. If you're contributing upstream, follow that repository's CONTRIBUTING guide.+| `references/defect-patterns.md` | The bug catalog — CKEditor-general groups (conversion, schema, commands, UI, lifecycle, localization, undo, tests) plus a **Trilium integration** group. For each: the symptom, how to spot it in a diff, why it's wrong, and the fix. The core of a correctness review. |## Provenance & source references-Self-contained and library-focused. Any `docs/…` / `packages/…` paths or the baseline commit point-into the **upstream CKEditor 5 repository**-([github.com/ckeditor/ckeditor5](https://github.com/ckeditor/ckeditor5)), not the project you are-reviewing. Distilled at upstream commit **`9ecca53627`** (mid-2026) from the patterns in the-companion skills and `docs/framework/contributing/code-style.md`. To refresh, compare those paths-against that commit inside a clone of ckeditor5 and bump the reference here.+The CKEditor-general defect patterns are distilled from the companion skills and the CKEditor 5+library at the pinned **48.2.0**; `docs/…` / `packages/…` paths in those patterns point into the+**external CKEditor 5 repository** ([github.com/ckeditor/ckeditor5](https://github.com/ckeditor/ckeditor5)),+not the Trilium code under review. The Trilium-specific paths (`packages/ckeditor5-*`,+`packages/ckeditor5/src/{plugins,index}.ts`, `apps/client/src/widgets/type_widgets/text/toolbar.ts`,+`lang/en.po`) point into the **Trilium monorepo**. To refresh, re-check those paths against the+current Trilium tree and bump the CKEditor version if the `ckeditor5` pin changes.diff --git a/.claude/skills/ckeditor5-reviewing/references/defect-patterns.md b/.claude/skills/ckeditor5-reviewing/references/defect-patterns.mdindex 06249e46d3..d9870c4541 100644--- a/.claude/skills/ckeditor5-reviewing/references/defect-patterns.md+++ b/.claude/skills/ckeditor5-reviewing/references/defect-patterns.md@@ -1,8 +1,11 @@-# CKEditor 5 defect patterns+# CKEditor 5 defect patterns (Trilium)-The high-value, easy-to-miss failure modes to hunt during a correctness review. Each: **symptom**,-how to **spot** it in a diff, **why** it's wrong, and the **fix**. Grouped by layer. For the-idiomatic "how it should look," see the `ckeditor5-plugin-development` skill.+The high-value, easy-to-miss failure modes to hunt during a correctness review of a Trilium+CKEditor 5 plugin. Each: **symptom**, how to **spot** it in a diff, **why** it's wrong, and the+**fix**. Grouped by layer. The **Conversion → Tests** groups are CKEditor-library-general (they+apply unchanged to Trilium's `packages/ckeditor5-*` plugins); the final **Trilium integration**+group covers the monorepo wiring/convention defects. For the idiomatic "how it should look," see the+`ckeditor5-plugin-development` skill.## Conversion@@ -135,21 +138,27 @@ idiomatic "how it should look," see the `ckeditor5-plugin-development` skill.- Why: breaks headless/server-side use and reuse of the editing layer.- Fix: editing logic in `*Editing`, UI in `*UI`, glue plugin requiring both.-**Outdated / mixed imports (post-v42).**-- Spot: deep imports `@ckeditor/ckeditor5-*/src/...`; mixing the `ckeditor5` aggregate with- individual `@ckeditor/*` packages in an app bundle; removed/renamed symbols (`Model`/`ViewModel`- → `UIModel`; `icons.check` → `IconCheck` from `@ckeditor/ckeditor5-icons`).-- Why: deep paths aren't a supported entry; mixing risks duplicate module instances; renamed- symbols don't exist.-- Fix: import from `ckeditor5` (and `ckeditor5-premium-features`); use current symbol names.+**Outdated / mixed imports (Trilium pins ckeditor5 48.2.0).**+- Spot: deep imports `@ckeditor/ckeditor5-*/src/...`; any `@ckeditor/*` package import instead of the+ `ckeditor5` aggregate; a `ckeditor5`/`@triliumnext/...` import *missing the file extension*;+ removed/renamed symbols (`Model`/`ViewModel` → `UIModel`; `icons.check` → `IconCheck`).+- Why: Trilium always imports from the `ckeditor5` aggregate (pinned 48.2.0) or cross-plugin+ `@triliumnext/ckeditor5-<x>`, **with explicit file extensions** — `eslint-config-ckeditor5`+ (`require-file-extensions-in-imports`, `allow-imports-only-from-main-package-entry-point`,+ `no-legacy-imports`) fails the build otherwise; deep `@ckeditor/*` paths also risk duplicate+ module instances; renamed symbols don't exist.+- Fix: import from `ckeditor5` (or `@triliumnext/ckeditor5-<x>`) with the file extension; use current+ symbol names. (See the Trilium integration group below for the augmentation-module variant.)## Localization**`t()` gaps / misuse.**-- Spot: user-facing strings not wrapped in `t()`; `t` renamed or called on a variable (JS static+- Spot: user-facing strings not wrapped in `t()`; `t` renamed or called on a variable (the staticanalyzer only recognizes a literal-arg `t()`); a reused string creating a new source message- instead of aliasing `editor.locale.t`.-- Fix: wrap all UI strings in `t()` with a literal first arg; reuse via the `locale.t` alias.+ instead of aliasing `editor.locale.t`; a new `t('…')` string with no matching entry added to the+ plugin's `lang/en.po` (+ `lang/contexts.json` where context disambiguation is needed).+- Fix: wrap all UI strings in `t()` with a literal first arg; reuse via the `locale.t` alias; add the+ source string to `lang/en.po` and its context note to `lang/contexts.json`.## Undo / batching@@ -164,4 +173,64 @@ idiomatic "how it should look," see the `ckeditor5-plugin-development` skill.`_getModelData`/`_getViewData`; only one selection shape covered; editor not destroyed in`afterEach`; legacy Chai/Sinon left in a touched file.- Fix: test the change itself; assert on stringified model/view; cover collapsed + ranged +- schema-disallowed; tear down.+ schema-disallowed; tear down. Tests are **Vitest** with real `ClassicEditor.create` and helpers+ from `ckeditor5`; run them via `pnpm --filter @triliumnext/ckeditor5-<f> test`.++## Trilium integration++The monorepo wiring and conventions — a plugin can be internally correct yet still broken because+nothing loads it, no button shows, or lint/license/localization is off.++**Plugin not registered in `plugins.ts`.**+- Spot: a new or renamed plugin class that is never added to `packages/ckeditor5/src/plugins.ts`, or+ added to the **wrong array** (`CORE_PLUGINS` / `TRILIUM_PLUGINS` / `EXTERNAL_PLUGINS` →+ `builtinPlugins`).+- Why: it never loads into the editor classes in `packages/ckeditor5/src/index.ts`+ (AttributeEditor[Balloon], ClassicEditor[Decoupled], PopupEditor[Balloon]) — the feature silently+ does nothing. (Exception: it may be pulled in transitively via another plugin's+ `static get requires()`; check the chain before flagging.)+- Fix: export the plugin and add it to the appropriate array so it reaches `builtinPlugins`.++**Toolbar component not wired up.**+- Spot: a plugin that registers a `componentFactory` button but no corresponding entry in+ `apps/client/src/widgets/type_widgets/text/toolbar.ts`.+- Why: the button never appears in the editor UI even though the plugin loaded.+- Fix: add the component name to the toolbar config.++**Import not from the aggregate / missing file extension.**+- Spot: imports from `@ckeditor/ckeditor5-*` (deep or top-level), or `ckeditor5` /+ `@triliumnext/ckeditor5-<x>` imports **without a file extension**.+- Why: `eslint-config-ckeditor5` (`require-file-extensions-in-imports`,+ `allow-imports-only-from-main-package-entry-point`, `no-legacy-imports`) fails the build.+- Fix: import from `ckeditor5` or cross-plugin `@triliumnext/ckeditor5-<x>`, always with the file+ extension. (See "Outdated / mixed imports" above.)++**License header inconsistent with the package.**+- Spot: a new file that adds or omits the CKSource header against the package's existing convention.+- Why: header/license practice is **not uniform** across Trilium's CKEditor packages (admonition+ carries the CKSource header; footnotes/math are `ISC`; keyboard-marker `GPL-3.0`; etc.).+- Fix: match the other source files in that package — don't add or strip headers wholesale. (Minor.)++**Augmentation via the wrong module.**+- Spot: `declare module '@ckeditor/ckeditor5-core'` (the upstream pattern) in a `.d.ts` /+ augmentation block.+- Why: Trilium augments the aggregate — the editor config/plugin-map types live on `ckeditor5`, so+ the wrong module declaration doesn't merge and the types are missing.+- Fix: `declare module 'ckeditor5'`.++**New UI strings missing from localization.**+- Spot: a new user-facing `t('…')` string with no entry in the plugin's `lang/en.po` (and, where+ context matters, `lang/contexts.json`).+- Why: the source catalog is incomplete; downstream translation can't pick the string up.+- Fix: add the string to `lang/en.po` and its context note to `lang/contexts.json`. (See the+ Localization group above.)++**Wrong test environment.**+- Spot: a widget/toolbar/layout-dependent test (anything needing real DOM geometry, focus, or+ rendering) running under **happy-dom** instead of browser mode; or vice-versa, a plain+ model/conversion test forced into the heavier browser mode.+- Why: Trilium splits environments — admonition/collapsible use **happy-dom**;+ math/mermaid/footnotes/keyboard-marker use **`@vitest/browser-webdriverio` browser mode** (NOT+ Playwright). A widget test under happy-dom gives false passes/failures because layout isn't real.+- Fix: match the plugin's configured environment; move browser-dependent assertions to a+ browser-mode package/config.diff --git a/.claude/skills/ckeditor5-testing/SKILL.md b/.claude/skills/ckeditor5-testing/SKILL.mdindex 8e22bab8eb..0f6c98ae99 100644--- a/.claude/skills/ckeditor5-testing/SKILL.md+++ b/.claude/skills/ckeditor5-testing/SKILL.md@@ -1,138 +1,134 @@---name: ckeditor5-testingdescription: >-- Write and run tests for CKEditor 5 plugins/features. Use when adding or- reviewing unit tests for a ckeditor5-* package, debugging a failing test,- migrating tests to Vitest, or setting up the test runner. Covers the current- Vitest + Playwright browser setup, the test-editor utilities- (ClassicTestEditor / VirtualTestEditor / ModelTestEditor), the model/view test- helpers (_setModelData/_getModelData/_getViewData and their {}/[] selection- syntax), vi spies/mocks, idiomatic patterns for schema/conversion/command/UI- tests, the --files runner options, and migrating off the old Karma/Mocha/Chai- setup. Complements the ckeditor5-plugin-development skill.+ Testing CKEditor 5 plugins in the Trilium monorepo. Use when adding or+ reviewing unit tests for a packages/ckeditor5-* package, debugging a failing+ test, or setting up a package's test runner. Covers the two Vitest+ environments Trilium uses (happy-dom and the WebdriverIO browser mode), the+ per-package vitest.config.ts, testing against a real ClassicEditor, the+ model/view helpers imported from 'ckeditor5' (_setModelData / _getModelData /+ _getViewData and their {}/[] selection syntax), vi spies/mocks, idiomatic+ patterns for schema/conversion/command/UI tests, the pnpm --filter runner, and+ Trilium-specific conventions and gotchas. Complements the+ ckeditor5-plugin-development and writing-unit-tests skills.----# CKEditor 5 testing+# CKEditor 5 testing (Trilium)-CKEditor 5 keeps a **complete unit-test suite with 100% code coverage per package**. Each-package owns its tests in `packages/ckeditor5-<name>/tests/`. Every code change should ship-with a test that proves it is needed.+Testing CKEditor 5 plugins in the **Trilium (TriliumNext Notes) monorepo**. Each plugin lives in+`packages/ckeditor5-<name>/` and owns its tests in `tests/`. Browser-mode packages gate `src/**`+at **100% coverage**, so every code change should ship with a test.-> **Important — the published docs are out of date.** The official "Testing environment" guide-> describes **Karma + Mocha + Chai + Sinon**. The repository has **migrated to Vitest**-> (browser mode via Playwright). Write new/edited tests in the **Vitest** style described here;-> treat Chai/Sinon idioms (`expect().to.equal`, `sinon.spy`, `equalMarkup`) as legacy to be-> migrated, not copied. See `references/migration-from-karma.md`.+## Scope & sources++This skill covers testing CKEditor 5 plugins in the **Trilium (TriliumNext Notes) monorepo**+(`packages/ckeditor5-*`). The CKEditor 5 library is pinned to 48.2.0. For general (non-CKEditor)+Trilium testing, see the `writing-unit-tests` skill.## When to use this skill-Adding/reviewing unit tests for a feature, debugging a failing test, migrating a legacy test-file to Vitest, or configuring the runner. For writing the feature itself, use the-`ckeditor5-plugin-development` skill.+Adding/reviewing unit tests for a plugin, debugging a failing test, or configuring a package's+runner. For writing the feature itself, use the `ckeditor5-plugin-development` skill. For general+Trilium testing (Preact components, jQuery widgets, server routes), use `writing-unit-tests`.## The current setup at a glance-This describes how the **upstream ckeditor5 monorepo** tests itself (the source of these patterns).-A standalone plugin package in your own project gets an equivalent Vitest setup from the-package-generator template; the **test-writing patterns** below transfer unchanged either way.--- **Runner:** Vitest (`vitest@^4`), one **project per package**. Config comes from the root- `createVitestConfig({ name: '<short-package-name>' })` factory; each package has a tiny- `vitest.config.ts` that calls it.-- **Environment:** real browser via `@vitest/browser-playwright` (Chromium). Tests have real- DOM APIs (`document.createElement`, etc.).-- **Globals:** `globals: true` is set, but migrated tests still **import explicitly** from- `vitest` — do the same.-- **Test files:** `tests/**/*.{js,ts}`; excluded: `**/_utils`, `**/fixtures`, `**/manual`.-- **Setup:** `test_setup.js` sets `globalThis.CKEDITOR_GLOBAL_LICENSE_KEY = 'GPL'` — you do- **not** pass a license key in tests.-- **Coverage:** `src/**` at **100%** thresholds (excludes `index.ts`, `augmentation.ts`,- `*config.ts`). Provider `v8`.-- **TypeScript:** tests may be `.js` or `.ts`; import source with explicit `.js` extension- (`../src/foo.js`).-- **Imports:** in your own project, import editor classes and the model/view helpers from the- `ckeditor5` package (e.g. `import { ClassicEditor, _setModelData } from 'ckeditor5';`). The- `@ckeditor/ckeditor5-core/tests/_utils/*` test editors shown below exist only in the ckeditor5- monorepo — see `references/test-utilities.md` for the downstream alternative.+- **Runner:** Vitest (`[email protected]`). **No shared factory** — each package has its own+ `vitest.config.ts` built with `defineConfig` directly.+- **Two environments**, chosen per package:+ - **happy-dom** (`environment: "happy-dom"`) — used by `admonition`, `collapsible`. Light, no+ coverage thresholds. happy-dom is **not a real browser**: `getBoundingClientRect()` returns+ zeros, layout is stubbed, `ResizeObserver` is stubbed. Fine for model/conversion/command+ logic; wrong for anything that measures the DOM.+ - **WebdriverIO browser mode** (`@vitest/browser-webdriverio`, headless Chrome) — used by+ `footnotes`, `keyboard-marker`, `math`, `mermaid`. Real DOM/layout. Gates `src/**` coverage+ at 100% (lines/functions/branches/statements). This is **not Playwright**.+- **Real editor, no test-editor factories.** Tests create a real `ClassicEditor` against a real+ DOM element (see below). There is **no** `ModelTestEditor`/`VirtualTestEditor`/`ClassicTestEditor`+ in Trilium — those live only in the upstream ckeditor5 monorepo's `tests/_utils`.+- **Helpers from `'ckeditor5'`:** `_setModelData`, `_getModelData`, `_getViewData` are imported+ from the `ckeditor5` package.+- **Test files:** `tests/**/*.[jt]s` (no `.spec`/`.test` suffix). `globals: true`. Coverage+ provider `v8`, `include: src/**`.+- **Imports** from `'ckeditor5'`; in-package source imports use a file extension.+- **License key:** tests pass `licenseKey: 'GPL'` in the editor config.+- Some packages (`admonition`, `footnotes`, `keyboard-marker`) have a vitest config but **no+ tests yet** — adding tests is encouraged.## Running tests-Per-package (from the package dir) — the everyday loop:-```bash-vitest run # one-shot ("test" script)-vitest # watch / debug ("test:debug")-vitest run --browser.headless # headless ("test:headless")-pnpm run coverage # headless + coverage (100% gate)-vitest run paragraphcommand # filter by file name substring+pnpm --filter @triliumnext/ckeditor5-math test # one package (from anywhere)+# or, from the package dir:+vitest run```-From the repo root, the dev-tools wrapper runs the suite and accepts `--files` patterns-(see `references/running-and-config.md`):+Debug a browser-mode package with a visible browser:```bash-pnpm run test # ckeditor5-dev-tests-run-automated (wraps Vitest)-pnpm run test -- --files=paragraph # one package (short name)-pnpm run test -- -c --files=core # with coverage+vitest --inspect-brk --no-file-parallelism --browser.headless=false```-`--files` rules (shared with manual tests): `core` or `ckeditor5-core` (a package),-`editor-*` (glob), `!core` / `!(core|engine)` (exclude), `engine/view/` (a sub-dir),-`basic-styles/bold*` (file glob), comma-separated sums.+Root orchestration: `pnpm test:parallel` runs the light packages in parallel; `pnpm+test:sequential` runs `math` and `mermaid` **sequentially** (browser resource limits).+`pnpm test:all` runs both. Each package exposes `"test": "vitest"` and+`"test:debug": "vitest --inspect-brk --no-file-parallelism --browser.headless=false"`.## Anatomy of a test-```js+```ts+import { ClassicEditor, Essentials, Paragraph, _setModelData } from 'ckeditor5';import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';-// ModelTestEditor lives in the ckeditor5 monorepo's tests/_utils (see references/test-utilities.md).-import { ModelTestEditor } from '@ckeditor/ckeditor5-core/tests/_utils/modeltesteditor.js';-import { _setModelData, _getModelData } from 'ckeditor5';-import { ParagraphCommand } from '../src/paragraphcommand.js';--describe( 'ParagraphCommand', () => {- let editor, model, command;-- beforeEach( () => {- return ModelTestEditor.create().then( newEditor => {- editor = newEditor;- model = editor.model;- command = new ParagraphCommand( editor );- editor.commands.add( 'paragraph', command );- model.schema.register( 'paragraph', { inheritAllFrom: '$block' } );- model.schema.register( 'heading1', { inheritAllFrom: '$block' } );+import MyPlugin from '../src/myplugin.js';++describe( 'MyPlugin', () => {+ let editorElement: HTMLDivElement, editor: ClassicEditor, model;++ beforeEach( async () => {+ editorElement = document.createElement( 'div' );+ document.body.appendChild( editorElement );++ editor = await ClassicEditor.create( editorElement, {+ licenseKey: 'GPL',+ plugins: [ Essentials, Paragraph, MyPlugin ]} );+ model = editor.model;} );afterEach( () => {- command.destroy(); // or editor.destroy() when you create a full editor+ editorElement.remove();+ return editor.destroy();+ } );++ it( 'loads the plugin', () => {+ expect( editor.plugins.get( MyPlugin ) ).toBeInstanceOf( MyPlugin );} );- it( 'is true when selection is in a paragraph', () => {+ it( 'keeps the selection in a paragraph', () => {_setModelData( model, '<paragraph>foo[]bar</paragraph>' );- expect( command.value ).toBe( true );+ expect( model.document.getRoot().getChild( 0 ).name ).toBe( 'paragraph' );} );} );```Conventions visible here and across the suite:-- Keep one top-level `describe` named after the unit, with nested `describe`s for areas- (`value`, `execute()`, …) and small focused `it`s.-- Create the editor in `beforeEach` (return the Promise — Vitest awaits it). **Always tear- down** in `afterEach` (`editor.destroy()`, and remove any DOM element you appended).-- Use the lightest test editor that works: `ModelTestEditor` (model only) < `VirtualTestEditor`- (model+engine, no DOM render) < `ClassicTestEditor` (full UI in a real element). Details in- `references/test-utilities.md`.+- One top-level `describe` named after the unit, nested `describe`s for areas (`isEnabled`,+ `execute()`, …), small focused `it`s.+- Create the editor in `beforeEach` (return the Promise or use `async`/`await` — Vitest awaits+ it), and **always tear down** in `afterEach`: `editor.destroy()` plus `editorElement.remove()`.+- Pass `licenseKey: 'GPL'`. List only the plugins the test needs (commands can also be+ instantiated directly, e.g. `new InsertMermaidCommand( editor )`).## Model/view test data-`_setModelData()` / `_getModelData()` (and `_getViewData()`/`_setViewData()`) stringify and-parse the engine structures, with a special selection syntax:+`_setModelData()` / `_getModelData()` (and `_getViewData()`) stringify and parse the engine+structures, with a special selection syntax:- `[]` — collapsed selection, **or** brackets around a range, anchored in an **element**.- `{}` — selection anchored inside a **text node** (e.g. `foo{}bar` / `f{oo}bar`).- Attributes render as `<$text bold="true">word</$text>`; elements as `<paragraph>…</paragraph>`.-```js+```ts_setModelData( model, '<paragraph>foo[]bar</paragraph>' );expect( _getModelData( model ) ).toEqual( '<paragraph>foo[]bar</paragraph>' );expect( _getViewData( editor.editing.view ) ).toEqual( '<p>foo{}bar</p>' );@@ -142,54 +138,32 @@ These are dev/test utilities only — never ship them in production code.## Assertions & spies (Vitest)-- Matchers: `expect(x).toBe()`, `.toEqual()`, `.toBeInstanceOf()`, `.toHaveBeenCalledOnce()`,- `.toHaveBeenCalledWith()`, `.toThrow()`. There are **no** custom Chai matchers (`equalMarkup`,- `.attribute`) — compare stringified model/view with `.toEqual()` instead.-- Spies/mocks via `vi`: `const spy = vi.spyOn( editor, 'execute' );` then- `expect( spy ).toHaveBeenCalledWith( 'paragraph' )`. Also `vi.fn()`, `vi.useFakeTimers()`,- `vi.stubGlobal()`. (Replaces Sinon — see the migration reference.)+- Both **Jest-style** (`expect(x).toBe(y)`, `.toEqual()`, `.toBeInstanceOf()`,+ `.toHaveBeenCalledWith()`) and **Chai-style** (`expect(x).to.equal(y)`, `.to.be.false`,+ `.to.instanceOf()`) matchers work in Vitest. The existing Trilium tests mix both. There are+ **no** custom matchers — compare stringified model/view directly.+- Spies/mocks via `vi`: `vi.spyOn( editor, 'execute' )`, `vi.fn()`, `vi.useFakeTimers()`.-```js+```tsconst spy = vi.spyOn( editor, 'execute' );button.fire( 'execute' );-expect( spy ).toHaveBeenCalledOnce();-expect( spy ).toHaveBeenCalledWith( 'paragraph' );+expect( spy ).toHaveBeenCalledWith( 'insertMermaid' );```## Reference map| File | Use it for ||------|-----------|-| `references/test-utilities.md` | The test editors (`ModelTestEditor`/`VirtualTestEditor`/`ClassicTestEditor`), other `_utils` (`articlepluginset`, `cleanup`, `generatelicensekey`), and the `_get/_set/_stringify/_parse` model & view helpers + selection syntax. |-| `references/patterns.md` | Idiomatic test recipes per concern: schema, conversion round-trips, commands (`value`/`isEnabled`/`execute`), UI (component factory, button binding, execute spy), keystrokes, events, async, and reaching 100% coverage. |-| `references/running-and-config.md` | Full runner reference: per-package vs. root wrapper, `--files` patterns, coverage/headless/watch, the `createVitestConfig` factory, browser mode, manual tests (md/js/html), memory-leak tests. |-| `references/migration-from-karma.md` | Mapping legacy Karma/Mocha/Chai/Sinon idioms to Vitest — for migrating existing test files (the repo is mid-migration). |+| `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; note on the 100% coverage gate for browser-mode packages. |+| `references/running-and-config.md` | Per-package `vitest.config.ts` (happy-dom shape and WebdriverIO browser shape), `pnpm --filter` commands, the debug command, `pnpm test:parallel`/`test:sequential` (math+mermaid sequential), coverage thresholds. |+| `references/test-conventions.md` | Trilium test **conventions & gotchas**: choosing happy-dom vs. browser mode, real-editor teardown, the both-assertion-styles note, sequential math/mermaid, and the pointer to `writing-unit-tests`. |## Quick review checklist-When reviewing tests: explicit `vitest` imports; lightest suitable-test editor; editor/command created in `beforeEach` and **destroyed** in `afterEach` (plus DOM-cleanup); model/view asserted via `_getModelData`/`_getViewData` + `toEqual` with correct-`[]`/`{}` selection syntax; spies via `vi`; behavior covered for collapsed **and** ranged-selections and schema-disallowed contexts; new `src/` lines covered (100% gate); no Chai/Sinon-leftovers; manual tests (if any) under `tests/manual/`.--## Provenance & source references--**This skill is self-contained, not tied to any particular project.** Repository paths it cites —-`vitest.config.ts`, `test_setup.js`, `packages/ckeditor5-…`, `@ckeditor/ckeditor5-…/tests/_utils/…`,-the baseline commit — point into the **upstream CKEditor 5 repository**-([github.com/ckeditor/ckeditor5](https://github.com/ckeditor/ckeditor5)), **not your project**. The-runner/config specifics describe how the ckeditor5 monorepo tests *itself*; the **patterns** (test-editors, `_setModelData`/`_getModelData`, `vi` spies, `describe`/`it` structure) are portable to any-project. Don't open these paths as local files unless you are working inside the ckeditor5-repository. (Note: the model/view helpers are published via the `ckeditor5` / `@ckeditor/ckeditor5-engine`-npm packages and work downstream; the `tests/_utils` test editors are monorepo-internal — see-`references/test-utilities.md` for the downstream caveat.)--This skill was distilled from that upstream repository at commit **`9ecca53627`** (mid-2026).-Because the repo is **mid-migration to Vitest**, the skill reflects the *current* setup verified-against source — not the (stale, Karma-era) published testing docs.--To refresh, compare the source/config/test-util paths against commit `9ecca53627` inside a clone of-ckeditor5 (watch the migration progress), then bump the commit reference here.+When reviewing tests: editor created in `beforeEach` with `licenseKey: 'GPL'` and **destroyed**+in `afterEach` (plus `editorElement.remove()`); model/view asserted via+`_getModelData`/`_getViewData` with correct `[]`/`{}` selection syntax; spies via `vi`; behavior+covered for collapsed **and** ranged selections and schema-disallowed contexts; for browser-mode+packages, new `src/` lines covered (100% gate); no reliance on real layout when the package uses+happy-dom.diff --git a/.claude/skills/ckeditor5-testing/references/migration-from-karma.md b/.claude/skills/ckeditor5-testing/references/migration-from-karma.mddeleted file mode 100644index 8020febfdd..0000000000--- a/.claude/skills/ckeditor5-testing/references/migration-from-karma.md+++ /dev/null@@ -1,98 +0,0 @@-# Migrating tests: Karma/Mocha/Chai/Sinon → Vitest--> This reference is mainly for working **inside the upstream ckeditor5 repository**, which is-> mid-migration to Vitest. It's equally useful in any project that still has legacy Karma/Mocha/-> Chai/Sinon CKEditor tests to bring over. The `test_setup.js`/`tests/_utils` references are-> upstream paths (see `test-utilities.md`).--The ckeditor5 repository is mid-migration (commits migrate packages one by one to Vitest). Many-test files still use the old stack. When you touch a legacy test, migrate it. This is the mapping.--## Imports & globals--- **Add explicit imports** at the top: `import { describe, it, expect, beforeEach, afterEach,- vi } from 'vitest';` (the old globals from Mocha/Chai are gone; `globals: true` is set but the- codebase imports explicitly).-- Source imports use the **`.js` extension**: `import { Foo } from '../src/foo.js';`.-- Drop any `import { expect } from 'chai'` / Chai plugin setup.--## Test structure--- `describe`/`it`/`beforeEach`/`afterEach` keep the same names and semantics — usually no change- beyond importing them.-- Async setup: returning a Promise still works; `async`/`await` is fine too.--## Assertions: Chai → Vitest `expect`--| Chai (old) | Vitest (new) |-|------------|--------------|-| `expect( x ).to.equal( y )` | `expect( x ).toBe( y )` |-| `expect( x ).to.deep.equal( y )` | `expect( x ).toEqual( y )` |-| `expect( x ).to.be.true` / `.false` | `expect( x ).toBe( true )` / `toBe( false )` |-| `expect( x ).to.be.null` / `.undefined` | `expect( x ).toBeNull()` / `toBeUndefined()` |-| `expect( x ).to.be.instanceOf( C )` | `expect( x ).toBeInstanceOf( C )` |-| `expect( arr ).to.have.length( n )` | `expect( arr ).toHaveLength( n )` |-| `expect( x ).to.include( y )` | `expect( x ).toContain( y )` |-| `expect( fn ).to.throw( /re/ )` | `expect( fn ).toThrow( /re/ )` |-| `expect( x ).to.exist` | `expect( x ).toBeTruthy()` (or `toBeDefined()`) |--### Custom CKEditor Chai assertions (removed)--The old Karma setup auto-loaded custom Chai matchers. They **do not exist** in Vitest:--- `expect( a ).to.equalMarkup( b )` → compare stringified structures directly:- `expect( _getModelData( model ) ).toEqual( '<paragraph>…</paragraph>' )` (use- `_getModelData`/`_getViewData`/`_stringifyModel`). The diff is on strings.-- `expect( selection ).to.have.attribute( 'linkHref', 'x' )` → assert explicitly:- `expect( selection.hasAttribute( 'linkHref' ) ).toBe( true )` and- `expect( selection.getAttribute( 'linkHref' ) ).toBe( 'x' )`.--## Spies/stubs/mocks: Sinon → `vi`--| Sinon (old) | Vitest (new) |-|-------------|--------------|-| `sinon.spy( obj, 'm' )` | `vi.spyOn( obj, 'm' )` |-| `sinon.stub( obj, 'm' ).returns( v )` | `vi.spyOn( obj, 'm' ).mockReturnValue( v )` |-| `sinon.stub( obj, 'm' ).callsFake( fn )` | `vi.spyOn( obj, 'm' ).mockImplementation( fn )` |-| `sinon.spy()` / `sinon.stub()` | `vi.fn()` |-| `spy.calledOnce` | `expect( spy ).toHaveBeenCalledOnce()` |-| `spy.calledWith( a )` | `expect( spy ).toHaveBeenCalledWith( a )` |-| `spy.called` | `expect( spy ).toHaveBeenCalled()` |-| `spy.callCount` | `expect( spy ).toHaveBeenCalledTimes( n )` |-| `spy.returned( v )` / `spy.args` | `spy.mock.results` / `spy.mock.calls` |-| `sinon.useFakeTimers()` | `vi.useFakeTimers()` (+ `vi.advanceTimersByTime()`, `vi.useRealTimers()`) |-| `clock.tick( n )` | `vi.advanceTimersByTime( n )` |--### The Sinon sandbox helper (remove it)--Legacy tests use `testUtils.createSinonSandbox()` + `testUtils.sinon.*` (from a `_utils/utils`-module). Replace with plain `vi`:--```js-// OLD-testUtils.createSinonSandbox();-it( '…', () => { testUtils.sinon.spy( obj, 'm' ); } );--// NEW — no sandbox; mocks auto-restore, or restore explicitly:-import { vi, afterEach } from 'vitest';-afterEach( () => vi.restoreAllMocks() ); // optional safety-it( '…', () => { vi.spyOn( obj, 'm' ); } );-```--## Environment differences--- Tests run in a **real browser** (Playwright Chromium), not jsdom — real DOM/layout APIs are- available; code that depended on Karma+webpack globals may need adjusting.-- No `licenseKey` in test editors — `test_setup.js` sets the global GPL key.-- `.svg` imports resolve to the SVG **string** (via the config's `load-svg` plugin), same as- before.--## Checklist for a migrated file--- [ ] Explicit `vitest` imports added.-- [ ] All `import … from 'chai'` / `sinon` removed; `.js` extensions on source imports.-- [ ] Chai matchers → Vitest matchers; `equalMarkup`/`.attribute` rewritten with data helpers.-- [ ] Sinon → `vi`; sandbox removed.-- [ ] Editor/command still created in `beforeEach` and **destroyed** in `afterEach` (+ DOM- cleanup); appended elements removed.-- [ ] `vitest run` passes and `pnpm run coverage` still hits 100% for the package.diff --git a/.claude/skills/ckeditor5-testing/references/patterns.md b/.claude/skills/ckeditor5-testing/references/patterns.mdindex 14c4b95512..096a37097b 100644--- a/.claude/skills/ckeditor5-testing/references/patterns.md+++ b/.claude/skills/ckeditor5-testing/references/patterns.md@@ -1,34 +1,41 @@-# Test patterns (Vitest)+# Test patterns (Trilium, Vitest)-> These patterns are portable to any project. Where examples import test editors from-> `@ckeditor/ckeditor5-core/tests/_utils/…` (an upstream-repo path), see the downstream caveat in-> `test-utilities.md` — the `_setModelData`/`_getModelData` helpers are published and work anywhere;-> the test editors are monorepo-internal.--Idiomatic recipes per concern. All examples assume explicit `vitest` imports and a test editor-created in `beforeEach`, destroyed in `afterEach`. Mirror the structure of the feature: a-`*editing` test for schema/conversion/command, a `*ui` test for buttons/dropdowns.+Idiomatic recipes per concern. All examples assume a real `ClassicEditor` created in `beforeEach`+and destroyed in `afterEach` (see `test-utilities.md`). Mirror the structure of the feature: an+`*editing` test for schema/conversion/command, a `*ui` test for buttons/dropdowns. Assertions may+be **Jest-style** (`toBe`/`toEqual`) or **Chai-style** (`to.equal`/`to.be.false`) — both work in+Vitest; the examples use Jest-style.## Setup / teardown-```js+```ts+import { ClassicEditor, Paragraph } from 'ckeditor5';import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import MyFeature from '../src/myfeature.js';-let editor, model;+let editorElement: HTMLDivElement, editor: ClassicEditor, model;-beforeEach( () => {- return VirtualTestEditor.create( { plugins: [ Paragraph, MyFeature ] } )- .then( newEditor => { editor = newEditor; model = editor.model; } );+beforeEach( async () => {+ editorElement = document.createElement( 'div' );+ document.body.appendChild( editorElement );+ editor = await ClassicEditor.create( editorElement, {+ licenseKey: 'GPL',+ plugins: [ Paragraph, MyFeature ]+ } );+ model = editor.model;} );-afterEach( () => editor.destroy() ); // + element.remove() for ClassicTestEditor+afterEach( () => {+ editorElement.remove();+ return editor.destroy();+} );```Return the Promise (or use `async`/`await`) so Vitest waits. Default `testTimeout` is 5000 ms.## Schema-```js+```tsit( 'allows the highlight attribute on $text', () => {expect( model.schema.checkAttribute( [ '$root', '$text' ], 'highlight' ) ).toBe( true );} );@@ -42,10 +49,10 @@ it( 'registers placeholder as an inline object', () => {## Conversion (round-trips)-Test each direction with the data helpers. Upcast = `setData` then read the model; data-downcast = `setData`/`setModelData` then `getData`; editing downcast = read `_getViewData`.+Test each direction with the data helpers. Upcast = `setData` then read the model; data downcast =+`setModelData` then `getData`; editing downcast = read `_getViewData`.-```js+```tsit( 'upcasts <mark> to the highlight attribute', () => {editor.setData( '<p>foo <mark>bar</mark></p>' );expect( _getModelData( model, { withoutSelection: true } ) )@@ -64,27 +71,23 @@ it( 'editing-downcasts to <mark> in the editing view', () => {} );```-For widgets, assert the editing view contains the widget classes/attributes-(`ck-widget`, `contenteditable`) while `getData()` stays clean.+For widgets, assert the editing view contains the widget classes/attributes (`ck-widget`,+`contenteditable`) while `getData()` stays clean. Widget rendering needs real layout — run such+tests in a **browser-mode** package, not happy-dom.## CommandsCover `value`, `isEnabled`, and `execute()` — for **collapsed and ranged** selections and for-**schema-disallowed** contexts (where `isEnabled` must be `false`).--```js-describe( 'value', () => {- it( 'reflects the current selection state', () => {- _setModelData( model, '<paragraph>[]foo</paragraph>' );- expect( command.value ).toBe( false );- _setModelData( model, '<paragraph><$text highlight="true">[]foo</$text></paragraph>' );- expect( command.value ).toBe( true );- } );-} );+**schema-disallowed** contexts (where `isEnabled` must be `false`). Instantiate the command+directly when convenient.++```ts+const command = new InsertMermaidCommand( editor );describe( 'isEnabled', () => {- it( 'is false where the attribute is disallowed', () => {- _setModelData( model, '<imageBlock></imageBlock>' ); // selection on object+ it( 'is false when a mermaid element is selected', () => {+ _setModelData( model,+ '<paragraph>foo</paragraph>[<mermaid source="flowchart TB"></mermaid>]' );expect( command.isEnabled ).toBe( false );} );} );@@ -96,33 +99,20 @@ describe( 'execute()', () => {expect( _getModelData( model ) ).toEqual( '<paragraph>[<$text highlight="true">foobar</$text>]</paragraph>' );} );-- it( 'is undoable as a single step', () => {- _setModelData( model, '<paragraph>[foobar]</paragraph>' );- command.execute();- editor.execute( 'undo' );- expect( _getModelData( model ) ).toEqual( '<paragraph>[foobar]</paragraph>' );- } );} );```## UI (component factory, button binding, execute)-Use `ClassicTestEditor` so `editor.ui` exists. Verify the factory produces the right view, the-button reflects command state, and clicking it runs the command.+`editor.ui` exists on the real editor. Verify the factory produces the right view, the button+reflects command state, and clicking it runs the command. UI/balloon positioning needs real+layout — keep these in a **browser-mode** package.-```js+```tsit( 'registers a ButtonView', () => {expect( editor.ui.componentFactory.create( 'highlight' ) ).toBeInstanceOf( ButtonView );} );-it( 'binds button state to the command', () => {- const button = editor.ui.componentFactory.create( 'highlight' );- const command = editor.commands.get( 'highlight' );- command.isEnabled = false;- expect( button.isEnabled ).toBe( false );-} );-it( 'executes the command on click and refocuses the editor', () => {const button = editor.ui.componentFactory.create( 'highlight' );const executeSpy = vi.spyOn( editor, 'execute' );@@ -138,7 +128,7 @@ For dropdowns, `create()` the component, inspect `dropdownView.listView`/`button## Keystrokes-```js+```tsit( 'executes the command on Ctrl+Alt+H', () => {const spy = vi.spyOn( editor, 'execute' );const wasHandled = editor.keystrokes.press( {@@ -150,12 +140,12 @@ it( 'executes the command on Ctrl+Alt+H', () => {} );```-(`keyCodes` from `@ckeditor/ckeditor5-utils`.) For view-document keydown handlers, fire on+(`keyCodes` from `'ckeditor5'`.) For view-document keydown handlers, fire on`editor.editing.view.document`.## Events & observables-```js+```tsit( 'fires change:value', () => {const spy = vi.fn();command.on( 'change:value', spy );@@ -170,12 +160,10 @@ it( 'fires change:value', () => {- `vi.fn()` — standalone mock callback.- `vi.useFakeTimers()` / `vi.advanceTimersByTime()` / `vi.useRealTimers()` — for debounced ortimeout-based code; restore in `afterEach`.-- `vi.stubGlobal( 'name', value )` — stub a global. Prefer `vi.restoreAllMocks()` in `afterEach`- if you don't rely on auto-restore.## Errors / warnings-```js+```tsit( 'throws on invalid config', () => {expect( () => editor.something() ).toThrow( /my-feature-error/ );} );@@ -183,9 +171,10 @@ it( 'throws on invalid config', () => {For `CKEditorError`, match the error id substring.-## Reaching 100% coverage+## Reaching 100% coverage (browser-mode packages)-The suite gates `src/**` at 100% (excluding `index.ts`, `augmentation.ts`, `*config.ts`). Every-branch needs a test: both states of each boolean, each schema-allowed/disallowed path, collapsed-vs. ranged selection, and error/guard branches. Run `pnpm run coverage` (headless + v8) and read-the HTML report to find uncovered lines before pushing.+Browser-mode packages (`footnotes`, `keyboard-marker`, `math`, `mermaid`) gate `src/**` at 100%+(lines/functions/branches/statements, provider `v8`). Every branch needs a test: both states of+each boolean, each schema-allowed/disallowed path, collapsed vs. ranged selection, and error/guard+branches. happy-dom packages (`admonition`, `collapsible`) have **no** threshold. Run the package's+`test` script and read the coverage text report to find uncovered lines before pushing.diff --git a/.claude/skills/ckeditor5-testing/references/running-and-config.md b/.claude/skills/ckeditor5-testing/references/running-and-config.mdindex e0068698c0..4bffd6e3c0 100644--- a/.claude/skills/ckeditor5-testing/references/running-and-config.md+++ b/.claude/skills/ckeditor5-testing/references/running-and-config.md@@ -1,12 +1,7 @@-# Running tests & configuration+# Running tests & configuration (Trilium)-> **Two contexts.** The **per-package scripts** below are what the package-generator produces, so-> they apply to a standalone plugin package in your own project. The **root runner**,-> `createVitestConfig` factory, `--files` patterns, manual-test and memory-test sections describe how-> the **upstream ckeditor5 monorepo** tests itself — paths like `vitest.config.ts`,-> `packages/*/vitest.config.ts`, and `test_setup.js` refer to that repository-> ([github.com/ckeditor/ckeditor5](https://github.com/ckeditor/ckeditor5)), not your project. Use the-> monorepo sections only when working inside ckeditor5 itself.+Trilium gives **each** `packages/ckeditor5-*` package its own `vitest.config.ts` (built with+`defineConfig` directly — there is no shared factory). Vitest is `4.1.8`.## Per-package scripts@@ -14,110 +9,115 @@ Each package's `package.json` defines:| Script | Command | Purpose ||--------|---------|---------|-| `test` | `vitest run` | One-shot run. |-| `test:debug` | `vitest` | Watch mode (re-runs on change; interactive). |-| `test:headless` | `vitest run --browser.headless` | Headless browser run (CI-like). |-| `coverage` | `pnpm run test:headless --coverage` | Headless + coverage (100% gate). |+| `test` | `vitest` | Run the package's tests (configs set `watch: false`, so this is one-shot). |+| `test:debug` | `vitest --inspect-brk --no-file-parallelism --browser.headless=false` | Attach a debugger and watch a browser-mode run with a visible window. |-Useful ad-hoc invocations from a package directory:+Run a single package from anywhere in the monorepo:```bash-vitest run highlightcommand # filter by filename substring-vitest run -t "execute" # filter by test name (-t/--testNamePattern)-vitest --browser.headless # watch, headless-vitest run --coverage # coverage for this package+pnpm --filter @triliumnext/ckeditor5-math test```-## Root runner (dev-tools wrapper)+Or, from the package directory: `vitest run`. Add `-t "name"` to filter by test name, or a+filename substring to filter by file.-The root `pnpm run test` calls `ckeditor5-dev-tests-run-automated` (from-`@ckeditor/ckeditor5-dev-tests`), which orchestrates Vitest across packages. It selects packages-as Vitest **projects** by short name and supports the legacy `--files` patterns.+## Two config shapes-```bash-pnpm run test # whole suite-pnpm run test -- --files=highlight # one package (short name)-pnpm run test -- -c --files=engine # with coverage-pnpm run test -- -cw --files=engine/view/,typing # coverage + watch, sub-dir + package+### happy-dom (e.g. `admonition`, `collapsible`)++Light, no coverage thresholds. Not a real browser — `getBoundingClientRect()` is zeroed, layout+and `ResizeObserver` are stubbed. Use for model/conversion/command logic.++```ts+import { defineConfig } from 'vitest/config';+import svg from 'vite-plugin-svgo';++export default defineConfig( {+ plugins: [ svg() ],+ test: {+ environment: 'happy-dom',+ include: [ 'tests/**/*.[jt]s' ],+ globals: true,+ watch: false,+ passWithNoTests: true,+ coverage: {+ provider: 'v8',+ include: [ 'src/**/*.{ts,tsx}' ],+ exclude: [ '**/*.{test,spec}.{ts,mts,cts,tsx,js,jsx}', '**/*.d.ts' ],+ reporter: [ 'text', 'lcov' ]+ }+ }+} );```-`--files` (alias `-f`) patterns (also used by manual tests):+### WebdriverIO browser mode (e.g. `footnotes`, `keyboard-marker`, `math`, `mermaid`)-| Pattern | Meaning |-|---------|---------|-| `core` / `ckeditor5-core` | One package (short or full name). |-| `editor-*` | Glob over package names. |-| `!core` / `!(core\|engine)` | Exclude one/several packages. |-| `engine/view/` | A sub-directory under a package's `tests/`. |-| `basic-styles/bold*` | Filename glob within a package. |-| `a,b,c` | Comma-separated sum of patterns. |+Real headless Chrome via `@vitest/browser-webdriverio` (**not** Playwright). Real DOM/layout.+Gates `src/**` coverage at 100%.-Other documented args (legacy Karma names; some map onto Vitest via the wrapper): `--watch`/`-w`,-`--coverage`/`-c`, `--source-map`/`-s`, `--verbose`/`-v`, `--browsers`, `--port`,-`--identity-file`/`-i` (license file for closed-source features). Running tests for the whole-monorepo root (no package) is not supported — tests belong to a package's `tests/` dir.+```ts+import { defineConfig } from 'vitest/config';+import svg from 'vite-plugin-svgo';+import { webdriverio } from '@vitest/browser-webdriverio';++export default defineConfig( {+ plugins: [ svg() ],+ test: {+ browser: {+ enabled: true,+ provider: webdriverio(),+ headless: true,+ ui: false,+ instances: [ { browser: 'chrome' } ]+ },+ include: [ 'tests/**/*.[jt]s' ],+ exclude: [ 'tests/setup.ts' ],+ globals: true,+ watch: false,+ coverage: {+ thresholds: { lines: 100, functions: 100, branches: 100, statements: 100 },+ provider: 'v8',+ include: [ 'src/**/*.{ts,tsx}' ],+ exclude: [ '**/*.{test,spec}.{ts,mts,cts,tsx,js,jsx}', '**/*.d.ts' ],+ reporter: [ 'text' ]+ }+ }+} );+```-## Vitest configuration+Common to both: `globals: true`, test glob `tests/**/*.[jt]s` (no `.spec`/`.test` suffix), the+`vite-plugin-svgo` plugin so `import icon from './x.svg'` resolves, and coverage via `v8` over+`src/**`.-Root `vitest.config.ts` exports two factories; **package configs should not configure Vitest-from scratch** — they call the factory:+## Debugging-```ts-// packages/ckeditor5-<name>/vitest.config.ts-import type { ViteUserConfig } from 'vitest/config';-import { createVitestConfig } from '../../vitest.config';+Browser-mode packages support an inspector + visible browser:-export default createVitestConfig( { name: '<short-package-name>' } );+```bash+vitest --inspect-brk --no-file-parallelism --browser.headless=false+# i.e. the package's `test:debug` script```-`createVitestConfig({ name, ...overrides })` provides the shared baseline; `name` is the short-package name used by `--project <short-name>`. Any extra props are merged into `test` as-overrides. The baseline sets:--- `globals: true`; `include: [ 'tests/**/*.{js,ts}' ]`;- `exclude: [ '**/_utils', '**/fixtures', '**/manual' ]`.-- `setupFiles: [ test_setup.js ]` — sets `globalThis.CKEDITOR_GLOBAL_LICENSE_KEY = 'GPL'`.-- `testTimeout: 5000`.-- **Browser mode** via `@vitest/browser-playwright`, Chromium (`channel: 'chrome'`), viewport- 1920×1080, `screenshotFailures: false`. (The browser provider is pluggable — `@vitest/browser-webdriverio`- is an equally valid choice; downstream projects pick one. `happy-dom`/`jsdom` also works for tests- that don't need real layout, though CKEditor UI/widget tests generally want a real browser.)-- **Coverage** (`v8`): `include: [ 'src/**' ]`, excludes `src/index.ts`, `src/augmentation.ts`,- `src/**/*config.ts`; `thresholds: { 100: true }`; reporters `text`, `html`.-- A `load-svg` plugin so `import icon from './x.svg'` yields the SVG string.--`createWorkspaceConfig( projects )` (default export) wires the root run across-`packages/*/vitest.config.ts` and the combined coverage (`html`, `json`, `lcovonly` →-`coverage-vitest/`). Because tests run in a **real browser**, DOM APIs are available directly-(no jsdom).--## Manual tests--Human-run smoke tests, served by `pnpm run manual` (default `http://localhost:8125`). A manual-test = **three files** sharing a base name in a `tests/manual/` directory (which must sit at the-root of `tests/`, e.g. `tests/manual/view/focus.js`, not `tests/view/manual/focus.js`):--- `<name>.md` — the steps to perform and what to verify.-- `<name>.js`/`.ts` — sets up an editor (`window.editor = editor;`).-- `<name>.html` — the markup (fragment is fine; merged into a template).--```js-import { ClassicEditor, Essentials, Paragraph } from 'ckeditor5';-ClassicEditor.create( { attachTo: document.querySelector( '#editor' ),- licenseKey: 'GPL', plugins: [ Essentials, Paragraph ] } )- .then( editor => { window.editor = editor; } );+`--no-file-parallelism` keeps one file at a time so breakpoints are predictable;+`--browser.headless=false` shows the Chrome window.++## Root orchestration++The root `package.json` splits the run because the browser-mode packages compete for browser+resources:++```bash+pnpm test:parallel # all but math & mermaid (and server/ckeditor5), in parallel+pnpm test:sequential # math & mermaid (and server/ckeditor5), sequentially+pnpm test:all # test:parallel && test:sequential```-`pnpm run manual` options: `--files`, `--language`, `--additional-languages`, `--debug`/`-d`-(e.g. `--debug engine` enables `// @if CK_DEBUG_ENGINE //` lines; on by default), `--port`,-`--disable-watch`. Add manual-test dependencies to the package `devDependencies`. Vitest-excludes `**/manual`, so manual tests never run as units. `pnpm run manual:verify` crawls the-manual-test pages headlessly to ensure they at least open without errors.+`math` and `mermaid` **must** run sequentially — running multiple headless Chrome instances at+once exhausts resources. Light (happy-dom) packages run in parallel.-## Memory-leak tests+## Notes-`pnpm run test:memory` builds a browser bundle and runs create/destroy cycles per editor in-headless Chromium, reporting **Baseline / Growth / Tail Growth / Status** (status `OK` when-Growth and Tail Growth stay under threshold). Options: `--editor <Name>` (repeatable; defaults-to Balloon/Classic/Decoupled/Inline/MultiRoot), `--html <file>` (from `scripts/memory/assets`),-`--no-build` (reuse existing assets).+- Some packages (`admonition`, `footnotes`, `keyboard-marker`) have a vitest config but **no tests+ yet** (`passWithNoTests` / empty `tests/`). Adding tests is encouraged.+- There are **no** manual-test or memory-leak harnesses in the Trilium plugin packages (those+ exist only in the upstream ckeditor5 monorepo).diff --git a/.claude/skills/ckeditor5-testing/references/test-conventions.md b/.claude/skills/ckeditor5-testing/references/test-conventions.mdnew file mode 100644index 0000000000..3ebd1ab592--- /dev/null+++ b/.claude/skills/ckeditor5-testing/references/test-conventions.md@@ -0,0 +1,80 @@+# Trilium test conventions & gotchas++Trilium never used Karma/Mocha/Sinon — the plugin tests are Vitest from the start, so there is no+migration to do. This reference collects the Trilium-specific conventions and traps when writing+CKEditor 5 plugin tests.++## Choosing an environment: happy-dom vs. browser mode++Pick per package (set in the package's `vitest.config.ts`):++- **happy-dom** (`admonition`, `collapsible`) — fast, but **not a real browser**.+ `getBoundingClientRect()` returns zeros, layout is stubbed, `ResizeObserver` is stubbed. Good+ for model logic, schema, conversion, and command behavior that never measures the DOM.+- **WebdriverIO browser mode** (`footnotes`, `keyboard-marker`, `math`, `mermaid`) — real headless+ Chrome, real layout. Required for anything that measures or positions DOM: widget rendering,+ balloon/toolbar placement, focus, scrolling, `getBoundingClientRect`. Gates `src/**` at 100%+ coverage.++If a test depends on real measurements and the package is on happy-dom, it will silently get zero+sizes — move the package (or the test) to browser mode rather than working around stubs. The+general `writing-unit-tests` skill reserves `@vitest/browser` for exactly these real-layout needs+(CKEditor, Excalidraw).++## Real-editor lifecycle & teardown++There are **no** test-editor factories in Trilium. Create a real `ClassicEditor` over a real+element with `licenseKey: 'GPL'`, and always tear it down:++```ts+beforeEach( async () => {+ editorElement = document.createElement( 'div' );+ document.body.appendChild( editorElement );+ editor = await ClassicEditor.create( editorElement, {+ licenseKey: 'GPL', plugins: [ Paragraph, MyPlugin ]+ } );+} );++afterEach( () => {+ editorElement.remove();+ return editor.destroy();+} );+```++Forgetting `editor.destroy()` or `editorElement.remove()` leaks editor DOM / body wrappers across+tests and causes flakiness.++## Assertion styles — both work++Vitest accepts **Jest-style** and **Chai-style** matchers, and the existing Trilium tests mix+them freely. Use whichever fits; don't "convert" one to the other for its own sake.++| Chai-style | Jest-style |+|------------|------------|+| `expect( x ).to.equal( y )` | `expect( x ).toBe( y )` |+| `expect( x ).to.deep.equal( y )` | `expect( x ).toEqual( y )` |+| `expect( x ).to.be.true` / `.false` | `expect( x ).toBe( true )` / `toBe( false )` |+| `expect( x ).to.instanceOf( C )` | `expect( x ).toBeInstanceOf( C )` |+| `expect( x ).to.throw( /re/ )` | `expect( x ).toThrow( /re/ )` |++There are **no** custom matchers (`equalMarkup`, `.attribute`) — compare stringified model/view+directly: `expect( _getModelData( model ) ).toEqual( '<paragraph>…</paragraph>' )`.++## Helpers & imports++- Import `_setModelData`, `_getModelData`, `_getViewData` (and editor classes, `keyCodes`, etc.)+ from `'ckeditor5'`. In-package source imports use a file extension (`../src/foo.js`).+- Spies/mocks via `vi` (`vi.spyOn` / `vi.fn` / `vi.useFakeTimers`).+- Test files: `tests/**/*.[jt]s`, no `.spec`/`.test` suffix.++## Running math & mermaid++`math` and `mermaid` run **sequentially** at the root (`pnpm test:sequential`) because each spins+up headless Chrome and they exhaust resources if run in parallel. Other packages run via+`pnpm test:parallel`. When running a single package, use `pnpm --filter @triliumnext/ckeditor5-<name> test`.++## See also++For general (non-CKEditor) Trilium testing — Preact components, jQuery widgets, client services,+server routes — use the `writing-unit-tests` skill, which also documents happy-dom's limits and+when to reach for `@vitest/browser`.diff --git a/.claude/skills/ckeditor5-testing/references/test-utilities.md b/.claude/skills/ckeditor5-testing/references/test-utilities.mdindex 7c06e39110..b1c5fc8647 100644--- a/.claude/skills/ckeditor5-testing/references/test-utilities.md+++ b/.claude/skills/ckeditor5-testing/references/test-utilities.md@@ -1,87 +1,64 @@-# Test utilities & data helpers--> **Path scope.** `@ckeditor/ckeditor5-core/tests/_utils/…` and `packages/…` refer to the upstream-> CKEditor 5 repository ([github.com/ckeditor/ckeditor5](https://github.com/ckeditor/ckeditor5)), not-> your project. **Downstream caveat:** the model/view helpers (`_setModelData` etc.) are published-> and importable from the `ckeditor5` / `@ckeditor/ckeditor5-engine` npm packages, so they work in-> any project. The **test editors** below live in the monorepo's `tests/_utils` and are generally-> *not* shipped to npm — inside the ckeditor5 repo import them as shown; in a standalone package,-> follow your package's own test setup (e.g. the package-generator template) and/or test against a-> real editor build such as `ClassicEditor`.--The building blocks for editor tests: lightweight test editors, shared `_utils`, and the-model/view stringify-parse helpers.--## Test editors (pick the lightest that works)--All live in `@ckeditor/ckeditor5-core/tests/_utils/` (upstream) and expose a static async `create()`-returning a Promise. Import with the explicit `.js` extension.--| Editor | Pipelines | Use when |-|--------|-----------|----------|-| `ModelTestEditor` | Full **data** pipeline; **editing pipeline disabled** (no view rendering). Creates the main model root. | Testing pure model logic / commands that only read/write the model. Cheapest. |-| `VirtualTestEditor` | Full **data + engine** pipeline, **no DOM rendering**. Creates the main model root. | Testing engine behavior, conversion, schema, features — without a real editable element. The default for most feature tests. |-| `ClassicTestEditor` | A simplified **full classic editor** with UI mounted into a real element (`ElementApiMixin`, `BoxedEditorUIView`, `InlineEditableUIView`). | Testing UI (toolbar buttons, balloons), DOM interaction, focus, or anything needing `editor.ui`. |--```js-import { ModelTestEditor } from '@ckeditor/ckeditor5-core/tests/_utils/modeltesteditor.js';-import { VirtualTestEditor } from '@ckeditor/ckeditor5-core/tests/_utils/virtualtesteditor.js';-import { ClassicTestEditor } from '@ckeditor/ckeditor5-core/tests/_utils/classictesteditor.js';--// Model only:-editor = await ModelTestEditor.create(); // then register schema yourself--// Engine + plugins, no DOM:-editor = await VirtualTestEditor.create( { plugins: [ Paragraph, MyFeature ] } );--// Full UI in a real element (remember to create AND remove the element):-editorElement = document.createElement( 'div' );-document.body.appendChild( editorElement );-editor = await ClassicTestEditor.create( editorElement, {- plugins: [ Paragraph, MyFeatureUI, Heading ],- toolbar: [ 'myButton' ]-} );-```+# Test utilities & data helpers (Trilium)++Trilium plugin tests run against a **real editor** and assert with the model/view stringify-parse+helpers. There are no test-editor factories in Trilium.-Teardown matters: `await editor.destroy()` in `afterEach`, and `editorElement.remove()` if you-appended one. Tests don't pass a `licenseKey` — `test_setup.js` sets the global GPL key.+## Test against a real `ClassicEditor`-## Other `_utils` helpers (core)+Create a real editor over a real DOM element. Pass `licenseKey: 'GPL'` and only the plugins the+test needs. Tear down in `afterEach`: destroy the editor and remove the element.-- `ArticlePluginSet` (`articlepluginset.js`) — a glue plugin bundling a typical article editor- (Essentials, Paragraph, Heading, Bold/Italic, List, Link, BlockQuote, Image+toolbar/caption,- Table+toolbar, MediaEmbed, Indent, Autoformat). Drop it into `plugins: [ ArticlePluginSet ]`- to get a realistic editor without listing everything.-- `removeEditorBodyOrphans()` (`cleanup.js`) — removes leftover `.ck-body-wrapper` elements- from the DOM; use after tests that intentionally crash editors (orphaned body collections).-- `generateLicenseKey( options )` (`generatelicensekey.js`) — builds license keys for license- tests (`isExpired`, `expExist`, `licenseType`, `distributionChannel`, …).-- `testUtils` / `testUtils.createSinonSandbox()` (`utils.js`) — **legacy Sinon helper**. In- Vitest, don't use it; use `vi.spyOn`/`vi.fn` (auto-restored, or `vi.restoreAllMocks()` in- `afterEach`). See `migration-from-karma.md`.+```ts+import { ClassicEditor, Paragraph } from 'ckeditor5';+import { describe, beforeEach, afterEach, it, expect } from 'vitest';+import MyEditing from '../src/myediting.js';-Packages also keep their own `tests/_utils/` (excluded from the run by config) for-feature-specific fixtures and helpers — follow the local conventions of the package you edit.+describe( 'MyEditing', () => {+ let editorElement: HTMLDivElement, editor: ClassicEditor, model;++ beforeEach( async () => {+ editorElement = document.createElement( 'div' );+ document.body.appendChild( editorElement );++ editor = await ClassicEditor.create( editorElement, {+ licenseKey: 'GPL',+ plugins: [ Paragraph, MyEditing ]+ } );+ model = editor.model;+ } );++ afterEach( () => {+ editorElement.remove();+ return editor.destroy();+ } );+} );+```++Notes:+- `editor.model`, `editor.editing.view`, `editor.ui`, `editor.commands`, `editor.plugins` are all+ available — it's a real editor, not a stripped-down test editor.+- Commands can be instantiated directly for focused tests:+ `command = new InsertMermaidCommand( editor )` after the editor is created.+- Teardown matters: always `editor.destroy()` **and** `editorElement.remove()`, or leftover+ editor DOM/body wrappers will leak between tests.++> The upstream ckeditor5 monorepo ships `ModelTestEditor` / `VirtualTestEditor` /+> `ClassicTestEditor` in `@ckeditor/ckeditor5-core/tests/_utils`, but those are monorepo-internal+> and are **not** available in Trilium. Use a real `ClassicEditor` as above.## Model & view data helpers-From the engine's `dev-utils` modules. They are re-exported by the `ckeditor5` aggregate, so-**import them from `'ckeditor5'` in your own project** (or from `@ckeditor/ckeditor5-engine`, the-in-monorepo style). They stringify/parse engine structures and are the backbone of assertions.-**Test/debug only — never in `src/`.**+Imported from the `ckeditor5` package. They stringify/parse engine structures and are the backbone+of assertions. **Test/debug only — never in `src/`.**Model:- `_setModelData( model, string )` — replace the document content + selection from a string.- `_getModelData( model[, options] )` — serialize current model + selection to a string.-- `_stringifyModel( node[, selectionOrRange] )` / `_parseModel( string, schema )` — pure- serialize/parse without touching a document.View:-- `_getViewData( view[, options] )` / `_setViewData( view, string )` — same for a view document- (e.g. `editor.editing.view`).-- `_stringifyView( node )` / `_parseView( string )`.+- `_getViewData( view[, options] )` — serialize a view document (e.g. `editor.editing.view`).-```js+```tsimport { _setModelData, _getModelData, _getViewData } from 'ckeditor5';_setModelData( model, '<paragraph>foo[]bar</paragraph>' );@@ -89,15 +66,18 @@ expect( _getModelData( model ) ).toEqual( '<paragraph>foo[]bar</paragraph>' );expect( _getViewData( editor.editing.view ) ).toEqual( '<p>foo{}bar</p>' );```+Existing Trilium tests sometimes alias on import, e.g.+`import { _setModelData as setModelData, _getModelData as getModelData } from 'ckeditor5'`.+### Selection / range string syntax- `[` … `]` — a position/range **anchored in an element** (also a collapsed `[]` caret).- `{` … `}` — a position/range **anchored inside a text node**.- A mixed range can use both ends, e.g. `<p>{Foo]<b>Bar</b></p>` starts in the `Foo` text nodeand ends in `<p>` at offset 1.-- Text attributes serialize as `<$text key="value">text</$text>`; selection attributes appear- on the collapsed selection.+- Text attributes serialize as `<$text key="value">text</$text>`; selection attributes appear on+ the collapsed selection.+- Element ranges wrap the node, e.g. `[<mermaid source="..."></mermaid>]` selects the element.-`_getModelData`/`_getViewData` options of note: `withoutSelection: true` to omit the selection-markers; `rootName` to target a non-default root. Check the `dev-utils/model` and-`dev-utils/view` API for the full option list.+`_getModelData`/`_getViewData` options of note: `withoutSelection: true` to omit selection+markers; `rootName` to target a non-default root.