Skip to content

Build your personal knowledge base with Trilium Notes

client/text editor: fix some issues, improve test coverage

Adorian Doranc88e567e520e
diff --git a/apps/client/src/components/app_context.ts b/apps/client/src/components/app_context.ts
index 1684869fc5..852ff9ba71 100644
--- a/apps/client/src/components/app_context.ts
+++ b/apps/client/src/components/app_context.ts
@@ -389,7 +389,6 @@ export type CommandMappings = {
pasteMarkdownIntoText: CommandData;
cutIntoNote: CommandData;
saveNoteDetailNow: CommandData;
- addChildNoteToText: CommandData;
addIncludeNoteToText: CommandData;
editReadOnlyNote: CommandData;
toggleRibbonTabClassicEditor: CommandData;
diff --git a/apps/client/src/widgets/dialogs/PopupEditor.spec.tsx b/apps/client/src/widgets/dialogs/PopupEditor.spec.tsx
index 0f969048bf..5b29da69c1 100644
--- a/apps/client/src/widgets/dialogs/PopupEditor.spec.tsx
+++ b/apps/client/src/widgets/dialogs/PopupEditor.spec.tsx
@@ -421,21 +421,24 @@ describe("PopupEditor", () => {
it("selects the title instead of the content when asked to, for that open only", async () => {
const handleEvent = vi.spyOn(parent, "handleEvent");
- const show = () =>
- act(async () => container.querySelector<HTMLElement>(".shown-stub")?.click());
+ const focusCalls = () =>
+ handleEvent.mock.calls.filter(([ name ]) => name.startsWith("focus"));
+ const selectTitle = [ "focusAndSelectTitle", { isNewNote: true, ntxId: "_popup-editor" } ];
+ const focusContent = [ "focusOnDetail", { ntxId: "_popup-editor" } ];
await openPopup({ noteIdOrPath: "root/n1", selectTitle: true });
- await show();
- expect(handleEvent).toHaveBeenCalledWith("focusAndSelectTitle", {
- isNewNote: true, ntxId: "_popup-editor"
- });
- expect(handleEvent).not.toHaveBeenCalledWith("focusOnDetail", expect.anything());
+ expect(focusCalls()).toEqual([]);
+ await act(async () => container.querySelector<HTMLElement>(".shown-stub")?.click());
+ expect(focusCalls()).toEqual([ selectTitle ]);
+ // Opened in the popup already on show, which fires no `shown` event.
handleEvent.mockClear();
await openPopup({ noteIdOrPath: "root/n2" });
- await show();
- expect(handleEvent).toHaveBeenCalledWith("focusOnDetail", { ntxId: "_popup-editor" });
- expect(handleEvent).not.toHaveBeenCalledWith("focusAndSelectTitle", expect.anything());
+ expect(focusCalls()).toEqual([ focusContent ]);
+
+ handleEvent.mockClear();
+ await openPopup({ noteIdOrPath: "root/n3", selectTitle: true });
+ expect(focusCalls()).toEqual([ selectTitle ]);
});
it("opens a nested popup over itself, which answers only its own command and context", async () => {
diff --git a/apps/client/src/widgets/dialogs/PopupEditor.tsx b/apps/client/src/widgets/dialogs/PopupEditor.tsx
index 4ff3fb6ab6..04263bc7f1 100644
--- a/apps/client/src/widgets/dialogs/PopupEditor.tsx
+++ b/apps/client/src/widgets/dialogs/PopupEditor.tsx
@@ -50,6 +50,8 @@ export default function PopupEditor({ ntxId = POPUP_EDITOR_NTX_ID, openCommand =
const [ stacked, setStacked ] = useState(false);
const [ switchable, setSwitchable ] = useState(false);
const selectsTitleRef = useRef(false);
+ /** Set while a note opened in the popup already on show waits to render before taking focus. */
+ const focusesOnRenderRef = useRef(false);
const parentComponent = useContext(ParentComponent);
const [ noteContext, setNoteContext ] = useState(() => new NoteContext(ntxId));
const modalRef = useRef<HTMLDivElement>(null);
@@ -74,6 +76,7 @@ export default function PopupEditor({ ntxId = POPUP_EDITOR_NTX_ID, openCommand =
setStacked(!!document.querySelector(".modal.show"));
setSwitchable(!!showNoteTypeSwitcher);
selectsTitleRef.current = !!selectTitle;
+ focusesOnRenderRef.current = shown;
const hasUserSetNoteReadOnly = note.hasLabel("readOnly");
await noteContext.setNote(noteIdOrPath, {
@@ -92,6 +95,25 @@ export default function PopupEditor({ ntxId = POPUP_EDITOR_NTX_ID, openCommand =
setShown(true);
});
+ function focusOpenedNote() {
+ const shownNtxId = noteContext.ntxId;
+ if (selectsTitleRef.current) {
+ parentComponent?.handleEvent("focusAndSelectTitle", {
+ isNewNote: true, ntxId: shownNtxId
+ });
+ } else {
+ parentComponent?.handleEvent("focusOnDetail", { ntxId: shownNtxId });
+ }
+ }
+
+ // The modal fires `shown` only as it opens, so a note opened in the popup already on show is
+ // focused once it renders.
+ useEffect(() => {
+ if (!focusesOnRenderRef.current) return;
+ focusesOnRenderRef.current = false;
+ focusOpenedNote();
+ }, [ noteContext ]);
+
// Asked to stand aside by something within it that has sent the reader elsewhere — the note map,
// whose nodes navigate the pane behind rather than the popup, which would otherwise be left covering
// the note it has just gone to with a map of the note it came from.
@@ -212,16 +234,7 @@ export default function PopupEditor({ ntxId = POPUP_EDITOR_NTX_ID, openCommand =
className="popup-editor-dialog"
size="lg"
show={shown}
- onShown={() => {
- const shownNtxId = noteContext.ntxId;
- if (selectsTitleRef.current) {
- parentComponent?.handleEvent("focusAndSelectTitle", {
- isNewNote: true, ntxId: shownNtxId
- });
- } else {
- parentComponent?.handleEvent("focusOnDetail", { ntxId: shownNtxId });
- }
- }}
+ onShown={focusOpenedNote}
onHidden={() => setShown(false)}
keepInDom // needed for faster loading
noFocus // automatic focus breaks block popup
diff --git a/apps/client/src/widgets/type_widgets/text/EditableText.tsx b/apps/client/src/widgets/type_widgets/text/EditableText.tsx
index ea60701498..a8456286a6 100644
--- a/apps/client/src/widgets/type_widgets/text/EditableText.tsx
+++ b/apps/client/src/widgets/type_widgets/text/EditableText.tsx
@@ -32,7 +32,6 @@ import {
import { setEditorNoteId } from "../../react/NoteStore";
import { TypeWidgetProps } from "../type_widget";
import AttachmentSaves, { InlineSourceSaves, useNoteEditor } from "./attachment_saves";
-import { insertChildNote } from "./child_note";
import CKEditor, { CKEditorApi, NotificationEventData, NotificationEventInfo } from "./CKEditor";
import type { ContentEmbedHandlers } from "./config";
import { enterContentEmbed, getContentEmbedTools } from "./content_embed_tools";
@@ -261,18 +260,6 @@ export default function EditableText({
const editor = await waitForEditor();
editor?.execute("insertDateTimeToText");
},
- async addChildNoteToTextCommand() {
- const editor = await waitForEditor();
- const parentNote = noteContext?.note;
- const parentNotePath = noteContext?.notePath;
- if (!editor || !parentNote || !parentNotePath) return;
-
- await insertChildNote(editor, {
- notePath: parentNotePath,
- isProtected: parentNote.isProtected,
- ntxId
- });
- },
// Include note functionality note
addIncludeNoteToTextCommand() {
if (!editorApiRef.current) return;
diff --git a/apps/client/src/widgets/type_widgets/text/child_note.spec.ts b/apps/client/src/widgets/type_widgets/text/child_note.spec.ts
index 7244816e29..ea343acd1d 100644
--- a/apps/client/src/widgets/type_widgets/text/child_note.spec.ts
+++ b/apps/client/src/widgets/type_widgets/text/child_note.spec.ts
@@ -1,20 +1,17 @@
-import type { CKTextEditor } from "@triliumnext/ckeditor5";
import { afterEach, beforeEach, describe, expect, it, type MockInstance, vi } from "vitest";
import appContext from "../../../components/app_context";
import noteCreate from "../../../services/note_create";
-import { createChildNote, insertChildNote, openChildNote } from "./child_note";
+import {
+ buildChildNoteHost, type ChildNoteParent, createChildNote, openChildNote
+} from "./child_note";
describe("child notes", () => {
- const editor = { execute: vi.fn() };
const parent = (ntxId: string) => ({ notePath: "root/parent", isProtected: true, ntxId });
- const insert = (ntxId: string) =>
- insertChildNote(editor as unknown as CKTextEditor, parent(ntxId));
let createNote: MockInstance<typeof noteCreate.createNote>;
let triggerCommand: MockInstance<typeof appContext.triggerCommand>;
beforeEach(() => {
- editor.execute.mockClear();
createNote = vi.spyOn(noteCreate, "createNote")
.mockResolvedValue({ note: { noteId: "child" }, branch: null } as never);
triggerCommand = vi.spyOn(appContext, "triggerCommand").mockReturnValue(undefined);
@@ -24,31 +21,35 @@ describe("child notes", () => {
vi.restoreAllMocks();
});
- it("links to a new child note and opens it to be named, nested in a popup", async () => {
- await insert("ntx-1");
+ it("creates an untitled child of the open note, and opens it to be named", async () => {
+ let openParent: ChildNoteParent | undefined = parent("ntx-1");
+ const host = buildChildNoteHost(() => openParent);
+ expect(await host.create()).toBe("root/parent/child");
expect(createNote).toHaveBeenCalledExactlyOnceWith("root/parent", {
title: undefined, activate: false, isProtected: true
});
- expect(editor.execute)
- .toHaveBeenCalledExactlyOnceWith("referenceLink", { href: "#root/parent/child" });
+
+ host.open("root/parent/child");
expect(triggerCommand).toHaveBeenCalledExactlyOnceWith("openInPopup", {
noteIdOrPath: "root/parent/child", showNoteTypeSwitcher: true, selectTitle: true
});
- await insert("_popup-editor");
+ openParent = parent("_popup-editor");
+ host.open("root/parent/child");
expect(triggerCommand).toHaveBeenLastCalledWith(
"openInNestedPopup", expect.objectContaining({ noteIdOrPath: "root/parent/child" })
);
+
+ openParent = undefined;
+ expect(await host.create()).toBeUndefined();
+ expect(createNote).toHaveBeenCalledOnce();
});
- it("links and opens nothing when the note is not created", async () => {
+ it("resolves to no path when the note is not created", async () => {
createNote.mockResolvedValue({ note: null, branch: undefined } as never);
- await insert("ntx-1");
-
- expect(editor.execute).not.toHaveBeenCalled();
- expect(triggerCommand).not.toHaveBeenCalled();
+ expect(await buildChildNoteHost(() => parent("ntx-1")).create()).toBeUndefined();
});
it("creates a named child note, and opens it on its content", async () => {
@@ -57,7 +58,7 @@ describe("child notes", () => {
title: "Named", activate: false, isProtected: true
});
- openChildNote("root/parent/child", parent("ntx-1"), { selectTitle: false });
+ openChildNote("root/parent/child", "ntx-1", { selectTitle: false });
expect(triggerCommand).toHaveBeenCalledExactlyOnceWith("openInPopup", {
noteIdOrPath: "root/parent/child", showNoteTypeSwitcher: true, selectTitle: false
});
diff --git a/apps/client/src/widgets/type_widgets/text/child_note.ts b/apps/client/src/widgets/type_widgets/text/child_note.ts
index f8f5328209..baadfd0e8a 100644
--- a/apps/client/src/widgets/type_widgets/text/child_note.ts
+++ b/apps/client/src/widgets/type_widgets/text/child_note.ts
@@ -1,4 +1,4 @@
-import type { CKTextEditor } from "@triliumnext/ckeditor5";
+import type { ChildNoteHost } from "@triliumnext/ckeditor5";
import appContext from "../../../components/app_context";
import note_create from "../../../services/note_create";
@@ -13,15 +13,19 @@ export interface ChildNoteParent {
}
/**
- * Creates an empty child note of `parent`, links to it at the selection of `editor`, and opens it
- * in Quick edit with its title selected.
+ * The host of the editor's `childNote` command: creates an empty child note of the note
+ * `getParent()` names, and opens it in Quick edit with its title selected.
*/
-export async function insertChildNote(editor: CKTextEditor, parent: ChildNoteParent) {
- const notePath = await createChildNote(parent);
- if (!notePath) return;
-
- editor.execute("referenceLink", { href: `#${notePath}` });
- openChildNote(notePath, parent, { selectTitle: true });
+export function buildChildNoteHost(getParent: () => ChildNoteParent | undefined): ChildNoteHost {
+ return {
+ async create() {
+ const parent = getParent();
+ return parent && await createChildNote(parent);
+ },
+ open(notePath) {
+ openChildNote(notePath, getParent()?.ntxId, { selectTitle: true });
+ }
+ };
}
/** Creates a child note of `parent` titled `title`, or untitled, and returns the path to it. */
@@ -34,10 +38,11 @@ export async function createChildNote({ notePath, isProtected }: ChildNoteParent
/**
* Opens a note made by `createChildNote()` in Quick edit, which offers the note types to turn the
- * empty note into. An editor already in Quick edit opens it in the nested popup.
+ * empty note into. An editor already in Quick edit, in the context `ntxId`, opens it in the nested
+ * popup.
*/
export function openChildNote(
- notePath: string, { ntxId }: ChildNoteParent, { selectTitle }: { selectTitle: boolean }
+ notePath: string, ntxId: string | null | undefined, { selectTitle }: { selectTitle: boolean }
) {
const command = ntxId?.startsWith(POPUP_EDITOR_NTX_ID) ? "openInNestedPopup" : "openInPopup";
void appContext.triggerCommand(command, {
diff --git a/apps/client/src/widgets/type_widgets/text/config.spec.ts b/apps/client/src/widgets/type_widgets/text/config.spec.ts
index d023b1b67c..8881564b12 100644
--- a/apps/client/src/widgets/type_widgets/text/config.spec.ts
+++ b/apps/client/src/widgets/type_widgets/text/config.spec.ts
@@ -407,12 +407,11 @@ describe("CK config - tables", () => {
expect(config.attachmentUpload?.getEmbedBoxSize?.("image/png", 1)).toBe("medium");
});
- it("hands dialogs, child notes and cut to note to the app commands that do them", async () => {
+ it("hands the dialogs and cut to note of the editor to the app commands that do them", async () => {
const triggerHostCommand = vi.fn(async () => undefined);
const config = await buildConfig(baseOpts({ triggerHostCommand }));
const callbacks = [
[ config.internalLink?.openDialog, "addLinkToText" ],
- [ config.childNote?.create, "addChildNoteToText" ],
[ config.markdownImport?.open, "pasteMarkdownIntoText" ],
[ config.contentEmbed?.pickNote, "addIncludeNoteToText" ],
[ config.cutToNote?.cut, "cutIntoNote" ],
diff --git a/apps/client/src/widgets/type_widgets/text/config.ts b/apps/client/src/widgets/type_widgets/text/config.ts
index d4ce0c0ac4..dc9bfb439e 100644
--- a/apps/client/src/widgets/type_widgets/text/config.ts
+++ b/apps/client/src/widgets/type_widgets/text/config.ts
@@ -27,7 +27,7 @@ import { convertImageToDrawing } from "../canvas/image_to_drawing.js";
import SAMPLE_DIAGRAMS from "../mermaid/sample_diagrams.js";
import buildAiAssistantStream, { type AiNoteLocationProvider, buildAiAssistantQuickActions } from "./ai_assistant_stream.js";
import diffAiResponse from "./ai_diff.js";
-import type { ChildNoteParent } from "./child_note.js";
+import { buildChildNoteHost, type ChildNoteParent } from "./child_note.js";
import { createColorMenuHost } from "./color_menu.js";
import { buildFontColorConfig, buildTableColorConfig } from "./color_palette.js";
import { createEmojiList, createNoteMentionList, createSlashCommandList } from "./mention_list_view.js";
@@ -55,8 +55,8 @@ export interface BuildEditorOptions {
*/
getNoteLocation?: AiNoteLocationProvider;
/**
- * The note the editor is open on, for the `@` list to create a child note under. A getter for
- * the same reason as `getNoteLocation`.
+ * The note the editor is open on, for the "New child note" button and the `@` list to create a
+ * child note under. A getter for the same reason as `getNoteLocation`.
*/
getChildNoteParent?: () => ChildNoteParent | undefined;
/** The ID of the note the editor is open on. A getter for the same reason as `getNoteLocation`. */
@@ -258,7 +258,7 @@ export async function buildConfig(opts: BuildEditorOptions): Promise<EditorConfi
getNoteId: opts.getNoteId,
attachmentUpload: buildAttachmentUploadHost(opts.getComponentId),
internalLink: { openDialog: bindHostCommand(opts, "addLinkToText") },
- childNote: { create: bindHostCommand(opts, "addChildNoteToText") },
+ childNote: buildChildNoteHost(() => opts.getChildNoteParent?.()),
markdownImport: { open: bindHostCommand(opts, "pasteMarkdownIntoText") },
inlineIcon: { showPicker: (request) => opts.showIconPicker?.(request) ?? null },
...(opts.referenceSource && buildReferenceConfig(opts.referenceSource)),
diff --git a/apps/client/src/widgets/type_widgets/text/mention_list_view.spec.tsx b/apps/client/src/widgets/type_widgets/text/mention_list_view.spec.tsx
index 9294a1d2fd..62c2fa7013 100644
--- a/apps/client/src/widgets/type_widgets/text/mention_list_view.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/text/mention_list_view.spec.tsx
@@ -126,7 +126,7 @@ describe("createNoteMentionList", () => {
expect(await commit.mock.calls[0]?.[0])
.toEqual({ id: "@root/edited/al", notePath: "root/edited/al" });
expect(openChildNote)
- .toHaveBeenCalledExactlyOnceWith("root/edited/al", parent, { selectTitle: false });
+ .toHaveBeenCalledExactlyOnceWith("root/edited/al", "ntx", { selectTitle: false });
expect(order).toEqual([ "link", "open" ]);
// Nothing is linked or opened where the note is not created.
diff --git a/apps/client/src/widgets/type_widgets/text/mention_list_view.tsx b/apps/client/src/widgets/type_widgets/text/mention_list_view.tsx
index 1b423ed569..d127b93b26 100644
--- a/apps/client/src/widgets/type_widgets/text/mention_list_view.tsx
+++ b/apps/client/src/widgets/type_widgets/text/mention_list_view.tsx
@@ -48,7 +48,7 @@ export function createNoteMentionList({
state.commit(mention);
// Runs after the commit inserts the link, which focuses the editor.
void mention.then((created) => created && openChildNote(
- created.notePath, childNoteParent, { selectTitle: false }
+ created.notePath, childNoteParent.ntxId, { selectTitle: false }
));
})}
/>
diff --git a/packages/ckeditor5/src/index.ts b/packages/ckeditor5/src/index.ts
index f8ea78891f..5f1bbe2e9b 100644
--- a/packages/ckeditor5/src/index.ts
+++ b/packages/ckeditor5/src/index.ts
@@ -29,6 +29,7 @@ export type {
export type { InlineEmbedSource } from "./plugins/content_embed/inline_source.js";
export type { ContentEmbedHost } from "./plugins/content_embed/content_embed.js";
export type { AttachmentLinkChange } from "./plugins/referencelink.js";
+export type { ChildNoteHost } from "./plugins/child_note.js";
export { getLinkAtSelection, replaceLinkAtSelection } from "./plugins/internallink.js";
export type { default as TriliumEmojiMention, EmojiSuggestion } from "./plugins/mention/emoji_mention.js";
export type { default as TriliumSlashCommands, SlashCommandConfig, SlashCommandDefinition, SlashCommandItem } from "./plugins/mention/slash_commands.js";
diff --git a/packages/ckeditor5/src/plugins/child_note.spec.ts b/packages/ckeditor5/src/plugins/child_note.spec.ts
index 988699559a..c5e6fde380 100644
--- a/packages/ckeditor5/src/plugins/child_note.spec.ts
+++ b/packages/ckeditor5/src/plugins/child_note.spec.ts
@@ -1,24 +1,42 @@
import {
- _setModelData as setModelData, ButtonView, ClassicEditor, CodeBlock, Essentials, LinkEditing,
- Paragraph
+ _getModelData as getModelData, _setModelData as setModelData, ButtonView, ClassicEditor,
+ CodeBlock, Essentials, LinkEditing, Paragraph
} from "ckeditor5";
-import { beforeEach, describe, expect, it, vi } from "vitest";
+import { beforeEach, describe, expect, it, type Mock, vi } from "vitest";
import { createTestEditor } from "../../test/editor-kit.js";
-import ChildNotePlugin, { COMMAND_NAME } from "./child_note.js";
+import ChildNotePlugin, { type ChildNoteHost, COMMAND_NAME } from "./child_note.js";
describe("ChildNotePlugin", () => {
let editor: ClassicEditor;
- let create: ReturnType<typeof vi.fn>;
+ let create: Mock<ChildNoteHost["create"]>;
+ let open: Mock<ChildNoteHost["open"]>;
beforeEach(async () => {
- create = vi.fn();
+ create = vi.fn(async () => undefined);
+ open = vi.fn();
editor = await createTestEditor(
[ Essentials, Paragraph, CodeBlock, LinkEditing, ChildNotePlugin ],
- { childNote: { create } }
+ { childNote: { create, open } }
);
});
+ /** Runs the command with `create()` resolving to `notePath` once `whileCreating` has run. */
+ async function createChildNote(notePath: string | undefined, whileCreating = () => {}) {
+ let resolveNote: (path: string | undefined) => void = () => {};
+ create.mockReturnValue(new Promise((resolve) => { resolveNote = resolve; }));
+
+ const executed = editor.execute(COMMAND_NAME) as Promise<void>;
+ whileCreating();
+ resolveNote(notePath);
+ await executed;
+ // The reference goes in once its title resolves.
+ await Promise.resolve();
+ await Promise.resolve();
+ }
+
+ const content = () => getModelData(editor.model, { withoutSelection: true });
+
it("has the host create the note from a button bound to the command", () => {
const button = editor.ui.componentFactory.create(COMMAND_NAME);
if (!(button instanceof ButtonView)) {
@@ -39,6 +57,33 @@ describe("ChildNotePlugin", () => {
expect(button.isEnabled).toBe(false);
});
+ it("links to the new note where the caret was, then has the host open it", async () => {
+ setModelData(editor.model, "<paragraph>foo[]bar</paragraph>");
+ const paragraph = editor.model.document.getRoot()?.getChild(0);
+
+ await createChildNote("root/parent/child", () => {
+ editor.model.change((writer) => {
+ if (paragraph) writer.setSelection(paragraph, "end");
+ });
+ });
+
+ // Without a host to name it, a reference is titled by its address.
+ expect(content()).toBe("<paragraph>foo<reference href=\"#root/parent/child\" "
+ + "storedTitle=\"#root/parent/child\"></reference>bar</paragraph>");
+ expect(open).toHaveBeenCalledExactlyOnceWith("root/parent/child");
+ });
+
+ it("links and opens nothing without a new note, or after a switch of note", async () => {
+ setModelData(editor.model, "<paragraph>foo[]</paragraph>");
+
+ await createChildNote(undefined);
+ expect(content()).toBe("<paragraph>foo</paragraph>");
+
+ await createChildNote("root/parent/child", () => editor.setData("<p>other</p>"));
+ expect(content()).toBe("<paragraph>other</paragraph>");
+ expect(open).not.toHaveBeenCalled();
+ });
+
it("is enabled only where the link to the new note can go", () => {
const command = editor.commands.get(COMMAND_NAME);
@@ -49,11 +94,18 @@ describe("ChildNotePlugin", () => {
expect(command?.isEnabled).toBe(false);
});
- it("is disabled without a host to create the note", async () => {
+ it("is disabled without a host to create the note, and does nothing if run", async () => {
const hostless =
await createTestEditor([ Essentials, Paragraph, LinkEditing, ChildNotePlugin ]);
setModelData(hostless.model, "<paragraph>foo[]</paragraph>");
+ const command = hostless.commands.get(COMMAND_NAME);
+ expect(command?.isEnabled).toBe(false);
- expect(hostless.commands.get(COMMAND_NAME)?.isEnabled).toBe(false);
+ if (command) {
+ command.isEnabled = true;
+ }
+ await hostless.execute(COMMAND_NAME);
+ expect(getModelData(hostless.model, { withoutSelection: true }))
+ .toBe("<paragraph>foo</paragraph>");
});
});
diff --git a/packages/ckeditor5/src/plugins/child_note.ts b/packages/ckeditor5/src/plugins/child_note.ts
index 26cb886456..f16066ffd4 100644
--- a/packages/ckeditor5/src/plugins/child_note.ts
+++ b/packages/ckeditor5/src/plugins/child_note.ts
@@ -1,13 +1,13 @@
import childNoteIcon from "boxicons/svg/regular/bx-subdirectory-right.svg?raw";
-import { ButtonView, Command, Plugin } from "ckeditor5";
+import { ButtonView, Command, ModelLivePosition, Plugin } from "ckeditor5";
import ReferenceLink from "./referencelink.js";
export const COMMAND_NAME = "childNote";
/**
- * The "New child note" button: has the host create a child note of the note the editor holds, which
- * the host links to at the selection and opens for the user to name.
+ * The "New child note" button: has the host create a child note of the note the editor holds,
+ * links to it at the selection, and has the host open it for the user to name.
*/
export default class ChildNotePlugin extends Plugin {
@@ -55,19 +55,46 @@ class ChildNoteCommand extends Command {
&& model.schema.checkChild(position, "reference");
}
- override execute() {
- this.editor.config.get("childNote")?.create();
+ /**
+ * Has the host create the note, then links to it where the selection was. Skips the link when
+ * the content was replaced meanwhile, as switching the editor to another note does.
+ */
+ override async execute() {
+ const editor = this.editor;
+ const host = editor.config.get("childNote");
+ const selectionPosition = editor.model.document.selection.getFirstPosition();
+ if (!host || !selectionPosition) {
+ return;
+ }
+
+ const position = ModelLivePosition.fromPosition(selectionPosition, "toPrevious");
+ try {
+ const notePath = await host.create();
+ if (notePath && position.root.rootName !== "$graveyard") {
+ editor.execute("referenceLink", {
+ href: `#${notePath}`, position: position.toPosition()
+ });
+ host.open(notePath);
+ }
+ } finally {
+ position.detach();
+ }
}
}
+/** Creates and opens the child notes the `childNote` command links to. */
+export interface ChildNoteHost {
+ /**
+ * Creates an empty child note of the note the editor holds, and resolves to the path of the
+ * new note, or to `undefined` when none is created.
+ */
+ create(): Promise<string | undefined>;
+ /** Opens the new note at `notePath` for the user to name, once the editor links to it. */
+ open(notePath: string): void;
+}
+
declare module "ckeditor5" {
interface EditorConfig {
- childNote?: {
- /**
- * Creates a child note of the note the editor holds, links to it at the selection and
- * opens it with its title selected.
- */
- create(): void;
- };
+ childNote?: ChildNoteHost;
}
}
diff --git a/packages/ckeditor5/src/plugins/referencelink.spec.ts b/packages/ckeditor5/src/plugins/referencelink.spec.ts
index b6d81e31b2..31f1e05493 100644
--- a/packages/ckeditor5/src/plugins/referencelink.spec.ts
+++ b/packages/ckeditor5/src/plugins/referencelink.spec.ts
@@ -140,6 +140,37 @@ describe("ReferenceLink", () => {
expect(findReference(editor)).toBeUndefined();
});
+
+ it("inserts at the position it is given instead of the selection", async () => {
+ setModelData(editor.model, "<paragraph>foo[]bar</paragraph>");
+ const paragraph = editor.model.document.getRoot()?.getChild(0);
+ if (!paragraph) {
+ throw new Error("The paragraph is missing.");
+ }
+
+ editor.execute("referenceLink", {
+ href: "#root/noteAbc", position: editor.model.createPositionAt(paragraph, 0)
+ });
+ resolveTitle();
+ await Promise.resolve();
+ await Promise.resolve();
+
+ expect(getModelData(editor.model, { withoutSelection: true })).toBe(
+ "<paragraph><reference href=\"#root/noteAbc\"></reference>foobar</paragraph>"
+ );
+ });
+ });
+
+ it("titles a reference by its stored title, or else its address, without a host", async () => {
+ const hostless =
+ await createTestEditor([ Essentials, Paragraph, LinkEditing, ReferenceLink ]);
+ setModelData(hostless.model, "<paragraph>"
+ + "<reference href=\"#root/a\" storedTitle=\"Stored\"></reference>"
+ + "<reference href=\"#root/b\"></reference></paragraph>");
+
+ const anchors = hostless.editing.view.getDomRoot()?.querySelectorAll("a.reference-link");
+ expect([ ...anchors ?? [] ].map((anchor) => anchor.textContent))
+ .toEqual([ "Stored", "#root/b" ]);
});
it("is enabled where text is allowed and disabled where it is not", () => {
diff --git a/packages/ckeditor5/src/plugins/referencelink.ts b/packages/ckeditor5/src/plugins/referencelink.ts
index b7b8e57d31..eaa6d19671 100644
--- a/packages/ckeditor5/src/plugins/referencelink.ts
+++ b/packages/ckeditor5/src/plugins/referencelink.ts
@@ -1,6 +1,7 @@
import {
- ClickObserver, Command, type Editor, LinkEditing, ModelElement, ModelLivePosition, Plugin, toWidget,
- type ViewDocumentClickEvent, ViewElement, viewToModelPositionOutsideModelElement, Widget
+ ClickObserver, Command, type Editor, LinkEditing, ModelElement, ModelLivePosition,
+ type ModelPosition, Plugin, toWidget, type ViewDocumentClickEvent, ViewElement,
+ viewToModelPositionOutsideModelElement, Widget
} from "ckeditor5";
export default class ReferenceLink extends Plugin {
@@ -12,9 +13,14 @@ export default class ReferenceLink extends Plugin {
class ReferenceLinkCommand extends Command {
/**
- * Inserts a reference to `href` at the selection, or in place of the `replace` reference.
+ * Inserts a reference to `href` at `position`, or at the selection, or in place of the `replace`
+ * reference.
*/
- override execute({ href, replace }: { href: string; replace?: ModelElement }) {
+ override execute({ href, replace, position }: {
+ href: string;
+ replace?: ModelElement;
+ position?: ModelPosition;
+ }) {
if (!href?.trim()) {
return;
}
@@ -38,7 +44,7 @@ class ReferenceLinkCommand extends Command {
return;
}
- const selectionPosition = editor.model.document.selection.getFirstPosition();
+ const selectionPosition = position ?? editor.model.document.selection.getFirstPosition();
if (!selectionPosition) {
return;
}
@@ -127,7 +133,7 @@ export class ReferenceLinkEditing extends Plugin {
continue;
}
- const href = String( reference.getAttribute( 'href' ) ?? '' );
+ const href = reference.getAttribute( 'href' ) as string;
const storedTitle = reference.getAttribute( 'storedTitle' ) as string | undefined;
const title = getReferenceTitleSync( editor, href, storedTitle );
if ( this._drawnTitles.get( reference ) !== title ) {