Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
client/text editor/canvas: make Excalidraw to follow the editable flag
Adorian Dorandb106b4ac4a2
diff --git a/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.spec.tsx b/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.spec.tsxindex d2838914b7..cb38602062 100644--- a/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.spec.tsx+++ b/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.spec.tsx@@ -1,16 +1,30 @@-import { render } from "preact";+import { type ComponentChildren, render, toChildArray, type VNode } from "preact";import { useEffect, useRef, useState } from "preact/hooks";import { act } from "preact/test-utils";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type { AttachmentEditor } from "../../../services/content_renderer";+vi.mock("@excalidraw/excalidraw", () => ({ exportToSvg: vi.fn() }));vi.mock("./Canvas", () => ({ CanvasEditor: MockCanvasEditor }));-vi.mock("./persistence", () => ({ useCanvasDrawingPersistence: () => ({}) }));+vi.mock("./persistence", () => ({+ useCanvasDrawingPersistence: (...args: unknown[]) => {+ persistenceArgs(...args);+ return {};+ }+}));const canvasEditorProps = vi.fn();+const persistenceArgs = vi.fn();++interface MockCanvasEditorProps {+ isDesktopLayout?: boolean;+ isReadOnly?: boolean;+ children?: ComponentChildren;+}/** Renders Excalidraw's focusable container after a render, as once its language loads. */-function MockCanvasEditor(props: { isDesktopLayout?: boolean }) {+function MockCanvasEditor(props: MockCanvasEditorProps) {canvasEditorProps(props);const [ isLoaded, setIsLoaded ] = useState(false);useEffect(() => setIsLoaded(true), []);@@ -31,6 +45,8 @@ globalThis.ResizeObserver = class {const {default: CanvasDrawing, useIsToolbarOverPanel, useSidePanels} = await import("./CanvasDrawing");+const { default: CanvasDrawingMenu } = await import("./CanvasDrawingMenu");+const { default: CanvasEmbedTools } = await import("./CanvasEmbedTools");/** Horizontal edges by class name; happy-dom computes no layout. */const edges: Record<string, { left: number; right: number }> = {@@ -288,6 +304,7 @@ describe("useSidePanels", () => {});describe("CanvasDrawing", () => {+ const ATTACHMENT = { attachmentId: "a1" } as never;let box: HTMLElement;beforeEach(() => {@@ -302,13 +319,73 @@ describe("CanvasDrawing", () => {box.remove();});- async function mount() {+ async function mount(editor?: AttachmentEditor) {await act(async () => {- render(<CanvasDrawing attachment={{ attachmentId: "a1" } as never} />, box);+ render(<CanvasDrawing attachment={ATTACHMENT} editor={editor} />, box);});return box.querySelector(".excalidraw");}+ /** Whether the last `CanvasEditor` is read-only, and what its menu and its tools can edit. */+ function getEditingState() {+ const props = canvasEditorProps.mock.lastCall?.[0] as MockCanvasEditorProps | undefined;+ const children = toChildArray(props?.children) as VNode<{ isEditable?: boolean }>[];+ const getIsEditable = (type: unknown) =>+ children.find((child) => child.type === type)?.props.isEditable;+ return {+ isReadOnly: props?.isReadOnly,+ menu: getIsEditable(CanvasDrawingMenu),+ tools: getIsEditable(CanvasEmbedTools)+ };+ }++ /** Sets or removes `data-editable`, as the Editable toggle of the embed does. */+ async function setEmbedEditable(embed: HTMLElement, isEditable: boolean) {+ await act(async () => {+ if (isEditable) {+ embed.setAttribute("data-editable", "true");+ } else {+ embed.removeAttribute("data-editable");+ }+ await Promise.resolve();+ });+ }++ it("follows the Editable toggle of its embed, saving all along", async () => {+ const editor = { canEdit: () => true, release: vi.fn() } as unknown as AttachmentEditor;+ const embed = document.createElement("figure");+ embed.className = "include-note";+ embed.setAttribute("data-editable", "true");+ embed.append(box);+ document.body.append(embed);++ await mount(editor);+ expect(getEditingState()).toEqual({ isReadOnly: false, menu: true, tools: true });++ await setEmbedEditable(embed, false);+ expect(getEditingState()).toEqual({ isReadOnly: true, menu: false, tools: false });+ expect(persistenceArgs).toHaveBeenLastCalledWith(+ ATTACHMENT, editor, expect.anything(), expect.anything()+ );++ await setEmbedEditable(embed, true);+ expect(getEditingState()).toEqual({ isReadOnly: false, menu: true, tools: true });++ // An attachment that the note cannot save is read-only, with no toggle to offer.+ render(null, box);+ await mount({ canEdit: () => false } as unknown as AttachmentEditor);+ expect(getEditingState()).toEqual({ isReadOnly: true, menu: false, tools: undefined });+ expect(persistenceArgs).toHaveBeenLastCalledWith(+ ATTACHMENT, undefined, expect.anything(), expect.anything()+ );+ embed.remove();+ });++ it("is editable outside an embed, which has no Editable toggle", async () => {+ await mount({ canEdit: () => true, release: vi.fn() } as unknown as AttachmentEditor);+ expect(getEditingState()).toEqual({ isReadOnly: false, menu: true, tools: true });+ });+it("takes the focus that its embed box holds once Excalidraw renders", async () => {box.focus();const excalidraw = await mount();diff --git a/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.tsx b/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.tsxindex ecce6d9ea5..4e40f494c0 100644--- a/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.tsx+++ b/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.tsx@@ -12,6 +12,7 @@ import type { AttachmentEditor } from "../../../services/content_renderer";import options from "../../../services/options";import { isDesktop } from "../../../services/utils";import { useColorScheme } from "../../react/hooks";+import { useIsContentEmbedEditable } from "../text/content_embed_tools";import { CanvasEditor } from "./Canvas";import CanvasDrawingMenu from "./CanvasDrawingMenu";import CanvasEmbedTools from "./CanvasEmbedTools";@@ -23,15 +24,21 @@ interface CanvasDrawingProps {editor?: AttachmentEditor;}-/** A canvas drawing saved in an attachment, edited in place inside the note that shows it. */+/**+ * A canvas drawing saved in an attachment, edited in place inside the note that shows it while+ * the Editable toggle of its embed is on.+ */export default function CanvasDrawing({ attachment, editor }: CanvasDrawingProps) {const rootRef = useRef<HTMLDivElement>(null);const apiRef = useRef<ExcalidrawImperativeAPI>(null);const colorScheme = useColorScheme();- const isEditable = !!editor?.canEdit(attachment) && !options.is("databaseReadonly");+ const canEdit = !!editor?.canEdit(attachment) && !options.is("databaseReadonly");+ const isEmbedEditable = useIsContentEmbedEditable(rootRef);+ const isEditable = canEdit && isEmbedEditable;+ // Follows `canEdit` rather than the toggle, so that turning editing off keeps a pending save.const persistence = useCanvasDrawingPersistence(attachment,- isEditable ? editor : undefined,+ canEdit ? editor : undefined,apiRef,colorScheme);@@ -53,7 +60,9 @@ export default function CanvasDrawing({ attachment, editor }: CanvasDrawingPropsisDesktopLayout={isDesktop()}><CanvasDrawingMenu apiRef={apiRef} isEditable={isEditable} />- {isEditable && <CanvasEmbedTools rootRef={rootRef} apiRef={apiRef} />}+ {canEdit && (+ <CanvasEmbedTools rootRef={rootRef} apiRef={apiRef} isEditable={isEditable} />+ )}</CanvasEditor></div>);diff --git a/apps/client/src/widgets/type_widgets/canvas/CanvasEmbedTools.spec.tsx b/apps/client/src/widgets/type_widgets/canvas/CanvasEmbedTools.spec.tsxindex 1233de1255..e114856ee5 100644--- a/apps/client/src/widgets/type_widgets/canvas/CanvasEmbedTools.spec.tsx+++ b/apps/client/src/widgets/type_widgets/canvas/CanvasEmbedTools.spec.tsx@@ -39,7 +39,7 @@ describe("CanvasEmbedTools", () => {});/** A drawing with Excalidraw's container and its undo and redo buttons. */- function Drawing() {+ function Drawing({ isEditable }: { isEditable: boolean }) {const rootRef = useRef<HTMLDivElement>(null);const apiRef = useRef<ExcalidrawImperativeAPI>(api.api);return (@@ -48,14 +48,14 @@ describe("CanvasEmbedTools", () => {<div className="excalidraw-container" tabIndex={0} /><button type="button" data-testid="button-undo" onClick={() => undo()} /><button type="button" data-testid="button-redo" disabled />- <CanvasEmbedTools rootRef={rootRef} apiRef={apiRef} />+ <CanvasEmbedTools rootRef={rootRef} apiRef={apiRef} isEditable={isEditable} /></div></figure>);}- async function mount() {- await act(async () => render(<Drawing />, container));+ async function mount(isEditable = true) {+ await act(async () => render(<Drawing isEditable={isEditable} />, container));const embed = container.querySelector<HTMLElement>("figure.include-note");const provider = embed && getContentEmbedTools(embed);if (!embed || !provider) {@@ -73,6 +73,7 @@ describe("CanvasEmbedTools", () => {expect(provider.hiddenToolbarItems).toEqual(["contentEmbedBoxSizeDropdown", "toggleContentEmbedTitle", "convertEmbedToLink"]);+ expect(provider.hasEditableFlag).toBe(true);const tools = provider.getTools();const count = MAIN_TOOL_IDS.length;expect(tools[0]).toEqual({@@ -229,6 +230,33 @@ describe("CanvasEmbedTools", () => {expect(api.setActiveTool).toHaveBeenCalledTimes(2);expect(api.updateScene).toHaveBeenCalledTimes(3);});++ it("offers and runs only the zoom while the drawing is read-only", async () => {+ const { provider } = await mount(false);+ const listener = vi.fn();+ provider.subscribe(listener);+ const getIds = () => provider.getTools().map((tool) => tool.id);+ expect(getIds()).toEqual([ "zoomOut", "resetZoom", "zoomIn" ]);+ expect(provider.hasEditableFlag).toBe(true);++ for (const id of [ "rectangle", "frame", "lock", "undo" ]) {+ provider.execute(id);+ }+ expect(api.setActiveTool).not.toHaveBeenCalled();+ expect(api.updateScene).not.toHaveBeenCalled();+ expect(undo).not.toHaveBeenCalled();++ provider.execute("zoomIn");+ expect(api.updateScene).toHaveBeenCalledExactlyOnceWith({+ appState: expect.objectContaining({ zoom: { value: 1.1 } })+ });++ await mount(true);+ expect(listener).toHaveBeenCalledTimes(1);+ expect(getIds()).toEqual([+ "lock", ...MAIN_TOOL_IDS, "moreTools", "undo", "redo", "zoomOut", "resetZoom", "zoomIn"+ ]);+ });});/** The part of Excalidraw's app state that the tools read. */diff --git a/apps/client/src/widgets/type_widgets/canvas/CanvasEmbedTools.tsx b/apps/client/src/widgets/type_widgets/canvas/CanvasEmbedTools.tsxindex f5f53d9eb7..5cf0b93f06 100644--- a/apps/client/src/widgets/type_widgets/canvas/CanvasEmbedTools.tsx+++ b/apps/client/src/widgets/type_widgets/canvas/CanvasEmbedTools.tsx@@ -87,17 +87,20 @@ interface CanvasEmbedToolsProps {/** The element of the drawing, inside the embed whose toolbar shows the tools. */rootRef: RefObject<HTMLElement>;apiRef: RefObject<ExcalidrawImperativeAPI>;+ /** Whether the Editable toggle of the embed is on. A read-only drawing offers the zoom only. */+ isEditable: boolean;}/*** Adds Excalidraw's tools, undo and redo, and zoom to the toolbar of the embed that shows the* drawing. Renders inside `<Excalidraw>`, for its translations.*/-export default function CanvasEmbedTools({ rootRef, apiRef }: CanvasEmbedToolsProps) {+export default function CanvasEmbedTools({ rootRef, apiRef, isEditable }: CanvasEmbedToolsProps) {const { t, langCode } = useExcalidrawTranslation();const [ tools ] = useState(() => new CanvasTools(rootRef));useEffect(() => tools.setTranslate(t), [ tools, t, langCode ]);+ useEffect(() => tools.setEditable(isEditable), [ tools, isEditable ]);useEffect(() => {const root = rootRef.current;@@ -129,8 +132,11 @@ export class CanvasTools implements ContentEmbedToolProvider {readonly hiddenToolbarItems: readonly ContentEmbedToolbarItem[] = ["contentEmbedBoxSizeDropdown", "toggleContentEmbedTitle", "convertEmbedToLink"];+ readonly hasEditableFlag = true;private api: ExcalidrawImperativeAPI | null = null;private translate: Translate | null = null;+ /** Whether the drawing can be edited, which adds the drawing tools and the history. */+ private isEditable = true;private listeners = new Set<() => void>();/** The tools as last notified, to notify the listeners only when they change. */private shownTools = "";@@ -167,14 +173,65 @@ export class CanvasTools implements ContentEmbedToolProvider {this.update();}+ setEditable(isEditable: boolean) {+ this.isEditable = isEditable;+ this.update();+ }+getTools(): ContentEmbedTool[] {const appState = this.api?.getAppState();if (!appState) {return [];}- const { activeTool, zoom } = appState;- const zoomPercent = Math.round(zoom.value * 100);+ const zoomTools = this.getZoomTools(appState.zoom.value);+ return this.isEditable+ ? [ ...this.getEditingTools(appState.activeTool), ...zoomTools ]+ : zoomTools;+ }++ execute(id: string) {+ const api = this.api;+ if (!api) return;++ // The embed covers the drawing with a backdrop until the drawing has the focus.+ const container = this.rootRef.current?.querySelector<HTMLElement>(".excalidraw-container");+ if (container && !container.contains(document.activeElement)) {+ container.focus({ preventScroll: true });+ }++ const appState = api.getAppState();+ const getZoom = ZOOMS[id];+ if (getZoom) {+ api.updateScene({ appState: getZoomState(appState, getZoom(appState.zoom.value)) });+ } else if (this.isEditable) {+ this.runEditingTool(api, appState, id);+ }+ }++ subscribe(callback: () => void) {+ this.listeners.add(callback);+ return () => {+ this.listeners.delete(callback);+ };+ }++ private update() {+ const shownTools = JSON.stringify(this.getTools());+ if (shownTools !== this.shownTools) {+ this.shownTools = shownTools;+ for (const listener of this.listeners) {+ listener();+ }+ }+ }++ private t(key: string) {+ return this.translate?.(key) ?? key;+ }++ /** The lock, the drawing tools, undo and redo. */+ private getEditingTools(activeTool: AppState["activeTool"]): ContentEmbedTool[] {return [{id: LOCK,@@ -204,18 +261,24 @@ export class CanvasTools implements ContentEmbedToolProvider {}))},this.getHistoryTool("undo", undoIcon),- this.getHistoryTool("redo", redoIcon),+ this.getHistoryTool("redo", redoIcon)+ ];+ }++ /** Zoom out, the zoom level that resets it, and zoom in. */+ private getZoomTools(zoom: number): ContentEmbedTool[] {+ return [{id: "zoomOut",label: this.t("buttons.zoomOut"),icon: zoomOutIcon,- isEnabled: zoom.value > MIN_ZOOM,+ isEnabled: zoom > MIN_ZOOM,group: "zoom"},{id: "resetZoom",label: this.t("buttons.resetZoom"),- text: `${zoomPercent}%`,+ text: `${Math.round(zoom * 100)}%`,class: "canvas-drawing-zoom-level",group: "zoom"},@@ -223,28 +286,16 @@ export class CanvasTools implements ContentEmbedToolProvider {id: "zoomIn",label: this.t("buttons.zoomIn"),icon: zoomInIcon,- isEnabled: zoom.value < MAX_ZOOM,+ isEnabled: zoom < MAX_ZOOM,group: "zoom"}];}- execute(id: string) {- const api = this.api;- if (!api) return;-- // The embed covers the drawing with a backdrop until the drawing has the focus.- const container = this.rootRef.current?.querySelector<HTMLElement>(".excalidraw-container");- if (container && !container.contains(document.activeElement)) {- container.focus({ preventScroll: true });- }-- const appState = api.getAppState();- const getZoom = ZOOMS[id];+ /** Runs the lock, a drawing tool, undo or redo. */+ private runEditingTool(api: ExcalidrawImperativeAPI, appState: AppState, id: string) {if (id === "undo" || id === "redo") {this.getHistoryButton(id)?.click();- } else if (getZoom) {- api.updateScene({ appState: getZoomState(appState, getZoom(appState.zoom.value)) });} else if (id === LOCK) {const locked = !appState.activeTool.locked;api.updateScene({ appState: { activeTool: { ...appState.activeTool, locked } } });@@ -253,27 +304,6 @@ export class CanvasTools implements ContentEmbedToolProvider {}}- subscribe(callback: () => void) {- this.listeners.add(callback);- return () => {- this.listeners.delete(callback);- };- }-- private update() {- const shownTools = JSON.stringify(this.getTools());- if (shownTools !== this.shownTools) {- this.shownTools = shownTools;- for (const listener of this.listeners) {- listener();- }- }- }-- private t(key: string) {- return this.translate?.(key) ?? key;- }-/** Undo or redo, enabled while Excalidraw's own button is: Excalidraw keeps the history. */private getHistoryTool(id: HistoryAction, icon: string): ContentEmbedTool {const button = this.getHistoryButton(id);diff --git a/apps/client/src/widgets/type_widgets/text/content_embed_tools.ts b/apps/client/src/widgets/type_widgets/text/content_embed_tools.tsindex ac4b36e82e..bd05005df4 100644--- a/apps/client/src/widgets/type_widgets/text/content_embed_tools.ts+++ b/apps/client/src/widgets/type_widgets/text/content_embed_tools.ts@@ -1,3 +1,6 @@+import type { RefObject } from "preact";+import { useEffect, useState } from "preact/hooks";+/** A button that the content of an embed adds to the toolbar of the embed. */export interface ContentEmbedTool {id: string;@@ -81,3 +84,28 @@ export function getContentEmbedTools(embed: HTMLElement) {}return null;}++/**+ * Whether the Editable toggle of the embed that contains `ref` is on, for content whose provider+ * sets `hasEditableFlag`. Content outside an embed has no toggle, and is editable. `false` until+ * the content is in the page.+ */+export function useIsContentEmbedEditable(ref: RefObject<HTMLElement>) {+ const [ isEditable, setIsEditable ] = useState(false);++ useEffect(() => {+ const embed = ref.current?.closest<HTMLElement>(".include-note");+ if (!embed) {+ setIsEditable(true);+ return;+ }++ const update = () => setIsEditable(embed.dataset.editable === "true");+ const observer = new MutationObserver(update);+ observer.observe(embed, { attributes: true, attributeFilter: [ "data-editable" ] });+ update();+ return () => observer.disconnect();+ }, [ ref ]);++ return isEditable;+}diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Include Note.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Include Note.htmlindex 7be47480f7..1a95844fb3 100644--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Include Note.html+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Include Note.html@@ -100,8 +100,9 @@<p>In a note being edited, the menu also has the commands of the include'stoolbar: 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.- For an embedded attachment they follow its first group of actions; for- an included note they end the menu.</p>+ A drawing canvas also has <em>Editable</em>, above <em>Size</em>. 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> buttonat the end of its title. To return, press <span class="tn-icon bx bx-exit"></span> <em>Exit fullscreen</em> in@@ -168,8 +169,8 @@<li>To insert a drawing canvas, press the <span class="tn-icon bx bx-pen"></span> <em>Insert drawing canvas</em> buttonin the <a class="reference-link" href="#root/_help_nRhnJkTT8cPs">Formatting toolbar</a>,next to the <span class="tn-icon cke cke-paper-clip"></span> <em>Attach file</em> button.- The canvas is added empty, in a <em>Medium</em> box with its title hidden,- and takes the focus, ready for drawing.</li>+ 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 on a canvas that does not have the focus, click it first. Untilthen, the mouse wheel and touch gestures scroll the note. The canvas thenhas the tools, menus and keyboard shortcuts of a Canvas note. The toolbars,@@ -178,10 +179,14 @@the text.</li><li>A new drawing has the background color of the note. A background chosenfrom 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 can then be panned and zoomed but not changed, and its toolbar+ holds only the zoom buttons. 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. While the drawing can be changed, its toolbar holds the drawing tools- and leaves the box size, <em>Show title</em> and <em>Convert to link</em> to- its <span class="tn-icon cke cke-three-vertical-dots"></span> <em>More actions</em> menu.</li>+ 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 howeversmall the box is. In the mobile layout, a narrow or short box switchesit to a compact interface. For more room, choose <em>Full</em>, or showdiff --git a/docs/User Guide/User Guide/Note Types/Text/Include Note.md b/docs/User Guide/User Guide/Note Types/Text/Include Note.mdindex ae13ed81c8..d5c1a426b1 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@@ -64,7 +64,7 @@ To open an included note in a new tab, press the <span class="tn-icon bx bx-linkThe <span class="tn-icon bx bx-dots-vertical-rounded"></span> _More actions_ 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.-In a note being edited, the menu also has the commands of the include's toolbar: the _Size_ submenu, _Show title_ and _Show caption_, each checked while it is in effect, and _Convert to link_ at the end. For an embedded attachment they follow its first group of actions; for an included note they end the menu.+In a note being edited, the menu also has the commands of the include's toolbar: the _Size_ submenu, _Show title_ and _Show caption_, each checked while it is in effect, and _Convert to link_ at the end. A drawing canvas also has _Editable_, above _Size_. For an embedded attachment they follow its first group of actions; for an included note they end the menu.To show an include of size _Medium_ or _Full_ on the whole screen, press the <span class="tn-icon bx bx-fullscreen"></span> _Fullscreen_ button at the end of its title. To return, press <span class="tn-icon bx bx-exit"></span> _Exit fullscreen_ in the top-right corner, or <kbd>Esc</kbd>.@@ -106,10 +106,11 @@ In a _Small_ or _Medium_ box, the image is scaled down to fit the height of theA drawing canvas is an Excalidraw canvas, like the one of a <a class="reference-link" href="../Canvas.md">Canvas</a> note, drawn directly in the text note. It is not a note of its own: the drawing is kept in a `Canvas.excalidraw` [attachment](../../Basic%20Concepts%20and%20Features/Notes/Attachments.md) of the text note and is saved together with the text.-* To insert a drawing canvas, press the <span class="tn-icon bx bx-pen"></span> _Insert drawing canvas_ button in the <a class="reference-link" href="Formatting%20toolbar.md">Formatting toolbar</a>, next to the <span class="tn-icon cke cke-paper-clip"></span> _Attach file_ button. The canvas is added empty, in a _Medium_ box with its title hidden, and takes the focus, ready for drawing.+* To insert a drawing canvas, press the <span class="tn-icon bx bx-pen"></span> _Insert drawing canvas_ button in the <a class="reference-link" href="Formatting%20toolbar.md">Formatting toolbar</a>, next to the <span class="tn-icon cke cke-paper-clip"></span> _Attach file_ button. The canvas is added empty and editable, in a _Medium_ box with its title hidden, and takes the focus, ready for drawing.* To draw on a canvas that does not have the focus, click it first. Until then, the mouse wheel and 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.* A new drawing has the background color of the note. A background chosen from the Excalidraw menu replaces it.-* The box sizes, resizing, the caption and the title work as for an included note. While the drawing can be changed, its toolbar holds the drawing tools and leaves the box size, _Show title_ and _Convert to link_ to its <span class="tn-icon cke cke-three-vertical-dots"></span> _More actions_ menu.+* 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 can then be panned and zoomed but not changed, and its toolbar holds only the zoom buttons. 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.* 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 _Full_, or show the title and press <span class="tn-icon bx bx-fullscreen"></span> _Fullscreen_.* Pictures added to the drawing are stored in the same attachment.* In a [read-only note](../../Basic%20Concepts%20and%20Features/Notes/Read-Only%20Notes.md), the drawing can be viewed but not changed.diff --git a/packages/ckeditor5/src/plugins/file_upload/file_upload_ui.spec.ts b/packages/ckeditor5/src/plugins/file_upload/file_upload_ui.spec.tsindex a979697981..663cadf009 100644--- a/packages/ckeditor5/src/plugins/file_upload/file_upload_ui.spec.ts+++ b/packages/ckeditor5/src/plugins/file_upload/file_upload_ui.spec.ts@@ -150,7 +150,7 @@ describe("FileUploadUI", () => {return button;}- it("embeds an empty canvas drawing, medium, untitled and focused, quietly", async () => {+ it("embeds an editable empty drawing, medium, untitled and focused, quietly", async () => {const button = createCanvasButton();const execute = vi.spyOn(editor, "execute").mockImplementation(() => undefined);const focus = vi.spyOn(editor.editing.view, "focus");@@ -165,6 +165,7 @@ describe("FileUploadUI", () => {asEmbed: true,boxSize: "medium",hideTitle: true,+ editable: true,quiet: true,focusEmbed: true});diff --git a/packages/ckeditor5/src/plugins/file_upload/file_upload_ui.ts b/packages/ckeditor5/src/plugins/file_upload/file_upload_ui.tsindex 8d2eb7a7fd..557f7e7a6b 100644--- a/packages/ckeditor5/src/plugins/file_upload/file_upload_ui.ts+++ b/packages/ckeditor5/src/plugins/file_upload/file_upload_ui.ts@@ -26,7 +26,8 @@ import type { FileUploadOptions } from "./fileuploadcommand.js";* Registers the `fileUpload` split button. The button attaches the picked files and links them;* the list also offers to embed them.*- * Also registers the `drawingCanvas` button, which attaches an empty canvas drawing and embeds it.+ * Also registers the `drawingCanvas` button, which attaches an empty canvas drawing and embeds it,+ * editable.*/export default class FileUploadUI extends Plugin {static get pluginName() {@@ -104,6 +105,7 @@ export default class FileUploadUI extends Plugin {asEmbed: true,boxSize: "medium",hideTitle: true,+ editable: true,quiet: true,focusEmbed: true});diff --git a/packages/ckeditor5/src/plugins/file_upload/fileuploadcommand.spec.ts b/packages/ckeditor5/src/plugins/file_upload/fileuploadcommand.spec.tsindex 7f686c053e..d639c7168a 100644--- a/packages/ckeditor5/src/plugins/file_upload/fileuploadcommand.spec.ts+++ b/packages/ckeditor5/src/plugins/file_upload/fileuploadcommand.spec.ts@@ -182,9 +182,10 @@ describe("FileUploadCommand", () => {});expect(getModelData(editor.model)).toMatch(/^<contentEmbed boxSize="medium" /);+ expect(getModelData(editor.model)).not.toMatch(/editable|hideTitle/);});- it("gives the embeds the box size and hidden title the caller asks for", () => {+ it("gives the embeds the box size, hidden title and editing the caller asks for", () => {const getEmbedBoxSize = vi.fn(() => "tiny");installGlobMock({ getComponentByEl: () => ({ getEmbedBoxSize }) });setModelData(editor.model, "<paragraph>[]</paragraph>");@@ -195,11 +196,12 @@ describe("FileUploadCommand", () => {],asEmbed: true,boxSize: "medium",- hideTitle: true+ hideTitle: true,+ editable: true});expect(getModelData(editor.model)).toMatch(new RegExp(- "^<contentEmbed boxSize=\"medium\" hideTitle=\"true\" " ++ "^<contentEmbed boxSize=\"medium\" editable=\"true\" hideTitle=\"true\" " +"uploadFileName=\"Canvas.excalidraw\""));expect(getEmbedBoxSize).not.toHaveBeenCalled();diff --git a/packages/ckeditor5/src/plugins/file_upload/fileuploadcommand.ts b/packages/ckeditor5/src/plugins/file_upload/fileuploadcommand.tsindex c79359bc3c..f1828d8233 100644--- a/packages/ckeditor5/src/plugins/file_upload/fileuploadcommand.ts+++ b/packages/ckeditor5/src/plugins/file_upload/fileuploadcommand.ts@@ -18,6 +18,8 @@ export interface FileUploadOptions {boxSize?: BoxSizeValue;/** Hides the title row of the embeds. */hideTitle?: boolean;+ /** Turns on the Editable toggle of the embeds, for content that has an editable mode. */+ editable?: boolean;/** Skips the `upload` event, for a file that the editor created itself. */quiet?: boolean;/** Gives the focus to what the embeds show, once the upload ends. */@@ -51,7 +53,7 @@ export default class FileUploadCommand extends Command {}override execute(options: FileUploadOptions) {- const { file: files, asEmbed, boxSize, hideTitle, quiet, focusEmbed } = options;+ const { file: files, asEmbed, boxSize, hideTitle, editable, quiet, focusEmbed } = options;const model = this.editor.model;const fileRepository = this.editor.plugins.get(FileRepository);@@ -74,7 +76,8 @@ export default class FileUploadCommand extends Command {if (asEmbed) {insertEmbedPlaceholder(writer, model, loader.id, file.name, {boxSize: boxSize ?? getEmbedBoxSize(this.editor, file),- hideTitle+ hideTitle,+ editable});} else {insertPlaceholder(writer, model, loader.id, file.name);@@ -104,11 +107,12 @@ function insertEmbedPlaceholder(model: Model,uploadId: string,fileName: string,- { boxSize, hideTitle }: { boxSize: string; hideTitle?: boolean }+ { boxSize, hideTitle, editable }: { boxSize: string; hideTitle?: boolean; editable?: boolean }) {const placeholder = writer.createElement("contentEmbed", {boxSize,...(hideTitle ? { hideTitle: true } : {}),+ ...(editable ? { editable: true } : {}),uploadId,uploadFileName: fileName});