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: focus the canvas after inserting it
Adorian Doran1eebd2235498
diff --git a/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.spec.tsx b/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.spec.tsxindex 4b763e086e..1bae2391fd 100644--- a/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.spec.tsx+++ b/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.spec.tsx@@ -1,10 +1,18 @@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, vi } from "vitest";vi.mock("@excalidraw/excalidraw", () => ({ exportToSvg: vi.fn() }));-vi.mock("./Canvas", () => ({ CanvasEditor: () => null }));+vi.mock("./Canvas", () => ({ CanvasEditor: MockCanvasEditor }));+vi.mock("./persistence", () => ({ useCanvasDrawingPersistence: () => ({}) }));++/** Renders Excalidraw's focusable container after a render, as once its language loads. */+function MockCanvasEditor() {+ const [ isLoaded, setIsLoaded ] = useState(false);+ useEffect(() => setIsLoaded(true), []);+ return isLoaded ? <div className="excalidraw" tabIndex={0} /> : <span className="loading" />;+}// happy-dom has no ResizeObserver; the spec runs the callback itself.let resizeCallback: (() => void) | undefined;@@ -16,7 +24,7 @@ globalThis.ResizeObserver = class {disconnect() {}} as unknown as typeof ResizeObserver;-const { useIsToolbarOverPanel } = await import("./CanvasDrawing");+const { default: CanvasDrawing, useIsToolbarOverPanel } = await import("./CanvasDrawing");/** Horizontal edges by class name; happy-dom computes no layout. */const edges: Record<string, { left: number; right: number }> = {@@ -82,3 +90,44 @@ describe("useIsToolbarOverPanel", () => {expect(root?.getAttribute("data-over")).toBe("true");});});++describe("CanvasDrawing", () => {+ let box: HTMLElement;++ beforeEach(() => {+ box = document.createElement("div");+ box.className = "include-note-content";+ box.tabIndex = -1;+ document.body.appendChild(box);+ });++ afterEach(() => {+ render(null, box);+ box.remove();+ });++ async function mount() {+ await act(async () => {+ render(<CanvasDrawing attachment={{ attachmentId: "a1" } as never} />, box);+ });+ return box.querySelector(".excalidraw");+ }++ it("takes the focus that its embed box holds once Excalidraw renders", async () => {+ box.focus();+ const excalidraw = await mount();+ expect(excalidraw).not.toBeNull();+ await vi.waitFor(() => expect(document.activeElement).toBe(excalidraw));+ });++ it("leaves the focus anywhere else alone", async () => {+ const editable = document.createElement("div");+ editable.tabIndex = 0;+ document.body.appendChild(editable);+ editable.focus();++ await mount();+ expect(document.activeElement).toBe(editable);+ editable.remove();+ });+});diff --git a/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.tsx b/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.tsxindex f56b0c83f5..314b473a0f 100644--- a/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.tsx+++ b/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.tsx@@ -33,6 +33,7 @@ export default function CanvasDrawing({ attachment, editor }: CanvasDrawingPropscolorScheme);const isToolbarOverPanel = useIsToolbarOverPanel(rootRef);+ useFocusFromEmbedBox(rootRef);return (<div@@ -69,6 +70,35 @@ export async function renderCanvasDrawingPicture(entity: FNote | FAttachment) {return svg;}+/**+ * Moves the focus into Excalidraw when the embed box around the drawing holds it. Excalidraw+ * renders its container only once its language loads, after the box may have taken the focus.+ */+function useFocusFromEmbedBox(rootRef: RefObject<HTMLElement>) {+ useEffect(() => {+ const root = rootRef.current;+ if (!root) return;++ // Returns whether the container exists, after which there is nothing left to wait for.+ const forwardFocus = () => {+ const container = root.querySelector<HTMLElement>(".excalidraw");+ if (container && document.activeElement === container.closest(".include-note-content")) {+ container.focus();+ }+ return !!container;+ };+ if (forwardFocus()) return;++ const observer = new MutationObserver(() => {+ if (forwardFocus()) {+ observer.disconnect();+ }+ });+ observer.observe(root, { childList: true, subtree: true });+ return () => observer.disconnect();+ }, [ rootRef ]);+}+/*** Whether Excalidraw's toolbar reaches over the column of the properties panel, which then starts* below the toolbar instead of at the top of the canvas.diff --git a/apps/client/src/widgets/type_widgets/text/ContentEmbed.spec.tsx b/apps/client/src/widgets/type_widgets/text/ContentEmbed.spec.tsxindex bfaf425265..1f43bd5f97 100644--- a/apps/client/src/widgets/type_widgets/text/ContentEmbed.spec.tsx+++ b/apps/client/src/widgets/type_widgets/text/ContentEmbed.spec.tsx@@ -350,6 +350,27 @@ describe("ContentEmbed", () => {});});+describe("ContentEmbed focused on mount", () => {+ it("gives the focus to the first focusable element of its content, or to the box", () => {+ const content = element(+ `<div class="rendered-content"><p>body</p><div tabindex="0"></div></div>`+ );+ renderBox({ content, isFocusedOnMount: true });+ expect(document.activeElement).toBe(content.querySelector("[tabindex]"));+ expect(contentBox().parentElement?.classList.contains("active")).toBe(true);++ act(() => render(null, container));+ renderBox({ isFocusedOnMount: true });+ expect(document.activeElement).toBe(contentBox());+ });++ it("leaves the focus where it is by default", () => {+ const content = element(`<div class="rendered-content"><div tabindex="0"></div></div>`);+ renderBox({ content });+ expect(document.activeElement).toBe(document.body);+ });+});+describe("TinyContentEmbed", () => {it("lays out a single row: icon, title and description, actions, menu", () => {const run = vi.fn();diff --git a/apps/client/src/widgets/type_widgets/text/ContentEmbed.tsx b/apps/client/src/widgets/type_widgets/text/ContentEmbed.tsxindex f1df5c7cf7..1230eac4f4 100644--- a/apps/client/src/widgets/type_widgets/text/ContentEmbed.tsx+++ b/apps/client/src/widgets/type_widgets/text/ContentEmbed.tsx@@ -28,6 +28,8 @@ export interface ContentEmbedProps {/** The note opened by the buttons in the title row. */notePath: string;viewScope?: ViewScope;+ /** Gives the focus to the content once mounted, as for a canvas drawing just added. */+ isFocusedOnMount?: boolean;}export interface TinyContentEmbedProps {@@ -45,7 +47,7 @@ export interface TinyContentEmbedProps {/** The title row and the content of an embedded note or attachment. */export default function ContentEmbed({- boxSize, title, content, contentType, notePath, viewScope+ boxSize, title, content, contentType, notePath, viewScope, isFocusedOnMount}: ContentEmbedProps) {const contentRef = useRef<HTMLDivElement>(null);const isContentActive = useFocusWithin(contentRef);@@ -61,6 +63,12 @@ export default function ContentEmbed({};}, [ content ]);+ useLayoutEffect(() => {+ if (isFocusedOnMount) {+ (content.querySelector<HTMLElement>(FOCUSABLE_SELECTOR) ?? contentRef.current)?.focus();+ }+ }, []);+return (<><divdiff --git a/apps/client/src/widgets/type_widgets/text/EditableText.tsx b/apps/client/src/widgets/type_widgets/text/EditableText.tsxindex 79a5bd2ff5..8256090404 100644--- a/apps/client/src/widgets/type_widgets/text/EditableText.tsx+++ b/apps/client/src/widgets/type_widgets/text/EditableText.tsx@@ -58,6 +58,8 @@ export default function EditableText({ note, parentComponent, ntxId, noteContext/** The note `contentRef` holds the content of, so a restarted editor can be marked as holding it. */const contentNoteIdRef = useRef<string>();const pendingAttachmentChangesRef = useRef<PendingAttachmentChanges>();+ /** The attachment whose embed takes the focus when it renders next. */+ const focusedAttachmentIdRef = useRef<string>();const watchdogRef = useRef<EditorWatchdog>(null);const stopWatchingEmbedsRef = useRef<() => void>();const editorApiRef = useRef<CKEditorApi>(null);@@ -201,7 +203,17 @@ export default function EditableText({ note, parentComponent, ntxId, noteContext},loadEmbeddedNote,loadEmbeddedAttachment(attachmentId: string, $el: JQuery<HTMLElement>, boxSize?: string) {- return loadEmbeddedAttachment(attachmentId, $el, boxSize, attachmentSaves);+ const isFocused = focusedAttachmentIdRef.current === attachmentId;+ if (isFocused) {+ focusedAttachmentIdRef.current = undefined;+ }+ return loadEmbeddedAttachment(attachmentId, $el, boxSize, {+ attachmentEditor: attachmentSaves,+ isFocused+ });+ },+ focusContentEmbed(attachmentId: string) {+ focusedAttachmentIdRef.current = attachmentId;},getAttachmentHref,getNoteId() {diff --git a/apps/client/src/widgets/type_widgets/text/utils.spec.ts b/apps/client/src/widgets/type_widgets/text/utils.spec.tsindex 3b59bfc0b6..bce72029de 100644--- a/apps/client/src/widgets/type_widgets/text/utils.spec.ts+++ b/apps/client/src/widgets/type_widgets/text/utils.spec.ts@@ -200,6 +200,22 @@ describe("loadEmbeddedAttachment", () => {});});+ it("passes the attachment editor to the renderer, and the focus to the box", async () => {+ const attachmentEditor = { canEdit: vi.fn() } as never;++ await loadEmbeddedAttachment("att1", $(createWrapper()), "medium", {+ attachmentEditor,+ isFocused: true+ });++ expect(content_renderer.getRenderedContent).toHaveBeenCalledWith(attachment, {+ interactive: true,+ mediaEnvironment: "embedded",+ attachmentEditor+ });+ expect(lastMount().props).toMatchObject({ isFocusedOnMount: true });+ });+it("leaves the box alone for a deleted attachment", async () => {vi.mocked(froca.getAttachment).mockResolvedValue(null);diff --git a/apps/client/src/widgets/type_widgets/text/utils.ts b/apps/client/src/widgets/type_widgets/text/utils.tsindex b8a55ec02b..3b6df551e6 100644--- a/apps/client/src/widgets/type_widgets/text/utils.ts+++ b/apps/client/src/widgets/type_widgets/text/utils.ts@@ -58,16 +58,22 @@ export async function loadEmbeddedNote(noteId: string, $el: JQuery<HTMLElement>,await mountEmbedBox(el, box, $renderedContent);}+interface EmbeddedAttachmentOptions {+ /** Saves the changes that the content makes to the attachment, such as a canvas drawing. */+ attachmentEditor?: AttachmentEditor;+ /** Whether the content takes the focus once the box is mounted. */+ isFocused?: boolean;+}+/*** Fills an embed box with an embedded attachment, under a title linking to it. Without a box- * size of its own, the box takes the one of its embed. `attachmentEditor` saves the changes that- * the content makes to the attachment, such as a canvas drawing.+ * size of its own, the box takes the one of its embed.*/export async function loadEmbeddedAttachment(attachmentId: string,$el: JQuery<HTMLElement>,boxSize?: string,- attachmentEditor?: AttachmentEditor+ { attachmentEditor, isFocused }: EmbeddedAttachmentOptions = {}) {const attachment = await froca.getAttachment(attachmentId, true);if (!attachment) return;@@ -109,7 +115,8 @@ export async function loadEmbeddedAttachment(content: $renderedContent[0],contentType: type,notePath: attachment.ownerId,- viewScope+ viewScope,+ ...(isFocused ? { isFocusedOnMount: true } : {})});await mountEmbedBox(el, box, $renderedContent);}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 cf5ac8577e..cb24b95740 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@@ -143,12 +143,14 @@<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.</li>- <li>To draw, click the canvas 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.</li>+ The canvas is added empty, 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. 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.</li><li>A new drawing has the background color of the note. A background chosenfrom the Excalidraw menu replaces it.</li><li>The box sizes, the caption and the title work as for an included note.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 0bb8291c77..e3c27c1721 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@@ -93,8 +93,8 @@ 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.json` [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.-* To draw, click the canvas 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.+* 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 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, the caption and the title work as for an included note. In a short box, Excalidraw uses a more compact layout for its toolbars. 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.diff --git a/packages/ckeditor5/src/augmentation.ts b/packages/ckeditor5/src/augmentation.tsindex c94e58f1bd..ad7c1601cc 100644--- a/packages/ckeditor5/src/augmentation.ts+++ b/packages/ckeditor5/src/augmentation.ts@@ -2,6 +2,7 @@ import "ckeditor5";declare global {interface Component {+ componentId: string;triggerCommand(command: string): void;}@@ -63,6 +64,11 @@ declare global {* leave it out.*/openContentEmbedMenu?(embed: HTMLElement, anchor: HTMLElement): void;+ /**+ * Gives the focus to what the embed of the attachment shows, once it renders. Hosts+ * without embeds leave it out.+ */+ focusContentEmbed?(attachmentId: string): void;/*** Reads a page's preview metadata through the host. Never rejects: any failure — network* error, HTTP error, unparseable page — resolves as `{ unresolved: true }` with@@ -79,7 +85,8 @@ declare global {getActiveContextNote(): {noteId: string;};- getHeaders(): Promise<Record<string, string>>;+ /** The headers of a request to the server, with `headers` added to them. */+ getHeaders(headers?: Record<string, string | undefined>): Promise<Record<string, string>>;getReferenceLinkTitle(href: string): Promise<string>;getReferenceLinkTitleSync(href: string): string;};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 5469470b7f..1d4f71b55c 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 and without a title, quietly", async () => {+ it("embeds an empty canvas 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,7 +165,8 @@ describe("FileUploadUI", () => {asEmbed: true,boxSize: "medium",hideTitle: true,- quiet: true+ quiet: true,+ focusEmbed: true});const [ file ] = (execute.mock.calls[0][1] as { file: File[] }).file;expect([ file.name, file.type ])diff --git a/packages/ckeditor5/src/plugins/file_upload/file_upload_ui.ts b/packages/ckeditor5/src/plugins/file_upload/file_upload_ui.tsindex 4eed96066f..8d2eb7a7fd 100644--- a/packages/ckeditor5/src/plugins/file_upload/file_upload_ui.ts+++ b/packages/ckeditor5/src/plugins/file_upload/file_upload_ui.ts@@ -104,7 +104,8 @@ export default class FileUploadUI extends Plugin {asEmbed: true,boxSize: "medium",hideTitle: true,- quiet: true+ quiet: true,+ focusEmbed: true});editor.editing.view.focus();});diff --git a/packages/ckeditor5/src/plugins/file_upload/fileuploadcommand.spec.ts b/packages/ckeditor5/src/plugins/file_upload/fileuploadcommand.spec.tsindex 364c945634..4bb83d6af8 100644--- a/packages/ckeditor5/src/plugins/file_upload/fileuploadcommand.spec.ts+++ b/packages/ckeditor5/src/plugins/file_upload/fileuploadcommand.spec.ts@@ -17,7 +17,7 @@ import { createTestEditor } from "../../../test/editor-kit.js";import { installGlobMock } from "../../../test/globals-test-kit.js";import ContentEmbed from "../content_embed/content_embed.js";import { isUploadAsLink } from "../uploadimage.js";-import FileUploadCommand, { isQuietUpload } from "./fileuploadcommand.js";+import FileUploadCommand, { isFocusUpload, isQuietUpload } from "./fileuploadcommand.js";/*** Minimal plugin that registers the 'reference' model schema AND the downcast@@ -202,16 +202,18 @@ describe("FileUploadCommand", () => {expect(getEmbedBoxSize).not.toHaveBeenCalled();});- it("marks the loaders of a quiet upload, and only those", () => {+ it("marks the loaders of a quiet upload and of a focus upload, and only those", () => {installGlobMock({ getComponentByEl: () => ({}) });setModelData(editor.model, "<paragraph>[]</paragraph>");const createLoaderSpy = vi.spyOn(editor.plugins.get(FileRepository), "createLoader");editor.execute("fileUpload", { file: [ new File(["1"], "one.txt") ] });editor.execute("fileUpload", { file: [ new File(["2"], "two.txt") ], quiet: true });+ editor.execute("fileUpload", { file: [ new File(["3"], "three.txt") ], focusEmbed: true });- expect(createLoaderSpy.mock.results.map(({ value }) => isQuietUpload(value as FileLoader)))- .toEqual([ false, true ]);+ const loaders = createLoaderSpy.mock.results.map(({ value }) => value as FileLoader);+ expect(loaders.map(isQuietUpload)).toEqual([ false, true, false ]);+ expect(loaders.map(isFocusUpload)).toEqual([ false, false, true ]);});it("marks the loader of every file to upload as a link, for an embed too", () => {diff --git a/packages/ckeditor5/src/plugins/file_upload/fileuploadcommand.ts b/packages/ckeditor5/src/plugins/file_upload/fileuploadcommand.tsindex 1d8f93b300..c79359bc3c 100644--- a/packages/ckeditor5/src/plugins/file_upload/fileuploadcommand.ts+++ b/packages/ckeditor5/src/plugins/file_upload/fileuploadcommand.ts@@ -20,15 +20,23 @@ export interface FileUploadOptions {hideTitle?: 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. */+ focusEmbed?: boolean;}const quietLoaders = new WeakSet<FileLoader>();+const focusLoaders = new WeakSet<FileLoader>();/** Whether the upload of `loader` is left out of the `upload` event. */export function isQuietUpload(loader: FileLoader) {return quietLoaders.has(loader);}+/** Whether the embed of the upload of `loader` takes the focus once the upload ends. */+export function isFocusUpload(loader: FileLoader) {+ return focusLoaders.has(loader);+}+/*** Uploads files as attachments of the note and inserts a reference link to each, separated by* spaces. Pictures are linked too, rather than shown. With `asEmbed`, each file is embedded@@ -42,7 +50,8 @@ export default class FileUploadCommand extends Command {this.isEnabled = !!position && model.schema.checkChild(position, "reference");}- override execute({ file: files, asEmbed, boxSize, hideTitle, quiet }: FileUploadOptions) {+ override execute(options: FileUploadOptions) {+ const { file: files, asEmbed, boxSize, hideTitle, quiet, focusEmbed } = options;const model = this.editor.model;const fileRepository = this.editor.plugins.get(FileRepository);@@ -58,6 +67,9 @@ export default class FileUploadCommand extends Command {if (quiet) {quietLoaders.add(loader);}+ if (focusEmbed) {+ focusLoaders.add(loader);+ }if (asEmbed) {insertEmbedPlaceholder(writer, model, loader.id, file.name, {diff --git a/packages/ckeditor5/src/plugins/file_upload/fileuploadediting.spec.ts b/packages/ckeditor5/src/plugins/file_upload/fileuploadediting.spec.tsindex ef792cd016..1a23dc872c 100644--- a/packages/ckeditor5/src/plugins/file_upload/fileuploadediting.spec.ts+++ b/packages/ckeditor5/src/plugins/file_upload/fileuploadediting.spec.ts@@ -603,10 +603,12 @@ class ReferenceSchema extends Plugin {describe("FileUploadEditing with embeds", () => {it("completes an embed placeholder with the attachment it uploaded", async () => {const loadEmbeddedAttachment = vi.fn();+ const focusContentEmbed = vi.fn();installGlobMock({getComponentByEl: () => ({getEmbedBoxSize: () => "small",- loadEmbeddedAttachment+ loadEmbeddedAttachment,+ focusContentEmbed})});const editor = await createTestEditor([@@ -628,5 +630,30 @@ describe("FileUploadEditing with embeds", () => {);editor.editing.view.getDomRoot()?.querySelectorAll("div.include-note-wrapper");expect(loadEmbeddedAttachment).toHaveBeenCalledWith("att1", expect.anything(), "small");+ expect(focusContentEmbed).not.toHaveBeenCalled();+ });++ it("asks the host to focus the embed of a focus upload, before it renders", async () => {+ const calls: string[] = [];+ installGlobMock({+ getComponentByEl: () => ({+ loadEmbeddedAttachment: (id: string) => calls.push(`load ${id}`),+ focusContentEmbed: (id: string) => calls.push(`focus ${id}`)+ })+ });+ const editor = await createTestEditor([+ Essentials, Paragraph, FileRepository, Notification, Clipboard, ReferenceSchema,+ ContentEmbed, FileUploadEditing+ ]);+ const controls = installUploadAdapter(editor);+ setModelData(editor.model, "<paragraph>[]</paragraph>");++ const file = new File(["{}"], "canvas.json");+ editor.execute("fileUpload", { file: [ file ], asEmbed: true, focusEmbed: true });+ await waitFor(() => controls.uploadCalled());+ controls.resolveUpload({ default: "#root/owner?viewMode=attachments&attachmentId=att1" });+ await waitFor(() => !getModelData(editor.model).includes("uploadId"));++ expect(calls).toEqual([ "focus att1", "load att1" ]);});});diff --git a/packages/ckeditor5/src/plugins/file_upload/fileuploadediting.ts b/packages/ckeditor5/src/plugins/file_upload/fileuploadediting.tsindex 38b15e9519..32ba1a0d01 100644--- a/packages/ckeditor5/src/plugins/file_upload/fileuploadediting.ts+++ b/packages/ckeditor5/src/plugins/file_upload/fileuploadediting.ts@@ -9,7 +9,7 @@ import {type ViewRange} from 'ckeditor5';import { getAttachmentId } from '../referencelink.js';-import FileUploadCommand, { isQuietUpload } from './fileuploadcommand';+import FileUploadCommand, { isFocusUpload, isQuietUpload } from './fileuploadcommand';/** A file attachment upload, announced by the `upload` event of `FileUploadEditing`. */export interface FileUploadData {@@ -145,9 +145,16 @@ export default class FileUploadEditing extends Plugin {return promise;} ).then( data => {+ const attachmentId = getAttachmentId( data.default );+ // Before `attachmentId` is set: setting it makes the host render the embed.+ const isEmbed = fileElement.is( 'element', 'contentEmbed' );+ if ( attachmentId && isEmbed && isFocusUpload( loader ) ) {+ glob.getComponentByEl<EditorComponent>( editor.editing.view.getDomRoot() )+ .focusContentEmbed?.( attachmentId );+ }+model.enqueueChange( { isUndoable: false }, writer => {- if ( fileElement.is( 'element', 'contentEmbed' ) ) {- const attachmentId = getAttachmentId( data.default );+ if ( isEmbed ) {writer.setAttribute( 'attachmentId', attachmentId, fileElement );} else {writer.setAttribute( 'href', data.default, fileElement );diff --git a/packages/ckeditor5/src/plugins/uploadimage.spec.ts b/packages/ckeditor5/src/plugins/uploadimage.spec.tsindex 0f9b4e8521..bafe7f03df 100644--- a/packages/ckeditor5/src/plugins/uploadimage.spec.ts+++ b/packages/ckeditor5/src/plugins/uploadimage.spec.ts@@ -167,12 +167,14 @@ describe("UploadimagePlugin", () => {installGlobMock({getHeaders,getActiveContextNote: () => ({ noteId: "noteAbc" }),- getComponentByEl: () => ({ getNoteId: () => "editorNote" })+ getComponentByEl: () => ({ componentId: "editor1", getNoteId: () => "editorNote" })});void createAdapter(new File(["content"], "pic.png", { type: "image/png" })).upload();expect((await awaitSentXhr()).url).toBe("api/notes/editorNote/attachments/upload");+ // As a change of the editor, which then does not redraw the embed it completes.+ expect(getHeaders).toHaveBeenCalledWith({ "trilium-component-id": "editor1" });});it("asks for a link only for a loader marked to upload as one", async () => {diff --git a/packages/ckeditor5/src/plugins/uploadimage.ts b/packages/ckeditor5/src/plugins/uploadimage.tsindex 1f5224f2ce..8e2c0eedc4 100644--- a/packages/ckeditor5/src/plugins/uploadimage.ts+++ b/packages/ckeditor5/src/plugins/uploadimage.ts@@ -85,13 +85,15 @@ class Adapter implements UploadAdapter {* @private*/_initRequest() {- return glob.getHeaders().then(headers => {+ const domRoot = this.editor.editing.view.getDomRoot();+ const component = glob.getComponentByEl<EditorComponent>( domRoot );++ // Sent as a change of the host, which then does not redraw the links and embeds it shows.+ return glob.getHeaders({ "trilium-component-id": component?.componentId }).then(headers => {const xhr = this.xhr = new XMLHttpRequest();// The note the editor holds, which is not the active tab's in a split or the quick edit// popup. A host that does not say falls back to the active tab's.- const domRoot = this.editor.editing.view.getDomRoot();- const component = glob.getComponentByEl<EditorComponent>( domRoot );const noteId = component?.getNoteId?.() ?? glob.getActiveContextNote().noteId;const query = isUploadAsLink(this.loader) ? "?link=true" : "";