Skip to content

Build your personal knowledge base with Trilium Notes

client/text editor/drawing canvas: add support for unified undo/redo history

Adorian Doranc59ee034e0de
diff --git a/.claude/skills/developing-content-embeds/SKILL.md b/.claude/skills/developing-content-embeds/SKILL.md
index 682dd60cb3..eb50be3c65 100644
--- a/.claude/skills/developing-content-embeds/SKILL.md
+++ b/.claude/skills/developing-content-embeds/SKILL.md
@@ -142,8 +142,9 @@ embeds receive `SourceEmbedProps` (`content`, `editor`) whichever storage the so
## Undo history
-The edits made in an embed's CodeMirror (code, Markdown, Mermaid, inline or not) are steps of the
-text editor's undo stack, in order with the text's own changes. Three layers:
+The edits made in an embed's CodeMirror (code, Markdown, Mermaid, inline or not) and in a drawing
+canvas's Excalidraw are steps of the text editor's undo stack, in order with the text's own
+changes. Three layers, with one recorder per editor in the middle:
- **`EmbedHistory`** (`packages/ckeditor5/src/plugins/content_embed/embed_history.ts`, required by
`ContentEmbed`) is editor-agnostic. `push({ undo, redo })` adds a batch that only adds or removes
@@ -158,17 +159,33 @@ text editor's undo stack, in order with the text's own changes. Three layers:
step whose document changed since does not apply. `view.setSharedHistory()` replaces the view's
own `history()` and routes Mod-Z/Mod-Y/Mod-Shift-Z, the `historyUndo`/`historyRedo` input
events and Vim's `u`/`Ctrl-R` to the host.
+- **`DrawingHistory`** (`canvas/drawing_history.tsx`) does the same for Excalidraw, whose 0.18
+ history is private. `useCanvasDrawingPersistence()` takes a `DrawingMount` when it reads the
+ content, attaches it once the scene shows, calls `record()` on each `onChange` and `detach()` in
+ a layout cleanup. A step is an element delta (before/after clones and the changed keys, never
+ `version`/`versionNonce`/`updated`/`status`) plus the background, recorded once
+ `isInteracting()` is false (pointer up, text submitted, line finished). A change with no input
+ inside the root since the last record (an image that finished loading) joins the last step while it
+ `isLatest()`. `api.registerAction()` replaces Excalidraw's `undo`/`redo` by name, so its keys,
+ its footer buttons and `CanvasTools` (which clicks `button-undo`) reach the host; the
+ replacement button copies Excalidraw's `ToolButton` markup. Without a mounted Excalidraw, a step
+ patches the scene the last one left and saves it through the `write` it attached with; a mount
+ that loaded before such a step (an undone Editable toggle remounts) gets the scene at attach.
+ `excalidraw_contract.spec.ts` pins the Excalidraw internals this relies on.
- **`EmbedHistories`** (`text/embed_history.ts`, one per `EditableText`) gives a `ContentHistory`
(`host` + `write`) per note ID, attachment ID or `InlineEmbedSource`, as `ContentEditor.history`.
- It imports no CodeMirror at runtime: `CodeEmbedEditor` creates the `SharedHistory` on it, and
- attaches it while mounted, read-only included.
+ Its `host` also tells whether the note can undo or redo (`isEnabled()`, `subscribe()`), for the
+ drawing's buttons. It imports no CodeMirror or Excalidraw at runtime: `CodeEmbedEditor` creates
+ the `SharedHistory` on it and `getDrawingHistory()` the `DrawingHistory`, each attached while
+ mounted, read-only included.
Content loaded from elsewhere goes through `view.loadText()`, which stays out of the history; a
`setText()` (re-indent) is a step. The `content` prop of `CodeEmbedEditor` loads, so a change made
while read-only (the re-indent stand-in in `CodeEmbed.tsx`) calls `setText()` on the read-only view,
after loading the unsaved content of the other embeds into it, or Undo skips it or reverts their
edits. Another editor joins by pushing its own steps to `EmbedHistory` through the same `host`.
-Included text notes and drawing canvases keep their own history.
+Included text notes keep their own history. Testing it live: open the note in one tab only, as
+editors of one note in several tabs reload each other's saves and mix up the result.
## Recipe: a new source embed (a diagram language)
@@ -269,6 +286,11 @@ in-place drawings replaced the code blocks the boxes need.
size a height in the component's CSS (`[data-box-size="small"]`, `"full"`) and `100%` under
`.include-note-content:fullscreen`, and size the wrapper too (`.source-embed`), or fullscreen
fills only part of the screen.
+- **Embeds nest, so scope box rules with `>`.** `.include-note[data-box-size="full"] .x` or
+ `.include-note-content:not(:fullscreen) .x` also matches the content of an embed inside that
+ box: a nested Medium box took the Full height, and a nested box in fullscreen lost its height.
+ Chain the embed's own elements, as `MarkdownEmbed.css` does: `.include-note >
+ .include-note-wrapper > .include-note-body > .include-note-content > .rendered-content`.
- **CKEditor hides a toolbar separator that is `:first-child`.** The leading separator of the
content tools needs an override in `packages/ckeditor5/src/theme/content_embed_tools.css`.
`CONTENT_EMBED_DISPLAY_MODE_SEPARATOR` separates Editable from the view buttons.
diff --git a/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.tsx b/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.tsx
index 3625cbc427..83b45a64f1 100644
--- a/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.tsx
+++ b/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.tsx
@@ -125,6 +125,7 @@ function LiveDrawing({
const frameRef = useRef(0);
const persistence = useCanvasDrawingPersistence(attachment, editor, apiRef, colorScheme, {
initialView: viewRef.current,
+ rootRef,
onSceneShown: () => {
isShownRef.current = true;
frameRef.current = requestAnimationFrame(onDrawn);
diff --git a/apps/client/src/widgets/type_widgets/canvas/CanvasEmbedTools.tsx b/apps/client/src/widgets/type_widgets/canvas/CanvasEmbedTools.tsx
index 577718e78f..2056782397 100644
--- a/apps/client/src/widgets/type_widgets/canvas/CanvasEmbedTools.tsx
+++ b/apps/client/src/widgets/type_widgets/canvas/CanvasEmbedTools.tsx
@@ -389,7 +389,10 @@ export class CanvasTools implements ContentEmbedToolProvider {
}
}
- /** Undo or redo, enabled while Excalidraw's own button is: Excalidraw keeps the history. */
+ /**
+ * Undo or redo, enabled while Excalidraw's button is. In a text note, the button undoes and
+ * redoes the changes of the note (`DrawingHistory`).
+ */
private getHistoryTool(id: HistoryAction, icon: string): ContentEmbedTool {
const button = this.getHistoryButton(id);
return {
diff --git a/apps/client/src/widgets/type_widgets/canvas/drawing_history.spec.tsx b/apps/client/src/widgets/type_widgets/canvas/drawing_history.spec.tsx
new file mode 100644
index 0000000000..71256c8ad6
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/canvas/drawing_history.spec.tsx
@@ -0,0 +1,294 @@
+import type { Action } from "@excalidraw/excalidraw/actions/types";
+import type { ExcalidrawElement } from "@excalidraw/excalidraw/element/types";
+import type {
+ AppState, BinaryFileData, ExcalidrawImperativeAPI
+} from "@excalidraw/excalidraw/types";
+import type { HostHistoryStep } from "@triliumnext/codemirror";
+import { type FunctionComponent, render } from "preact";
+import { act } from "preact/test-utils";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import type { EmbedHostHistory, HistoryCommand } from "../text/embed_history";
+import DrawingHistory, {
+ applyChanges, type ElementChange, getChangedKeys
+} from "./drawing_history";
+
+vi.mock("@excalidraw/excalidraw", () => ({
+ CaptureUpdateAction: { NEVER: "NEVER" },
+ newElementWith: (element: ExcalidrawElement, updates: object) =>
+ ({ ...element, ...updates, version: element.version + 1 }),
+ useI18n: () => ({ t: (key: string) => key, langCode: "en" })
+}));
+
+const RECTANGLE = element({ id: "r1", type: "rectangle", x: 0, index: "a0" });
+const ELLIPSE = element({ id: "e1", type: "ellipse", x: 50, index: "a1" });
+const IMAGE = element({ id: "i1", type: "image", width: 100, fileId: "f1", index: "a2" });
+const IMAGE_FILE = { id: "f1", dataURL: "data:image/png;base64,AA==" } as BinaryFileData;
+
+describe("DrawingHistory", () => {
+ afterEach(() => {
+ document.body.replaceChildren();
+ });
+
+ it("keeps each change that the user ends as a step of the note, to undo and redo", async () => {
+ const { host, steps } = createHost();
+ const drawing = createDrawing([ RECTANGLE ]);
+ const mount = new DrawingHistory(host).mount();
+ mount.attach(drawing.api, drawing.root, vi.fn());
+ expect([ ...drawing.actions.keys() ]).toEqual([ "undo", "redo" ]);
+
+ // A drag ends once the pointer is up.
+ drawing.input("pointerdown");
+ drawing.appState.cursorButton = "down";
+ drawing.setElements([ { ...RECTANGLE, x: 10, version: 2 } ]);
+ mount.record();
+ expect(steps).toHaveLength(0);
+ drawing.appState.cursorButton = "up";
+ mount.record();
+ mount.record();
+ expect(steps).toHaveLength(1);
+ expect(drawing.api.history.clear).toHaveBeenCalled();
+
+ drawing.input("keydown");
+ drawing.setElements([ ...drawing.getElements(), ELLIPSE ]);
+ drawing.appState.viewBackgroundColor = "#ffc9c9";
+ mount.record();
+ expect(steps).toHaveLength(2);
+
+ expect(steps[1].undo()).toBe(true);
+ expect(drawing.getElements().map(({ id, isDeleted }) => [ id, isDeleted ]))
+ .toEqual([ [ "r1", false ], [ "e1", true ] ]);
+ expect(drawing.appState.viewBackgroundColor).toBe("transparent");
+ await Promise.resolve();
+ expect(document.activeElement).toBe(drawing.container);
+ // What a step changes is no step of its own.
+ mount.record();
+ expect(steps).toHaveLength(2);
+
+ expect(steps[0].undo()).toBe(true);
+ expect(drawing.getElements()[0]).toMatchObject({ x: 0, version: 3 });
+ expect(steps[0].redo()).toBe(true);
+ expect(steps[1].redo()).toBe(true);
+ expect(drawing.getElements()).toMatchObject([
+ { id: "r1", x: 10, version: 4 }, { id: "e1", isDeleted: false }
+ ]);
+ expect(drawing.appState.viewBackgroundColor).toBe("#ffc9c9");
+ });
+
+ it("joins a change that the user did not make to the last step, while it is the last", () => {
+ const { host, steps, setLatest } = createHost();
+ const drawing = createDrawing([]);
+ drawing.files.f1 = IMAGE_FILE;
+ const mount = new DrawingHistory(host).mount();
+ mount.attach(drawing.api, drawing.root, vi.fn());
+
+ drawing.input("drop");
+ drawing.setElements([ IMAGE ]);
+ mount.record();
+ // The image loads and takes its own size.
+ drawing.setElements([ { ...IMAGE, width: 300, version: 2 } ]);
+ mount.record();
+ expect(steps).toHaveLength(1);
+
+ steps[0].undo();
+ expect(drawing.getElements()[0]).toMatchObject({ isDeleted: true });
+ steps[0].redo();
+ expect(drawing.getElements()[0]).toMatchObject({ isDeleted: false, width: 300 });
+
+ setLatest(false);
+ const [ image ] = drawing.getElements();
+ drawing.setElements([ { ...image, width: 400, version: image.version + 1 } ]);
+ mount.record();
+ expect(steps).toHaveLength(2);
+ });
+
+ it("changes the drawing while no Excalidraw shows it, and shows that in the next one", () => {
+ const { host, steps } = createHost();
+ const history = new DrawingHistory(host);
+ const write = vi.fn();
+ const first = createDrawing([ RECTANGLE ]);
+ const firstMount = history.mount();
+ firstMount.attach(first.api, first.root, write);
+ first.input("pointerdown");
+ first.setElements([ { ...RECTANGLE, x: 10, version: 2 } ]);
+ firstMount.record();
+ firstMount.detach();
+ expect(steps).toHaveLength(1);
+
+ // The next Excalidraw loads the saved drawing before the step applies.
+ const nextMount = history.mount();
+ expect(steps[0].undo()).toBe(true);
+ expect(write).toHaveBeenCalledOnce();
+ expect(write.mock.calls[0][0].elements).toMatchObject([ { id: "r1", x: 0 } ]);
+
+ const next = createDrawing([ { ...RECTANGLE, x: 10, version: 2 } ]);
+ nextMount.attach(next.api, next.root, write);
+ expect(next.getElements()).toMatchObject([ { id: "r1", x: 0 } ]);
+
+ const later = createDrawing([ { ...RECTANGLE, version: 3 } ]);
+ history.mount().attach(later.api, later.root, write);
+ expect(later.api.updateScene).not.toHaveBeenCalled();
+ // A step applies to every Excalidraw that shows the drawing.
+ steps[0].redo();
+ expect(next.getElements()[0]).toMatchObject({ x: 10 });
+ expect(later.getElements()[0]).toMatchObject({ x: 10 });
+ expect(write).toHaveBeenCalledOnce();
+ });
+
+ it("undoes and redoes the note with the keys and the buttons of Excalidraw", () => {
+ const { host, setEnabled } = createHost();
+ const drawing = createDrawing([]);
+ new DrawingHistory(host).mount().attach(drawing.api, drawing.root, vi.fn());
+ const undo = drawing.actions.get("undo");
+ const redo = drawing.actions.get("redo");
+ expect(undo && redo).toBeTruthy();
+
+ const keyTest = (action: Action | undefined, init: KeyboardEventInit) =>
+ action?.keyTest?.(new KeyboardEvent("keydown", init), drawing.appState, [], never());
+ expect(keyTest(undo, { key: "z", code: "KeyZ", ctrlKey: true })).toBe(true);
+ expect(keyTest(undo, { key: "я", code: "KeyZ", ctrlKey: true })).toBe(true);
+ expect(keyTest(undo, { key: "z", ctrlKey: true, shiftKey: true })).toBe(false);
+ expect(keyTest(undo, { key: "z" })).toBe(false);
+ expect(keyTest(redo, { key: "Z", ctrlKey: true, shiftKey: true })).toBe(true);
+ expect(keyTest(redo, { key: "y", ctrlKey: true })).toBe(true);
+ expect(keyTest(redo, { key: "z", ctrlKey: true })).toBe(false);
+
+ expect(undo?.perform([], drawing.appState, null, never())).toBe(false);
+ expect(host.undo).toHaveBeenCalledOnce();
+ drawing.appState.newElement = ELLIPSE as AppState["newElement"];
+ redo?.perform([], drawing.appState, null, never());
+ expect(host.redo).not.toHaveBeenCalled();
+
+ const Panel = undo?.PanelComponent as unknown as FunctionComponent<{
+ updateData: () => void;
+ }>;
+ const updateData = vi.fn();
+ act(() => render(<Panel updateData={updateData} />, drawing.container));
+ const button = drawing.container.querySelector<HTMLButtonElement>(
+ "[data-testid=button-undo]");
+ expect(button?.disabled).toBe(true);
+ act(() => setEnabled("undo", true));
+ expect(button?.disabled).toBe(false);
+ button?.click();
+ expect(updateData).toHaveBeenCalledOnce();
+ act(() => render(null, drawing.container));
+ });
+});
+
+describe("applyChanges", () => {
+ const deleteEllipse = new Map<string, ElementChange>([ [ "e1", {
+ before: ELLIPSE,
+ after: { ...ELLIPSE, isDeleted: true, version: 2 },
+ keys: [ "isDeleted" ]
+ } ] ]);
+
+ it("brings back an element that the drawing dropped, in its place in the z-order", () => {
+ const elements = [ RECTANGLE, IMAGE ];
+ expect(applyChanges(elements, deleteEllipse, true).map(({ id }) => id))
+ .toEqual([ "r1", "e1", "i1" ]);
+ expect(applyChanges(elements, deleteEllipse, false)).toEqual(elements);
+ });
+});
+
+describe("getChangedKeys", () => {
+ it("records the properties that the user changes, not those that Excalidraw sets", () => {
+ expect(getChangedKeys(RECTANGLE, {
+ ...RECTANGLE, x: 5, version: 9, versionNonce: 1, updated: 2
+ } as ExcalidrawElement)).toEqual([ "x" ]);
+ expect(getChangedKeys(IMAGE, { ...IMAGE, status: "saved" } as ExcalidrawElement))
+ .toEqual([]);
+ const deleted = { ...ELLIPSE, isDeleted: true };
+ expect(getChangedKeys(undefined, deleted)).toEqual([]);
+ expect(getChangedKeys(deleted, { ...deleted, x: 1 })).toEqual([]);
+ expect(getChangedKeys(undefined, ELLIPSE))
+ .toEqual([ "isDeleted", "id", "type", "x", "index" ]);
+ });
+});
+
+function element(properties: Record<string, unknown>) {
+ return { version: 1, isDeleted: false, ...properties } as unknown as ExcalidrawElement;
+}
+
+function never() {
+ return undefined as never;
+}
+
+/** The undo stack of a text note, whose steps run when the spec calls them. */
+function createHost() {
+ const steps: HostHistoryStep[] = [];
+ const enabled: Record<HistoryCommand, boolean> = { undo: false, redo: false };
+ const listeners = new Set<() => void>();
+ let isLatest = true;
+ const host = {
+ push: vi.fn((step: HostHistoryStep) => {
+ steps.push(step);
+ const count = steps.length;
+ return { isLatest: () => isLatest && steps.length === count };
+ }),
+ undo: vi.fn(),
+ redo: vi.fn(),
+ isEnabled: (name: HistoryCommand) => enabled[name],
+ subscribe: (listener: () => void) => {
+ listeners.add(listener);
+ return () => listeners.delete(listener);
+ }
+ } satisfies EmbedHostHistory;
+
+ return {
+ host,
+ steps,
+ setLatest: (value: boolean) => {
+ isLatest = value;
+ },
+ setEnabled: (name: HistoryCommand, value: boolean) => {
+ enabled[name] = value;
+ for (const listener of listeners) listener();
+ }
+ };
+}
+
+/** An Excalidraw that shows `elements`, in a root with its focusable container. */
+function createDrawing(elements: ExcalidrawElement[]) {
+ let scene = elements;
+ const appState = {
+ cursorButton: "up", viewBackgroundColor: "transparent", scrollX: 0, scrollY: 0,
+ zoom: { value: 1 }, gridModeEnabled: false
+ } as AppState;
+ const files: Record<string, BinaryFileData> = {};
+ const actions = new Map<string, Action>();
+ const root = document.createElement("div");
+ const container = document.createElement("div");
+ container.className = "excalidraw-container";
+ container.tabIndex = 0;
+ root.append(container);
+ document.body.append(root);
+
+ const api = {
+ getSceneElementsIncludingDeleted: () => scene,
+ getAppState: () => appState,
+ getFiles: () => files,
+ addFiles: vi.fn((added: BinaryFileData[]) => {
+ for (const file of added) files[file.id] = file;
+ }),
+ updateScene: vi.fn((data: { elements?: ExcalidrawElement[]; appState?: object }) => {
+ scene = data.elements ?? scene;
+ Object.assign(appState, data.appState);
+ }),
+ history: { clear: vi.fn() },
+ registerAction: (action: Action) => actions.set(action.name, action)
+ };
+
+ return {
+ api: api as unknown as ExcalidrawImperativeAPI & typeof api,
+ appState,
+ files,
+ actions,
+ root,
+ container,
+ getElements: () => scene,
+ setElements: (next: ExcalidrawElement[]) => {
+ scene = next;
+ },
+ input: (type: string) => container.dispatchEvent(new Event(type, { bubbles: true }))
+ };
+}
diff --git a/apps/client/src/widgets/type_widgets/canvas/drawing_history.tsx b/apps/client/src/widgets/type_widgets/canvas/drawing_history.tsx
new file mode 100644
index 0000000000..6159f483e5
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/canvas/drawing_history.tsx
@@ -0,0 +1,517 @@
+import { CaptureUpdateAction, newElementWith } from "@excalidraw/excalidraw";
+import type { Action, PanelComponentProps } from "@excalidraw/excalidraw/actions/types";
+import type { ExcalidrawElement } from "@excalidraw/excalidraw/element/types";
+import type { AppState, BinaryFiles, ExcalidrawImperativeAPI } from "@excalidraw/excalidraw/types";
+import clsx from "clsx";
+import { useSyncExternalStore } from "preact/compat";
+
+import { isMac } from "../../../services/utils";
+import type { ContentHistory, EmbedHostHistory, HistoryCommand } from "../text/embed_history";
+import { useExcalidrawTranslation } from "./CanvasEmbedTools";
+
+/** The view and the settings that the content of a drawing keeps. */
+export type SavedAppState = Pick<
+ AppState, "scrollX" | "scrollY" | "zoom" | "gridModeEnabled" | "viewBackgroundColor"
+>;
+
+/** A drawing as Excalidraw holds it, deleted elements included. */
+export interface DrawingScene {
+ elements: readonly ExcalidrawElement[];
+ appState: SavedAppState;
+ files: BinaryFiles;
+}
+
+/** An Excalidraw that shows the drawing, from the moment it starts to load the drawing. */
+export interface DrawingMount {
+ /**
+ * Records the changes of `api` from now on, once it shows the loaded drawing. Input inside
+ * `root` marks the changes that the user makes. `write` saves the drawing once no Excalidraw
+ * shows it.
+ */
+ attach(
+ api: ExcalidrawImperativeAPI,
+ root: HTMLElement | null,
+ write: (scene: DrawingScene) => void
+ ): void;
+ /** Records the change of the drawing that Excalidraw ended, if any. */
+ record(): void;
+ /** Stops recording, before Excalidraw unmounts. */
+ detach(): void;
+}
+
+/** A change of one element of a drawing. */
+export interface ElementChange {
+ /** The element before the change, or `undefined` for one that the change created. */
+ before: ExcalidrawElement | undefined;
+ after: ExcalidrawElement;
+ /** The properties that the change sets. */
+ keys: string[];
+}
+
+/** A change of a drawing, kept as a step of the undo stack of the text note. */
+interface DrawingStep {
+ changes: Map<string, ElementChange>;
+ /** The background before and after the change, when the change sets it. */
+ background?: [ string, string ];
+ /** The images of the changed elements, for an Excalidraw that has not loaded them. */
+ files: BinaryFiles;
+}
+
+interface RecordedStep extends DrawingStep {
+ entry: { isLatest(): boolean };
+}
+
+interface AttachedDrawing {
+ api: ExcalidrawImperativeAPI;
+ root: HTMLElement | null;
+ /** The elements as last recorded, by ID, cloned as Excalidraw changes elements in place. */
+ committed: Map<string, ExcalidrawElement>;
+ background: string;
+ /** Whether the user acted on the drawing since its last recorded change. */
+ hasInput: boolean;
+ stopListening(): void;
+}
+
+/** The properties that Excalidraw sets on its own, which no step records. */
+const UNRECORDED_KEYS = new Set([ "version", "versionNonce", "updated", "status" ]);
+/** The events with which the user changes a drawing. */
+const INPUT_EVENTS = [ "pointerdown", "keydown", "paste", "drop" ] as const;
+/** The paths of Excalidraw's icons of undo and redo. */
+export const HISTORY_ICON_PATHS: Record<HistoryCommand, string> = {
+ undo: "M7.5 10.833 4.167 7.5 7.5 4.167M4.167 7.5h9.166a3.333 3.333 0 0 1 0 6.667H12.5",
+ redo: "M12.5 10.833 15.833 7.5 12.5 4.167M15.833 7.5H6.667a3.333 3.333 0 1 0 0 6.667H7.5"
+};
+
+/**
+ * The undo history of a canvas drawing, kept on the undo stack of the text note that embeds it.
+ * Each Excalidraw that shows the drawing records a step once the user ends a change, and its Undo
+ * and Redo act on the last change of the note. A step changes every Excalidraw that shows the
+ * drawing, or the drawing through the last `write` while none does.
+ */
+export default class DrawingHistory {
+ /** Counts the steps applied, so that an Excalidraw that loaded before one shows it. */
+ private revision = 0;
+ private readonly drawings = new Set<AttachedDrawing>();
+ /** The drawing of the last Excalidraw that went away, for the steps applied without one. */
+ private scene: DrawingScene | undefined;
+ private write: ((scene: DrawingScene) => void) | undefined;
+ private lastStep: RecordedStep | undefined;
+
+ constructor(private readonly host: EmbedHostHistory) {}
+
+ /** A mount for an Excalidraw that loads the drawing now. */
+ mount(): DrawingMount {
+ const revision = this.revision;
+ let drawing: AttachedDrawing | undefined;
+ return {
+ attach: (api, root, write) => {
+ drawing = this.attach(api, root, write, revision);
+ },
+ record: () => {
+ if (drawing) this.record(drawing);
+ },
+ detach: () => {
+ if (drawing) this.detach(drawing);
+ drawing = undefined;
+ }
+ };
+ }
+
+ private attach(
+ api: ExcalidrawImperativeAPI,
+ root: HTMLElement | null,
+ write: (scene: DrawingScene) => void,
+ revision: number
+ ) {
+ const scene = revision === this.revision ? undefined : this.getLatestScene();
+ if (scene) {
+ addMissingFiles(api, scene.files);
+ api.updateScene({
+ elements: scene.elements,
+ appState: { viewBackgroundColor: scene.appState.viewBackgroundColor },
+ captureUpdate: CaptureUpdateAction.NEVER
+ });
+ }
+
+ const { viewBackgroundColor } = scene?.appState ?? api.getAppState();
+ const drawing: AttachedDrawing = {
+ api,
+ root,
+ committed: new Map(),
+ background: viewBackgroundColor,
+ hasInput: false,
+ stopListening: () => {}
+ };
+ commitElements(drawing);
+ api.history.clear();
+ api.registerAction(createHistoryAction("undo", this.host));
+ api.registerAction(createHistoryAction("redo", this.host));
+
+ if (root) {
+ const onInput = () => {
+ drawing.hasInput = true;
+ };
+ for (const type of INPUT_EVENTS) {
+ root.addEventListener(type, onInput, { capture: true });
+ }
+ drawing.stopListening = () => {
+ for (const type of INPUT_EVENTS) {
+ root.removeEventListener(type, onInput, { capture: true });
+ }
+ };
+ }
+
+ this.drawings.add(drawing);
+ this.write = write;
+ return drawing;
+ }
+
+ private detach(drawing: AttachedDrawing) {
+ drawing.stopListening();
+ this.drawings.delete(drawing);
+ if (!this.drawings.size) {
+ this.scene = getDrawingScene(drawing.api);
+ }
+ }
+
+ /**
+ * Records the changes of `drawing` since its last record, unless the user is still making them.
+ * A change that the user did not make, such as an image that finished loading, joins the last
+ * step while nothing entered the undo stack after it.
+ */
+ private record(drawing: AttachedDrawing) {
+ const { api } = drawing;
+ const appState = api.getAppState();
+ if (isInteracting(appState)) return;
+
+ const changes = commitElements(drawing);
+ const step: DrawingStep = { changes, files: getChangedFiles(api, changes) };
+ if (appState.viewBackgroundColor !== drawing.background) {
+ step.background = [ drawing.background, appState.viewBackgroundColor ];
+ drawing.background = appState.viewBackgroundColor;
+ }
+ if (!changes.size && !step.background) return;
+
+ const isUserChange = drawing.hasInput;
+ drawing.hasInput = false;
+ // Excalidraw's own history goes unused while the note keeps the steps.
+ api.history.clear();
+ if (!isUserChange && this.lastStep?.entry.isLatest()) {
+ joinStep(this.lastStep, step);
+ return;
+ }
+
+ const recorded: RecordedStep = { ...step, entry: { isLatest: () => false } };
+ recorded.entry = this.host.push({
+ undo: () => this.apply(recorded, true),
+ redo: () => this.apply(recorded, false)
+ });
+ this.lastStep = recorded;
+ }
+
+ private apply(step: DrawingStep, isUndo: boolean) {
+ const [ first ] = this.drawings;
+ if (first) {
+ for (const drawing of this.drawings) {
+ applyToDrawing(drawing, step, isUndo);
+ }
+ // Deferred until after the Undo button of the toolbar focuses the text editor.
+ queueMicrotask(() => {
+ first.root?.querySelector<HTMLElement>(".excalidraw-container")?.focus();
+ });
+ } else if (this.scene) {
+ this.scene = applyToScene(this.scene, step, isUndo);
+ this.write?.(this.scene);
+ } else {
+ return false;
+ }
+
+ this.revision++;
+ return true;
+ }
+
+ private getLatestScene() {
+ const [ drawing ] = this.drawings;
+ return drawing ? getDrawingScene(drawing.api) : this.scene;
+ }
+}
+
+/** The history of the drawing of `history`, which the first call creates. */
+export function getDrawingHistory(history: ContentHistory) {
+ history.drawing ??= new DrawingHistory(history.host);
+ return history.drawing;
+}
+
+/**
+ * `elements` with the changes undone, or made again. An element that `elements` lacks, as one that
+ * was deleted before the drawing saved, comes back from the change.
+ */
+export function applyChanges(
+ elements: readonly ExcalidrawElement[],
+ changes: ReadonlyMap<string, ElementChange>,
+ isUndo: boolean
+) {
+ const missing = new Map(changes);
+ const result: ExcalidrawElement[] = [];
+ for (const element of elements) {
+ const change = missing.get(element.id);
+ missing.delete(element.id);
+ result.push(change ? applyChange(element, change, isUndo) : element);
+ }
+
+ for (const change of missing.values()) {
+ const target = isUndo ? change.before : change.after;
+ if (target && !target.isDeleted) {
+ insertByIndex(result, newElementWith(structuredClone(target), {}, true));
+ }
+ }
+ return result;
+}
+
+/**
+ * The properties that differ between `before` and `after`, those that Excalidraw sets on its own
+ * left out. None for an element that is deleted on both sides.
+ */
+export function getChangedKeys(before: ExcalidrawElement | undefined, after: ExcalidrawElement) {
+ if (after.isDeleted && (!before || before.isDeleted)) {
+ return [];
+ }
+
+ const beforeValues: Record<string, unknown> = before ?? {};
+ const afterValues: Record<string, unknown> = after;
+ const keys = new Set([ ...Object.keys(beforeValues), ...Object.keys(afterValues) ]);
+ return [ ...keys ].filter((key) => !UNRECORDED_KEYS.has(key)
+ && JSON.stringify(beforeValues[key]) !== JSON.stringify(afterValues[key]));
+}
+
+/** Whether the user is in the middle of a change, which Excalidraw has yet to end. */
+export function isInteracting(appState: AppState) {
+ return appState.cursorButton === "down"
+ || appState.isResizing
+ || appState.isRotating
+ || appState.selectedElementsAreBeingDragged
+ || !!(appState.newElement || appState.multiElement || appState.resizingElement
+ || appState.selectionElement || appState.editingTextElement
+ || appState.pendingImageElementId);
+}
+
+/** Takes the elements that changed since the last call as recorded, and returns their changes. */
+function commitElements(drawing: AttachedDrawing) {
+ const changes = new Map<string, ElementChange>();
+ for (const element of drawing.api.getSceneElementsIncludingDeleted()) {
+ const before = drawing.committed.get(element.id);
+ if (before?.version === element.version) continue;
+
+ const after = structuredClone(element);
+ drawing.committed.set(element.id, after);
+ const keys = getChangedKeys(before, after);
+ if (keys.length) {
+ changes.set(element.id, { before, after, keys });
+ }
+ }
+ return changes;
+}
+
+/** Adds the changes of `next`, which follow those of `step`, to `step`. */
+function joinStep(step: DrawingStep, next: DrawingStep) {
+ for (const [ id, change ] of next.changes) {
+ const joined = step.changes.get(id);
+ if (joined) {
+ joined.after = change.after;
+ joined.keys = getChangedKeys(joined.before, change.after);
+ } else {
+ step.changes.set(id, change);
+ }
+ }
+ if (next.background) {
+ step.background = [ step.background?.[0] ?? next.background[0], next.background[1] ];
+ }
+ Object.assign(step.files, next.files);
+}
+
+function applyToDrawing(drawing: AttachedDrawing, step: DrawingStep, isUndo: boolean) {
+ const { api } = drawing;
+ const background = step.background?.[isUndo ? 0 : 1];
+ addMissingFiles(api, step.files);
+ api.updateScene({
+ elements: applyChanges(api.getSceneElementsIncludingDeleted(), step.changes, isUndo),
+ ...(background !== undefined && { appState: { viewBackgroundColor: background } }),
+ captureUpdate: CaptureUpdateAction.NEVER
+ });
+ // Excalidraw renders the new app state later, but replaces the elements at once.
+ commitElements(drawing);
+ drawing.background = background ?? drawing.background;
+ drawing.hasInput = false;
+}
+
+function applyToScene(scene: DrawingScene, step: DrawingStep, isUndo: boolean): DrawingScene {
+ const background = step.background?.[isUndo ? 0 : 1];
+ return {
+ elements: applyChanges(scene.elements, step.changes, isUndo),
+ appState: background === undefined
+ ? scene.appState
+ : { ...scene.appState, viewBackgroundColor: background },
+ files: { ...step.files, ...scene.files }
+ };
+}
+
+/** `element` with the properties that `change` sets, from before or after it. */
+function applyChange(element: ExcalidrawElement, change: ElementChange, isUndo: boolean) {
+ const target: Record<string, unknown> | undefined = isUndo ? change.before : change.after;
+ if (!target) {
+ return newElementWith(element, { isDeleted: true });
+ }
+
+ const updates: Record<string, unknown> = {};
+ for (const key of change.keys) {
+ // A copy, as Excalidraw can change the arrays of an element in place.
+ updates[key] = structuredClone(target[key]);
+ }
+ return newElementWith(element, updates);
+}
+
+/** Inserts `element` into `elements` before the first one above it, by the fractional index. */
+function insertByIndex(elements: ExcalidrawElement[], element: ExcalidrawElement) {
+ const { index } = element;
+ const position = index === null
+ ? -1
+ : elements.findIndex((other) => other.index !== null && other.index > index);
+ if (position < 0) {
+ elements.push(element);
+ } else {
+ elements.splice(position, 0, element);
+ }
+}
+
+/** The images of the elements in `changes` that `api` has loaded. */
+function getChangedFiles(api: ExcalidrawImperativeAPI, changes: Map<string, ElementChange>) {
+ const loaded = api.getFiles();
+ const files: BinaryFiles = {};
+ for (const { after } of changes.values()) {
+ const fileId = "fileId" in after ? after.fileId : null;
+ if (fileId && loaded[fileId]) {
+ files[fileId] = loaded[fileId];
+ }
+ }
+ return files;
+}
+
+function addMissingFiles(api: ExcalidrawImperativeAPI, files: BinaryFiles) {
+ const loaded = api.getFiles();
+ const missing = Object.values(files).filter((file) => !loaded[file.id]);
+ if (missing.length) {
+ api.addFiles(missing);
+ }
+}
+
+/** The drawing that `api` shows. */
+function getDrawingScene(api: ExcalidrawImperativeAPI): DrawingScene {
+ const { scrollX, scrollY, zoom, gridModeEnabled, viewBackgroundColor } = api.getAppState();
+ return {
+ elements: api.getSceneElementsIncludingDeleted(),
+ appState: { scrollX, scrollY, zoom, gridModeEnabled, viewBackgroundColor },
+ files: api.getFiles()
+ };
+}
+
+/**
+ * Excalidraw's undo or redo, as its keys and its button run it, which undoes or redoes the last
+ * change of the text note instead.
+ */
+function createHistoryAction(name: HistoryCommand, host: EmbedHostHistory): Action {
+ return {
+ name,
+ label: `buttons.${name}`,
+ trackEvent: false,
+ perform: (_elements, appState) => {
+ if (!isInteracting(appState)) {
+ host[name]();
+ }
+ return false;
+ },
+ keyTest: name === "undo" ? isUndoKey : isRedoKey,
+ // Excalidraw types its components with React's types, which Preact's do not satisfy.
+ PanelComponent: (({ updateData, data }: PanelComponentProps) => (
+ <HistoryButton
+ name={name}
+ host={host}
+ size={data?.size ?? "medium"}
+ onClick={() => updateData()}
+ />
+ )) as unknown as Action["PanelComponent"]
+ };
+}
+
+interface HistoryButtonProps {
+ name: HistoryCommand;
+ host: EmbedHostHistory;
+ /** The size of Excalidraw's `ToolButton`, such as `medium`. */
+ size: string;
+ onClick: () => void;
+}
+
+/** Excalidraw's undo or redo button, enabled while the text note can undo or redo. */
+function HistoryButton({ name, host, size, onClick }: HistoryButtonProps) {
+ const { t } = useExcalidrawTranslation();
+ const isEnabled = useSyncExternalStore(host.subscribe, () => host.isEnabled(name));
+
+ return (
+ <button
+ type="button"
+ className={clsx(
+ "ToolIcon_type_button", `ToolIcon_size_${size}`, "ToolIcon_type_button--show",
+ "ToolIcon"
+ )}
+ aria-label={t(`buttons.${name}`)}
+ data-testid={`button-${name}`}
+ disabled={!isEnabled}
+ onClick={onClick}
+ >
+ <div className="ToolIcon__icon" aria-hidden="true" aria-disabled={!isEnabled}>
+ <svg
+ aria-hidden="true"
+ focusable="false"
+ role="img"
+ viewBox="0 0 20 20"
+ fill="none"
+ stroke="currentColor"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ >
+ <path d={HISTORY_ICON_PATHS[name]} stroke-width="1.25" />
+ </svg>
+ </div>
+ </button>
+ );
+}
+
+interface KeyEvent {
+ key: string;
+ code: string;
+ shiftKey: boolean;
+ ctrlKey: boolean;
+ metaKey: boolean;
+}
+
+/** Ctrl+Z, or ⌘Z on macOS. */
+function isUndoKey(event: KeyEvent) {
+ return hasCommandKey(event) && !event.shiftKey && matchesKey(event, "z");
+}
+
+/** Ctrl+Y or Ctrl+Shift+Z, or ⌘Y or ⌘⇧Z on macOS, as in the text note. */
+function isRedoKey(event: KeyEvent) {
+ return hasCommandKey(event) && matchesKey(event, event.shiftKey ? "z" : "y");
+}
+
+function hasCommandKey(event: KeyEvent) {
+ return isMac() ? event.metaKey : event.ctrlKey;
+}
+
+/**
+ * Whether `event` presses the Latin letter `key`, or the key in its place on the keyboard of a
+ * layout without Latin letters, as Excalidraw matches its shortcuts.
+ */
+function matchesKey(event: KeyEvent, key: string) {
+ return event.key.toLowerCase() === key
+ || (!/^[a-z]$/i.test(event.key) && event.code === `Key${key.toUpperCase()}`);
+}
diff --git a/apps/client/src/widgets/type_widgets/canvas/excalidraw_contract.spec.ts b/apps/client/src/widgets/type_widgets/canvas/excalidraw_contract.spec.ts
index c255fc8546..cf9a244d98 100644
--- a/apps/client/src/widgets/type_widgets/canvas/excalidraw_contract.spec.ts
+++ b/apps/client/src/widgets/type_widgets/canvas/excalidraw_contract.spec.ts
@@ -13,6 +13,7 @@ const {
const { MAX_ZOOM, MIN_ZOOM } = await import("./drawing_view");
const { FITTED_MENU_STYLES } = await import("./CanvasDrawing");
const { DRAWING_DARK_FILTER, IMAGE_DARK_FILTER } = await import("./persistence");
+const { HISTORY_ICON_PATHS, isInteracting } = await import("./drawing_history");
/** The classes of Trilium that `CanvasDrawing.css` selects. Every other class is Excalidraw's. */
const TRILIUM_CLASSES = new Set([
@@ -170,6 +171,32 @@ describe("Excalidraw contract of the canvas drawing", () => {
expect(handleWheel).not.toContain("this.setState(");
});
+ it("lets the undo history of the note replace Excalidraw's undo and redo", () => {
+ const source = readBundle(developmentDir, [ ".js" ]).replace(/\s+/g, "");
+
+ // `registerAction()` replaces the action of the name, which the keys and the buttons run.
+ expect(source).toContain(
+ "registerAction:(action)=>{this.actionManager.registerAction(action);}");
+ expect(source).toContain("registerAction(action){this.actions[action.name]=action;}");
+ for (const name of HISTORY_ACTIONS) {
+ const create = `create${name[0].toUpperCase()}${name.slice(1)}Action`;
+ expect(source).toContain(
+ `this.actionManager.registerAction(${create}(this.history,this.store));`);
+ expect(source).toContain(`renderAction("${name}")`);
+ expect(source).toContain(`d:"${HISTORY_ICON_PATHS[name].replace(/\s+/g, "")}"`);
+ }
+ // The store ends a change before `onChange`, which records it.
+ expect(source).toContain("this.store.commit(elementsMap,this.state);"
+ + "if(!this.state.isLoading){this.props.onChange?.(elements,this.state,this.files);");
+
+ // `isInteracting()` holds a change back at least while Excalidraw's undo would wait.
+ const guard = source
+ .match(/varexecuteHistoryAction=\(app,appState,updater\)=>\{if\((.*?)\)\{/)?.[1];
+ const flags = [ ...guard?.matchAll(/!appState\.(\w+)/g) ?? [] ].map((match) => match[1]);
+ expect(flags).toHaveLength(6);
+ expect(flags.filter((flag) => !isInteracting({ [flag]: true } as never))).toEqual([]);
+ });
+
it("takes the wheel on its container, after `useNoteScrollingWheel()` on the drawing", () => {
const source = readBundle(developmentDir, [ ".js" ]).replace(/\s+/g, "");
diff --git a/apps/client/src/widgets/type_widgets/canvas/persistence.spec.tsx b/apps/client/src/widgets/type_widgets/canvas/persistence.spec.tsx
index 83fdc677ea..6e8daf0791 100644
--- a/apps/client/src/widgets/type_widgets/canvas/persistence.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/canvas/persistence.spec.tsx
@@ -12,6 +12,7 @@
*/
import { exportToSvg } from "@excalidraw/excalidraw";
import { ExcalidrawImperativeAPI, ExcalidrawInitialDataState } from "@excalidraw/excalidraw/types";
+import type { HostHistoryStep } from "@triliumnext/codemirror";
import { type RefObject, render } from "preact";
import { act } from "preact/test-utils";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
@@ -21,6 +22,7 @@ import type FNote from "../../../entities/fnote";
import type { ContentEditor } from "../../../services/content_renderer";
import server from "../../../services/server";
import { buildNote } from "../../../test/easy-froca";
+import type { EmbedHostHistory } from "../text/embed_history";
import useCanvasPersistence, {
saveDrawingPicture, useCanvasDrawingPersistence
} from "./persistence";
@@ -50,7 +52,9 @@ vi.mock("@excalidraw/excalidraw", () => ({
Math.max(...elements.map(({ x, width }) => x + width)),
Math.max(...elements.map(({ y, height }) => y + height))
],
- CaptureUpdateAction: { IMMEDIATELY: "IMMEDIATELY", NEVER: "NEVER", EVENTUALLY: "EVENTUALLY" }
+ CaptureUpdateAction: { IMMEDIATELY: "IMMEDIATELY", NEVER: "NEVER", EVENTUALLY: "EVENTUALLY" },
+ newElementWith: (element: FakeElement, updates: object) =>
+ ({ ...element, ...updates, version: element.version + 1 })
}));
vi.stubGlobal("logError", vi.fn());
@@ -284,9 +288,13 @@ describe("useCanvasDrawingPersistence", () => {
) {
const api = {
getSceneElements: () => sceneElements,
+ getSceneElementsIncludingDeleted: () => sceneElements,
getAppState: () => appState,
getFiles: () => sceneFiles,
- updateScene
+ updateScene,
+ addFiles: vi.fn(),
+ history: { clear: vi.fn() },
+ registerAction: vi.fn()
} as unknown as ExcalidrawImperativeAPI;
const apiRef = { current: api } as RefObject<ExcalidrawImperativeAPI | null>;
await act(async () => {
@@ -381,6 +389,40 @@ describe("useCanvasDrawingPersistence", () => {
expect(editor.release).toHaveBeenCalledOnce();
});
+ it("keeps its changes on the undo stack of the note, also once Excalidraw is gone", async () => {
+ const loaded = [ { id: "r1", type: "rectangle", version: 3, x: 0 } ];
+ const { attachment } = buildAttachment({ elements: loaded });
+ const steps: HostHistoryStep[] = [];
+ const host: EmbedHostHistory = {
+ push: (step) => {
+ steps.push(step);
+ return { isLatest: () => true };
+ },
+ undo: vi.fn(),
+ redo: vi.fn(),
+ isEnabled: () => false,
+ subscribe: () => () => {}
+ };
+ const editor = { ...buildEditor(), history: { host, write: vi.fn() } };
+ const root = document.createElement("div");
+ await mount(attachment, editor, { rootRef: { current: root } });
+
+ change();
+ sceneElements = loaded;
+ change();
+ root.dispatchEvent(new Event("pointerdown"));
+ const moved = { ...loaded[0], x: 10, version: 4 };
+ sceneElements = [ moved ];
+ change();
+ expect(steps).toHaveLength(1);
+
+ act(() => render(null, container));
+ editor.scheduleSave.mockClear();
+ expect(steps[0].undo()).toBe(true);
+ const [ getContent ] = editor.scheduleSave.mock.calls[0];
+ expect(JSON.parse(getContent()).elements).toMatchObject([ { id: "r1", x: 0 } ]);
+ });
+
it("loads the images it refers to from its note and saves them by reference", async () => {
const owner = buildNote({ title: "Owner" });
const getAttachmentsByRole = vi.fn(async () => [
diff --git a/apps/client/src/widgets/type_widgets/canvas/persistence.ts b/apps/client/src/widgets/type_widgets/canvas/persistence.ts
index dcfdd5b1ea..1a0e46f0a5 100644
--- a/apps/client/src/widgets/type_widgets/canvas/persistence.ts
+++ b/apps/client/src/widgets/type_widgets/canvas/persistence.ts
@@ -15,6 +15,7 @@ import type { ContentEditor } from "../../../services/content_renderer";
import froca from "../../../services/froca";
import server from "../../../services/server";
import { SavedData, useEditorSpacedUpdate } from "../../react/hooks";
+import { type DrawingScene, getDrawingHistory, type SavedAppState } from "./drawing_history";
import { type DrawingView, getBoundedView, getFittedView } from "./drawing_view";
import {
buildNewImageAttachments, CANVAS_EXPORT_TITLE, IMAGE_ROLE, loadImageAttachments, loadImageFiles
@@ -356,6 +357,8 @@ interface DrawingPersistenceOptions {
initialView?: DrawingView | null;
/** Called once Excalidraw shows the loaded scene. */
onSceneShown?: () => void;
+ /** The element that holds Excalidraw, in which the undo history of the note watches input. */
+ rootRef?: RefObject<HTMLElement | null>;
}
/**
@@ -367,7 +370,7 @@ export function useCanvasDrawingPersistence(
editor: ContentEditor | undefined,
apiRef: RefObject<ExcalidrawImperativeAPI | null>,
theme: AppState["theme"],
- { initialView, onSceneShown }: DrawingPersistenceOptions = {}
+ { initialView, onSceneShown, rootRef }: DrawingPersistenceOptions = {}
): Partial<ExcalidrawProps> {
const currentSceneVersion = useRef(0);
/** The saved part of the app state, read from the editor at the first change. */
@@ -405,9 +408,13 @@ export function useCanvasDrawingPersistence(
files: loaded.files
};
});
+ // Created with the load above, so that a step applied while Excalidraw loads reaches it.
+ const [ drawingMount ] = useState(() =>
+ editor?.history && getDrawingHistory(editor.history).mount());
// A layout cleanup runs during the unmount, before Excalidraw's `componentWillUnmount()` empties
- // the scene that `release()` reads; a passive one runs after paint.
+ // the scene that `detach()` and `release()` read; a passive one runs after paint.
+ useLayoutEffect(() => () => drawingMount?.detach(), [ drawingMount ]);
useLayoutEffect(() => () => editor?.release(), [ editor ]);
return {
@@ -428,6 +435,10 @@ export function useCanvasDrawingPersistence(
const sceneVersion = getSceneVersion(api.getSceneElements());
if (!isSceneShownRef.current && (isLoadedSceneEmptyRef.current || sceneVersion)) {
isSceneShownRef.current = true;
+ drawingMount?.attach(api, rootRef?.current ?? null, (scene) => editor?.scheduleSave(
+ () => serializeDrawing(scene, referencedFileIds.current),
+ (content) => saveDrawingPicture(attachment, content, scene.files)
+ ));
onSceneShown?.();
}
if (!editor) return;
@@ -436,6 +447,7 @@ export function useCanvasDrawingPersistence(
if (sceneVersion === 0) return;
initialSceneAppliedRef.current = true;
}
+ drawingMount?.record();
const appState = getImportantAppState(api.getAppState());
const previousAppState = appStateToCompare.current;
@@ -447,7 +459,11 @@ export function useCanvasDrawingPersistence(
currentSceneVersion.current = sceneVersion;
editor.scheduleSave(
- () => serializeDrawing(api, referencedFileIds.current),
+ () => serializeDrawing({
+ elements: api.getSceneElements(),
+ appState: api.getAppState(),
+ files: api.getFiles()
+ }, referencedFileIds.current),
(content) => saveDrawingPicture(attachment, content, api.getFiles())
);
}
@@ -629,13 +645,14 @@ function markBitmaps(picture: SVGSVGElement) {
* The content of a canvas drawing. Unlike a canvas note, a drawing keeps its images inline, except
* the ones it refers to by file ID.
*/
-function serializeDrawing(api: ExcalidrawImperativeAPI, referencedFileIds: ReadonlySet<string>) {
- const elements = api.getSceneElements();
- const files = getActiveFiles(elements, api.getFiles());
+function serializeDrawing(scene: DrawingScene, referencedFileIds: ReadonlySet<string>) {
+ const elements = scene.elements.filter(
+ (element): element is NonDeletedExcalidrawElement => !element.isDeleted);
+ const files = getActiveFiles(elements, scene.files);
for (const fileId of referencedFileIds) {
delete files[fileId];
}
- return JSON.stringify(buildSceneContent(elements, api.getAppState(), files));
+ return JSON.stringify(buildSceneContent(elements, scene.appState, files));
}
export function parseContent(newContent: string, entity: FNote | FAttachment): CanvasContent {
@@ -693,7 +710,7 @@ async function getData(api: ExcalidrawImperativeAPI, appStateToCompare: RefObjec
/** The scene as the content of a canvas note or of a canvas drawing stores it. */
function buildSceneContent(
elements: readonly NonDeletedExcalidrawElement[],
- appState: AppState,
+ appState: SavedAppState,
files: Record<string, BinaryFileData>
) {
return {
@@ -721,7 +738,7 @@ function getActiveFiles(elements: readonly NonDeletedExcalidrawElement[], files:
return activeFiles;
}
-function getImportantAppState(appState: AppState): ImportantAppState {
+function getImportantAppState(appState: ImportantAppState): ImportantAppState {
return {
gridModeEnabled: appState.gridModeEnabled,
viewBackgroundColor: appState.viewBackgroundColor
diff --git a/apps/client/src/widgets/type_widgets/markdown/MarkdownEmbed.css b/apps/client/src/widgets/type_widgets/markdown/MarkdownEmbed.css
index ea1a79a92f..fe8129ef41 100644
--- a/apps/client/src/widgets/type_widgets/markdown/MarkdownEmbed.css
+++ b/apps/client/src/widgets/type_widgets/markdown/MarkdownEmbed.css
@@ -22,23 +22,25 @@
}
}
-.include-note-content:fullscreen .markdown-embed {
+.include-note-content:fullscreen > .rendered-content > .markdown-embed {
height: 100%;
}
-.include-note-content:not(:fullscreen) .markdown-embed-content.with-source {
+.include-note-content:not(:fullscreen) > .rendered-content > .markdown-embed
+ > .markdown-embed-content.with-source {
border-radius: var(--_include-note-framed-top-radius) var(--_include-note-framed-top-radius)
var(--_include-note-framed-bottom-radius)
var(--_include-note-framed-bottom-radius);
overflow: hidden;
}
-.include-note[data-box-size="full"] .include-note-content:not(:fullscreen)
- .markdown-embed-content.with-source {
+.include-note[data-box-size="full"] > .include-note-wrapper > .include-note-body
+ > .include-note-content:not(:fullscreen) > .rendered-content > .markdown-embed
+ > .markdown-embed-content.with-source {
height: auto;
- .note-detail-split,
- .note-detail-split > :is(.note-detail-split-editor-col, .note-detail-split-preview-col) {
+ > .note-detail-split,
+ > .note-detail-split > :is(.note-detail-split-editor-col, .note-detail-split-preview-col) {
height: auto;
}
}
diff --git a/apps/client/src/widgets/type_widgets/mermaid/MermaidDiagram.spec.tsx b/apps/client/src/widgets/type_widgets/mermaid/MermaidDiagram.spec.tsx
index 97700de740..ad79720e1e 100644
--- a/apps/client/src/widgets/type_widgets/mermaid/MermaidDiagram.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/mermaid/MermaidDiagram.spec.tsx
@@ -210,7 +210,8 @@ describe("MermaidDiagram", () => {
it("keeps the edits of its source on the text note's undo stack, read-only too", async () => {
const host = {
- push: vi.fn(() => ({ isLatest: () => false })), undo: vi.fn(), redo: vi.fn()
+ push: vi.fn(() => ({ isLatest: () => false })), undo: vi.fn(), redo: vi.fn(),
+ isEnabled: () => false, subscribe: () => () => {}
};
const editor = { ...buildEditor(), history: { host, write: vi.fn() } };
const { figure } = await mount({ editor, isEditable: true, displayMode: "split" });
diff --git a/apps/client/src/widgets/type_widgets/text/embed_history.spec.ts b/apps/client/src/widgets/type_widgets/text/embed_history.spec.ts
index d1d311659f..8f23d110f4 100644
--- a/apps/client/src/widgets/type_widgets/text/embed_history.spec.ts
+++ b/apps/client/src/widgets/type_widgets/text/embed_history.spec.ts
@@ -21,22 +21,32 @@ describe("EmbedHistories", () => {
let editor: AttributeEditor | null = null;
const { host } = new EmbedHistories(() => editor).get("note1", vi.fn());
const step = { undo: vi.fn(() => true), redo: vi.fn(() => true) };
+ const listener = vi.fn();
expect(host.push(step).isLatest()).toBe(false);
host.undo();
host.redo();
expect(step.undo).not.toHaveBeenCalled();
+ expect(host.isEnabled("undo")).toBe(false);
+ host.subscribe(listener)();
const element = document.createElement("div");
document.body.append(element);
editor = await AttributeEditor.create(element, {
licenseKey: "GPL", extraPlugins: [ EmbedHistory ]
});
+ const unsubscribe = host.subscribe(listener);
expect(host.push(step).isLatest()).toBe(true);
+ expect(host.isEnabled("undo")).toBe(true);
+ expect(listener).toHaveBeenCalled();
host.undo();
expect(step.undo).toHaveBeenCalledOnce();
+ expect(host.isEnabled("redo")).toBe(true);
+ unsubscribe();
+ listener.mockClear();
host.redo();
expect(step.redo).toHaveBeenCalledOnce();
+ expect(listener).not.toHaveBeenCalled();
await editor.destroy();
element.remove();
diff --git a/apps/client/src/widgets/type_widgets/text/embed_history.ts b/apps/client/src/widgets/type_widgets/text/embed_history.ts
index 2bf2cb9250..81c2a14cda 100644
--- a/apps/client/src/widgets/type_widgets/text/embed_history.ts
+++ b/apps/client/src/widgets/type_widgets/text/embed_history.ts
@@ -1,16 +1,33 @@
import type { CKTextEditor } from "@triliumnext/ckeditor5";
import type { HostHistory, SharedHistory } from "@triliumnext/codemirror";
+import type DrawingHistory from "../canvas/drawing_history";
+
+/** The undo and redo commands of the text editor. */
+export type HistoryCommand = "undo" | "redo";
+
+/** The undo stack of the text note, as the content of its embeds reaches it. */
+export interface EmbedHostHistory extends HostHistory {
+ /** Whether the text note has a change to undo, or to redo. */
+ isEnabled(name: HistoryCommand): boolean;
+ /** Calls `listener` when `isEnabled()` changes, until the returned call. */
+ subscribe(listener: () => void): () => void;
+}
+
/** The undo history of a note, an attachment or an inline source that a text note embeds. */
export interface ContentHistory {
/** The undo stack of the text note. */
- readonly host: HostHistory;
+ readonly host: EmbedHostHistory;
/** Saves the content while no editor shows it. */
readonly write: (text: string) => void;
/** The history of the code editors of the content, which the first of them creates. */
shared?: SharedHistory;
+ /** The history of the drawing of the content, which the first Excalidraw of it creates. */
+ drawing?: DrawingHistory;
}
+const HISTORY_COMMANDS: readonly HistoryCommand[] = [ "undo", "redo" ];
+
/**
* The undo histories of the content in the embeds of a text note, which keep their steps on the
* undo stack of the text editor.
@@ -18,14 +35,26 @@ export interface ContentHistory {
export default class EmbedHistories {
private readonly byId = new Map<string, ContentHistory>();
private readonly bySource = new WeakMap<object, ContentHistory>();
- private readonly host: HostHistory;
+ private readonly host: EmbedHostHistory;
- constructor(getEditor: () => Pick<CKTextEditor, "plugins"> | null) {
+ constructor(getEditor: () => Pick<CKTextEditor, "plugins" | "commands"> | null) {
const getPlugin = () => getEditor()?.plugins.get("EmbedHistory");
this.host = {
push: (step) => getPlugin()?.push(step) ?? { isLatest: () => false },
undo: () => getPlugin()?.undo(),
- redo: () => getPlugin()?.redo()
+ redo: () => getPlugin()?.redo(),
+ isEnabled: (name) => !!getEditor()?.commands.get(name)?.isEnabled,
+ subscribe: (listener) => {
+ const commands = HISTORY_COMMANDS.map((name) => getEditor()?.commands.get(name));
+ for (const command of commands) {
+ command?.on("change:isEnabled", listener);
+ }
+ return () => {
+ for (const command of commands) {
+ command?.off("change:isEnabled", listener);
+ }
+ };
+ }
};
}
diff --git a/apps/server/src/assets/help/help_content.json b/apps/server/src/assets/help/help_content.json
index 560d53e402..858b1755f7 100644
--- a/apps/server/src/assets/help/help_content.json
+++ b/apps/server/src/assets/help/help_content.json
@@ -134,7 +134,7 @@
"_help_0Ofbk1aSuVRu": "<figure class=\"image image-style-align-right image_resized\" style=\"width:50.47%;\"><img style=\"aspect-ratio:880/553;\" src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/Images/Image%20references_image.png\" width=\"880\" height=\"553\"></figure><p>Image references are an easy way to embed the preview of another note type into a&nbsp;<a class=\"reference-link\" href=\"#root/_help_iPIMuisry3hd\">Text</a>&nbsp;note.</p><h2>Supported note types</h2><ul><li><a class=\"reference-link\" href=\"#root/_help_grjYqerjn243\">Canvas</a></li><li><a class=\"reference-link\" href=\"#root/_help_s1aBHPd79XYj\">Mermaid Diagrams</a></li><li><a class=\"reference-link\" href=\"#root/_help_gBbsAeiuUxI5\">Mind Map</a></li></ul><h2>Steps</h2><ol><li>Go to one of the supported notes (listed above) and look for the&nbsp;<span class=\"tn-icon bx bx-copy\"></span> button in the&nbsp;<a class=\"reference-link\" href=\"#root/_help_1P8QXI5edXNd\">Note buttons</a>&nbsp;area.</li><li>Go to a&nbsp;<a class=\"reference-link\" href=\"#root/_help_iPIMuisry3hd\">Text</a>&nbsp;note and use the Paste function to insert the reference to that note.</li></ol><h2>Interaction</h2><ul><li>Double-clicking an image reference from a text note will automatically open the target note.</li><li>Clicking an image reference while <kbd>Ctrl</kbd> is pressed will open the target note in a new tab.</li><li>Modifying the target note should also update the image reference. If that doesn't happen, consider&nbsp;<a class=\"reference-link\" href=\"#root/_help_s8alTXmpFR61\">Refreshing the application</a>.</li></ul>",
"_help_VRoP0g1uHHc2": "<figure class=\"image image-style-align-center image_resized\" style=\"width:76.29%;\"><img style=\"aspect-ratio:1479/865;\" src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/In-editor%20AI%20assistant_image.png\" width=\"1479\" height=\"865\"></figure><p>The AI assistant works on the text you are already writing: select a passage and have it rewritten, translated or turned into a table, or ask for new content at the cursor. Unlike the <a href=\"#root/_help_LrKznOtw9cQD\">AI chat</a>, it does not open a conversation window, the result is previewed in place and only enters the note when you accept it.</p><h2>Requirements</h2><p>The assistant is only available once at least one provider is configured in&nbsp;<a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a>&nbsp;→ <em>AI / LLM</em>, with at least one model selected for it. Until then the toolbar entry is not shown at all.</p><h2>Accessing the AI assistant</h2><p>To access the AI assistant:</p><ul><li>Look for the&nbsp;<span class=\"tn-icon cke cke-trilium-ai\"></span> button in the&nbsp;<a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a>. Press the button itself to enter the <em>Ask AI</em> mode or press the arrow key next to it to access the quick commands and the model selection.</li><li>Look for <em>AI assistant</em> or any of the <em>AI</em>-prefixed quick commands in&nbsp;<a class=\"reference-link\" href=\"#root/_help_ZlN4nump6EbW\">Slash Commands</a>.</li><li>Press <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>K</kbd>.</li><li>Select a text and choose the <em>AI assistant</em> option in the&nbsp;<a class=\"reference-link\" href=\"#root/_help_jcQVxzYybYgz\">Note contextual menu</a>.</li></ul><h2>What the assistant works on</h2><figure class=\"table\"><table><thead><tr><th>Situation</th><th>What is sent</th></tr></thead><tbody><tr><td>Text is selected</td><td>The selection.</td></tr><tr><td>Nothing is selected, and you pick a quick action</td><td>The paragraph the cursor is in.</td></tr><tr><td>Nothing is selected, and you type your own prompt</td><td>Nothing, the response is new content written at the cursor.</td></tr></tbody></table></figure><p>In all cases the assistant also sends the text before and after the target, so that the model can tell what it is writing into: asked to <em>Continue writing</em> or to summarize, a model that can only see the selected words is guessing at the document around them. This surrounding text is context only, it is never rewritten.</p><aside class=\"admonition important\"><p>That means a single run sends more than the passage you highlighted. See&nbsp;<a class=\"reference-link\" href=\"#root/_help_cRRrdZjgyhNc\">Privacy</a>&nbsp;for exactly what leaves your machine.</p></aside><h2>Quick actions</h2><p>The arrow beside the toolbar button opens a menu of ready-made instructions, grouped by what they do.</p><ul><li>The <em>Reformat</em> actions produce real Trilium content rather than plain text: <em>Diagram</em> inserts a Mermaid diagram, <em>Callout</em> an admonition, and <em>Collapsible</em> a collapsible block.</li><li>The <em>Translate</em> group lists the <a href=\"#root/_help_veGu4faJErEM\">content languages</a> you have enabled, or a predefined list if no content languages are set. It can be filled from within the editor, the last entry of the submenu opens the language configuration directly.</li></ul><p>Actions that need something to work on are greyed out when there is nothing to work on (for example an empty paragraph with no selection).</p><h2>Asking for something specific</h2><p>Choosing <em>Ask AI…</em> (<span class=\"tn-icon bx bx-message-square-dots\"></span>) opens a prompt where you can describe the change in your own words, for example: \"make this less formal\", \"add a row for 2024\", \"write an intro paragraph for this section\". Press <kbd>Enter</kbd> or the <span class=\"tn-icon cke cke-arrow-up\"></span> send button to run it.</p><p>Once a response arrives you can keep going in the same prompt, and the assistant treats it as a conversation rather than as a fresh request: after <em>Translate this to German</em>, asking for <em>make it shorter</em> shortens the German, not the original.</p><h2>Reviewing the result</h2><p>The response streams in as it is generated, and can be interrupted at any point by pressing the <em>Stop</em> (<span class=\"tn-icon cke cke-stop\"></span>) button; whatever arrived before that stays usable.</p><p>Nothing is written into the note until you say so. The review offers:</p><ul><li><em>Result</em>, which displays the response as it will be inserted.</li><li><em>Changes</em>, which displays an inline diff against the original, with insertions and deletions marked. When the model rewrote the passage rather than editing it, the review opens on <em>Result</em> instead: a diff of two texts with little in common is harder to read than the answer itself.</li><li><em>Try again</em> (<span class=\"tn-icon cke cke-refresh\"></span>), to re-run the same instruction.</li><li><em>Replace</em>, which substitutes the original passage</li><li><em>Insert below</em>, which keeps the original and adds the response after it.</li></ul><p>Trilium also reports the model that produced it, the tokens consumed and, for providers that report it, the price.</p><p>If you ask for a correction and there is nothing to correct, the assistant will indicate it instead of showing a blank diff.</p><h2>Choosing the model</h2><p>The bottom of the quick actions menu shows which model the assistant runs on, and lets you pick another from the models you selected in&nbsp;<a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a>&nbsp;→ <em>AI / LLM</em>, grouped by provider.</p><p>The model can also be changed while asking for something specific, or after the assistant has generated its response (i.e. if the response needs a better model).</p><p>This choice is separate from the model used by the chat, and is remembered across notes and devices. Left unset, the assistant follows the first configured provider.</p>",
"_help_mVEYwt20exhO": "<p><em>Quick actions</em> are a feature of the&nbsp;<a class=\"reference-link\" href=\"#root/_help_VRoP0g1uHHc2\">In-editor AI assistant</a>&nbsp;for&nbsp;<a class=\"reference-link\" href=\"#root/_help_iPIMuisry3hd\">Text</a>&nbsp;notes which automatically triggers an LLM suggestion based on a defined prompt. The built-in quick actions come with a predefined prompt, but it is also possible to define your own quick actions.</p><h2>Creating a custom quick action</h2><p>In the&nbsp;<a class=\"reference-link\" href=\"#root/_help_oPVyFC7WL2Lp\">Note Tree</a>: </p><ol><li>Right-click the note where you want to place the quick action.</li><li>Select <em>Insert child note</em>.</li><li>Select <em>More</em> → <em>AI Quick Action</em>. The entry appears only when AI is enabled.</li></ol><p>Afterwards, simply type in the content of the note the desired prompt. The text can be formatted in the same manner as a normal text note and it will be passed to the LLM as Markdown.</p><p>The title of the note will become the title of the quick action.</p><p>Of note:</p><ul><li><a class=\"reference-link\" href=\"#root/_help_6f9hih2hXXZk\">Code</a>&nbsp;notes work too.</li><li>An empty note is ignored.</li><li><a class=\"reference-link\" href=\"#root/_help_MKmLg5x6xkor\">Archived Notes</a>&nbsp;are also excluded.</li></ul><h2>Using a quick action</h2><p>Once a quick action is defined, the action will appear under the <em>Quick Actions</em> dropdown in a group called <em>Custom</em>.</p>",
- "_help_nBAXQFj20hS1": "<p>Text notes can \"include\" another note as a read-only widget or an interactive widget, depending on the type of note.</p><p>This can be useful for e.g. including a dynamically generated chart (from scripts &amp; \"render HTML\" note) or other more advanced use cases.</p><h2>Including a note</h2><p>In the&nbsp;<a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a>, look for the&nbsp;<span class=\"tn-icon cke cke-trilium-note\"></span> button. There is also a keyboard shortcut defined for it but it is not allocated by default.</p><p>To include a note that is already linked, right-click a reference link to it in a text note being edited and select <em>Convert link to an included note</em>, at the end of the menu. The include gets the box size that suits the note, as one added from the button does.</p><p>An <a href=\"#root/_help_0vhv7lsOLy82\">attachment</a> can be included the same way, from the context menu of a link to it (see <em>Embedding an attachment</em> there).</p><p>A link to blocks of a text note is converted the same way, with <em>Convert link to note excerpt</em>, and the include then shows only those blocks. See <a class=\"reference-link\" href=\"#root/_help_klC3ilXa9kUE\">Block references</a>.</p><h2>Box sizes</h2><p>The box size sets how much of the included note is shown.</p><ul><li><em>Tiny</em> shows a single row instead of the content: the note's icon, its title with the path to the note above it, and buttons to act on the note. The included note is never rendered, so wherever the note is shown outside the editor, such as in print, in a tooltip or on a shared page, a <em>Tiny</em> include appears as a link to the included note.</li><li><em>Small</em> and <em>Medium</em> show the content in a box of limited height. Text scrolls inside the box, while a picture, a diagram or a video is scaled down to fit it.</li><li><em>Full</em> shows the whole content.</li><li><em>Expandable</em> shows only the title until its <span class=\"tn-icon bx bx-chevron-right\"></span> arrow is pressed. In a read-only note, a click anywhere on the title row other than its buttons and link expands or collapses it as well.</li></ul><p>A new include gets the size that suits what it shows:</p><ul><li><em>Tiny</em> for a note or an attachment that has no preview, such as a relation map or an archive.</li><li><em>Small</em> for audio.</li><li><em>Full</em> for a code note or a code file, such as a <code>.js</code>, <code>.py</code> or <code>.txt</code> attachment, and for an excerpt of the blocks of a text note.</li><li><em>Medium</em> for anything else.</li></ul><p>The dialog that includes a note selects that size once the note is picked, and you can choose another one there. To change the size later, select the include and use the <em>Box size</em> menu in its toolbar, or the <em>Size</em> submenu of its <em>More actions</em> menu. For an included code or Markdown note and an embedded code or Markdown file, the <em>Box size</em> menu is the <span class=\"tn-icon bx bx-move-vertical\"></span> button, whose tooltip names the current size.</p><h2>Resizing</h2><p>A <em>Small</em>, <em>Medium</em> or <em>Expandable</em> include can be resized to any width and height. A <em>Tiny</em> or <em>Full</em> include always fits its content.</p><ul><li>To resize an include, select it and drag the handle in its bottom-right corner. To change only the width or only the height, drag the middle of its right or bottom edge instead, where a touch screen shows a handle too. In right-to-left text, the handle is in the bottom-left corner and the width changes from the left edge.</li><li>Resizing works with a mouse, a pen or a finger.</li><li>While the height changes, moving the handle near the top or the bottom of the note scrolls the note.</li><li>An include narrower than the note is centered, so changing its width moves both of its sides. Making it as wide as the note returns it to the full width.</li><li>To cancel a resize, press <kbd>Esc</kbd> before releasing the handle.</li><li>To reset the size, double-click the corner handle, or double-tap it on a touch screen. Double-clicking the right or bottom edge resets only the width or the height.</li><li>Choosing a box size resets the height. Choosing <em>Tiny</em> or <em>Full</em> resets the width too.</li><li>While an <em>Expandable</em> include is collapsed, only its width can be changed.</li></ul><h2>Caption</h2><p>An include can have a caption, shown centered at the bottom of its box. The caption is part of the text note, so it can be formatted like the rest of the text, for example in bold or with a link.</p><ul><li>To add a caption, select the include, press the <span class=\"tn-icon cke cke-caption\"></span> <em>Toggle caption on</em> button in its toolbar and type the caption.</li><li>To remove the caption, press the same button again. Pressing it once more brings back the text it had, as long as the note stays open.</li><li>A <em>Tiny</em> include has no caption. Switching an include to <em>Tiny</em> removes its caption, and switching it back to a larger size restores the caption, as long as the note stays open.</li><li>An <em>Expandable</em> include shows its caption under the title while the content is collapsed, and under the content once it is expanded.</li></ul><h2>Title</h2><p>The title row of an include links to the included note and holds its buttons. To show only the content, select the include and press the <span class=\"tn-icon bx bx-window-alt\"></span> <em>Show title</em> button in its toolbar. Pressing it again shows the title.</p><ul><li>While the title is hidden, the <span class=\"tn-icon cke cke-three-vertical-dots\"></span> <em>More actions</em> button in the toolbar of the include opens the menu of the included note.</li><li>A <em>Tiny</em> or <em>Expandable</em> include always shows its title, and its toolbar has no <em>Show title</em> button.</li></ul><h2>Opening an included note</h2><p>To open an included note in a new tab, press the <span class=\"tn-icon bx bx-link-external\"></span> <em>Open in new tab</em> button at the end of its title. An embedded attachment has the same button.</p><p>The <span class=\"tn-icon bx bx-dots-vertical-rounded\"></span> <em>More actions</em> button at the end of the title row opens the same menu as right-clicking anywhere on the title row: the other places to open the note in and, for an embedded attachment, the actions on the attachment.</p><p>In a note being edited, the menu also has the commands of the include's toolbar: the <em>Size</em> submenu, <em>Show title</em> and <em>Show caption</em>, each checked while it is in effect, and <em>Convert to link</em> at the end. A drawing canvas, a Mermaid diagram, an included text, code or Markdown note and an embedded code or Markdown file also have <em>Editable</em>, above <em>Size</em>. An included code or Markdown note, an embedded code or Markdown file and a Mermaid diagram also have the <em>Word wrap</em> and <em>Line numbers</em> submenus after <em>Editable</em> (see <em>Editing an include in place</em> below). A Mermaid diagram, an included Markdown note and an embedded Markdown file also have <em>Source view</em>, <em>Split view</em> and <em>Preview</em> after these submenus. For an embedded attachment they follow its first group of actions; for an included note they end the menu.</p><p>To show an include of size <em>Medium</em> or <em>Full</em> on the whole screen, press the <span class=\"tn-icon bx bx-fullscreen\"></span> <em>Fullscreen</em> button at the end of its title. An excerpt of the blocks of a note has an <span class=\"tn-icon bx bx-pencil\"></span> <em>Edit excerpt</em> button there instead; see <a class=\"reference-link\" href=\"#root/_help_klC3ilXa9kUE\">Block references</a>. To return, press <span class=\"tn-icon bx bx-exit\"></span> <em>Exit fullscreen</em> in the top-right corner, or <kbd>Esc</kbd>.</p><p>A <em>Tiny</em> include has these buttons instead, followed by the same <em>More actions</em> button:</p><ul><li>For a note, <span class=\"tn-icon bx bx-edit\"></span> <em>Quick edit</em> opens the note in&nbsp;<a class=\"reference-link\" href=\"#root/_help_ZjLYv08Rp3qC\">Quick edit</a>, and <span class=\"tn-icon bx bx-link-external\"></span> <em>Open in new tab</em> opens it in a new tab.</li><li>For an embedded attachment, <span class=\"tn-icon bx bx-file-find\"></span> <em>Open externally</em> opens the file in another application, and <span class=\"tn-icon bx bx-download\"></span> <em>Download</em> downloads it. The size of the file is shown under its title.</li></ul><h2>Converting an include to a link</h2><p>To replace an include with a link to the included note, select it and press the <span class=\"tn-icon cke cke-link\"></span> <em>Convert to link</em> button in its toolbar, or choose <em>Convert to link</em> at the end of its <em>More actions</em> menu. An embedded attachment turns into a link to the attachment the same way.</p><h2>Included notes in the share functionality</h2><p>If a <a href=\"#root/_help_R9pX4DGra2Vt\">shared note</a> contains one or more included notes, they will be displayed in the content of the note as if they were part of the note itself. The caption of an include is shown under the included content. A <em>Tiny</em> include is shown as a link to the included note instead, and so is an include that would show a note already shown around it, such as a note that includes itself. The same goes for a printed or exported note.</p><p>For this to work, the included notes must also be shared, otherwise they will not be shown. However, the included notes can still be hidden from the note tree via <code>#shareHiddenFromTree</code>.</p><h2>Interactive notes</h2><p>Since v0.104.0, included notes might become interactive depending on their note type:</p><ul><li><a class=\"reference-link\" href=\"#root/_help_GTwFsgaA0lCt\">Collections</a>&nbsp;(e.g.&nbsp;<a class=\"reference-link\" href=\"#root/_help_81SGnPGMk7Xc\">Geo Map</a>) will render fully interactive, including creating new notes.</li><li><a class=\"reference-link\" href=\"#root/_help_m523cpzocqaD\">Saved Search</a>&nbsp;will also display the results.</li><li><a class=\"reference-link\" href=\"#root/_help_1vHRoWCEjj0L\">Web View</a>&nbsp;provides an interactive preview of the website.</li></ul><h2>Included images</h2><p>An included image, whether an image note or an image attachment, is shown in the image viewer, which zooms and pans it:</p><ul><li>To zoom, press the <span class=\"tn-icon bx bx-plus-circle\"></span> <em>Zoom in</em> and <span class=\"tn-icon bx bx-minus-circle\"></span> <em>Zoom out</em> buttons in the bottom-right corner of the image, or pinch on a touch screen. The percentage between them resets the zoom.</li><li>To zoom with the mouse wheel, click the image first. Until then, the mouse wheel scrolls the note.</li><li>To pan an image that is zoomed in, drag it. At its fitted size, dragging the image on a touch screen scrolls the note.</li><li>To return to the fitted size, double-click the image.</li></ul><p>In a <em>Small</em> or <em>Medium</em> box, the image is scaled down to fit the height of the box. In fullscreen, it fits the screen.</p><h2>Editing an include in place</h2><p>An included text note, an included code note and an embedded code file such as a <code>.js</code>, <code>.py</code> or <code>.txt</code> attachment can be edited without leaving the note that includes them. Until then, a code note or file is shown read-only in the code editor, where its code can be selected and copied, and its blocks folded and unfolded with the arrows in its gutter. Included Markdown can be edited too, see <em>Included Markdown</em> below.</p><ul><li>To edit, select the include and turn on the <span class=\"tn-icon bx bx-edit-alt\"></span> <em>Editable</em> button at the start of its toolbar, or check <em>Editable</em> in its <span class=\"tn-icon cke cke-three-vertical-dots\"></span> <em>More actions</em> menu. Turn <em>Editable</em> off to stop editing.</li><li>While <em>Editable</em> is on, the arrow keys move the caret into the include and back out, as through the rest of the text. Entering from above or from the left puts the caret at the start of the include, and entering from below or from the right puts it at the end. A collapsed <em>Expandable</em> include is skipped.</li><li>While an included text note has the focus, the formatting toolbar applies to it. The notes it includes in turn stay read-only.</li><li>Code is edited in the same code editor as a <a class=\"reference-link\" href=\"#root/_help_6f9hih2hXXZk\">Code</a> note, with its theme, indentation and line wrapping settings.</li><li>Typing <code>/</code> in the code lists the <a class=\"reference-link\" href=\"#root/_help_IEgsWp5hHH35\">Code Snippets</a> of its language, as in a code note.</li><li>The toolbar of an included code note or an embedded code file also has the language and indentation menus of the&nbsp;<a class=\"reference-link\" href=\"#root/_help_AlJ73vBCjWDw\">Status bar</a>, between <em>Editable</em> and the <span class=\"tn-icon bx bx-move-vertical\"></span> <em>Box size</em> menu: <em>Change language mode</em>, which shows the current language, and <em>Change tab width</em>, which shows the current indentation. <em>Re-indent content to</em> converts the indentation of the code itself and saves it to the included note or file, whether <em>Editable</em> is on or off.<ul><li>For an included note, the menus change the note, as they do in its own tab.</li><li>For an embedded code file, the language and indentation settings change only how this include shows the file, and are saved with the note that includes it. The language replaces the one that the file name gives, and the <em>Use default</em> entries return to the indentation set in&nbsp;<a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a> → <em>Code Notes</em>. These settings leave the file itself unchanged, and other includes of it keep their own settings.</li></ul></li><li>The <span class=\"tn-icon cke cke-three-vertical-dots\"></span> <em>More actions</em> menu of an included code or Markdown note, an embedded code or Markdown file and a <a href=\"#root/_help_CohkqWQC1iBv\">Mermaid diagram</a> has two more submenus after <em>Editable</em>, each with <em>Auto</em>, <em>On</em> and <em>Off</em>. They change how the code editor shows the source.<ul><li><em>Word wrap</em> wraps long lines instead of scrolling them. <em>Auto</em> follows the setting in <a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a> → <em>Code Notes</em>. For an included note, it sets the <code>#wrapLines</code> label of the note, as the <em>Word wrap</em> submenu of its <a class=\"reference-link\" href=\"#root/_help_8YBEPzcpUgxw\">Note menu</a> does for a code note. For an embedded file or a Mermaid diagram, it changes only this include.</li><li><em>Line numbers</em> shows or hides the numbers at the start of each line. <em>Auto</em> shows them, as a code note does. It changes only this include, for an included note as well.</li></ul></li><li>The changes are saved as you type, to the included note or to the attachment, as they would be in its own tab.</li><li>The changes made in the code editor of an include are part of the undo history of the note that includes it, together with the changes to its text, in the order they were made. This includes the source of included Markdown and of a <a href=\"#root/_help_CohkqWQC1iBv\">Mermaid diagram</a>.<ul><li><kbd>Ctrl</kbd>+<kbd>Z</kbd> undoes the last change of the note, and <kbd>Ctrl</kbd>+<kbd>Y</kbd> or <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>Z</kbd> redoes it, whether the caret is in the text or in an include, and also while <em>Editable</em> is off. The <span class=\"tn-icon cke cke-undo\"></span> <em>Undo</em> and <span class=\"tn-icon cke cke-redo\"></span> <em>Redo</em> buttons of the formatting toolbar do the same. With the Vim key bindings, <code>u</code> and <kbd>Ctrl</kbd>+<kbd>R</kbd> in an include do the same too.</li><li>The focus moves to the change that was undone or redone: into the code editor of the include, or back to the text.</li><li>Undoing a change of an included note saves the included note again. Once the included note has been changed elsewhere, for example in another tab, its earlier changes can no longer be undone from here, and undo skips them.</li><li>An included text note and a drawing canvas keep an undo history of their own.</li></ul></li><li>An include of <a class=\"reference-link\" href=\"#root/_help_klC3ilXa9kUE\">Block references</a> edits only the referenced blocks.</li><li>Editing is not available in a <a href=\"#root/_help_CoFPLs3dRlXc\">read-only note</a>, for an included note marked <code>#readOnly</code>, or for an attachment of another note.</li><li><a class=\"reference-link\" href=\"#root/_help_McngOG2jbUWX\">Search in note</a> finds the text of included text and code notes among the results of the note around them, and replaces it while <em>Editable</em> is on.</li></ul><h2>Included Markdown</h2><p>An included&nbsp;<a class=\"reference-link\" href=\"#root/_help_6RM1Q7ppFVoj\">Markdown</a>&nbsp;note and an embedded Markdown file, such as a <code>.md</code> attachment, are shown with the same three views as a Markdown note in its own tab (see&nbsp;<a class=\"reference-link\" href=\"#root/_help_SL5f1Auq7sVN\">Note types with split view</a>): <span class=\"tn-icon bx bx-code\"></span> <em>Source view</em>, <span class=\"tn-icon bx bxs-dock-left\"></span> <em>Split view</em> and <span class=\"tn-icon bx bx-show\"></span> <em>Preview</em>.</p><ul><li>To switch the view, press one of the three buttons in the title row of the include. In a note being edited, the toolbar of the include has the same buttons after <em>Editable</em>, and its <span class=\"tn-icon cke cke-three-vertical-dots\"></span> <em>More actions</em> menu has them as <em>Source view</em>, <em>Split view</em> and <em>Preview</em>.</li><li>Until a view is chosen, the include shows the <em>Preview</em>, and the <em>Split view</em> while <em>Editable</em> is on.</li><li>To edit the Markdown, turn on <em>Editable</em> (see <em>Editing an include in place</em> above). The source is edited in the code editor of a Markdown note, and the preview follows the changes as you type. While <em>Editable</em> is off, the source can be read and copied but not changed.</li><li>The source has the slash commands and the <code>@</code> and <code>[[</code> note links of a <a class=\"reference-link\" href=\"#root/_help_6RM1Q7ppFVoj\">Markdown</a> note. A note created from the <code>@</code> or <code>[[</code> list goes under the included note, or for an embedded file under the note that includes it, and <code>/image</code> uploads the image to that same note.</li><li>The <em>Word wrap</em> and <em>Line numbers</em> submenus of the <em>More actions</em> menu change how the source shows, as for code (see <em>Editing an include in place</em> above).</li><li>As in a Markdown note, the preview scrolls along with the source and highlights the block where the cursor is, and <kbd>Ctrl</kbd>+<kbd>B</kbd>, <kbd>Ctrl</kbd>+<kbd>I</kbd>, <kbd>Ctrl</kbd>+<kbd>M</kbd> and <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>X</kbd> format the selection.</li><li>In a note being edited, the view is saved with the include, so two includes of the same note can show different views. In a <a href=\"#root/_help_CoFPLs3dRlXc\">read-only note</a>, the view can be changed too, until the note is opened again.</li><li>While the source shows, the include has the height of its box size, or the height it was resized to. A <em>Full</em> include fits its content instead.</li><li><a class=\"reference-link\" href=\"#root/_help_McngOG2jbUWX\">Search in note</a>&nbsp;searches the source while it shows, and the preview otherwise.</li></ul><h2>Drawing canvases</h2><p>A drawing canvas is an Excalidraw canvas, like the one of a <a class=\"reference-link\" href=\"#root/_help_grjYqerjn243\">Canvas</a> note, drawn directly in the text note. It is not a note of its own: the drawing is kept in a <code>Canvas.excalidraw</code> <a href=\"#root/_help_0vhv7lsOLy82\">attachment</a> of the text note and is saved together with the text.</p><ul><li>To insert a drawing canvas, open the <span class=\"tn-icon cke cke-plus\"></span> <em>Insert</em> menu of the <a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a> and choose <span class=\"tn-icon bx bx-pen\"></span> <em>Drawing canvas</em>, above <em>Mermaid diagram</em>. It is also available as <em>Drawing canvas</em> in the <a class=\"reference-link\" href=\"#root/_help_ZlN4nump6EbW\">Slash Commands</a>. The canvas is added empty and editable, in a <em>Medium</em> box with its title hidden, and takes the focus, ready for drawing.</li><li>To draw or write over an image, select the image and press the <span class=\"tn-icon bx bxs-pen\"></span> <em>Convert image to a drawing canvas</em> button of its toolbar. The image is replaced by an editable drawing canvas in a <em>Medium</em> box, with its title hidden and the focus in it. The image sits at its original size in the middle of the canvas, zoomed so that all of it shows, and is locked so that it cannot be selected or moved by accident. While it is locked, the canvas can be zoomed in on the image but not zoomed out past it or scrolled beyond its edges. To move or resize the image anyway, right-click it and choose <em>Unlock</em>. The caption of the image is kept, but not its alignment or link. Only an image on its own line can be converted, not one inside a paragraph. Undo brings the image back.</li><li>An Excalidraw file (<code>.excalidraw</code>) attached with the <span class=\"tn-icon cke cke-paper-clip\"></span><em>Attach file</em> button becomes a drawing canvas too, in a <em>Medium</em> box titled with the file name. It starts with <em>Editable</em> off, so the drawing shows but cannot be changed until <em>Editable</em> is turned on (see below).</li><li>To draw on a canvas that does not have the focus, click it first. Until then, touch gestures scroll the note. The canvas then has the tools, menus and keyboard shortcuts of a Canvas note. The toolbars, the menus and the properties of the selected shapes show only while the canvas has the focus, so elsewhere the drawing reads like a picture in the text.</li><li>The mouse wheel and the touchpad scroll the note over a canvas too, as over the text. To zoom, use the zoom buttons of the canvas toolbar; to move around the drawing, use the <span class=\"tn-icon bx bxs-hand\"></span> <em>Hand</em> tool. In fullscreen, the mouse wheel moves and zooms the drawing instead.</li><li>The canvas toolbar replaces the Excalidraw menu: <em>Export image</em>, <em>Find on canvas</em>, <em>Library</em> and <em>Help</em> are at the end of its <span class=\"tn-icon bx bx-category\"></span> <em>More tools</em> menu. In fullscreen, the Excalidraw menu shows again.</li><li>A new drawing has the background color of the note. A background chosen from the Excalidraw menu replaces it.</li><li>To protect a finished drawing from accidental changes, select it and turn off the <span class=\"tn-icon bx bx-edit-alt\"></span> <em>Editable</em> button at the start of its toolbar, or uncheck <em>Editable</em> in its <span class=\"tn-icon cke cke-three-vertical-dots\"></span> <em>More actions</em> menu. The drawing then shows as a still picture, at the zoom and position it had, and can no longer be changed, zoomed or moved. To draw again, turn <em>Editable</em> back on.</li><li>The box sizes, resizing, the caption and the title work as for an included note, but the toolbar of a drawing leaves the box size, <em>Show title</em> and <em>Convert to link</em> to its <em>More actions</em> menu.</li><li>In the desktop layout, Excalidraw keeps its desktop interface however small the box is. In the mobile layout, a narrow or short box switches it to a compact interface. For more room, choose <em>Full</em>, or show the title and press <span class=\"tn-icon bx bx-fullscreen\"></span> <em>Fullscreen</em>.</li><li>Pictures added to the drawing are stored in the same attachment. A converted image is kept as an image attachment of the note instead, named with a generated code.</li><li>In a <a href=\"#root/_help_CoFPLs3dRlXc\">read-only note</a>, the drawing shows as a still picture too.</li><li>On a <a href=\"#root/_help_R9pX4DGra2Vt\">shared page</a>, the drawing is shown as a picture at its own size, whatever the size of its box, in light or dark colors to match the page. Each change to the drawing saves this picture as an SVG image attachment of the note, also named with a generated code.</li></ul><h3>Limitations</h3><ul><li>The Excalidraw shape library is not saved for a drawing canvas.</li><li>Outside the editor, for example in a tooltip, when printing or in the list of attachments, the drawing is shown as a picture.</li><li>A drawing has no picture for shared pages until its first change, except one converted from an image. Until then, for example for an attached <code>.excalidraw</code> file, a shared page shows a link to download the drawing instead.</li><li>In Safari, the picture of a drawing on a shared page follows the light or dark appearance of the system rather than the theme chosen on the page.</li><li>A copy of a drawing canvas pasted in the same note shares the drawing with the original, so a change to one shows in the other only after the note is opened again. A copy pasted in another note gets a drawing of its own.</li></ul>",
+ "_help_nBAXQFj20hS1": "<p>Text notes can \"include\" another note as a read-only widget or an interactive widget, depending on the type of note.</p><p>This can be useful for e.g. including a dynamically generated chart (from scripts &amp; \"render HTML\" note) or other more advanced use cases.</p><h2>Including a note</h2><p>In the&nbsp;<a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a>, look for the&nbsp;<span class=\"tn-icon cke cke-trilium-note\"></span> button. There is also a keyboard shortcut defined for it but it is not allocated by default.</p><p>To include a note that is already linked, right-click a reference link to it in a text note being edited and select <em>Convert link to an included note</em>, at the end of the menu. The include gets the box size that suits the note, as one added from the button does.</p><p>An <a href=\"#root/_help_0vhv7lsOLy82\">attachment</a> can be included the same way, from the context menu of a link to it (see <em>Embedding an attachment</em> there).</p><p>A link to blocks of a text note is converted the same way, with <em>Convert link to note excerpt</em>, and the include then shows only those blocks. See <a class=\"reference-link\" href=\"#root/_help_klC3ilXa9kUE\">Block references</a>.</p><h2>Box sizes</h2><p>The box size sets how much of the included note is shown.</p><ul><li><em>Tiny</em> shows a single row instead of the content: the note's icon, its title with the path to the note above it, and buttons to act on the note. The included note is never rendered, so wherever the note is shown outside the editor, such as in print, in a tooltip or on a shared page, a <em>Tiny</em> include appears as a link to the included note.</li><li><em>Small</em> and <em>Medium</em> show the content in a box of limited height. Text scrolls inside the box, while a picture, a diagram or a video is scaled down to fit it.</li><li><em>Full</em> shows the whole content.</li><li><em>Expandable</em> shows only the title until its <span class=\"tn-icon bx bx-chevron-right\"></span> arrow is pressed. In a read-only note, a click anywhere on the title row other than its buttons and link expands or collapses it as well.</li></ul><p>A new include gets the size that suits what it shows:</p><ul><li><em>Tiny</em> for a note or an attachment that has no preview, such as a relation map or an archive.</li><li><em>Small</em> for audio.</li><li><em>Full</em> for a code note or a code file, such as a <code>.js</code>, <code>.py</code> or <code>.txt</code> attachment, and for an excerpt of the blocks of a text note.</li><li><em>Medium</em> for anything else.</li></ul><p>The dialog that includes a note selects that size once the note is picked, and you can choose another one there. To change the size later, select the include and use the <em>Box size</em> menu in its toolbar, or the <em>Size</em> submenu of its <em>More actions</em> menu. For an included code or Markdown note and an embedded code or Markdown file, the <em>Box size</em> menu is the <span class=\"tn-icon bx bx-move-vertical\"></span> button, whose tooltip names the current size.</p><h2>Resizing</h2><p>A <em>Small</em>, <em>Medium</em> or <em>Expandable</em> include can be resized to any width and height. A <em>Tiny</em> or <em>Full</em> include always fits its content.</p><ul><li>To resize an include, select it and drag the handle in its bottom-right corner. To change only the width or only the height, drag the middle of its right or bottom edge instead, where a touch screen shows a handle too. In right-to-left text, the handle is in the bottom-left corner and the width changes from the left edge.</li><li>Resizing works with a mouse, a pen or a finger.</li><li>While the height changes, moving the handle near the top or the bottom of the note scrolls the note.</li><li>An include narrower than the note is centered, so changing its width moves both of its sides. Making it as wide as the note returns it to the full width.</li><li>To cancel a resize, press <kbd>Esc</kbd> before releasing the handle.</li><li>To reset the size, double-click the corner handle, or double-tap it on a touch screen. Double-clicking the right or bottom edge resets only the width or the height.</li><li>Choosing a box size resets the height. Choosing <em>Tiny</em> or <em>Full</em> resets the width too.</li><li>While an <em>Expandable</em> include is collapsed, only its width can be changed.</li></ul><h2>Caption</h2><p>An include can have a caption, shown centered at the bottom of its box. The caption is part of the text note, so it can be formatted like the rest of the text, for example in bold or with a link.</p><ul><li>To add a caption, select the include, press the <span class=\"tn-icon cke cke-caption\"></span> <em>Toggle caption on</em> button in its toolbar and type the caption.</li><li>To remove the caption, press the same button again. Pressing it once more brings back the text it had, as long as the note stays open.</li><li>A <em>Tiny</em> include has no caption. Switching an include to <em>Tiny</em> removes its caption, and switching it back to a larger size restores the caption, as long as the note stays open.</li><li>An <em>Expandable</em> include shows its caption under the title while the content is collapsed, and under the content once it is expanded.</li></ul><h2>Title</h2><p>The title row of an include links to the included note and holds its buttons. To show only the content, select the include and press the <span class=\"tn-icon bx bx-window-alt\"></span> <em>Show title</em> button in its toolbar. Pressing it again shows the title.</p><ul><li>While the title is hidden, the <span class=\"tn-icon cke cke-three-vertical-dots\"></span> <em>More actions</em> button in the toolbar of the include opens the menu of the included note.</li><li>A <em>Tiny</em> or <em>Expandable</em> include always shows its title, and its toolbar has no <em>Show title</em> button.</li></ul><h2>Opening an included note</h2><p>To open an included note in a new tab, press the <span class=\"tn-icon bx bx-link-external\"></span> <em>Open in new tab</em> button at the end of its title. An embedded attachment has the same button.</p><p>The <span class=\"tn-icon bx bx-dots-vertical-rounded\"></span> <em>More actions</em> button at the end of the title row opens the same menu as right-clicking anywhere on the title row: the other places to open the note in and, for an embedded attachment, the actions on the attachment.</p><p>In a note being edited, the menu also has the commands of the include's toolbar: the <em>Size</em> submenu, <em>Show title</em> and <em>Show caption</em>, each checked while it is in effect, and <em>Convert to link</em> at the end. A drawing canvas, a Mermaid diagram, an included text, code or Markdown note and an embedded code or Markdown file also have <em>Editable</em>, above <em>Size</em>. An included code or Markdown note, an embedded code or Markdown file and a Mermaid diagram also have the <em>Word wrap</em> and <em>Line numbers</em> submenus after <em>Editable</em> (see <em>Editing an include in place</em> below). A Mermaid diagram, an included Markdown note and an embedded Markdown file also have <em>Source view</em>, <em>Split view</em> and <em>Preview</em> after these submenus. For an embedded attachment they follow its first group of actions; for an included note they end the menu.</p><p>To show an include of size <em>Medium</em> or <em>Full</em> on the whole screen, press the <span class=\"tn-icon bx bx-fullscreen\"></span> <em>Fullscreen</em> button at the end of its title. An excerpt of the blocks of a note has an <span class=\"tn-icon bx bx-pencil\"></span> <em>Edit excerpt</em> button there instead; see <a class=\"reference-link\" href=\"#root/_help_klC3ilXa9kUE\">Block references</a>. To return, press <span class=\"tn-icon bx bx-exit\"></span> <em>Exit fullscreen</em> in the top-right corner, or <kbd>Esc</kbd>.</p><p>A <em>Tiny</em> include has these buttons instead, followed by the same <em>More actions</em> button:</p><ul><li>For a note, <span class=\"tn-icon bx bx-edit\"></span> <em>Quick edit</em> opens the note in&nbsp;<a class=\"reference-link\" href=\"#root/_help_ZjLYv08Rp3qC\">Quick edit</a>, and <span class=\"tn-icon bx bx-link-external\"></span> <em>Open in new tab</em> opens it in a new tab.</li><li>For an embedded attachment, <span class=\"tn-icon bx bx-file-find\"></span> <em>Open externally</em> opens the file in another application, and <span class=\"tn-icon bx bx-download\"></span> <em>Download</em> downloads it. The size of the file is shown under its title.</li></ul><h2>Converting an include to a link</h2><p>To replace an include with a link to the included note, select it and press the <span class=\"tn-icon cke cke-link\"></span> <em>Convert to link</em> button in its toolbar, or choose <em>Convert to link</em> at the end of its <em>More actions</em> menu. An embedded attachment turns into a link to the attachment the same way.</p><h2>Included notes in the share functionality</h2><p>If a <a href=\"#root/_help_R9pX4DGra2Vt\">shared note</a> contains one or more included notes, they will be displayed in the content of the note as if they were part of the note itself. The caption of an include is shown under the included content. A <em>Tiny</em> include is shown as a link to the included note instead, and so is an include that would show a note already shown around it, such as a note that includes itself. The same goes for a printed or exported note.</p><p>For this to work, the included notes must also be shared, otherwise they will not be shown. However, the included notes can still be hidden from the note tree via <code>#shareHiddenFromTree</code>.</p><h2>Interactive notes</h2><p>Since v0.104.0, included notes might become interactive depending on their note type:</p><ul><li><a class=\"reference-link\" href=\"#root/_help_GTwFsgaA0lCt\">Collections</a>&nbsp;(e.g.&nbsp;<a class=\"reference-link\" href=\"#root/_help_81SGnPGMk7Xc\">Geo Map</a>) will render fully interactive, including creating new notes.</li><li><a class=\"reference-link\" href=\"#root/_help_m523cpzocqaD\">Saved Search</a>&nbsp;will also display the results.</li><li><a class=\"reference-link\" href=\"#root/_help_1vHRoWCEjj0L\">Web View</a>&nbsp;provides an interactive preview of the website.</li></ul><h2>Included images</h2><p>An included image, whether an image note or an image attachment, is shown in the image viewer, which zooms and pans it:</p><ul><li>To zoom, press the <span class=\"tn-icon bx bx-plus-circle\"></span> <em>Zoom in</em> and <span class=\"tn-icon bx bx-minus-circle\"></span> <em>Zoom out</em> buttons in the bottom-right corner of the image, or pinch on a touch screen. The percentage between them resets the zoom.</li><li>To zoom with the mouse wheel, click the image first. Until then, the mouse wheel scrolls the note.</li><li>To pan an image that is zoomed in, drag it. At its fitted size, dragging the image on a touch screen scrolls the note.</li><li>To return to the fitted size, double-click the image.</li></ul><p>In a <em>Small</em> or <em>Medium</em> box, the image is scaled down to fit the height of the box. In fullscreen, it fits the screen.</p><h2>Editing an include in place</h2><p>An included text note, an included code note and an embedded code file such as a <code>.js</code>, <code>.py</code> or <code>.txt</code> attachment can be edited without leaving the note that includes them. Until then, a code note or file is shown read-only in the code editor, where its code can be selected and copied, and its blocks folded and unfolded with the arrows in its gutter. Included Markdown can be edited too, see <em>Included Markdown</em> below.</p><ul><li>To edit, select the include and turn on the <span class=\"tn-icon bx bx-edit-alt\"></span> <em>Editable</em> button at the start of its toolbar, or check <em>Editable</em> in its <span class=\"tn-icon cke cke-three-vertical-dots\"></span> <em>More actions</em> menu. Turn <em>Editable</em> off to stop editing.</li><li>While <em>Editable</em> is on, the arrow keys move the caret into the include and back out, as through the rest of the text. Entering from above or from the left puts the caret at the start of the include, and entering from below or from the right puts it at the end. A collapsed <em>Expandable</em> include is skipped.</li><li>While an included text note has the focus, the formatting toolbar applies to it. The notes it includes in turn stay read-only.</li><li>Code is edited in the same code editor as a <a class=\"reference-link\" href=\"#root/_help_6f9hih2hXXZk\">Code</a> note, with its theme, indentation and line wrapping settings.</li><li>Typing <code>/</code> in the code lists the <a class=\"reference-link\" href=\"#root/_help_IEgsWp5hHH35\">Code Snippets</a> of its language, as in a code note.</li><li>The toolbar of an included code note or an embedded code file also has the language and indentation menus of the&nbsp;<a class=\"reference-link\" href=\"#root/_help_AlJ73vBCjWDw\">Status bar</a>, between <em>Editable</em> and the <span class=\"tn-icon bx bx-move-vertical\"></span> <em>Box size</em> menu: <em>Change language mode</em>, which shows the current language, and <em>Change tab width</em>, which shows the current indentation. <em>Re-indent content to</em> converts the indentation of the code itself and saves it to the included note or file, whether <em>Editable</em> is on or off.<ul><li>For an included note, the menus change the note, as they do in its own tab.</li><li>For an embedded code file, the language and indentation settings change only how this include shows the file, and are saved with the note that includes it. The language replaces the one that the file name gives, and the <em>Use default</em> entries return to the indentation set in&nbsp;<a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a> → <em>Code Notes</em>. These settings leave the file itself unchanged, and other includes of it keep their own settings.</li></ul></li><li>The <span class=\"tn-icon cke cke-three-vertical-dots\"></span> <em>More actions</em> menu of an included code or Markdown note, an embedded code or Markdown file and a <a href=\"#root/_help_CohkqWQC1iBv\">Mermaid diagram</a> has two more submenus after <em>Editable</em>, each with <em>Auto</em>, <em>On</em> and <em>Off</em>. They change how the code editor shows the source.<ul><li><em>Word wrap</em> wraps long lines instead of scrolling them. <em>Auto</em> follows the setting in <a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a> → <em>Code Notes</em>. For an included note, it sets the <code>#wrapLines</code> label of the note, as the <em>Word wrap</em> submenu of its <a class=\"reference-link\" href=\"#root/_help_8YBEPzcpUgxw\">Note menu</a> does for a code note. For an embedded file or a Mermaid diagram, it changes only this include.</li><li><em>Line numbers</em> shows or hides the numbers at the start of each line. <em>Auto</em> shows them, as a code note does. It changes only this include, for an included note as well.</li></ul></li><li>The changes are saved as you type, to the included note or to the attachment, as they would be in its own tab.</li><li>The changes made in the code editor of an include are part of the undo history of the note that includes it, together with the changes to its text, in the order they were made. This includes the source of included Markdown and of a <a href=\"#root/_help_CohkqWQC1iBv\">Mermaid diagram</a>, and the changes to a drawing canvas (see below).<ul><li><kbd>Ctrl</kbd>+<kbd>Z</kbd> undoes the last change of the note, and <kbd>Ctrl</kbd>+<kbd>Y</kbd> or <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>Z</kbd> redoes it, whether the caret is in the text or in an include, and also while <em>Editable</em> is off. The <span class=\"tn-icon cke cke-undo\"></span> <em>Undo</em> and <span class=\"tn-icon cke cke-redo\"></span> <em>Redo</em> buttons of the formatting toolbar do the same. With the Vim key bindings, <code>u</code> and <kbd>Ctrl</kbd>+<kbd>R</kbd> in an include do the same too.</li><li>The focus moves to the change that was undone or redone: into the code editor or the drawing canvas of the include, or back to the text.</li><li>Undoing a change of an included note saves the included note again. Once the included note has been changed elsewhere, for example in another tab, its earlier changes can no longer be undone from here, and undo skips them.</li><li>An included text note keeps an undo history of its own.</li></ul></li><li>An include of <a class=\"reference-link\" href=\"#root/_help_klC3ilXa9kUE\">Block references</a> edits only the referenced blocks.</li><li>Editing is not available in a <a href=\"#root/_help_CoFPLs3dRlXc\">read-only note</a>, for an included note marked <code>#readOnly</code>, or for an attachment of another note.</li><li><a class=\"reference-link\" href=\"#root/_help_McngOG2jbUWX\">Search in note</a> finds the text of included text and code notes among the results of the note around them, and replaces it while <em>Editable</em> is on.</li></ul><h2>Included Markdown</h2><p>An included&nbsp;<a class=\"reference-link\" href=\"#root/_help_6RM1Q7ppFVoj\">Markdown</a>&nbsp;note and an embedded Markdown file, such as a <code>.md</code> attachment, are shown with the same three views as a Markdown note in its own tab (see&nbsp;<a class=\"reference-link\" href=\"#root/_help_SL5f1Auq7sVN\">Note types with split view</a>): <span class=\"tn-icon bx bx-code\"></span> <em>Source view</em>, <span class=\"tn-icon bx bxs-dock-left\"></span> <em>Split view</em> and <span class=\"tn-icon bx bx-show\"></span> <em>Preview</em>.</p><ul><li>To switch the view, press one of the three buttons in the title row of the include. In a note being edited, the toolbar of the include has the same buttons after <em>Editable</em>, and its <span class=\"tn-icon cke cke-three-vertical-dots\"></span> <em>More actions</em> menu has them as <em>Source view</em>, <em>Split view</em> and <em>Preview</em>.</li><li>Until a view is chosen, the include shows the <em>Preview</em>, and the <em>Split view</em> while <em>Editable</em> is on.</li><li>To edit the Markdown, turn on <em>Editable</em> (see <em>Editing an include in place</em> above). The source is edited in the code editor of a Markdown note, and the preview follows the changes as you type. While <em>Editable</em> is off, the source can be read and copied but not changed.</li><li>The source has the slash commands and the <code>@</code> and <code>[[</code> note links of a <a class=\"reference-link\" href=\"#root/_help_6RM1Q7ppFVoj\">Markdown</a> note. A note created from the <code>@</code> or <code>[[</code> list goes under the included note, or for an embedded file under the note that includes it, and <code>/image</code> uploads the image to that same note.</li><li>The <em>Word wrap</em> and <em>Line numbers</em> submenus of the <em>More actions</em> menu change how the source shows, as for code (see <em>Editing an include in place</em> above).</li><li>As in a Markdown note, the preview scrolls along with the source and highlights the block where the cursor is, and <kbd>Ctrl</kbd>+<kbd>B</kbd>, <kbd>Ctrl</kbd>+<kbd>I</kbd>, <kbd>Ctrl</kbd>+<kbd>M</kbd> and <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>X</kbd> format the selection.</li><li>In a note being edited, the view is saved with the include, so two includes of the same note can show different views. In a <a href=\"#root/_help_CoFPLs3dRlXc\">read-only note</a>, the view can be changed too, until the note is opened again.</li><li>While the source shows, the include has the height of its box size, or the height it was resized to. A <em>Full</em> include fits its content instead.</li><li><a class=\"reference-link\" href=\"#root/_help_McngOG2jbUWX\">Search in note</a>&nbsp;searches the source while it shows, and the preview otherwise.</li></ul><h2>Drawing canvases</h2><p>A drawing canvas is an Excalidraw canvas, like the one of a <a class=\"reference-link\" href=\"#root/_help_grjYqerjn243\">Canvas</a> note, drawn directly in the text note. It is not a note of its own: the drawing is kept in a <code>Canvas.excalidraw</code> <a href=\"#root/_help_0vhv7lsOLy82\">attachment</a> of the text note and is saved together with the text.</p><ul><li>To insert a drawing canvas, open the <span class=\"tn-icon cke cke-plus\"></span> <em>Insert</em> menu of the <a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a> and choose <span class=\"tn-icon bx bx-pen\"></span> <em>Drawing canvas</em>, above <em>Mermaid diagram</em>. It is also available as <em>Drawing canvas</em> in the <a class=\"reference-link\" href=\"#root/_help_ZlN4nump6EbW\">Slash Commands</a>. The canvas is added empty and editable, in a <em>Medium</em> box with its title hidden, and takes the focus, ready for drawing.</li><li>To draw or write over an image, select the image and press the <span class=\"tn-icon bx bxs-pen\"></span> <em>Convert image to a drawing canvas</em> button of its toolbar. The image is replaced by an editable drawing canvas in a <em>Medium</em> box, with its title hidden and the focus in it. The image sits at its original size in the middle of the canvas, zoomed so that all of it shows, and is locked so that it cannot be selected or moved by accident. While it is locked, the canvas can be zoomed in on the image but not zoomed out past it or scrolled beyond its edges. To move or resize the image anyway, right-click it and choose <em>Unlock</em>. The caption of the image is kept, but not its alignment or link. Only an image on its own line can be converted, not one inside a paragraph. Undo brings the image back.</li><li>An Excalidraw file (<code>.excalidraw</code>) attached with the <span class=\"tn-icon cke cke-paper-clip\"></span><em>Attach file</em> button becomes a drawing canvas too, in a <em>Medium</em> box titled with the file name. It starts with <em>Editable</em> off, so the drawing shows but cannot be changed until <em>Editable</em> is turned on (see below).</li><li>To draw on a canvas that does not have the focus, click it first. Until then, touch gestures scroll the note. The canvas then has the tools, menus and keyboard shortcuts of a Canvas note. The toolbars, the menus and the properties of the selected shapes show only while the canvas has the focus, so elsewhere the drawing reads like a picture in the text.</li><li>The mouse wheel and the touchpad scroll the note over a canvas too, as over the text. To zoom, use the zoom buttons of the canvas toolbar; to move around the drawing, use the <span class=\"tn-icon bx bxs-hand\"></span> <em>Hand</em> tool. In fullscreen, the mouse wheel moves and zooms the drawing instead.</li><li>The canvas toolbar replaces the Excalidraw menu: <em>Export image</em>, <em>Find on canvas</em>, <em>Library</em> and <em>Help</em> are at the end of its <span class=\"tn-icon bx bx-category\"></span> <em>More tools</em> menu. In fullscreen, the Excalidraw menu shows again.</li><li>The changes to the drawing are part of the undo history of the text note (see <em>Editing an include in place</em> above). <kbd>Ctrl</kbd>+<kbd>Z</kbd>, <kbd>Ctrl</kbd>+<kbd>Y</kbd> and the <span class=\"tn-icon bx bx-undo\"></span> <em>Undo</em> and <span class=\"tn-icon bx bx-redo\"></span> <em>Redo</em> buttons of the canvas toolbar undo and redo the last change of the note, in the drawing or in the text.</li><li>A new drawing has the background color of the note. A background chosen from the Excalidraw menu replaces it.</li><li>To protect a finished drawing from accidental changes, select it and turn off the <span class=\"tn-icon bx bx-edit-alt\"></span> <em>Editable</em> button at the start of its toolbar, or uncheck <em>Editable</em> in its <span class=\"tn-icon cke cke-three-vertical-dots\"></span> <em>More actions</em> menu. The drawing then shows as a still picture, at the zoom and position it had, and can no longer be changed, zoomed or moved. To draw again, turn <em>Editable</em> back on.</li><li>The box sizes, resizing, the caption and the title work as for an included note, but the toolbar of a drawing leaves the box size, <em>Show title</em> and <em>Convert to link</em> to its <em>More actions</em> menu.</li><li>In the desktop layout, Excalidraw keeps its desktop interface however small the box is. In the mobile layout, a narrow or short box switches it to a compact interface. For more room, choose <em>Full</em>, or show the title and press <span class=\"tn-icon bx bx-fullscreen\"></span> <em>Fullscreen</em>.</li><li>Pictures added to the drawing are stored in the same attachment. A converted image is kept as an image attachment of the note instead, named with a generated code.</li><li>In a <a href=\"#root/_help_CoFPLs3dRlXc\">read-only note</a>, the drawing shows as a still picture too.</li><li>On a <a href=\"#root/_help_R9pX4DGra2Vt\">shared page</a>, the drawing is shown as a picture at its own size, whatever the size of its box, in light or dark colors to match the page. Each change to the drawing saves this picture as an SVG image attachment of the note, also named with a generated code.</li></ul><h3>Limitations</h3><ul><li>The Excalidraw shape library is not saved for a drawing canvas.</li><li>Outside the editor, for example in a tooltip, when printing or in the list of attachments, the drawing is shown as a picture.</li><li>A drawing has no picture for shared pages until its first change, except one converted from an image. Until then, for example for an attached <code>.excalidraw</code> file, a shared page shows a link to download the drawing instead.</li><li>In Safari, the picture of a drawing on a shared page follows the light or dark appearance of the system rather than the theme chosen on the page.</li><li>A copy of a drawing canvas pasted in the same note shares the drawing with the original, so a change to one shows in the other only after the note is opened again. A copy pasted in another note gets a drawing of its own.</li></ul>",
"_help_CohkqWQC1iBv": "<p>Press the&nbsp;<span class=\"tn-icon cke cke-plus\"></span> button in the&nbsp;<a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a>&nbsp;to reveal special inserable items and blocks such as symbols, Math expressions and separators.</p><h2>Bookmarks</h2><p>See the dedicated&nbsp;<a class=\"reference-link\" href=\"#root/_help_oSuaNgyyKnhu\">Anchors</a>&nbsp;section.</p><h2>Emoji</h2><figure class=\"image image-style-align-right image_resized\" style=\"width:42.4%;\"><img style=\"aspect-ratio:366/410;\" src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/Insert%20buttons_plus.png\" width=\"366\" height=\"410\"></figure><p>This feature allows inserting Unicode emoji characters. Simply select a category and a desired emoji to insert it.</p><p>Emojis can also be searched by their English name and the skin tone can be selected via a combo box to the right.</p><p>There is also the possibility of inserting emojis directly by typing <code>:</code> followed by a name of an emoji, triggering the display of a list of emojis. Simply use the arrow keys to select one and press <kbd>Enter</kbd> or <kbd>Tab</kbd> to insert it.</p><img src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/1_Insert%20buttons_plus.png\" width=\"272\" height=\"187\"><h2>Symbols</h2><figure class=\"image image-style-align-right\"><img style=\"aspect-ratio:346/322;\" src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/Insert%20buttons_image.png\" width=\"346\" height=\"322\"></figure><p>Pressing the&nbsp;<span class=\"tn-icon cke cke-special-characters\"></span> button will reveal a popup window displaying a list of characters that are generally more difficult to insert directly from the keyboard, such as a subset of emojis, quotation characters, etc.</p><p>Interaction:</p><ul><li>Click on a character to insert it at the current cursor position.</li><li>The window can be dragged around by the top bar where the title is, to avoid it getting in the way of the text.</li><li>Click on the <em>Category</em> selector to filter the characters.</li></ul><h2>Multicolumn layout</h2><p>See the dedicated&nbsp;<a class=\"reference-link\" href=\"#root/_help_wYDzQ1fBFgfT\">Multicolumn layout</a>&nbsp;page.</p><h2>Math equations</h2><p>See the dedicated&nbsp;<a class=\"reference-link\" href=\"#root/_help_YfYAtQBcfo5V\">Math Equations</a>&nbsp;page.</p><h2>Drawing canvas</h2><p>Choose <span class=\"tn-icon bx bx-pen\"></span> <em>Drawing canvas</em> to draw on an Excalidraw canvas inside the text. See <em>Drawing canvases</em> in <a class=\"reference-link\" href=\"#root/_help_nBAXQFj20hS1\">Include Note</a>.</p><h2>Mermaid diagram</h2><p>Press the&nbsp;<span class=\"tn-icon cke cke-trilium-mermaid-insert\"></span> button to create an inline Mermaid diagram. The arrow next to it lists a template for each kind of diagram. The diagram is also available as <em>Mermaid diagram</em> in the&nbsp;<a class=\"reference-link\" href=\"#root/_help_ZlN4nump6EbW\">Slash Commands</a>.</p><p>This feature is quite similar to the&nbsp;<a class=\"reference-link\" href=\"#root/_help_s1aBHPd79XYj\">Mermaid Diagrams</a>&nbsp;note types and is meant as an alternative to it for simple diagrams. For more complex diagrams, use the&nbsp;<a class=\"reference-link\" href=\"#root/_help_nBAXQFj20hS1\">Include Note</a>&nbsp;feature for a dedicated Mermaid note.</p><figure class=\"image\"><img style=\"aspect-ratio:1174/358;\" src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/2_Insert%20buttons_image.png\" width=\"1174\" height=\"358\"></figure><p>A diagram shows in a box like the one of an included note, so it can be resized, given another box size (<em>Small</em>, <em>Medium</em> or <em>Full</em>) from its <span class=\"tn-icon cke cke-three-vertical-dots\"></span> <em>More actions</em> menu or shown in fullscreen, as described in&nbsp;<a class=\"reference-link\" href=\"#root/_help_nBAXQFj20hS1\">Include Note</a>.</p><ul><li>The <span class=\"tn-icon bx bx-edit-alt\"></span> <em>Editable</em> button at the start of the diagram's toolbar decides whether its source can be changed. While it is off, the source still shows, but read-only.</li><li>The buttons next to it choose what the diagram shows, as for a Mermaid note: <span class=\"tn-icon bx bx-code\"></span> <em>Source view</em> for the Mermaid source alone, <span class=\"tn-icon bx bxs-dock-left\"></span> <em>Split view</em> for the source with the diagram next to it, and <span class=\"tn-icon bx bx-show\"></span> <em>Preview</em> for the diagram alone. Its <em>More actions</em> menu offers the same choice.</li><li>The <em>Word wrap</em> and <em>Line numbers</em> submenus of its <em>More actions</em> menu change how the source shows, each with <em>Auto</em>, <em>On</em> and <em>Off</em>, as for an included code note (see <em>Editing an include in place</em> in <a class=\"reference-link\" href=\"#root/_help_nBAXQFj20hS1\">Include Note</a>).</li><li>A new diagram starts editable, in <em>Split view</em>. The diagram updates a moment after you stop typing. If the source has an error, the error shows over the last diagram that worked, which stays dimmed, as in a Mermaid note. On desktop, drag the divider between the source and the diagram to resize them.</li><li>A diagram without a chosen view shows the source next to the diagram while it is editable, and the diagram alone otherwise. In a read-only note, the source can never be changed. A read-only note and the AI chat show a diagram in the same box, in the view it was saved with, and with the zoom buttons over the diagram instead of in a toolbar. A <em>Medium</em> or <em>Full</em> diagram also has a <span class=\"tn-icon bx bx-fullscreen\"></span> <em>Fullscreen</em> button there, or over the source in the <em>Source</em> view.</li><li>To zoom, use the <span class=\"tn-icon bx bx-zoom-out\"></span> and <span class=\"tn-icon bx bx-zoom-in\"></span> buttons of the diagram's toolbar; the zoom level between them resets the zoom. In fullscreen, where the toolbar is hidden, the same buttons show over the diagram. Drag the diagram to move around it, and double-click it to reset the view. The mouse wheel scrolls the note until you click the diagram, and then zooms it.</li><li>While the source shows, the <span class=\"tn-icon bx bx-help-circle\"></span> <em>Mermaid syntax help</em> button at the end of the toolbar opens the help on&nbsp;<a class=\"reference-link\" href=\"#root/_help_s1aBHPd79XYj\">Mermaid Diagrams</a>, which links to the Mermaid syntax.</li><li>The changes made to the source of a diagram are part of the undo history of the text note, in the order they were made. <kbd>Ctrl</kbd>+<kbd>Z</kbd> and <kbd>Ctrl</kbd>+<kbd>Y</kbd> undo and redo them from the source as well as from the text, as described in <em>Editing an include in place</em> in <a class=\"reference-link\" href=\"#root/_help_nBAXQFj20hS1\">Include Note</a>.</li></ul><p>The source of the diagram stays in the note as a Mermaid code block, so the diagram is exported to Markdown as a <code>mermaid</code> code block that other applications can show.</p><p>Diagrams created in earlier versions keep the view they were saved with, and open editable.</p><h2>Horizontal ruler</h2><p>This feature will display a horizontal line, generally useful to separate different sections of the text. To do so, press the&nbsp;<span class=\"tn-icon cke cke-horizontal-line\"></span> button in the&nbsp;<a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a>.</p><img src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/1_Insert%20buttons_image.png\" width=\"502\" height=\"95\"><p>Alternatively, it's possible to insert a horizontal ruler by typing <code>---</code>.</p><h2>Page break</h2><figure class=\"image image-style-align-right\"><img style=\"aspect-ratio:371/79;\" src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/3_Insert%20buttons_image.png\" width=\"371\" height=\"79\"></figure><p>Page breaks provide a way to force the next paragraph or block (table, image, etc.) to be displayed onto the next page when printing (either to a real printer to <a href=\"#root/_help_NRnIZmSMc5sj\">when exporting to PDF</a>).</p><p>Page breaks are marked in the editor with the words <em>Page break</em>, but they will not actually be shown when printed.</p><ul><li>To insert a page break, press the&nbsp;<span class=\"tn-icon cke cke-page-break\"></span> in the formatting toolbar.</li><li>To insert many page breaks at once, insert a page break first, click on it and press <kbd>Ctrl</kbd>+<kbd>C</kbd>. Then use <kbd>Ctrl</kbd>+<kbd>V</kbd>, to paste as many times as needed.</li></ul><h2>Date and time</h2><p>The <span class=\"tn-icon cke cke-trilium-date-time\"></span> button inserts the current date and time at the cursor, replacing the selected text if there is any. The inserted text takes the formatting of the text around it, so a date inserted inside bold text is bold too.</p><ul><li>To insert the date in the default format, press the button itself or press <kbd>Alt</kbd>+<kbd>T</kbd>.</li><li>To insert it in another format, press the arrow next to the button and pick a format from the list. Each entry shows the current date and time in that format: the default one, the date or the time alone, the date written out, and ISO 8601.</li><li>The same formats are offered by the <a class=\"reference-link\" href=\"#root/_help_ZlN4nump6EbW\">Slash Commands</a>: type <code>/date</code>, <code>/time</code>, <code>/now</code> or <code>/today</code>. The <em>Insert date/time</em> entry uses the default format, and shows what it inserts underneath; the other entries show their output in the title.</li></ul><p>The default format can be changed in <a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a> → <em>Text Notes</em> → <em>Editor</em> → <em>Date/time format</em>, using <a href=\"https://day.js.org/docs/en/display/format\">Day.js format tokens</a> (for example <code>DD.MM.YYYY HH:mm</code>).</p><h2>Icons</h2><p>Icons just like the ones for the <a href=\"#root/_help_p9kXRFAkwN4o\">note icon</a> can be inserted in text. For more information see&nbsp;<a class=\"reference-link\" href=\"#root/_help_hD8GawVuazff\">Icons</a>.</p>",
"_help_hD8GawVuazff": "<p>Icons just like the <a href=\"#root/_help_hD8GawVuazff\">note icons</a> can be inserted in the content of a note, including from any other <a href=\"#root/_help_gOKqSJgXLcIj\">custom icon packs</a>.</p><h2>Features</h2><ul><li>The icon can be formatted through the<a class=\"reference-link\" href=\"#root/_help_Gr6xFaF6ioJ5\">General formatting</a>&nbsp;tools of the&nbsp;<a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a>:<ul><li>Foreground/icon color</li><li>Background color/highlight</li><li>Font size</li></ul></li><li>Custom&nbsp;<a class=\"reference-link\" href=\"#root/_help_gOKqSJgXLcIj\">Icon Packs</a>&nbsp;are also supported.<ul><li>For emojis, prefer the Emoji functionality from&nbsp;<a class=\"reference-link\" href=\"#root/_help_CohkqWQC1iBv\">Insert buttons</a>.</li></ul></li><li>When an icon is clicked a floating toolbar appears with the following functions:<ul><li><span class=\"tn-icon bx bx-sticker\"></span>&nbsp;which changes the icon.</li><li><span class=\"tn-icon bx bx-reflect-horizontal\"></span>&nbsp;which applies transforms: rotate (90 / 180 / 270) and flip horizontal/vertical. Only one transform can be used per icon.</li></ul></li></ul><h2>Usage</h2><ul><li>The in-app help/user guide makes use of these icons in order to illustrate buttons in the UI.</li><li>The&nbsp;<a class=\"reference-link\" href=\"#root/_help_GnhlmrATVqcH\">Microsoft OneNote</a>&nbsp;importer also makes use of them for the&nbsp;<a class=\"reference-link\" href=\"#root/_help_LpvyEIBIAAj7\">Tags</a>.</li></ul><h2>Inserting an icon</h2><p>There are two ways to insert an icon:</p><ul><li>Via the&nbsp;<a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a>&nbsp;look for the&nbsp;<span class=\"tn-icon bx bx-plus\"></span> icon and then the&nbsp;<span class=\"tn-icon bx bx-sticker\"></span> icon.</li><li>Via&nbsp;<a class=\"reference-link\" href=\"#root/_help_ZlN4nump6EbW\">Slash Commands</a>, type <code>/icon</code>.</li></ul><p>An icon picker will appear, search for an icon and click it to insert it in the document.</p><h2>Finding notes by their icons</h2><p>An icon can be <a href=\"#root/_help_eIg8jdvaoNNd\">searched</a>. A note containing a&nbsp;<span class=\"tn-icon bx bx-star\"></span> icon can be found by searching for <code>star</code>, or its <code>iconClass</code> (<code>bx-star</code>).</p><p>To find the name of the icon, hover the mouse over an icon while in the icon picker.</p><h2>Markdown rendering</h2><p>When exporting to&nbsp;<a class=\"reference-link\" href=\"#root/_help_Oau6X9rCuegd\">Markdown</a>, the item will render as raw HTML representation of the icon as is used by Trilium:</p><pre><code class=\"language-text-html\">&lt;span class=\"tn-icon bx bx-star\"&gt;&lt;/span&gt;</code></pre>",
"_help_oiVPnW8QfnvS": "<h2>Trilium-specific shortcuts</h2><figure class=\"table\"><table><thead><tr><th>Action</th><th>PC</th><th>Mac</th></tr></thead><tbody><tr><td>Bring up inline formatting toolbar (arrow keys ←,→ to navigate, Enter to apply)</td><td>Alt+F10</td><td>⌥+F10</td></tr><tr><td>Bring up block formatting toolbar</td><td>Alt+F10</td><td>⌥+F10</td></tr><tr><td>Create <a href=\"#root/_help_QEAPj01N5f7w\">external link</a></td><td>Ctrl+K</td><td>⌘+K</td></tr><tr><td>Create <a href=\"#root/_help_QEAPj01N5f7w\">internal (note) link</a></td><td>Ctrl+L</td><td>⌘+L</td></tr><tr><td>Inserts current date and time at caret position</td><td>Alt+T</td><td>⌥+T</td></tr><tr><td>Increase paragraph indentation</td><td>Tab</td><td>⇥</td></tr><tr><td>Decrease paragraph indentation</td><td>Shift + Tab</td><td>⇧ + ⇥</td></tr><tr><td>Mark selected text as <a href=\"#root/_help_UYuUB1ZekNQU\">keyboard shortcut</a></td><td>Ctrl + Alt + K</td><td>⌘+ ⌥+ K</td></tr><tr><td>Insert&nbsp;<a class=\"reference-link\" href=\"#root/_help_YfYAtQBcfo5V\">Math Equations</a></td><td>Ctrl + M</td><td>⌘+ M</td></tr><tr><td>Move blocks (lists, paragraphs, etc.) up</td><td>Ctrl+↑</td><td>⌘+↑</td></tr><tr><td>Alt+↑</td><td>⌥+↑</td><td></td></tr><tr><td>Move blocks (lists, paragraphs, etc.) down</td><td>Ctrl+↑</td><td>⌘+↑</td></tr><tr><td>Alt+↓</td><td>⌥+↓</td><td></td></tr><tr><td>Move the selected content to another column of a <a class=\"reference-link\" href=\"#root/_help_wYDzQ1fBFgfT\">Multicolumn layout</a></td><td>Ctrl+←, Ctrl+→, Ctrl+Shift+Home, Ctrl+Shift+End</td><td>⌘+←, ⌘+→, ⌘+⇧+Home, ⌘+⇧+End</td></tr><tr><td>Move the current column of a multicolumn layout</td><td>Ctrl+Alt+←, Ctrl+Alt+→, Ctrl+Alt+Home, Ctrl+Alt+End</td><td>⌘+⌥+←, ⌘+⌥+→, ⌘+⌥+Home, ⌘+⌥+End</td></tr><tr><td>Add a column after or before the current one in a multicolumn layout</td><td>Ctrl+Enter, Ctrl+Shift+Enter</td><td>⌘+Enter, ⌘+⇧+Enter</td></tr><tr><td>Move the selected content to another tab in <a class=\"reference-link\" href=\"#root/_help_EK2ckIZ74tbT\">Content tabs</a></td><td>Ctrl+←, Ctrl+→, Ctrl+Shift+Home, Ctrl+Shift+End</td><td>⌘+←, ⌘+→, ⌘+⇧+Home, ⌘+⇧+End</td></tr><tr><td>Move the current tab of a tabs block</td><td>Ctrl+Alt+←, Ctrl+Alt+→, Ctrl+Alt+Home, Ctrl+Alt+End</td><td>⌘+⌥+←, ⌘+⌥+→, ⌘+⌥+Home, ⌘+⌥+End</td></tr><tr><td>Add a tab after or before the current one in a tabs block</td><td>Ctrl+Enter, Ctrl+Shift+Enter</td><td>⌘+Enter, ⌘+⇧+Enter</td></tr></tbody></table></figure><h2>Common shortcuts</h2><aside class=\"admonition tip\"><p>This section of keyboard shortcuts presents a subset of the keyboard shortcuts as supported by the editor technology we are using,&nbsp;<a class=\"reference-link\" href=\"#root/_help_MI26XDLSAlCD\">CKEditor</a>. The shortcuts were taken from the <a href=\"https://ckeditor.com/docs/ckeditor5/latest/features/accessibility.html#keyboard-shortcuts\">official documentation</a>. Note that not all the shortcuts in the original documentation are applicable (due to using a different configuration).</p></aside><h3>Content editing</h3><figure class=\"table\"><table><thead><tr><th>Action</th><th>PC</th><th>Mac</th></tr></thead><tbody><tr><td>Insert a hard break (a new paragraph)</td><td>Enter</td><td></td></tr><tr><td>Insert a soft break (a <code>&lt;br&gt;</code> element)</td><td>Shift+Enter</td><td>⇧Enter</td></tr><tr><td>Copy selected content</td><td>Ctrl+C</td><td>⌘C</td></tr><tr><td>Paste content</td><td>Ctrl+V</td><td>⌘V</td></tr><tr><td>Paste content as plain text</td><td>Ctrl+Shift+V</td><td>⌘⇧V</td></tr><tr><td>Undo</td><td>Ctrl+Z</td><td>⌘Z</td></tr><tr><td>Redo</td><td>Ctrl+Y, Ctrl+Shift+Z</td><td>⌘Y, ⌘⇧Z</td></tr><tr><td>Bold text</td><td>Ctrl+B</td><td>⌘B</td></tr><tr><td>Change text case</td><td>Shift+F3</td><td>⇧F3 (may require Fn)</td></tr><tr><td>Create link</td><td>Ctrl+K</td><td>⌘K</td></tr><tr><td>Move out of a link</td><td>←←, →→</td><td></td></tr><tr><td>Move out of an inline code style</td><td>←←, →→</td><td></td></tr><tr><td>Select all</td><td>Ctrl+A</td><td>⌘A</td></tr><tr><td>Find in the document</td><td>Ctrl+F</td><td>⌘F</td></tr><tr><td>Copy text formatting</td><td>Ctrl+Shift+C</td><td>⌘⇧C</td></tr><tr><td>Paste text formatting</td><td>Ctrl+Shift+V</td><td>⌘⇧V</td></tr><tr><td>Italic text</td><td>Ctrl+I</td><td>⌘I</td></tr><tr><td>Strikethrough text</td><td>Ctrl+Shift+X</td><td>⌘⇧X</td></tr><tr><td>Underline text</td><td>Ctrl+U</td><td>⌘U</td></tr><tr><td>Revert autoformatting action</td><td>Backspace</td><td></td></tr></tbody></table></figure><h3>Interacting with blocks</h3><p>Blocks are images, tables, blockquotes, annotations.</p><figure class=\"table\"><table><thead><tr><th>Action</th><th>PC</th><th>Mac</th></tr></thead><tbody><tr><td>Insert a new paragraph directly after a widget</td><td>Enter</td><td></td></tr><tr><td>Insert a new paragraph directly before a widget</td><td>Shift+Enter</td><td>⇧Enter</td></tr><tr><td>Move the caret to allow typing directly before a widget</td><td>↑, ←</td><td></td></tr><tr><td>Move the caret to allow typing directly after a widget</td><td>↓, →</td><td></td></tr><tr><td>After entering a nested editable, move the selection to the closest ancestor widget. For example: move from an image caption to the whole image widget.</td><td>Tab then Esc</td><td></td></tr></tbody></table></figure><p>Specifically for lists:</p><figure class=\"table\"><table><thead><tr><th>Action</th><th>PC</th><th>Mac</th></tr></thead><tbody><tr><td>Increase list item indent</td><td>⇥</td><td></td></tr><tr><td>Decrease list item indent</td><td>Shift+⇥</td><td>⇧⇥</td></tr></tbody></table></figure><p>In tables:</p><figure class=\"table\"><table><thead><tr><th>Action</th><th>PC</th><th>Mac</th></tr></thead><tbody><tr><td>Move the selection to the next cell</td><td>⇥</td><td></td></tr><tr><td>Move the selection to the previous cell</td><td>Shift+⇥</td><td>⇧⇥</td></tr><tr><td>Insert a new table row (when in the last cell of a table)</td><td>⇥</td><td></td></tr><tr><td>Navigate through the table</td><td>↑, →, ↓, ←</td><td></td></tr></tbody></table></figure><h3>General UI shortcuts</h3><figure class=\"table\"><table><thead><tr><th>Action</th><th>PC</th><th>Mac</th></tr></thead><tbody><tr><td>Close contextual balloons, dropdowns, and dialogs</td><td>Esc</td><td></td></tr><tr><td>Open the accessibility help dialog</td><td>Alt+0</td><td>⌥0</td></tr><tr><td>Move focus between form fields (inputs, buttons, etc.)</td><td>⇥, Shift+⇥</td><td>⇥, ⇧⇥</td></tr><tr><td>Move focus to the toolbar, navigate between toolbars</td><td>Alt+F10</td><td>⌥F10 (may require Fn)</td></tr><tr><td>Navigate through the toolbar or menu bar</td><td>↑, →, ↓, ←</td><td></td></tr><tr><td>Navigate to the next focusable field or an element outside the editor</td><td>Tab, Shift+Tab</td><td></td></tr><tr><td>Execute the currently focused button. Executing buttons that interact with the editor content moves the focus back to the content.</td><td>Enter, Space</td><td></td></tr><tr><td>Move focus in and out of an active dialog window</td><td>Ctrl+F6</td><td>⌘F6 (may require Fn)</td></tr></tbody></table></figure>",
diff --git a/docs/User Guide/User Guide/Note Types/Text/Include Note.md b/docs/User Guide/User Guide/Note Types/Text/Include Note.md
index de74fc7cb2..adae3a60be 100644
--- a/docs/User Guide/User Guide/Note Types/Text/Include Note.md
+++ b/docs/User Guide/User Guide/Note Types/Text/Include Note.md
@@ -120,11 +120,11 @@ An included text note, an included code note and an embedded code file such as a
* _Word wrap_ wraps long lines instead of scrolling them. _Auto_ follows the setting in <a class="reference-link" href="../../Basic%20Concepts%20and%20Features/UI%20Elements/Options.md">Options</a> → _Code Notes_. For an included note, it sets the `#wrapLines` label of the note, as the _Word wrap_ submenu of its <a class="reference-link" href="../../Basic%20Concepts%20and%20Features/UI%20Elements/Note%20menu.md">Note menu</a> does for a code note. For an embedded file or a Mermaid diagram, it changes only this include.
* _Line numbers_ shows or hides the numbers at the start of each line. _Auto_ shows them, as a code note does. It changes only this include, for an included note as well.
* The changes are saved as you type, to the included note or to the attachment, as they would be in its own tab.
-* The changes made in the code editor of an include are part of the undo history of the note that includes it, together with the changes to its text, in the order they were made. This includes the source of included Markdown and of a [Mermaid diagram](Insert%20buttons.md).
+* The changes made in the code editor of an include are part of the undo history of the note that includes it, together with the changes to its text, in the order they were made. This includes the source of included Markdown and of a [Mermaid diagram](Insert%20buttons.md), and the changes to a drawing canvas (see below).
* <kbd>Ctrl</kbd>+<kbd>Z</kbd> undoes the last change of the note, and <kbd>Ctrl</kbd>+<kbd>Y</kbd> or <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>Z</kbd> redoes it, whether the caret is in the text or in an include, and also while _Editable_ is off. The <span class="tn-icon cke cke-undo"></span> _Undo_ and <span class="tn-icon cke cke-redo"></span> _Redo_ buttons of the formatting toolbar do the same. With the Vim key bindings, `u` and <kbd>Ctrl</kbd>+<kbd>R</kbd> in an include do the same too.
- * The focus moves to the change that was undone or redone: into the code editor of the include, or back to the text.
+ * The focus moves to the change that was undone or redone: into the code editor or the drawing canvas of the include, or back to the text.
* Undoing a change of an included note saves the included note again. Once the included note has been changed elsewhere, for example in another tab, its earlier changes can no longer be undone from here, and undo skips them.
- * An included text note and a drawing canvas keep an undo history of their own.
+ * An included text note keeps an undo history of its own.
* An include of <a class="reference-link" href="Block%20references.md">Block references</a> edits only the referenced blocks.
* Editing is not available in a [read-only note](../../Basic%20Concepts%20and%20Features/Notes/Read-Only%20Notes.md), for an included note marked `#readOnly`, or for an attachment of another note.
* <a class="reference-link" href="../../Basic%20Concepts%20and%20Features/Navigation/Search%20in%20note.md">Search in note</a> finds the text of included text and code notes among the results of the note around them, and replaces it while _Editable_ is on.
@@ -153,6 +153,7 @@ A drawing canvas is an Excalidraw canvas, like the one of a <a class="reference-
* To draw on a canvas that does not have the focus, click it first. Until then, touch gestures scroll the note. The canvas then has the tools, menus and keyboard shortcuts of a Canvas note. The toolbars, the menus and the properties of the selected shapes show only while the canvas has the focus, so elsewhere the drawing reads like a picture in the text.
* The mouse wheel and the touchpad scroll the note over a canvas too, as over the text. To zoom, use the zoom buttons of the canvas toolbar; to move around the drawing, use the <span class="tn-icon bx bxs-hand"></span> _Hand_ tool. In fullscreen, the mouse wheel moves and zooms the drawing instead.
* The canvas toolbar replaces the Excalidraw menu: _Export image_, _Find on canvas_, _Library_ and _Help_ are at the end of its <span class="tn-icon bx bx-category"></span> _More tools_ menu. In fullscreen, the Excalidraw menu shows again.
+* The changes to the drawing are part of the undo history of the text note (see _Editing an include in place_ above). <kbd>Ctrl</kbd>+<kbd>Z</kbd>, <kbd>Ctrl</kbd>+<kbd>Y</kbd> and the <span class="tn-icon bx bx-undo"></span> _Undo_ and <span class="tn-icon bx bx-redo"></span> _Redo_ buttons of the canvas toolbar undo and redo the last change of the note, in the drawing or in the text.
* A new drawing has the background color of the note. A background chosen from the Excalidraw menu replaces it.
* To protect a finished drawing from accidental changes, select it and turn off the <span class="tn-icon bx bx-edit-alt"></span> _Editable_ button at the start of its toolbar, or uncheck _Editable_ in its <span class="tn-icon cke cke-three-vertical-dots"></span> _More actions_ menu. The drawing then shows as a still picture, at the zoom and position it had, and can no longer be changed, zoomed or moved. To draw again, turn _Editable_ back on.
* The box sizes, resizing, the caption and the title work as for an included note, but the toolbar of a drawing leaves the box size, _Show title_ and _Convert to link_ to its _More actions_ menu.