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/drawing canvas: use a static image rendition while in read-only mode
Adorian Doran31010ac21216
diff --git a/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.css b/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.cssindex 8d919e39f1..deb14d716e 100644--- a/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.css+++ b/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.css@@ -19,6 +19,7 @@/* Resets the typography inherited from the text note. */> .canvas-drawing-editor {+ position: relative;height: 100%;font-size: var(--canvas-drawing-font-size);line-height: var(--bs-body-line-height);@@ -26,6 +27,7 @@overflow-wrap: normal;> .canvas-render {+ position: relative;height: 100%;transition: opacity 150ms ease-out;}@@ -152,7 +154,7 @@/* Excalidraw hides its overflow, so its rounded container clips what it draws. */.include-note-content:not(:fullscreen) .canvas-drawing {- &, .excalidraw-container {+ &, .excalidraw-container, .canvas-drawing-view {border-radius: var(--_canvas-drawing-top-radius) var(--_canvas-drawing-top-radius)var(--_canvas-drawing-bottom-radius) var(--_canvas-drawing-bottom-radius);}@@ -167,6 +169,29 @@}}+/* The picture of the drawing that `DrawingPicture` places, under Excalidraw while both show. */+.canvas-drawing-view {+ position: absolute;+ inset: 0;+ overflow: hidden;++ &::before {+ position: absolute;+ inset: 0;+ background-color: var(--canvas-drawing-view-background, transparent);+ content: "";+ }++ /* Excalidraw's `THEME_FILTER`, which its dark theme gives the whole canvas. */+ &.theme-dark::before {+ filter: invert(93%) hue-rotate(180deg);+ }++ > svg {+ position: absolute;+ }+}+.canvas-drawing-picture {max-width: 100%;height: auto;diff --git a/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.spec.tsx b/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.spec.tsxindex 20a1ece583..3e88325527 100644--- a/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.spec.tsx+++ b/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.spec.tsx@@ -5,11 +5,34 @@ import { useEffect, useRef, useState } from "preact/hooks";import { act } from "preact/test-utils";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import Component from "../../../components/component";import type { ContentEditor } from "../../../services/content_renderer";+import LoadResults from "../../../services/load_results";import { buildNote } from "../../../test/easy-froca";+import { ParentComponent } from "../../react/react_utils";import { getContentEmbedTools } from "../text/content_embed_tools";-vi.mock("@excalidraw/excalidraw", () => ({ exportToSvg: vi.fn() }));+interface Box {+ x: number;+ y: number;+ width: number;+ height: number;+}++vi.mock("@excalidraw/excalidraw", () => ({+ exportToSvg: vi.fn(),+ getCommonBounds: (elements: Box[]) => [+ Math.min(...elements.map(({ x }) => x)),+ Math.min(...elements.map(({ y }) => y)),+ Math.max(...elements.map(({ x, width }) => x + width)),+ Math.max(...elements.map(({ y, height }) => y + height))+ ]+}));+// happy-dom lays nothing out: every picture of a drawing has a box of 400 × 200.+vi.mock("../../react/hooks", async (importOriginal) => ({+ ...await importOriginal<typeof import("../../react/hooks")>(),+ useElementSize: () => ({ width: 400, height: 200 })+}));vi.mock("./Canvas", () => ({ CanvasEditor: MockCanvasEditor }));vi.mock("./persistence", () => ({useCanvasDrawingPersistence: (...args: unknown[]) => {@@ -39,9 +62,16 @@ interface MockCanvasEditorProps {apiRef?: RefObject<unknown>;isDesktopLayout?: boolean;isReadOnly?: boolean;+ persistence?: { onChange?: (...args: unknown[]) => void };children?: ComponentChildren;}+/** The options that `LiveDrawing` gives its persistence. */+interface PersistenceOptions {+ initialView?: unknown;+ onSceneShown?: () => void;+}+/** Renders Excalidraw's focusable container after a render, as once its language loads. */function MockCanvasEditor(props: MockCanvasEditorProps) {canvasEditorProps(props);@@ -549,10 +579,27 @@ describe("useNoteScrollingWheel", () => {});describe("CanvasDrawing", () => {- const ATTACHMENT = { attachmentId: "a1" } as never;+ const SCENE = JSON.stringify({ elements: [ { x: 50, y: 30, width: 200, height: 100 } ] });+ const ATTACHMENT = {+ attachmentId: "a1",+ getBlob: async () => ({ content: sceneContent })+ } as never;+ const EDITOR = {+ canEdit: () => true,+ release: vi.fn(),+ getUnsavedContent: () => undefined+ } as unknown as ContentEditor;let box: HTMLElement;+ let sceneContent: string;beforeEach(() => {+ sceneContent = SCENE;+ vi.mocked(exportToSvg).mockReset().mockImplementation(async () => {+ const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");+ svg.setAttribute("width", "200");+ svg.setAttribute("height", "100");+ return svg;+ });box = document.createElement("div");box.className = "include-note-content";box.tabIndex = -1;@@ -564,9 +611,10 @@ describe("CanvasDrawing", () => {box.remove();});- async function mount(editor?: ContentEditor) {+ /** Mounts the drawing, which `editor` saves, or none for `null`. */+ async function mount(editor: ContentEditor | null = EDITOR) {await act(async () => {- render(<CanvasDrawing attachment={ATTACHMENT} editor={editor} />, box);+ render(<CanvasDrawing attachment={ATTACHMENT} editor={editor ?? undefined} />, box);});return box.querySelector(".excalidraw");}@@ -596,38 +644,157 @@ describe("CanvasDrawing", () => {});}- it("follows the Editable toggle of its embed, saving all along", async () => {- const editor = { canEdit: () => true, release: vi.fn() } as unknown as ContentEditor;+ it("edits in Excalidraw while its embed is editable, else shows a picture", async () => {const embed = document.createElement("figure");embed.className = "include-note";embed.setAttribute("data-editable", "true");embed.append(box);document.body.append(embed);+ const getPicture = () => box.querySelector(".canvas-drawing-view");+ const getExcalidraw = () => box.querySelector(".excalidraw");+ sceneContent = JSON.stringify({+ elements: [ { x: 50, y: 30, width: 200, height: 100 } ],+ appState: { zoom: { value: 1 }, scrollX: 0, scrollY: 0 }+ });- await mount(editor);+ await mount();expect(getEditingState()).toEqual({ isReadOnly: false, menu: true, tools: true });- // `CanvasEmbedTools`, not rendered by the mock editor, adds the only buttons.- expect(getContentEmbedTools(embed)).toBeNull();-+ expect(getPicture()).toBeNull();+ await new Promise(requestAnimationFrame);+ expect(exportToSvg).not.toHaveBeenCalled();+ expect(getContentEmbedTools(embed)?.hasEditableFlag).toBe(true);++ // Excalidraw stays, read-only, until the picture of the drawing shows at the same view.+ const options = persistenceArgs.mock.lastCall?.[4] as PersistenceOptions;+ // Excalidraw counts as drawn on the frame after it shows the scene.+ await act(async () => {+ options.onSceneShown?.();+ await new Promise(requestAnimationFrame);+ });+ const { onChange } = (canvasEditorProps.mock.lastCall?.[0] as MockCanvasEditorProps)+ .persistence ?? {};+ onChange?.([], { zoom: { value: 2 }, scrollX: 10, scrollY: 20 }, {});await setEmbedEditable(embed, false);- expect(getEditingState()).toEqual({ isReadOnly: true, menu: false, tools: false });- expect(persistenceArgs).toHaveBeenLastCalledWith(- ATTACHMENT, editor, expect.anything(), expect.anything()- );-+ expect(getEditingState().isReadOnly).toBe(true);+ expect(getPicture()).not.toBeNull();+ await vi.waitFor(() => expect(getExcalidraw()).toBeNull());+ expect(box.querySelector<SVGElement>(".canvas-drawing-view > svg")?.style.left)+ .toBe("120px");+ expect(getContentEmbedTools(embed)?.hasEditableFlag).toBe(true);++ // The picture stays until Excalidraw shows the drawing, opened at the view of the picture.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.+ expect(getExcalidraw()).not.toBeNull();+ expect(getPicture()).not.toBeNull();+ const reopened = persistenceArgs.mock.lastCall?.[4] as PersistenceOptions;+ expect(reopened.initialView).toEqual({ zoom: { value: 2 }, scrollX: 10, scrollY: 20 });+ await act(async () => reopened.onSceneShown?.());+ await vi.waitFor(() => expect(getPicture()).toBeNull());++ // An attachment that the note cannot save shows as a picture, with no toggle to offer.render(null, box);- await mount({ canEdit: () => false } as unknown as ContentEditor);- expect(getEditingState()).toEqual({ isReadOnly: true, menu: false, tools: undefined });- expect(persistenceArgs).toHaveBeenLastCalledWith(- ATTACHMENT, undefined, expect.anything(), expect.anything()- );+ persistenceArgs.mockClear();+ await mount({ ...EDITOR, canEdit: () => false });+ await vi.waitFor(() => expect(box.querySelector(".canvas-drawing-view > svg"))+ .not.toBeNull());+ expect(getExcalidraw()).toBeNull();+ expect(persistenceArgs).not.toHaveBeenCalled();+ expect(getContentEmbedTools(embed)).toBeNull();embed.remove();});+ it("shows the picture at the saved view, else fit, on the drawing's background", async () => {+ sceneContent = JSON.stringify({+ elements: [ { x: 50, y: 30, width: 200, height: 100 } ],+ appState: {+ zoom: { value: 2 }, scrollX: 10, scrollY: 20, viewBackgroundColor: "#ffc9c9"+ }+ });+ await mount(null);+ const layer = box.querySelector<HTMLElement>(".canvas-drawing-view");+ const svg = await vi.waitFor(() => {+ const shown = box.querySelector<SVGElement>(".canvas-drawing-view > svg");+ if (!shown) throw new Error("Expected the picture.");+ return shown;+ });+ // At (50 + 10) × 2 and (30 + 20) × 2, twice the 200 × 100 of the shapes.+ expect([ svg.style.left, svg.style.top, svg.style.width, svg.style.height ])+ .toEqual([ "120px", "100px", "400px", "200px" ]);+ expect(layer?.style.getPropertyValue("--canvas-drawing-view-background")).toBe("#ffc9c9");+ expect(vi.mocked(exportToSvg)).toHaveBeenLastCalledWith(expect.objectContaining({+ appState: expect.objectContaining({ exportBackground: false }),+ exportPadding: 0+ }));++ // Without a saved view, fit in the 400 × 200 box, centered.+ render(null, box);+ sceneContent = JSON.stringify({ elements: [ { x: 50, y: 30, width: 200, height: 100 } ] });+ await mount(null);+ await vi.waitFor(() => expect(box.querySelector<SVGElement>(".canvas-drawing-view > svg")+ ?.style.left).toBe("0px"));+ const fitted = box.querySelector<SVGElement>(".canvas-drawing-view > svg");+ expect([ fitted?.style.top, fitted?.style.width, fitted?.style.height ])+ .toEqual([ "0px", "400px", "200px" ]);++ // A saved view past the left edge of the image of an image canvas moves back inside it.+ render(null, box);+ sceneContent = JSON.stringify({+ elements: [ { type: "image", locked: true, x: 0, y: 0, width: 800, height: 400 } ],+ appState: { zoom: { value: 1 }, scrollX: 100, scrollY: 0 }+ });+ await mount(null);+ await vi.waitFor(() => expect(box.querySelector<SVGElement>(".canvas-drawing-view > svg")+ ?.style.left).toBe("600px"));+ });++ it("centers the picture once fullscreen changes its size, as Excalidraw does", async () => {+ sceneContent = JSON.stringify({+ elements: [ { x: 50, y: 30, width: 200, height: 100 } ],+ appState: { zoom: { value: 2 }, scrollX: 10, scrollY: 20 }+ });+ await mount(null);+ const getSvg = () => box.querySelector<SVGElement>(".canvas-drawing-view > svg");+ await vi.waitFor(() => expect(getSvg()?.style.left).toBe("120px"));+ vi.spyOn(HTMLElement.prototype, "getBoundingClientRect")+ .mockReturnValue({ width: 400, height: 200 } as DOMRect);++ await act(async () => {+ box.dispatchEvent(new Event("enterFullscreen", { bubbles: true }));+ });++ // The center of the shapes, (150, 80), in the middle of the 400 × 200 box at zoom 2.+ expect([ getSvg()?.style.left, getSvg()?.style.top ]).toEqual([ "0px", "0px" ]);+ vi.restoreAllMocks();+ });++ it("renders the picture again when the drawing saves, and not for other saves", async () => {+ const parent = new Component();+ await act(async () => {+ render(+ <ParentComponent.Provider value={parent}>+ <CanvasDrawing attachment={ATTACHMENT} />+ </ParentComponent.Provider>,+ box+ );+ });+ await vi.waitFor(() => expect(exportToSvg).toHaveBeenCalledTimes(1));++ const save = async (attachmentId: string) => {+ const loadResults = new LoadResults([]);+ loadResults.addAttachmentRow({ attachmentId } as never, "any");+ await act(async () => {+ await parent.handleEvent("entitiesReloaded", { loadResults });+ });+ };+ await save("other");+ sceneContent = JSON.stringify({ elements: [ { x: 0, y: 0, width: 10, height: 10 } ] });+ await save("a1");+ await vi.waitFor(() => expect(exportToSvg).toHaveBeenCalledTimes(2));+ await save("a1");+ await new Promise((resolve) => setTimeout(resolve, 50));+ expect(exportToSvg).toHaveBeenCalledTimes(2);+ });+it("is editable outside an embed, which has no Editable toggle", async () => {await mount({ canEdit: () => true, release: vi.fn() } as unknown as ContentEditor);expect(getEditingState()).toEqual({ isReadOnly: false, menu: true, tools: true });diff --git a/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.tsx b/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.tsxindex 996aa2e7fe..cc0b2c1514 100644--- a/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.tsx+++ b/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.tsx@@ -1,10 +1,11 @@import "./CanvasDrawing.css";-import { exportToSvg } from "@excalidraw/excalidraw";+import { exportToSvg, getCommonBounds } from "@excalidraw/excalidraw";+import type { ExcalidrawElement } from "@excalidraw/excalidraw/element/types";import type { AppState, ExcalidrawImperativeAPI } from "@excalidraw/excalidraw/types";import clsx from "clsx";import type { RefObject } from "preact";-import { useEffect, useMemo, useRef, useState } from "preact/hooks";+import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "preact/hooks";import type NoteContext from "../../../components/note_context";import type FAttachment from "../../../entities/fattachment";@@ -13,14 +14,16 @@ import { bindAttachmentEditor, type ContentEditor } from "../../../services/contimport options from "../../../services/options";import { getEffectiveThemeStyle } from "../../../services/theme";import { isDesktop } from "../../../services/utils";-import { useColorScheme, useEffectiveReadOnly } from "../../react/hooks";+import {+ useColorScheme, useEffectiveReadOnly, useElementSize, useTriliumEvent+} from "../../react/hooks";import { useAttachmentEditor } from "../text/attachment_saves";import { useContentEmbedEvent } from "../text/content_embed_tools";import { useEditableEmbed } from "../text/editable_embed";import { CanvasEditor } from "./Canvas";import CanvasDrawingMenu from "./CanvasDrawingMenu";-import CanvasEmbedTools from "./CanvasEmbedTools";-import { getBoundedView } from "./drawing_view";+import CanvasEmbedTools, { CanvasTools } from "./CanvasEmbedTools";+import { type DrawingView, getBoundedView, getCenteredView, getFittedView } from "./drawing_view";import { loadDrawingFiles, parseContent, useCanvasDrawingPersistence } from "./persistence";interface CanvasDrawingProps {@@ -29,31 +32,33 @@ interface CanvasDrawingProps {editor?: ContentEditor;}+/** What a drawing in an embed shows: Excalidraw while it is edited, otherwise a picture. */+type DrawingMode = "editor" | "picture";+/**- * 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.+ * A canvas drawing saved in an attachment. While the Editable toggle of its embed is on, Excalidraw+ * edits it in place inside the note that shows it; otherwise it shows as a picture at the same+ * view.*/export default function CanvasDrawing({ attachment, editor }: CanvasDrawingProps) {const rootRef = useRef<HTMLDivElement>(null);const apiRef = useRef<ExcalidrawImperativeAPI>(null);+ // The view shown last, which the picture and Excalidraw take over from each other.+ const viewRef = useRef<DrawingView | null>(null);const colorScheme = useColorScheme();- // `CanvasEmbedTools` adds the buttons of the drawing to the toolbar of the embed.- const { canEdit, isEditing: isEditable } = useEditableEmbed(rootRef, {+ const [ tools ] = useState(() => new CanvasTools(rootRef));+ const { isEditing } = useEditableEmbed(rootRef, {editor,note: null,- tools: null,+ tools,focusTarget: ".excalidraw"});- // Follows `canEdit` rather than the toggle, so that turning editing off keeps a pending save.- const persistence = useCanvasDrawingPersistence(- attachment,- canEdit ? editor : undefined,- apiRef,- colorScheme- );+ const mode: DrawingMode = isEditing ? "editor" : "picture";+ // Stays until the other mode draws, so that switching shows no empty box.+ const [ drawnMode, setDrawnMode ] = useState<DrawingMode | null>(null);const isToolbarOverPanel = useIsToolbarOverPanel(rootRef);const isRecentering = useRecenteringOnFullscreen(rootRef, apiRef);- useSidePanels(rootRef, isEditable);+ useSidePanels(rootRef, isEditing);useTopLayerContextMenu(rootRef, apiRef);useNoteScrollingWheel(rootRef);@@ -66,24 +71,281 @@ export default function CanvasDrawing({ attachment, editor }: CanvasDrawingPropsisRecentering && "recentering")}>- <CanvasEditor- apiRef={apiRef}- isReadOnly={!isEditable}- colorScheme={colorScheme}- persistence={persistence}- constrainView={getBoundedView}- isEmbedded- isDesktopLayout={isDesktop()}- >- <CanvasDrawingMenu apiRef={apiRef} isEditable={isEditable} />- {canEdit && (- <CanvasEmbedTools rootRef={rootRef} apiRef={apiRef} isEditable={isEditable} />- )}- </CanvasEditor>+ {(mode === "picture" || drawnMode === "picture") && (+ <DrawingPicture+ attachment={attachment}+ editor={editor}+ colorScheme={colorScheme}+ rootRef={rootRef}+ viewRef={viewRef}+ onDrawn={() => setDrawnMode("picture")}+ />+ )}+ {(mode === "editor" || drawnMode === "editor") && (+ <LiveDrawing+ attachment={attachment}+ editor={editor}+ colorScheme={colorScheme}+ rootRef={rootRef}+ apiRef={apiRef}+ viewRef={viewRef}+ tools={tools}+ isEditable={isEditing}+ onDrawn={() => setDrawnMode("editor")}+ />+ )}</div>);}+interface LiveDrawingProps {+ attachment: FAttachment;+ /** Saves the changes. */+ editor: ContentEditor | undefined;+ colorScheme: AppState["theme"];+ rootRef: RefObject<HTMLDivElement | null>;+ apiRef: RefObject<ExcalidrawImperativeAPI | null>;+ viewRef: RefObject<DrawingView | null>;+ tools: CanvasTools;+ isEditable: boolean;+ /** Called on the frame after Excalidraw shows the drawing. */+ onDrawn: () => void;+}++/**+ * The drawing in Excalidraw, opened at the view of `viewRef`, which follows the view from then on.+ * Its persistence saves what is left to save before Excalidraw unmounts.+ */+function LiveDrawing({+ attachment, editor, colorScheme, rootRef, apiRef, viewRef, tools, isEditable, onDrawn+}: LiveDrawingProps) {+ const isShownRef = useRef(false);+ const frameRef = useRef(0);+ const persistence = useCanvasDrawingPersistence(attachment, editor, apiRef, colorScheme, {+ initialView: viewRef.current,+ onSceneShown: () => {+ isShownRef.current = true;+ frameRef.current = requestAnimationFrame(onDrawn);+ }+ });+ useLayoutEffect(() => () => {+ cancelAnimationFrame(frameRef.current);+ apiRef.current = null;+ }, [ apiRef ]);++ return (+ <CanvasEditor+ apiRef={apiRef}+ isReadOnly={!isEditable}+ colorScheme={colorScheme}+ persistence={{+ ...persistence,+ onChange: (elements, appState, files) => {+ persistence.onChange?.(elements, appState, files);+ if (isShownRef.current) {+ const { zoom, scrollX, scrollY } = appState;+ viewRef.current = { zoom, scrollX, scrollY };+ }+ }+ }}+ constrainView={getBoundedView}+ isEmbedded+ isDesktopLayout={isDesktop()}+ >+ <CanvasDrawingMenu apiRef={apiRef} isEditable={isEditable} />+ <CanvasEmbedTools+ rootRef={rootRef}+ apiRef={apiRef}+ tools={tools}+ isEditable={isEditable}+ />+ </CanvasEditor>+ );+}++interface DrawingPictureProps {+ attachment: FAttachment;+ /** Holds the changes not saved yet, which the picture shows. */+ editor: ContentEditor | undefined;+ colorScheme: AppState["theme"];+ rootRef: RefObject<HTMLElement | null>;+ viewRef: RefObject<DrawingView | null>;+ /** Called on the frame after the picture shows. */+ onDrawn: () => void;+}++/**+ * The drawing as a picture, at the view of `viewRef`, else at the saved view, else fit in the box.+ * It renders again when the drawing saves, and centers the drawing once fullscreen changes its+ * size, as Excalidraw does.+ */+function DrawingPicture({+ attachment, editor, colorScheme, rootRef, viewRef, onDrawn+}: DrawingPictureProps) {+ const layerRef = useRef<HTMLDivElement>(null);+ const [ scene, setScene ] = useState<PictureScene | null>(null);+ const [ revision, setRevision ] = useState(0);+ const [ recenterings, setRecenterings ] = useState(0);+ const renderedKeyRef = useRef<string | null>(null);+ const size = useElementSize(layerRef);++ useTriliumEvent("entitiesReloaded", ({ loadResults }) => {+ const rows = loadResults.getAttachmentRows();+ if (rows.some((row) => row.attachmentId === attachment.attachmentId)) {+ setRevision((count) => count + 1);+ }+ });++ useEffect(() => {+ let isCurrent = true;+ // Starts on the next frame, so that a drawing whose embed turns out editable renders none.+ const frame = requestAnimationFrame(async () => {+ const content = editor?.getUnsavedContent()+ ?? (await attachment.getBlob())?.content ?? "";+ const key = `${colorScheme}\n${content}`;+ if (key === renderedKeyRef.current) return;++ const rendered = await renderPictureScene(attachment, content, colorScheme === "dark");+ if (isCurrent) {+ renderedKeyRef.current = key;+ setScene(rendered);+ }+ });+ return () => {+ isCurrent = false;+ cancelAnimationFrame(frame);+ };+ }, [ attachment, editor, colorScheme, revision ]);++ const recenter = () => {+ const box = layerRef.current?.getBoundingClientRect();+ const view = viewRef.current;+ if (!scene || !box || !view) return;++ viewRef.current = getCenteredView(scene.elements, view, box.width, box.height) ?? view;+ setRecenterings((count) => count + 1);+ };+ useContentEmbedEvent(rootRef, "enterFullscreen", recenter);+ useContentEmbedEvent(rootRef, "leaveFullscreen", recenter);++ useLayoutEffect(() => {+ const layer = layerRef.current;+ if (!layer || !scene || !size?.width || !size.height) return;++ const view = getPictureView(scene, size.width, size.height, viewRef.current);+ viewRef.current = view;+ if (scene.picture && view) {+ placePicture(scene.picture, view);+ }+ layer.replaceChildren(...(scene.picture ? [ scene.picture.svg ] : []));+ const frame = requestAnimationFrame(onDrawn);+ return () => cancelAnimationFrame(frame);+ }, [ scene, size, recenterings ]);++ return (+ <div+ ref={layerRef}+ className={clsx("canvas-drawing-view", colorScheme === "dark" && "theme-dark")}+ style={scene?.background+ ? { "--canvas-drawing-view-background": scene.background }+ : undefined}+ />+ );+}++/** The picture of the content of a drawing, and where it sits in the scene. */+interface ScenePicture {+ svg: SVGSVGElement;+ x: number;+ y: number;+ width: number;+ height: number;+}++interface PictureScene {+ /** The picture of the content, or `null` for an empty drawing. */+ picture: ScenePicture | null;+ /** The shapes that are not deleted. */+ elements: ExcalidrawElement[];+ savedView: DrawingView | null;+ /** The background picked for the drawing, or `null` while it shows the note's. */+ background: string | null;+}++/** The picture of the drawing in `content`, the content of `attachment`. */+async function renderPictureScene(+ attachment: FAttachment,+ content: string,+ isDark: boolean+): Promise<PictureScene> {+ const scene = parseContent(content, attachment);+ const elements = (scene.elements ?? []).filter((element) => !element.isDeleted);+ const { zoom, scrollX, scrollY, viewBackgroundColor } = scene.appState ?? {};+ const savedView = zoom && scrollX !== undefined && scrollY !== undefined+ ? { zoom, scrollX, scrollY }+ : null;+ const background = viewBackgroundColor && viewBackgroundColor !== "transparent"+ ? viewBackgroundColor+ : null;+ if (!elements.length) {+ return { picture: null, elements, savedView, background };+ }++ const svg = await exportToSvg({+ elements,+ appState: { ...scene.appState, exportBackground: false, exportWithDarkMode: isDark },+ files: (await loadDrawingFiles(attachment, scene)).files,+ exportPadding: 0+ });+ const width = Number(svg.getAttribute("width"));+ const height = Number(svg.getAttribute("height"));+ // The picture starts at the top left of the shapes and of the names of the frames, which sit+ // above the frames, so it is placed by the bottom right corner of the shapes.+ const [ , , maxX, maxY ] = getCommonBounds(getRootElements(elements));+ return {+ picture: { svg, x: maxX - width, y: maxY - height, width, height },+ elements,+ savedView,+ background+ };+}++/**+ * The shapes that Excalidraw's export takes the size of: those outside frames, and the frames,+ * which clip what they hold.+ */+function getRootElements(elements: readonly ExcalidrawElement[]) {+ const frameIds = new Set(elements+ .filter((element) => element.type === "frame" || element.type === "magicframe")+ .map((element) => element.id));+ return elements.filter((element) => !element.frameId || !frameIds.has(element.frameId));+}++/**+ * The view of the picture of a drawing `width` by `height`: `view`, else the saved one, else the+ * content fit, kept inside the image of an image canvas. `null` without either.+ */+function getPictureView(+ scene: PictureScene,+ width: number,+ height: number,+ view: DrawingView | null+): DrawingView | null {+ const shown = view ?? scene.savedView ?? getFittedView(scene.elements, width, height);+ if (!shown) return null;++ return getBoundedView(scene.elements, { ...shown, width, height } as AppState) ?? shown;+}++/** Places `picture` where Excalidraw would draw its content at `view`. */+function placePicture({ svg, x, y, width, height }: ScenePicture, view: DrawingView) {+ const zoom = view.zoom.value;+ svg.style.left = `${(x + view.scrollX) * zoom}px`;+ svg.style.top = `${(y + view.scrollY) * zoom}px`;+ svg.style.width = `${width * zoom}px`;+ svg.style.height = `${height * zoom}px`;+}+/** A picture of the canvas drawing saved in `entity`, or `null` for an empty drawing. */export async function renderCanvasDrawingPicture(entity: FNote | FAttachment) {const blob = await entity.getBlob();diff --git a/apps/client/src/widgets/type_widgets/canvas/CanvasEmbedTools.spec.tsx b/apps/client/src/widgets/type_widgets/canvas/CanvasEmbedTools.spec.tsxindex 62ae7d5d37..0f8dc645a6 100644--- a/apps/client/src/widgets/type_widgets/canvas/CanvasEmbedTools.spec.tsx+++ b/apps/client/src/widgets/type_widgets/canvas/CanvasEmbedTools.spec.tsx@@ -1,6 +1,6 @@import type { AppState, ExcalidrawImperativeAPI } from "@excalidraw/excalidraw/types";import { render } from "preact";-import { useRef } from "preact/hooks";+import { useEffect, useRef, useState } from "preact/hooks";import { act } from "preact/test-utils";import { afterEach, beforeEach, describe, expect, it, type Mock, vi } from "vitest";@@ -11,9 +11,9 @@ vi.mock("@excalidraw/excalidraw", () => ({}));vi.mock("../../../services/i18n", () => ({ t: (key: string) => key }));-const { default: CanvasEmbedTools } = await import("./CanvasEmbedTools");+const { default: CanvasEmbedTools, CanvasTools } = await import("./CanvasEmbedTools");const {- getContentEmbedTools, watchContentEmbedTools+ getContentEmbedTools, registerContentEmbedTools, watchContentEmbedTools} = await import("../text/content_embed_tools");const MAIN_TOOL_IDS = [@@ -40,10 +40,18 @@ describe("CanvasEmbedTools", () => {container.remove();});- /** A drawing with Excalidraw's container and its undo and redo buttons. */+ /**+ * A drawing with Excalidraw's container and its undo and redo buttons, which adds its tools to+ * the toolbar of its embed, as `CanvasDrawing` does.+ */function Drawing({ isEditable }: { isEditable: boolean }) {const rootRef = useRef<HTMLDivElement>(null);const apiRef = useRef<ExcalidrawImperativeAPI>(api.api);+ const [ tools ] = useState(() => new CanvasTools(rootRef));+ useEffect(() => {+ const root = rootRef.current;+ return root ? registerContentEmbedTools(root, tools) : undefined;+ }, [ tools ]);return (<figure className="include-note" data-box-size="medium"><div className="include-note-content">@@ -54,6 +62,7 @@ describe("CanvasEmbedTools", () => {<CanvasEmbedToolsrootRef={rootRef}apiRef={apiRef}+ tools={tools}isEditable={isEditable}/></div>@@ -225,6 +234,27 @@ describe("CanvasEmbedTools", () => {expect(api.setActiveTool).not.toHaveBeenCalled();});+ it("offers and runs fullscreen alone without Excalidraw, as for a picture", () => {+ const embed = document.createElement("figure");+ embed.className = "include-note";+ Object.assign(embed.dataset, { hideTitle: "true", boxSize: "medium" });+ const box = document.createElement("div");+ box.className = "include-note-content";+ box.requestFullscreen = vi.fn(async () => {});+ const root = document.createElement("div");+ box.append(root);+ embed.append(box);+ container.append(embed);+ const tools = new CanvasTools({ current: root });++ expect(tools.getTools()).toEqual([+ { id: "fullscreen", label: "common.fullscreen", icon: ICON, group: "zoom" }+ ]);+ tools.execute("zoomIn");+ tools.execute("fullscreen");+ expect(box.requestFullscreen).toHaveBeenCalledOnce();+ });+it("runs a tool with the focus in the drawing", async () => {const { provider } = await mount();diff --git a/apps/client/src/widgets/type_widgets/canvas/CanvasEmbedTools.tsx b/apps/client/src/widgets/type_widgets/canvas/CanvasEmbedTools.tsxindex dcb1f24e39..3f914ebc83 100644--- a/apps/client/src/widgets/type_widgets/canvas/CanvasEmbedTools.tsx+++ b/apps/client/src/widgets/type_widgets/canvas/CanvasEmbedTools.tsx@@ -23,14 +23,13 @@ import zoomInIcon from "boxicons/svg/regular/bx-zoom-in.svg?raw";import zoomOutIcon from "boxicons/svg/regular/bx-zoom-out.svg?raw";import handIcon from "boxicons/svg/solid/bxs-hand.svg?raw";import type { RefObject } from "preact";-import { useEffect, useState } from "preact/hooks";+import { useEffect } from "preact/hooks";import { t } from "../../../services/i18n";import {type ContentEmbedTool,type ContentEmbedToolbarItem,type ContentEmbedToolProvider,- registerContentEmbedTools,showContentEmbedFullscreen} from "../text/content_embed_tools";import { getBoundedView, MAX_ZOOM, MIN_ZOOM } from "./drawing_view";@@ -91,17 +90,20 @@ interface CanvasEmbedToolsProps {/** The element of the drawing, inside the embed whose toolbar shows the tools. */rootRef: RefObject<HTMLElement | null>;apiRef: RefObject<ExcalidrawImperativeAPI | null>;+ /** The tools of the drawing, which the drawing adds to the toolbar of its embed. */+ tools: CanvasTools;/** 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.+ * Gives `tools` Excalidraw's tools, undo and redo, and zoom, while Excalidraw shows the drawing.+ * Renders inside `<Excalidraw>`, for its translations.*/-export default function CanvasEmbedTools({ rootRef, apiRef, isEditable }: CanvasEmbedToolsProps) {+export default function CanvasEmbedTools({+ rootRef, apiRef, tools, 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 ]);@@ -112,12 +114,10 @@ export default function CanvasEmbedTools({ rootRef, apiRef, isEditable }: Canvasif (!root || !api) return;const disconnect = tools.connect(api);- const unregister = registerContentEmbedTools(root, tools);// `CanvasDrawing.css` hides Excalidraw's own controls while these replace them.root.setAttribute("data-embed-tools", "");return () => {root.removeAttribute("data-embed-tools");- unregister();disconnect();};}, [ tools, rootRef, apiRef ]);@@ -131,7 +131,10 @@ export function useExcalidrawTranslation() {return useI18n() as unknown as { t: Translate; langCode: string };}-/** Excalidraw's tools and commands, as buttons of the toolbar of the embed with the drawing. */+/**+ * Excalidraw's tools and commands, as buttons of the toolbar of the embed with the drawing. Without+ * Excalidraw, as while the drawing shows as a picture, only fullscreen.+ */export class CanvasTools implements ContentEmbedToolProvider {readonly hiddenToolbarItems: readonly ContentEmbedToolbarItem[] = ["contentEmbedBoxSizeDropdown", "toggleContentEmbedTitle", "convertEmbedToLink"@@ -185,7 +188,7 @@ export class CanvasTools implements ContentEmbedToolProvider {getTools(): ContentEmbedTool[] {const appState = this.api?.getAppState();if (!appState) {- return [];+ return this.getFullscreenTools();}const zoomTools = [@@ -198,20 +201,23 @@ export class CanvasTools implements ContentEmbedToolProvider {}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 (id === FULLSCREEN) {showContentEmbedFullscreen(this.rootRef.current);- } else if (getZoom) {+ return;+ }++ const api = this.api;+ if (!api) return;++ const appState = api.getAppState();+ const getZoom = ZOOMS[id];+ if (getZoom) {const view = getZoomState(appState, getZoom(appState.zoom.value));const boundedView = getBoundedView(api.getSceneElements(), { ...appState, ...view });api.updateScene({ appState: boundedView ?? view });diff --git a/apps/client/src/widgets/type_widgets/canvas/drawing_view.spec.ts b/apps/client/src/widgets/type_widgets/canvas/drawing_view.spec.tsindex 7707b76479..21a31463dc 100644--- a/apps/client/src/widgets/type_widgets/canvas/drawing_view.spec.ts+++ b/apps/client/src/widgets/type_widgets/canvas/drawing_view.spec.ts@@ -1,6 +1,6 @@import { describe, expect, it, vi } from "vitest";-import { getBoundedView } from "./drawing_view";+import { getBoundedView, getCenteredView } from "./drawing_view";interface Box {x: number;@@ -52,3 +52,15 @@ describe("getBoundedView", () => {expect(bound([ IMAGE ], 0.25, 0, 0, 0)).toBeNull();});});++describe("getCenteredView", () => {+ it("centers the shapes of a drawing at the same zoom, and nothing without them", () => {+ const view = { zoom: { value: 2 }, scrollX: 0, scrollY: 0 } as never;+ const shape = { x: 100, y: 50, width: 200, height: 100 };++ expect(getCenteredView([ shape ] as never, view, 1000, 500))+ .toEqual({ zoom: { value: 2 }, scrollX: 50, scrollY: 25 });+ expect(getCenteredView([ { ...shape, isDeleted: true } ] as never, view, 1000, 500))+ .toBeNull();+ });+});diff --git a/apps/client/src/widgets/type_widgets/canvas/drawing_view.ts b/apps/client/src/widgets/type_widgets/canvas/drawing_view.tsindex 24d4b701bd..719da91563 100644--- a/apps/client/src/widgets/type_widgets/canvas/drawing_view.ts+++ b/apps/client/src/widgets/type_widgets/canvas/drawing_view.ts@@ -6,7 +6,7 @@ import type { AppState, NormalizedZoomValue } from "@excalidraw/excalidraw/typesexport const MIN_ZOOM = 0.1;export const MAX_ZOOM = 30;-type DrawingView = Pick<AppState, "zoom" | "scrollX" | "scrollY">;+export type DrawingView = Pick<AppState, "zoom" | "scrollX" | "scrollY">;/*** The view of a drawing `width` by `height` that saved none, such as one converted from an image:@@ -23,6 +23,28 @@ export function getFittedView(return fitView(getCommonBounds(shown), width, height);}+/**+ * `view` moved so that it centers the content of a drawing `width` by `height` at the same zoom, as+ * Excalidraw's `scrollToContent()` does. `null` without content.+ */+export function getCenteredView(+ elements: readonly ExcalidrawElement[],+ view: DrawingView,+ width: number,+ height: number+): DrawingView | null {+ const shown = elements.filter((element) => !element.isDeleted);+ if (!shown.length) return null;++ const [ minX, minY, maxX, maxY ] = getCommonBounds(shown);+ const zoom = view.zoom.value;+ return {+ zoom: view.zoom,+ scrollX: width / 2 / zoom - (minX + maxX) / 2,+ scrollY: height / 2 / zoom - (minY + maxY) / 2+ };+}+/*** The view of a drawing over a locked image, such as one converted from an image, kept inside the* image: zoomed out no further than the whole image and moved back within its edges. `null` whendiff --git a/apps/client/src/widgets/type_widgets/canvas/excalidraw_contract.spec.ts b/apps/client/src/widgets/type_widgets/canvas/excalidraw_contract.spec.tsindex dbbe9d5c97..a6a9ab4df6 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@@ -16,7 +16,8 @@ const { FITTED_MENU_STYLES } = await import("./CanvasDrawing");/** The classes of Trilium that `CanvasDrawing.css` selects. Every other class is Excalidraw's. */const TRILIUM_CLASSES = new Set(["note-detail", "canvas-drawing", "canvas-drawing-editor", "canvas-render",- "canvas-drawing-picture", "toolbar-over-panel", "recentering", "include-note",+ "canvas-drawing-picture", "canvas-drawing-view", "theme-dark", "toolbar-over-panel",+ "recentering", "include-note","include-note-body","include-note-content", "active", "tn-icon"]);diff --git a/apps/client/src/widgets/type_widgets/canvas/persistence.spec.tsx b/apps/client/src/widgets/type_widgets/canvas/persistence.spec.tsxindex f2531a04aa..11f63b0d23 100644--- a/apps/client/src/widgets/type_widgets/canvas/persistence.spec.tsx+++ b/apps/client/src/widgets/type_widgets/canvas/persistence.spec.tsx@@ -231,12 +231,13 @@ describe("useCanvasDrawingPersistence", () => {let appState: Record<string, unknown>;let updateScene: ReturnType<typeof vi.fn>;- function DrawingProbe({ attachment, editor, apiRef }: {+ function DrawingProbe({ attachment, editor, apiRef, options }: {attachment: FAttachment;editor: ContentEditor | undefined;apiRef: RefObject<ExcalidrawImperativeAPI | null>;+ options?: Parameters<typeof useCanvasDrawingPersistence>[4];}) {- drawingProps = useCanvasDrawingPersistence(attachment, editor, apiRef, "light");+ drawingProps = useCanvasDrawingPersistence(attachment, editor, apiRef, "light", options);return null;}@@ -273,7 +274,11 @@ describe("useCanvasDrawingPersistence", () => {} satisfies ContentEditor;}- async function mount(attachment: FAttachment, editor: ContentEditor | undefined) {+ async function mount(+ attachment: FAttachment,+ editor: ContentEditor | undefined,+ options?: Parameters<typeof useCanvasDrawingPersistence>[4]+ ) {const api = {getSceneElements: () => sceneElements,getAppState: () => appState,@@ -283,7 +288,12 @@ describe("useCanvasDrawingPersistence", () => {const apiRef = { current: api } as RefObject<ExcalidrawImperativeAPI | null>;await act(async () => {render(- <DrawingProbe attachment={attachment} editor={editor} apiRef={apiRef} />,+ <DrawingProbe+ attachment={attachment}+ editor={editor}+ apiRef={apiRef}+ options={options}+ />,container);});@@ -442,6 +452,38 @@ describe("useCanvasDrawingPersistence", () => {});});+ it("opens at the view it is given, which needs no fit, and tells once it shows", async () => {+ const loaded = [ { id: "r1", type: "rectangle", version: 3 } ];+ const placed = [ { ...loaded[0], x: 0, y: 0, width: 100, height: 100 } ];+ const view = { zoom: { value: 2 }, scrollX: 5, scrollY: 6 };+ const onSceneShown = vi.fn();+ const { attachment } = buildAttachment({ elements: placed, appState: { zoom: 1 } });++ const initialData = await mount(attachment, buildEditor(), {+ initialView: view as never,+ onSceneShown+ });+ expect(initialData.appState).toEqual(expect.objectContaining(view));++ // Excalidraw reports its empty scene, then the loaded one, twice.+ change();+ expect(onSceneShown).not.toHaveBeenCalled();+ sceneElements = loaded;+ const sized = { ...appState, width: 1000, height: 500 };+ drawingProps?.onChange?.(placed as never, sized as never, {});+ change();+ expect(onSceneShown).toHaveBeenCalledOnce();+ expect(updateScene).not.toHaveBeenCalled();++ act(() => render(null, container));+ sceneElements = [];+ const empty = vi.fn();+ const { attachment: emptyDrawing } = buildAttachment({ elements: [] });+ await mount(emptyDrawing, undefined, { onSceneShown: empty });+ change();+ expect(empty).toHaveBeenCalledOnce();+ });+it("saves nothing without an editor", async () => {const loaded = [ { id: "r1", type: "rectangle", version: 3 } ];const { attachment } = buildAttachment({ elements: loaded });diff --git a/apps/client/src/widgets/type_widgets/canvas/persistence.ts b/apps/client/src/widgets/type_widgets/canvas/persistence.tsindex 928bc995e1..067ccef572 100644--- a/apps/client/src/widgets/type_widgets/canvas/persistence.ts+++ b/apps/client/src/widgets/type_widgets/canvas/persistence.ts@@ -15,7 +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 { getBoundedView, getFittedView } from "./drawing_view";+import { type DrawingView, getBoundedView, getFittedView } from "./drawing_view";import {buildNewImageAttachments, CANVAS_EXPORT_TITLE, IMAGE_ROLE, loadImageAttachments, loadImageFiles} from "./image_attachments";@@ -351,6 +351,13 @@ export default function useCanvasPersistence(note: FNote, noteContext: NoteConte};}+interface DrawingPersistenceOptions {+ /** The view to open the drawing at, instead of the saved one. */+ initialView?: DrawingView | null;+ /** Called once Excalidraw shows the loaded scene. */+ onSceneShown?: () => void;+}+/*** Loads a canvas drawing from an attachment and passes its changes to `editor`, which saves them.* Without `editor`, the drawing is read-only.@@ -359,7 +366,8 @@ export function useCanvasDrawingPersistence(attachment: FAttachment,editor: ContentEditor | undefined,apiRef: RefObject<ExcalidrawImperativeAPI | null>,- theme: AppState["theme"]+ theme: AppState["theme"],+ { initialView, onSceneShown }: DrawingPersistenceOptions = {}): Partial<ExcalidrawProps> {const currentSceneVersion = useRef(0);/** The saved part of the app state, read from the editor at the first change. */@@ -368,6 +376,9 @@ export function useCanvasDrawingPersistence(const initialSceneAppliedRef = useRef(true);const referencedFileIds = useRef<ReadonlySet<string>>(new Set());const isFitPendingRef = useRef(false);+ /** Whether the loaded scene shows nothing, known once it loads. */+ const isLoadedSceneEmptyRef = useRef(false);+ const isSceneShownRef = useRef(false);const [ initialData ] = useState(async (): Promise<ExcalidrawInitialDataState> => {const unsavedContent = editor?.getUnsavedContent();@@ -381,13 +392,16 @@ export function useCanvasDrawingPersistence(const elements = content.elements ?? [];currentSceneVersion.current = getSceneVersion(elements);initialSceneAppliedRef.current = currentSceneVersion.current === 0;- isFitPendingRef.current = !content.appState?.zoom- && elements.some((element) => !element.isDeleted);+ isLoadedSceneEmptyRef.current = !elements.some((element) => !element.isDeleted);+ isFitPendingRef.current = !initialView && !content.appState?.zoom+ && !isLoadedSceneEmptyRef.current;return {elements,// A drawing shows the background of the note unless one is picked for it.- appState: { viewBackgroundColor: "transparent", ...content.appState, theme },+ appState: {+ viewBackgroundColor: "transparent", ...content.appState, ...initialView, theme+ },files: loaded.files};});@@ -409,9 +423,15 @@ export function useCanvasDrawingPersistence(if (fitted) isFitPendingRef.current = false;const view = fitted || getBoundedView(elements, state);if (api && view) api.updateScene({ appState: view });- if (!api || !editor) return;+ if (!api) return;const sceneVersion = getSceneVersion(api.getSceneElements());+ if (!isSceneShownRef.current && (isLoadedSceneEmptyRef.current || sceneVersion)) {+ isSceneShownRef.current = true;+ onSceneShown?.();+ }+ if (!editor) return;+if (!initialSceneAppliedRef.current) {if (sceneVersion === 0) return;initialSceneAppliedRef.current = true;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 8cba6e6d91..d45641c598 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@@ -225,16 +225,16 @@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, asover 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,- or drag it while it is not editable. In fullscreen, the mouse wheel moves- and zooms the drawing instead.</li>+ 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>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 turnoff the <span class="tn-icon bx bx-edit-alt"></span> <em>Editable</em> buttonat 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>+ 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 includednote, but the toolbar of a drawing leaves the box size, <em>Show title</em> and <em>Convert to link</em> toits <em>More actions</em> menu.</li>@@ -246,7 +246,7 @@image is kept as an image attachment of the note instead, named with agenerated code.</li><li>In a <a href="#root/_help_CoFPLs3dRlXc">read-only note</a>, the drawing- can be viewed but not changed.</li>+ shows as a still picture too.</li></ul><h3>Limitations</h3><ul>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.mdindex 32764a2b0d..6294898d60 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@@ -123,13 +123,13 @@ A drawing canvas is an Excalidraw canvas, like the one of a <a class="reference-* To draw or write over an image, select the image and press the <span class="tn-icon bx bxs-pen"></span> _Convert image to a drawing canvas_ button of its toolbar. The image is replaced by an editable drawing canvas in a _Medium_ 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 _Unlock_. The caption of the image is kept, but not its size, alignment or link. Only an image on its own line can be converted, not one inside a paragraph. Undo brings the image back.* An Excalidraw file (`.excalidraw`) attached with the <span class="tn-icon cke cke-paper-clip"></span>_Attach file_ button becomes a drawing canvas too, in a _Medium_ box titled with the file name. It starts with _Editable_ off, so the drawing shows but cannot be changed until _Editable_ is turned on (see below).* 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, or drag it while it is not editable. In fullscreen, the mouse wheel moves and zooms the drawing instead.+* 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.* 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 can then be panned and zoomed but not changed, and its toolbar holds only the zoom buttons. To draw again, turn _Editable_ back on.+* 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.* 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. A converted image is kept as an image attachment of the note instead, named with a generated code.-* In a [read-only note](../../Basic%20Concepts%20and%20Features/Notes/Read-Only%20Notes.md), the drawing can be viewed but not changed.+* In a [read-only note](../../Basic%20Concepts%20and%20Features/Notes/Read-Only%20Notes.md), the drawing shows as a still picture too.### Limitations