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: add support for editing included text notes
Adorian Doran9c30e92fc5fe
diff --git a/apps/client/src/services/content_renderer.spec.ts b/apps/client/src/services/content_renderer.spec.tsindex 5cee53ad32..e325bad4fb 100644--- a/apps/client/src/services/content_renderer.spec.ts+++ b/apps/client/src/services/content_renderer.spec.ts@@ -113,6 +113,10 @@ const codeEmbedComponent = vi.fn((_props: any): VNode<any> =>h("span", { class: "mock-code-embed-marker" }));vi.mock("../widgets/type_widgets/code/CodeEmbed", () => ({ default: codeEmbedComponent }));+const textEmbedComponent = vi.fn((_props: any): VNode<any> =>+ h("span", { class: "mock-text-embed-marker" }));+vi.mock("../widgets/type_widgets/text/TextEmbed", () => ({ default: textEmbedComponent }));+// `addHook` is a no-op here: sanitize_content.ts registers a DOMPurify hook at// module load (pulled in transitively), which would otherwise throw against this mock.vi.mock("dompurify", () => ({ default: { sanitize: (s: string) => s, addHook: () => {} } }));@@ -415,6 +419,45 @@ describe("getRenderedContent editable code", () => {expect(attachmentEditor.release).toHaveBeenCalledWith(att.attachmentId);});+ it("mounts TextEmbed for an interactive text note, with a preview to render again", async () => {+ const note = buildNote({ title: "Doc", type: "text", content: "<p>Hi</p>" });+ const noteEditor = buildEditor();++ const { type, $renderedContent } = await getRenderedContent(note, {+ interactive: true,+ embedsAsReferenceLinks: true,+ noteEditor+ });++ expect(type).toBe("text");+ expect($renderedContent.find(".text-embed[data-interactive-mount]").length).toBe(1);+ const props = textEmbedComponent.mock.calls[0][0];+ expect(props.note).toBe(note);+ expect(props.content).toBe("<p>Hi</p>");+ expect(props.preview.querySelector(".from-render-text")).not.toBeNull();+ expect(renderText).toHaveBeenLastCalledWith(+ note, expect.anything(), expect.objectContaining({ embedsAsReferenceLinks: true }));+ expect(props.editor.canEdit()).toBe(true);+ expect(noteEditor.canEdit).toHaveBeenCalledWith(note);++ const again = await props.renderPreview();+ expect(again).not.toBe(props.preview);+ expect(again.querySelector(".from-render-text")).not.toBeNull();+ });++ it("edits only code and text notes", async () => {+ const json = buildNote({+ title: "Data", type: "file", mime: "application/json", content: "{}"+ });+ const { $renderedContent } = await getRenderedContent(json, {+ interactive: true,+ noteEditor: buildEditor()+ });++ expect($renderedContent.find("pre > code").text()).toBe("{}");+ expect(codeEmbedComponent).not.toHaveBeenCalled();+ });+it("keeps the static preview without an editor, or outside an embed", async () => {const note = buildNote({title: "Script", type: "code", mime: "text/javascript", content: "x"@@ -431,6 +474,11 @@ describe("getRenderedContent editable code", () => {expect(results.map(({ $renderedContent }) => $renderedContent.find("pre > code").text())).toEqual([ "x", "y", "x" ]);expect(codeEmbedComponent).not.toHaveBeenCalled();++ const text = buildNote({ title: "Doc", type: "text", content: "<p>Hi</p>" });+ const { $renderedContent } = await getRenderedContent(text, { noteEditor: buildEditor() });+ expect($renderedContent.find(".from-render-text").length).toBe(1);+ expect(textEmbedComponent).not.toHaveBeenCalled();});});@@ -995,7 +1043,7 @@ describe("getRenderedContent canvas drawing rendering", () => {it("mounts the editor for an interactive attachment, with its saving editor", async () => {const att = buildAttachment({ role: "file", mime: canvasMime });- const attachmentEditor = { canEdit: vi.fn() } as any;+ const attachmentEditor = { canEdit: vi.fn(() => true), release: vi.fn() } as any;const { type, $renderedContent } = await getRenderedContent(att, {interactive: true,@@ -1005,8 +1053,12 @@ describe("getRenderedContent canvas drawing rendering", () => {expect(type).toBe("canvasDrawing");const $drawing = $renderedContent.find(".canvas-drawing[data-interactive-mount]");expect($drawing.find(".mock-canvas-drawing-marker").length).toBe(1);- expect(canvasDrawingComponent).toHaveBeenCalledWith(- { attachment: att, editor: attachmentEditor }, expect.anything());+ const { attachment, editor } = canvasDrawingComponent.mock.calls[0][0];+ expect(attachment).toBe(att);+ expect(editor.canEdit()).toBe(true);+ editor.release();+ expect(attachmentEditor.canEdit).toHaveBeenCalledWith(att);+ expect(attachmentEditor.release).toHaveBeenCalledWith(att.attachmentId);expect(renderCanvasDrawingPicture).not.toHaveBeenCalled();});diff --git a/apps/client/src/services/content_renderer.ts b/apps/client/src/services/content_renderer.tsindex 5652a7f9a7..c313ffbbfb 100644--- a/apps/client/src/services/content_renderer.ts+++ b/apps/client/src/services/content_renderer.ts@@ -125,6 +125,9 @@ export interface NoteEditor {const CODE_MIME_TYPES = new Set(["application/json"]);+/** The types of the notes that an embed can edit in place. */+const EDITABLE_NOTE_TYPES = new Set<string>([ "code", "text" ]);+/** The media types of attached files, besides `text/*` and JSON, that show as code. */const ATTACHED_CODE_MIME_TYPES = new Set(["application/javascript", "application/x-javascript", "application/x-sql"@@ -160,6 +163,9 @@ export async function getRenderedContent(this: {} | { ctx: string }, entity: FNo// view type is excluded: it's the only view that re-propagates `interactive` to its tiles, so// skipping it here is what keeps an embedded collection from recursing into itself.await renderCollection(entity, $renderedContent);+ } else if (type === "text" && options.interactive && options.noteEditor+ && entity instanceof FNote) {+ await renderEditableText(entity, $renderedContent, options);} else if (type === "text" || type === "book") {await renderText(entity, $renderedContent, options);} else if (type === "markdown") {@@ -242,6 +248,40 @@ export async function getRenderedContent(this: {} | { ctx: string }, entity: FNo};}+/**+ * Renders a text note that `TextEmbed` edits in place while the Editable toggle of its embed is+ * on.+ */+async function renderEditableText(+ note: FNote,+ $renderedContent: JQuery<HTMLElement>,+ options: RenderOptions+) {+ const renderPreview = async () => {+ const $preview = $("<div>");+ await renderText(note, $preview, options);+ return $preview[0];+ };+ const [ preview, blob, { default: TextEmbed } ] = await Promise.all([+ renderPreview(),+ note.getBlob(),+ import("../widgets/type_widgets/text/TextEmbed")+ ]);++ const $container = $('<div class="text-embed">');+ const container = $container.get(0);+ if (container) {+ await mountInteractiveWidget(h(TextEmbed, {+ note,+ editor: getContentEditor(note, options),+ content: blob?.content ?? "",+ preview,+ renderPreview+ }), container);+ }+ $renderedContent.append($container);+}+/*** Renders a markdown note by converting its source to CKEditor-compatible HTML,* then running the same post-render pipeline as text notes (embedded notes,@@ -366,29 +406,36 @@ export interface ContentEditor {componentId?: string;}+/** `editor`, saving the changes to `attachment`. */+export function bindAttachmentEditor(+ editor: AttachmentEditor,+ attachment: FAttachment+): ContentEditor {+ return {+ canEdit: () => editor.canEdit(attachment),+ getUnsavedContent: () => editor.getUnsavedContent(attachment.attachmentId),+ scheduleSave: (getContent) => editor.scheduleSave(attachment, getContent),+ release: () => editor.release(attachment.attachmentId)+ };+}+/** The editor of `options` that saves the changes to `entity`, or `undefined`. */function getContentEditor(entity: FNote | FAttachment,options: RenderOptions): ContentEditor | undefined {if (entity instanceof FAttachment) {- const editor = options.attachmentEditor;- return editor && {- canEdit: () => editor.canEdit(entity),- getUnsavedContent: () => editor.getUnsavedContent(entity.attachmentId),- scheduleSave: (getContent) => editor.scheduleSave(entity, getContent),- release: () => editor.release(entity.attachmentId)- };+ return options.attachmentEditor && bindAttachmentEditor(options.attachmentEditor, entity);}const editor = options.noteEditor;- return editor && {+ return editor && EDITABLE_NOTE_TYPES.has(entity.type) ? {canEdit: () => editor.canEdit(entity),getUnsavedContent: () => editor.getUnsavedContent(entity.noteId),scheduleSave: (getContent) => editor.scheduleSave(entity, getContent),release: () => editor.release(entity.noteId),componentId: editor.componentId- };+ } : undefined;}async function renderImage(entity: FNote | FAttachment, $renderedContent: JQuery<HTMLElement>, options: RenderOptions = {}) {@@ -453,7 +500,7 @@ async function renderCanvasDrawing(if (container) {await mountInteractiveWidget(h(CanvasDrawing, {attachment: entity,- editor: options.attachmentEditor+ editor: getContentEditor(entity, options)}), container);}$renderedContent.append($container);diff --git a/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.spec.tsx b/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.spec.tsxindex f1b533dc31..48f902ba53 100644--- a/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.spec.tsx+++ b/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.spec.tsx@@ -5,8 +5,9 @@ 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";+import type { ContentEditor } from "../../../services/content_renderer";import { buildNote } from "../../../test/easy-froca";+import { getContentEmbedTools } from "../text/content_embed_tools";vi.mock("@excalidraw/excalidraw", () => ({ exportToSvg: vi.fn() }));vi.mock("./Canvas", () => ({ CanvasEditor: MockCanvasEditor }));@@ -19,7 +20,7 @@ vi.mock("./persistence", () => ({getInlineFiles: () => ({})}));const { detailEditor, attachmentEditorMounts, canvasEditorMounts } = vi.hoisted(() => ({- detailEditor: { canEdit: () => true, release: () => {} },+ detailEditor: { canEdit: () => true, release: vi.fn() },attachmentEditorMounts: vi.fn(),canvasEditorMounts: vi.fn()}));@@ -500,7 +501,7 @@ describe("CanvasDrawing", () => {box.remove();});- async function mount(editor?: AttachmentEditor) {+ async function mount(editor?: ContentEditor) {await act(async () => {render(<CanvasDrawing attachment={ATTACHMENT} editor={editor} />, box);});@@ -533,7 +534,7 @@ describe("CanvasDrawing", () => {}it("follows the Editable toggle of its embed, saving all along", async () => {- const editor = { canEdit: () => true, release: vi.fn() } as unknown as AttachmentEditor;+ const editor = { canEdit: () => true, release: vi.fn() } as unknown as ContentEditor;const embed = document.createElement("figure");embed.className = "include-note";embed.setAttribute("data-editable", "true");@@ -542,6 +543,8 @@ describe("CanvasDrawing", () => {await mount(editor);expect(getEditingState()).toEqual({ isReadOnly: false, menu: true, tools: true });+ // `CanvasEmbedTools`, not rendered by the mock editor, adds the only buttons.+ expect(getContentEmbedTools(embed)).toBeNull();await setEmbedEditable(embed, false);expect(getEditingState()).toEqual({ isReadOnly: true, menu: false, tools: false });@@ -554,7 +557,7 @@ describe("CanvasDrawing", () => {// 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);+ 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()@@ -563,7 +566,7 @@ describe("CanvasDrawing", () => {});it("is editable outside an embed, which has no Editable toggle", async () => {- await mount({ canEdit: () => true, release: vi.fn() } as unknown as AttachmentEditor);+ await mount({ canEdit: () => true, release: vi.fn() } as unknown as ContentEditor);expect(getEditingState()).toEqual({ isReadOnly: false, menu: true, tools: true });});@@ -649,9 +652,9 @@ describe("CanvasDrawing", () => {await mountDetail("Owner");expect(getEditingState()).toEqual({ isReadOnly: false, menu: true, tools: undefined });- expect(persistenceArgs).toHaveBeenLastCalledWith(- ATTACHMENT, detailEditor, expect.anything(), expect.anything()- );+ const detailDrawingEditor = persistenceArgs.mock.lastCall?.[1] as ContentEditor;+ detailDrawingEditor.release();+ expect(detailEditor.release).toHaveBeenCalledWith("a1");render(null, box);await mountDetail("Locked owner", { "#readOnly": "" });diff --git a/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.tsx b/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.tsxindex 0c0fbd65c4..9646242457 100644--- a/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.tsx+++ b/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.tsx@@ -4,18 +4,19 @@ import { exportToSvg } from "@excalidraw/excalidraw";import type { AppState, ExcalidrawImperativeAPI } from "@excalidraw/excalidraw/types";import clsx from "clsx";import type { RefObject } from "preact";-import { useEffect, useRef, useState } from "preact/hooks";+import { useEffect, useMemo, useRef, useState } from "preact/hooks";import type NoteContext from "../../../components/note_context";import type FAttachment from "../../../entities/fattachment";import type FNote from "../../../entities/fnote";-import type { AttachmentEditor } from "../../../services/content_renderer";+import { bindAttachmentEditor, type ContentEditor } from "../../../services/content_renderer";import options from "../../../services/options";import { getEffectiveThemeStyle } from "../../../services/theme";import { isDesktop } from "../../../services/utils";import { useColorScheme, useEffectiveReadOnly } from "../../react/hooks";import { useAttachmentEditor } from "../text/attachment_saves";-import { useContentEmbedEvent, useIsContentEmbedEditable } from "../text/content_embed_tools";+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";@@ -24,7 +25,7 @@ import { getInlineFiles, parseContent, useCanvasDrawingPersistence } from "./perinterface CanvasDrawingProps {attachment: FAttachment;/** Saves the changes. Without it, or for an attachment of another note, it is read-only. */- editor?: AttachmentEditor;+ editor?: ContentEditor;}/**@@ -35,9 +36,13 @@ export default function CanvasDrawing({ attachment, editor }: CanvasDrawingPropsconst rootRef = useRef<HTMLDivElement>(null);const apiRef = useRef<ExcalidrawImperativeAPI>(null);const colorScheme = useColorScheme();- const canEdit = !!editor?.canEdit(attachment) && !options.is("databaseReadonly");- const isEmbedEditable = useIsContentEmbedEditable(rootRef);- const isEditable = canEdit && isEmbedEditable;+ // `CanvasEmbedTools` adds the buttons of the drawing to the toolbar of the embed.+ const { canEdit, isEditing: isEditable } = useEditableEmbed(rootRef, {+ editor,+ note: null,+ tools: null,+ focusTarget: ".excalidraw"+ });// Follows `canEdit` rather than the toggle, so that turning editing off keeps a pending save.const persistence = useCanvasDrawingPersistence(attachment,@@ -46,7 +51,6 @@ export default function CanvasDrawing({ attachment, editor }: CanvasDrawingPropscolorScheme);const isToolbarOverPanel = useIsToolbarOverPanel(rootRef);- useFocusFromEmbedBox(rootRef);const isRecentering = useRecenteringOnFullscreen(rootRef, apiRef);useSidePanels(rootRef, isEditable);useTopLayerContextMenu(rootRef, apiRef);@@ -118,7 +122,11 @@ export function CanvasDrawingDetail({attachment, note, noteContext, revision}: CanvasDrawingDetailProps) {// Outlives the drawing loaded again for each revision, which starts from its unsaved changes.- const editor = useAttachmentEditor(note, noteContext);+ const attachmentEditor = useAttachmentEditor(note, noteContext);+ const editor = useMemo(+ () => bindAttachmentEditor(attachmentEditor, attachment),+ [ attachmentEditor, attachment ]+ );return (<DetailDrawing@@ -132,7 +140,7 @@ export function CanvasDrawingDetail({}interface DetailDrawingProps extends Omit<CanvasDrawingDetailProps, "revision"> {- editor: AttachmentEditor;+ editor: ContentEditor;}/** The drawing of `CanvasDrawingDetail`, saved by `editor`. */@@ -140,7 +148,7 @@ function DetailDrawing({ attachment, note, noteContext, editor }: DetailDrawingPconst apiRef = useRef<ExcalidrawImperativeAPI>(null);const colorScheme = useColorScheme();const isNoteReadOnly = useEffectiveReadOnly(note, noteContext);- const canEdit = editor.canEdit(attachment) && !isNoteReadOnly+ const canEdit = editor.canEdit() && !isNoteReadOnly&& !options.is("databaseReadonly");const persistence = useCanvasDrawingPersistence(attachment,@@ -191,35 +199,6 @@ function useRecenteringOnFullscreen(return isRecentering;}-/**- * Moves the focus into Excalidraw when the embed box around the drawing holds it. Excalidraw- * renders its container only once its language loads, which can be after the box took the focus.- */-function useFocusFromEmbedBox(rootRef: RefObject<HTMLElement | null>) {- 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/canvas/persistence.spec.tsx b/apps/client/src/widgets/type_widgets/canvas/persistence.spec.tsxindex ebabae5ecf..5d2bace414 100644--- a/apps/client/src/widgets/type_widgets/canvas/persistence.spec.tsx+++ b/apps/client/src/widgets/type_widgets/canvas/persistence.spec.tsx@@ -17,7 +17,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import type FAttachment from "../../../entities/fattachment";import type FNote from "../../../entities/fnote";-import type { AttachmentEditor } from "../../../services/content_renderer";+import type { ContentEditor } from "../../../services/content_renderer";import server from "../../../services/server";import { buildNote } from "../../../test/easy-froca";import useCanvasPersistence, { useCanvasDrawingPersistence } from "./persistence";@@ -217,7 +217,7 @@ describe("useCanvasDrawingPersistence", () => {function DrawingProbe({ attachment, editor, apiRef }: {attachment: FAttachment;- editor: AttachmentEditor | undefined;+ editor: ContentEditor | undefined;apiRef: RefObject<ExcalidrawImperativeAPI | null>;}) {drawingProps = useCanvasDrawingPersistence(attachment, editor, apiRef, "light");@@ -251,10 +251,10 @@ describe("useCanvasDrawingPersistence", () => {getUnsavedContent: vi.fn(() => unsavedContent),scheduleSave: vi.fn(),release: vi.fn()- } satisfies AttachmentEditor;+ } satisfies ContentEditor;}- async function mount(attachment: FAttachment, editor: AttachmentEditor | undefined) {+ async function mount(attachment: FAttachment, editor: ContentEditor | undefined) {const api = {getSceneElements: () => sceneElements,getAppState: () => appState,@@ -316,8 +316,7 @@ describe("useCanvasDrawingPersistence", () => {sceneElements = [ { ...loaded[0], version: 4 }, loaded[1] ];change();expect(editor.scheduleSave).toHaveBeenCalledTimes(1);- const [ savedAttachment, getContent ] = editor.scheduleSave.mock.calls[0];- expect(savedAttachment).toBe(attachment);+ const [ getContent ] = editor.scheduleSave.mock.calls[0];expect(JSON.parse(getContent())).toEqual({type: "excalidraw",version: 2,@@ -335,7 +334,7 @@ describe("useCanvasDrawingPersistence", () => {expect(editor.scheduleSave).toHaveBeenCalledTimes(2);act(() => render(null, container));- expect(editor.release).toHaveBeenCalledWith("a1");+ expect(editor.release).toHaveBeenCalledOnce();});it("saves nothing without an editor", async () => {diff --git a/apps/client/src/widgets/type_widgets/canvas/persistence.ts b/apps/client/src/widgets/type_widgets/canvas/persistence.tsindex 498cde410a..fd42233103 100644--- a/apps/client/src/widgets/type_widgets/canvas/persistence.ts+++ b/apps/client/src/widgets/type_widgets/canvas/persistence.ts@@ -8,7 +8,7 @@ import { useEffect, useLayoutEffect, useRef, useState } from "preact/hooks";import NoteContext from "../../../components/note_context";import type FAttachment from "../../../entities/fattachment";import FNote from "../../../entities/fnote";-import type { AttachmentEditor } from "../../../services/content_renderer";+import type { ContentEditor } from "../../../services/content_renderer";import server from "../../../services/server";import { SavedData, useEditorSpacedUpdate } from "../../react/hooks";import { buildNewImageAttachments, CANVAS_EXPORT_TITLE, IMAGE_ROLE, loadImageAttachments } from "./image_attachments";@@ -350,7 +350,7 @@ export default function useCanvasPersistence(note: FNote, noteContext: NoteConte*/export function useCanvasDrawingPersistence(attachment: FAttachment,- editor: AttachmentEditor | undefined,+ editor: ContentEditor | undefined,apiRef: RefObject<ExcalidrawImperativeAPI | null>,theme: AppState["theme"]): Partial<ExcalidrawProps> {@@ -361,7 +361,7 @@ export function useCanvasDrawingPersistence(const initialSceneAppliedRef = useRef(true);const [ initialData ] = useState(async (): Promise<ExcalidrawInitialDataState> => {- const unsavedContent = editor?.getUnsavedContent(attachment.attachmentId);+ const unsavedContent = editor?.getUnsavedContent();const blobContent = unsavedContent === undefined? (await attachment.getBlob())?.content ?? "": unsavedContent;@@ -381,7 +381,7 @@ export function useCanvasDrawingPersistence(// A layout cleanup runs during the unmount, before Excalidraw's `componentWillUnmount()` empties// the scene that `release()` reads; a passive one runs after paint.- useLayoutEffect(() => () => editor?.release(attachment.attachmentId), [ editor, attachment ]);+ useLayoutEffect(() => () => editor?.release(), [ editor ]);return {initialData,@@ -407,7 +407,7 @@ export function useCanvasDrawingPersistence(if (sceneVersion === currentSceneVersion.current && !isAppStateChanged) return;currentSceneVersion.current = sceneVersion;- editor.scheduleSave(attachment, () => serializeDrawing(api));+ editor.scheduleSave(() => serializeDrawing(api));}};}diff --git a/apps/client/src/widgets/type_widgets/code/CodeEmbed.spec.tsx b/apps/client/src/widgets/type_widgets/code/CodeEmbed.spec.tsxindex 32a74a8f99..1342d27a33 100644--- a/apps/client/src/widgets/type_widgets/code/CodeEmbed.spec.tsx+++ b/apps/client/src/widgets/type_widgets/code/CodeEmbed.spec.tsx@@ -39,7 +39,7 @@ describe("CodeEmbed", () => {const note = buildCodeNote("print(1)");const preview = buildPreview("print(1)");const { figure } = await mount(note, buildEditor(), { preview });- expect(figure.querySelector(".code-embed-preview")?.firstChild).toBe(preview);+ expect(figure.querySelector(".editable-embed-preview")?.firstChild).toBe(preview);expect(getContentEmbedTools(figure)?.hasEditableFlag).toBe(true);const { figure: locked } = await mount(note, buildEditor({ canEdit: () => false }));@@ -58,7 +58,7 @@ describe("CodeEmbed", () => {const view = await findView(figure);expect(view.state.doc.toString()).toBe("print(1)");- expect(figure.querySelector(".code-embed-preview")).toBeNull();+ expect(figure.querySelector(".editable-embed-preview")).toBeNull();expect(editor.scheduleSave).not.toHaveBeenCalled();act(() => view.dispatch({ changes: { from: 0, insert: "# " } }));@@ -80,7 +80,7 @@ describe("CodeEmbed", () => {expect(editor.release).toHaveBeenCalledOnce();await vi.waitFor(() => {- expect(figure.querySelector(".code-embed-preview")?.textContent).toBe("ab");+ expect(figure.querySelector(".editable-embed-preview")?.textContent).toBe("ab");});expect(figure.querySelector(".cm-editor")).toBeNull();});diff --git a/apps/client/src/widgets/type_widgets/code/CodeEmbed.tsx b/apps/client/src/widgets/type_widgets/code/CodeEmbed.tsxindex d5228c66c7..104f3d7c86 100644--- a/apps/client/src/widgets/type_widgets/code/CodeEmbed.tsx+++ b/apps/client/src/widgets/type_widgets/code/CodeEmbed.tsx@@ -1,17 +1,15 @@import "./CodeEmbed.css";-import type { RefObject } from "preact";-import { lazy, Suspense } from "preact/compat";-import { useEffect, useLayoutEffect, useRef, useState } from "preact/hooks";+import { lazy } from "preact/compat";+import { useEffect, useRef, useState } from "preact/hooks";import type FAttachment from "../../../entities/fattachment";import FNote from "../../../entities/fnote";import { type ContentEditor, renderCodePreview } from "../../../services/content_renderer";-import options from "../../../services/options";-import { useNoteBlob, useNoteLabelBoolean, useNoteProperty } from "../../react/hooks";+import { useNoteBlob, useNoteProperty } from "../../react/hooks";import {- type ContentEmbedToolProvider, registerContentEmbedTools, useIsContentEmbedEditable-} from "../text/content_embed_tools";+ EditableEmbedContent, useEditableEmbed, useEmbedPreview+} from "../text/editable_embed";const CodeEmbedEditor = lazy(() => import("./CodeEmbedEditor"));@@ -36,90 +34,34 @@ export default function CodeEmbed({}: CodeEmbedProps) {const rootRef = useRef<HTMLDivElement>(null);const note = entity instanceof FNote ? entity : null;- const [ isNoteReadOnly ] = useNoteLabelBoolean(note, "readOnly");- const canEdit = editor.canEdit() && !isNoteReadOnly && !options.is("databaseReadonly");- const isEmbedEditable = useIsContentEmbedEditable(rootRef);- const isEditing = canEdit && isEmbedEditable;+ const { isEditing } = useEditableEmbed(rootRef, { editor, note, focusTarget: ".cm-content" });const [ content, setContent ] = useState(initialContent);const mime = useNoteProperty(note, "mime") ?? initialMime;- useEditableFlag(rootRef, canEdit);useChangesFromElsewhere(note, editor, setContent);- useFocusFromEmbedBox(rootRef, isEditing);-- const isInitial = content === initialContent && mime === initialMime;- const previewView = (- <CodePreview- content={content}- mime={mime}- initialPreview={isInitial ? preview : undefined}- />+ const shownPreview = useEmbedPreview(+ preview,+ `${mime}\n${content}`,+ () => renderCodePreview(content, mime));return (- <div ref={rootRef} className="code-embed-content">- {isEditing ? (- <Suspense fallback={previewView}>- <CodeEmbedEditor- note={note}- editor={editor}- content={content}- mime={mime}- onClose={setContent}- />- </Suspense>- ) : previewView}- </div>+ <EditableEmbedContent+ rootRef={rootRef}+ className="code-embed-content"+ isEditing={isEditing}+ preview={shownPreview}+ >+ <CodeEmbedEditor+ note={note}+ editor={editor}+ content={content}+ mime={mime}+ onClose={setContent}+ />+ </EditableEmbedContent>);}-interface CodePreviewProps {- content: string;- mime: string;- /** The highlighted `content`, when it is rendered already. */- initialPreview?: HTMLElement;-}--/** The highlighted content. */-function CodePreview({ content, mime, initialPreview }: CodePreviewProps) {- const containerRef = useRef<HTMLDivElement>(null);-- useLayoutEffect(() => {- if (initialPreview) {- containerRef.current?.replaceChildren(initialPreview);- return;- }-- let isCurrent = true;- renderCodePreview(content, mime).then((preview) => {- if (isCurrent) {- containerRef.current?.replaceChildren(preview);- }- });- return () => {- isCurrent = false;- };- }, [ content, mime, initialPreview ]);-- return <div ref={containerRef} className="code-embed-preview" />;-}--/** Gives the embed that contains `rootRef` its Editable toggle while `canEdit`. */-function useEditableFlag(rootRef: RefObject<HTMLElement | null>, canEdit: boolean) {- useEffect(() => {- const root = rootRef.current;- if (!root || !canEdit) return;-- return registerContentEmbedTools(root, EDITABLE_FLAG_PROVIDER);- }, [ rootRef, canEdit ]);-}--const EDITABLE_FLAG_PROVIDER: ContentEmbedToolProvider = {- hasEditableFlag: true,- getTools: () => [],- execute: () => {},- subscribe: () => () => {}-};-/*** Shows the content that another component saves to `note`. Unsaved changes made in the embed* are kept, and replace that content when they save.@@ -137,16 +79,3 @@ function useChangesFromElsewhere(}}, [ blob ]);}--/** Moves the focus into CodeMirror when the embed box around it takes the focus. */-function useFocusFromEmbedBox(rootRef: RefObject<HTMLElement | null>, isEditing: boolean) {- useEffect(() => {- const root = rootRef.current;- const box = root?.closest<HTMLElement>(".include-note-content");- if (!root || !box || !isEditing) return;-- const forwardFocus = () => root.querySelector<HTMLElement>(".cm-content")?.focus();- box.addEventListener("focus", forwardFocus);- return () => box.removeEventListener("focus", forwardFocus);- }, [ rootRef, isEditing ]);-}diff --git a/apps/client/src/widgets/type_widgets/text/EditableText.tsx b/apps/client/src/widgets/type_widgets/text/EditableText.tsxindex 04d7368c37..0f04ec813e 100644--- a/apps/client/src/widgets/type_widgets/text/EditableText.tsx+++ b/apps/client/src/widgets/type_widgets/text/EditableText.tsx@@ -33,6 +33,7 @@ import { TypeWidgetProps } from "../type_widget";import AttachmentSaves, { useNoteEditor } from "./attachment_saves";import CKEditorWithWatchdog, { CKEditorApi, NotificationEventData, NotificationEventInfo } from "./CKEditorWithWatchdog";import { getContentEmbedTools } from "./content_embed_tools";+import { useEmbedEditors } from "./editable_embed";import getTemplates, { updateTemplateCache } from "./snippets.js";import linkEmbedService from "../../../services/link_embed";import { usesClassicToolbar } from "./toolbar";@@ -78,6 +79,8 @@ export default function EditableText({ note, parentComponent, ntxId, noteContextconst [ attachmentSaves ] = useState(() =>new AttachmentSaves(() => spacedUpdate.scheduleUpdate()));const noteEditor = useNoteEditor(noteContext);+ const { noteEditor: embedNoteEditor, attachmentEditor: embedAttachmentEditor } =+ useEmbedEditors({ noteEditor, attachmentEditor: attachmentSaves });const spacedUpdate = useEditorSpacedUpdate({note,noteContext,@@ -203,7 +206,7 @@ export default function EditableText({ note, parentComponent, ntxId, noteContext});},loadEmbeddedNote(noteId: string, $el: JQuery<HTMLElement>, boxSize?: string) {- return loadEmbeddedNote(noteId, $el, boxSize, { noteEditor });+ return loadEmbeddedNote(noteId, $el, boxSize, { noteEditor: embedNoteEditor });},loadEmbeddedAttachment(attachmentId: string, $el: JQuery<HTMLElement>, boxSize?: string) {const isFocused = focusedAttachmentIdRef.current === attachmentId;@@ -211,7 +214,7 @@ export default function EditableText({ note, parentComponent, ntxId, noteContextfocusedAttachmentIdRef.current = undefined;}return loadEmbeddedAttachment(attachmentId, $el, boxSize, {- attachmentEditor: attachmentSaves,+ attachmentEditor: embedAttachmentEditor,isFocused});},@@ -301,7 +304,7 @@ export default function EditableText({ note, parentComponent, ntxId, noteContextuseTriliumEvent("refreshEmbeddedNote", ({ noteId }) => {if (!containerRef.current) return;- refreshEmbeddedNote(containerRef.current, noteId, { noteEditor });+ refreshEmbeddedNote(containerRef.current, noteId, { noteEditor: embedNoteEditor });});useEffect(() => () => stopWatchingEmbedsRef.current?.(), []);diff --git a/apps/client/src/widgets/type_widgets/text/TextEmbed.spec.tsx b/apps/client/src/widgets/type_widgets/text/TextEmbed.spec.tsxnew file mode 100644index 0000000000..0a2455a529--- /dev/null+++ b/apps/client/src/widgets/type_widgets/text/TextEmbed.spec.tsx@@ -0,0 +1,151 @@+import { render } from "preact";+import { useContext } from "preact/hooks";+import { act } from "preact/test-utils";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import appContext from "../../../components/app_context";+import type FNote from "../../../entities/fnote";+import froca from "../../../services/froca";+import type { ContentEditor } from "../../../services/content_renderer";+import { buildNote } from "../../../test/easy-froca";+import { useTriliumEvent } from "../../react/hooks";+import { ParentComponent } from "../../react/react_utils";+import type { TypeWidgetProps } from "../type_widget";+import { getContentEmbedTools } from "./content_embed_tools";+import { NestedEmbedContext } from "./editable_embed";+import TextEmbed from "./TextEmbed";++const editorAskedToSave = vi.fn();+const editorProps = vi.fn();++/** The text editor, which has a spec of its own. It listens for what a real editor listens for. */+vi.mock("./EditableText", () => ({+ default: (props: TypeWidgetProps) => {+ const isNested = useContext(NestedEmbedContext);+ editorProps({ ...props, isNested });+ useTriliumEvent("beforeNoteContextRemove", editorAskedToSave);+ return <div className="editable-text-stub" />;+ }+}));++const figures: HTMLElement[] = [];++beforeEach(() => {+ // `useEmbeddedNoteContext()` asks the tab manager where the reader is hoisted.+ (appContext as unknown as { tabManager: unknown }).tabManager = {+ getActiveContext: () => undefined,+ getActiveContextNotePath: () => undefined,+ openContextWithNote: async () => undefined+ };+ editorAskedToSave.mockClear();+ editorProps.mockClear();+});++afterEach(() => {+ for (const figure of figures) {+ const box = figure.querySelector(".include-note-content");+ if (box) act(() => render(null, box));+ figure.remove();+ }+ figures.length = 0;+ (appContext as unknown as { tabManager: unknown }).tabManager = undefined;+});++describe("TextEmbed", () => {+ it("shows the preview, and offers the Editable toggle only where it can edit", async () => {+ const preview = buildPreview("Hello");+ const { figure } = await mount(buildTextNote("hello"), buildEditor(), { preview });+ expect(figure.querySelector(".editable-embed-preview")?.firstChild).toBe(preview);+ expect(getContentEmbedTools(figure)?.hasEditableFlag).toBe(true);+ expect(editorProps).not.toHaveBeenCalled();++ const { figure: locked } = await mount(buildTextNote("locked"), undefined);+ expect(getContentEmbedTools(locked)).toBeNull();+ });++ it("edits in a note context of its own, and saves before the editor goes away", async () => {+ const note = buildTextNote("edited");+ const { figure } = await mount(note, buildEditor(), { isEditable: true });++ // The editor module loads on demand, which takes a while under a busy test run.+ await vi.waitFor(() => expect(editorProps).toHaveBeenCalled(), { timeout: 5000 });+ // Mounted once the note context holds the note, with the floating toolbar from the start.+ const props = editorProps.mock.calls[0][0] as TypeWidgetProps & { isNested: boolean };+ expect(props.note).toBe(note);+ expect(props.ntxId).toMatch(/^_embed_/);+ expect(props.noteContext?.ntxId).toBe(props.ntxId);+ expect(props.viewScope?.floatingToolbar).toBe(true);+ expect(props.isNested).toBe(true);+ // The plugins of the editor find their host from its DOM.+ const stub = figure.querySelector<HTMLElement>(".editable-text-stub");+ expect(stub && appContext.getComponentByEl(stub)).toBe(props.parentComponent);+ expect(figure.querySelector(".editable-embed-preview")).toBeNull();++ await act(async () => {+ delete figure.dataset.editable;+ await Promise.resolve();+ });+ expect(editorAskedToSave).toHaveBeenCalledWith({ ntxIds: [ props.ntxId ] });+ expect(figure.querySelector(".editable-text-stub")).toBeNull();+ expect(figure.querySelector(".editable-embed-preview")).not.toBeNull();+ });+});++interface MountOptions {+ preview?: HTMLElement;+ isEditable?: boolean;+}++/** Renders `TextEmbed` in the markup of an embed, as the host does. */+async function mount(note: FNote, editor: ContentEditor | undefined, options: MountOptions = {}) {+ const figure = document.createElement("figure");+ figure.className = "include-note";+ if (options.isEditable) {+ figure.dataset.editable = "true";+ }+ const box = document.createElement("div");+ box.className = "include-note-content";+ figure.append(box);+ document.body.append(figure);+ figures.push(figure);++ const content = (await note.getBlob())?.content ?? "";+ await act(async () => {+ render(+ <ParentComponent.Provider value={appContext}>+ <TextEmbed+ note={note}+ editor={editor}+ content={content}+ preview={options.preview ?? buildPreview(content)}+ renderPreview={async () => buildPreview(content)}+ />+ </ParentComponent.Provider>,+ box+ );+ });+ return { figure };+}++function buildTextNote(id: string) {+ const root = froca.notes["root"] ?? buildNote({ id: "root", title: "root" });+ const note = buildNote({ id, title: id, type: "text", content: `<p>${id}</p>` });+ root.children.push(note.noteId);+ note.parents.push(root.noteId);+ return note;+}++function buildEditor(): ContentEditor {+ return {+ canEdit: () => true,+ getUnsavedContent: () => undefined,+ scheduleSave: vi.fn(),+ release: vi.fn()+ };+}++function buildPreview(content: string) {+ const div = document.createElement("div");+ div.innerHTML = content;+ return div;+}diff --git a/apps/client/src/widgets/type_widgets/text/TextEmbed.tsx b/apps/client/src/widgets/type_widgets/text/TextEmbed.tsxnew file mode 100644index 0000000000..68680c1441--- /dev/null+++ b/apps/client/src/widgets/type_widgets/text/TextEmbed.tsx@@ -0,0 +1,49 @@+import { lazy } from "preact/compat";+import { useRef } from "preact/hooks";++import type FNote from "../../../entities/fnote";+import type { ContentEditor } from "../../../services/content_renderer";+import { useNoteBlob } from "../../react/hooks";+import { EditableEmbedContent, useEditableEmbed, useEmbedPreview } from "./editable_embed";++const TextEmbedEditor = lazy(() => import("./TextEmbedEditor"));++interface TextEmbedProps {+ note: FNote;+ /** Tells whether the note can be edited here. The editor saves the note on its own. */+ editor: ContentEditor | undefined;+ /** The content of the note that `preview` shows. */+ content: string;+ /** The rendered note. */+ preview: HTMLElement;+ /** Renders the note again, after a change. */+ renderPreview: () => Promise<HTMLElement>;+}++/**+ * A text note in an embed, shown rendered, and edited with a text editor of its own while the+ * Editable toggle of its embed is on.+ */+export default function TextEmbed({+ note, editor, content, preview, renderPreview+}: TextEmbedProps) {+ const rootRef = useRef<HTMLDivElement>(null);+ const { isEditing } = useEditableEmbed(rootRef, {+ editor,+ note,+ focusTarget: ".ck-editor__editable"+ });+ const blob = useNoteBlob(note);+ const shownPreview = useEmbedPreview(preview, blob?.content ?? content, renderPreview);++ return (+ <EditableEmbedContent+ rootRef={rootRef}+ className="text-embed-content"+ isEditing={isEditing}+ preview={shownPreview}+ >+ <TextEmbedEditor note={note} />+ </EditableEmbedContent>+ );+}diff --git a/apps/client/src/widgets/type_widgets/text/TextEmbedEditor.css b/apps/client/src/widgets/type_widgets/text/TextEmbedEditor.cssnew file mode 100644index 0000000000..fbbda5717d--- /dev/null+++ b/apps/client/src/widgets/type_widgets/text/TextEmbedEditor.css@@ -0,0 +1,5 @@+.include-note-content .text-embed-editor {+ .note-detail-editable-text-editor {+ padding-top: 0;+ }+}diff --git a/apps/client/src/widgets/type_widgets/text/TextEmbedEditor.tsx b/apps/client/src/widgets/type_widgets/text/TextEmbedEditor.tsxnew file mode 100644index 0000000000..e29a6960ec--- /dev/null+++ b/apps/client/src/widgets/type_widgets/text/TextEmbedEditor.tsx@@ -0,0 +1,56 @@+import "./TextEmbedEditor.css";++import { useLayoutEffect, useRef, useState } from "preact/hooks";++import type FNote from "../../../entities/fnote";+import { randomString } from "../../../services/utils";+import {+ announceEmbeddedNoteClosing, EmbeddedNoteScope, useEmbeddedNoteContext+} from "../../EmbeddedNotePane";+import { useLegacyComponentElement, useNoteContext } from "../../react/hooks";+import EditableText from "./EditableText";+import { NestedEmbedContext } from "./editable_embed";++/**+ * The text editor of a text note in an embed. It has a note context and a component of its own,+ * as the note pane of a geo map does, and saves the note as a note tab does.+ */+export default function TextEmbedEditor({ note }: { note: FNote }) {+ const [ ntxId ] = useState(() => `_embed_${randomString(10)}`);+ const { noteContext, component } = useEmbeddedNoteContext(note, ntxId);++ // A layout cleanup runs while the editor is still mounted, so it saves what is left.+ useLayoutEffect(() => () => {+ void announceEmbeddedNoteClosing(component, ntxId);+ }, [ component, ntxId ]);++ return (+ <EmbeddedNoteScope component={component} noteContext={noteContext}>+ <NestedEmbedContext.Provider value={true}>+ <ScopedEditor note={note} />+ </NestedEmbedContext.Provider>+ </EmbeddedNoteScope>+ );+}++/** The editor, once the note context of the embed holds `note`. */+function ScopedEditor({ note }: { note: FNote }) {+ const rootRef = useRef<HTMLDivElement>(null);+ const { note: contextNote, noteContext, ntxId, parentComponent } = useNoteContext();+ // The plugins of the editor find their host by the element of its component.+ useLegacyComponentElement(rootRef);++ return (+ <div ref={rootRef} className="text-embed-editor">+ {noteContext && contextNote?.noteId === note.noteId && (+ <EditableText+ note={note}+ noteContext={noteContext}+ ntxId={ntxId ?? null}+ parentComponent={parentComponent}+ viewScope={noteContext.viewScope}+ />+ )}+ </div>+ );+}diff --git a/apps/client/src/widgets/type_widgets/text/attachment_saves.spec.ts b/apps/client/src/widgets/type_widgets/text/attachment_saves.spec.tsindex 613c9b6cd6..3671d654d3 100644--- a/apps/client/src/widgets/type_widgets/text/attachment_saves.spec.ts+++ b/apps/client/src/widgets/type_widgets/text/attachment_saves.spec.ts@@ -161,11 +161,12 @@ describe("NoteSaves", () => {return { noteId, type: "code", isContentAvailable: () => true, ...overrides } as FNote;}- it("edits code notes whose content is available", () => {- const saves = new NoteSaves(vi.fn(), "host");+ it("edits the notes whose content is available, except the note that shows them", () => {+ const saves = new NoteSaves(vi.fn(), "host", () => "host1");expect(saves.canEdit(buildCodeNote("code1"))).toBe(true);- expect(saves.canEdit(buildCodeNote("text1", { type: "text" }))).toBe(false);+ expect(saves.canEdit(buildCodeNote("text1", { type: "text" }))).toBe(true);+ expect(saves.canEdit(buildCodeNote("host1", { type: "text" }))).toBe(false);expect(saves.canEdit(buildCodeNote("locked", { isContentAvailable: () => false }))).toBe(false);});diff --git a/apps/client/src/widgets/type_widgets/text/attachment_saves.ts b/apps/client/src/widgets/type_widgets/text/attachment_saves.tsindex 2a64f9817f..bd44d6c51e 100644--- a/apps/client/src/widgets/type_widgets/text/attachment_saves.ts+++ b/apps/client/src/widgets/type_widgets/text/attachment_saves.ts@@ -128,16 +128,18 @@ export class NoteSaves extends PendingSaves<FNote, SavedNote> implements NoteEdi/*** @param scheduleUpdate schedules a save.* @param componentId the component that saves the changes.+ * @param getHostNoteId the note that shows the embeds, which they cannot edit.*/constructor(private scheduleUpdate: () => void,- readonly componentId: string | undefined+ readonly componentId: string | undefined,+ private getHostNoteId: () => string | undefined = () => undefined) {super();}canEdit(note: FNote) {- return note.type === "code" && note.isContentAvailable();+ return note.noteId !== this.getHostNoteId() && note.isContentAvailable();}scheduleSave(note: FNote, getContent: () => string) {@@ -205,12 +207,13 @@ export function useAttachmentEditor(*/export function useNoteEditor(noteContext: NoteContext | null | undefined): NoteEditor {const parentComponent = useContext(ParentComponent);+ const noteContextRef = useRef(noteContext);+ noteContextRef.current = noteContext;const [ saves ] = useState(() => new NoteSaves(() => spacedUpdate.scheduleUpdate(),- parentComponent?.componentId+ parentComponent?.componentId,+ () => noteContextRef.current?.noteId ?? undefined));- const noteContextRef = useRef(noteContext);- noteContextRef.current = noteContext;const [ spacedUpdate ] = useState(() => new SpacedUpdate<SavedNote[]>({diff --git a/apps/client/src/widgets/type_widgets/text/editable_embed.spec.tsx b/apps/client/src/widgets/type_widgets/text/editable_embed.spec.tsxnew file mode 100644index 0000000000..ae21cd7c95--- /dev/null+++ b/apps/client/src/widgets/type_widgets/text/editable_embed.spec.tsx@@ -0,0 +1,187 @@+import { render } from "preact";+import { useRef } from "preact/hooks";+import { act } from "preact/test-utils";+import { afterEach, describe, expect, it, vi } from "vitest";++import type { ContentEditor } from "../../../services/content_renderer";+import options from "../../../services/options";+import { buildNote } from "../../../test/easy-froca";+import { type ContentEmbedToolProvider, getContentEmbedTools } from "./content_embed_tools";+import {+ type EditableEmbedOptions, NestedEmbedContext, useEditableEmbed, useEmbedEditors,+ useEmbedPreview+} from "./editable_embed";++const figures: HTMLElement[] = [];++afterEach(() => {+ for (const figure of figures) {+ const box = figure.querySelector(".include-note-content");+ if (box) act(() => render(null, box));+ figure.remove();+ }+ figures.length = 0;+ options.set("databaseReadonly", "false");+});++describe("useEditableEmbed", () => {+ it("can edit with an editor that saves, unless the note or database is read-only", async () => {+ const editable = await mountProbe({ editor: buildEditor(), note: null });+ expect(editable.state).toEqual({ canEdit: true, isEditing: false });+ expect(getContentEmbedTools(editable.figure)?.hasEditableFlag).toBe(true);++ const readOnly: Array<Partial<EditableEmbedOptions>> = [+ { editor: undefined },+ { editor: buildEditor(false) },+ { note: buildNote({ title: "Fixed", "#readOnly": "" }) }+ ];+ for (const overrides of readOnly) {+ const { state, figure } =+ await mountProbe({ editor: buildEditor(), note: null, ...overrides });+ expect(state.canEdit).toBe(false);+ expect(getContentEmbedTools(figure)).toBeNull();+ }++ options.set("databaseReadonly", "true");+ expect((await mountProbe({ editor: buildEditor(), note: null })).state.canEdit).toBe(false);+ });++ it("edits while the Editable toggle of the embed is on", async () => {+ const probe = await mountProbe({ editor: buildEditor(), note: null }, { isEditable: true });+ expect(probe.state).toEqual({ canEdit: true, isEditing: true });++ await act(async () => {+ delete probe.figure.dataset.editable;+ await Promise.resolve();+ });+ expect(probe.state).toEqual({ canEdit: true, isEditing: false });++ const locked =+ await mountProbe({ editor: buildEditor(false), note: null }, { isEditable: true });+ expect(locked.state).toEqual({ canEdit: false, isEditing: false });+ });++ it("adds the buttons it is given, or none for content that adds its own", async () => {+ const tools = { hasEditableFlag: true } as ContentEmbedToolProvider;+ const custom = await mountProbe({ editor: buildEditor(), note: null, tools });+ expect(getContentEmbedTools(custom.figure)).toBe(tools);++ const own = await mountProbe({ editor: buildEditor(), note: null, tools: null });+ expect(getContentEmbedTools(own.figure)).toBeNull();+ });++ it("passes the focus of the embed box to its target, also once it renders", async () => {+ const { figure, root } = await mountProbe({+ editor: buildEditor(),+ note: null,+ focusTarget: ".target"+ });+ const box = figure.querySelector<HTMLElement>(".include-note-content");+ box?.focus();+ expect(document.activeElement).toBe(box);++ const target = document.createElement("div");+ target.className = "target";+ target.tabIndex = -1;+ root?.append(target);+ await vi.waitFor(() => expect(document.activeElement).toBe(target));++ box?.focus();+ expect(document.activeElement).toBe(target);+ });+});++describe("useEmbedEditors", () => {+ it("passes the editors on, except from a host nested in an embed", () => {+ const editors = { noteEditor: "notes", attachmentEditor: "attachments" };+ const results: object[] = [];+ function Probe() {+ results.push(useEmbedEditors(editors));+ return null;+ }++ const container = document.createElement("div");+ act(() => render(<Probe />, container));+ act(() => render(+ <NestedEmbedContext.Provider value={true}><Probe /></NestedEmbedContext.Provider>,+ container+ ));++ expect(results).toEqual([ editors, {} ]);+ act(() => render(null, container));+ });+});++describe("useEmbedPreview", () => {+ it("keeps the first preview for its key, and renders one for any other key", async () => {+ const initial = document.createElement("pre");+ const rendered = document.createElement("pre");+ const renderPreview = vi.fn(async () => rendered);+ let preview: HTMLElement | undefined;+ function Probe({ previewKey }: { previewKey: string }) {+ preview = useEmbedPreview(initial, previewKey, renderPreview);+ return null;+ }++ const container = document.createElement("div");+ await act(async () => render(<Probe previewKey="a" />, container));+ expect(preview).toBe(initial);+ expect(renderPreview).not.toHaveBeenCalled();++ await act(async () => render(<Probe previewKey="b" />, container));+ await vi.waitFor(() => expect(preview).toBe(rendered));+ expect(renderPreview).toHaveBeenCalledOnce();++ await act(async () => render(<Probe previewKey="a" />, container));+ expect(preview).toBe(initial);+ expect(renderPreview).toHaveBeenCalledOnce();+ act(() => render(null, container));+ });+});++interface ProbeState {+ canEdit: boolean;+ isEditing: boolean;+}++/** Renders a component that uses `useEditableEmbed()`, in the markup of an embed. */+async function mountProbe(+ embedOptions: EditableEmbedOptions,+ { isEditable = false }: { isEditable?: boolean } = {}+) {+ const figure = document.createElement("figure");+ figure.className = "include-note";+ if (isEditable) {+ figure.dataset.editable = "true";+ }+ const box = document.createElement("div");+ box.className = "include-note-content";+ box.tabIndex = -1;+ figure.append(box);+ document.body.append(figure);+ figures.push(figure);++ const probe = {+ state: { canEdit: false, isEditing: false } as ProbeState,+ figure,+ root: null as HTMLElement | null+ };+ function Probe() {+ const rootRef = useRef<HTMLDivElement>(null);+ probe.state = useEditableEmbed(rootRef, embedOptions);+ return <div ref={rootRef} className="probe" />;+ }++ await act(async () => render(<Probe />, box));+ probe.root = box.querySelector(".probe");+ return probe;+}++function buildEditor(canEdit = true): ContentEditor {+ return {+ canEdit: () => canEdit,+ getUnsavedContent: () => undefined,+ scheduleSave: vi.fn(),+ release: vi.fn()+ };+}diff --git a/apps/client/src/widgets/type_widgets/text/editable_embed.tsx b/apps/client/src/widgets/type_widgets/text/editable_embed.tsxnew file mode 100644index 0000000000..609bacd158--- /dev/null+++ b/apps/client/src/widgets/type_widgets/text/editable_embed.tsx@@ -0,0 +1,162 @@+import { type ComponentChildren, createContext, type RefObject } from "preact";+import { Suspense } from "preact/compat";+import { useContext, useEffect, useLayoutEffect, useRef, useState } from "preact/hooks";++import type FNote from "../../../entities/fnote";+import type { ContentEditor } from "../../../services/content_renderer";+import options from "../../../services/options";+import { useNoteLabelBoolean } from "../../react/hooks";+import {+ type ContentEmbedToolProvider, registerContentEmbedTools, useIsContentEmbedEditable+} from "./content_embed_tools";++/**+ * Whether the content renders inside the editor of an embed. Its own embeds then stay read-only,+ * so that editors nest one level deep at most.+ */+export const NestedEmbedContext = createContext(false);++/**+ * The editors that a host passes to its embeds, such as its `AttachmentEditor`: none for a host+ * nested in an embed.+ */+export function useEmbedEditors<T extends object>(editors: T): Partial<T> {+ return useContext(NestedEmbedContext) ? {} : editors;+}++export interface EditableEmbedOptions {+ /** Saves the changes, or `undefined` where the content is read-only. */+ editor: ContentEditor | undefined;+ /** The note shown, whose `#readOnly` label keeps it read-only. `null` for an attachment. */+ note: FNote | null;+ /**+ * The buttons that the content adds to the toolbar of its embed while it can be edited, with+ * `hasEditableFlag` set. The Editable toggle alone when left out, and `null` for content that+ * adds its own.+ */+ tools?: ContentEmbedToolProvider | null;+ /** Selects the element of the content that takes the focus when the embed box does. */+ focusTarget?: string;+}++/**+ * The editable mode of the content of an embed: `canEdit` while `editor` can save the content, and+ * `isEditing` while the Editable toggle of the embed is on as well.+ */+export function useEditableEmbed(+ rootRef: RefObject<HTMLElement | null>,+ { editor, note, tools, focusTarget }: EditableEmbedOptions+) {+ const [ isNoteReadOnly ] = useNoteLabelBoolean(note, "readOnly");+ const canEdit = !!editor?.canEdit() && !isNoteReadOnly && !options.is("databaseReadonly");+ const isToggledOn = useIsContentEmbedEditable(rootRef);+ const provider = tools === undefined ? EDITABLE_FLAG_TOOLS : tools;++ useEffect(() => {+ const root = rootRef.current;+ if (!root || !canEdit || !provider) return;++ return registerContentEmbedTools(root, provider);+ }, [ rootRef, canEdit, provider ]);+ useFocusFromEmbedBox(rootRef, focusTarget);++ return { canEdit, isEditing: canEdit && isToggledOn };+}++interface EditableEmbedContentProps {+ rootRef: RefObject<HTMLDivElement | null>;+ className: string;+ isEditing: boolean;+ /** The rendered content, shown while the content is not edited. */+ preview: HTMLElement;+ /** The editor, loaded on demand, which replaces the preview while `isEditing`. */+ children: ComponentChildren;+}++/** The content of an embed: its preview, replaced by its editor while it is edited. */+export function EditableEmbedContent({+ rootRef, className, isEditing, preview, children+}: EditableEmbedContentProps) {+ const previewView = <EmbedPreview element={preview} />;++ return (+ <div ref={rootRef} className={className}>+ {isEditing ? <Suspense fallback={previewView}>{children}</Suspense> : previewView}+ </div>+ );+}++/**+ * The preview of the content of an embed: `initial` while `key` has its first value, otherwise+ * what `render` returns for the current key. The previous preview stays until the next is ready.+ */+export function useEmbedPreview(+ initial: HTMLElement,+ key: string,+ render: () => Promise<HTMLElement>+) {+ const [ preview, setPreview ] = useState(initial);+ const initialKeyRef = useRef(key);++ useEffect(() => {+ if (key === initialKeyRef.current) {+ setPreview(initial);+ return;+ }++ let isCurrent = true;+ render().then((element) => {+ if (isCurrent) {+ setPreview(element);+ }+ });+ return () => {+ isCurrent = false;+ };+ }, [ key ]);++ return preview;+}++const EDITABLE_FLAG_TOOLS: ContentEmbedToolProvider = {+ hasEditableFlag: true,+ getTools: () => [],+ execute: () => {},+ subscribe: () => () => {}+};++function EmbedPreview({ element }: { element: HTMLElement }) {+ const containerRef = useRef<HTMLDivElement>(null);++ useLayoutEffect(() => {+ containerRef.current?.replaceChildren(element);+ }, [ element ]);++ return <div ref={containerRef} className="editable-embed-preview" />;+}++/**+ * Moves the focus to the element that `selector` matches when the embed box around `rootRef`+ * holds it, including when that element renders after the box took the focus.+ */+function useFocusFromEmbedBox(rootRef: RefObject<HTMLElement | null>, selector?: string) {+ useEffect(() => {+ const root = rootRef.current;+ const box = root?.closest<HTMLElement>(".include-note-content");+ if (!root || !box || !selector) return;++ const forwardFocus = () => {+ if (document.activeElement === box) {+ root.querySelector<HTMLElement>(selector)?.focus();+ }+ };+ const observer = new MutationObserver(forwardFocus);+ observer.observe(root, { childList: true, subtree: true });+ box.addEventListener("focus", forwardFocus);+ forwardFocus();+ return () => {+ observer.disconnect();+ box.removeEventListener("focus", forwardFocus);+ };+ }, [ rootRef, selector ]);+}diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/Notes/Attachments.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/Notes/Attachments.htmlindex 82cdf6b9bb..e8ba05ee83 100644--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/Notes/Attachments.html+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/Notes/Attachments.html@@ -68,8 +68,8 @@class="reference-link" href="#root/_help_nBAXQFj20hS1">Include Note</a> showsa note: a picture is displayed, a PDF, a video or a document is previewed,and a code or text file is shown with syntax highlighting. An embedded- code file can also be edited in place (see <em>Included code</em> in <a class="reference-link"- href="#root/_help_nBAXQFj20hS1">Include Note</a>).</p>+ code file can also be edited in place (see <em>Editing an include in place</em> in <a+ class="reference-link" href="#root/_help_nBAXQFj20hS1">Include Note</a>).</p><ul><li>To attach files and embed them straight away, select <em>Attach and embed file</em> fromthe arrow beside the <span class="tn-icon cke cke-paper-clip"></span> <em>Attach file</em> button.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 a5fc91a094..ece296835f 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,9 +100,10 @@<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.- A drawing canvas, an included code note and an embedded code file also- have <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>+ A drawing canvas, an included text or code note and an embedded code file+ also have <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@@ -159,16 +160,20 @@</ul><p>In a <em>Small</em> or <em>Medium</em> box, the image is scaled down to fitthe height of the box. In fullscreen, it fits the screen.</p>-<h2>Included code</h2>-<p>An included code note, or an embedded code file such as a <code>.js</code>, <code>.py</code> or <code>.txt</code> attachment,- is shown with syntax highlighting. It can also be edited in place, in the- same code editor as a <a class="reference-link" href="#root/_help_6f9hih2hXXZk">Code</a> note.</p>+<h2>Editing an include in place</h2>+<p>An included text note, an included code note and an embedded code file+ such as a <code>.js</code>, <code>.py</code> or <code>.txt</code> attachment+ can be edited without leaving the note that includes them. A code note+ or file is shown with syntax highlighting until then.</p><ul>- <li>To edit the code, select the include and turn on the <span class="tn-icon bx bx-edit-alt"></span> <em>Editable</em> button+ <li>To edit, select the include and turn on the <span class="tn-icon bx bx-edit-alt"></span> <em>Editable</em> buttonat the start of its toolbar, or check <em>Editable</em> in its <span class="tn-icon cke cke-three-vertical-dots"></span> <em>More actions</em> menu.- The highlighted code is replaced by the code editor, which follows the- theme, indentation and line wrapping settings of code notes. Turn <em>Editable</em> off- to return to the highlighted view.</li>+ Turn <em>Editable</em> off to return to the preview.</li>+ <li>A text note is edited with the floating toolbar, which appears over the+ selected text, whichever toolbar the other text notes use. The notes it+ includes in turn stay read-only.</li>+ <li>Code is edited in the same code editor as a <a class="reference-link" href="#root/_help_6f9hih2hXXZk">Code</a> note,+ with its theme, indentation and line wrapping settings.</li><li>The changes are saved as you type, to the included note or to the attachment,as they would be in its own tab.</li><li>Editing is not available in a <a href="#root/_help_CoFPLs3dRlXc">read-only note</a>,diff --git a/docs/User Guide/User Guide/Basic Concepts and Features/Notes/Attachments.md b/docs/User Guide/User Guide/Basic Concepts and Features/Notes/Attachments.mdindex f4f61ab04c..175c694f6b 100644--- a/docs/User Guide/User Guide/Basic Concepts and Features/Notes/Attachments.md+++ b/docs/User Guide/User Guide/Basic Concepts and Features/Notes/Attachments.md@@ -37,7 +37,7 @@ Links follow changes to their attachment: renaming it updates the title they sho## Embedding an attachment-An attachment can be shown in the text instead of linked, the way <a class="reference-link" href="../../Note%20Types/Text/Include%20Note.md">Include Note</a> shows a note: a picture is displayed, a PDF, a video or a document is previewed, and a code or text file is shown with syntax highlighting. An embedded code file can also be edited in place (see _Included code_ in <a class="reference-link" href="../../Note%20Types/Text/Include%20Note.md">Include Note</a>).+An attachment can be shown in the text instead of linked, the way <a class="reference-link" href="../../Note%20Types/Text/Include%20Note.md">Include Note</a> shows a note: a picture is displayed, a PDF, a video or a document is previewed, and a code or text file is shown with syntax highlighting. An embedded code file can also be edited in place (see _Editing an include in place_ in <a class="reference-link" href="../../Note%20Types/Text/Include%20Note.md">Include Note</a>).* To attach files and embed them straight away, select _Attach and embed file_ from the arrow beside the <span class="tn-icon cke cke-paper-clip"></span> _Attach file_ button. Each file gets an embed of its own, which shows the file name while the file uploads.* To embed an attachment that is already linked, right-click a link to it in a text note being edited and select _Convert link to an embed_, at the end of the menu.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 0d6b0ad569..a50fc77e3f 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. A drawing canvas, an included code note and an embedded code file also have _Editable_, above _Size_. 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, an included text or code note and an embedded code file also have _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>.@@ -102,11 +102,13 @@ An included image, whether an image note or an image attachment, is shown in theIn a _Small_ or _Medium_ box, the image is scaled down to fit the height of the box. In fullscreen, it fits the screen.-## Included code+## Editing an include in place-An included code note, or an embedded code file such as a `.js`, `.py` or `.txt` attachment, is shown with syntax highlighting. It can also be edited in place, in the same code editor as a <a class="reference-link" href="../Code.md">Code</a> note.+An included text note, an included code note and an embedded code file such as a `.js`, `.py` or `.txt` attachment can be edited without leaving the note that includes them. A code note or file is shown with syntax highlighting until then.-* To edit the code, select the include and turn on the <span class="tn-icon bx bx-edit-alt"></span> _Editable_ button at the start of its toolbar, or check _Editable_ in its <span class="tn-icon cke cke-three-vertical-dots"></span> _More actions_ menu. The highlighted code is replaced by the code editor, which follows the theme, indentation and line wrapping settings of code notes. Turn _Editable_ off to return to the highlighted view.+* To edit, select the include and turn on the <span class="tn-icon bx bx-edit-alt"></span> _Editable_ button at the start of its toolbar, or check _Editable_ in its <span class="tn-icon cke cke-three-vertical-dots"></span> _More actions_ menu. Turn _Editable_ off to return to the preview.+* A text note is edited with the floating toolbar, which appears over the selected text, whichever toolbar the other text notes use. The notes it includes in turn stay read-only.+* Code is edited in the same code editor as a <a class="reference-link" href="../Code.md">Code</a> note, with its theme, indentation and line wrapping settings.* The changes are saved as you type, to the included note or to the attachment, as they would be in its own tab.* Editing is not available in a [read-only note](../../Basic%20Concepts%20and%20Features/Notes/Read-Only%20Notes.md), for an included note marked `#readOnly`, or for an attachment of another note.diff --git a/packages/ckeditor5/src/plugins/content_embed/content_embed.spec.ts b/packages/ckeditor5/src/plugins/content_embed/content_embed.spec.tsindex 5f9c3c9550..bcda9847b5 100644--- a/packages/ckeditor5/src/plugins/content_embed/content_embed.spec.ts+++ b/packages/ckeditor5/src/plugins/content_embed/content_embed.spec.ts@@ -448,8 +448,12 @@ describe("ContentEmbed", () => {expect(viewFocus).not.toHaveBeenCalled();const change = vi.spyOn(editor.model, "enqueueChange");+ // The content hears its own focus, as the editor of an included note must.+ const heard = vi.fn();+ button?.addEventListener("focus", heard);button?.focus();expect(document.activeElement).toBe(button);+ expect(heard).toHaveBeenCalledOnce();expect(change).not.toHaveBeenCalled();});diff --git a/packages/ckeditor5/src/plugins/content_embed/content_embed.ts b/packages/ckeditor5/src/plugins/content_embed/content_embed.tsindex 186273410e..ef4f2c40b6 100644--- a/packages/ckeditor5/src/plugins/content_embed/content_embed.ts+++ b/packages/ckeditor5/src/plugins/content_embed/content_embed.ts@@ -26,6 +26,7 @@ import windowIcon from 'boxicons/svg/regular/bx-window-alt.svg?raw';import noteIcon from '../../icons/note.svg?raw';import { getAttachmentId, getNoteId } from '../referencelink.js';import ResizableWidgets, { SIZE_ATTRIBUTES } from '../resizable_widgets/resizable_widgets.js';+import './nested_editor_events.js';export const COMMAND_NAME = 'insertContentEmbed';export const BOX_SIZE_COMMAND_NAME = 'contentEmbedBoxSize';@@ -1214,7 +1215,12 @@ function preventCKEditorHandling( domElement: HTMLElement, editor: Editor ) {}, { capture: true } );domElement.addEventListener( 'focus', ( evt: FocusEvent ) => {- stopEventPropagationAndHackRendererFocus( evt );+ // The content of the embed, such as the editor of an included note, hears its own focus.+ if ( isInEmbedContent( evt.target ) ) {+ hackRendererFocus();+ } else {+ stopEventPropagationAndHackRendererFocus( evt );+ }// Content that takes the focus without a press, as a canvas drawing just added, selects// its widget as a press does, which shows its toolbar. The focus stays in the content.@@ -1233,12 +1239,21 @@ function preventCKEditorHandling( domElement: HTMLElement, editor: Editor ) {function stopEventPropagationAndHackRendererFocus( evt: Event ) {evt.stopPropagation();+ hackRendererFocus();+ }++ function hackRendererFocus() {// This prevents rendering changed view selection thus preventing to changing DOM selection while inside a widget.//@ts-expect-error: We are accessing a private field.editor.editing.view._renderer.isFocused = false;}}+/** Whether `target` is in the content box of an embed, rather than in its title row. */+function isInEmbedContent( target: EventTarget | null ): boolean {+ return target instanceof Element && !!target.closest( '.include-note-content' );+}+/*** Whether a mousedown target needs the browser's native handling to keep working — so the widget's* event interception should step aside. Covers form controls, links and media (which need focus,diff --git a/packages/ckeditor5/src/plugins/content_embed/nested_editor_events.spec.ts b/packages/ckeditor5/src/plugins/content_embed/nested_editor_events.spec.tsnew file mode 100644index 0000000000..4d86b93ec1--- /dev/null+++ b/packages/ckeditor5/src/plugins/content_embed/nested_editor_events.spec.ts@@ -0,0 +1,59 @@+import { FocusObserver, InputObserver, Paragraph } from "ckeditor5";+import { afterEach, describe, expect, it, vi } from "vitest";++import { createTestEditor } from "../../../test/editor-kit.js";+import "./nested_editor_events.js";++afterEach(() => {+ for (const marker of document.querySelectorAll("body > [data-cke-ignore-events]")) {+ marker.remove();+ }+});++describe("nested editor events", () => {+ it("lets an editor inside an element marked to be ignored handle its own events", async () => {+ const editor = await createTestEditor([ Paragraph ]);+ const root = getDomRoot(editor);+ // The wrapper of an embed, as the outer editor renders it.+ const marker = document.createElement("div");+ marker.dataset.ckeIgnoreEvents = "true";+ document.body.append(marker);+ marker.append(root);+ editor.setData("<p>ab</p>");++ root.focus();+ await vi.waitFor(() => expect(editor.editing.view.document.isFocused).toBe(true));+ const input = editor.editing.view.getObserver(InputObserver);+ const paragraph = root.querySelector("p");+ expect(input?.checkShouldIgnoreEventFromTarget(paragraph)).toBe(false);+ });++ it("still ignores the events from inside an element marked in the editor's own root", async () => {+ const editor = await createTestEditor([ Paragraph ]);+ const root = getDomRoot(editor);+ const marker = document.createElement("div");+ marker.dataset.ckeIgnoreEvents = "true";+ const inner = document.createElement("span");+ marker.append(inner);+ root.append(marker);+ const outside = document.createElement("span");+ const outerMarker = document.createElement("div");+ outerMarker.dataset.ckeIgnoreEvents = "true";+ outerMarker.append(outside);+ document.body.append(outerMarker);++ const observer = editor.editing.view.getObserver(FocusObserver);+ expect(observer?.checkShouldIgnoreEventFromTarget(inner)).toBe(true);+ expect(observer?.checkShouldIgnoreEventFromTarget(inner.appendChild(new Text("x"))))+ .toBe(true);+ expect(observer?.checkShouldIgnoreEventFromTarget(root)).toBe(false);+ expect(observer?.checkShouldIgnoreEventFromTarget(outside)).toBe(true);+ expect(observer?.checkShouldIgnoreEventFromTarget(null)).toBe(false);+ });+});++function getDomRoot(editor: Awaited<ReturnType<typeof createTestEditor>>) {+ const root = editor.editing.view.getDomRoot();+ if (!root) throw new Error("Expected the editable root of the editor.");+ return root;+}diff --git a/packages/ckeditor5/src/plugins/content_embed/nested_editor_events.ts b/packages/ckeditor5/src/plugins/content_embed/nested_editor_events.tsnew file mode 100644index 0000000000..21e23de77a--- /dev/null+++ b/packages/ckeditor5/src/plugins/content_embed/nested_editor_events.ts@@ -0,0 +1,26 @@+import { Observer } from "ckeditor5";++/**+ * Lets an editor nested in the content of an embed handle its own events.+ *+ * An observer ignores the events from inside an element marked `data-cke-ignore-events`, as the+ * wrapper of an embed is. A nested editor is inside that wrapper too, so for an event from an+ * editable root of the observer's view, only a marked element inside that root counts.+ */+const checkShouldIgnoreEventFromTarget = Observer.prototype.checkShouldIgnoreEventFromTarget;++Observer.prototype.checkShouldIgnoreEventFromTarget = function (+ this: Observer,+ domTarget: Node | null+) {+ const element = domTarget?.nodeType === Node.TEXT_NODE ? domTarget.parentElement : domTarget;+ const root = element instanceof Element+ ? [ ...this.view.domRoots.values() ].find((domRoot) => domRoot.contains(element))+ : undefined;+ if (!root || !(element instanceof Element)) {+ return checkShouldIgnoreEventFromTarget.call(this, domTarget);+ }++ const marker = element.closest("[data-cke-ignore-events]");+ return !!marker && root.contains(marker);+};