Skip to content

Build your personal knowledge base with Trilium Notes

client/text editor/transclusion: fix some issues

Adorian Dorand0890b3fcdb1
diff --git a/apps/client/src/components/note_context.ts b/apps/client/src/components/note_context.ts
index ba0fdb8575..f8bc14e539 100644
--- a/apps/client/src/components/note_context.ts
+++ b/apps/client/src/components/note_context.ts
@@ -24,6 +24,8 @@ export interface SetNoteOpts {
viewScope?: ViewScope;
/** If true, skip closing the currently active dialog. Used when opening a note into a stackable popup (e.g. quick-edit) that must not dismiss the dialog it was launched from. */
keepActiveDialog?: boolean;
+ /** If true, the note is not added to the recent notes, as for an included note being edited. */
+ skipRecentNotes?: boolean;
}
export type GetTextEditorCallback = (editor: CKTextEditor) => void;
@@ -214,7 +216,9 @@ class NoteContext extends Component implements EventListener<"entitiesReloaded">
}
}
- this.saveToRecentNotes(resolvedNotePath);
+ if (!opts.skipRecentNotes) {
+ this.saveToRecentNotes(resolvedNotePath);
+ }
protectedSessionHolder.touchProtectedSessionIfNecessary(this.note);
diff --git a/apps/client/src/services/content_renderer.spec.ts b/apps/client/src/services/content_renderer.spec.ts
index 00cf28b72e..407daa610f 100644
--- a/apps/client/src/services/content_renderer.spec.ts
+++ b/apps/client/src/services/content_renderer.spec.ts
@@ -7,10 +7,14 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
const renderText = vi.fn(async (...args: any[]) => {
args[1].append($('<div class="from-render-text">'));
});
+const renderTextContent = vi.fn(async (...args: any[]) => {
+ args[2].append($('<div class="from-render-text-content">').attr("data-content", args[1]));
+});
const postProcessRichContent = vi.fn(async (..._args: any[]) => {});
const renderChildrenList = vi.fn(async (..._args: any[]) => {});
vi.mock("./content_renderer_text.js", () => ({
default: (...args: any[]) => renderText(...args),
+ renderTextContent: (...args: any[]) => renderTextContent(...args),
postProcessRichContent: (...args: any[]) => postProcessRichContent(...args),
renderChildrenList: (...args: any[]) => renderChildrenList(...args)
}));
@@ -129,6 +133,7 @@ vi.mock("@triliumnext/commons/src/lib/markdown_renderer", async (orig) => ({
// --- Imports AFTER the mocks. ---
import appContext from "../components/app_context.js";
+import type { SaveState } from "../components/note_context.js";
import FAttachment from "../entities/fattachment.js";
import { buildNote } from "../test/easy-froca.js";
import {
@@ -358,7 +363,9 @@ describe("getRenderedContent editable code", () => {
canEdit: vi.fn(() => true),
getUnsavedContent: vi.fn((): string | undefined => undefined),
scheduleSave: vi.fn(),
- release: vi.fn()
+ release: vi.fn(),
+ getSaveState: vi.fn((): SaveState | undefined => "saving"),
+ subscribeSaveState: vi.fn(() => () => {})
};
}
@@ -427,6 +434,11 @@ describe("getRenderedContent editable code", () => {
expect(noteEditor.getUnsavedContent).toHaveBeenCalledWith(note.noteId);
expect(noteEditor.scheduleSave).toHaveBeenCalledWith(note, getContent);
expect(noteEditor.release).toHaveBeenCalledWith(note.noteId);
+ const listener = () => {};
+ expect(props.editor.getSaveState()).toBe("saving");
+ props.editor.subscribeSaveState(listener);
+ expect(noteEditor.getSaveState).toHaveBeenCalledWith(note.noteId);
+ expect(noteEditor.subscribeSaveState).toHaveBeenCalledWith(listener);
});
it("mounts CodeEmbed for an interactive code file, saved by `attachmentEditor`", async () => {
@@ -462,15 +474,18 @@ describe("getRenderedContent editable code", () => {
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 }));
+ const rendered = (preview: HTMLElement) =>
+ preview.querySelector(".from-render-text-content")?.getAttribute("data-content");
+ expect(rendered(props.preview)).toBe("<p>Hi</p>");
+ expect(renderTextContent).toHaveBeenLastCalledWith(
+ note, "<p>Hi</p>", expect.anything(),
+ expect.objectContaining({ embedsAsReferenceLinks: true }));
expect(props.editor.canEdit()).toBe(true);
expect(noteEditor.canEdit).toHaveBeenCalledWith(note);
- const again = await props.renderPreview();
+ const again = await props.renderPreview("<p>Edited</p>");
expect(again).not.toBe(props.preview);
- expect(again.querySelector(".from-render-text")).not.toBeNull();
+ expect(rendered(again)).toBe("<p>Edited</p>");
});
it("edits only code and text notes", async () => {
diff --git a/apps/client/src/services/content_renderer.ts b/apps/client/src/services/content_renderer.ts
index 3462d4c61f..84915fa625 100644
--- a/apps/client/src/services/content_renderer.ts
+++ b/apps/client/src/services/content_renderer.ts
@@ -13,6 +13,7 @@ import {
import DOMPurify from "dompurify";
import { h, type JSX, render } from "preact";
+import type { SaveState } from "../components/note_context.js";
import FAttachment from "../entities/fattachment.js";
import FNote from "../entities/fnote.js";
import imageContextMenuService from "../menus/image_context_menu.js";
@@ -20,7 +21,9 @@ import { t } from "../services/i18n.js";
import { type MediaEnvironment, showsFileActions } from "../widgets/type_widgets/file/media_environment.js";
import type { LlmChatContent, StoredMessage } from "../widgets/type_widgets/llm_chat/llm_chat_types.js";
import type { BoxSize } from "../widgets/type_widgets/text/CKEditorWithWatchdog.js";
-import renderText, { postProcessRichContent, renderChildrenList } from "./content_renderer_text.js";
+import renderText, {
+ postProcessRichContent, renderChildrenList, renderTextContent
+} from "./content_renderer_text.js";
import renderDoc from "./doc_renderer.js";
import { getMermaidConfig, postprocessMermaidSvg } from "./mermaid.js";
import { renderOfficeToHtml } from "./office_renderer.js";
@@ -119,6 +122,10 @@ export interface NoteEditor {
scheduleSave(note: FNote, getContent: () => string): void;
/** Reads the unsaved content of the note now, before its editor unmounts. */
release(noteId: string): void;
+ /** How the saving of the note goes, or `undefined` before its first change. */
+ getSaveState(noteId: string): SaveState | undefined;
+ /** Calls `listener` when the save state of a note changes, until the returned call. */
+ subscribeSaveState(listener: () => void): () => void;
}
const CODE_MIME_TYPES = new Set(["application/json"]);
@@ -259,16 +266,17 @@ async function renderEditableText(
$renderedContent: JQuery<HTMLElement>,
options: RenderOptions
) {
- const renderPreview = async () => {
+ const renderPreview = async (content: string) => {
const $preview = $("<div>");
- await renderText(note, $preview, options);
+ await renderTextContent(note, content, $preview, options);
return $preview[0];
};
- const [ preview, blob, { default: TextEmbed } ] = await Promise.all([
- renderPreview(),
+ const [ blob, { default: TextEmbed } ] = await Promise.all([
note.getBlob(),
import("../widgets/type_widgets/text/TextEmbed")
]);
+ const content = blob?.content ?? "";
+ const preview = await renderPreview(content);
const $container = $('<div class="text-embed">');
const container = $container.get(0);
@@ -276,7 +284,7 @@ async function renderEditableText(
await mountInteractiveWidget(h(TextEmbed, {
note,
editor: getContentEditor(note, options),
- content: blob?.content ?? "",
+ content,
preview,
renderPreview
}), container);
@@ -404,6 +412,13 @@ export interface ContentEditor {
getUnsavedContent(): string | undefined;
scheduleSave(getContent: () => string): void;
release(): void;
+ /**
+ * How the saving goes, for content that saves on its own rather than with the note that shows
+ * it, or `undefined`.
+ */
+ getSaveState?(): SaveState | undefined;
+ /** Calls `listener` when `getSaveState()` changes, until the returned call. */
+ subscribeSaveState?(listener: () => void): () => void;
}
/** `editor`, saving the changes to `attachment`. */
@@ -433,7 +448,9 @@ function getContentEditor(
canEdit: () => editor.canEdit(entity),
getUnsavedContent: () => editor.getUnsavedContent(entity.noteId),
scheduleSave: (getContent) => editor.scheduleSave(entity, getContent),
- release: () => editor.release(entity.noteId)
+ release: () => editor.release(entity.noteId),
+ getSaveState: () => editor.getSaveState(entity.noteId),
+ subscribeSaveState: (listener) => editor.subscribeSaveState(listener)
} : undefined;
}
diff --git a/apps/client/src/services/content_renderer_text.spec.ts b/apps/client/src/services/content_renderer_text.spec.ts
index e0f0615c05..6f5553d532 100644
--- a/apps/client/src/services/content_renderer_text.spec.ts
+++ b/apps/client/src/services/content_renderer_text.spec.ts
@@ -55,6 +55,7 @@ import renderText, {
applyInlineMermaid,
postProcessRichContent,
renderChildrenList,
+ renderTextContent,
rewriteMermaidDiagramsInContainer
} from "./content_renderer_text";
@@ -249,6 +250,22 @@ describe("Text content renderer", () => {
expect(items[1].textContent).toBe("Child note 3");
});
+ it("renders given content in place of the saved one, and the children list when empty", async () => {
+ const note = buildNote({
+ title: "Edited note",
+ content: "<p>Saved</p>",
+ children: [ { title: "Child note" } ]
+ });
+
+ const edited = document.createElement("div");
+ await renderTextContent(note, "<p>Edited</p>", $(edited));
+ expect(edited.querySelector(".ck-content")?.innerHTML).toBe("<p>Edited</p>");
+
+ const emptied = document.createElement("div");
+ await renderTextContent(note, "<p>&nbsp;</p>", $(emptied));
+ expect(emptied.querySelector("a")?.textContent).toBe("Child note");
+ });
+
it("renders nothing for an empty note with no children when noChildrenList is set", async () => {
const contentEl = document.createElement("div");
const note = buildNote({ title: "Empty note" });
diff --git a/apps/client/src/services/content_renderer_text.ts b/apps/client/src/services/content_renderer_text.ts
index daca0762ba..c04f84aa26 100644
--- a/apps/client/src/services/content_renderer_text.ts
+++ b/apps/client/src/services/content_renderer_text.ts
@@ -16,9 +16,21 @@ import { isHtmlEmpty } from "./utils.js";
export default async function renderText(note: FNote | FAttachment, $renderedContent: JQuery<HTMLElement>, options: RenderOptions = {}) {
// entity must be FNote
const blob = await note.getBlob();
+ await renderTextContent(note, blob?.content, $renderedContent, options);
+}
- if (blob && !isHtmlEmpty(blob.content)) {
- $renderedContent.append($('<div class="ck-content">').html(sanitizeNoteContentHtml(blob.content)));
+/**
+ * Renders `content`, the HTML of `note`, which can differ from the saved content, as while the
+ * note is edited. An empty note shows the list of its children instead.
+ */
+export async function renderTextContent(
+ note: FNote | FAttachment,
+ content: string | undefined,
+ $renderedContent: JQuery<HTMLElement>,
+ options: RenderOptions = {}
+) {
+ if (content !== undefined && !isHtmlEmpty(content)) {
+ $renderedContent.append($('<div class="ck-content">').html(sanitizeNoteContentHtml(content)));
await postProcessRichContent(note, $renderedContent, options);
} else if (note instanceof FNote && !options.noChildrenList) {
await renderChildrenList($renderedContent, note, options.includeArchivedNotes ?? false);
diff --git a/apps/client/src/widgets/EmbeddedNotePane.tsx b/apps/client/src/widgets/EmbeddedNotePane.tsx
index 0c12d8e979..03ccbba14c 100644
--- a/apps/client/src/widgets/EmbeddedNotePane.tsx
+++ b/apps/client/src/widgets/EmbeddedNotePane.tsx
@@ -45,7 +45,7 @@ import { NoteContextContext, ParentComponent } from "./react/react_utils";
export function useEmbeddedNoteContext(
note: FNote | undefined,
ntxId: string,
- { floatingToolbar = true }: { floatingToolbar?: boolean } = {}
+ { floatingToolbar = true, skipRecentNotes = false }: EmbeddedNoteContextOptions = {}
) {
const parentComponent = useContext(ParentComponent);
const [ noteContext ] = useState(() => new NoteContext(ntxId));
@@ -70,6 +70,7 @@ export function useEmbeddedNoteContext(
// Selecting a note in the pane is not the kind of navigation that should dismiss an
// open dialog.
keepActiveDialog: true,
+ skipRecentNotes,
viewScope: {
// A note held read-only only because of its size is editable here, as it is in the
// quick editor; one the reader has marked read-only stays that way.
@@ -84,6 +85,13 @@ export function useEmbeddedNoteContext(
return { noteContext, component };
}
+interface EmbeddedNoteContextOptions {
+ /** Whether the editor shows its buttons in a toolbar that follows the selection. */
+ floatingToolbar?: boolean;
+ /** Whether the note stays out of the recent notes. */
+ skipRecentNotes?: boolean;
+}
+
/**
* Announces that the pane's note context is going, giving whatever is being edited in it the chance
* to save. Closing a pane announces nothing on its own — the widgets are simply unmounted — so the
diff --git a/apps/client/src/widgets/layout/NoteBadges.tsx b/apps/client/src/widgets/layout/NoteBadges.tsx
index 51aea38451..d68031421b 100644
--- a/apps/client/src/widgets/layout/NoteBadges.tsx
+++ b/apps/client/src/widgets/layout/NoteBadges.tsx
@@ -4,6 +4,7 @@ import { isOfficeMimeType } from "@triliumnext/commons";
import { clsx } from "clsx";
import { useEffect, useState } from "preact/hooks";
+import type { SaveState } from "../../components/note_context";
import { copyTextWithToast } from "../../services/clipboard_ext";
import { t } from "../../services/i18n";
import { goToLinkExt } from "../../services/link";
@@ -180,12 +181,18 @@ const SAVE_STATE_DEBOUNCE_MS = 200;
export function SaveStatusBadge() {
const { noteContext} = useNoteContext();
const saveState = useGetContextDataFrom(noteContext, "saveState");
- const [debouncedState, setDebouncedState] = useState(saveState);
+
+ return <SaveStateBadge state={saveState?.state} />;
+}
+
+/** The badge of `state`, which follows a change of the state once it lasts a moment. */
+export function SaveStateBadge({ state }: { state: SaveState | undefined }) {
+ const [debouncedState, setDebouncedState] = useState(state);
useEffect(() => {
- const timer = setTimeout(() => setDebouncedState(saveState), SAVE_STATE_DEBOUNCE_MS);
+ const timer = setTimeout(() => setDebouncedState(state), SAVE_STATE_DEBOUNCE_MS);
return () => clearTimeout(timer);
- }, [saveState]);
+ }, [state]);
if (!debouncedState) return;
@@ -212,11 +219,11 @@ export function SaveStatusBadge() {
}
};
- const { icon, title, tooltip } = stateConfig[debouncedState.state];
+ const { icon, title, tooltip } = stateConfig[debouncedState];
return (
<Badge
- className={clsx("save-status-badge", debouncedState.state)}
+ className={clsx("save-status-badge", debouncedState)}
icon={icon}
text={title}
tooltip={tooltip}
diff --git a/apps/client/src/widgets/type_widgets/code/CodeEmbed.spec.tsx b/apps/client/src/widgets/type_widgets/code/CodeEmbed.spec.tsx
index 5b178fc4ca..6486278ed9 100644
--- a/apps/client/src/widgets/type_widgets/code/CodeEmbed.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/code/CodeEmbed.spec.tsx
@@ -3,6 +3,7 @@ import { act } from "preact/test-utils";
import { afterEach, describe, expect, it, vi } from "vitest";
import Component from "../../../components/component";
+import type { SaveState } from "../../../components/note_context";
import FAttachment from "../../../entities/fattachment";
import FBlob from "../../../entities/fblob";
import type FNote from "../../../entities/fnote";
@@ -175,6 +176,37 @@ describe("CodeEmbed", () => {
expect(view.state.doc.toString()).toBe("new");
});
+ it("shows how the saving goes in the title row of its embed while it edits", async () => {
+ const listeners = new Set<() => void>();
+ let state: SaveState = "unsaved";
+ const editor = buildEditor({
+ getSaveState: () => state,
+ subscribeSaveState: (listener) => {
+ listeners.add(listener);
+ return () => listeners.delete(listener);
+ }
+ });
+ const { figure } = await mount(buildCodeNote("x"), editor, {
+ content: "x",
+ isEditable: true
+ });
+ const findBadge = (name: string) =>
+ figure.querySelector(`.include-note-badges > .save-status-badge.${name}`);
+ await vi.waitFor(() => expect(findBadge("unsaved")).not.toBeNull());
+
+ act(() => {
+ state = "error";
+ for (const listener of listeners) listener();
+ });
+ await vi.waitFor(() => expect(findBadge("error")).not.toBeNull());
+
+ await act(async () => {
+ delete figure.dataset.editable;
+ await Promise.resolve();
+ });
+ expect(figure.querySelector(".save-status-badge")).toBeNull();
+ });
+
it("loads the note as saved elsewhere, unless it has unsaved changes", async () => {
const { figure } = await mount(buildCodeNote("saved"), buildEditor(), {
content: "stale",
@@ -215,9 +247,17 @@ async function mount(
if (options.isEditable) {
figure.dataset.editable = "true";
}
+ const wrapper = document.createElement("div");
+ wrapper.className = "include-note-wrapper";
+ const titleRow = document.createElement("div");
+ titleRow.className = "include-note-title-row";
+ const badges = document.createElement("div");
+ badges.className = "include-note-badges";
+ titleRow.append(badges);
const box = document.createElement("div");
box.className = "include-note-content";
- figure.append(box);
+ wrapper.append(titleRow, box);
+ figure.append(wrapper);
document.body.append(figure);
figures.push(figure);
diff --git a/apps/client/src/widgets/type_widgets/code/CodeEmbed.tsx b/apps/client/src/widgets/type_widgets/code/CodeEmbed.tsx
index e3911d65c6..f135308f2c 100644
--- a/apps/client/src/widgets/type_widgets/code/CodeEmbed.tsx
+++ b/apps/client/src/widgets/type_widgets/code/CodeEmbed.tsx
@@ -1,14 +1,16 @@
import "./CodeEmbed.css";
-import { lazy } from "preact/compat";
+import { createPortal, type RefObject } from "preact";
+import { lazy, useSyncExternalStore } 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 { SaveStateBadge } from "../../layout/NoteBadges";
import { useNoteBlob, useNoteProperty, useTriliumEvent } from "../../react/hooks";
import {
- EditableEmbedContent, useEditableEmbed, useEmbedPreview
+ EditableEmbedContent, useEditableEmbed, useEmbedBadgeSlot, useEmbedPreview
} from "../text/editable_embed";
const CodeEmbedEditor = lazy(() => import("./CodeEmbedEditor"));
@@ -46,23 +48,46 @@ export default function CodeEmbed({
);
return (
- <EditableEmbedContent
- rootRef={rootRef}
- className="code-embed-content"
- isEditing={isEditing}
- preview={shownPreview}
- >
- <CodeEmbedEditor
- note={note}
- editor={editor}
- content={content}
- mime={mime}
- onClose={setContent}
- />
- </EditableEmbedContent>
+ <>
+ <EditableEmbedContent
+ rootRef={rootRef}
+ className="code-embed-content"
+ isEditing={isEditing}
+ preview={shownPreview}
+ >
+ <CodeEmbedEditor
+ note={note}
+ editor={editor}
+ content={content}
+ mime={mime}
+ onClose={setContent}
+ />
+ </EditableEmbedContent>
+ <SaveStatus rootRef={rootRef} editor={editor} isShown={isEditing} />
+ </>
);
}
+interface SaveStatusProps {
+ rootRef: RefObject<HTMLElement | null>;
+ editor: ContentEditor;
+ isShown: boolean;
+}
+
+/**
+ * The save state of `editor` in the title row of the embed around `rootRef`, while `isShown`, for
+ * content that saves on its own.
+ */
+function SaveStatus({ rootRef, editor, isShown }: SaveStatusProps) {
+ const slot = useEmbedBadgeSlot(rootRef, isShown);
+ const state = useSyncExternalStore(
+ editor.subscribeSaveState ?? subscribeToNothing,
+ () => editor.getSaveState?.()
+ );
+
+ return slot && createPortal(<SaveStateBadge state={state} />, slot);
+}
+
/**
* Shows the content of `entity` each time it saves, also when another embed of it saved it.
* Unsaved changes made in the embed are kept, and replace that content when they save.
@@ -96,3 +121,7 @@ function useSavedContent(
}
}, [ content ]);
}
+
+function subscribeToNothing() {
+ return () => {};
+}
diff --git a/apps/client/src/widgets/type_widgets/text/TextEmbed.spec.tsx b/apps/client/src/widgets/type_widgets/text/TextEmbed.spec.tsx
index bb3037488a..e5a4e7ba20 100644
--- a/apps/client/src/widgets/type_widgets/text/TextEmbed.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/text/TextEmbed.spec.tsx
@@ -4,8 +4,11 @@ import { act } from "preact/test-utils";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import appContext from "../../../components/app_context";
+import NoteContext from "../../../components/note_context";
+import FBlob from "../../../entities/fblob";
import type FNote from "../../../entities/fnote";
import froca from "../../../services/froca";
+import LoadResults from "../../../services/load_results";
import type { ContentEditor } from "../../../services/content_renderer";
import { buildNote } from "../../../test/easy-froca";
import { useTriliumEvent } from "../../react/hooks";
@@ -17,6 +20,8 @@ import TextEmbed from "./TextEmbed";
const editorAskedToSave = vi.fn();
const editorProps = vi.fn();
+/** What the text editor holds. */
+let editorData = "";
/** The text editor, which has a spec of its own. It listens for what a real editor listens for. */
vi.mock("./EditableText", () => ({
@@ -24,7 +29,18 @@ vi.mock("./EditableText", () => ({
const isNested = useContext(NestedEmbedContext);
editorProps({ ...props, isNested });
useTriliumEvent("beforeNoteContextRemove", editorAskedToSave);
- return <div className="editable-text-stub" />;
+ return (
+ <div className="editable-text-stub">
+ <div
+ className="ck-editor__editable"
+ ref={(element) => {
+ if (element) {
+ Object.assign(element, { ckeditorInstance: { getData: () => editorData } });
+ }
+ }}
+ />
+ </div>
+ );
}
}));
@@ -72,6 +88,7 @@ describe("TextEmbed", () => {
});
it("edits in a note context of its own, and saves before the editor goes away", async () => {
+ const saveToRecentNotes = vi.spyOn(NoteContext.prototype, "saveToRecentNotes");
const note = buildTextNote("edited");
const { figure } = await mount(note, buildEditor(), { isEditable: true, hasFixedToolbar: true });
@@ -85,6 +102,9 @@ describe("TextEmbed", () => {
// Inside an editor with a fixed toolbar, that toolbar shows the buttons of this editor.
expect(props.viewScope).toMatchObject({ viewMode: "default", floatingToolbar: false });
expect(props.isNested).toBe(true);
+ // Editing an included note does not add it to the recent notes.
+ expect(saveToRecentNotes).not.toHaveBeenCalled();
+ saveToRecentNotes.mockRestore();
// 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);
@@ -106,6 +126,76 @@ describe("TextEmbed", () => {
expect(figure.querySelector(".editable-text-stub")).toBeNull();
expect(figure.querySelector(".editable-embed-preview")).not.toBeNull();
});
+
+ it("previews what the editor holds once it closes, before the note saves", async () => {
+ const note = buildTextNote("closing");
+ const renderPreview = vi.fn(async (content: string) => buildPreview(content));
+ let finishSave = () => {};
+ editorAskedToSave.mockImplementationOnce(() => new Promise<void>((resolve) => {
+ finishSave = resolve;
+ }));
+ const { figure } = await mount(note, buildEditor(), { isEditable: true, renderPreview });
+ await vi.waitFor(() => {
+ expect(figure.querySelector(".editable-text-stub")).not.toBeNull();
+ }, { timeout: 5000 });
+
+ editorData = "<p>Typed just now</p>";
+ await act(async () => {
+ delete figure.dataset.editable;
+ await Promise.resolve();
+ });
+ const shownPreview = () => figure.querySelector(".editable-embed-preview")?.innerHTML;
+ await vi.waitFor(() => expect(shownPreview()).toBe("<div><p>Typed just now</p></div>"));
+
+ // A save made before the editor closed lands while its last save runs.
+ note.getBlob = async () => buildBlob("<p>Typed</p>");
+ const earlierSave = new LoadResults([]);
+ earlierSave.addNoteContent(note.noteId, "other-component");
+ await act(async () => {
+ await appContext.handleEvent("entitiesReloaded", { loadResults: earlierSave });
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ });
+ expect(shownPreview()).toBe("<div><p>Typed just now</p></div>");
+ expect(renderPreview).toHaveBeenCalledExactlyOnceWith("<p>Typed just now</p>");
+ await act(async () => {
+ finishSave();
+ });
+ });
+
+ it("loads the note once the save of the editor it replaces lands", async () => {
+ const note = buildTextNote("redrawn");
+ const countEditors = () =>
+ new Set(editorProps.mock.calls.map(([ props ]) => props.ntxId)).size;
+ let finishSave = () => {};
+ editorAskedToSave.mockImplementationOnce(() => new Promise<void>((resolve) => {
+ finishSave = resolve;
+ }));
+ const { figure: first } = await mount(note, buildEditor(), { isEditable: true });
+ await vi.waitFor(() => expect(countEditors()).toBe(1), { timeout: 5000 });
+
+ // The host draws the embed again, as for a change of its size.
+ const firstBox = first.querySelector(".include-note-content");
+ expect(firstBox).not.toBeNull();
+ await act(async () => {
+ if (firstBox) render(null, firstBox);
+ });
+ expect(editorAskedToSave).toHaveBeenCalledOnce();
+ const { figure: second } = await mount(note, buildEditor(), { isEditable: true });
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ });
+ expect(countEditors()).toBe(1);
+ expect(second.querySelector(".editable-embed-preview")).not.toBeNull();
+
+ // The content fetched before the save lands is not loaded.
+ froca.blobPromises[`notes-${note.noteId}`] = Promise.resolve(null);
+ await act(async () => {
+ finishSave();
+ });
+ await vi.waitFor(() => expect(countEditors()).toBe(2), { timeout: 5000 });
+ expect(froca.blobPromises[`notes-${note.noteId}`]).toBeUndefined();
+ expect(second.querySelector(".editable-text-stub")).not.toBeNull();
+ });
});
interface MountOptions {
@@ -113,6 +203,7 @@ interface MountOptions {
isEditable?: boolean;
/** Whether the editor around the embed has a fixed toolbar, rather than a floating one. */
hasFixedToolbar?: boolean;
+ renderPreview?: (content: string) => Promise<HTMLElement>;
}
/** Renders `TextEmbed` in the markup of an embed, as the host does. */
@@ -149,7 +240,7 @@ async function mount(note: FNote, editor: ContentEditor | undefined, options: Mo
editor={editor}
content={content}
preview={options.preview ?? buildPreview(content)}
- renderPreview={async () => buildPreview(content)}
+ renderPreview={options.renderPreview ?? (async (html) => buildPreview(html))}
/>
</ParentComponent.Provider>,
box
@@ -175,6 +266,16 @@ function buildEditor(): ContentEditor {
};
}
+function buildBlob(content: string) {
+ return new FBlob({
+ blobId: `blob-${content}`,
+ content,
+ contentLength: content.length,
+ dateModified: "",
+ utcDateModified: ""
+ });
+}
+
function buildPreview(content: string) {
const div = document.createElement("div");
div.innerHTML = content;
diff --git a/apps/client/src/widgets/type_widgets/text/TextEmbed.tsx b/apps/client/src/widgets/type_widgets/text/TextEmbed.tsx
index 0ffff70c30..a2b417e1fd 100644
--- a/apps/client/src/widgets/type_widgets/text/TextEmbed.tsx
+++ b/apps/client/src/widgets/type_widgets/text/TextEmbed.tsx
@@ -1,8 +1,9 @@
import { lazy } from "preact/compat";
-import { useRef } from "preact/hooks";
+import { useEffect, useRef, useState } from "preact/hooks";
import type FNote from "../../../entities/fnote";
import type { ContentEditor } from "../../../services/content_renderer";
+import froca from "../../../services/froca";
import { useNoteBlob } from "../../react/hooks";
import {
EditableEmbedContent, hasFixedToolbarAround, useEditableEmbed, useEmbedPreview
@@ -18,8 +19,8 @@ interface TextEmbedProps {
content: string;
/** The rendered note. */
preview: HTMLElement;
- /** Renders the note again, after a change. */
- renderPreview: () => Promise<HTMLElement>;
+ /** Renders the note with `content`, after a change. */
+ renderPreview: (content: string) => Promise<HTMLElement>;
}
/**
@@ -27,7 +28,7 @@ interface TextEmbedProps {
* Editable toggle of its embed is on.
*/
export default function TextEmbed({
- note, editor, content, preview, renderPreview
+ note, editor, content: initialContent, preview, renderPreview
}: TextEmbedProps) {
const rootRef = useRef<HTMLDivElement>(null);
const { isEditing } = useEditableEmbed(rootRef, {
@@ -35,9 +36,17 @@ export default function TextEmbed({
note,
focusTarget: ".ck-editor__editable"
});
+ const [ content, setContent ] = useState(initialContent);
const blob = useNoteBlob(note);
+ // While the last save of the editor runs, the preview shows what the editor held, rather than
+ // what an earlier save stored.
+ useEffect(() => {
+ if (blob && !getClosingSave(note.noteId)) {
+ setContent(blob.content);
+ }
+ }, [ blob ]);
const shownPreview =
- useEmbedPreview(preview, blob?.content ?? content, renderPreview, isEditing);
+ useEmbedPreview(preview, content, () => renderPreview(content), isEditing);
return (
<EditableEmbedContent
@@ -49,7 +58,34 @@ export default function TextEmbed({
<TextEmbedEditor
note={note}
hasFixedToolbar={isEditing && hasFixedToolbarAround(rootRef.current)}
+ onClose={setContent}
/>
</EditableEmbedContent>
);
}
+
+/** The last saves of the editors of included notes that went away, by note ID, until they land. */
+const closingSaves = new Map<string, Promise<void>>();
+
+/**
+ * Tracks `save`, the last save of an editor of `noteId` that went away, until it lands. Then drops
+ * the content that `froca` fetched before, so that the next editor loads what the save stored.
+ */
+export function trackClosingSave(noteId: string, save: Promise<unknown> | null) {
+ const tracked: Promise<void> = Promise.resolve(save)
+ .catch(() => {
+ // Failures are logged by `SpacedUpdate` and retried.
+ })
+ .then(() => {
+ delete froca.blobPromises[`notes-${noteId}`];
+ if (closingSaves.get(noteId) === tracked) {
+ closingSaves.delete(noteId);
+ }
+ });
+ closingSaves.set(noteId, tracked);
+}
+
+/** The last save of an editor of `noteId` that went away, while it runs. */
+export function getClosingSave(noteId: string) {
+ return closingSaves.get(noteId);
+}
diff --git a/apps/client/src/widgets/type_widgets/text/TextEmbedEditor.tsx b/apps/client/src/widgets/type_widgets/text/TextEmbedEditor.tsx
index 727f8af1dd..aa60d4d028 100644
--- a/apps/client/src/widgets/type_widgets/text/TextEmbedEditor.tsx
+++ b/apps/client/src/widgets/type_widgets/text/TextEmbedEditor.tsx
@@ -1,6 +1,6 @@
import "./TextEmbedEditor.css";
-import { createPortal } from "preact";
+import { createPortal, type RefObject } from "preact";
import { useLayoutEffect, useRef, useState } from "preact/hooks";
import type FNote from "../../../entities/fnote";
@@ -11,42 +11,62 @@ import {
import { SaveStatusBadge } from "../../layout/NoteBadges";
import { useLegacyComponentElement, useNoteContext } from "../../react/hooks";
import EditableText from "./EditableText";
-import { NestedEmbedContext, useEmbedBadgeSlot } from "./editable_embed";
+import { findTextEditorIn, NestedEmbedContext, useEmbedBadgeSlot } from "./editable_embed";
+import { getClosingSave, trackClosingSave } from "./TextEmbed";
interface TextEmbedEditorProps {
note: FNote;
/** Whether the editor around the embed has a fixed toolbar, rather than a floating one. */
hasFixedToolbar: boolean;
+ /** Receives the content of the editor as it goes away, which can be unsaved yet. */
+ onClose(content: string): void;
}
/**
* 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, hasFixedToolbar }: TextEmbedEditorProps) {
+export default function TextEmbedEditor({ note, hasFixedToolbar, onClose }: TextEmbedEditorProps) {
+ // The embed shows its preview until the editor that it replaces has saved the note.
+ const closingSave = getClosingSave(note.noteId);
+ if (closingSave) throw closingSave;
+
const [ ntxId ] = useState(() => `_embed_${randomString(10)}`);
+ const rootRef = useRef<HTMLDivElement>(null);
+ const onCloseRef = useRef(onClose);
+ onCloseRef.current = onClose;
// Inside an editor with a fixed toolbar, that toolbar shows the buttons of this editor while
// it has the focus.
- const { noteContext, component } =
- useEmbeddedNoteContext(note, ntxId, { floatingToolbar: !hasFixedToolbar });
+ const { noteContext, component } = useEmbeddedNoteContext(note, ntxId, {
+ floatingToolbar: !hasFixedToolbar,
+ skipRecentNotes: true
+ });
// A layout cleanup runs while the editor is still mounted, so it saves what is left.
useLayoutEffect(() => () => {
- void announceEmbeddedNoteClosing(component, ntxId);
+ trackClosingSave(note.noteId, announceEmbeddedNoteClosing(component, ntxId));
+ const content = findTextEditorIn(rootRef.current)?.getData();
+ if (content !== undefined) {
+ onCloseRef.current(content);
+ }
}, [ component, ntxId ]);
return (
<EmbeddedNoteScope component={component} noteContext={noteContext}>
<NestedEmbedContext.Provider value={true}>
- <ScopedEditor note={note} />
+ <ScopedEditor rootRef={rootRef} note={note} />
</NestedEmbedContext.Provider>
</EmbeddedNoteScope>
);
}
+interface ScopedEditorProps {
+ rootRef: RefObject<HTMLDivElement | null>;
+ note: FNote;
+}
+
/** The editor, once the note context of the embed holds `note`. */
-function ScopedEditor({ note }: { note: FNote }) {
- const rootRef = useRef<HTMLDivElement>(null);
+function ScopedEditor({ rootRef, note }: ScopedEditorProps) {
const { note: contextNote, noteContext, ntxId, parentComponent } = useNoteContext();
// The plugins of the editor find their host by the element of its component.
useLegacyComponentElement(rootRef);
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.ts
index da4f53504b..5f328eba57 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
@@ -191,6 +191,41 @@ describe("NoteSaves", () => {
expect(saves.getUnsavedContent("code1")).toBe("changed meanwhile");
expect(saves.getUnsavedContent("code2")).toBeUndefined();
});
+
+ it("tracks the save state of each note, and tells its listeners", async () => {
+ const saves = new NoteSaves(vi.fn(), "host");
+ const listener = vi.fn();
+ const unsubscribe = saves.subscribeSaveState(listener);
+ const first = buildCodeNote("code1");
+ const second = buildCodeNote("code2");
+ expect(saves.getSaveState("code1")).toBeUndefined();
+
+ saves.scheduleSave(first, () => "one");
+ saves.scheduleSave(second, () => "two");
+ expect(saves.getSaveState("code1")).toBe("unsaved");
+ expect(listener).toHaveBeenCalled();
+
+ const seen: [ string, string | undefined ][] = [];
+ await expect(saves.save(saves.collect(), async ({ note }) => {
+ seen.push([ note.noteId, saves.getSaveState(note.noteId) ]);
+ if (note.noteId === "code2") throw new Error("offline");
+ })).rejects.toThrow("offline");
+ expect(seen).toStrictEqual([ [ "code1", "saving" ], [ "code2", "saving" ] ]);
+ expect(saves.getSaveState("code1")).toBe("saved");
+ expect(saves.getSaveState("code2")).toBe("error");
+ expect(saves.getUnsavedContent("code1")).toBeUndefined();
+
+ // A change made while the note saves keeps it unsaved.
+ await saves.save(saves.collect(), async () => {
+ saves.scheduleSave(second, () => "newer");
+ });
+ expect(saves.getSaveState("code2")).toBe("unsaved");
+
+ unsubscribe();
+ listener.mockClear();
+ saves.scheduleSave(first, () => "changed");
+ expect(listener).not.toHaveBeenCalled();
+ });
});
describe("useNoteEditor", () => {
@@ -218,8 +253,9 @@ describe("useNoteEditor", () => {
expect(serverPut).toHaveBeenCalledExactlyOnceWith(
"notes/code1/data", { content: "first" }, component.componentId);
expect(editor?.getUnsavedContent("code1")).toBeUndefined();
- expect(noteContext.setContextData)
- .toHaveBeenLastCalledWith("saveState", { state: "saved" });
+ // The embed of the note shows its save state, not the indicator of the host note.
+ expect(editor?.getSaveState("code1")).toBe("saved");
+ expect(noteContext.setContextData).not.toHaveBeenCalled();
editor?.scheduleSave(code, () => "second");
editor?.release("code1");
diff --git a/apps/client/src/widgets/type_widgets/text/attachment_saves.ts b/apps/client/src/widgets/type_widgets/text/attachment_saves.ts
index bd44d6c51e..83ba4dee31 100644
--- a/apps/client/src/widgets/type_widgets/text/attachment_saves.ts
+++ b/apps/client/src/widgets/type_widgets/text/attachment_saves.ts
@@ -1,6 +1,6 @@
import { useCallback, useContext, useEffect, useRef, useState } from "preact/hooks";
-import type NoteContext from "../../../components/note_context";
+import type { default as NoteContext, SaveState } from "../../../components/note_context";
import type FAttachment from "../../../entities/fattachment";
import type FNote from "../../../entities/fnote";
import type { AttachmentEditor, NoteEditor } from "../../../services/content_renderer";
@@ -33,7 +33,7 @@ interface PendingSave<T> {
*/
abstract class PendingSaves<T, I extends object> {
protected pending = new Map<string, PendingSave<T>>();
- private sentRevisions = new WeakMap<I[], Map<string, number>>();
+ private sentRevisions = new WeakMap<I, { id: string; revision: number }>();
getUnsavedContent(id: string) {
const save = this.pending.get(id);
@@ -50,14 +50,10 @@ abstract class PendingSaves<T, I extends object> {
/** Drops the changes that `items`, as returned by `collectItems()`, saved. */
markSaved(items: I[] | undefined) {
- const revisions = items && this.sentRevisions.get(items);
- if (!revisions) {
- return;
- }
-
- for (const [ id, revision ] of revisions) {
- if (this.pending.get(id)?.revision === revision) {
- this.pending.delete(id);
+ for (const item of items ?? []) {
+ const sent = this.sentRevisions.get(item);
+ if (sent && this.pending.get(sent.id)?.revision === sent.revision) {
+ this.pending.delete(sent.id);
}
}
}
@@ -70,13 +66,12 @@ abstract class PendingSaves<T, I extends object> {
/** One item for each change, with the content read at the time of the call. */
protected collectItems(toItem: (id: string, entity: T, content: string) => I) {
const items: I[] = [];
- const revisions = new Map<string, number>();
for (const [ id, save ] of this.pending) {
- items.push(toItem(id, save.entity, readContent(save)));
- revisions.set(id, save.revision);
+ const item = toItem(id, save.entity, readContent(save));
+ this.sentRevisions.set(item, { id, revision: save.revision });
+ items.push(item);
}
- this.sentRevisions.set(items, revisions);
return items;
}
}
@@ -125,6 +120,9 @@ export default class AttachmentSaves
* shows. `useNoteEditor()` saves them.
*/
export class NoteSaves extends PendingSaves<FNote, SavedNote> implements NoteEditor {
+ private saveStates = new Map<string, SaveState>();
+ private stateListeners = new Set<() => void>();
+
/**
* @param scheduleUpdate schedules a save.
* @param componentId the component that saves the changes.
@@ -144,13 +142,52 @@ export class NoteSaves extends PendingSaves<FNote, SavedNote> implements NoteEdi
scheduleSave(note: FNote, getContent: () => string) {
this.schedule(note.noteId, note, getContent);
+ this.setSaveState(note.noteId, "unsaved");
this.scheduleUpdate();
}
+ getSaveState(noteId: string) {
+ return this.saveStates.get(noteId);
+ }
+
+ subscribeSaveState(listener: () => void) {
+ this.stateListeners.add(listener);
+ return () => {
+ this.stateListeners.delete(listener);
+ };
+ }
+
/** The notes to save, read at the time of the call. */
collect() {
return this.collectItems((_noteId, note, content) => ({ note, content }));
}
+
+ /**
+ * Saves `items`, as returned by `collect()`, one note after the other with `saveNote`. Stops at
+ * the first note that fails to save, and rejects with its error.
+ */
+ async save(items: SavedNote[], saveNote: (item: SavedNote) => Promise<unknown>) {
+ for (const item of items) {
+ const { noteId } = item.note;
+ this.setSaveState(noteId, "saving");
+ try {
+ await saveNote(item);
+ } catch (e) {
+ this.setSaveState(noteId, "error");
+ throw e;
+ }
+
+ this.markSaved([ item ]);
+ this.setSaveState(noteId, this.pending.has(noteId) ? "unsaved" : "saved");
+ }
+ }
+
+ private setSaveState(noteId: string, state: SaveState) {
+ this.saveStates.set(noteId, state);
+ for (const listener of this.stateListeners) {
+ listener();
+ }
+ }
}
/**
@@ -215,21 +252,14 @@ export function useNoteEditor(noteContext: NoteContext | null | undefined): Note
() => noteContextRef.current?.noteId ?? undefined
));
- const [ spacedUpdate ] = useState(() => new SpacedUpdate<SavedNote[]>(
- {
- key: null,
- prepare: () => saves.collect(),
- commit: async (notes) => {
- for (const { note, content } of notes) {
- protected_session_holder.touchProtectedSessionIfNecessary(note);
- await server.put(`notes/${note.noteId}/data`, { content }, saves.componentId);
- }
- saves.markSaved(notes);
- }
- },
- undefined,
- (state) => noteContextRef.current?.setContextData("saveState", { state })
- ));
+ const [ spacedUpdate ] = useState(() => new SpacedUpdate<SavedNote[]>({
+ key: null,
+ prepare: () => saves.collect(),
+ commit: (notes) => saves.save(notes, ({ note, content }) => {
+ protected_session_holder.touchProtectedSessionIfNecessary(note);
+ return server.put(`notes/${note.noteId}/data`, { content }, saves.componentId);
+ })
+ }));
useSaveBeforeLeaving(spacedUpdate, noteContext);
useSaveOnUnmount(spacedUpdate);
diff --git a/apps/client/src/widgets/type_widgets/text/editable_embed.tsx b/apps/client/src/widgets/type_widgets/text/editable_embed.tsx
index 0499ca7144..b74cd3527f 100644
--- a/apps/client/src/widgets/type_widgets/text/editable_embed.tsx
+++ b/apps/client/src/widgets/type_widgets/text/editable_embed.tsx
@@ -172,17 +172,18 @@ export function useNestedEditor(ntxId: string | null | undefined) {
/**
* The element in the title row of the embed around `rootRef` that holds the badges of its content,
- * such as the save status of an included note, or `null`.
+ * such as the save status of an included note, or `null`. `null` while not `isShown` as well:
+ * content mounts before its embed box takes it in, so it looks for the element once it shows.
*/
-export function useEmbedBadgeSlot(rootRef: RefObject<HTMLElement | null>) {
+export function useEmbedBadgeSlot(rootRef: RefObject<HTMLElement | null>, isShown = true) {
const [ slot, setSlot ] = useState<HTMLElement | null>(null);
useEffect(() => {
- const wrapper = rootRef.current?.closest(".include-note-wrapper");
+ const wrapper = isShown ? rootRef.current?.closest(".include-note-wrapper") : null;
setSlot(wrapper?.querySelector<HTMLElement>(
":scope > .include-note-title-row > .include-note-badges"
) ?? null);
- }, [ rootRef ]);
+ }, [ rootRef, isShown ]);
return slot;
}
@@ -196,6 +197,11 @@ export function hasFixedToolbarAround(element: HTMLElement | null) {
return !!editable?.ckeditorInstance?.ui.view.toolbar;
}
+/** The text editor whose editable root is in `element`, as the editor of an included note. */
+export function findTextEditorIn(element: HTMLElement | null) {
+ return element?.querySelector<EditorRootElement>(EDITOR_ROOT_SELECTOR)?.ckeditorInstance;
+}
+
/** The editable root of a text editor, which CKEditor gives a reference to the editor. */
type EditorRootElement = HTMLElement & { ckeditorInstance?: CKTextEditor };
diff --git a/packages/ckeditor5/src/plugins/copy_anchor_link.spec.ts b/packages/ckeditor5/src/plugins/copy_anchor_link.spec.ts
index 7bc8a1a20a..67ebe653c7 100644
--- a/packages/ckeditor5/src/plugins/copy_anchor_link.spec.ts
+++ b/packages/ckeditor5/src/plugins/copy_anchor_link.spec.ts
@@ -9,14 +9,17 @@ describe("CopyAnchorLinkButton", () => {
let editor: ClassicEditor;
let getActiveContextNote: ReturnType<typeof vi.fn>;
let getReferenceLinkTitleSync: ReturnType<typeof vi.fn>;
+ let getComponentByEl: ReturnType<typeof vi.fn>;
let copyHtml: ReturnType<typeof vi.fn>;
beforeEach(async () => {
getActiveContextNote = vi.fn(() => ({ noteId: "noteAbc" }));
getReferenceLinkTitleSync = vi.fn(() => "Some title");
+ getComponentByEl = vi.fn(() => ({}));
installGlobMock({
getActiveContextNote,
- getReferenceLinkTitleSync
+ getReferenceLinkTitleSync,
+ getComponentByEl
});
copyHtml = vi.fn();
@@ -45,6 +48,17 @@ describe("CopyAnchorLinkButton", () => {
expect(copyHtml).toHaveBeenCalledWith(`<a class="reference-link" href="${href}">Some title</a>`, href);
});
+ it("links to the note of the editor, which can differ from the active one", () => {
+ getComponentByEl.mockReturnValue({ getNoteId: () => "includedNote" });
+ setModelData(editor.model, "<paragraph>[<bookmark bookmarkId=\"anchor\"></bookmark>]</paragraph>");
+
+ getButton().fire("execute");
+
+ const href = "#root/includedNote?bookmark=anchor";
+ expect(getComponentByEl).toHaveBeenCalledWith(editor.editing.view.getDomRoot());
+ expect(copyHtml).toHaveBeenCalledWith(`<a class="reference-link" href="${href}">Some title</a>`, href);
+ });
+
it("escapes HTML special characters in the generated link", () => {
getReferenceLinkTitleSync.mockReturnValue("a<b>&\"c");
setModelData(editor.model, "<paragraph>[<bookmark bookmarkId=\"anchor\"></bookmark>]</paragraph>");
diff --git a/packages/ckeditor5/src/plugins/copy_anchor_link.ts b/packages/ckeditor5/src/plugins/copy_anchor_link.ts
index e989529236..97fcceb412 100644
--- a/packages/ckeditor5/src/plugins/copy_anchor_link.ts
+++ b/packages/ckeditor5/src/plugins/copy_anchor_link.ts
@@ -30,7 +30,11 @@ export default class CopyAnchorLinkButton extends Plugin {
if (selectedElement?.name === "bookmark") {
const bookmarkId = selectedElement.getAttribute("bookmarkId") as string;
- const noteId = glob.getActiveContextNote()?.noteId;
+ // The note the editor holds, which is not the active tab's in an included note.
+ const component = glob.getComponentByEl<EditorComponent>(
+ editor.editing.view.getDomRoot()
+ );
+ const noteId = component?.getNoteId?.() ?? glob.getActiveContextNote()?.noteId;
if (noteId && bookmarkId) {
const href = `#root/${noteId}?bookmark=${encodeURIComponent(bookmarkId)}`;