Skip to content

Build your personal knowledge base with Trilium Notes

client/text editor: create a collapsible plugin for CK Editor

Adorian Doranca8e7b98b398
diff --git a/apps/client/src/widgets/type_widgets/text/toolbar.ts b/apps/client/src/widgets/type_widgets/text/toolbar.ts
index b5ef750a1f..b6afecb2b7 100644
--- a/apps/client/src/widgets/type_widgets/text/toolbar.ts
+++ b/apps/client/src/widgets/type_widgets/text/toolbar.ts
@@ -67,6 +67,7 @@ export function buildClassicToolbar(multilineToolbar: boolean) {
"|",
"blockQuote",
"admonition",
+ "collapsible",
"insertTable",
"|",
"code",
@@ -127,6 +128,7 @@ export function buildFloatingToolbar() {
"|",
"blockQuote",
"admonition",
+ "collapsible",
"codeBlock",
"insertTable",
"footnote",
diff --git a/packages/ckeditor5-collapsible/package.json b/packages/ckeditor5-collapsible/package.json
new file mode 100644
index 0000000000..015040625b
--- /dev/null
+++ b/packages/ckeditor5-collapsible/package.json
@@ -0,0 +1,30 @@
+{
+ "name": "@triliumnext/ckeditor5-collapsible",
+ "version": "1.0.0",
+ "description": "Collapsible block (HTML <details>/<summary>) feature for CKEditor 5.",
+ "keywords": [
+ "ckeditor",
+ "ckeditor5",
+ "ckeditor 5",
+ "ckeditor5-feature",
+ "ckeditor5-plugin",
+ "collapsible",
+ "details"
+ ],
+ "type": "module",
+ "main": "src/index.ts",
+ "engines": {
+ "node": ">=18.0.0",
+ "npm": ">=5.7.1"
+ },
+ "devDependencies": {
+ "ckeditor5": "48.0.1",
+ "typescript": "6.0.3"
+ },
+ "peerDependencies": {
+ "ckeditor5": "48.0.1"
+ },
+ "author": "Trilium contributors",
+ "license": "GPL-2.0-or-later",
+ "scripts": {}
+}
diff --git a/packages/ckeditor5-collapsible/src/augmentation.ts b/packages/ckeditor5-collapsible/src/augmentation.ts
new file mode 100644
index 0000000000..9aa910e6e4
--- /dev/null
+++ b/packages/ckeditor5-collapsible/src/augmentation.ts
@@ -0,0 +1,16 @@
+import CollapsibleCommand from "./collapsiblecommand.js";
+import CollapsibleEditing from "./collapsibleediting.js";
+import CollapsibleUI from "./collapsibleui.js";
+import type { Collapsible } from "./index.js";
+
+declare module "ckeditor5" {
+ interface PluginsMap {
+ [Collapsible.pluginName]: Collapsible;
+ [CollapsibleEditing.pluginName]: CollapsibleEditing;
+ [CollapsibleUI.pluginName]: CollapsibleUI;
+ }
+
+ interface CommandsMap {
+ collapsible: CollapsibleCommand;
+ }
+}
diff --git a/packages/ckeditor5-collapsible/src/collapsible.ts b/packages/ckeditor5-collapsible/src/collapsible.ts
new file mode 100644
index 0000000000..4e328d57e4
--- /dev/null
+++ b/packages/ckeditor5-collapsible/src/collapsible.ts
@@ -0,0 +1,16 @@
+import { Plugin } from 'ckeditor5';
+
+import CollapsibleEditing from './collapsibleediting.js';
+import CollapsibleUI from './collapsibleui.js';
+
+export default class Collapsible extends Plugin {
+
+ public static get requires() {
+ return [ CollapsibleEditing, CollapsibleUI ] as const;
+ }
+
+ public static get pluginName() {
+ return "Collapsible" as const;
+ }
+
+}
diff --git a/packages/ckeditor5-collapsible/src/collapsiblecommand.ts b/packages/ckeditor5-collapsible/src/collapsiblecommand.ts
new file mode 100644
index 0000000000..e8b802c310
--- /dev/null
+++ b/packages/ckeditor5-collapsible/src/collapsiblecommand.ts
@@ -0,0 +1,58 @@
+import { Command } from "ckeditor5";
+
+/**
+ * Inserts a new collapsible block (<details><summary>…</summary>…</details>) at the
+ * current selection. The summary becomes the editable title; the body holds a single
+ * empty paragraph by default and may contain any block content (including nested
+ * collapsibles).
+ */
+export default class CollapsibleCommand extends Command {
+
+ declare public value: boolean;
+
+ public override refresh(): void {
+ const selection = this.editor.model.document.selection;
+ const block = selection.getFirstPosition()?.findAncestor("details");
+ this.value = !!block;
+ this.isEnabled = this._checkEnabled();
+ }
+
+ public override execute(): void {
+ const editor = this.editor;
+ const model = editor.model;
+
+ model.change(writer => {
+ const detailsEl = writer.createElement("details");
+ const summaryEl = writer.createElement("summary");
+ const paragraphEl = writer.createElement("paragraph");
+
+ writer.append(summaryEl, detailsEl);
+ writer.append(paragraphEl, detailsEl);
+
+ model.insertContent(detailsEl);
+
+ // Make sure the user can put the caret immediately above and below the block
+ // without having to escape via keyboard tricks (matches the table plugin's UX).
+ const before = detailsEl.previousSibling;
+ if (!before || !before.is("element", "paragraph")) {
+ writer.insertElement("paragraph", writer.createPositionBefore(detailsEl));
+ }
+ const after = detailsEl.nextSibling;
+ if (!after || !after.is("element", "paragraph")) {
+ writer.insertElement("paragraph", writer.createPositionAfter(detailsEl));
+ }
+
+ // Place the cursor inside the summary so the user can immediately type a title.
+ writer.setSelection(summaryEl, 0);
+ });
+ }
+
+ private _checkEnabled(): boolean {
+ const model = this.editor.model;
+ const firstPosition = model.document.selection.getFirstPosition();
+ if (!firstPosition) {
+ return false;
+ }
+ return !!model.schema.findAllowedParent(firstPosition, "details");
+ }
+}
diff --git a/packages/ckeditor5-collapsible/src/collapsibleediting.ts b/packages/ckeditor5-collapsible/src/collapsibleediting.ts
new file mode 100644
index 0000000000..9a6baf0407
--- /dev/null
+++ b/packages/ckeditor5-collapsible/src/collapsibleediting.ts
@@ -0,0 +1,186 @@
+import { Plugin, Enter, Delete, type ViewDocumentEnterEvent, type ViewDocumentDeleteEvent } from "ckeditor5";
+import CollapsibleCommand from "./collapsiblecommand.js";
+
+/**
+ * Defines the schema, conversion and basic key handling for collapsible blocks.
+ *
+ * Model:
+ * <details>
+ * <summary>title text</summary>
+ * …any block content (including nested <details>)…
+ * </details>
+ *
+ * Data view (output HTML): <details class="trilium-collapsible"><summary>…</summary>…</details>
+ * Editing view: same, but with `open` attribute so the body is always visible while editing.
+ */
+export default class CollapsibleEditing extends Plugin {
+
+ public static get pluginName() {
+ return "CollapsibleEditing" as const;
+ }
+
+ public static get requires() {
+ return [Enter, Delete] as const;
+ }
+
+ public init(): void {
+ const editor = this.editor;
+ const schema = editor.model.schema;
+ const conversion = editor.conversion;
+
+ editor.commands.add("collapsible", new CollapsibleCommand(editor));
+
+ // Schema --------------------------------------------------------------
+
+ schema.register("details", {
+ inheritAllFrom: "$container"
+ });
+
+ schema.register("summary", {
+ allowIn: "details",
+ allowContentOf: "$block",
+ isLimit: true
+ });
+
+ // Conversion ----------------------------------------------------------
+
+ // <details> upcast: accept any <details>, ignore the `open` attribute.
+ conversion.for("upcast").elementToElement({
+ view: "details",
+ model: "details"
+ });
+
+ // <details> data downcast: emit a plain <details class="trilium-collapsible">.
+ conversion.for("dataDowncast").elementToElement({
+ model: "details",
+ view: (_modelElement, { writer }) => {
+ return writer.createContainerElement("details", { class: "trilium-collapsible" });
+ }
+ });
+
+ // <details> editing downcast: force `open` so the user can edit the body.
+ conversion.for("editingDowncast").elementToElement({
+ model: "details",
+ view: (_modelElement, { writer }) => {
+ return writer.createContainerElement("details", {
+ class: "trilium-collapsible",
+ open: "open"
+ });
+ }
+ });
+
+ // <summary> conversion (same in both pipelines).
+ conversion.for("upcast").elementToElement({ view: "summary", model: "summary" });
+ conversion.for("downcast").elementToElement({ model: "summary", view: "summary" });
+
+ // UX: pressing Enter inside an empty summary moves the cursor into the body.
+ const viewDocument = editor.editing.view.document;
+ const selection = editor.model.document.selection;
+
+ this.listenTo<ViewDocumentEnterEvent>(viewDocument, "enter", (evt, data) => {
+ if (!selection.isCollapsed) {
+ return;
+ }
+
+ const position = selection.getLastPosition();
+ const summary = position?.findAncestor("summary");
+ if (!summary) {
+ return;
+ }
+
+ const details = summary.parent;
+ if (!details || !details.is("element", "details")) {
+ return;
+ }
+
+ // Always: stop the default Enter behavior inside <summary> (no newlines in titles).
+ data.preventDefault();
+ evt.stop();
+
+ // Move the cursor to the start of the first body block.
+ const firstBodyBlock = summary.nextSibling;
+ if (firstBodyBlock && firstBodyBlock.is("element")) {
+ editor.model.change(writer => {
+ writer.setSelection(firstBodyBlock, 0);
+ });
+ }
+ }, { context: "summary" });
+
+ // UX: pressing Enter inside an empty trailing paragraph of the body exits the
+ // collapsible (text + Enter + Enter → out — same convention as blockquote).
+ this.listenTo<ViewDocumentEnterEvent>(viewDocument, "enter", (evt, data) => {
+ if (!selection.isCollapsed) {
+ return;
+ }
+
+ const positionParent = selection.getLastPosition()?.parent;
+ if (!positionParent || !positionParent.is("element") || positionParent.is("element", "summary")) {
+ return;
+ }
+ if (!positionParent.isEmpty || positionParent.nextSibling) {
+ return;
+ }
+
+ const details = positionParent.parent;
+ if (!details || !details.is("element", "details")) {
+ return;
+ }
+
+ data.preventDefault();
+ evt.stop();
+
+ editor.model.change(writer => {
+ writer.remove(positionParent);
+ const after = details.nextSibling;
+ if (after && after.is("element", "paragraph")) {
+ writer.setSelection(after, 0);
+ } else {
+ const newParagraph = writer.createElement("paragraph");
+ writer.insert(newParagraph, writer.createPositionAfter(details));
+ writer.setSelection(newParagraph, 0);
+ }
+ });
+ });
+
+ // UX: backspace at the start of an empty summary unwraps the collapsible.
+ this.listenTo<ViewDocumentDeleteEvent>(viewDocument, "delete", (evt, data) => {
+ if (data.direction !== "backward" || !selection.isCollapsed) {
+ return;
+ }
+
+ const position = selection.getLastPosition();
+ const summary = position?.findAncestor("summary");
+ if (!summary || !summary.isEmpty) {
+ return;
+ }
+
+ const details = summary.parent;
+ if (!details || !details.is("element", "details")) {
+ return;
+ }
+
+ data.preventDefault();
+ evt.stop();
+
+ editor.model.change(writer => {
+ writer.unwrap(details);
+ });
+ }, { context: "summary" });
+
+ // Postfixer: drop entirely empty <details> elements (defensive cleanup).
+ editor.model.document.registerPostFixer(writer => {
+ const changes = editor.model.document.differ.getChanges();
+ for (const entry of changes) {
+ if (entry.type !== "remove" && entry.type !== "insert") {
+ continue;
+ }
+ const parent = entry.position.parent;
+ if (parent.is("element", "details") && parent.isEmpty) {
+ writer.remove(parent);
+ return true;
+ }
+ }
+ return false;
+ });
+ }
+}
diff --git a/packages/ckeditor5-collapsible/src/collapsibleui.ts b/packages/ckeditor5-collapsible/src/collapsibleui.ts
new file mode 100644
index 0000000000..858c52cfd3
--- /dev/null
+++ b/packages/ckeditor5-collapsible/src/collapsibleui.ts
@@ -0,0 +1,36 @@
+import { ButtonView, Plugin } from "ckeditor5";
+import collapsibleIcon from "../theme/icons/collapsible.svg?raw";
+
+export default class CollapsibleUI extends Plugin {
+
+ public static get pluginName() {
+ return "CollapsibleUI" as const;
+ }
+
+ public init(): void {
+ const editor = this.editor;
+ const t = editor.locale.t;
+
+ editor.ui.componentFactory.add("collapsible", locale => {
+ const command = editor.commands.get("collapsible")!;
+ const button = new ButtonView(locale);
+
+ button.set({
+ label: t("Collapsible block"),
+ icon: collapsibleIcon,
+ tooltip: true,
+ isToggleable: true
+ });
+
+ button.bind("isOn").to(command, "value");
+ button.bind("isEnabled").to(command, "isEnabled");
+
+ this.listenTo(button, "execute", () => {
+ editor.execute("collapsible");
+ editor.editing.view.focus();
+ });
+
+ return button;
+ });
+ }
+}
diff --git a/packages/ckeditor5-collapsible/src/index.ts b/packages/ckeditor5-collapsible/src/index.ts
new file mode 100644
index 0000000000..053e369b2d
--- /dev/null
+++ b/packages/ckeditor5-collapsible/src/index.ts
@@ -0,0 +1,12 @@
+import collapsibleIcon from "../theme/icons/collapsible.svg?raw";
+import "./augmentation.js";
+import "../theme/collapsible.css";
+
+export { default as Collapsible } from "./collapsible.js";
+export { default as CollapsibleEditing } from "./collapsibleediting.js";
+export { default as CollapsibleUI } from "./collapsibleui.js";
+export type { default as CollapsibleCommand } from "./collapsiblecommand.js";
+
+export const icons = {
+ collapsibleIcon
+};
diff --git a/packages/ckeditor5-collapsible/theme/collapsible.css b/packages/ckeditor5-collapsible/theme/collapsible.css
new file mode 100644
index 0000000000..84f02c004d
--- /dev/null
+++ b/packages/ckeditor5-collapsible/theme/collapsible.css
@@ -0,0 +1,33 @@
+/*
+ * Shared styles for collapsible blocks (rendered as native HTML <details>/<summary>).
+ * Used in both the editor and the read-only/published view via .ck-content.
+ */
+
+.ck-content details.trilium-collapsible {
+ border: 1px solid var(--card-border-color, #ddd);
+ border-radius: 6px;
+ background: var(--card-background-color, transparent);
+ padding: 0.5em 1em;
+ margin: 1em 0;
+}
+
+.ck-content details.trilium-collapsible > summary {
+ cursor: pointer;
+ font-weight: 600;
+ padding: 0.25em 0;
+ outline: none;
+}
+
+.ck-content details.trilium-collapsible[open] > summary {
+ margin-bottom: 0.5em;
+}
+
+/*
+ * Editing-only tweaks: while the user is editing we keep the block expanded
+ * (the `open` attribute is forced by the editing downcast) and we make the
+ * summary behave like a regular editable text block instead of a toggle.
+ */
+
+.ck-editor__editable details.trilium-collapsible > summary {
+ cursor: text;
+}
diff --git a/packages/ckeditor5-collapsible/theme/icons/collapsible.svg b/packages/ckeditor5-collapsible/theme/icons/collapsible.svg
new file mode 100644
index 0000000000..d343e8b0e3
--- /dev/null
+++ b/packages/ckeditor5-collapsible/theme/icons/collapsible.svg
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20">
+ <path fill="currentColor" d="M2 3h16v3H2V3zm0 6h16v2H2V9zm0 4h10v2H2v-2zm0 4h10v2H2v-2z"/>
+ <path fill="currentColor" d="M16 13.5l-3 3 .9.9L16 15.3l2.1 2.1.9-.9z"/>
+</svg>
diff --git a/packages/ckeditor5-collapsible/tsconfig.json b/packages/ckeditor5-collapsible/tsconfig.json
new file mode 100644
index 0000000000..4b991ad444
--- /dev/null
+++ b/packages/ckeditor5-collapsible/tsconfig.json
@@ -0,0 +1,32 @@
+{
+ "compilerOptions": {
+ "types": [],
+ "lib": [
+ "ES2019",
+ "ES2020.String",
+ "DOM",
+ "DOM.Iterable"
+ ],
+ "noImplicitAny": true,
+ "noImplicitOverride": true,
+ "composite": true,
+ "strict": true,
+ "target": "es2019",
+ "sourceMap": true,
+ "allowJs": true,
+ "moduleDetection": "force",
+ "moduleResolution": "NodeNext",
+ "module": "NodeNext",
+ "skipLibCheck": true,
+ "noUncheckedSideEffectImports": false,
+ "outDir": "out-tsc",
+ "typeRoots": [
+ "typings",
+ "node_modules/@types"
+ ]
+ },
+ "include": [
+ "./src",
+ "./typings"
+ ]
+}
diff --git a/packages/ckeditor5-collapsible/typings/types.d.ts b/packages/ckeditor5-collapsible/typings/types.d.ts
new file mode 100644
index 0000000000..09be57e1c9
--- /dev/null
+++ b/packages/ckeditor5-collapsible/typings/types.d.ts
@@ -0,0 +1,4 @@
+declare module '*.svg?raw' {
+ const content: string;
+ export default content;
+}
diff --git a/packages/ckeditor5/package.json b/packages/ckeditor5/package.json
index e4ee0e7cd0..99fa2ee5f3 100644
--- a/packages/ckeditor5/package.json
+++ b/packages/ckeditor5/package.json
@@ -8,6 +8,7 @@
"dependencies": {
"@triliumnext/commons": "workspace:*",
"@triliumnext/ckeditor5-admonition": "workspace:*",
+ "@triliumnext/ckeditor5-collapsible": "workspace:*",
"@triliumnext/ckeditor5-footnotes": "workspace:*",
"@triliumnext/ckeditor5-keyboard-marker": "workspace:*",
"@triliumnext/ckeditor5-math": "workspace:*",
diff --git a/packages/ckeditor5/src/plugins.ts b/packages/ckeditor5/src/plugins.ts
index 939a284ea7..8522c09521 100644
--- a/packages/ckeditor5/src/plugins.ts
+++ b/packages/ckeditor5/src/plugins.ts
@@ -19,6 +19,7 @@ import SyntaxHighlighting from "./plugins/syntax_highlighting/index.js";
import { Kbd } from "@triliumnext/ckeditor5-keyboard-marker";
import { Mermaid } from "@triliumnext/ckeditor5-mermaid";
import { Admonition } from "@triliumnext/ckeditor5-admonition";
+import { Collapsible } from "@triliumnext/ckeditor5-collapsible";
import { Footnotes } from "@triliumnext/ckeditor5-footnotes";
import { Math, AutoformatMath } from "@triliumnext/ckeditor5-math";
import CopyAnchorLinkButton from "./plugins/copy_anchor_link.js";
@@ -74,6 +75,7 @@ const EXTERNAL_PLUGINS: typeof Plugin[] = [
Kbd,
Mermaid,
Admonition,
+ Collapsible,
Footnotes,
Math,
AutoformatMath
diff --git a/packages/ckeditor5/tsconfig.lib.json b/packages/ckeditor5/tsconfig.lib.json
index 613c7845e1..583a2668c3 100644
--- a/packages/ckeditor5/tsconfig.lib.json
+++ b/packages/ckeditor5/tsconfig.lib.json
@@ -27,6 +27,9 @@
{
"path": "../ckeditor5-admonition"
},
+ {
+ "path": "../ckeditor5-collapsible"
+ },
{
"path": "../ckeditor5-mermaid"
},
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index f0674deebd..e602c27399 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -948,6 +948,9 @@ importers:
'@triliumnext/ckeditor5-admonition':
specifier: workspace:*
version: link:../ckeditor5-admonition
+ '@triliumnext/ckeditor5-collapsible':
+ specifier: workspace:*
+ version: link:../ckeditor5-collapsible
'@triliumnext/ckeditor5-footnotes':
specifier: workspace:*
version: link:../ckeditor5-footnotes
@@ -1015,6 +1018,15 @@ importers:
specifier: 9.27.0
+ packages/ckeditor5-collapsible:
+ devDependencies:
+ ckeditor5:
+ specifier: 48.0.1
+ version: 48.0.1
+ typescript:
+ specifier: 6.0.3
+ version: 6.0.3
+
packages/ckeditor5-footnotes:
devDependencies:
'@ckeditor/ckeditor5-inspector':