Skip to content

Build your personal knowledge base with Trilium Notes

chore(skills): document persisting data-trilium-* attributes for CKEditor plugins

Elian Doranaad50f47f414
diff --git a/.claude/skills/ckeditor5-plugin-development/SKILL.md b/.claude/skills/ckeditor5-plugin-development/SKILL.md
index 6fb0d7b633..1c0b8b5820 100644
--- a/.claude/skills/ckeditor5-plugin-development/SKILL.md
+++ b/.claude/skills/ckeditor5-plugin-development/SKILL.md
@@ -9,7 +9,8 @@ description: >-
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()),
- registering a plugin into plugins.ts / the editor classes / toolbar.ts, or
+ registering a plugin into plugins.ts / the editor classes / toolbar.ts, persisting a
+ `data-trilium-*` attribute through the model→view→data→markdown→share pipeline, or
adding a new plugin folder under src/plugins/. Covers the architecture,
idiomatic patterns, Trilium packaging/registration, code-style conventions,
and a review checklist.
@@ -260,6 +261,7 @@ Load the focused reference for the task at hand:
| `references/widgets.md` | Block & inline widgets: `toWidget`/`toWidgetEditable`, nested editables, `insertObject`, widget toolbars, view↔model position mapping, custom properties, and external/async-rendered widgets (UI-element render callbacks, re-render on change, stale-render guard, lazy-load). |
| `references/conventions.md` | Trilium conventions: imports from `ckeditor5`/`@triliumnext` + required file extensions, per-package license/headers (not uniform), `@triliumnext` scope + `workspace:*`, per-package tsconfig, `?raw` icons, localization via `editor.t()` message ids, `declare module 'ckeditor5'` augmentation, plus the upstream naming/CSS/BEM/JSDoc/TypeScript rules inherited via `eslint-config-ckeditor5`. For writing idiomatic code and reviewing. |
| `references/tooling-and-packaging.md` | Trilium packaging & wiring: the `@triliumnext/ckeditor5-<feature>` package layout, `workspace:*` deps, `main: src/index.ts` (no per-package dist), tsconfig/eslint/stylelint setup, the full registration flow (`plugins.ts` arrays → editor classes `builtinPlugins` → `toolbar.ts`), the three editor classes, the Vite build, how `apps/client` creates the editor (config, watchdog, lazy premium), and the Inspector. |
+| `references/persisted-attributes.md` | Persisting a `data-trilium-*` attribute end to end: schema → both conversion directions → the **deliberate** markdown export/import decision (collapsed is DROPPED, task-state is KEPT) → editing-view-only CSS so read-only and share rendering stay correct. Read it before storing plugin state in the saved note content. |
| `references/review-checklist.md` | A structured checklist for reviewing an existing plugin (architecture, schema, conversion, commands, UI, a11y, conventions). |
| `references/recipes.md` | Task-oriented how-tos: insert content, find/iterate nodes, custom observers, place caret, extend other plugins' UI, etc. |
| `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, sanitizing untrusted HTML (CKEditor ships no sanitizer — the host supplies one per feature namespace), clipboard pipeline, markers, post-fixers, async/upload. Each cites its source file. |
diff --git a/.claude/skills/ckeditor5-plugin-development/references/persisted-attributes.md b/.claude/skills/ckeditor5-plugin-development/references/persisted-attributes.md
new file mode 100644
index 0000000000..bde5842515
--- /dev/null
+++ b/.claude/skills/ckeditor5-plugin-development/references/persisted-attributes.md
@@ -0,0 +1,120 @@
+# Persisting a `data-trilium-*` attribute (model → view → data → markdown → share)
+
+When a plugin stores state in the saved note content, that state has to survive the whole pipeline. Two real plugins are the canonical worked examples, and they make **opposite** markdown decisions:
+
+| Plugin | Model attr | Data attr | Scope | Markdown | File |
+|---|---|---|---|---|---|
+| `CollapsibleListItems` | `listCollapsed` | `data-trilium-collapsed` | list item | **DROPPED** on export | `plugins/collapsible_list_items.ts` |
+| `TodoListMultistateEditing` | `taskState` | `data-trilium-task-state` | block | **KEPT** through export+import | `plugins/todo_list_multistate/todo_list_multistate_editing.ts` |
+
+This is **explicit conversion**, not GeneralHtmlSupport. GHS (`config.ts` `htmlSupport: buildHtmlSupportConfig()`, derived from the `allowedHtmlTags` option) is the separate path for arbitrary *user-pasted* HTML, not for a feature you author.
+
+## Step 1 — schema
+
+Allow the attribute on the model node (`collapsible_list_items.ts:46`):
+
+```ts
+editor.model.schema.extend("$block", { allowAttributes: LIST_COLLAPSED_ATTRIBUTE });
+```
+
+`todo_list_multistate_editing.ts:105` does the same for `TASK_STATE_ATTRIBUTE`.
+
+## Step 2 — conversion BOTH directions (asymmetric = the classic bug)
+
+### List-item-scoped state → `ListEditing.registerDowncastStrategy`
+
+Lists are flat in the model (sibling blocks with `listIndent`/`listItemId`), so item-level attributes use the list plugin's downcast strategy, which writes onto the rendered `<li>`. `collapsible_list_items.ts:50`:
+
+```ts
+editor.plugins.get(ListEditing).registerDowncastStrategy({
+ scope: "item",
+ attributeName: LIST_COLLAPSED_ATTRIBUTE,
+ setAttributeOnDowncast(writer, value, element) {
+ if (value) {
+ writer.setAttribute(COLLAPSED_DATA_ATTRIBUTE, "true", element); // data-trilium-collapsed
+ } else {
+ writer.removeAttribute(COLLAPSED_DATA_ATTRIBUTE, element);
+ }
+ }
+});
+
+editor.conversion.for("upcast").attributeToAttribute({
+ view: { name: "li", key: COLLAPSED_DATA_ATTRIBUTE },
+ model: {
+ key: LIST_COLLAPSED_ATTRIBUTE,
+ value: (viewElement) => viewElement.getAttribute(COLLAPSED_DATA_ATTRIBUTE) === "true" ? true : null
+ }
+});
+```
+
+`todo_list_multistate_editing.ts:123` is the richer version: its `registerDowncastStrategy` (`scope:"item"`) writes `data-trilium-task-state` only for non-anchor states, and its `options.dataPipeline` check keeps an editing-only `tn-unknown-task-state` class OUT of the saved data — note the **data vs editing pipeline split**: classes/markers you only want in the editing view must be gated on `!options?.dataPipeline`.
+
+### Block-level state → `attributeToAttribute` both ways
+
+For a plain block attribute (not list-scoped), register `attributeToAttribute` for downcast and upcast symmetrically. The upcast value-normalizer returns `null` for empty/anchor values so junk doesn't become a model attribute.
+
+> **Rule:** every downcast needs a matching upcast or the value silently vanishes on the next load. If you write the downcast, write the upcast in the same commit.
+
+## Step 3 — DECIDE the markdown behaviour, then test it
+
+Markdown round-trip is **not** automatic and **not** guaranteed — it's a per-feature choice made in `packages/trilium-core/src/services/{export,import}/markdown.ts`.
+
+### KEEP (task-state) — export reads the data attr
+
+`export/markdown.ts:365-372` (inside the list-item replacement rule):
+
+```ts
+} else if (parent.classList.contains("todo-list")) {
+ const state = (node as HTMLElement).getAttribute("data-trilium-task-state");
+ const stateMarker = state
+ ? currentTaskStates.find((s) => s.name === state)?.markdownSymbol
+ : undefined;
+ if (stateMarker) {
+ prefix = `- [${stateMarker}] `;
+ } else {
+ const isChecked = node.querySelector("input[type=checkbox]:checked");
+ prefix = (isChecked ? "- [x] " : "- [ ] ");
+ }
+}
+```
+
+Tests: export `export/markdown.spec.ts:555` ("exports todo list multistate markers from data-trilium-task-state"); import `import/markdown.spec.ts:401` ("imports todo list multistate markers as data-trilium-task-state").
+
+### DROP (collapsed) — no markdown syntax, children survive as bullets
+
+There is no markdown for "collapsed", so the attribute is dropped on export while the nested `<li>`s round-trip as ordinary bullets. The decision is documented and locked by a test — `export/markdown.spec.ts:704`:
+
+```ts
+it("drops data-trilium-collapsed but keeps the collapsed item's children as bullets", () => {
+ // Collapsing is editor-only UI state … Markdown has no syntax for it — so the attribute
+ // is dropped on export while the nested structure still round-trips as ordinary bullets.
+ const html = /* <ul><li data-trilium-collapsed="true">Parent<ul><li>Child</li></ul></li>… */;
+ const expected = `* Parent\n * Child\n* Sibling`;
+ expect(markdownExportService.toMarkdown(html)).toBe(expected);
+});
+```
+
+Even when dropped on markdown export, the attribute must still survive the **HTML import/clone** path: `import/single.spec.ts:88` ("safe import preserves data-trilium-collapsed on list items") asserts the data attribute isn't stripped by the HTML sanitizer on import.
+
+**Whichever you choose, add both an export test (`export/markdown.spec.ts`) and an import test (`import/markdown.spec.ts` or `import/single.spec.ts`).** If your attribute also renders outside the editor, extend `markdown_renderer.ts`/`.spec.ts` in `@triliumnext/commons` too. Coverage of these core specs goes through the server suite — see the **analyzing-coverage** and **writing-unit-tests** skills.
+
+## Step 4 — editing-only visuals scoped to the editing view
+
+Any hide/show or decorative behaviour must be **CSS scoped to the editing view**, imported at the top of the plugin (`collapsible_list_items.ts:1`):
+
+```ts
+import "../theme/collapsible_list_items.css";
+```
+
+Because the hide is CSS in the editing pipeline only, the saved data still contains the full (hidden) subtree, so **read-only rendering and the share-theme stay fully expanded** — share-theme needs no change. The spec proves it: in the editor the nested `<ul>` computes `display: none` (`collapsible_list_items.spec.ts:61-65`), but `editor.getData()` still contains the children and `data-trilium-collapsed="true"` (`:67`).
+
+For visual state that depends on the *value* of the attribute (task-state icons), the CSS can target the data attribute directly — `packages/trilium-core/src/services/task_states.ts:181` (the core copy, **not** the `apps/client/.../services/task_states.ts` one `config.ts` imports) generates `[data-trilium-task-state="<name>"] { … }` rules, which is what makes the icons appear in read-only and shared notes too.
+
+## Step 5 — test the model↔data round-trip in the plugin spec
+
+The browser spec asserts the full loop (`collapsible_list_items.spec.ts`):
+- toggle command → the rendered `<li>` carries the attribute (`:35`) → `editor.getData()` contains `data-trilium-collapsed="true"` (`:43`);
+- `editor.setData('<ul><li data-trilium-collapsed="true">…')` → upcast produces the model attribute (`:53-67`);
+- loading a collapsed subtree does **not** auto-expand (children arrive with the parent), and junk persisted state with nothing to collapse is normalized away (`:71` onward).
+
+Harness reminders (full detail in the **ckeditor5-testing** skill): `licenseKey: "GPL"` is mandatory in every `*Editor.create(...)`; lists are **flat** in the model (sibling blocks related by `listIndent`/`listItemId`, not nested `<li>`), so don't write nested-element model fixtures for them; import `_setModelData as setModelData` from `"ckeditor5"`; run with `pnpm --filter ckeditor5 test src/plugins/<x>.spec.ts`.