Skip to content

Build your personal knowledge base with Trilium Notes

client/text editor/include notes: refactor

Adorian Doran86b09868c7c6
diff --git a/.claude/skills/ckeditor5-plugin-development/references/ui-and-localization.md b/.claude/skills/ckeditor5-plugin-development/references/ui-and-localization.md
index 2c87e03746..5c5f885cf8 100644
--- a/.claude/skills/ckeditor5-plugin-development/references/ui-and-localization.md
+++ b/.claude/skills/ckeditor5-plugin-development/references/ui-and-localization.md
@@ -101,7 +101,7 @@ Each `items` / `blockToolbar` entry is one of:
"bold" // a component-factory name (string)
"|" // a visual separator
{ label: "Insert", icon, items: [ // a grouped dropdown (nestable)
- "link", "internallink", "includeNote", "|", "collapsible", "math", "mermaid"
+ "link", "internallink", "contentEmbed", "|", "collapsible", "math", "mermaid"
] }
```
diff --git a/apps/client/src/components/app_context.ts b/apps/client/src/components/app_context.ts
index bc2eb3f4e6..dbd2250b39 100644
--- a/apps/client/src/components/app_context.ts
+++ b/apps/client/src/components/app_context.ts
@@ -20,9 +20,9 @@ import { ReactWrappedWidget } from "../widgets/basic_widget.js";
import type RootContainer from "../widgets/containers/root_container.js";
import { AddLinkOpts } from "../widgets/dialogs/add_link.jsx";
import type { ConfirmWithMessageOptions, ConfirmWithTitleOptions } from "../widgets/dialogs/confirm.js";
+import { ContentEmbedOpts } from "../widgets/dialogs/content_embed.jsx";
import type { ResolveOptions } from "../widgets/dialogs/delete_notes.js";
import { IconPickerOpts } from "../widgets/dialogs/icon_picker.jsx";
-import { IncludeNoteOpts } from "../widgets/dialogs/include_note.jsx";
import type { InfoProps } from "../widgets/dialogs/info.jsx";
import type { LightboxOptions } from "../widgets/dialogs/lightbox.jsx";
import type { MarkdownImportOpts } from "../widgets/dialogs/markdown_import.jsx";
@@ -270,7 +270,7 @@ export type CommandMappings = {
showPasswordNotSet: CommandData;
showProtectedSessionPasswordDialog: CommandData;
showUploadAttachmentsDialog: CommandData & { noteId: string };
- showIncludeNoteDialog: CommandData & IncludeNoteOpts;
+ showContentEmbedDialog: CommandData & ContentEmbedOpts;
showAddLinkDialog: CommandData & AddLinkOpts;
showIconPickerDialog: CommandData & IconPickerOpts;
showPasteMarkdownDialog: CommandData & MarkdownImportOpts;
@@ -471,7 +471,7 @@ type EventMappings = {
notesReloaded: {
noteIds: string[];
};
- refreshIncludedNote: {
+ refreshEmbeddedNote: {
noteId: string;
};
apiLogMessages: {
@@ -595,7 +595,7 @@ type EventMappings = {
relationMapResetZoomOut: { ntxId: string | null | undefined };
activeNoteChanged: {ntxId: string | null | undefined};
showAddLinkDialog: AddLinkOpts;
- showIncludeDialog: IncludeNoteOpts;
+ showContentEmbedDialog: ContentEmbedOpts;
openBulkActionsDialog: {
selectedOrActiveNoteIds: string[];
};
diff --git a/apps/client/src/layouts/layout_commons.tsx b/apps/client/src/layouts/layout_commons.tsx
index 7582a8df4f..e3da3f05aa 100644
--- a/apps/client/src/layouts/layout_commons.tsx
+++ b/apps/client/src/layouts/layout_commons.tsx
@@ -18,7 +18,7 @@ export function applyModals(rootContainer: RootContainer) {
.child(<LazyDialog triggerEvents={["showRecentChanges", "showDeletedNotes"]} loader={() => import("../widgets/dialogs/recent_changes.js")} />)
.child(<LazyDialog triggerEvents={["editBranchPrefix"]} loader={() => import("../widgets/dialogs/branch_prefix.js")} />)
.child(<LazyDialog triggerEvents={["sortChildNotes"]} loader={() => import("../widgets/dialogs/sort_child_notes.js")} />)
- .child(<LazyDialog triggerEvents={["showIncludeNoteDialog"]} loader={() => import("../widgets/dialogs/include_note.js")} />)
+ .child(<LazyDialog triggerEvents={["showContentEmbedDialog"]} loader={() => import("../widgets/dialogs/content_embed.js")} />)
.child(<LazyDialog triggerEvents={["showNotePickerDialog"]} loader={() => import("../widgets/dialogs/note_picker.js")} />)
.child(<LazyDialog triggerEvents={["chooseNoteType"]} loader={() => import("../widgets/dialogs/note_type_chooser.js")} />)
.child(<LazyDialog triggerEvents={["jumpToNote", "commandPalette"]} loader={() => import("../widgets/dialogs/jump_to_note.js")} />)
diff --git a/apps/client/src/menus/link_context_menu.spec.ts b/apps/client/src/menus/link_context_menu.spec.ts
index 9301f9e492..3ddddc59eb 100644
--- a/apps/client/src/menus/link_context_menu.spec.ts
+++ b/apps/client/src/menus/link_context_menu.spec.ts
@@ -18,14 +18,14 @@ const mocks = vi.hoisted(() => ({
getAttachmentOfNote: vi.fn(),
getAttachmentActionGroups: vi.fn(),
getTextEditorContaining: vi.fn(),
- getIncludeBoxSize: vi.fn()
+ getEmbedBoxSize: vi.fn()
}));
vi.mock("./text_editor_context_menu", () => ({
getTextEditorContaining: mocks.getTextEditorContaining
}));
-vi.mock("../services/content_renderer", () => ({ getIncludeBoxSize: mocks.getIncludeBoxSize }));
+vi.mock("../services/content_renderer", () => ({ getEmbedBoxSize: mocks.getEmbedBoxSize }));
vi.mock("./context_menu", () => ({ default: { show: mocks.show } }));
@@ -215,12 +215,12 @@ describe("getOriginBelow", () => {
it("opens a menu below the anchor, from the anchor or from another element", () => {
const anchor = document.createElement("button");
anchor.getBoundingClientRect = () => ({ left: 40, bottom: 70 }) as DOMRect;
- const include = document.createElement("figure");
+ const embed = document.createElement("figure");
const below = { pageX: 40 + window.scrollX, pageY: 70 + window.scrollY };
expect(linkContextMenu.getOriginBelow(anchor)).toEqual({ ...below, target: anchor });
- expect(linkContextMenu.getOriginBelow(anchor, include))
- .toEqual({ ...below, target: include });
+ expect(linkContextMenu.getOriginBelow(anchor, embed))
+ .toEqual({ ...below, target: embed });
});
});
@@ -274,7 +274,7 @@ describe("openContextMenu", () => {
const execute = vi.fn();
const attachment = { attachmentId: "att-1" };
mocks.getAttachmentOfNote.mockResolvedValue(attachment);
- mocks.getIncludeBoxSize.mockReturnValue("small");
+ mocks.getEmbedBoxSize.mockReturnValue("small");
mocks.getAttachmentActionGroups.mockReturnValue([
[ { title: "Download", icon: "bx bx-download", run: vi.fn() } ]
]);
@@ -298,7 +298,7 @@ describe("openContextMenu", () => {
{ title: "link_context_menu.convert_link_to_embed" }
]);
items.at(-1).handler();
- expect(mocks.getIncludeBoxSize).toHaveBeenCalledWith(attachment);
+ expect(mocks.getEmbedBoxSize).toHaveBeenCalledWith(attachment);
expect(execute).toHaveBeenCalledWith("embedAttachmentLink", {
domElement: link,
boxSize: "small"
@@ -311,17 +311,17 @@ describe("openContextMenu", () => {
expect(mocks.getTextEditorContaining).toHaveBeenCalledTimes(1);
});
- describe("opened on an include in a note being edited", () => {
+ describe("opened on an embed in a note being edited", () => {
const CHECK = "bx bx-check";
const execute = vi.fn();
const focus = vi.fn();
- const selectIncludeAt = vi.fn();
+ const selectEmbedAt = vi.fn();
let hasPlugin = true;
let state: Record<string, unknown> | null;
let editable: HTMLElement;
beforeEach(() => {
- selectIncludeAt.mockReset().mockReturnValue(true);
+ selectEmbedAt.mockReset().mockReturnValue(true);
hasPlugin = true;
state = {
boxSize: "medium", isTitleShown: false, isTitleToggleable: true,
@@ -336,8 +336,8 @@ describe("openContextMenu", () => {
plugins: {
has: () => hasPlugin,
get: () => ({
- selectIncludeAt,
- getIncludeStateAt: () => state,
+ selectEmbedAt,
+ getEmbedStateAt: () => state,
getBoxSizes: () => [
{ value: "tiny", label: "Tiny" },
{ value: "medium", label: "Medium" }
@@ -359,9 +359,9 @@ describe("openContextMenu", () => {
+ `</figure>`;
});
- function include() {
+ function embed() {
const figure = editable.querySelector<HTMLElement>("figure");
- if (!figure) throw new Error("Expected an include.");
+ if (!figure) throw new Error("Expected an embed.");
return figure;
}
@@ -378,16 +378,16 @@ describe("openContextMenu", () => {
function pick(item: { handler: () => void }) {
execute.mockClear();
focus.mockClear();
- selectIncludeAt.mockClear();
+ selectEmbedAt.mockClear();
item.handler();
- expect(selectIncludeAt).toHaveBeenCalledWith(include());
+ expect(selectEmbedAt).toHaveBeenCalledWith(embed());
expect(focus).toHaveBeenCalledOnce();
return execute.mock.calls;
}
it("puts the commands of an embed after its first group, converting it last", async () => {
// From the title, from the menu button beside it, and from a control acting on the
- // whole include, as its toolbar does.
+ // whole embed, as its toolbar does.
for (const target of [ "a", "button.include-note-menu", "figure" ]) {
const items = await openOn(editable.querySelector(target));
@@ -421,26 +421,26 @@ describe("openContextMenu", () => {
]);
expect(items).toHaveLength(13);
}
- expect(selectIncludeAt).not.toHaveBeenCalled();
+ expect(selectEmbedAt).not.toHaveBeenCalled();
const items = await openOn(editable.querySelector("a"));
expect(pick(items[7].items[0]))
- .toEqual([ [ "includeNoteBoxSize", { value: "tiny" } ] ]);
- expect(pick(items[8])).toEqual([ [ "toggleIncludeNoteTitle", undefined ] ]);
+ .toEqual([ [ "contentEmbedBoxSize", { value: "tiny" } ] ]);
+ expect(pick(items[8])).toEqual([ [ "toggleContentEmbedTitle", undefined ] ]);
expect(pick(items[9]))
- .toEqual([ [ "toggleIncludeNoteCaption", { focusCaptionOnShow: true } ] ]);
+ .toEqual([ [ "toggleContentEmbedCaption", { focusCaptionOnShow: true } ] ]);
expect(pick(items[12])).toEqual([ [ "convertEmbedToLink", undefined ] ]);
- // An include the editor cannot select is left as it is.
- selectIncludeAt.mockReturnValue(false);
+ // An embed the editor cannot select is left as it is.
+ selectEmbedAt.mockReturnValue(false);
execute.mockClear();
items[12].handler();
expect(execute).not.toHaveBeenCalled();
});
- it("appends the commands of an included note, its conversion in a group of its own", async () => {
- include().removeAttribute("data-attachment-id");
- include().setAttribute("data-note-id", "n1");
+ it("appends the commands of an embedded note, its conversion in a group of its own", async () => {
+ embed().removeAttribute("data-attachment-id");
+ embed().setAttribute("data-note-id", "n1");
const items = await openOn(editable.querySelector("a"), {});
@@ -456,8 +456,8 @@ describe("openContextMenu", () => {
expect(mocks.getAttachmentOfNote).not.toHaveBeenCalled();
});
- it("disables what the include cannot do, and offers nothing for no include", async () => {
- include().removeAttribute("data-attachment-id");
+ it("disables what the embed cannot do, and offers nothing for no embed", async () => {
+ embed().removeAttribute("data-attachment-id");
state = {
boxSize: "tiny", isTitleShown: true, isTitleToggleable: false,
hasCaption: false, isCaptionToggleable: false, isConvertibleToLink: false
@@ -469,8 +469,8 @@ describe("openContextMenu", () => {
{ title: "link_context_menu.show_caption", enabled: false, trailingIcon: undefined }
]);
- // A link in the included content, an include the editor does not know, and an editor
- // without includes.
+ // A link in the embedded content, an embed the editor does not know, and an editor
+ // without embeds.
expect(await openOn(editable.querySelector(".include-note-content a"), {}))
.toHaveLength(4);
state = null;
@@ -483,7 +483,7 @@ describe("openContextMenu", () => {
editable.removeAttribute("contenteditable");
expect(await openOn(editable.querySelector("a"), {})).toHaveLength(4);
expect(mocks.getTextEditorContaining).toHaveBeenCalledTimes(4);
- expect(selectIncludeAt).not.toHaveBeenCalled();
+ expect(selectEmbedAt).not.toHaveBeenCalled();
});
});
diff --git a/apps/client/src/menus/link_context_menu.ts b/apps/client/src/menus/link_context_menu.ts
index 336fe15afe..3be00de9ef 100644
--- a/apps/client/src/menus/link_context_menu.ts
+++ b/apps/client/src/menus/link_context_menu.ts
@@ -1,4 +1,4 @@
-import type { CKTextEditor, IncludeNoteState } from "@triliumnext/ckeditor5";
+import type { CKTextEditor, ContentEmbedState } from "@triliumnext/ckeditor5";
import type { GeoMouseEvent } from "../widgets/collections/geomap/map.js";
@@ -19,11 +19,11 @@ import { getTextEditorContaining } from "./text_editor_context_menu.js";
*/
export type LinkMenuOrigin = Pick<MouseEvent, "pageX" | "pageY" | "target">;
-/** The include a menu is opened on, in a text note open for editing. */
-interface MenuInclude {
+/** The embed a menu is opened on, in a text note open for editing. */
+interface MenuEmbed {
editor: CKTextEditor;
element: Element;
- state: IncludeNoteState;
+ state: ContentEmbedState;
}
const CHECK_ICON = "bx bx-check";
@@ -39,10 +39,10 @@ async function openContextMenu(
const request = ++lastMenuRequest;
const noteId = notePath.split("/").at(-1) ?? notePath;
const editor = await getEditingTextEditor(getTarget(e));
- const include = editor && getMenuInclude(e, editor);
+ const embed = editor && getMenuEmbed(e, editor);
const ownItems = viewScope.viewMode === "attachments" && viewScope.attachmentId
- ? await getAttachmentItems(noteId, viewScope.attachmentId, e, editor, include)
- : getIncludedNoteItems(include);
+ ? await getAttachmentItems(noteId, viewScope.attachmentId, e, editor, embed)
+ : getEmbeddedNoteItems(embed);
// A later right-click opened its own menu while this one waited for the editor or the
// attachment.
if (request !== lastMenuRequest) {
@@ -158,7 +158,7 @@ async function getAttachmentItems(
attachmentId: string,
e: LinkMenuOrigin,
editor: CKTextEditor | null,
- include: MenuInclude | null
+ embed: MenuEmbed | null
): Promise<MenuItem<CommandNames>[]> {
// Imported on demand: `attachment_actions` imports `link`, which imports this module.
const [ attachment, { getAttachmentActionGroups } ] = await Promise.all([
@@ -176,59 +176,59 @@ async function getAttachmentItems(
enabled: !action.disabledReason,
handler: () => void action.run()
})));
- const groups = [ firstGroup, include ? getIncludeItems(include) : [], ...otherGroups ];
+ const groups = [ firstGroup, embed ? getEmbedItems(embed) : [], ...otherGroups ];
const actionItems = groups
.filter((group) => group.length > 0)
.flatMap((group): MenuItem<CommandNames>[] => [ { kind: "separator" }, ...group ]);
const embedItem = await getConvertToEmbedItem(e, editor, attachment);
- const conversionItems = [ embedItem, include && getConvertToLinkItem(include) ]
+ const conversionItems = [ embedItem, embed && getConvertToLinkItem(embed) ]
.filter((item) => !!item);
return [ ...actionItems, ...conversionItems ];
}
/**
- * The commands of an included note that the menu is opened on, in a group of their own, and
+ * The commands of an embedded note that the menu is opened on, in a group of their own, and
* converting it in another.
*/
-function getIncludedNoteItems(include: MenuInclude | null): MenuItem<CommandNames>[] {
- if (!include) {
+function getEmbeddedNoteItems(embed: MenuEmbed | null): MenuItem<CommandNames>[] {
+ if (!embed) {
return [];
}
- const linkItem = getConvertToLinkItem(include);
+ const linkItem = getConvertToLinkItem(embed);
return [
{ kind: "separator" },
- ...getIncludeItems(include),
+ ...getEmbedItems(embed),
...(linkItem ? [ { kind: "separator" } as const, linkItem ] : [])
];
}
/**
- * The include that a menu is opened on: from its title row, or from a control acting on the whole
- * include, such as its toolbar. A link inside the included content opens the menu of that link.
+ * The embed that a menu is opened on: from its title row, or from a control acting on the whole
+ * embed, such as its toolbar. A link inside the embedded content opens the menu of that link.
*/
-function getMenuInclude(e: LinkMenuOrigin, editor: CKTextEditor): MenuInclude | null {
+function getMenuEmbed(e: LinkMenuOrigin, editor: CKTextEditor): MenuEmbed | null {
const target = getTarget(e);
const element = target?.matches(".include-note")
? target
: target?.closest(".include-note-title-row")?.closest(".include-note");
- if (!element || !editor.plugins.has("IncludeNote")) {
+ if (!element || !editor.plugins.has("ContentEmbed")) {
return null;
}
- const state = editor.plugins.get("IncludeNote").getIncludeStateAt(element);
+ const state = editor.plugins.get("ContentEmbed").getEmbedStateAt(element);
return state ? { editor, element, state } : null;
}
-/** The commands that the toolbar of an include offers, with what each shows checked. */
-function getIncludeItems(include: MenuInclude): MenuItem<CommandNames>[] {
- const { editor, state } = include;
- const sizeItems = editor.plugins.get("IncludeNote").getBoxSizes()
+/** The commands that the toolbar of an embed offers, with what each shows checked. */
+function getEmbedItems(embed: MenuEmbed): MenuItem<CommandNames>[] {
+ const { editor, state } = embed;
+ const sizeItems = editor.plugins.get("ContentEmbed").getBoxSizes()
.map(({ value, label }): MenuItem<CommandNames> => ({
title: escapeHtml(label),
trailingIcon: value === state.boxSize ? CHECK_ICON : undefined,
- handler: () => runIncludeCommand(include, "includeNoteBoxSize", { value })
+ handler: () => runEmbedCommand(embed, "contentEmbedBoxSize", { value })
}));
return [
@@ -241,27 +241,27 @@ function getIncludeItems(include: MenuInclude): MenuItem<CommandNames>[] {
uiIcon: "bx bx-window-alt",
enabled: state.isTitleToggleable,
trailingIcon: state.isTitleShown ? CHECK_ICON : undefined,
- handler: () => runIncludeCommand(include, "toggleIncludeNoteTitle")
+ handler: () => runEmbedCommand(embed, "toggleContentEmbedTitle")
},
{
title: t("link_context_menu.show_caption"),
uiIcon: "bx bx-captions",
enabled: state.isCaptionToggleable,
trailingIcon: state.hasCaption ? CHECK_ICON : undefined,
- handler: () => runIncludeCommand(include, "toggleIncludeNoteCaption", {
+ handler: () => runEmbedCommand(embed, "toggleContentEmbedCaption", {
focusCaptionOnShow: true
})
}
];
}
-/** Runs `command` on the include, which the commands act on once it is selected. */
-function runIncludeCommand(
- { editor, element }: MenuInclude,
+/** Runs `command` on the embed, which the commands act on once it is selected. */
+function runEmbedCommand(
+ { editor, element }: MenuEmbed,
command: string,
options?: Record<string, unknown>
) {
- if (editor.plugins.get("IncludeNote").selectIncludeAt(element)) {
+ if (editor.plugins.get("ContentEmbed").selectEmbedAt(element)) {
editor.execute(command, options);
editor.editing.view.focus();
}
@@ -279,27 +279,27 @@ async function getConvertToEmbedItem(
}
// Imported on demand: `content_renderer` imports `link`, which imports this module.
- const { getIncludeBoxSize } = await import("../services/content_renderer.js");
+ const { getEmbedBoxSize } = await import("../services/content_renderer.js");
return {
title: t("link_context_menu.convert_link_to_embed"),
uiIcon: "bx bx-window-alt",
handler: () => editor.execute("embedAttachmentLink", {
domElement: link,
- boxSize: getIncludeBoxSize(attachment)
+ boxSize: getEmbedBoxSize(attachment)
})
};
}
-/** "Convert to link", for an include that names a note or an attachment. */
-function getConvertToLinkItem(include: MenuInclude): MenuItem<CommandNames> | null {
- if (!include.state.isConvertibleToLink) {
+/** "Convert to link", for an embed that names a note or an attachment. */
+function getConvertToLinkItem(embed: MenuEmbed): MenuItem<CommandNames> | null {
+ if (!embed.state.isConvertibleToLink) {
return null;
}
return {
title: t("link_context_menu.convert_embed_to_link"),
uiIcon: "bx bx-link",
- handler: () => runIncludeCommand(include, "convertEmbedToLink")
+ handler: () => runEmbedCommand(embed, "convertEmbedToLink")
};
}
diff --git a/apps/client/src/print.spec.tsx b/apps/client/src/print.spec.tsx
index b3df7aa707..e14e7252c7 100644
--- a/apps/client/src/print.spec.tsx
+++ b/apps/client/src/print.spec.tsx
@@ -177,8 +177,8 @@ describe("SingleNoteRenderer", () => {
expect(onReady).toHaveBeenCalledWith({ type: "single-note" });
});
expect(lazyImg.getAttribute("loading")).toBe("eager");
- // Printing preserves full include-note nesting via expandNestedIncludes.
- expect(h.getRenderedContent).toHaveBeenCalledWith(note, { noChildrenList: true, expandNestedIncludes: true, mediaEnvironment: "native" });
+ // Printing preserves full embed nesting via expandNestedEmbeds.
+ expect(h.getRenderedContent).toHaveBeenCalledWith(note, { noChildrenList: true, expandNestedEmbeds: true, mediaEnvironment: "native" });
});
it("renders a non-text, non-spreadsheet note via the content renderer", async () => {
@@ -187,8 +187,8 @@ describe("SingleNoteRenderer", () => {
renderInto(<SingleNoteRenderer note={note} onReady={onReady} onProgressChanged={() => {}} />);
await vi.waitFor(() => expect(onReady).toHaveBeenCalledWith({ type: "single-note" }));
- // Printing preserves full include-note nesting via expandNestedIncludes.
- expect(h.getRenderedContent).toHaveBeenCalledWith(note, { noChildrenList: true, expandNestedIncludes: true, mediaEnvironment: "native" });
+ // Printing preserves full embed nesting via expandNestedEmbeds.
+ expect(h.getRenderedContent).toHaveBeenCalledWith(note, { noChildrenList: true, expandNestedEmbeds: true, mediaEnvironment: "native" });
});
});
diff --git a/apps/client/src/print.tsx b/apps/client/src/print.tsx
index 2aa73d393e..66c1d0fa4e 100644
--- a/apps/client/src/print.tsx
+++ b/apps/client/src/print.tsx
@@ -116,12 +116,12 @@ export function SingleNoteRenderer({ note, onReady }: RendererProps) {
if (note.type === "text") {
await import("@triliumnext/ckeditor5/src/theme/ck-content.css");
}
- // Printing preserves full include-note nesting (see expandNestedIncludes).
- const { $renderedContent } = await content_renderer.getRenderedContent(note, { noChildrenList: true, expandNestedIncludes: true, mediaEnvironment: "native" });
+ // Printing preserves full embed nesting (see expandNestedEmbeds).
+ const { $renderedContent } = await content_renderer.getRenderedContent(note, { noChildrenList: true, expandNestedEmbeds: true, mediaEnvironment: "native" });
container.replaceChildren(...$renderedContent);
// Note types rendered as a mounted component (an AI chat) start their transform
- // passes — mermaid, syntax highlighting, included notes — in a layout effect that
+ // passes — mermaid, syntax highlighting, embedded notes — in a layout effect that
// getRenderedContent does not await. Printing snapshots the page, so wait for those
// to settle first; otherwise they land after the capture and are missing from the PDF.
await waitForPendingRenders(container);
diff --git a/apps/client/src/services/content_renderer.spec.ts b/apps/client/src/services/content_renderer.spec.ts
index 9648a41bf5..0e462b30a6 100644
--- a/apps/client/src/services/content_renderer.spec.ts
+++ b/apps/client/src/services/content_renderer.spec.ts
@@ -113,7 +113,7 @@ import FAttachment from "../entities/fattachment.js";
import { buildNote } from "../test/easy-froca.js";
import {
disposeInteractiveContent,
- getIncludeBoxSize,
+ getEmbedBoxSize,
getRenderedContent as rawGetRenderedContent,
getUploadBoxSize
} from "./content_renderer.js";
@@ -156,8 +156,8 @@ beforeEach(() => {
(window as any).electronApi = undefined;
});
-describe("getIncludeBoxSize", () => {
- it("sizes an include by what it previews: none, audio, code or anything else", () => {
+describe("getEmbedBoxSize", () => {
+ it("sizes an embed by what it previews: none, audio, code or anything else", () => {
const protectedCode = buildNote({ title: "Secret", type: "code", mime: "text/javascript" });
protectedCode.isProtected = true;
@@ -168,18 +168,18 @@ describe("getIncludeBoxSize", () => {
buildNote({ title: "Archive", type: "file", mime: "application/zip" }),
buildAttachment({ role: "file", mime: "application/zip" }),
buildAttachment({ role: "canvasLibraryItem", mime: "application/json" })
- ].map(getIncludeBoxSize)).toEqual(Array(6).fill("tiny"));
+ ].map(getEmbedBoxSize)).toEqual(Array(6).fill("tiny"));
expect([
buildNote({ title: "Song", type: "file", mime: "audio/mpeg" }),
buildAttachment({ role: "file", mime: "audio/ogg" })
- ].map(getIncludeBoxSize)).toEqual([ "small", "small" ]);
+ ].map(getEmbedBoxSize)).toEqual([ "small", "small" ]);
expect([
buildNote({ title: "Script", type: "code", mime: "text/javascript" }),
protectedCode,
buildAttachment({ role: "file", mime: "application/json" })
- ].map(getIncludeBoxSize)).toEqual([ "full", "full", "full" ]);
+ ].map(getEmbedBoxSize)).toEqual([ "full", "full", "full" ]);
expect(touchProtectedSession).not.toHaveBeenCalled();
expect([
@@ -191,7 +191,7 @@ describe("getIncludeBoxSize", () => {
buildNote({ title: "Clip", type: "file", mime: "video/mp4" }),
buildAttachment({ role: "file", mime: "application/pdf" }),
buildAttachment({ role: "image", mime: "image/png" })
- ].map(getIncludeBoxSize)).toEqual(Array(8).fill("medium"));
+ ].map(getEmbedBoxSize)).toEqual(Array(8).fill("medium"));
});
it("sizes an upload by its media type, as the attachment it becomes", () => {
diff --git a/apps/client/src/services/content_renderer.ts b/apps/client/src/services/content_renderer.ts
index 45c8aa3254..83007ccc30 100644
--- a/apps/client/src/services/content_renderer.ts
+++ b/apps/client/src/services/content_renderer.ts
@@ -38,21 +38,21 @@ export interface RenderOptions {
trim?: boolean;
/** If enabled, it will prevent the default behavior in which an empty note would display a list of children. */
noChildrenList?: boolean;
- /** If enabled, it will prevent rendering of included notes. */
- noIncludedNotes?: boolean;
+ /** If enabled, it will prevent rendering of embedded notes. */
+ noContentEmbeds?: boolean;
/**
- * Keep expanding includes recursively at every depth. Used for printing/export,
+ * Keep expanding embeds recursively at every depth. Used for printing/export,
* which preserves full nesting. When false (the default for on-screen display), only the first
- * level of inclusion is rendered and deeper includes are replaced with a reference
- * link (see {@link includesAsReferenceLinks}).
+ * level of embedding is rendered and deeper embeds are replaced with a reference
+ * link (see {@link embedsAsReferenceLinks}).
*/
- expandNestedIncludes?: boolean;
+ expandNestedEmbeds?: boolean;
/**
- * Internal: render this note's own includes as reference links instead of expanding
- * them. Set when rendering a note that is itself already an included note in display mode, so that
- * inclusion stops after the first level.
+ * Internal: render this note's own embeds as reference links instead of expanding
+ * them. Set when rendering a note that is itself already an embedded note in display mode, so that
+ * embedding stops after the first level.
*/
- includesAsReferenceLinks?: boolean;
+ embedsAsReferenceLinks?: boolean;
/** If enabled, it will include archived notes when rendering children list. */
includeArchivedNotes?: boolean;
/** Set of note IDs that have already been seen during rendering to prevent infinite recursion. */
@@ -194,7 +194,7 @@ export async function getRenderedContent(this: {} | { ctx: string }, entity: FNo
/**
* Renders a markdown note by converting its source to CKEditor-compatible HTML,
- * then running the same post-render pipeline as text notes (included notes,
+ * then running the same post-render pipeline as text notes (embedded notes,
* math, reference links, Mermaid, code highlight) so the preview matches what
* the user sees in the Markdown note type's preview pane.
*/
@@ -625,7 +625,7 @@ export function disposeInteractiveContent($renderedContent: JQuery<HTMLElement>)
/**
* Mounts a collection — a book or a saved search — as the live {@link EmbeddedNoteList}, the same
* results widget used in the note detail (grid/list/table/board/calendar/map/presentation). Used by
- * interactive contexts (e.g. the dashboard and included notes) that opt in via
+ * interactive contexts (e.g. the dashboard and embedded notes) that opt in via
* {@link RenderOptions.interactive}; every other context keeps the static fallback. Loaded lazily so
* the collection views (and their dependencies) are only pulled in when a collection is embedded.
*/
@@ -672,10 +672,10 @@ async function showRenderError($content: JQuery<HTMLElement>, error: unknown, no
}
/**
- * The box size a new include of `entity` starts with: `tiny` when the include shows no preview of
+ * The box size a new embed of `entity` starts with: `tiny` when the embed shows no preview of
* it, `small` for audio, `full` for code and `medium` for the rest.
*/
-export function getIncludeBoxSize(entity: FNote | FAttachment): BoxSize {
+export function getEmbedBoxSize(entity: FNote | FAttachment): BoxSize {
const type = getContentType(entity);
const hasPreview = type === "webView"
? entity instanceof FNote && entity.hasLabel("webViewSrc")
diff --git a/apps/client/src/services/content_renderer_text.spec.ts b/apps/client/src/services/content_renderer_text.spec.ts
index 49b5745ad9..80b07702b2 100644
--- a/apps/client/src/services/content_renderer_text.spec.ts
+++ b/apps/client/src/services/content_renderer_text.spec.ts
@@ -58,9 +58,9 @@ import renderText, {
} from "./content_renderer_text";
describe("Text content renderer", () => {
- it("renders included note", async () => {
+ it("renders embedded note", async () => {
const contentEl = document.createElement("div");
- const includedNote = buildNote({
+ const embeddedNote = buildNote({
title: "Included note",
content: "<p>This is the included note.</p>"
});
@@ -70,7 +70,7 @@ describe("Text content renderer", () => {
<p>
Hi there
</p>
- <section class="include-note" data-note-id="${includedNote.noteId}" data-box-size="medium">
+ <section class="include-note" data-note-id="${embeddedNote.noteId}" data-box-size="medium">
&nbsp;
</section>
`
@@ -80,36 +80,36 @@ describe("Text content renderer", () => {
expect(contentEl.querySelectorAll("section.include-note p").length).toBe(1);
});
- it("renders the caption of an include after its content, unless Tiny or nested", async () => {
+ it("renders the caption of an embed after its content, unless Tiny or nested", async () => {
const contentEl = document.createElement("div");
const figure = (noteId: string, boxSize: string, caption: string) =>
`<figure class="include-note" data-note-id="${noteId}" data-box-size="${boxSize}">`
+ `<figcaption>${caption}</figcaption></figure>`;
const nestedNote = buildNote({ title: "Nested note", content: "<p>Nested.</p>" });
- const includedNote = buildNote({
+ const embeddedNote = buildNote({
title: "Included note",
content: `<p>Included.</p>${figure(nestedNote.noteId, "medium", "Nested caption")}`
});
const note = buildNote({
title: "New note",
- content: figure(includedNote.noteId, "medium", "A <strong>caption</strong>")
- + figure(includedNote.noteId, "tiny", "Tiny caption")
+ content: figure(embeddedNote.noteId, "medium", "A <strong>caption</strong>")
+ + figure(embeddedNote.noteId, "tiny", "Tiny caption")
});
await renderText(note, $(contentEl));
- const [ include, tinyInclude ] = contentEl.querySelectorAll(".ck-content > .include-note");
- expect(include.querySelector("p")?.textContent).toBe("Included.");
- expect(include.lastElementChild?.outerHTML)
+ const [ embed, tinyEmbed ] = contentEl.querySelectorAll(".ck-content > .include-note");
+ expect(embed.querySelector("p")?.textContent).toBe("Included.");
+ expect(embed.lastElementChild?.outerHTML)
.toBe("<figcaption>A <strong>caption</strong></figcaption>");
- expect(include.querySelectorAll("figcaption")).toHaveLength(1);
- expect(tinyInclude.querySelector("p")?.textContent).toBe("Included.");
- expect(tinyInclude.querySelector("figcaption")).toBeNull();
+ expect(embed.querySelectorAll("figcaption")).toHaveLength(1);
+ expect(tinyEmbed.querySelector("p")?.textContent).toBe("Included.");
+ expect(tinyEmbed.querySelector("figcaption")).toBeNull();
});
- it("skips rendering included note", async () => {
+ it("skips rendering embedded note", async () => {
const contentEl = document.createElement("div");
- const includedNote = buildNote({
+ const embeddedNote = buildNote({
title: "Included note",
content: "<p>This is the included note.</p>"
});
@@ -119,12 +119,12 @@ describe("Text content renderer", () => {
<p>
Hi there
</p>
- <section class="include-note" data-note-id="${includedNote.noteId}" data-box-size="medium">
+ <section class="include-note" data-note-id="${embeddedNote.noteId}" data-box-size="medium">
&nbsp;
</section>
`
});
- await renderText(note, $(contentEl), { noIncludedNotes: true });
+ await renderText(note, $(contentEl), { noContentEmbeds: true });
expect(contentEl.querySelectorAll("section.include-note").length).toBe(0);
});
@@ -290,9 +290,9 @@ describe("Text content renderer", () => {
});
});
-describe("Nested include notes (single-level display vs recursive print)", () => {
- function buildIncludeChain() {
- // C (leaf) ← included by B ← included by A. Distinctive bodies so we can
+describe("Nested embeds (single-level display vs recursive print)", () => {
+ function buildEmbedChain() {
+ // C (leaf) ← embedded by B ← embedded by A. Distinctive bodies so we can
// assert which levels were expanded vs. replaced with a reference link.
const noteC = buildNote({ id: "nestC", title: "Note C", content: "<p>C body</p>" });
const noteB = buildNote({
@@ -314,8 +314,8 @@ describe("Nested include notes (single-level display vs recursive print)", () =>
return { noteA, noteB, noteC };
}
- it("on display, renders only the first level and replaces the nested include with a reference link", async () => {
- const { noteA } = buildIncludeChain();
+ it("on display, renders only the first level and replaces the nested embed with a reference link", async () => {
+ const { noteA } = buildEmbedChain();
const contentEl = document.createElement("div");
await renderText(noteA, $(contentEl));
@@ -323,17 +323,17 @@ describe("Nested include notes (single-level display vs recursive print)", () =>
expect(contentEl.textContent).toContain("B body");
// Second level (C) is NOT expanded — its body must be absent.
expect(contentEl.textContent).not.toContain("C body");
- // The nested include section for C is gone, replaced by a reference link to C.
+ // The nested embed section for C is gone, replaced by a reference link to C.
expect(contentEl.querySelector('section.include-note[data-note-id="nestC"]')).toBeNull();
const refLink = contentEl.querySelector("a.reference-link");
expect(refLink).not.toBeNull();
expect(refLink?.getAttribute("href")).toContain("nestC");
});
- it("on print (expandNestedIncludes), keeps expanding nested includes recursively", async () => {
- const { noteA } = buildIncludeChain();
+ it("on print (expandNestedEmbeds), keeps expanding nested embeds recursively", async () => {
+ const { noteA } = buildEmbedChain();
const contentEl = document.createElement("div");
- await renderText(noteA, $(contentEl), { expandNestedIncludes: true });
+ await renderText(noteA, $(contentEl), { expandNestedEmbeds: true });
// Both levels expanded, all bodies present, no reference-link placeholder.
expect(contentEl.textContent).toContain("B body");
@@ -342,7 +342,7 @@ describe("Nested include notes (single-level display vs recursive print)", () =>
});
it("on print, expands a note shared across sibling branches in each branch (not a false cycle)", async () => {
- // Diamond: A includes B and C; both B and C include D. D is not a cycle, so under recursive
+ // Diamond: A embeds B and C; both B and C embed D. D is not a cycle, so under recursive
// expansion it must render in both branches (the ancestor path is tracked per-branch).
buildNote({ id: "dagD", title: "Note D", content: "<p>D body</p>" });
buildNote({ id: "dagB", title: "Note B", content: `<p>B body</p><section class="include-note" data-note-id="dagD" data-box-size="medium">&nbsp;</section>` });
@@ -356,18 +356,18 @@ describe("Nested include notes (single-level display vs recursive print)", () =>
`
});
const contentEl = document.createElement("div");
- await renderText(noteA, $(contentEl), { expandNestedIncludes: true });
+ await renderText(noteA, $(contentEl), { expandNestedEmbeds: true });
expect((contentEl.textContent?.match(/D body/g) ?? []).length).toBe(2);
expect(contentEl.querySelector("a.reference-link")).toBeNull();
});
- it("renders a note's own includes as reference links when includesAsReferenceLinks is set", async () => {
- // This mirrors how an already-included note (e.g. the editor include widget) is rendered:
- // its content shows, but its own includes degrade to reference links.
- const { noteB } = buildIncludeChain();
+ it("renders a note's own embeds as reference links when embedsAsReferenceLinks is set", async () => {
+ // This mirrors how an already-embedded note (e.g. the editor embed widget) is rendered:
+ // its content shows, but its own embeds degrade to reference links.
+ const { noteB } = buildEmbedChain();
const contentEl = document.createElement("div");
- await renderText(noteB, $(contentEl), { includesAsReferenceLinks: true });
+ await renderText(noteB, $(contentEl), { embedsAsReferenceLinks: true });
expect(contentEl.textContent).toContain("B body");
expect(contentEl.textContent).not.toContain("C body");
@@ -386,7 +386,7 @@ describe("Nested include notes (single-level display vs recursive print)", () =>
`
});
const contentEl = document.createElement("div");
- await renderText(note, $(contentEl), { includesAsReferenceLinks: true });
+ await renderText(note, $(contentEl), { embedsAsReferenceLinks: true });
// Neither the missing-id nor the invalid-id section is converted to a reference link;
// both are left in place.
@@ -395,7 +395,7 @@ describe("Nested include notes (single-level display vs recursive print)", () =>
});
});
-describe("renderIncludedNotes via postProcessRichContent", () => {
+describe("renderContentEmbeds via postProcessRichContent", () => {
it("warns and skips an include-note section whose note cannot be found", async () => {
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
// Make the froca reload a no-op so the missing note stays absent from the
@@ -452,7 +452,7 @@ describe("Attachment embeds", () => {
.toContain("api/attachments/embedPic/image/");
const nestedEl = document.createElement("div");
- await renderText(owner, $(nestedEl), { includesAsReferenceLinks: true });
+ await renderText(owner, $(nestedEl), { embedsAsReferenceLinks: true });
expect(nestedEl.querySelector("section.include-note")).toBeNull();
expect(nestedEl.querySelector("a.reference-link")?.getAttribute("href"))
.toBe(`#root/${owner.noteId}?viewMode=attachments&attachmentId=embedPic`);
diff --git a/apps/client/src/services/content_renderer_text.ts b/apps/client/src/services/content_renderer_text.ts
index e2048414ad..7f05bad082 100644
--- a/apps/client/src/services/content_renderer_text.ts
+++ b/apps/client/src/services/content_renderer_text.ts
@@ -35,14 +35,14 @@ export default async function renderText(note: FNote | FAttachment, $renderedCon
export async function postProcessRichContent(note: FNote | FAttachment, $renderedContent: JQuery<HTMLElement>, options: RenderOptions = {}) {
const seenNoteIds = options.seenNoteIds ?? new Set<string>();
seenNoteIds.add("noteId" in note ? note.noteId : note.attachmentId);
- if (options.noIncludedNotes) {
+ if (options.noContentEmbeds) {
$renderedContent.find(".include-note").remove();
- } else if (options.includesAsReferenceLinks) {
- // This note is itself an included note in display mode: stop after the first level by
- // degrading its own includes to reference links instead of expanding them.
- await replaceIncludesWithReferenceLinks($renderedContent[0]);
+ } else if (options.embedsAsReferenceLinks) {
+ // This note is itself an embedded note in display mode: stop after the first level by
+ // degrading its own embeds to reference links instead of expanding them.
+ await replaceEmbedsWithReferenceLinks($renderedContent[0]);
} else {
- await renderIncludedNotes($renderedContent[0], seenNoteIds, options.expandNestedIncludes ?? false);
+ await renderContentEmbeds($renderedContent[0], seenNoteIds, options.expandNestedEmbeds ?? false);
}
if ($renderedContent.find("span.math-tex").length > 0) {
@@ -75,14 +75,14 @@ export async function postProcessRichContent(note: FNote | FAttachment, $rendere
}
}
-async function renderIncludedNotes(contentEl: HTMLElement, seenNoteIds: Set<string>, expandNested: boolean) {
+async function renderContentEmbeds(contentEl: HTMLElement, seenNoteIds: Set<string>, expandNested: boolean) {
// TODO: Consider duplicating with server's share/content_renderer.ts.
- const includeNoteEls = contentEl.querySelectorAll(".include-note");
+ const embedEls = contentEl.querySelectorAll(".include-note");
// Gather the list of items to load.
const noteIds: string[] = [];
- for (const includeNoteEl of includeNoteEls) {
- const noteId = includeNoteEl.getAttribute("data-note-id");
+ for (const embedEl of embedEls) {
+ const noteId = embedEl.getAttribute("data-note-id");
if (noteId) {
noteIds.push(noteId);
}
@@ -92,77 +92,77 @@ async function renderIncludedNotes(contentEl: HTMLElement, seenNoteIds: Set<stri
await froca.getNotes(noteIds);
// Render and integrate the notes.
- for (const includeNoteEl of includeNoteEls) {
- const attachment = await getEmbeddedAttachment(includeNoteEl);
+ for (const embedEl of embedEls) {
+ const attachment = await getEmbeddedAttachment(embedEl);
if (attachment) {
const { $renderedContent } = await content_renderer.getRenderedContent(attachment);
- replaceIncludeContent(includeNoteEl, $renderedContent.toArray());
+ replaceEmbedContent(embedEl, $renderedContent.toArray());
continue;
}
- const noteId = includeNoteEl.getAttribute("data-note-id");
+ const noteId = embedEl.getAttribute("data-note-id");
if (!noteId) continue;
const note = froca.getNoteFromCache(noteId);
if (!note) {
- console.warn(`Unable to include ${noteId} because it could not be found.`);
+ console.warn(`Unable to embed ${noteId} because it could not be found.`);
continue;
}
if (seenNoteIds.has(noteId)) {
- console.warn(`Skipping inclusion of ${noteId} to avoid circular reference.`);
- includeNoteEl.remove();
+ console.warn(`Skipping embedding of ${noteId} to avoid circular reference.`);
+ embedEl.remove();
continue;
}
- // On display only the first level is expanded: the included note is rendered with its own
- // includes degraded to reference links. Printing/export keeps expanding recursively.
+ // On display only the first level is expanded: the embedded note is rendered with its own
+ // embeds degraded to reference links. Printing/export keeps expanding recursively.
// Clone seenNoteIds per descent so it tracks the current ancestor path only — sibling
- // branches must not pollute each other (a note included in two sub-trees is not a cycle).
+ // branches must not pollute each other (a note embedded in two sub-trees is not a cycle).
const renderedContent = (await content_renderer.getRenderedContent(note, expandNested
- ? { seenNoteIds: new Set(seenNoteIds), expandNestedIncludes: true }
- : { seenNoteIds: new Set(seenNoteIds), includesAsReferenceLinks: true }
+ ? { seenNoteIds: new Set(seenNoteIds), expandNestedEmbeds: true }
+ : { seenNoteIds: new Set(seenNoteIds), embedsAsReferenceLinks: true }
)).$renderedContent;
- replaceIncludeContent(includeNoteEl, renderedContent.toArray());
+ replaceEmbedContent(embedEl, renderedContent.toArray());
}
}
-/** Puts `content` in an include, followed by the include's caption. */
-function replaceIncludeContent(includeNoteEl: Element, content: Node[]) {
- const caption = getIncludeCaption(includeNoteEl);
- includeNoteEl.replaceChildren(...content, ...(caption ? [ caption ] : []));
+/** Puts `content` in an embed, followed by the embed's caption. */
+function replaceEmbedContent(embedEl: Element, content: Node[]) {
+ const caption = getEmbedCaption(embedEl);
+ embedEl.replaceChildren(...content, ...(caption ? [ caption ] : []));
}
-/** The caption of an include, or `null` for a Tiny include, which shows none. */
-export function getIncludeCaption(includeNoteEl: Element) {
- if (includeNoteEl.getAttribute("data-box-size") === "tiny") {
+/** The caption of an embed, or `null` for a Tiny embed, which shows none. */
+export function getEmbedCaption(embedEl: Element) {
+ if (embedEl.getAttribute("data-box-size") === "tiny") {
return null;
}
- return includeNoteEl.querySelector<HTMLElement>(":scope > figcaption");
+ return embedEl.querySelector<HTMLElement>(":scope > figcaption");
}
/**
* Replace each `.include-note` in the given content with a bare reference link to the
- * included note, without expanding it. Used on display to stop inclusion after the first level so a
- * note's transitive include graph is not rendered inline. The link's title, icon and colour are
+ * embedded note, without expanding it. Used on display to stop embedding after the first level so a
+ * note's transitive embed graph is not rendered inline. The link's title, icon and colour are
* filled in by the reference-link post-processing pass in `postProcessRichContent` (the same pass
* that resolves reference links authored in the note), which also batch-prefetches the note.
*/
-async function replaceIncludesWithReferenceLinks(contentEl: HTMLElement) {
- for (const includeNoteEl of contentEl.querySelectorAll(".include-note")) {
- const attachment = await getEmbeddedAttachment(includeNoteEl);
+async function replaceEmbedsWithReferenceLinks(contentEl: HTMLElement) {
+ for (const embedEl of contentEl.querySelectorAll(".include-note")) {
+ const attachment = await getEmbeddedAttachment(embedEl);
if (attachment) {
const { ownerId, attachmentId } = attachment;
const href = `#root/${ownerId}?viewMode=attachments&attachmentId=${attachmentId}`;
const referenceLink = document.createElement("a");
referenceLink.className = "reference-link";
referenceLink.setAttribute("href", href);
- includeNoteEl.replaceWith(referenceLink);
+ embedEl.replaceWith(referenceLink);
continue;
}
- const noteId = includeNoteEl.getAttribute("data-note-id");
+ const noteId = embedEl.getAttribute("data-note-id");
// Validate the ID against a note-ID allow-list before interpolating it into the href: it
// comes from note HTML, and the reference-link pass later reinterprets that href.
if (!noteId || !/^[a-zA-Z0-9_]+$/.test(noteId)) continue;
@@ -170,13 +170,13 @@ async function replaceIncludesWithReferenceLinks(contentEl: HTMLElement) {
const referenceLink = document.createElement("a");
referenceLink.className = "reference-link";
referenceLink.setAttribute("href", `#root/${noteId}`);
- includeNoteEl.replaceWith(referenceLink);
+ embedEl.replaceWith(referenceLink);
}
}
-/** The attachment an include embeds, or `null` for an include of a note. */
-async function getEmbeddedAttachment(includeNoteEl: Element) {
- const attachmentId = includeNoteEl.getAttribute("data-attachment-id");
+/** The attachment an embed shows, or `null` for an embed of a note. */
+async function getEmbeddedAttachment(embedEl: Element) {
+ const attachmentId = embedEl.getAttribute("data-attachment-id");
// The ID comes from note HTML, so it is checked before it reaches a request or an href.
if (!attachmentId || !/^[a-zA-Z0-9_]+$/.test(attachmentId)) {
return null;
diff --git a/apps/client/src/services/frontend_script_api.spec.ts b/apps/client/src/services/frontend_script_api.spec.ts
index 09cc63b98b..020b00f59a 100644
--- a/apps/client/src/services/frontend_script_api.spec.ts
+++ b/apps/client/src/services/frontend_script_api.spec.ts
@@ -486,7 +486,7 @@ describe("commands and events", () => {
expect(triggerCommand).toHaveBeenCalledWith("addTextToActiveEditor", { text: "hello" });
api.refreshIncludedNote("incl1");
- expect(triggerEvent).toHaveBeenCalledWith("refreshIncludedNote", { noteId: "incl1" });
+ expect(triggerEvent).toHaveBeenCalledWith("refreshEmbeddedNote", { noteId: "incl1" });
});
it("getActiveNoteDetailWidget resolves through the executeInActiveNoteDetailWidget command callback", async () => {
diff --git a/apps/client/src/services/frontend_script_api.ts b/apps/client/src/services/frontend_script_api.ts
index 169449abd9..163fa051dc 100644
--- a/apps/client/src/services/frontend_script_api.ts
+++ b/apps/client/src/services/frontend_script_api.ts
@@ -776,7 +776,7 @@ function FrontendScriptApi(this: Api, startNote: FNote, currentNote: FNote, orig
this.waitUntilSynced = ws.waitForMaxKnownEntityChangeId;
- this.refreshIncludedNote = (includedNoteId) => appContext.triggerEvent("refreshIncludedNote", { noteId: includedNoteId });
+ this.refreshIncludedNote = (includedNoteId) => appContext.triggerEvent("refreshEmbeddedNote", { noteId: includedNoteId });
this.randomString = utils.randomString;
this.formatSize = utils.formatSize;
diff --git a/apps/client/src/widgets/collections/legacy/ListOrGridView.tsx b/apps/client/src/widgets/collections/legacy/ListOrGridView.tsx
index 7968008af4..1c3700fe14 100644
--- a/apps/client/src/widgets/collections/legacy/ListOrGridView.tsx
+++ b/apps/client/src/widgets/collections/legacy/ListOrGridView.tsx
@@ -324,8 +324,8 @@ export function NoteContent({ note, trim, noChildrenList, highlightedTokens, inc
content_renderer.getRenderedContent(note, {
trim,
noChildrenList,
- // The note list is a lightweight preview: don't render included notes at all.
- noIncludedNotes: true,
+ // The note list is a lightweight preview: don't render embedded notes at all.
+ noContentEmbeds: true,
includeArchivedNotes,
showTextRepresentation,
interactive
diff --git a/apps/client/src/widgets/collections/legacy/ListPrintView.tsx b/apps/client/src/widgets/collections/legacy/ListPrintView.tsx
index 17b5f87d13..a584696fb3 100644
--- a/apps/client/src/widgets/collections/legacy/ListPrintView.tsx
+++ b/apps/client/src/widgets/collections/legacy/ListPrintView.tsx
@@ -33,8 +33,8 @@ export function ListPrintView({ note, noteIds: unfilteredNoteIds, onReady, onPro
const content = await content_renderer.getRenderedContent(note, {
trim: false,
noChildrenList: true,
- // Printing preserves full include-note nesting (see expandNestedIncludes).
- expandNestedIncludes: true,
+ // Printing preserves full embed nesting (see expandNestedEmbeds).
+ expandNestedEmbeds: true,
mediaEnvironment: "native"
});
diff --git a/apps/client/src/widgets/dialogs/include_note.spec.tsx b/apps/client/src/widgets/dialogs/content_embed.spec.tsx
similarity index 89%
rename from apps/client/src/widgets/dialogs/include_note.spec.tsx
rename to apps/client/src/widgets/dialogs/content_embed.spec.tsx
index 5b3159a987..32055bf5dd 100644
--- a/apps/client/src/widgets/dialogs/include_note.spec.tsx
+++ b/apps/client/src/widgets/dialogs/content_embed.spec.tsx
@@ -7,7 +7,7 @@ import type { Suggestion } from "../../services/note_autocomplete";
import { buildNote } from "../../test/easy-froca";
import { renderInto } from "../../test/render";
import { ParentComponent } from "../react/react_utils";
-import IncludeNoteDialog from "./include_note";
+import ContentEmbedDialog from "./content_embed";
const autocomplete = vi.hoisted(() => ({
onChange: undefined as ((suggestion: Suggestion | null) => void) | undefined
@@ -22,17 +22,17 @@ vi.mock("../react/NoteAutocomplete", () => ({
}
}));
-describe("IncludeNoteDialog", () => {
+describe("ContentEmbedDialog", () => {
let host: Component;
let container: HTMLElement;
- const editorApi = { addIncludeNote: vi.fn(), addImage: vi.fn() };
+ const editorApi = { addContentEmbed: vi.fn(), addImage: vi.fn() };
beforeEach(async () => {
vi.clearAllMocks();
host = new Component();
container = renderInto(
<ParentComponent.Provider value={host}>
- <IncludeNoteDialog />
+ <ContentEmbedDialog />
</ParentComponent.Provider>
);
await open();
@@ -40,7 +40,7 @@ describe("IncludeNoteDialog", () => {
async function open() {
await act(async () => {
- void host.handleEventInChildren("showIncludeNoteDialog", { editorApi });
+ void host.handleEventInChildren("showContentEmbedDialog", { editorApi });
});
}
@@ -92,6 +92,6 @@ describe("IncludeNoteDialog", () => {
await choose("expandable");
await submit();
- expect(editorApi.addIncludeNote).toHaveBeenCalledWith(song.noteId, "expandable");
+ expect(editorApi.addContentEmbed).toHaveBeenCalledWith(song.noteId, "expandable");
});
});
diff --git a/apps/client/src/widgets/dialogs/include_note.tsx b/apps/client/src/widgets/dialogs/content_embed.tsx
similarity index 83%
rename from apps/client/src/widgets/dialogs/include_note.tsx
rename to apps/client/src/widgets/dialogs/content_embed.tsx
index 4952630188..088067d313 100644
--- a/apps/client/src/widgets/dialogs/include_note.tsx
+++ b/apps/client/src/widgets/dialogs/content_embed.tsx
@@ -1,5 +1,5 @@
import { useCallback, useRef, useState } from "preact/hooks";
-import { getIncludeBoxSize } from "../../services/content_renderer";
+import { getEmbedBoxSize } from "../../services/content_renderer";
import { t } from "../../services/i18n";
import FormGroup from "../react/FormGroup";
import FormRadioGroup from "../react/FormRadioGroup";
@@ -12,20 +12,20 @@ import froca from "../../services/froca";
import { useNote, useTriliumEvent } from "../react/hooks";
import type { BoxSize, CKEditorApi } from "../type_widgets/text/CKEditorWithWatchdog";
-export interface IncludeNoteOpts {
- editorApi: Pick<CKEditorApi, "addIncludeNote" | "addImage">;
+export interface ContentEmbedOpts {
+ editorApi: Pick<CKEditorApi, "addContentEmbed" | "addImage">;
}
-export default function IncludeNoteDialog() {
- const editorApiRef = useRef<Pick<CKEditorApi, "addIncludeNote" | "addImage">>(null);
+export default function ContentEmbedDialog() {
+ const editorApiRef = useRef<Pick<CKEditorApi, "addContentEmbed" | "addImage">>(null);
const [suggestion, setSuggestion] = useState<Suggestion | null>(null);
// The size chosen by hand, otherwise the one that suits the picked note.
const [chosenBoxSize, setChosenBoxSize] = useState<BoxSize | null>(null);
const [shown, setShown] = useState(false);
const note = useNote(suggestion?.notePath ? tree.getNoteIdFromUrl(suggestion.notePath) : null);
- const boxSize = chosenBoxSize ?? (note ? getIncludeBoxSize(note) : "medium");
+ const boxSize = chosenBoxSize ?? (note ? getEmbedBoxSize(note) : "medium");
- useTriliumEvent("showIncludeNoteDialog", ({ editorApi }) => {
+ useTriliumEvent("showContentEmbedDialog", ({ editorApi }) => {
editorApiRef.current = editorApi;
setChosenBoxSize(null);
setShown(true);
@@ -48,7 +48,7 @@ export default function IncludeNoteDialog() {
onSubmit={async () => {
if (!suggestion?.notePath || !editorApiRef.current) return;
setShown(false);
- await includeNote(suggestion.notePath, editorApiRef.current, boxSize);
+ await embedNote(suggestion.notePath, editorApiRef.current, boxSize);
}}
footer={<Button text={t("include_note.button_include")} keyboardShortcut="Enter" />}
show={shown}
@@ -82,7 +82,7 @@ export default function IncludeNoteDialog() {
)
}
-async function includeNote(notePath: string, editorApi: Pick<CKEditorApi, "addIncludeNote" | "addImage">, boxSize: BoxSize) {
+async function embedNote(notePath: string, editorApi: Pick<CKEditorApi, "addContentEmbed" | "addImage">, boxSize: BoxSize) {
const noteId = tree.getNoteIdFromUrl(notePath);
if (!noteId) {
return;
@@ -94,6 +94,6 @@ async function includeNote(notePath: string, editorApi: Pick<CKEditorApi, "addIn
// so we'll just add an IMG tag
editorApi.addImage(noteId);
} else {
- editorApi.addIncludeNote(noteId, boxSize);
+ editorApi.addContentEmbed(noteId, boxSize);
}
}
diff --git a/apps/client/src/widgets/type_widgets/markdown/Markdown.tsx b/apps/client/src/widgets/type_widgets/markdown/Markdown.tsx
index 63c69dd48e..f6616bf987 100644
--- a/apps/client/src/widgets/type_widgets/markdown/Markdown.tsx
+++ b/apps/client/src/widgets/type_widgets/markdown/Markdown.tsx
@@ -276,7 +276,7 @@ function useSyncedScrolling(view: VanillaCodeMirror | null, preview: HTMLDivElem
*
* The marker is painted as the preview's background (see `Markdown.css`), so its geometry has to
* be measured here. Every block is observed for resize, since a block that grows after render —
- * a mermaid diagram, an image, an included note — shifts everything below it.
+ * a mermaid diagram, an image, an embedded note — shifts everything below it.
*/
function useSyncedHighlight(view: VanillaCodeMirror | null, preview: HTMLDivElement | null, html: string) {
useEffect(() => {
@@ -374,9 +374,9 @@ function useTextCommands(parentComponent: TypeWidgetProps["parentComponent"], ed
addIncludeNoteToTextCommand() {
if (!editorView) return;
- parentComponent?.triggerCommand("showIncludeNoteDialog", {
+ parentComponent?.triggerCommand("showContentEmbedDialog", {
editorApi: {
- addIncludeNote(noteId: string, boxSize?: string) {
+ addContentEmbed(noteId: string, boxSize?: string) {
insertText(editorView, `<figure class="include-note" data-note-id="${noteId}" data-box-size="${boxSize ?? "full"}"></figure>\n`);
editorView.focus();
},
diff --git a/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsx b/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsx
index 85dbdee1ec..4129e1d345 100644
--- a/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsx
+++ b/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsx
@@ -19,7 +19,7 @@ export interface CKEditorApi {
addLink(notePath: string, linkTitle: string | null, externalLink?: boolean): void;
addLinkToEditor(linkHref: string, linkTitle: string): void;
addHtmlToEditor(html: string): void;
- addIncludeNote(noteId: string, boxSize?: BoxSize): void;
+ addContentEmbed(noteId: string, boxSize?: BoxSize): void;
addImage(noteId: string): Promise<void>;
}
@@ -170,15 +170,15 @@ export default function CKEditorWithWatchdog({ containerRef: externalContainerRe
}
});
},
- addIncludeNote(noteId, boxSize) {
+ addContentEmbed(noteId, boxSize) {
const editor = watchdogRef.current?.editor;
if (!editor) return;
editor?.model.change((writer) => {
- // Insert <includeNote>*</includeNote> at the current selection position
+ // Insert <contentEmbed>*</contentEmbed> at the current selection position
// in a way that will result in creating a valid model structure
editor?.model.insertContent(
- writer.createElement("includeNote", {
+ writer.createElement("contentEmbed", {
noteId,
boxSize
})
diff --git a/apps/client/src/widgets/type_widgets/text/IncludeNote.spec.tsx b/apps/client/src/widgets/type_widgets/text/ContentEmbed.spec.tsx
similarity index 95%
rename from apps/client/src/widgets/type_widgets/text/IncludeNote.spec.tsx
rename to apps/client/src/widgets/type_widgets/text/ContentEmbed.spec.tsx
index bc3fce8cc2..576cef6140 100644
--- a/apps/client/src/widgets/type_widgets/text/IncludeNote.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/text/ContentEmbed.spec.tsx
@@ -26,12 +26,12 @@ vi.mock("../../../menus/link_context_menu", () => ({
}));
vi.mock("../../../services/content_renderer", () => ({ default: { disposeInteractiveContent } }));
-import IncludeNote, {
+import ContentEmbed, {
getNoteActions,
- type IncludeNoteProps,
- TinyIncludeNote,
- type TinyIncludeNoteProps
-} from "./IncludeNote";
+ type ContentEmbedProps,
+ TinyContentEmbed,
+ type TinyContentEmbedProps
+} from "./ContentEmbed";
const ATTACHMENT_SCOPE = { viewMode: "attachments", attachmentId: "att1" } as const;
@@ -61,27 +61,27 @@ function element(html: string) {
return first;
}
-function renderBox(props: Partial<IncludeNoteProps> = {}) {
- const boxProps: IncludeNoteProps = {
+function renderBox(props: Partial<ContentEmbedProps> = {}) {
+ const boxProps: ContentEmbedProps = {
title: element(`<span><a href="#root/noteA">Note A</a></span>`),
content: element(`<div class="rendered-content"><p>body</p></div>`),
contentType: "text",
notePath: "noteA",
...props
};
- act(() => render(<IncludeNote {...boxProps} />, container));
+ act(() => render(<ContentEmbed {...boxProps} />, container));
return boxProps;
}
-function renderTinyBox(props: Partial<TinyIncludeNoteProps> = {}) {
- const boxProps: TinyIncludeNoteProps = {
+function renderTinyBox(props: Partial<TinyContentEmbedProps> = {}) {
+ const boxProps: TinyContentEmbedProps = {
icon: "bx bx-note",
title: element(`<span><a href="#root/noteA">Note A</a></span>`),
notePath: "noteA",
actions: [],
...props
};
- act(() => render(<TinyIncludeNote {...boxProps} />, container));
+ act(() => render(<TinyContentEmbed {...boxProps} />, container));
return boxProps;
}
@@ -116,7 +116,7 @@ function tooltipOf(target: HTMLElement) {
}
/**
- * Right-clicks `target`, and tells whether the box opened the include's menu for it, taking the
+ * Right-clicks `target`, and tells whether the box opened the embed's menu for it, taking the
* click from the browser and what surrounds the box.
*/
function rightClick(target: Element | null) {
@@ -144,7 +144,7 @@ function click(target: HTMLElement) {
return { event, isStopped: stopPropagation.mock.calls.length > 0 };
}
-describe("IncludeNote", () => {
+describe("ContentEmbed", () => {
it("lays out the title row for each box size", () => {
const plain = [ "title", "open", "menu" ];
const withFullscreen = [ "title", "open", "fullscreen", "menu" ];
@@ -297,7 +297,7 @@ describe("IncludeNote", () => {
});
});
-describe("TinyIncludeNote", () => {
+describe("TinyContentEmbed", () => {
it("lays out a single row: icon, title and description, actions, menu", () => {
const run = vi.fn();
const { title } = renderTinyBox({
diff --git a/apps/client/src/widgets/type_widgets/text/IncludeNote.tsx b/apps/client/src/widgets/type_widgets/text/ContentEmbed.tsx
similarity index 85%
rename from apps/client/src/widgets/type_widgets/text/IncludeNote.tsx
rename to apps/client/src/widgets/type_widgets/text/ContentEmbed.tsx
index da5c4f93f7..1a070045a1 100644
--- a/apps/client/src/widgets/type_widgets/text/IncludeNote.tsx
+++ b/apps/client/src/widgets/type_widgets/text/ContentEmbed.tsx
@@ -10,16 +10,16 @@ import ActionButton from "../../react/ActionButton";
import Icon from "../../react/Icon";
import OverlayControlGroup, { OverlayControlButton } from "../../react/OverlayControlGroup";
-/** An action on the included note or attachment, offered as a button in the title row. */
-export interface IncludeNoteAction {
+/** An action on the embedded note or attachment, offered as a button in the title row. */
+export interface ContentEmbedAction {
title: string;
icon: string;
run: () => void | Promise<void>;
}
-export interface IncludeNoteProps {
+export interface ContentEmbedProps {
boxSize?: string;
- /** The link to the included note or attachment, shown as the title. */
+ /** The link to the embedded note or attachment, shown as the title. */
title: HTMLElement;
/** The rendered note or attachment. */
content: HTMLElement;
@@ -29,9 +29,9 @@ export interface IncludeNoteProps {
viewScope?: ViewScope;
}
-export interface TinyIncludeNoteProps {
+export interface TinyContentEmbedProps {
icon: string;
- /** The link to the included note or attachment, shown as the title. */
+ /** The link to the embedded note or attachment, shown as the title. */
title: HTMLElement;
/** A line under the title, such as the size of an attachment. */
description?: string;
@@ -39,13 +39,13 @@ export interface TinyIncludeNoteProps {
notePath: string;
viewScope?: ViewScope;
/** The buttons before the "More actions" menu. */
- actions: IncludeNoteAction[];
+ actions: ContentEmbedAction[];
}
-/** The title row and the content of an included note or embedded attachment. */
-export default function IncludeNote({
+/** The title row and the content of an embedded note or attachment. */
+export default function ContentEmbed({
boxSize, title, content, contentType, notePath, viewScope
-}: IncludeNoteProps) {
+}: ContentEmbedProps) {
const contentRef = useRef<HTMLDivElement>(null);
const [ isExpanded, setIsExpanded ] = useState(false);
const isExpandable = boxSize === "expandable";
@@ -77,8 +77,8 @@ export default function IncludeNote({
}}
/>
)}
- <IncludeNoteTitle title={title} />
- <IncludeNoteActionButton
+ <ContentEmbedTitle title={title} />
+ <ContentEmbedActionButton
className="include-note-open"
action={getOpenInNewTabAction(notePath, viewScope)}
/>
@@ -90,7 +90,7 @@ export default function IncludeNote({
onClick={(e) => {
e.stopPropagation();
contentRef.current?.requestFullscreen().catch((error: unknown) => {
- console.warn("Could not show the include in fullscreen:", error);
+ console.warn("Could not show the embed in fullscreen:", error);
});
}}
/>
@@ -126,10 +126,10 @@ export default function IncludeNote({
);
}
-/** A tiny include: a single row with an icon, the title and the actions, and no content. */
-export function TinyIncludeNote({
+/** A tiny embed: a single row with an icon, the title and the actions, and no content. */
+export function TinyContentEmbed({
icon, title, description, notePath, viewScope, actions
-}: TinyIncludeNoteProps) {
+}: TinyContentEmbedProps) {
return (
<div
className="include-note-title-row"
@@ -137,11 +137,11 @@ export function TinyIncludeNote({
>
<Icon className="include-note-icon" icon={icon} />
<div className="include-note-heading">
- <IncludeNoteTitle title={title} />
+ <ContentEmbedTitle title={title} />
{description && <small className="include-note-description">{description}</small>}
</div>
{actions.map((action) => (
- <IncludeNoteActionButton
+ <ContentEmbedActionButton
key={action.title}
className="include-note-action"
action={action}
@@ -152,8 +152,8 @@ export function TinyIncludeNote({
);
}
-/** The buttons of a tiny include of a note: "Quick edit" and "Open in new tab". */
-export function getNoteActions(notePath: string): IncludeNoteAction[] {
+/** The buttons of a tiny embed of a note: "Quick edit" and "Open in new tab". */
+export function getNoteActions(notePath: string): ContentEmbedAction[] {
return [
{
title: t("link_context_menu.open_note_in_popup"),
@@ -166,7 +166,7 @@ export function getNoteActions(notePath: string): IncludeNoteAction[] {
];
}
-function getOpenInNewTabAction(notePath: string, viewScope?: ViewScope): IncludeNoteAction {
+function getOpenInNewTabAction(notePath: string, viewScope?: ViewScope): ContentEmbedAction {
return {
title: t("common.open_in_new_tab"),
icon: "bx bx-link-external",
@@ -180,7 +180,7 @@ function getOpenInNewTabAction(notePath: string, viewScope?: ViewScope): Include
};
}
-function IncludeNoteTitle({ title }: { title: HTMLElement }) {
+function ContentEmbedTitle({ title }: { title: HTMLElement }) {
const titleRef = useRef<HTMLHeadingElement>(null);
useLayoutEffect(() => {
@@ -190,9 +190,9 @@ function IncludeNoteTitle({ title }: { title: HTMLElement }) {
return <h4 ref={titleRef} className="include-note-title" />;
}
-function IncludeNoteActionButton({ className, action }: {
+function ContentEmbedActionButton({ className, action }: {
className: string;
- action: IncludeNoteAction;
+ action: ContentEmbedAction;
}) {
return (
<ActionButton
@@ -208,7 +208,7 @@ function IncludeNoteActionButton({ className, action }: {
}
/**
- * Opens the menu of the include for a right click on its title row. The title link is left to the
+ * Opens the menu of the embed for a right click on its title row. The title link is left to the
* handler of every link, which opens the same menu, or a quick edit with Ctrl.
*/
function openMenuOnRightClick(e: MouseEvent, notePath: string, viewScope?: ViewScope) {
diff --git a/apps/client/src/widgets/type_widgets/text/EditableText.tsx b/apps/client/src/widgets/type_widgets/text/EditableText.tsx
index 0ff01688bf..5e4e01fb0b 100644
--- a/apps/client/src/widgets/type_widgets/text/EditableText.tsx
+++ b/apps/client/src/widgets/type_widgets/text/EditableText.tsx
@@ -37,12 +37,12 @@ import linkEmbedService from "../../../services/link_embed";
import { usesClassicToolbar } from "./toolbar";
import {
getAttachmentHref,
- loadIncludedAttachment,
- loadIncludedNote,
- openIncludeNoteMenu,
- refreshIncludedNote,
+ loadEmbeddedAttachment,
+ loadEmbeddedNote,
+ openContentEmbedMenu,
+ refreshEmbeddedNote,
setupImageOpening,
- watchIncludedNotes
+ watchContentEmbeds
} from "./utils";
/**
@@ -58,7 +58,7 @@ export default function EditableText({ note, parentComponent, ntxId, noteContext
const contentNoteIdRef = useRef<string>();
const pendingAttachmentChangesRef = useRef<PendingAttachmentChanges>();
const watchdogRef = useRef<EditorWatchdog>(null);
- const stopWatchingIncludesRef = useRef<() => void>();
+ const stopWatchingEmbedsRef = useRef<() => void>();
const editorApiRef = useRef<CKEditorApi>(null);
/** The open icon picker request and its balloon container, or `null` when none is open. */
const [ iconPickerRequest, setIconPickerRequest ] = useState<IconPickerOpts & { container: HTMLElement } | null>(null);
@@ -188,18 +188,18 @@ export default function EditableText({ note, parentComponent, ntxId, noteContext
// Include note functionality note
addIncludeNoteToTextCommand() {
if (!editorApiRef.current) return;
- parentComponent?.triggerCommand("showIncludeNoteDialog", {
+ parentComponent?.triggerCommand("showContentEmbedDialog", {
editorApi: editorApiRef.current,
});
},
- loadIncludedNote,
- loadIncludedAttachment,
+ loadEmbeddedNote,
+ loadEmbeddedAttachment,
getAttachmentHref,
getNoteId() {
return note.noteId;
},
getEmbedBoxSize: getUploadBoxSize,
- openIncludeNoteMenu,
+ openContentEmbedMenu,
// Link preview functionality. The insert flow itself lives in the editor (a balloon form),
// so the host only has to supply the metadata and the rendering.
async fetchLinkMetadata(url: string) {
@@ -287,12 +287,12 @@ export default function EditableText({ note, parentComponent, ntxId, noteContext
}
});
- useTriliumEvent("refreshIncludedNote", ({ noteId }) => {
+ useTriliumEvent("refreshEmbeddedNote", ({ noteId }) => {
if (!containerRef.current) return;
- refreshIncludedNote(containerRef.current, noteId);
+ refreshEmbeddedNote(containerRef.current, noteId);
});
- useEffect(() => () => stopWatchingIncludesRef.current?.(), []);
+ useEffect(() => () => stopWatchingEmbedsRef.current?.(), []);
useTriliumEvent("entitiesReloaded", ({ loadResults }) => {
const editor = watchdogRef.current?.editor as CKTextEditor | null | undefined;
@@ -535,8 +535,8 @@ export default function EditableText({ note, parentComponent, ntxId, noteContext
onEditorInitialized={(editor) => {
if (containerRef.current) {
setupImageOpening(containerRef.current, false);
- stopWatchingIncludesRef.current?.();
- stopWatchingIncludesRef.current = watchIncludedNotes(containerRef.current);
+ stopWatchingEmbedsRef.current?.();
+ stopWatchingEmbedsRef.current = watchContentEmbeds(containerRef.current);
}
editor.plugins.get("FileUploadEditing")
diff --git a/apps/client/src/widgets/type_widgets/text/ReadOnlyText.spec.tsx b/apps/client/src/widgets/type_widgets/text/ReadOnlyText.spec.tsx
index 387a78ffbb..19d81fbd0a 100644
--- a/apps/client/src/widgets/type_widgets/text/ReadOnlyText.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/text/ReadOnlyText.spec.tsx
@@ -33,13 +33,13 @@ import ReadOnlyText from "./ReadOnlyText";
// Imported by ReadOnlyText only for its content styles; irrelevant (and heavy) in happy-dom.
vi.mock("@triliumnext/ckeditor5", () => ({}));
-const { watchIncludedNotes, stopWatchingIncludes } = vi.hoisted(() => {
+const { watchContentEmbeds, stopWatchingEmbeds } = vi.hoisted(() => {
const stop = vi.fn();
- return { watchIncludedNotes: vi.fn(() => stop), stopWatchingIncludes: stop };
+ return { watchContentEmbeds: vi.fn(() => stop), stopWatchingEmbeds: stop };
});
vi.mock("./utils", async (importOriginal) => ({
...await importOriginal<typeof import("./utils")>(),
- watchIncludedNotes
+ watchContentEmbeds
}));
vi.stubGlobal("logError", vi.fn());
@@ -280,21 +280,21 @@ describe("ReadOnlyText text direction", () => {
});
});
-describe("ReadOnlyText included notes", () => {
- it("watches its content for include boxes until it unmounts", async () => {
- watchIncludedNotes.mockClear();
- stopWatchingIncludes.mockClear();
+describe("ReadOnlyText embedded notes", () => {
+ it("watches its content for embed boxes until it unmounts", async () => {
+ watchContentEmbeds.mockClear();
+ stopWatchingEmbeds.mockClear();
const harness = setupHarness({ isVisible: true });
await harness.mount();
const content = harness.container.querySelector(".note-detail-readonly-text-content");
expect(content).not.toBeNull();
- expect(watchIncludedNotes.mock.calls).toEqual([ [ content ] ]);
- expect(stopWatchingIncludes).not.toHaveBeenCalled();
+ expect(watchContentEmbeds.mock.calls).toEqual([ [ content ] ]);
+ expect(stopWatchingEmbeds).not.toHaveBeenCalled();
await act(async () => render(null, harness.container));
harness.container.remove();
- expect(stopWatchingIncludes).toHaveBeenCalledOnce();
+ expect(stopWatchingEmbeds).toHaveBeenCalledOnce();
});
});
diff --git a/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx b/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx
index fbea07e36f..a7e1c216cd 100644
--- a/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx
+++ b/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx
@@ -23,11 +23,11 @@ import { RawHtmlBlock } from "../../react/RawHtml";
import { TypeWidgetProps } from "../type_widget";
import { applyReferenceLinks } from "./read_only_helper";
import {
- loadIncludedAttachment,
- loadIncludedNote,
- refreshIncludedNote,
+ loadEmbeddedAttachment,
+ loadEmbeddedNote,
+ refreshEmbeddedNote,
setupImageOpening,
- watchIncludedNotes
+ watchContentEmbeds
} from "./utils";
export default function ReadOnlyText({ note, noteContext, ntxId, parentComponent, isVisible }: TypeWidgetProps) {
@@ -83,7 +83,7 @@ interface ReadOnlyTextContentProps {
/**
* Renders arbitrary CKEditor-style HTML with the same pipeline as {@link ReadOnlyText}:
- * mermaid rewriting, inline mermaid, included-note expansion, KaTeX math, reference-link
+ * mermaid rewriting, inline mermaid, embed expansion, KaTeX math, reference-link
* titles, code-block syntax highlighting, and image click handling. Transforms re-run
* whenever `html` changes.
*/
@@ -108,14 +108,14 @@ export function ReadOnlyTextContent({ html, ntxId, dir, className, contentRef: e
appContext.triggerEvent("contentElRefreshed", { ntxId, contentEl: container });
}
- // The passes that lazily load their library (mermaid, highlight.js) — plus included notes,
+ // The passes that lazily load their library (mermaid, highlight.js) — plus embedded notes,
// which render a whole note of their own — finish after this effect returns. On screen they
// simply paint when ready; a caller that snapshots the DOM instead (printing) has to wait for
// them, so the work is registered rather than dropped on the floor.
trackPendingRender(container, Promise.all([
rewriteMermaidDiagramsInContainer(container),
applyInlineMermaid(container),
- applyIncludedNotes(container),
+ applyContentEmbeds(container),
applyLinkEmbeds(container),
applyReferenceLinks(container),
formatCodeBlocks($(container))
@@ -127,13 +127,13 @@ export function ReadOnlyTextContent({ html, ntxId, dir, className, contentRef: e
useEffect(() => {
if (!contentRef.current) return;
- return watchIncludedNotes(contentRef.current);
+ return watchContentEmbeds(contentRef.current);
}, [ contentRef ]);
- // React to included note changes.
- useTriliumEvent("refreshIncludedNote", ({ noteId }) => {
+ // React to embedded note changes.
+ useTriliumEvent("refreshEmbeddedNote", ({ noteId }) => {
if (!contentRef.current) return;
- refreshIncludedNote(contentRef.current, noteId);
+ refreshEmbeddedNote(contentRef.current, noteId);
});
// Search integration.
@@ -164,15 +164,15 @@ function useNoteLanguage(note: FNote) {
return { isRtl };
}
-function applyIncludedNotes(container: HTMLDivElement) {
+function applyContentEmbeds(container: HTMLDivElement) {
const loaded: Promise<unknown>[] = [];
- const includedNotes = container.querySelectorAll<HTMLElement>(".include-note");
- for (const includedNote of includedNotes) {
- const { attachmentId, noteId } = includedNote.dataset;
+ const embeddedNotes = container.querySelectorAll<HTMLElement>(".include-note");
+ for (const embeddedNote of embeddedNotes) {
+ const { attachmentId, noteId } = embeddedNote.dataset;
if (attachmentId) {
- loaded.push(loadIncludedAttachment(attachmentId, $(includedNote)));
+ loaded.push(loadEmbeddedAttachment(attachmentId, $(embeddedNote)));
} else if (noteId) {
- loaded.push(loadIncludedNote(noteId, $(includedNote)));
+ loaded.push(loadEmbeddedNote(noteId, $(embeddedNote)));
}
}
return Promise.all(loaded);
diff --git a/apps/client/src/widgets/type_widgets/text/toolbar.ts b/apps/client/src/widgets/type_widgets/text/toolbar.ts
index 0f6c272eca..c7ef2a35a7 100644
--- a/apps/client/src/widgets/type_widgets/text/toolbar.ts
+++ b/apps/client/src/widgets/type_widgets/text/toolbar.ts
@@ -105,7 +105,7 @@ export function buildClassicToolbar(multilineToolbar: boolean, aiAssistant: bool
"footnote",
{
...buildInsertGroup(),
- items: ["link", "linkEmbed", "bookmark", "internallink", "includeNote", "|", "collapsible", "math", "mermaid", "horizontalLine", "pageBreak", "|", "dateTime", "specialCharacters", "emoji", "insertIcon"]
+ items: ["link", "linkEmbed", "bookmark", "internallink", "contentEmbed", "|", "collapsible", "math", "mermaid", "horizontalLine", "pageBreak", "|", "dateTime", "specialCharacters", "emoji", "insertIcon"]
},
"|",
buildAlignmentToolbar(),
@@ -176,7 +176,7 @@ export function buildFloatingToolbar(aiAssistant: boolean) {
"footnote",
{
...buildInsertGroup(),
- items: ["link", "linkEmbed", "bookmark", "internallink", "includeNote", "|", "collapsible", "math", "mermaid", "horizontalLine", "pageBreak", "dateTime"]
+ items: ["link", "linkEmbed", "bookmark", "internallink", "contentEmbed", "|", "collapsible", "math", "mermaid", "horizontalLine", "pageBreak", "dateTime"]
},
"|",
buildAlignmentToolbar(),
diff --git a/apps/client/src/widgets/type_widgets/text/utils.spec.ts b/apps/client/src/widgets/type_widgets/text/utils.spec.ts
index 1dac1f9479..3b59bfc0b6 100644
--- a/apps/client/src/widgets/type_widgets/text/utils.spec.ts
+++ b/apps/client/src/widgets/type_widgets/text/utils.spec.ts
@@ -18,9 +18,9 @@ vi.mock("../../../services/content_renderer", () => ({
mountInteractiveWidget: vi.fn()
}
}));
-vi.mock("./IncludeNote", () => ({
+vi.mock("./ContentEmbed", () => ({
default: () => null,
- TinyIncludeNote: () => null,
+ TinyContentEmbed: () => null,
getNoteActions: vi.fn()
}));
vi.mock("../../../services/attachment_actions", () => ({
@@ -39,20 +39,20 @@ import { getDownloadAction, getOpenExternallyAction } from "../../../services/at
import content_renderer from "../../../services/content_renderer";
import froca from "../../../services/froca";
import link from "../../../services/link";
-import IncludeNote, {
+import ContentEmbed, {
getNoteActions,
- type IncludeNoteAction,
- type IncludeNoteProps,
- TinyIncludeNote,
- type TinyIncludeNoteProps
-} from "./IncludeNote";
+ type ContentEmbedAction,
+ type ContentEmbedProps,
+ TinyContentEmbed,
+ type TinyContentEmbedProps
+} from "./ContentEmbed";
import {
getAttachmentHref,
- loadIncludedAttachment,
- loadIncludedNote,
- openIncludeNoteMenu,
- refreshIncludedNote,
- watchIncludedNotes
+ loadEmbeddedAttachment,
+ loadEmbeddedNote,
+ openContentEmbedMenu,
+ refreshEmbeddedNote,
+ watchContentEmbeds
} from "./utils";
const note = { noteId: "noteY", getIcon: () => "bx bx-note" } as unknown as FNote;
@@ -79,17 +79,17 @@ beforeEach(() => {
.mockResolvedValue({ $renderedContent: $(content), type: "pdf" } as never);
});
-function action(title: string): IncludeNoteAction {
+function action(title: string): ContentEmbedAction {
return { title, icon: `bx bx-${title}`, run: vi.fn() };
}
-/** The include box mounted last, and the element it was mounted in. */
+/** The embed box mounted last, and the element it was mounted in. */
function lastMount() {
const call = vi.mocked(content_renderer.mountInteractiveWidget).mock.lastCall;
if (!call) {
- throw new Error("Expected a mounted include box.");
+ throw new Error("Expected a mounted embed box.");
}
- const vnode = call[0] as VNode<IncludeNoteProps & TinyIncludeNoteProps>;
+ const vnode = call[0] as VNode<ContentEmbedProps & TinyContentEmbedProps>;
return { type: vnode.type, props: vnode.props, container: call[1] };
}
@@ -97,7 +97,7 @@ afterEach(() => {
document.body.replaceChildren();
});
-/** Puts `element` in the page, where the includes that load are. */
+/** Puts `element` in the page, where the embeds that load are. */
function inPage<T extends HTMLElement>(element: T) {
document.body.append(element);
return element;
@@ -109,11 +109,11 @@ function createWrapper() {
return wrapper;
}
-describe("loadIncludedNote", () => {
- it("mounts a box with the note, its own includes reduced to reference links", async () => {
+describe("loadEmbeddedNote", () => {
+ it("mounts a box with the note, its own embeds reduced to reference links", async () => {
const wrapper = createWrapper();
- await loadIncludedNote("noteY", $(wrapper), "medium");
+ await loadEmbeddedNote("noteY", $(wrapper), "medium");
expect(link.createLink).toHaveBeenCalledWith("noteY", {
showTooltip: false,
@@ -121,11 +121,11 @@ describe("loadIncludedNote", () => {
});
expect(content_renderer.getRenderedContent).toHaveBeenCalledWith(note, {
interactive: true,
- includesAsReferenceLinks: true,
+ embedsAsReferenceLinks: true,
mediaEnvironment: "embedded"
});
const mount = lastMount();
- expect(mount.type).toBe(IncludeNote);
+ expect(mount.type).toBe(ContentEmbed);
expect(mount.container).toBe(wrapper);
expect(mount.props).toEqual({
boxSize: "medium",
@@ -139,7 +139,7 @@ describe("loadIncludedNote", () => {
it("leaves the box alone for a note that no longer exists", async () => {
vi.mocked(froca.getNote).mockResolvedValue(null);
- await loadIncludedNote("noteY", $(createWrapper()), "small");
+ await loadEmbeddedNote("noteY", $(createWrapper()), "small");
expect(link.createLink).not.toHaveBeenCalled();
expect(content_renderer.mountInteractiveWidget).not.toHaveBeenCalled();
@@ -153,7 +153,7 @@ describe("loadIncludedNote", () => {
figure.dataset.boxSize = "tiny";
figure.innerHTML = "<figcaption>Caption</figcaption>";
- await loadIncludedNote("noteY", $(figure));
+ await loadEmbeddedNote("noteY", $(figure));
expect(link.createLink).toHaveBeenCalledWith("noteY", {
showTooltip: false,
@@ -162,7 +162,7 @@ describe("loadIncludedNote", () => {
expect(content_renderer.getRenderedContent).not.toHaveBeenCalled();
expect(getNoteActions).toHaveBeenCalledWith("noteY");
const mount = lastMount();
- expect(mount.type).toBe(TinyIncludeNote);
+ expect(mount.type).toBe(TinyContentEmbed);
expect([ ...figure.childNodes ]).toEqual([ mount.container ]);
expect(mount.props).toEqual({
icon: "bx bx-note",
@@ -173,11 +173,11 @@ describe("loadIncludedNote", () => {
});
});
-describe("loadIncludedAttachment", () => {
+describe("loadEmbeddedAttachment", () => {
it("mounts a box with the attachment, opened in its note", async () => {
const wrapper = createWrapper();
- await loadIncludedAttachment("att1", $(wrapper), "full");
+ await loadEmbeddedAttachment("att1", $(wrapper), "full");
expect(froca.getAttachment).toHaveBeenCalledWith("att1", true);
expect(link.createLink).toHaveBeenCalledWith("owner", {
@@ -188,7 +188,7 @@ describe("loadIncludedAttachment", () => {
expect(content_renderer.getRenderedContent)
.toHaveBeenCalledWith(attachment, { interactive: true, mediaEnvironment: "embedded" });
const mount = lastMount();
- expect(mount.type).toBe(IncludeNote);
+ expect(mount.type).toBe(ContentEmbed);
expect(mount.container).toBe(wrapper);
expect(mount.props).toEqual({
boxSize: "full",
@@ -203,7 +203,7 @@ describe("loadIncludedAttachment", () => {
it("leaves the box alone for a deleted attachment", async () => {
vi.mocked(froca.getAttachment).mockResolvedValue(null);
- await loadIncludedAttachment("att1", $(createWrapper()), "small");
+ await loadEmbeddedAttachment("att1", $(createWrapper()), "small");
expect(link.createLink).not.toHaveBeenCalled();
expect(content_renderer.mountInteractiveWidget).not.toHaveBeenCalled();
@@ -215,7 +215,7 @@ describe("loadIncludedAttachment", () => {
vi.mocked(getDownloadAction).mockReturnValue(download);
const wrapper = createWrapper();
- await loadIncludedAttachment("att1", $(wrapper), "tiny");
+ await loadEmbeddedAttachment("att1", $(wrapper), "tiny");
expect(link.createLink).toHaveBeenCalledWith("owner", {
showTooltip: false,
@@ -225,7 +225,7 @@ describe("loadIncludedAttachment", () => {
expect(getOpenExternallyAction).toHaveBeenCalledWith(attachment);
expect(getDownloadAction).toHaveBeenCalledWith(attachment);
const mount = lastMount();
- expect(mount.type).toBe(TinyIncludeNote);
+ expect(mount.type).toBe(TinyContentEmbed);
expect(mount.container).toBe(wrapper);
expect(mount.props).toEqual({
icon: attachmentIcon("file", "application/pdf"),
@@ -238,15 +238,15 @@ describe("loadIncludedAttachment", () => {
});
});
-describe("the element an include box is mounted in", () => {
- it("is a wrapper created in a read-only include ahead of its caption", async () => {
+describe("the element an embed box is mounted in", () => {
+ it("is a wrapper created in a read-only embed ahead of its caption", async () => {
const figure = inPage(document.createElement("figure"));
figure.className = "include-note";
figure.dataset.boxSize = "expandable";
figure.innerHTML = "&nbsp;<figcaption>Caption</figcaption>";
const caption = figure.querySelector("figcaption");
- await loadIncludedNote("noteY", $(figure));
+ await loadEmbeddedNote("noteY", $(figure));
const { container, props } = lastMount();
expect(caption).not.toBeNull();
@@ -255,23 +255,23 @@ describe("the element an include box is mounted in", () => {
expect(props.boxSize).toBe("expandable");
// Loading again, as a refresh does, reuses the wrapper.
- await loadIncludedNote("noteY", $(figure), "small");
+ await loadEmbeddedNote("noteY", $(figure), "small");
expect(lastMount().container).toBe(container);
expect(lastMount().props.boxSize).toBe("small");
});
- it("is a wrapper created in a legacy <section> include", async () => {
+ it("is a wrapper created in a legacy <section> embed", async () => {
const section = inPage(document.createElement("section"));
section.className = "include-note";
section.dataset.boxSize = "medium";
- await loadIncludedNote("noteY", $(section));
+ await loadEmbeddedNote("noteY", $(section));
expect([ ...section.childNodes ]).toEqual([ lastMount().container ]);
expect(lastMount().props.boxSize).toBe("medium");
});
- it("is the wrapper an editor include holds, leaving the editor's own elements", async () => {
+ it("is the wrapper an editor embed holds, leaving the editor's own elements", async () => {
const figure = inPage(document.createElement("figure"));
figure.className = "include-note ck-widget";
figure.dataset.boxSize = "full";
@@ -280,7 +280,7 @@ describe("the element an include box is mounted in", () => {
const typeAround = document.createElement("div");
figure.append(wrapper, caption, typeAround);
- await loadIncludedAttachment("att1", $(figure));
+ await loadEmbeddedAttachment("att1", $(figure));
expect(lastMount().container).toBe(wrapper);
expect(lastMount().props.boxSize).toBe("full");
@@ -288,13 +288,13 @@ describe("the element an include box is mounted in", () => {
});
});
-describe("an include that leaves the page while it loads", () => {
+describe("an embed that leaves the page while it loads", () => {
it("gets no box, and the content rendered for it is disposed", async () => {
const loads: [ (wrapper: HTMLElement) => Promise<void>, boolean ][] = [
- [ (wrapper) => loadIncludedNote("noteY", $(wrapper), "medium"), true ],
- [ (wrapper) => loadIncludedNote("noteY", $(wrapper), "tiny"), false ],
- [ (wrapper) => loadIncludedAttachment("att1", $(wrapper), "full"), true ],
- [ (wrapper) => loadIncludedAttachment("att1", $(wrapper), "tiny"), false ]
+ [ (wrapper) => loadEmbeddedNote("noteY", $(wrapper), "medium"), true ],
+ [ (wrapper) => loadEmbeddedNote("noteY", $(wrapper), "tiny"), false ],
+ [ (wrapper) => loadEmbeddedAttachment("att1", $(wrapper), "full"), true ],
+ [ (wrapper) => loadEmbeddedAttachment("att1", $(wrapper), "tiny"), false ]
];
for (const [ load, rendersContent ] of loads) {
@@ -315,15 +315,15 @@ describe("an include that leaves the page while it loads", () => {
});
});
-describe("refreshIncludedNote", () => {
- it("reloads every include of the note, of either element", async () => {
+describe("refreshEmbeddedNote", () => {
+ it("reloads every embed of the note, of either element", async () => {
const container = inPage(document.createElement("div"));
container.innerHTML = `<figure class="include-note" data-note-id="noteY"></figure>`
+ `<section class="include-note" data-note-id="noteY"></section>`
+ `<figure class="include-note" data-note-id="other"></figure>`;
const [ figure, section ] = [ ...container.children ];
- refreshIncludedNote(container, "noteY");
+ refreshEmbeddedNote(container, "noteY");
await vi.waitFor(() => {
expect(content_renderer.mountInteractiveWidget).toHaveBeenCalledTimes(2);
@@ -334,7 +334,7 @@ describe("refreshIncludedNote", () => {
});
});
-describe("watchIncludedNotes", () => {
+describe("watchContentEmbeds", () => {
let container: HTMLElement;
beforeEach(() => {
@@ -358,26 +358,26 @@ describe("watchIncludedNotes", () => {
}
it("unmounts what is removed from the container, but not what is moved within it", async () => {
- const stop = watchIncludedNotes(container);
- const [ paragraph, include, quote ] = [ ...container.children ];
+ const stop = watchContentEmbeds(container);
+ const [ paragraph, embed, quote ] = [ ...container.children ];
- include.remove();
+ embed.remove();
quote.remove();
container.append(quote);
paragraph.firstChild?.remove();
await flush();
- expect(disposed()).toEqual([ include ]);
+ expect(disposed()).toEqual([ embed ]);
stop();
});
it("unmounts what is left on stop, and stops watching", async () => {
- const stop = watchIncludedNotes(container);
- const include = container.querySelector("figure");
- include?.remove();
+ const stop = watchContentEmbeds(container);
+ const embed = container.querySelector("figure");
+ embed?.remove();
stop();
- expect(disposed()).toEqual([ include, container ]);
+ expect(disposed()).toEqual([ embed, container ]);
container.querySelector("blockquote")?.remove();
await flush();
@@ -385,30 +385,30 @@ describe("watchIncludedNotes", () => {
});
});
-describe("openIncludeNoteMenu", () => {
- it("opens the menu of the note or attachment an include shows, below the anchor", async () => {
+describe("openContentEmbedMenu", () => {
+ it("opens the menu of the note or attachment an embed shows, below the anchor", async () => {
const anchor = document.createElement("button");
- const noteInclude = inPage(document.createElement("figure"));
- noteInclude.dataset.noteId = "noteY";
+ const noteEmbed = inPage(document.createElement("figure"));
+ noteEmbed.dataset.noteId = "noteY";
const embed = inPage(document.createElement("figure"));
embed.dataset.attachmentId = "att1";
- await openIncludeNoteMenu(noteInclude, anchor);
- await openIncludeNoteMenu(embed, anchor);
+ await openContentEmbedMenu(noteEmbed, anchor);
+ await openContentEmbedMenu(embed, anchor);
expect(vi.mocked(linkContextMenu.openContextMenu).mock.calls).toEqual([
- [ "noteY", { anchor, target: noteInclude }, {} ],
+ [ "noteY", { anchor, target: noteEmbed }, {} ],
[ "owner", { anchor, target: embed }, ATTACHMENT_SCOPE ]
]);
});
- it("opens nothing for an include of a deleted attachment, or of nothing", async () => {
+ it("opens nothing for an embed of a deleted attachment, or of nothing", async () => {
vi.mocked(froca.getAttachment).mockResolvedValue(null);
const embed = inPage(document.createElement("figure"));
embed.dataset.attachmentId = "att1";
- await openIncludeNoteMenu(embed, document.createElement("button"));
- await openIncludeNoteMenu(inPage(document.createElement("figure")), document.createElement("button"));
+ await openContentEmbedMenu(embed, document.createElement("button"));
+ await openContentEmbedMenu(inPage(document.createElement("figure")), document.createElement("button"));
expect(linkContextMenu.openContextMenu).not.toHaveBeenCalled();
});
diff --git a/apps/client/src/widgets/type_widgets/text/utils.ts b/apps/client/src/widgets/type_widgets/text/utils.ts
index 6b5f24a9eb..d8e936a853 100644
--- a/apps/client/src/widgets/type_widgets/text/utils.ts
+++ b/apps/client/src/widgets/type_widgets/text/utils.ts
@@ -4,34 +4,34 @@ import { h, type JSX } from "preact";
import appContext from "../../../components/app_context";
import linkContextMenu from "../../../menus/link_context_menu";
import content_renderer from "../../../services/content_renderer";
-import { getIncludeCaption } from "../../../services/content_renderer_text";
+import { getEmbedCaption } from "../../../services/content_renderer_text";
import froca from "../../../services/froca";
import link, { ViewScope } from "../../../services/link";
import utils from "../../../services/utils";
-import IncludeNote, { getNoteActions, TinyIncludeNote } from "./IncludeNote";
+import ContentEmbed, { getNoteActions, TinyContentEmbed } from "./ContentEmbed";
/**
- * Fills an include box with a note. Without a box size of its own, the box takes the one of its
- * include.
+ * Fills an embed box with a note. Without a box size of its own, the box takes the one of its
+ * embed.
*/
-export async function loadIncludedNote(noteId: string, $el: JQuery<HTMLElement>, boxSize?: string) {
+export async function loadEmbeddedNote(noteId: string, $el: JQuery<HTMLElement>, boxSize?: string) {
const note = await froca.getNote(noteId);
if (!note) return;
const el = $el[0];
- const size = boxSize ?? getIncludeBoxSize(el);
+ const size = boxSize ?? getEmbedBoxSize(el);
if (size === "tiny") {
const $link = await link.createLink(note.noteId, {
showTooltip: false,
showNotePath: true
});
- const box = h(TinyIncludeNote, {
+ const box = h(TinyContentEmbed, {
icon: note.getIcon(),
title: $link[0],
notePath: note.noteId,
actions: getNoteActions(note.noteId)
});
- await mountIncludeBox(el, box);
+ await mountEmbedBox(el, box);
return;
}
@@ -40,29 +40,29 @@ export async function loadIncludedNote(noteId: string, $el: JQuery<HTMLElement>,
showNoteIcon: true
});
- // The include widget itself is the first level of inclusion, so the included note's own
- // includes are rendered as reference links rather than expanded (see includesAsReferenceLinks).
+ // The embed widget itself is the first level of embedding, so the embedded note's own
+ // embeds are rendered as reference links rather than expanded (see embedsAsReferenceLinks).
const { $renderedContent, type } = await content_renderer.getRenderedContent(note, {
interactive: true,
- includesAsReferenceLinks: true,
+ embedsAsReferenceLinks: true,
mediaEnvironment: "embedded"
});
- const box = h(IncludeNote, {
+ const box = h(ContentEmbed, {
boxSize: size,
title: $link[0],
content: $renderedContent[0],
contentType: type,
notePath: note.noteId
});
- await mountIncludeBox(el, box, $renderedContent);
+ await mountEmbedBox(el, box, $renderedContent);
}
/**
- * Fills an include box with an embedded attachment, under a title linking to it. Without a box
- * size of its own, the box takes the one of its include.
+ * Fills an embed box with an embedded attachment, under a title linking to it. Without a box
+ * size of its own, the box takes the one of its embed.
*/
-export async function loadIncludedAttachment(
+export async function loadEmbeddedAttachment(
attachmentId: string,
$el: JQuery<HTMLElement>,
boxSize?: string
@@ -71,7 +71,7 @@ export async function loadIncludedAttachment(
if (!attachment) return;
const el = $el[0];
- const size = boxSize ?? getIncludeBoxSize(el);
+ const size = boxSize ?? getEmbedBoxSize(el);
const viewScope: ViewScope = { viewMode: "attachments", attachmentId };
if (size === "tiny") {
// `attachment_actions` is imported on demand: it imports the image compression dialog.
@@ -79,7 +79,7 @@ export async function loadIncludedAttachment(
link.createLink(attachment.ownerId, { showTooltip: false, viewScope }),
import("../../../services/attachment_actions")
]);
- const box = h(TinyIncludeNote, {
+ const box = h(TinyContentEmbed, {
icon: attachmentIcon(attachment.role, attachment.mime),
title: $link[0],
description: utils.formatSize(attachment.contentLength),
@@ -87,7 +87,7 @@ export async function loadIncludedAttachment(
viewScope,
actions: [ getOpenExternallyAction(attachment), getDownloadAction(attachment) ]
});
- await mountIncludeBox(el, box);
+ await mountEmbedBox(el, box);
return;
}
@@ -101,7 +101,7 @@ export async function loadIncludedAttachment(
{ interactive: true, mediaEnvironment: "embedded" }
);
- const box = h(IncludeNote, {
+ const box = h(ContentEmbed, {
boxSize: size,
title: $link[0],
content: $renderedContent[0],
@@ -109,14 +109,14 @@ export async function loadIncludedAttachment(
notePath: attachment.ownerId,
viewScope
});
- await mountIncludeBox(el, box, $renderedContent);
+ await mountEmbedBox(el, box, $renderedContent);
}
/**
- * Mounts `box` in the include `el`. An include that left the page while it loaded gets no box,
- * and `content` rendered for it is disposed: `watchIncludedNotes()` has already passed it.
+ * Mounts `box` in the embed `el`. An embed that left the page while it loaded gets no box,
+ * and `content` rendered for it is disposed: `watchContentEmbeds()` has already passed it.
*/
-async function mountIncludeBox(el: HTMLElement, box: JSX.Element, content?: JQuery<HTMLElement>) {
+async function mountEmbedBox(el: HTMLElement, box: JSX.Element, content?: JQuery<HTMLElement>) {
if (!el.isConnected) {
if (content) {
content_renderer.disposeInteractiveContent(content);
@@ -127,12 +127,12 @@ async function mountIncludeBox(el: HTMLElement, box: JSX.Element, content?: JQue
await content_renderer.mountInteractiveWidget(box, getWrapper(el));
}
-function getIncludeBoxSize(el: HTMLElement) {
+function getEmbedBoxSize(el: HTMLElement) {
return el.closest<HTMLElement>(".include-note")?.dataset.boxSize;
}
/**
- * The element an include box is mounted in: `el` when it is the `.include-note-wrapper` the
+ * The element an embed box is mounted in: `el` when it is the `.include-note-wrapper` the
* editor renders, otherwise the wrapper of the `.include-note`, reused or created ahead of the
* caption.
*/
@@ -148,18 +148,18 @@ function getWrapper(el: HTMLElement) {
const wrapper = document.createElement("div");
wrapper.className = "include-note-wrapper";
- const caption = getIncludeCaption(el);
+ const caption = getEmbedCaption(el);
el.replaceChildren(wrapper, ...(caption ? [ caption ] : []));
return wrapper;
}
/**
- * Opens the context menu of the note or attachment that `include` shows, below `anchor`. The menu
- * opens from the include, so that the text editor that contains it stays focused.
+ * Opens the context menu of the note or attachment that `embed` shows, below `anchor`. The menu
+ * opens from the embed, so that the text editor that contains it stays focused.
*/
-export async function openIncludeNoteMenu(include: HTMLElement, anchor: HTMLElement) {
- const { noteId, attachmentId } = include.dataset;
- const origin = linkContextMenu.getOriginBelow(anchor, include);
+export async function openContentEmbedMenu(embed: HTMLElement, anchor: HTMLElement) {
+ const { noteId, attachmentId } = embed.dataset;
+ const origin = linkContextMenu.getOriginBelow(anchor, embed);
if (attachmentId) {
const attachment = await froca.getAttachment(attachmentId, true);
@@ -183,10 +183,10 @@ export async function getAttachmentHref(attachmentId: string) {
}
/**
- * Unmounts the include boxes, and what they show, once they leave `container`. The returned
+ * Unmounts the embed boxes, and what they show, once they leave `container`. The returned
* function stops watching and unmounts the boxes still in it.
*/
-export function watchIncludedNotes(container: HTMLElement) {
+export function watchContentEmbeds(container: HTMLElement) {
const observer = new MutationObserver(disposeRemoved);
observer.observe(container, { childList: true, subtree: true });
@@ -208,10 +208,10 @@ function disposeRemoved(records: MutationRecord[]) {
}
}
-export function refreshIncludedNote(container: HTMLDivElement, noteId: string) {
- const includedNotes = container.querySelectorAll(`.include-note[data-note-id="${noteId}"]`);
- for (const includedNote of includedNotes) {
- loadIncludedNote(noteId, $(includedNote as HTMLElement));
+export function refreshEmbeddedNote(container: HTMLDivElement, noteId: string) {
+ const embeddedNotes = container.querySelectorAll(`.include-note[data-note-id="${noteId}"]`);
+ for (const embeddedNote of embeddedNotes) {
+ loadEmbeddedNote(noteId, $(embeddedNote as HTMLElement));
}
}
diff --git a/packages/ckeditor5/src/augmentation.ts b/packages/ckeditor5/src/augmentation.ts
index 1ddc60b9dc..c94e58f1bd 100644
--- a/packages/ckeditor5/src/augmentation.ts
+++ b/packages/ckeditor5/src/augmentation.ts
@@ -43,8 +43,8 @@ declare global {
formatDateTime(date: Date, format?: string): string;
loadReferenceLinkTitle($el: JQuery<HTMLElement>, href: string): Promise<void>;
createNoteForReferenceLink(title: string, intoInbox: boolean): Promise<string | undefined>;
- loadIncludedNote(noteId: string, $el: JQuery<HTMLElement>, boxSize?: string): void;
- loadIncludedAttachment(
+ loadEmbeddedNote(noteId: string, $el: JQuery<HTMLElement>, boxSize?: string): void;
+ loadEmbeddedAttachment(
attachmentId: string,
$el: JQuery<HTMLElement>,
boxSize?: string
@@ -55,14 +55,14 @@ declare global {
getNoteId?(): string | undefined;
/**
* The box size of a new embed of a file being uploaded, from its media type. Hosts without
- * includes leave it out.
+ * embeds leave it out.
*/
getEmbedBoxSize?(mime: string): string;
/**
- * Opens the context menu of what `include` shows, below `anchor`. Hosts without includes
+ * Opens the context menu of what `embed` shows, below `anchor`. Hosts without embeds
* leave it out.
*/
- openIncludeNoteMenu?(include: HTMLElement, anchor: HTMLElement): void;
+ openContentEmbedMenu?(embed: HTMLElement, anchor: HTMLElement): void;
/**
* Reads a page's preview metadata through the host. Never rejects: any failure — network
* error, HTTP error, unparseable page — resolves as `{ unresolved: true }` with
diff --git a/packages/ckeditor5/src/index.ts b/packages/ckeditor5/src/index.ts
index 8af13f3801..9aa1d36be8 100644
--- a/packages/ckeditor5/src/index.ts
+++ b/packages/ckeditor5/src/index.ts
@@ -15,7 +15,7 @@ export type { EditorConfig, MentionFeed, MentionFeedObjectItem, ModelNode, Model
export type { ClipboardImageEmbedConfig } from "./plugins/clipboard_image_embed.js";
export type { FileUploadData, FileUploadEvent } from "./plugins/file_upload/fileuploadediting.js";
export type { PasteTarget } from "./plugins/cuttonote.js";
-export type { IncludeNoteState } from "./plugins/includenote.js";
+export type { ContentEmbedState } from "./plugins/content_embed/content_embed.js";
export type { AttachmentLinkChange } from "./plugins/referencelink.js";
export type { SlashCommandConfig, SlashCommandDefinition } from "./plugins/mention/slash_commands.js";
export type { TriliumMentionFeed } from "./plugins/mention/types.js";
@@ -29,7 +29,7 @@ export * from "./utils.js";
// Import with sideffects to ensure that type augmentations are present.
import "./plugins/file_upload/uploadfileplugin.js";
-import "./plugins/includenote.js";
+import "./plugins/content_embed/content_embed.js";
import "./plugins/math/math.js";
import "./plugins/mermaid/mermaid.js";
import "./plugins/referencelink.js";
diff --git a/packages/ckeditor5/src/plugins.spec.ts b/packages/ckeditor5/src/plugins.spec.ts
index a855de4c05..b44547abe1 100644
--- a/packages/ckeditor5/src/plugins.spec.ts
+++ b/packages/ckeditor5/src/plugins.spec.ts
@@ -11,7 +11,7 @@ import CutToNotePlugin from "./plugins/cuttonote.js";
import Uploadfileplugin from "./plugins/file_upload/uploadfileplugin.js";
import FindInLinkWidgets from "./plugins/find_in_link_widgets.js";
import TriliumFormatPainter from "./plugins/format_painter/format_painter.js";
-import IncludeNote from "./plugins/includenote.js";
+import ContentEmbed from "./plugins/content_embed/content_embed.js";
import InternalLinkPlugin from "./plugins/internallink.js";
import LinkEmbed from "./plugins/link_embed/link_embed.js";
import TriliumSlashCommands from "./plugins/mention/slash_commands.js";
@@ -78,7 +78,7 @@ describe("plugin lists", () => {
it("COMMON_PLUGINS includes the in-tree Trilium feature plugins", () => {
expect(COMMON_PLUGINS).toContain(CutToNotePlugin);
expect(COMMON_PLUGINS).toContain(InternalLinkPlugin);
- expect(COMMON_PLUGINS).toContain(IncludeNote);
+ expect(COMMON_PLUGINS).toContain(ContentEmbed);
expect(COMMON_PLUGINS).toContain(LinkEmbed);
expect(COMMON_PLUGINS).toContain(FindInLinkWidgets);
expect(COMMON_PLUGINS).toContain(Uploadfileplugin);
diff --git a/packages/ckeditor5/src/plugins.ts b/packages/ckeditor5/src/plugins.ts
index 367a239464..f651e8be93 100644
--- a/packages/ckeditor5/src/plugins.ts
+++ b/packages/ckeditor5/src/plugins.ts
@@ -20,7 +20,7 @@ import TriliumEmojiMention from "./plugins/mention/emoji_mention.js";
import TriliumMentionUI from "./plugins/mention/trilium_mention_ui.js";
import TriliumSlashCommands from "./plugins/mention/slash_commands.js";
import TriliumFormatPainter from "./plugins/format_painter/format_painter.js";
-import IncludeNote from "./plugins/includenote.js";
+import ContentEmbed from "./plugins/content_embed/content_embed.js";
import InlineIcon from "./plugins/inline_icon/inline_icon.js";
import LinkEmbed from "./plugins/link_embed/link_embed.js";
import Uploadfileplugin from "./plugins/file_upload/uploadfileplugin.js";
@@ -51,8 +51,9 @@ import InlineCodeNoSpellcheck from "./plugins/inline_code_no_spellcheck.js";
import InlineCodeToolbar from "./plugins/inline_code_toolbar.js";
import AdmonitionTypeDropdown from "./plugins/admonition/admonition_type_dropdown.js";
import AdmonitionToolbar from "./plugins/admonition/admonition_toolbar.js";
-import IncludeNoteBoxSizeDropdown from "./plugins/include_note_box_size_dropdown.js";
-import IncludeNoteToolbar from "./plugins/include_note_toolbar.js";
+import ContentEmbedBoxSizeDropdown
+ from "./plugins/content_embed/content_embed_box_size_dropdown.js";
+import ContentEmbedToolbar from "./plugins/content_embed/content_embed_toolbar.js";
import LinkEmbedToolbar from "./plugins/link_embed/link_embed_toolbar.js";
import TodoListMultistate from "./plugins/todo_list_multistate/todo_list_multistate.js";
import TodoListUncheckOnEnter from "./plugins/todo_list_uncheck_on_enter.js";
@@ -79,7 +80,7 @@ const TRILIUM_PLUGINS: typeof Plugin[] = [
RemoveFormatLinksPlugin,
IndentBlockShortcutPlugin,
MarkdownImportPlugin,
- IncludeNote,
+ ContentEmbed,
InlineIcon,
LinkEmbed,
Uploadfileplugin,
@@ -94,8 +95,8 @@ const TRILIUM_PLUGINS: typeof Plugin[] = [
InlineCodeToolbar,
AdmonitionTypeDropdown,
AdmonitionToolbar,
- IncludeNoteBoxSizeDropdown,
- IncludeNoteToolbar,
+ ContentEmbedBoxSizeDropdown,
+ ContentEmbedToolbar,
LinkEmbedToolbar,
TodoListMultistate,
CollapsibleListItems,
diff --git a/packages/ckeditor5/src/plugins/includenote.spec.ts b/packages/ckeditor5/src/plugins/content_embed/content_embed.spec.ts
similarity index 78%
rename from packages/ckeditor5/src/plugins/includenote.spec.ts
rename to packages/ckeditor5/src/plugins/content_embed/content_embed.spec.ts
index 13b3c31f9e..5b469f1afa 100644
--- a/packages/ckeditor5/src/plugins/includenote.spec.ts
+++ b/packages/ckeditor5/src/plugins/content_embed/content_embed.spec.ts
@@ -16,33 +16,33 @@ import {
import bxWindowAlt from "boxicons/svg/regular/bx-window-alt.svg?raw";
import { beforeEach, describe, expect, it, vi } from "vitest";
-import { createTestEditor } from "../../test/editor-kit.js";
-import { installGlobMock } from "../../test/globals-test-kit.js";
-import IncludeNote, {
+import { createTestEditor } from "../../../test/editor-kit.js";
+import { installGlobMock } from "../../../test/globals-test-kit.js";
+import ReferenceLink from "../referencelink.js";
+import ContentEmbed, {
BOX_SIZE_COMMAND_NAME,
BOX_SIZES,
COMMAND_NAME,
EMBED_ATTACHMENT_LINK_COMMAND,
CONVERT_EMBED_TO_LINK_COMMAND,
- INCLUDE_NOTE_MENU,
+ CONTENT_EMBED_MENU,
TOGGLE_CAPTION_COMMAND_NAME,
TOGGLE_TITLE_COMMAND_NAME
-} from "./includenote.js";
-import ReferenceLink from "./referencelink.js";
+} from "./content_embed.js";
-describe("IncludeNote", () => {
+describe("ContentEmbed", () => {
let editor: ClassicEditor;
let triggerCommand: ReturnType<typeof vi.fn>;
- let loadIncludedNote: ReturnType<typeof vi.fn>;
+ let loadEmbeddedNote: ReturnType<typeof vi.fn>;
beforeEach(async () => {
triggerCommand = vi.fn();
- loadIncludedNote = vi.fn();
+ loadEmbeddedNote = vi.fn();
installGlobMock({
- getComponentByEl: () => ({ triggerCommand, loadIncludedNote })
+ getComponentByEl: () => ({ triggerCommand, loadEmbeddedNote })
});
- editor = await createTestEditor([Essentials, Paragraph, Widget, IncludeNote]);
+ editor = await createTestEditor([Essentials, Paragraph, Widget, ContentEmbed]);
});
// -----------------------------------------------------------------------
@@ -50,16 +50,16 @@ describe("IncludeNote", () => {
// -----------------------------------------------------------------------
it("loads the plugin, sub-plugins, schema, commands and the toolbar button", () => {
- expect(editor.plugins.get(IncludeNote)).toBeInstanceOf(IncludeNote);
+ expect(editor.plugins.get(ContentEmbed)).toBeInstanceOf(ContentEmbed);
expect(editor.commands.get(COMMAND_NAME)).toBeDefined();
expect(editor.commands.get(BOX_SIZE_COMMAND_NAME)).toBeDefined();
- expect(editor.ui.componentFactory.has("includeNote")).toBe(true);
+ expect(editor.ui.componentFactory.has("contentEmbed")).toBe(true);
const schema = editor.model.schema;
- expect(schema.isRegistered("includeNote")).toBe(true);
- expect(schema.isObject("includeNote")).toBe(true);
- expect(schema.checkAttribute(["$root", "includeNote"], "noteId")).toBe(true);
- expect(schema.checkAttribute(["$root", "includeNote"], "boxSize")).toBe(true);
+ expect(schema.isRegistered("contentEmbed")).toBe(true);
+ expect(schema.isObject("contentEmbed")).toBe(true);
+ expect(schema.checkAttribute(["$root", "contentEmbed"], "noteId")).toBe(true);
+ expect(schema.checkAttribute(["$root", "contentEmbed"], "boxSize")).toBe(true);
});
// -----------------------------------------------------------------------
@@ -67,7 +67,7 @@ describe("IncludeNote", () => {
// -----------------------------------------------------------------------
it("wires the toolbar button to the insert command (enablement and execution)", () => {
- const view = editor.ui.componentFactory.create("includeNote") as {
+ const view = editor.ui.componentFactory.create("contentEmbed") as {
isEnabled: boolean;
isOn: boolean;
label: string;
@@ -87,12 +87,12 @@ describe("IncludeNote", () => {
// Conversion: upcast / data downcast / editing downcast
// -----------------------------------------------------------------------
- it("loads a <figure> include and a legacy <section>, and saves a <figure>", () => {
+ it("loads a <figure> embed and a legacy <section>, and saves a <figure>", () => {
for (const tag of [ "figure", "section" ]) {
editor.setData(`<${tag} class="include-note" data-note-id="abc123"`
+ ` data-box-size="medium"></${tag}>`);
- const element = findIncludeNote(editor);
+ const element = findContentEmbed(editor);
expect(element?.getAttribute("noteId")).toBe("abc123");
expect(element?.getAttribute("boxSize")).toBe("medium");
expect(editor.getData()).toBe("<figure class=\"include-note\" data-note-id=\"abc123\" "
@@ -100,7 +100,7 @@ describe("IncludeNote", () => {
}
});
- it("editing-downcasts to a widget and invokes loadIncludedNote when the UIElement renders", () => {
+ it("editing-downcasts to a widget and invokes loadEmbeddedNote when the UIElement renders", () => {
editor.setData(
'<figure class="include-note" data-note-id="noteY" data-box-size="small"></figure>'
);
@@ -117,15 +117,15 @@ describe("IncludeNote", () => {
const wrapper = domRoot?.querySelector("div.include-note-wrapper");
expect(wrapper).not.toBeNull();
- expect(loadIncludedNote).toHaveBeenCalledTimes(1);
- expect(loadIncludedNote.mock.calls[0]?.[0]).toBe("noteY");
+ expect(loadEmbeddedNote).toHaveBeenCalledTimes(1);
+ expect(loadEmbeddedNote.mock.calls[0]?.[0]).toBe("noteY");
// The box size is passed explicitly so the client render does not have to read it back
// from the DOM (which may not be flushed yet at conversion time).
- expect(loadIncludedNote.mock.calls[0]?.[2]).toBe("small");
+ expect(loadEmbeddedNote.mock.calls[0]?.[2]).toBe("small");
});
it("updates the box-size class on the editing view when the boxSize attribute changes", () => {
- insertIncludeNote(editor, "noteZ", "small");
+ insertContentEmbed(editor, "noteZ", "small");
const domRoot = editor.editing.view.getDomRoot();
const figure = domRoot?.querySelector("figure.include-note");
@@ -138,26 +138,26 @@ describe("IncludeNote", () => {
expect(figure?.getAttribute("data-box-size")).toBe("full");
});
- it("re-renders the included note content with the new size on a genuine box-size change", () => {
- insertIncludeNote(editor, "noteReload", "small");
+ it("re-renders the embedded note content with the new size on a genuine box-size change", () => {
+ insertContentEmbed(editor, "noteReload", "small");
// One call for the initial render.
- expect(loadIncludedNote).toHaveBeenCalledTimes(1);
- expect(loadIncludedNote.mock.calls[0]?.[2]).toBe("small");
+ expect(loadEmbeddedNote).toHaveBeenCalledTimes(1);
+ expect(loadEmbeddedNote.mock.calls[0]?.[2]).toBe("small");
editor.execute(BOX_SIZE_COMMAND_NAME, { value: "expandable" });
// The downcast handler drives a second render with the new size, without any DOM observer.
- expect(loadIncludedNote).toHaveBeenCalledTimes(2);
- const reloadCall = loadIncludedNote.mock.calls[1];
+ expect(loadEmbeddedNote).toHaveBeenCalledTimes(2);
+ const reloadCall = loadEmbeddedNote.mock.calls[1];
expect(reloadCall?.[0]).toBe("noteReload");
expect(reloadCall?.[2]).toBe("expandable");
});
it("handles a boxSize change from an empty old value (no class to remove)", () => {
- // Insert an includeNote whose boxSize is empty so the attribute-change converter
+ // Insert an contentEmbed whose boxSize is empty so the attribute-change converter
// hits the falsy `oldBoxSize` branch when the value is set for the first time.
- const element = insertIncludeNote(editor, "noteW", "");
+ const element = insertContentEmbed(editor, "noteW", "");
editor.model.change((writer) => {
writer.setAttribute("boxSize", "medium", element);
@@ -170,7 +170,7 @@ describe("IncludeNote", () => {
});
it("ignores a boxSize change cleared to an empty value (no new class to add)", () => {
- const element = insertIncludeNote(editor, "noteV", "small");
+ const element = insertContentEmbed(editor, "noteV", "small");
editor.model.change((writer) => {
writer.setAttribute("boxSize", "", element);
@@ -184,7 +184,7 @@ describe("IncludeNote", () => {
});
// -----------------------------------------------------------------------
- // InsertIncludeNoteCommand
+ // InsertContentEmbedCommand
// -----------------------------------------------------------------------
it("triggers addIncludeNoteToText on the Trilium component when the insert command executes", () => {
@@ -198,10 +198,10 @@ describe("IncludeNote", () => {
setModelData(editor.model, "<paragraph>foo[]bar</paragraph>");
expect(command?.isEnabled).toBe(true);
- // Forbid includeNote anywhere via a child check, then refresh: no allowed parent
+ // Forbid contentEmbed anywhere via a child check, then refresh: no allowed parent
// for the current selection means the command disables itself.
editor.model.schema.addChildCheck((_context, def) => {
- if (def.name === "includeNote") {
+ if (def.name === "contentEmbed") {
return false;
}
});
@@ -210,10 +210,10 @@ describe("IncludeNote", () => {
});
// -----------------------------------------------------------------------
- // IncludeNoteBoxSizeCommand
+ // ContentEmbedBoxSizeCommand
// -----------------------------------------------------------------------
- it("box-size command is disabled with no selected includeNote and reports a null value", () => {
+ it("box-size command is disabled with no embed selected and reports a null value", () => {
setModelData(editor.model, "<paragraph>foo[]bar</paragraph>");
const command = editor.commands.get(BOX_SIZE_COMMAND_NAME) as {
@@ -224,8 +224,8 @@ describe("IncludeNote", () => {
expect(command.value).toBeNull();
});
- it("box-size command enables and reflects the value when an includeNote is selected", () => {
- insertIncludeNote(editor, "noteSel", "medium");
+ it("box-size command enables and reflects the value when an contentEmbed is selected", () => {
+ insertContentEmbed(editor, "noteSel", "medium");
const command = editor.commands.get(BOX_SIZE_COMMAND_NAME) as {
isEnabled: boolean;
@@ -238,16 +238,16 @@ describe("IncludeNote", () => {
for (const value of BOX_SIZES) {
editor.execute(BOX_SIZE_COMMAND_NAME, { value });
expect(command.value).toBe(value);
- expect(findIncludeNote(editor)?.getAttribute("boxSize")).toBe(value);
+ expect(findContentEmbed(editor)?.getAttribute("boxSize")).toBe(value);
}
});
- it("box-size command resolves the includeNote via an ancestor position (not a direct selection)", () => {
- // Make the includeNote allow text inside so the selection can be placed within it
+ it("box-size command resolves the contentEmbed via an ancestor position (not a direct selection)", () => {
+ // Make the contentEmbed allow text inside so the selection can be placed within it
// (a collapsed position) rather than selecting the element itself.
- editor.model.schema.extend("$text", { allowIn: "includeNote" });
+ editor.model.schema.extend("$text", { allowIn: "contentEmbed" });
- const element = insertIncludeNote(editor, "noteAnc", "expandable");
+ const element = insertContentEmbed(editor, "noteAnc", "expandable");
editor.model.change((writer) => {
writer.setSelection(writer.createPositionAt(element, 0));
});
@@ -265,8 +265,8 @@ describe("IncludeNote", () => {
const before = editor.getData();
// The decorated Command.execute short-circuits while the command is disabled, so to
- // run our execute() body with no includeNote selected we force it enabled first. This
- // exercises the falsy `if (includeNoteElement)` branch.
+ // run our execute() body with no contentEmbed selected we force it enabled first. This
+ // exercises the falsy `if (embedElement)` branch.
const command = editor.commands.get(BOX_SIZE_COMMAND_NAME) as {
isEnabled: boolean;
execute(options: { value: string }): void;
@@ -278,11 +278,11 @@ describe("IncludeNote", () => {
});
// -----------------------------------------------------------------------
- // preventCKEditorHandling / selectIncludeNoteWidget (DOM event handlers)
+ // preventCKEditorHandling / selectContentEmbedWidget (DOM event handlers)
// -----------------------------------------------------------------------
it("selects the widget and suppresses editor handling on a mousedown inside the wrapper", () => {
- insertIncludeNote(editor, "noteEvt", "small");
+ insertContentEmbed(editor, "noteEvt", "small");
const domRoot = editor.editing.view.getDomRoot();
const wrapper = domRoot?.querySelector("div.include-note-wrapper");
@@ -298,11 +298,11 @@ describe("IncludeNote", () => {
// The widget should now be selected (the mousedown handler selects it).
const selected = editor.model.document.selection.getSelectedElement();
- expect(selected?.name).toBe("includeNote");
+ expect(selected?.name).toBe("contentEmbed");
});
it("suppresses the native caret on a non-interactive mousedown but not on interactive targets", () => {
- insertIncludeNote(editor, "noteCaret", "small");
+ insertContentEmbed(editor, "noteCaret", "small");
const domRoot = editor.editing.view.getDomRoot();
const wrapper = domRoot?.querySelector("div.include-note-wrapper");
@@ -333,11 +333,11 @@ describe("IncludeNote", () => {
});
it("selects the widget on a press on a title row button, and keeps the focus in the editor", () => {
- const include = insertIncludeNote(editor, "noteButton", "small");
+ const embed = insertContentEmbed(editor, "noteButton", "small");
editor.model.change((writer) => {
- const paragraph = include.nextSibling;
+ const paragraph = embed.nextSibling;
if (!paragraph) {
- throw new Error("Expected a paragraph after the include.");
+ throw new Error("Expected a paragraph after the embed.");
}
writer.setSelection(paragraph, 0);
});
@@ -362,7 +362,7 @@ describe("IncludeNote", () => {
const stop = vi.spyOn(evt, "stopPropagation");
titleRowButton.querySelector("span")?.dispatchEvent(evt);
- expect(editor.model.document.selection.getSelectedElement()).toBe(include);
+ expect(editor.model.document.selection.getSelectedElement()).toBe(embed);
expect(document.activeElement).toBe(domRoot);
// No focus for the button itself; its click still runs.
expect(evt.defaultPrevented).toBe(true);
@@ -370,7 +370,7 @@ describe("IncludeNote", () => {
});
it("leaves a mousedown inside an embedded collection untouched so the live widget keeps working", () => {
- insertIncludeNote(editor, "noteColl", "full");
+ insertContentEmbed(editor, "noteColl", "full");
const domRoot = editor.editing.view.getDomRoot();
const wrapper = domRoot?.querySelector("div.include-note-wrapper");
@@ -397,7 +397,7 @@ describe("IncludeNote", () => {
});
it("treats a mousedown whose target is not an Element (e.g. a text node) as non-interactive", () => {
- insertIncludeNote(editor, "noteText", "small");
+ insertContentEmbed(editor, "noteText", "small");
const domRoot = editor.editing.view.getDomRoot();
const wrapper = domRoot?.querySelector("div.include-note-wrapper");
@@ -422,7 +422,7 @@ describe("IncludeNote", () => {
});
it("stops propagation on focus and keydown inside the wrapper", () => {
- insertIncludeNote(editor, "noteKbd", "small");
+ insertContentEmbed(editor, "noteKbd", "small");
const domRoot = editor.editing.view.getDomRoot();
const wrapper = domRoot?.querySelector("div.include-note-wrapper");
@@ -442,8 +442,8 @@ describe("IncludeNote", () => {
expect(keyStop).toHaveBeenCalled();
});
- it("does nothing on a mousedown when the wrapper has no enclosing include", () => {
- insertIncludeNote(editor, "noteDetached", "small");
+ it("does nothing on a mousedown when the wrapper has no enclosing embed", () => {
+ insertContentEmbed(editor, "noteDetached", "small");
const domRoot = editor.editing.view.getDomRoot();
const wrapper = domRoot?.querySelector("div.include-note-wrapper");
@@ -453,7 +453,7 @@ describe("IncludeNote", () => {
}
// Detach the wrapper (which carries the capture-phase mousedown handler) from its
- // include so that domElement.closest(".include-note") returns null. The handler
+ // embed so that domElement.closest(".include-note") returns null. The handler
// still fires because it is bound to the wrapper element itself.
const holder = document.createElement("div");
document.body.appendChild(holder);
@@ -466,8 +466,8 @@ describe("IncludeNote", () => {
expect(true).toBe(true);
});
- it("does nothing on a mousedown when the include is not mapped to a view element", () => {
- insertIncludeNote(editor, "noteUnmapped", "small");
+ it("does nothing on a mousedown when the embed is not mapped to a view element", () => {
+ insertContentEmbed(editor, "noteUnmapped", "small");
const domRoot = editor.editing.view.getDomRoot();
const wrapper = domRoot?.querySelector("div.include-note-wrapper");
@@ -477,8 +477,8 @@ describe("IncludeNote", () => {
}
// Move the wrapper into a hand-built figure.include-note that the editor's
- // DomConverter knows nothing about. closest() then finds this fake include, but
- // mapDomToView() returns nothing for it, so selectIncludeNoteWidget returns early.
+ // DomConverter knows nothing about. closest() then finds this fake embed, but
+ // mapDomToView() returns nothing for it, so selectContentEmbedWidget returns early.
const fakeFigure = document.createElement("figure");
fakeFigure.className = "include-note";
document.body.appendChild(fakeFigure);
@@ -490,8 +490,8 @@ describe("IncludeNote", () => {
expect(true).toBe(true);
});
- it("does nothing on a mousedown when the include's view maps to no model element", () => {
- insertIncludeNote(editor, "noteNoModel", "small");
+ it("does nothing on a mousedown when the embed's view maps to no model element", () => {
+ insertContentEmbed(editor, "noteNoModel", "small");
const domRoot = editor.editing.view.getDomRoot();
const wrapper = domRoot?.querySelector("div.include-note-wrapper");
@@ -503,7 +503,7 @@ describe("IncludeNote", () => {
}
// The DOM->view mapping stays intact (mapDomToView succeeds), but we break the
- // view->model mapping so selectIncludeNoteWidget returns at the !modelElement guard.
+ // view->model mapping so selectContentEmbedWidget returns at the !modelElement guard.
const viewElement = editor.editing.view.domConverter.mapDomToView(figure);
expect(viewElement).toBeDefined();
if (viewElement && viewElement.is("element")) {
@@ -515,7 +515,7 @@ describe("IncludeNote", () => {
}).not.toThrow();
});
- it("selects the include that a DOM element is part of, for a context menu opened on it", () => {
+ it("selects the embed that a DOM element is part of, for a context menu opened on it", () => {
editor.setData("<p>foo</p>"
+ "<figure class=\"include-note\" data-note-id=\"noteMenu\" data-box-size=\"small\">"
+ "</figure>");
@@ -523,22 +523,22 @@ describe("IncludeNote", () => {
const wrapper = domRoot?.querySelector("div.include-note-wrapper");
const paragraph = domRoot?.querySelector("p");
if (!wrapper || !paragraph) {
- throw new Error("Expected a rendered include and paragraph.");
+ throw new Error("Expected a rendered embed and paragraph.");
}
const title = document.createElement("h4");
wrapper.append(title);
- const plugin = editor.plugins.get("IncludeNote");
+ const plugin = editor.plugins.get("ContentEmbed");
- expect(plugin.selectIncludeAt(paragraph)).toBe(false);
+ expect(plugin.selectEmbedAt(paragraph)).toBe(false);
expect(editor.model.document.selection.getSelectedElement()).toBeNull();
- expect(plugin.selectIncludeAt(title)).toBe(true);
+ expect(plugin.selectEmbedAt(title)).toBe(true);
expect(editor.model.document.selection.getSelectedElement()?.getAttribute("noteId"))
.toBe("noteMenu");
});
it("falls back gracefully in the button factory when the insert command is absent", () => {
- // Exercise the falsy `if (command)` branch in IncludeNoteUI: when the command lookup
+ // Exercise the falsy `if (command)` branch in ContentEmbedUI: when the command lookup
// returns undefined, the button must still be created (just without the binding).
const realGet = editor.commands.get.bind(editor.commands);
const absent: string[] = [
@@ -549,7 +549,7 @@ describe("IncludeNote", () => {
.mockImplementation((name) => (absent.includes(name) ? undefined : realGet(name)));
try {
- const view = editor.ui.componentFactory.create("includeNote") as unknown as { label: string };
+ const view = editor.ui.componentFactory.create("contentEmbed") as unknown as { label: string };
expect(view.label).toBe("Include note");
const convert = editor.ui.componentFactory.create(CONVERT_EMBED_TO_LINK_COMMAND);
expect((convert as unknown as { label: string }).label).toBe("Convert to link");
@@ -561,24 +561,24 @@ describe("IncludeNote", () => {
});
});
-describe("IncludeNote with attachments", () => {
+describe("ContentEmbed with attachments", () => {
const LINK_HREF = "#root/owner?viewMode=attachments&attachmentId=att1";
const embedHtml = (attachmentId = "att1") =>
`<figure class="include-note" data-attachment-id="${attachmentId}" data-box-size="small">`
+ "</figure>";
let editor: ClassicEditor;
- let loadIncludedNote: ReturnType<typeof vi.fn>;
- let loadIncludedAttachment: ReturnType<typeof vi.fn>;
+ let loadEmbeddedNote: ReturnType<typeof vi.fn>;
+ let loadEmbeddedAttachment: ReturnType<typeof vi.fn>;
let getAttachmentHref: ReturnType<typeof vi.fn>;
beforeEach(async () => {
- loadIncludedNote = vi.fn();
- loadIncludedAttachment = vi.fn();
+ loadEmbeddedNote = vi.fn();
+ loadEmbeddedAttachment = vi.fn();
getAttachmentHref = vi.fn(async () => LINK_HREF);
installGlobMock({
getComponentByEl: () => ({
- loadIncludedNote,
- loadIncludedAttachment,
+ loadEmbeddedNote,
+ loadEmbeddedAttachment,
getAttachmentHref,
loadReferenceLinkTitle: vi.fn(async () => undefined)
}),
@@ -586,7 +586,7 @@ describe("IncludeNote with attachments", () => {
});
editor = await createTestEditor([
- Essentials, Paragraph, Undo, Widget, LinkEditing, ReferenceLink, IncludeNote
+ Essentials, Paragraph, Undo, Widget, LinkEditing, ReferenceLink, ContentEmbed
]);
});
@@ -597,7 +597,7 @@ describe("IncludeNote with attachments", () => {
function selectEmbed() {
editor.model.change((writer) => {
- const element = findIncludeNote(editor);
+ const element = findContentEmbed(editor);
if (element) {
writer.setSelection(element, "on");
}
@@ -607,41 +607,41 @@ describe("IncludeNote with attachments", () => {
it("stores, saves and renders an embed by its attachment", () => {
editor.setData(embedHtml());
- const element = findIncludeNote(editor);
+ const element = findContentEmbed(editor);
expect(element?.getAttribute("attachmentId")).toBe("att1");
expect(element?.hasAttribute("noteId")).toBe(false);
expect(editor.getData()).toContain('data-attachment-id="att1"');
expect(editor.getData()).not.toContain("data-note-id");
expect(renderEmbeds()).toHaveLength(1);
- expect(loadIncludedNote).not.toHaveBeenCalled();
- expect(loadIncludedAttachment).toHaveBeenCalledTimes(1);
- expect(loadIncludedAttachment.mock.calls[0]?.[0]).toBe("att1");
- expect(loadIncludedAttachment.mock.calls[0]?.[2]).toBe("small");
+ expect(loadEmbeddedNote).not.toHaveBeenCalled();
+ expect(loadEmbeddedAttachment).toHaveBeenCalledTimes(1);
+ expect(loadEmbeddedAttachment.mock.calls[0]?.[0]).toBe("att1");
+ expect(loadEmbeddedAttachment.mock.calls[0]?.[2]).toBe("small");
selectEmbed();
editor.execute(BOX_SIZE_COMMAND_NAME, { value: "full" });
- expect(loadIncludedAttachment.mock.calls.at(-1)?.[2]).toBe("full");
+ expect(loadEmbeddedAttachment.mock.calls.at(-1)?.[2]).toBe("full");
});
it("shows an embed by its file name while it uploads, and saves it naming nothing", () => {
setModelData(
editor.model,
- "<includeNote boxSize=\"small\" uploadFileName=\"report.pdf\" uploadId=\"u1\">"
- + "</includeNote>"
+ "<contentEmbed boxSize=\"small\" uploadFileName=\"report.pdf\" uploadId=\"u1\">"
+ + "</contentEmbed>"
);
const wrapper = renderEmbeds()?.[0];
const title = wrapper?.querySelector(".include-note-title");
expect(title?.textContent).toBe("report.pdf");
expect(title?.querySelector(".bx.bx-loader-alt.bx-spin")).not.toBeNull();
- expect(loadIncludedAttachment).not.toHaveBeenCalled();
- expect(loadIncludedNote).not.toHaveBeenCalled();
+ expect(loadEmbeddedAttachment).not.toHaveBeenCalled();
+ expect(loadEmbeddedNote).not.toHaveBeenCalled();
const data = editor.getData();
expect(data).toContain("<figure class=\"include-note\" data-box-size=\"small\">");
expect(data).not.toMatch(/data-(note|attachment)-id/);
- const element = findIncludeNote(editor);
+ const element = findContentEmbed(editor);
if (!element) {
throw new Error("Expected the embed.");
}
@@ -649,14 +649,14 @@ describe("IncludeNote with attachments", () => {
// The two steps of `FileUploadEditing` once the upload ends.
editor.model.change((writer) => writer.setAttribute("attachmentId", "att1", element));
expect(wrapper?.querySelector(".include-note-title")?.textContent).toBe("report.pdf");
- expect(loadIncludedAttachment).not.toHaveBeenCalled();
+ expect(loadEmbeddedAttachment).not.toHaveBeenCalled();
editor.model.change((writer) => writer.removeAttribute("uploadFileName", element));
expect(renderEmbeds()?.[0]).toBe(wrapper);
expect(wrapper?.querySelector(".include-note-title")).toBeNull();
expect(wrapper?.parentElement?.getAttribute("data-attachment-id")).toBe("att1");
- expect(loadIncludedAttachment).toHaveBeenCalledTimes(1);
- expect(loadIncludedAttachment).toHaveBeenCalledWith("att1", expect.anything(), "small");
+ expect(loadEmbeddedAttachment).toHaveBeenCalledTimes(1);
+ expect(loadEmbeddedAttachment).toHaveBeenCalledWith("att1", expect.anything(), "small");
});
it("turns an attachment link into an embed in its place, as one undo step", () => {
@@ -667,7 +667,7 @@ describe("IncludeNote with attachments", () => {
expect(getModelData(editor.model, { withoutSelection: true })).toBe(
"<paragraph>Before </paragraph>" +
- "<includeNote attachmentId=\"att1\" boxSize=\"expandable\"></includeNote>" +
+ "<contentEmbed attachmentId=\"att1\" boxSize=\"expandable\"></contentEmbed>" +
"<paragraph> after</paragraph>"
);
@@ -678,7 +678,7 @@ describe("IncludeNote with attachments", () => {
const relinked = editor.editing.view.getDomRoot()?.querySelector("a.reference-link");
editor.execute(EMBED_ATTACHMENT_LINK_COMMAND, { domElement: relinked });
- expect(findIncludeNote(editor)?.getAttribute("boxSize")).toBe("medium");
+ expect(findContentEmbed(editor)?.getAttribute("boxSize")).toBe("medium");
});
it("leaves a link to a note, and anything other than a link, alone", () => {
@@ -696,15 +696,15 @@ describe("IncludeNote with attachments", () => {
expect(getModelData(editor.model, { withoutSelection: true })).toBe(before);
});
- it("loads an include that names nothing, as one saved mid-upload, as an empty box", () => {
+ it("loads an embed that names nothing, as one saved mid-upload, as an empty box", () => {
editor.setData("<figure class=\"include-note\" data-box-size=\"small\"></figure>");
expect(renderEmbeds()).toHaveLength(1);
- expect(loadIncludedNote).not.toHaveBeenCalled();
- expect(loadIncludedAttachment).not.toHaveBeenCalled();
+ expect(loadEmbeddedNote).not.toHaveBeenCalled();
+ expect(loadEmbeddedAttachment).not.toHaveBeenCalled();
});
- it("turns an embed or an included note into a link, and nothing else", async () => {
+ it("turns an embed of an attachment or a note into a link, and nothing else", async () => {
const command = editor.commands.get(CONVERT_EMBED_TO_LINK_COMMAND);
const button = editor.ui.componentFactory.create(CONVERT_EMBED_TO_LINK_COMMAND);
if (!(button instanceof ButtonView)) {
@@ -739,7 +739,7 @@ describe("IncludeNote with attachments", () => {
expect(getAttachmentHref).toHaveBeenCalledOnce();
});
- it("describes the include an element is part of, without selecting it", () => {
+ it("describes the embed an element is part of, without selecting it", () => {
editor.setData(embedHtml()
+ "<figure class=\"include-note\" data-note-id=\"noteX\" data-box-size=\"medium\""
+ " data-hide-title=\"true\"><figcaption>Caption</figcaption></figure>"
@@ -754,9 +754,9 @@ describe("IncludeNote with attachments", () => {
}
});
const [ embed, note, tiny ] = renderEmbeds() ?? [];
- const plugin = editor.plugins.get("IncludeNote");
+ const plugin = editor.plugins.get("ContentEmbed");
- const states = [ embed, note, tiny ].map((wrapper) => plugin.getIncludeStateAt(wrapper));
+ const states = [ embed, note, tiny ].map((wrapper) => plugin.getEmbedStateAt(wrapper));
expect(states).toEqual([ {
boxSize: "small", isTitleShown: true, isTitleToggleable: true,
hasCaption: false, isCaptionToggleable: true, isConvertibleToLink: true
@@ -768,7 +768,7 @@ describe("IncludeNote with attachments", () => {
hasCaption: false, isCaptionToggleable: false, isConvertibleToLink: true
} ]);
const paragraph = editor.editing.view.getDomRoot()?.querySelector("p") ?? embed;
- expect(plugin.getIncludeStateAt(paragraph)).toBeNull();
+ expect(plugin.getEmbedStateAt(paragraph)).toBeNull();
const position = editor.model.document.selection.getFirstPosition();
expect(position?.parent.is("element", "paragraph")).toBe(true);
@@ -781,7 +781,7 @@ describe("IncludeNote with attachments", () => {
]);
});
- it("converts the embed that selectIncludeAt() selects from its title row", async () => {
+ it("converts the embed that selectEmbedAt() selects from its title row", async () => {
editor.setData("<p>before</p>" + embedHtml());
const command = editor.commands.get(CONVERT_EMBED_TO_LINK_COMMAND);
const wrapper = renderEmbeds()?.[0];
@@ -793,7 +793,7 @@ describe("IncludeNote with attachments", () => {
wrapper.append(titleRow);
expect(command?.isEnabled).toBe(false);
- expect(editor.plugins.get("IncludeNote").selectIncludeAt(titleRow)).toBe(true);
+ expect(editor.plugins.get("ContentEmbed").selectEmbedAt(titleRow)).toBe(true);
expect(command?.isEnabled).toBe(true);
await editor.execute(CONVERT_EMBED_TO_LINK_COMMAND);
@@ -803,7 +803,7 @@ describe("IncludeNote with attachments", () => {
);
});
- it("converts nothing when no include is selected", async () => {
+ it("converts nothing when no embed is selected", async () => {
editor.setData(embedHtml() + "<p>after</p>");
setModelData(editor.model, "<paragraph>foo[]bar</paragraph>");
const before = editor.getData();
@@ -828,13 +828,13 @@ describe("IncludeNote with attachments", () => {
await editor.execute(CONVERT_EMBED_TO_LINK_COMMAND);
- expect(findIncludeNote(editor)?.getAttribute("attachmentId")).toBe("att1");
+ expect(findContentEmbed(editor)?.getAttribute("attachmentId")).toBe("att1");
});
it("redraws the embeds of a changed attachment and removes those of a deleted one", () => {
editor.setData(embedHtml("att1") + embedHtml("att2"));
renderEmbeds();
- loadIncludedAttachment.mockClear();
+ loadEmbeddedAttachment.mockClear();
editor.plugins.get("ReferenceLinkEditing").updateAttachmentLinks([
{ attachmentId: "att1", isDeleted: false },
@@ -842,27 +842,29 @@ describe("IncludeNote with attachments", () => {
]);
renderEmbeds();
- const redrawn = loadIncludedAttachment.mock.calls.map(([ attachmentId ]) => attachmentId);
+ const redrawn = loadEmbeddedAttachment.mock.calls.map(([ attachmentId ]) => attachmentId);
expect(redrawn).toContain("att1");
expect(redrawn).not.toContain("att2");
expect(getModelData(editor.model, { withoutSelection: true }))
- .toBe("<includeNote attachmentId=\"att1\" boxSize=\"small\"></includeNote>");
+ .toBe("<contentEmbed attachmentId=\"att1\" boxSize=\"small\"></contentEmbed>");
});
});
-describe("IncludeNote captions", () => {
+describe("ContentEmbed captions", () => {
const CAPTIONED = "<figure class=\"include-note\" data-note-id=\"n1\" data-box-size=\"medium\">"
+ "<figcaption>A <strong>bold</strong> caption</figcaption></figure>";
let editor: ClassicEditor;
- let loadIncludedNote: ReturnType<typeof vi.fn>;
+ let loadEmbeddedNote: ReturnType<typeof vi.fn>;
beforeEach(async () => {
- loadIncludedNote = vi.fn();
+ loadEmbeddedNote = vi.fn();
installGlobMock({
- getComponentByEl: () => ({ loadIncludedNote })
+ getComponentByEl: () => ({ loadEmbeddedNote })
});
- editor = await createTestEditor([ Essentials, Paragraph, Bold, Undo, Widget, IncludeNote ]);
+ editor = await createTestEditor([
+ Essentials, Paragraph, Bold, Undo, Widget, ContentEmbed
+ ]);
});
function getCommand() {
@@ -873,11 +875,11 @@ describe("IncludeNote captions", () => {
return command;
}
- function selectInclude() {
+ function selectEmbed() {
editor.model.change((writer) => {
- const include = findIncludeNote(editor);
- if (include) {
- writer.setSelection(include, "on");
+ const embed = findContentEmbed(editor);
+ if (embed) {
+ writer.setSelection(embed, "on");
}
});
}
@@ -900,15 +902,15 @@ describe("IncludeNote captions", () => {
editor.setData(CAPTIONED);
expect(getModelData(editor.model, { withoutSelection: true })).toBe(
- "<includeNote boxSize=\"medium\" noteId=\"n1\">"
- + "<caption>A <$text bold=\"true\">bold</$text> caption</caption></includeNote>"
+ "<contentEmbed boxSize=\"medium\" noteId=\"n1\">"
+ + "<caption>A <$text bold=\"true\">bold</$text> caption</caption></contentEmbed>"
);
expect(editor.getData()).toBe(CAPTIONED);
expect(getRenderedCaption()?.getAttribute("contenteditable")).toBe("true");
});
it("toggles a caption on after the content and off again, keeping its text", () => {
- insertIncludeNote(editor, "n1", "medium");
+ insertContentEmbed(editor, "n1", "medium");
const command = getCommand();
expect(command.isEnabled).toBe(true);
expect(command.value).toBe(false);
@@ -927,7 +929,7 @@ describe("IncludeNote captions", () => {
editor.execute(TOGGLE_CAPTION_COMMAND_NAME);
expect(command.value).toBe(false);
expect(editor.getData()).not.toContain("figcaption");
- expect(editor.model.document.selection.getSelectedElement()?.name).toBe("includeNote");
+ expect(editor.model.document.selection.getSelectedElement()?.name).toBe("contentEmbed");
editor.execute(TOGGLE_CAPTION_COMMAND_NAME);
expect(editor.getData()).toContain("<figcaption>Caption</figcaption>");
@@ -935,10 +937,10 @@ describe("IncludeNote captions", () => {
});
it("keeps the rendered content while the caption is toggled and edited", () => {
- insertIncludeNote(editor, "n1", "medium");
+ insertContentEmbed(editor, "n1", "medium");
const wrapper = editor.editing.view.getDomRoot()?.querySelector(".include-note-wrapper");
expect(wrapper).not.toBeNull();
- expect(loadIncludedNote).toHaveBeenCalledTimes(1);
+ expect(loadEmbeddedNote).toHaveBeenCalledTimes(1);
editor.execute(TOGGLE_CAPTION_COMMAND_NAME, { focusCaptionOnShow: true });
editor.model.change((writer) => {
@@ -953,14 +955,14 @@ describe("IncludeNote captions", () => {
expect(getRenderedCaption()?.textContent).toBe("Caption");
expect(editor.editing.view.getDomRoot()?.querySelector(".include-note-wrapper"))
.toBe(wrapper);
- expect(loadIncludedNote).toHaveBeenCalledTimes(1);
+ expect(loadEmbeddedNote).toHaveBeenCalledTimes(1);
});
- it("is disabled with no include selected and on a Tiny include", () => {
+ it("is disabled with no embed selected and on a Tiny embed", () => {
setModelData(editor.model, "<paragraph>foo[]</paragraph>");
expect(getCommand().isEnabled).toBe(false);
- insertIncludeNote(editor, "n1", "tiny");
+ insertContentEmbed(editor, "n1", "tiny");
expect(getCommand().isEnabled).toBe(false);
expect(getCommand().value).toBe(false);
});
@@ -970,7 +972,7 @@ describe("IncludeNote captions", () => {
if (!(button instanceof ButtonView)) {
throw new Error("Expected a button.");
}
- insertIncludeNote(editor, "n1", "medium");
+ insertContentEmbed(editor, "n1", "medium");
expect(button.label).toBe("Toggle caption on");
expect(button.isOn).toBe(false);
@@ -981,13 +983,13 @@ describe("IncludeNote captions", () => {
expect(isSelectionInCaption()).toBe(true);
});
- it("removes the caption of a Tiny include and restores it on a larger size, undoably", () => {
+ it("removes the caption of a Tiny embed and restores it on a larger size, undoably", () => {
editor.setData(CAPTIONED);
- selectInclude();
+ selectEmbed();
editor.execute(BOX_SIZE_COMMAND_NAME, { value: "tiny" });
expect(getModelData(editor.model, { withoutSelection: true }))
- .toBe("<includeNote boxSize=\"tiny\" noteId=\"n1\"></includeNote>");
+ .toBe("<contentEmbed boxSize=\"tiny\" noteId=\"n1\"></contentEmbed>");
editor.execute(BOX_SIZE_COMMAND_NAME, { value: "small" });
expect(editor.getData()).toBe(CAPTIONED.replace("medium", "small"));
@@ -998,9 +1000,9 @@ describe("IncludeNote captions", () => {
expect(editor.getData()).toBe(CAPTIONED);
});
- it("leaves a caption hidden with the toggle hidden when the include leaves Tiny", () => {
+ it("leaves a caption hidden with the toggle hidden when the embed leaves Tiny", () => {
editor.setData(CAPTIONED);
- selectInclude();
+ selectEmbed();
editor.execute(TOGGLE_CAPTION_COMMAND_NAME);
editor.execute(BOX_SIZE_COMMAND_NAME, { value: "tiny" });
@@ -1009,29 +1011,29 @@ describe("IncludeNote captions", () => {
expect(editor.getData()).not.toContain("figcaption");
});
- it("drops the caption of a Tiny include it loads", () => {
+ it("drops the caption of a Tiny embed it loads", () => {
editor.setData(CAPTIONED.replace("medium", "tiny"));
expect(getModelData(editor.model, { withoutSelection: true }))
- .toBe("<includeNote boxSize=\"tiny\" noteId=\"n1\"></includeNote>");
+ .toBe("<contentEmbed boxSize=\"tiny\" noteId=\"n1\"></contentEmbed>");
});
});
-describe("IncludeNote title", () => {
+describe("ContentEmbed title", () => {
const UNTITLED = "<figure class=\"include-note\" data-note-id=\"n1\" data-box-size=\"medium\""
+ " data-hide-title=\"true\">&nbsp;</figure>";
let editor: ClassicEditor;
- let loadIncludedNote: ReturnType<typeof vi.fn>;
- let openIncludeNoteMenu: ReturnType<typeof vi.fn>;
+ let loadEmbeddedNote: ReturnType<typeof vi.fn>;
+ let openContentEmbedMenu: ReturnType<typeof vi.fn>;
beforeEach(async () => {
- loadIncludedNote = vi.fn();
- openIncludeNoteMenu = vi.fn();
+ loadEmbeddedNote = vi.fn();
+ openContentEmbedMenu = vi.fn();
installGlobMock({
- getComponentByEl: () => ({ loadIncludedNote, openIncludeNoteMenu })
+ getComponentByEl: () => ({ loadEmbeddedNote, openContentEmbedMenu })
});
- editor = await createTestEditor([ Essentials, Paragraph, Undo, Widget, IncludeNote ]);
+ editor = await createTestEditor([ Essentials, Paragraph, Undo, Widget, ContentEmbed ]);
});
function getCommand() {
@@ -1042,22 +1044,22 @@ describe("IncludeNote title", () => {
return command;
}
- function getRenderedInclude() {
- const include = editor.editing.view.getDomRoot()?.querySelector("figure.include-note");
- if (!include) {
- throw new Error("Expected a rendered include.");
+ function getRenderedEmbed() {
+ const embed = editor.editing.view.getDomRoot()?.querySelector("figure.include-note");
+ if (!embed) {
+ throw new Error("Expected a rendered embed.");
}
- return include;
+ return embed;
}
- it("loads and saves a hidden title, and marks the include it renders", () => {
+ it("loads and saves a hidden title, and marks the embed it renders", () => {
editor.setData(UNTITLED);
expect(getModelData(editor.model, { withoutSelection: true })).toBe(
- "<includeNote boxSize=\"medium\" hideTitle=\"true\" noteId=\"n1\"></includeNote>"
+ "<contentEmbed boxSize=\"medium\" hideTitle=\"true\" noteId=\"n1\"></contentEmbed>"
);
expect(editor.getData()).toBe(UNTITLED);
- expect(getRenderedInclude().getAttribute("data-hide-title")).toBe("true");
+ expect(getRenderedEmbed().getAttribute("data-hide-title")).toBe("true");
editor.setData(UNTITLED.replace(" data-hide-title=\"true\"", ""));
expect(getModelData(editor.model, { withoutSelection: true })).not.toContain("hideTitle");
@@ -1065,48 +1067,48 @@ describe("IncludeNote title", () => {
});
it("hides the title and shows it again, keeping the rendered content", () => {
- insertIncludeNote(editor, "n1", "medium");
- const wrapper = getRenderedInclude().querySelector(".include-note-wrapper");
+ insertContentEmbed(editor, "n1", "medium");
+ const wrapper = getRenderedEmbed().querySelector(".include-note-wrapper");
const command = getCommand();
expect(command.isEnabled).toBe(true);
expect(command.value).toBe(true);
editor.execute(TOGGLE_TITLE_COMMAND_NAME);
expect(command.value).toBe(false);
- expect(getRenderedInclude().getAttribute("data-hide-title")).toBe("true");
+ expect(getRenderedEmbed().getAttribute("data-hide-title")).toBe("true");
expect(editor.getData()).toContain("data-hide-title=\"true\"");
- expect(editor.model.document.selection.getSelectedElement()?.name).toBe("includeNote");
+ expect(editor.model.document.selection.getSelectedElement()?.name).toBe("contentEmbed");
editor.execute(TOGGLE_TITLE_COMMAND_NAME);
expect(command.value).toBe(true);
- expect(getRenderedInclude().hasAttribute("data-hide-title")).toBe(false);
+ expect(getRenderedEmbed().hasAttribute("data-hide-title")).toBe(false);
expect(editor.getData()).not.toContain("data-hide-title");
- expect(getRenderedInclude().querySelector(".include-note-wrapper")).toBe(wrapper);
- expect(loadIncludedNote).toHaveBeenCalledTimes(1);
+ expect(getRenderedEmbed().querySelector(".include-note-wrapper")).toBe(wrapper);
+ expect(loadEmbeddedNote).toHaveBeenCalledTimes(1);
});
- it("is disabled with no include selected, and on a Tiny or Expandable include", () => {
+ it("is disabled with no embed selected, and on a Tiny or Expandable embed", () => {
setModelData(editor.model, "<paragraph>foo[]</paragraph>");
expect(getCommand().isEnabled).toBe(false);
for (const [ boxSize, isEnabled ] of [
[ "tiny", false ], [ "expandable", false ], [ "small", true ], [ "full", true ]
] as const) {
- insertIncludeNote(editor, "n1", boxSize);
+ insertContentEmbed(editor, "n1", boxSize);
expect(getCommand().isEnabled, boxSize).toBe(isEnabled);
}
});
it("offers a Show title button, and a menu button while the title is hidden", () => {
const toggle = editor.ui.componentFactory.create(TOGGLE_TITLE_COMMAND_NAME);
- const menu = editor.ui.componentFactory.create(INCLUDE_NOTE_MENU);
+ const menu = editor.ui.componentFactory.create(CONTENT_EMBED_MENU);
if (!(toggle instanceof ButtonView) || toggle instanceof SwitchButtonView
|| !(menu instanceof ButtonView)) {
throw new Error("Expected two buttons.");
}
menu.render();
- insertIncludeNote(editor, "n1", "medium");
+ insertContentEmbed(editor, "n1", "medium");
expect([ toggle.icon, toggle.withText, toggle.tooltip, toggle.isToggleable ])
.toEqual([ bxWindowAlt, false, true, true ]);
expect([ toggle.label, toggle.isOn, toggle.isVisible ]).toEqual([ "Show title", true, true ]);
@@ -1117,40 +1119,40 @@ describe("IncludeNote title", () => {
expect(menu.isVisible).toBe(true);
menu.fire("execute");
- expect(openIncludeNoteMenu).toHaveBeenCalledWith(getRenderedInclude(), menu.element);
+ expect(openContentEmbedMenu).toHaveBeenCalledWith(getRenderedEmbed(), menu.element);
editor.execute(BOX_SIZE_COMMAND_NAME, { value: "tiny" });
expect([ toggle.isVisible, menu.isVisible ]).toEqual([ false, false ]);
});
});
-function findIncludeNote(editor: ClassicEditor): ModelElement | undefined {
+function findContentEmbed(editor: ClassicEditor): ModelElement | undefined {
const root = editor.model.document.getRoot();
if (!root) {
return undefined;
}
for (const item of editor.model.createRangeIn(root).getItems()) {
- if (item.is("element", "includeNote")) {
+ if (item.is("element", "contentEmbed")) {
return item;
}
}
return undefined;
}
-function insertIncludeNote(editor: ClassicEditor, noteId: string, boxSize: string): ModelElement {
+function insertContentEmbed(editor: ClassicEditor, noteId: string, boxSize: string): ModelElement {
let created: ModelElement | null = null;
editor.model.change((writer) => {
const root = editor.model.document.getRoot();
if (!root) {
throw new Error("The editor has no root.");
}
- const element = writer.createElement("includeNote", { noteId, boxSize });
+ const element = writer.createElement("contentEmbed", { noteId, boxSize });
writer.insert(element, root, 0);
writer.setSelection(element, "on");
created = element;
});
if (!created) {
- throw new Error("Failed to create includeNote element.");
+ throw new Error("Failed to create contentEmbed element.");
}
return created;
}
diff --git a/packages/ckeditor5/src/plugins/includenote.ts b/packages/ckeditor5/src/plugins/content_embed/content_embed.ts
similarity index 67%
rename from packages/ckeditor5/src/plugins/includenote.ts
rename to packages/ckeditor5/src/plugins/content_embed/content_embed.ts
index 7b2d9deb5f..3004775186 100644
--- a/packages/ckeditor5/src/plugins/includenote.ts
+++ b/packages/ckeditor5/src/plugins/content_embed/content_embed.ts
@@ -22,26 +22,26 @@ import {
type Observable
} from 'ckeditor5';
import windowIcon from 'boxicons/svg/regular/bx-window-alt.svg?raw';
-import noteIcon from '../icons/note.svg?raw';
-import { getAttachmentId } from './referencelink.js';
+import noteIcon from '../../icons/note.svg?raw';
+import { getAttachmentId } from '../referencelink.js';
-export const COMMAND_NAME = 'insertIncludeNote';
-export const BOX_SIZE_COMMAND_NAME = 'includeNoteBoxSize';
+export const COMMAND_NAME = 'insertContentEmbed';
+export const BOX_SIZE_COMMAND_NAME = 'contentEmbedBoxSize';
export const EMBED_ATTACHMENT_LINK_COMMAND = 'embedAttachmentLink';
export const CONVERT_EMBED_TO_LINK_COMMAND = 'convertEmbedToLink';
-export const TOGGLE_CAPTION_COMMAND_NAME = 'toggleIncludeNoteCaption';
-export const TOGGLE_TITLE_COMMAND_NAME = 'toggleIncludeNoteTitle';
-/** The toolbar button that opens the context menu of an include whose title is hidden. */
-export const INCLUDE_NOTE_MENU = 'includeNoteMenu';
+export const TOGGLE_CAPTION_COMMAND_NAME = 'toggleContentEmbedCaption';
+export const TOGGLE_TITLE_COMMAND_NAME = 'toggleContentEmbedTitle';
+/** The toolbar button that opens the context menu of an embed whose title is hidden. */
+export const CONTENT_EMBED_MENU = 'contentEmbedMenu';
export const BOX_SIZES = [ 'tiny', 'small', 'medium', 'full', 'expandable' ] as const;
export type BoxSizeValue = typeof BOX_SIZES[number];
-/** What the toolbar of an include shows of it, for a menu offering the same commands. */
-export interface IncludeNoteState {
+/** What the toolbar of an embed shows of it, for a menu offering the same commands. */
+export interface ContentEmbedState {
boxSize: BoxSizeValue | null;
- /** Whether the title shows, which a Tiny or an Expandable include always does. */
+ /** Whether the title shows, which a Tiny or an Expandable embed always does. */
isTitleShown: boolean;
isTitleToggleable: boolean;
hasCaption: boolean;
@@ -76,51 +76,51 @@ export function getBoxSizeLabel(t: (message: string) => string, size: BoxSizeVal
}
}
-export default class IncludeNote extends Plugin {
+export default class ContentEmbed extends Plugin {
static get requires() {
- return [ IncludeNoteEditing, IncludeNoteUI ];
+ return [ ContentEmbedEditing, ContentEmbedUI ];
}
static get pluginName() {
- return 'IncludeNote' as const;
+ return 'ContentEmbed' as const;
}
/**
- * Selects the include that `domElement` is part of, so that commands act on the include a
- * context menu is opened on. Returns `false` when `domElement` is not part of an include of
+ * Selects the embed that `domElement` is part of, so that commands act on the embed a
+ * context menu is opened on. Returns `false` when `domElement` is not part of an embed of
* this editor.
*/
- selectIncludeAt( domElement: Element ): boolean {
- const include = getIncludeNoteAt( this.editor, domElement );
- if ( !include ) {
+ selectEmbedAt( domElement: Element ): boolean {
+ const embed = getContentEmbedAt( this.editor, domElement );
+ if ( !embed ) {
return false;
}
this.editor.model.enqueueChange( { isUndoable: false }, writer => {
- writer.setSelection( include, 'on' );
+ writer.setSelection( embed, 'on' );
} );
return true;
}
/**
- * The state of the include that `domElement` is part of, as its toolbar shows it with the
- * include selected, or `null`. The selection is left as it is.
+ * The state of the embed that `domElement` is part of, as its toolbar shows it with the
+ * embed selected, or `null`. The selection is left as it is.
*/
- getIncludeStateAt( domElement: Element ): IncludeNoteState | null {
+ getEmbedStateAt( domElement: Element ): ContentEmbedState | null {
const editor = this.editor;
- const include = getIncludeNoteAt( editor, domElement );
- if ( !include ) {
+ const embed = getContentEmbedAt( editor, domElement );
+ if ( !embed ) {
return null;
}
- const isTitleToggleable = isIncludeTitleToggleable( include );
+ const isTitleToggleable = isEmbedTitleToggleable( embed );
return {
- boxSize: include.getAttribute( 'boxSize' ) as BoxSizeValue | undefined ?? null,
- isTitleShown: !isTitleToggleable || !include.getAttribute( 'hideTitle' ),
+ boxSize: embed.getAttribute( 'boxSize' ) as BoxSizeValue | undefined ?? null,
+ isTitleShown: !isTitleToggleable || !embed.getAttribute( 'hideTitle' ),
isTitleToggleable,
- hasCaption: !!getCaption( include ),
- isCaptionToggleable: isIncludeCaptionToggleable( editor, include ),
- isConvertibleToLink: isIncludeConvertibleToLink( editor, include )
+ hasCaption: !!getCaption( embed ),
+ isCaptionToggleable: isEmbedCaptionToggleable( editor, embed ),
+ isConvertibleToLink: isEmbedConvertibleToLink( editor, embed )
};
}
@@ -130,14 +130,14 @@ export default class IncludeNote extends Plugin {
}
}
-class IncludeNoteUI extends Plugin {
+class ContentEmbedUI extends Plugin {
init() {
const editor = this.editor;
const t = editor.t;
- // The "includeNote" button must be registered among the UI components of the editor
+ // The "contentEmbed" button must be registered among the UI components of the editor
// to be displayed in the toolbar.
- editor.ui.componentFactory.add( 'includeNote', locale => {
+ editor.ui.componentFactory.add( 'contentEmbed', locale => {
// The state of the button will be bound to the widget command.
const command = editor.commands.get( COMMAND_NAME );
@@ -173,7 +173,7 @@ class IncludeNoteUI extends Plugin {
tooltip: true
} );
- // Shown only on an include that names a note or an attachment.
+ // Shown only on an embed that names a note or an attachment.
if ( command ) {
buttonView.bind( 'isEnabled' ).to( command );
buttonView.bind( 'isVisible' ).to( command, 'isEnabled' );
@@ -235,7 +235,7 @@ class IncludeNoteUI extends Plugin {
return buttonView;
} );
- editor.ui.componentFactory.add( INCLUDE_NOTE_MENU, locale => {
+ editor.ui.componentFactory.add( CONTENT_EMBED_MENU, locale => {
const command = editor.commands.get( TOGGLE_TITLE_COMMAND_NAME );
const buttonView = new ButtonView( locale );
@@ -253,7 +253,7 @@ class IncludeNoteUI extends Plugin {
}
this.listenTo( buttonView, 'execute', () => {
- openIncludeNoteMenu( editor, buttonView.element );
+ openContentEmbedMenu( editor, buttonView.element );
} );
return buttonView;
@@ -261,20 +261,20 @@ class IncludeNoteUI extends Plugin {
}
}
-class IncludeNoteEditing extends Plugin {
+class ContentEmbedEditing extends Plugin {
static get requires() {
return [ Widget ];
}
static get pluginName() {
- return 'IncludeNoteEditing' as const;
+ return 'ContentEmbedEditing' as const;
}
- /** The captions that were hidden or that a Tiny box size removed, by include. */
+ /** The captions that were hidden or that a Tiny box size removed, by embed. */
private readonly savedCaptions = new WeakMap<ModelElement, unknown>();
- /** The includes whose saved caption a Tiny box size removed. */
- private readonly tinyIncludes = new WeakSet<ModelElement>();
+ /** The embeds whose saved caption a Tiny box size removed. */
+ private readonly tinyEmbeds = new WeakSet<ModelElement>();
init() {
this._defineSchema();
@@ -282,41 +282,41 @@ class IncludeNoteEditing extends Plugin {
const editor = this.editor;
const commands = editor.commands;
- commands.add( COMMAND_NAME, new InsertIncludeNoteCommand( editor ) );
- commands.add( BOX_SIZE_COMMAND_NAME, new IncludeNoteBoxSizeCommand( editor ) );
+ commands.add( COMMAND_NAME, new InsertContentEmbedCommand( editor ) );
+ commands.add( BOX_SIZE_COMMAND_NAME, new ContentEmbedBoxSizeCommand( editor ) );
commands.add( EMBED_ATTACHMENT_LINK_COMMAND, new EmbedAttachmentLinkCommand( editor ) );
commands.add( CONVERT_EMBED_TO_LINK_COMMAND, new ConvertEmbedToLinkCommand( editor ) );
- commands.add( TOGGLE_CAPTION_COMMAND_NAME, new ToggleIncludeNoteCaptionCommand( editor ) );
- commands.add( TOGGLE_TITLE_COMMAND_NAME, new ToggleIncludeNoteTitleCommand( editor ) );
+ commands.add( TOGGLE_CAPTION_COMMAND_NAME, new ToggleContentEmbedCaptionCommand( editor ) );
+ commands.add( TOGGLE_TITLE_COMMAND_NAME, new ToggleContentEmbedTitleCommand( editor ) );
editor.model.document.registerPostFixer( writer => this.removeTinyCaptions( writer ) );
}
- /** Keeps a copy of `caption`, for `include` to show again. */
- saveCaption( include: ModelElement, caption: ModelElement ) {
- this.savedCaptions.set( include, caption.toJSON() );
- this.tinyIncludes.delete( include );
+ /** Keeps a copy of `caption`, for `embed` to show again. */
+ saveCaption( embed: ModelElement, caption: ModelElement ) {
+ this.savedCaptions.set( embed, caption.toJSON() );
+ this.tinyEmbeds.delete( embed );
}
- /** A copy of the caption last saved for `include`, or `null`. */
- getSavedCaption( include: ModelElement ): ModelElement | null {
- const json = this.savedCaptions.get( include );
+ /** A copy of the caption last saved for `embed`, or `null`. */
+ getSavedCaption( embed: ModelElement ): ModelElement | null {
+ const json = this.savedCaptions.get( embed );
return json ? ModelElement.fromJSON( json ) : null;
}
- /** A copy of the caption that a Tiny box size removed from `include`, or `null`. */
- takeTinyCaption( include: ModelElement ): ModelElement | null {
- return this.tinyIncludes.delete( include ) ? this.getSavedCaption( include ) : null;
+ /** A copy of the caption that a Tiny box size removed from `embed`, or `null`. */
+ takeTinyCaption( embed: ModelElement ): ModelElement | null {
+ return this.tinyEmbeds.delete( embed ) ? this.getSavedCaption( embed ) : null;
}
_defineSchema() {
const schema = this.editor.model.schema;
- schema.register( 'includeNote', {
+ schema.register( 'contentEmbed', {
// Behaves like a self-contained object (e.g. an image).
isObject: true,
- // An include shows either a note or, as an embed, an attachment. An embed that
+ // An embed shows either a note or an attachment. An embed that
// `FileUploadEditing` is uploading carries the upload attributes instead of its id.
allowAttributes: [
'noteId', 'attachmentId', 'boxSize', 'hideTitle', 'uploadId', 'uploadStatus',
@@ -329,10 +329,10 @@ class IncludeNoteEditing extends Plugin {
// `ImageCaptionEditing` and `TableCaptionEditing` share the same `caption` element.
if ( schema.isRegistered( 'caption' ) ) {
- schema.extend( 'caption', { allowIn: 'includeNote' } );
+ schema.extend( 'caption', { allowIn: 'contentEmbed' } );
} else {
schema.register( 'caption', {
- allowIn: 'includeNote',
+ allowIn: 'contentEmbed',
allowContentOf: '$block',
isLimit: true
} );
@@ -344,65 +344,65 @@ class IncludeNoteEditing extends Plugin {
const conversion = editor.conversion;
const t = editor.t;
- // <includeNote> converters
+ // <contentEmbed> converters
conversion.for( 'upcast' ).elementToElement( {
model: ( viewElement, { writer: modelWriter } ) => {
const attachmentId = viewElement.getAttribute( 'data-attachment-id' );
- const included = attachmentId
+ const embedded = attachmentId
? { attachmentId }
: { noteId: viewElement.getAttribute( 'data-note-id' ) };
- return modelWriter.createElement( 'includeNote', {
- ...included,
+ return modelWriter.createElement( 'contentEmbed', {
+ ...embedded,
boxSize: viewElement.getAttribute( 'data-box-size' ),
...( viewElement.getAttribute( 'data-hide-title' ) === 'true'
? { hideTitle: true }
: {} )
} );
},
- // Includes saved before captions existed are `<section>` elements.
+ // Embeds saved before captions existed are `<section>` elements.
view: {
name: /^(?:figure|section)$/,
classes: 'include-note'
}
} );
conversion.for( 'dataDowncast' ).elementToElement( {
- model: 'includeNote',
+ model: 'contentEmbed',
view: ( modelElement, { writer: viewWriter } ) => {
return viewWriter.createContainerElement( 'figure', {
class: 'include-note',
- ...getIncludedEntityAttributes( modelElement ),
+ ...getEmbeddedEntityAttributes( modelElement ),
'data-box-size': modelElement.getAttribute( 'boxSize' ),
...getTitleAttributes( modelElement )
} );
}
} );
conversion.for( 'editingDowncast' ).elementToElement( {
- model: 'includeNote',
+ model: 'contentEmbed',
view: ( modelElement, { writer: viewWriter } ) => {
const boxSize = modelElement.getAttribute( 'boxSize' ) as string | undefined;
const figure = viewWriter.createContainerElement( 'figure', {
class: 'include-note box-size-' + boxSize,
- ...getIncludedEntityAttributes( modelElement ),
+ ...getEmbeddedEntityAttributes( modelElement ),
'data-box-size': boxSize,
...getTitleAttributes( modelElement )
} );
- const includedNoteWrapper = viewWriter.createUIElement( 'div', {
+ const embedWrapper = viewWriter.createUIElement( 'div', {
class: 'include-note-wrapper',
"data-cke-ignore-events": true
}, function( domDocument ) {
const domElement = this.toDomElement( domDocument );
- showIncludedContent( editor, modelElement, domElement );
+ showEmbeddedContent( editor, modelElement, domElement );
preventCKEditorHandling( domElement, editor );
return domElement;
} );
- viewWriter.insert( viewWriter.createPositionAt( figure, 0 ), includedNoteWrapper );
+ viewWriter.insert( viewWriter.createPositionAt( figure, 0 ), embedWrapper );
// hasSelectionHandle gives the block widget CKEditor's own drag grip so it moves
// atomically, instead of the browser's native drag tearing the embedded note apart.
@@ -417,7 +417,7 @@ class IncludeNoteEditing extends Plugin {
// Handle boxSize attribute changes on existing elements
conversion.for( 'editingDowncast' ).add( dispatcher => {
- dispatcher.on( 'attribute:boxSize:includeNote', ( evt, data, conversionApi ) => {
+ dispatcher.on( 'attribute:boxSize:contentEmbed', ( evt, data, conversionApi ) => {
const viewElement = conversionApi.mapper.toViewElement( data.item );
/* v8 ignore next 3 -- defensive guard: when the attribute:boxSize event fires the model item is always mapped to a rendered view element; forcing an unmapped state (mapper.unbindModelElement) crashes the conversion pipeline elsewhere before this guard can be observed, so it is unreachable from a unit test */
if ( !viewElement ) {
@@ -436,16 +436,16 @@ class IncludeNoteEditing extends Plugin {
viewWriter.addClass( 'box-size-' + newBoxSize, viewElement );
viewWriter.setAttribute( 'data-box-size', newBoxSize, viewElement );
- // Re-render the included note content with the new box size. We drive this
+ // Re-render the embedded note content with the new box size. We drive this
// directly from the converter (rather than observing the DOM attribute) so the
// content is only rebuilt on a genuine box-size change — not whenever CKEditor
// re-applies unrelated attributes (e.g. `draggable` while selecting the widget).
- reloadIncludedNote( editor, viewElement, data.item as ModelElement, newBoxSize );
+ reloadEmbeddedContent( editor, viewElement, data.item as ModelElement, newBoxSize );
}
} );
// Shows or hides the title without drawing the content again.
- dispatcher.on( 'attribute:hideTitle:includeNote', ( _evt, data, conversionApi ) => {
+ dispatcher.on( 'attribute:hideTitle:contentEmbed', ( _evt, data, conversionApi ) => {
const viewElement = conversionApi.mapper.toViewElement( data.item as ModelElement );
if ( !viewElement ) {
return;
@@ -459,30 +459,30 @@ class IncludeNoteEditing extends Plugin {
} );
// Redraws the content in place when an upload ends. A converter that lists
- // `attributes` also reconverts the include on every change of its children, such as
+ // `attributes` also reconverts the embed on every change of its children, such as
// a caption toggle.
for ( const attribute of [ 'attachmentId', 'uploadFileName' ] ) {
- dispatcher.on( `attribute:${ attribute }:includeNote`, ( _evt, data, api ) => {
- redrawIncludedEntity( editor, data.item as ModelElement, api );
+ dispatcher.on( `attribute:${ attribute }:contentEmbed`, ( _evt, data, api ) => {
+ redrawEmbeddedEntity( editor, data.item as ModelElement, api );
} );
}
} );
- // <caption> converters, for the caption of an include only
+ // <caption> converters, for the caption of an embed only
conversion.for( 'upcast' ).elementToElement( {
- view: element => isIncludeNoteCaptionView( element ) ? { name: true } : null,
+ view: element => isContentEmbedCaptionView( element ) ? { name: true } : null,
model: 'caption'
} );
conversion.for( 'dataDowncast' ).elementToElement( {
model: 'caption',
- view: ( modelElement, { writer: viewWriter } ) => isIncludeNote( modelElement.parent )
+ view: ( modelElement, { writer: viewWriter } ) => isContentEmbed( modelElement.parent )
? viewWriter.createContainerElement( 'figcaption' )
: null
} );
conversion.for( 'editingDowncast' ).elementToElement( {
model: 'caption',
view: ( modelElement, { writer: viewWriter } ) => {
- if ( !isIncludeNote( modelElement.parent ) ) {
+ if ( !isContentEmbed( modelElement.parent ) ) {
return null;
}
@@ -507,7 +507,7 @@ class IncludeNoteEditing extends Plugin {
'modelToViewPosition',
( _evt, data ) => {
const parent = data.modelPosition.parent;
- const viewElement = parent.is( 'element', 'includeNote' )
+ const viewElement = parent.is( 'element', 'contentEmbed' )
? data.mapper.toViewElement( parent )
: undefined;
const wrapperIndex = viewElement ? getWrapperIndex( viewElement ) : null;
@@ -523,27 +523,27 @@ class IncludeNoteEditing extends Plugin {
}
/**
- * Removes the caption of every Tiny include that a change touched, keeping a copy for when
- * the include gets a larger box size.
+ * Removes the caption of every Tiny embed that a change touched, keeping a copy for when
+ * the embed gets a larger box size.
*/
private removeTinyCaptions( writer: ModelWriter ) {
- const includes = new Set<ModelElement>();
+ const embeds = new Set<ModelElement>();
for ( const change of this.editor.model.document.differ.getChanges() ) {
if ( change.type === 'attribute' && change.attributeKey === 'boxSize' ) {
- addIncludeNotes( includes, change.range.start.nodeAfter );
+ addContentEmbeds( embeds, change.range.start.nodeAfter );
} else if ( change.type === 'insert' && change.name === 'caption' ) {
- addIncludeNotes( includes, change.position.parent );
+ addContentEmbeds( embeds, change.position.parent );
} else if ( change.type === 'insert' && change.name !== '$text' ) {
- addIncludeNotes( includes, change.position.nodeAfter );
+ addContentEmbeds( embeds, change.position.nodeAfter );
}
}
let isChanged = false;
- for ( const include of includes ) {
- const caption = getCaption( include );
- if ( caption && include.getAttribute( 'boxSize' ) === 'tiny' ) {
- this.saveCaption( include, caption );
- this.tinyIncludes.add( include );
+ for ( const embed of embeds ) {
+ const caption = getCaption( embed );
+ if ( caption && embed.getAttribute( 'boxSize' ) === 'tiny' ) {
+ this.saveCaption( embed, caption );
+ this.tinyEmbeds.add( embed );
writer.remove( caption );
isChanged = true;
}
@@ -553,7 +553,7 @@ class IncludeNoteEditing extends Plugin {
}
}
-class InsertIncludeNoteCommand extends Command {
+class InsertContentEmbedCommand extends Command {
override execute() {
const editorEl = this.editor.editing.view.getDomRoot();
const component = glob.getComponentByEl(editorEl);
@@ -565,35 +565,35 @@ class InsertIncludeNoteCommand extends Command {
const model = this.editor.model;
const selection = model.document.selection;
const firstPosition = selection.getFirstPosition();
- const allowedIn = firstPosition && model.schema.findAllowedParent( firstPosition, 'includeNote' );
+ const allowedIn = firstPosition && model.schema.findAllowedParent( firstPosition, 'contentEmbed' );
this.isEnabled = allowedIn !== null;
}
}
-class IncludeNoteBoxSizeCommand extends Command {
+class ContentEmbedBoxSizeCommand extends Command {
declare value: BoxSizeValue | null;
/**
- * Sets the box size of the selected include. Tiny takes the caption away, and a larger size
+ * Sets the box size of the selected embed. Tiny takes the caption away, and a larger size
* shows it again.
*/
override execute( options: { value: BoxSizeValue } ) {
const editor = this.editor;
- const includeNoteElement = getSelectedIncludeNote( editor );
+ const embedElement = getSelectedContentEmbed( editor );
- if ( includeNoteElement ) {
+ if ( embedElement ) {
editor.model.change( writer => {
- const wasTiny = includeNoteElement.getAttribute( 'boxSize' ) === 'tiny';
- writer.setAttribute( 'boxSize', options.value, includeNoteElement );
+ const wasTiny = embedElement.getAttribute( 'boxSize' ) === 'tiny';
+ writer.setAttribute( 'boxSize', options.value, embedElement );
if ( options.value === 'tiny' ) {
- writer.setSelection( includeNoteElement, 'on' );
- } else if ( wasTiny && !getCaption( includeNoteElement ) ) {
- const caption = editor.plugins.get( IncludeNoteEditing )
- .takeTinyCaption( includeNoteElement );
+ writer.setSelection( embedElement, 'on' );
+ } else if ( wasTiny && !getCaption( embedElement ) ) {
+ const caption = editor.plugins.get( ContentEmbedEditing )
+ .takeTinyCaption( embedElement );
if ( caption ) {
- writer.append( caption, includeNoteElement );
+ writer.append( caption, embedElement );
}
}
} );
@@ -601,22 +601,22 @@ class IncludeNoteBoxSizeCommand extends Command {
}
override refresh() {
- const includeNoteElement = getSelectedIncludeNote( this.editor );
+ const embedElement = getSelectedContentEmbed( this.editor );
- this.isEnabled = !!includeNoteElement;
- this.value = includeNoteElement?.getAttribute( 'boxSize' ) as BoxSizeValue | null ?? null;
+ this.isEnabled = !!embedElement;
+ this.value = embedElement?.getAttribute( 'boxSize' ) as BoxSizeValue | null ?? null;
}
}
-/** Shows or hides the caption of the selected include. A Tiny include has none. */
-export class ToggleIncludeNoteCaptionCommand extends Command {
+/** Shows or hides the caption of the selected embed. A Tiny embed has none. */
+export class ToggleContentEmbedCaptionCommand extends Command {
declare value: boolean;
override refresh() {
- const include = getSelectedIncludeNote( this.editor );
+ const embed = getSelectedContentEmbed( this.editor );
- this.isEnabled = !!include && isIncludeCaptionToggleable( this.editor, include );
- this.value = !!include && !!getCaption( include );
+ this.isEnabled = !!embed && isEmbedCaptionToggleable( this.editor, embed );
+ this.value = !!embed && !!getCaption( embed );
}
/**
@@ -625,23 +625,23 @@ export class ToggleIncludeNoteCaptionCommand extends Command {
*/
override execute( { focusCaptionOnShow = false }: { focusCaptionOnShow?: boolean } = {} ) {
const editor = this.editor;
- const include = getSelectedIncludeNote( editor );
- if ( !include ) {
+ const embed = getSelectedContentEmbed( editor );
+ if ( !embed ) {
return;
}
- const editing = editor.plugins.get( IncludeNoteEditing );
+ const editing = editor.plugins.get( ContentEmbedEditing );
editor.model.change( writer => {
- const caption = getCaption( include );
+ const caption = getCaption( embed );
if ( caption ) {
- editing.saveCaption( include, caption );
- writer.setSelection( include, 'on' );
+ editing.saveCaption( embed, caption );
+ writer.setSelection( embed, 'on' );
writer.remove( caption );
return;
}
- const shown = editing.getSavedCaption( include ) ?? writer.createElement( 'caption' );
- writer.append( shown, include );
+ const shown = editing.getSavedCaption( embed ) ?? writer.createElement( 'caption' );
+ writer.append( shown, embed );
if ( focusCaptionOnShow ) {
writer.setSelection( shown, 'in' );
}
@@ -650,31 +650,31 @@ export class ToggleIncludeNoteCaptionCommand extends Command {
}
/**
- * Shows or hides the title row of the selected include. A Tiny or an Expandable include always
+ * Shows or hides the title row of the selected embed. A Tiny or an Expandable embed always
* shows it.
*/
-export class ToggleIncludeNoteTitleCommand extends Command {
+export class ToggleContentEmbedTitleCommand extends Command {
/** Whether the title shows. */
declare value: boolean;
override refresh() {
- const include = getSelectedIncludeNote( this.editor );
+ const embed = getSelectedContentEmbed( this.editor );
- this.isEnabled = !!include && isIncludeTitleToggleable( include );
- this.value = !include?.getAttribute( 'hideTitle' );
+ this.isEnabled = !!embed && isEmbedTitleToggleable( embed );
+ this.value = !embed?.getAttribute( 'hideTitle' );
}
override execute() {
- const include = getSelectedIncludeNote( this.editor );
- if ( !include ) {
+ const embed = getSelectedContentEmbed( this.editor );
+ if ( !embed ) {
return;
}
this.editor.model.change( writer => {
- if ( include.getAttribute( 'hideTitle' ) ) {
- writer.removeAttribute( 'hideTitle', include );
+ if ( embed.getAttribute( 'hideTitle' ) ) {
+ writer.removeAttribute( 'hideTitle', embed );
} else {
- writer.setAttribute( 'hideTitle', true, include );
+ writer.setAttribute( 'hideTitle', true, embed );
}
} );
}
@@ -700,7 +700,7 @@ class EmbedAttachmentLinkCommand extends Command {
}
editor.model.change( writer => {
- const embed = writer.createElement( 'includeNote', {
+ const embed = writer.createElement( 'contentEmbed', {
attachmentId,
boxSize: boxSize ?? 'medium'
} );
@@ -710,17 +710,17 @@ class EmbedAttachmentLinkCommand extends Command {
}
}
-/** Replaces the selected include with a link to the note or attachment it shows. */
+/** Replaces the selected embed with a link to the note or attachment it shows. */
class ConvertEmbedToLinkCommand extends Command {
override refresh() {
- const embed = getSelectedIncludeNote( this.editor );
+ const embed = getSelectedContentEmbed( this.editor );
- this.isEnabled = !!embed && isIncludeConvertibleToLink( this.editor, embed );
+ this.isEnabled = !!embed && isEmbedConvertibleToLink( this.editor, embed );
}
override async execute() {
const editor = this.editor;
- const embed = getSelectedIncludeNote( editor );
+ const embed = getSelectedContentEmbed( editor );
const attachmentId = embed?.getAttribute( 'attachmentId' ) as string | undefined;
const noteId = embed?.getAttribute( 'noteId' ) as string | undefined;
if ( !embed || ( !attachmentId && !noteId ) ) {
@@ -750,23 +750,23 @@ class ConvertEmbedToLinkCommand extends Command {
}
}
-/** The include the selection is on or inside, or `null`. */
-function getSelectedIncludeNote( editor: Editor ) {
+/** The embed the selection is on or inside, or `null`. */
+function getSelectedContentEmbed( editor: Editor ) {
const selection = editor.model.document.selection;
const selectedElement = selection.getSelectedElement();
- if ( selectedElement?.name === 'includeNote' ) {
+ if ( selectedElement?.name === 'contentEmbed' ) {
return selectedElement;
}
- return selection.getFirstPosition()?.findAncestor( 'includeNote' ) ?? null;
+ return selection.getFirstPosition()?.findAncestor( 'contentEmbed' ) ?? null;
}
-/** The include whose rendering contains `domElement`, or `null`. */
-function getIncludeNoteAt( editor: Editor, domElement: Element ) {
- const includeElement = domElement.closest<HTMLElement>( '.include-note' );
- const viewElement = includeElement
- && editor.editing.view.domConverter.mapDomToView( includeElement );
+/** The embed whose rendering contains `domElement`, or `null`. */
+function getContentEmbedAt( editor: Editor, domElement: Element ) {
+ const embedElement = domElement.closest<HTMLElement>( '.include-note' );
+ const viewElement = embedElement
+ && editor.editing.view.domConverter.mapDomToView( embedElement );
if ( !viewElement?.is( 'element' ) ) {
return null;
}
@@ -774,31 +774,31 @@ function getIncludeNoteAt( editor: Editor, domElement: Element ) {
return editor.editing.mapper.toModelElement( viewElement ) ?? null;
}
-function isIncludeNote( node: ModelNode | ModelDocumentFragment | null ): node is ModelElement {
- return !!node?.is( 'element', 'includeNote' );
+function isContentEmbed( node: ModelNode | ModelDocumentFragment | null ): node is ModelElement {
+ return !!node?.is( 'element', 'contentEmbed' );
}
-/** Whether the title of `include` can be hidden: a Tiny or an Expandable one always shows it. */
-function isIncludeTitleToggleable( include: ModelElement ) {
- const boxSize = include.getAttribute( 'boxSize' );
+/** Whether the title of `embed` can be hidden: a Tiny or an Expandable one always shows it. */
+function isEmbedTitleToggleable( embed: ModelElement ) {
+ const boxSize = embed.getAttribute( 'boxSize' );
return boxSize !== 'tiny' && boxSize !== 'expandable';
}
-/** Whether `include` can have a caption. A Tiny include has none. */
-function isIncludeCaptionToggleable( editor: Editor, include: ModelElement ) {
- return include.getAttribute( 'boxSize' ) !== 'tiny'
- && editor.model.schema.checkChild( include, 'caption' );
+/** Whether `embed` can have a caption. A Tiny embed has none. */
+function isEmbedCaptionToggleable( editor: Editor, embed: ModelElement ) {
+ return embed.getAttribute( 'boxSize' ) !== 'tiny'
+ && editor.model.schema.checkChild( embed, 'caption' );
}
-/** Whether `include` names a note or an attachment, which a link can then point to. */
-function isIncludeConvertibleToLink( editor: Editor, include: ModelElement ) {
- return ( !!include.getAttribute( 'attachmentId' ) || !!include.getAttribute( 'noteId' ) )
+/** Whether `embed` names a note or an attachment, which a link can then point to. */
+function isEmbedConvertibleToLink( editor: Editor, embed: ModelElement ) {
+ return ( !!embed.getAttribute( 'attachmentId' ) || !!embed.getAttribute( 'noteId' ) )
&& editor.model.schema.isRegistered( 'reference' );
}
-/** The caption of `include`, or `null`. */
-function getCaption( include: ModelElement ) {
- for ( const child of include.getChildren() ) {
+/** The caption of `embed`, or `null`. */
+function getCaption( embed: ModelElement ) {
+ for ( const child of embed.getChildren() ) {
if ( child.is( 'element', 'caption' ) ) {
return child;
}
@@ -807,14 +807,14 @@ function getCaption( include: ModelElement ) {
return null;
}
-/** Whether `element` is the `<figcaption>` of an include. */
-function isIncludeNoteCaptionView( element: ViewElement ) {
+/** Whether `element` is the `<figcaption>` of an embed. */
+function isContentEmbedCaptionView( element: ViewElement ) {
const parent = element.parent;
return element.name === 'figcaption' && !!parent?.is( 'element' )
&& parent.hasClass( 'include-note' );
}
-/** The index of the content wrapper among the children of an include's view, or `null`. */
+/** The index of the content wrapper among the children of an embed's view, or `null`. */
function getWrapperIndex( viewElement: ViewElement ) {
for ( const [ index, child ] of Array.from( viewElement.getChildren() ).entries() ) {
if ( child.is( 'uiElement' ) && child.hasClass( 'include-note-wrapper' ) ) {
@@ -825,25 +825,25 @@ function getWrapperIndex( viewElement: ViewElement ) {
return null;
}
-/** Adds `node`, when it is an include, and every include inside it to `includes`. */
-function addIncludeNotes(
- includes: Set<ModelElement>,
+/** Adds `node`, when it is an embed, and every embed inside it to `embeds`. */
+function addContentEmbeds(
+ embeds: Set<ModelElement>,
node: ModelNode | ModelDocumentFragment | null
) {
- if ( isIncludeNote( node ) ) {
- includes.add( node );
+ if ( isContentEmbed( node ) ) {
+ embeds.add( node );
} else if ( node?.is( 'element' ) ) {
for ( const descendant of node.getChildren() ) {
- addIncludeNotes( includes, descendant );
+ addContentEmbeds( embeds, descendant );
}
}
}
/**
- * The `data-*` attribute naming what an include shows: an attachment, or a note. An embed whose
+ * The `data-*` attribute naming what an embed shows: an attachment, or a note. An embed whose
* upload has not ended names nothing.
*/
-function getIncludedEntityAttributes( element: ModelElement ): Record<string, string> {
+function getEmbeddedEntityAttributes( element: ModelElement ): Record<string, string> {
const attachmentId = element.getAttribute( 'attachmentId' ) as string | undefined;
const noteId = element.getAttribute( 'noteId' ) as string | undefined;
@@ -854,22 +854,22 @@ function getIncludedEntityAttributes( element: ModelElement ): Record<string, st
return noteId ? { 'data-note-id': noteId } : {};
}
-/** The `data-hide-title` attribute of an include whose title is hidden. */
+/** The `data-hide-title` attribute of an embed whose title is hidden. */
function getTitleAttributes( element: ModelElement ): Record<string, string> {
return element.getAttribute( 'hideTitle' ) ? { 'data-hide-title': 'true' } : {};
}
-/** Has the host open the context menu of the selected include, below `anchor`. */
-function openIncludeNoteMenu( editor: Editor, anchor: HTMLElement | null ) {
- const include = getSelectedIncludeNote( editor );
- const viewElement = include && editor.editing.mapper.toViewElement( include );
+/** Has the host open the context menu of the selected embed, below `anchor`. */
+function openContentEmbedMenu( editor: Editor, anchor: HTMLElement | null ) {
+ const embed = getSelectedContentEmbed( editor );
+ const viewElement = embed && editor.editing.mapper.toViewElement( embed );
const domElement = viewElement && editor.editing.view.domConverter.mapViewToDom( viewElement );
if ( !anchor || !( domElement instanceof HTMLElement ) ) {
return;
}
const component = glob.getComponentByEl<EditorComponent>( editor.editing.view.getDomRoot() );
- component.openIncludeNoteMenu?.( domElement, anchor );
+ component.openContentEmbedMenu?.( domElement, anchor );
}
/** The title of an embed whose upload is under way: a spinner and the name of the file. */
@@ -889,14 +889,14 @@ function createUploadTitle( domDocument: Document, fileName: string ) {
const shownContents = new WeakMap<HTMLElement, string>();
/**
- * Draws what an include shows into its content wrapper: the file name while an upload is under
+ * Draws what an embed shows into its content wrapper: the file name while an upload is under
* way, then the attachment or note.
*/
-function showIncludedContent( editor: Editor, element: ModelElement, wrapper: HTMLElement ) {
+function showEmbeddedContent( editor: Editor, element: ModelElement, wrapper: HTMLElement ) {
const uploadFileName = element.getAttribute( 'uploadFileName' ) as string | undefined;
const shown = uploadFileName
? `upload:${ uploadFileName }`
- : JSON.stringify( getIncludedEntityAttributes( element ) );
+ : JSON.stringify( getEmbeddedEntityAttributes( element ) );
const previous = shownContents.get( wrapper );
if ( previous === shown ) {
return;
@@ -912,16 +912,16 @@ function showIncludedContent( editor: Editor, element: ModelElement, wrapper: HT
wrapper.replaceChildren();
}
const boxSize = element.getAttribute( 'boxSize' ) as string | undefined;
- loadIncludedContent( editor, element, $( wrapper ), boxSize );
+ loadEmbeddedContent( editor, element, $( wrapper ), boxSize );
}
-/** Updates the `data-*` attribute of an include's view to what it shows, and redraws it. */
-function redrawIncludedEntity(
+/** Updates the `data-*` attribute of an embed's view to what it shows, and redraws it. */
+function redrawEmbeddedEntity(
editor: Editor,
- include: ModelElement,
+ embed: ModelElement,
conversionApi: DowncastConversionApi
) {
- const viewElement = conversionApi.mapper.toViewElement( include );
+ const viewElement = conversionApi.mapper.toViewElement( embed );
if ( !viewElement ) {
return;
}
@@ -929,24 +929,24 @@ function redrawIncludedEntity(
const viewWriter = conversionApi.writer;
viewWriter.removeAttribute( 'data-attachment-id', viewElement );
viewWriter.removeAttribute( 'data-note-id', viewElement );
- for ( const [ key, value ] of Object.entries( getIncludedEntityAttributes( include ) ) ) {
+ for ( const [ key, value ] of Object.entries( getEmbeddedEntityAttributes( embed ) ) ) {
viewWriter.setAttribute( key, value, viewElement );
}
const wrapper = getWrapperDom( editor, viewElement );
if ( wrapper ) {
- showIncludedContent( editor, include, wrapper );
+ showEmbeddedContent( editor, embed, wrapper );
}
}
-/** The content wrapper of a rendered include, or `null` before the include is rendered. */
+/** The content wrapper of a rendered embed, or `null` before the embed is rendered. */
function getWrapperDom( editor: Editor, viewElement: ViewElement ) {
return editor.editing.view.domConverter.mapViewToDom( viewElement )
?.querySelector<HTMLElement>( ':scope > .include-note-wrapper' ) ?? null;
}
-/** Has the host render what an include shows into its wrapper. */
-function loadIncludedContent(
+/** Has the host render what an embed shows into its wrapper. */
+function loadEmbeddedContent(
editor: Editor,
element: ModelElement,
$wrapper: JQuery<HTMLElement>,
@@ -958,14 +958,14 @@ function loadIncludedContent(
const noteId = element.getAttribute( 'noteId' ) as string | undefined;
if ( attachmentId ) {
- component.loadIncludedAttachment( attachmentId, $wrapper, boxSize );
+ component.loadEmbeddedAttachment( attachmentId, $wrapper, boxSize );
} else if ( noteId ) {
- component.loadIncludedNote( noteId, $wrapper, boxSize );
+ component.loadEmbeddedNote( noteId, $wrapper, boxSize );
}
}
/**
- * Re-renders the included note content of an already-rendered widget after its box size changed.
+ * Re-renders the embedded note content of an already-rendered widget after its box size changed.
*
* The wrapper is a `UIElement` whose DOM is opaque to CKEditor, so we reach into it directly to
* trigger the client-side render. The box size is passed explicitly because, at conversion time,
@@ -975,11 +975,11 @@ function loadIncludedContent(
* DOM, so `mapViewToDom()` returns nothing and this is a no-op — the `UIElement` render callback
* performs that first paint instead. It only does work on a subsequent, genuine box-size change.
*/
-function reloadIncludedNote( editor: Editor, viewElement: ViewElement, modelElement: ModelElement, boxSize: string ) {
+function reloadEmbeddedContent( editor: Editor, viewElement: ViewElement, modelElement: ModelElement, boxSize: string ) {
const wrapperDom = getWrapperDom( editor, viewElement );
if ( wrapperDom ) {
- loadIncludedContent( editor, modelElement, $( wrapperDom ), boxSize );
+ loadEmbeddedContent( editor, modelElement, $( wrapperDom ), boxSize );
}
}
@@ -994,11 +994,11 @@ function preventCKEditorHandling( domElement: HTMLElement, editor: Editor ) {
//domElement.addEventListener( 'click', stopEventPropagationAndHackRendererFocus, { capture: true } );
domElement.addEventListener( 'mousedown', ( evt: MouseEvent ) => {
- // A button of the title row selects the include. Preventing the default keeps the focus
+ // A button of the title row selects the embed. Preventing the default keeps the focus
// in the editor instead of the button, and the click still fires.
if ( isTitleRowButton( evt.target ) ) {
evt.preventDefault();
- selectIncludeNoteWidget( domElement, editor );
+ selectContentEmbedWidget( domElement, editor );
return;
}
@@ -1022,7 +1022,7 @@ function preventCKEditorHandling( domElement: HTMLElement, editor: Editor ) {
editor.editing.view._renderer.isFocused = false;
// Select the widget so the toolbar can appear
- selectIncludeNoteWidget( domElement, editor );
+ selectContentEmbedWidget( domElement, editor );
}, { capture: true } );
domElement.addEventListener( 'focus', stopEventPropagationAndHackRendererFocus, { capture: true } );
@@ -1066,8 +1066,8 @@ function isTitleRowButton( target: EventTarget | null ): boolean {
return target instanceof Element && !!target.closest( '.include-note-title-row button' );
}
-function selectIncludeNoteWidget( domElement: HTMLElement, editor: Editor ) {
- const modelElement = getIncludeNoteAt( editor, domElement );
+function selectContentEmbedWidget( domElement: HTMLElement, editor: Editor ) {
+ const modelElement = getContentEmbedAt( editor, domElement );
if ( !modelElement ) {
return;
}
@@ -1083,11 +1083,11 @@ function selectIncludeNoteWidget( domElement: HTMLElement, editor: Editor ) {
declare module 'ckeditor5' {
interface PluginsMap {
- [ IncludeNote.pluginName ]: IncludeNote;
+ [ ContentEmbed.pluginName ]: ContentEmbed;
}
interface CommandsMap {
- toggleIncludeNoteCaption: ToggleIncludeNoteCaptionCommand;
- toggleIncludeNoteTitle: ToggleIncludeNoteTitleCommand;
+ toggleContentEmbedCaption: ToggleContentEmbedCaptionCommand;
+ toggleContentEmbedTitle: ToggleContentEmbedTitleCommand;
}
}
diff --git a/packages/ckeditor5/src/plugins/include_note_box_size_dropdown.spec.ts b/packages/ckeditor5/src/plugins/content_embed/content_embed_box_size_dropdown.spec.ts
similarity index 80%
rename from packages/ckeditor5/src/plugins/include_note_box_size_dropdown.spec.ts
rename to packages/ckeditor5/src/plugins/content_embed/content_embed_box_size_dropdown.spec.ts
index d11d2233ba..124729c7f8 100644
--- a/packages/ckeditor5/src/plugins/include_note_box_size_dropdown.spec.ts
+++ b/packages/ckeditor5/src/plugins/content_embed/content_embed_box_size_dropdown.spec.ts
@@ -1,30 +1,30 @@
import { ClassicEditor, Essentials, Paragraph, Widget, _setModelData as setModelData } from "ckeditor5";
import { beforeEach, describe, expect, it, vi } from "vitest";
-import { createTestEditor } from "../../test/editor-kit.js";
-import { installGlobMock } from "../../test/globals-test-kit.js";
-import IncludeNoteBoxSizeDropdown from "./include_note_box_size_dropdown.js";
-import IncludeNote, { BOX_SIZE_COMMAND_NAME, BOX_SIZES } from "./includenote.js";
+import { createTestEditor } from "../../../test/editor-kit.js";
+import { installGlobMock } from "../../../test/globals-test-kit.js";
+import ContentEmbedBoxSizeDropdown from "./content_embed_box_size_dropdown.js";
+import ContentEmbed, { BOX_SIZE_COMMAND_NAME, BOX_SIZES } from "./content_embed.js";
-describe("IncludeNoteBoxSizeDropdown", () => {
+describe("ContentEmbedBoxSizeDropdown", () => {
let editor: ClassicEditor;
beforeEach(async () => {
- const loadIncludedNote = vi.fn();
+ const loadEmbeddedNote = vi.fn();
installGlobMock({
- getComponentByEl: () => ({ loadIncludedNote })
+ getComponentByEl: () => ({ loadEmbeddedNote })
});
- editor = await createTestEditor([Essentials, Paragraph, Widget, IncludeNote, IncludeNoteBoxSizeDropdown]);
+ editor = await createTestEditor([Essentials, Paragraph, Widget, ContentEmbed, ContentEmbedBoxSizeDropdown]);
});
it("loads the plugin and registers the dropdown component", () => {
- expect(editor.plugins.get(IncludeNoteBoxSizeDropdown)).toBeInstanceOf(IncludeNoteBoxSizeDropdown);
- expect(editor.ui.componentFactory.has("includeNoteBoxSizeDropdown")).toBe(true);
+ expect(editor.plugins.get(ContentEmbedBoxSizeDropdown)).toBeInstanceOf(ContentEmbedBoxSizeDropdown);
+ expect(editor.ui.componentFactory.has("contentEmbedBoxSizeDropdown")).toBe(true);
});
it("dropdown has all BOX_SIZES as list items with correct labels", () => {
- const dropdownView = editor.ui.componentFactory.create("includeNoteBoxSizeDropdown") as {
+ const dropdownView = editor.ui.componentFactory.create("contentEmbedBoxSizeDropdown") as {
listView?: { items: Iterable<{ children?: Iterable<{ label?: string }> }> };
panelView?: { children: Iterable<{ items: Iterable<{ children?: Iterable<{ label?: string }> }> }> };
};
@@ -40,32 +40,32 @@ describe("IncludeNoteBoxSizeDropdown", () => {
});
it("button label shows 'Box size' when command value is null", () => {
- const dropdownView = editor.ui.componentFactory.create("includeNoteBoxSizeDropdown") as unknown as {
+ const dropdownView = editor.ui.componentFactory.create("contentEmbedBoxSizeDropdown") as unknown as {
buttonView: { label: string };
};
const command = editor.commands.get(BOX_SIZE_COMMAND_NAME) as { value: string | null; isEnabled: boolean };
- // No include note selected -> value is null
+ // No embed selected -> value is null
expect(command.value).toBeNull();
expect(dropdownView.buttonView.label).toBe("Box size");
});
it("button label updates to the size label when a value is set", () => {
- // Insert an includeNote element so the command can find something to bind to
+ // Insert an contentEmbed element so the command can find something to bind to
editor.model.change((writer) => {
const root = editor.model.document.getRoot();
if (!root) {
throw new Error("No root");
}
- const includeNote = writer.createElement("includeNote", {
+ const contentEmbed = writer.createElement("contentEmbed", {
noteId: "test-note",
boxSize: "small"
});
- writer.insert(includeNote, root, 0);
- writer.setSelection(includeNote, "on");
+ writer.insert(contentEmbed, root, 0);
+ writer.setSelection(contentEmbed, "on");
});
- const dropdownView = editor.ui.componentFactory.create("includeNoteBoxSizeDropdown") as unknown as {
+ const dropdownView = editor.ui.componentFactory.create("contentEmbedBoxSizeDropdown") as unknown as {
buttonView: { label: string };
};
@@ -76,7 +76,7 @@ describe("IncludeNoteBoxSizeDropdown", () => {
});
it("button label falls back to raw value for an unknown size", () => {
- // Insert an includeNote with a size value not in BOX_SIZES
+ // Insert an contentEmbed with a size value not in BOX_SIZES
editor.model.change((writer) => {
const root = editor.model.document.getRoot();
if (!root) {
@@ -84,15 +84,15 @@ describe("IncludeNoteBoxSizeDropdown", () => {
}
// Extend schema temporarily by bypassing schema checks for test
- const includeNote = writer.createElement("includeNote", {
+ const contentEmbed = writer.createElement("contentEmbed", {
noteId: "test-note",
boxSize: "huge"
});
- writer.insert(includeNote, root, 0);
- writer.setSelection(includeNote, "on");
+ writer.insert(contentEmbed, root, 0);
+ writer.setSelection(contentEmbed, "on");
});
- const dropdownView = editor.ui.componentFactory.create("includeNoteBoxSizeDropdown") as unknown as {
+ const dropdownView = editor.ui.componentFactory.create("contentEmbedBoxSizeDropdown") as unknown as {
buttonView: { label: string };
};
@@ -107,31 +107,31 @@ describe("IncludeNoteBoxSizeDropdown", () => {
});
it("dropdown is bound to command isEnabled", () => {
- const dropdownView = editor.ui.componentFactory.create("includeNoteBoxSizeDropdown") as unknown as {
+ const dropdownView = editor.ui.componentFactory.create("contentEmbedBoxSizeDropdown") as unknown as {
isEnabled: boolean;
};
const command = editor.commands.get(BOX_SIZE_COMMAND_NAME) as { isEnabled: boolean };
- // With no include note selected the command should be disabled
+ // With no embed selected the command should be disabled
expect(dropdownView.isEnabled).toBe(command.isEnabled);
expect(dropdownView.isEnabled).toBe(false);
});
- it("dropdown is enabled when an include note element is selected", () => {
+ it("dropdown is enabled when an embed element is selected", () => {
editor.model.change((writer) => {
const root = editor.model.document.getRoot();
if (!root) {
throw new Error("No root");
}
- const includeNote = writer.createElement("includeNote", {
+ const contentEmbed = writer.createElement("contentEmbed", {
noteId: "test-note-2",
boxSize: "medium"
});
- writer.insert(includeNote, root, 0);
- writer.setSelection(includeNote, "on");
+ writer.insert(contentEmbed, root, 0);
+ writer.setSelection(contentEmbed, "on");
});
- const dropdownView = editor.ui.componentFactory.create("includeNoteBoxSizeDropdown") as unknown as {
+ const dropdownView = editor.ui.componentFactory.create("contentEmbedBoxSizeDropdown") as unknown as {
isEnabled: boolean;
};
@@ -144,18 +144,18 @@ describe("IncludeNoteBoxSizeDropdown", () => {
if (!root) {
throw new Error("No root");
}
- const includeNote = writer.createElement("includeNote", {
+ const contentEmbed = writer.createElement("contentEmbed", {
noteId: "test-note-3",
boxSize: "small"
});
- writer.insert(includeNote, root, 0);
- writer.setSelection(includeNote, "on");
+ writer.insert(contentEmbed, root, 0);
+ writer.setSelection(contentEmbed, "on");
});
const spy = vi.spyOn(editor, "execute");
// Create the dropdown (which calls addListToDropdown and registers the "execute" listener)
- const dropdownView = editor.ui.componentFactory.create("includeNoteBoxSizeDropdown");
+ const dropdownView = editor.ui.componentFactory.create("contentEmbedBoxSizeDropdown");
// In CKEditor, when a dropdown list item is activated the dropdown fires "execute"
// with evt.source being the button model of the chosen item. We simulate that by
@@ -218,16 +218,16 @@ describe("IncludeNoteBoxSizeDropdown", () => {
if (!root) {
throw new Error("No root");
}
- const includeNote = writer.createElement("includeNote", {
+ const contentEmbed = writer.createElement("contentEmbed", {
noteId: "test-note-4",
boxSize: "medium"
});
- writer.insert(includeNote, root, 0);
- writer.setSelection(includeNote, "on");
+ writer.insert(contentEmbed, root, 0);
+ writer.setSelection(contentEmbed, "on");
});
// Create a fresh dropdown which builds the itemDefinitions for the current command state
- const dropdownView = editor.ui.componentFactory.create("includeNoteBoxSizeDropdown") as unknown as {
+ const dropdownView = editor.ui.componentFactory.create("contentEmbedBoxSizeDropdown") as unknown as {
panelView: {
children: {
get(index: number): {
@@ -255,7 +255,7 @@ describe("IncludeNoteBoxSizeDropdown", () => {
it("_getBoxSizeListItemDefinitions returns one item per BOX_SIZES entry", () => {
// Indirect test: verify the dropdown panel eventually has as many items as BOX_SIZES
- const dropdownView = editor.ui.componentFactory.create("includeNoteBoxSizeDropdown");
+ const dropdownView = editor.ui.componentFactory.create("contentEmbedBoxSizeDropdown");
// Force the dropdown to render its panel
(dropdownView as unknown as { render(): void }).render?.();
@@ -266,7 +266,7 @@ describe("IncludeNoteBoxSizeDropdown", () => {
expect(panel).toBeDefined();
});
- it("initialises with IncludeNote in its requires list", () => {
- expect(IncludeNoteBoxSizeDropdown.requires).toContain(IncludeNote);
+ it("initialises with ContentEmbed in its requires list", () => {
+ expect(ContentEmbedBoxSizeDropdown.requires).toContain(ContentEmbed);
});
});
diff --git a/packages/ckeditor5/src/plugins/include_note_box_size_dropdown.ts b/packages/ckeditor5/src/plugins/content_embed/content_embed_box_size_dropdown.ts
similarity index 86%
rename from packages/ckeditor5/src/plugins/include_note_box_size_dropdown.ts
rename to packages/ckeditor5/src/plugins/content_embed/content_embed_box_size_dropdown.ts
index 8d68a99b98..0710ea7597 100644
--- a/packages/ckeditor5/src/plugins/include_note_box_size_dropdown.ts
+++ b/packages/ckeditor5/src/plugins/content_embed/content_embed_box_size_dropdown.ts
@@ -1,13 +1,13 @@
import { Plugin, type ListDropdownButtonDefinition, Collection, ViewModel, createDropdown, addListToDropdown, DropdownButtonView, type Command } from "ckeditor5";
-import IncludeNote, { BOX_SIZE_COMMAND_NAME, BOX_SIZES, type BoxSizeValue, getBoxSizeLabel } from "./includenote.js";
+import ContentEmbed, { BOX_SIZE_COMMAND_NAME, BOX_SIZES, type BoxSizeValue, getBoxSizeLabel } from "./content_embed.js";
/**
- * Toolbar item which displays the list of box sizes for include notes in a dropdown.
+ * Toolbar item which displays the list of box sizes for embeds in a dropdown.
*/
-export default class IncludeNoteBoxSizeDropdown extends Plugin {
+export default class ContentEmbedBoxSizeDropdown extends Plugin {
static get requires() {
- return [IncludeNote] as const;
+ return [ContentEmbed] as const;
}
public init() {
@@ -17,7 +17,7 @@ export default class IncludeNoteBoxSizeDropdown extends Plugin {
const itemDefinitions = this._getBoxSizeListItemDefinitions();
const command = editor.commands.get(BOX_SIZE_COMMAND_NAME) as Command & { value: BoxSizeValue | null };
- componentFactory.add("includeNoteBoxSizeDropdown", _locale => {
+ componentFactory.add("contentEmbedBoxSizeDropdown", _locale => {
const dropdownView = createDropdown(editor.locale, DropdownButtonView);
const boxSizeLabel = editor.t("Box size");
dropdownView.buttonView.set({
diff --git a/packages/ckeditor5/src/plugins/include_note_toolbar.spec.ts b/packages/ckeditor5/src/plugins/content_embed/content_embed_toolbar.spec.ts
similarity index 79%
rename from packages/ckeditor5/src/plugins/include_note_toolbar.spec.ts
rename to packages/ckeditor5/src/plugins/content_embed/content_embed_toolbar.spec.ts
index 0d7a639dc5..a8df074106 100644
--- a/packages/ckeditor5/src/plugins/include_note_toolbar.spec.ts
+++ b/packages/ckeditor5/src/plugins/content_embed/content_embed_toolbar.spec.ts
@@ -1,17 +1,17 @@
import { ClassicEditor, Essentials, Paragraph, Plugin, toWidget, Widget, WidgetToolbarRepository, _setModelData as setModelData } from "ckeditor5";
import { beforeEach, describe, expect, it, vi } from "vitest";
-import { createTestEditor } from "../../test/editor-kit.js";
-import { installGlobMock } from "../../test/globals-test-kit.js";
-import IncludeNote, {
+import { createTestEditor } from "../../../test/editor-kit.js";
+import { installGlobMock } from "../../../test/globals-test-kit.js";
+import LinkEmbed from "../link_embed/link_embed.js";
+import ContentEmbed, {
CONVERT_EMBED_TO_LINK_COMMAND,
- INCLUDE_NOTE_MENU,
+ CONTENT_EMBED_MENU,
TOGGLE_CAPTION_COMMAND_NAME,
TOGGLE_TITLE_COMMAND_NAME
-} from "./includenote.js";
-import IncludeNoteBoxSizeDropdown from "./include_note_box_size_dropdown.js";
-import IncludeNoteToolbar from "./include_note_toolbar.js";
-import LinkEmbed from "./link_embed/link_embed.js";
+} from "./content_embed.js";
+import ContentEmbedBoxSizeDropdown from "./content_embed_box_size_dropdown.js";
+import ContentEmbedToolbar from "./content_embed_toolbar.js";
// ---------------------------------------------------------------------------
// Minimal inline plugin that registers a widget without a class attribute.
@@ -62,9 +62,9 @@ function getRelatedElementFn(ed: ClassicEditor): (selection: unknown) => unknown
getRelatedElement: (selection: unknown) => unknown;
}>;
};
- const def = repository._toolbarDefinitions.get("includeNote");
+ const def = repository._toolbarDefinitions.get("contentEmbed");
if (!def) {
- throw new Error("IncludeNote toolbar definition not found in WidgetToolbarRepository.");
+ throw new Error("ContentEmbed toolbar definition not found in WidgetToolbarRepository.");
}
return def.getRelatedElement;
}
@@ -73,30 +73,30 @@ function getRelatedElementFn(ed: ClassicEditor): (selection: unknown) => unknown
const EMPTY_SELECTION = { getSelectedElement: () => null, getFirstPosition: () => null };
// ---------------------------------------------------------------------------
-// Suite 1: basic plugin registration (IncludeNote only, no LinkEmbed)
+// Suite 1: basic plugin registration (ContentEmbed only, no LinkEmbed)
// ---------------------------------------------------------------------------
-describe("IncludeNoteToolbar", () => {
+describe("ContentEmbedToolbar", () => {
let editor: ClassicEditor;
beforeEach(async () => {
- const loadIncludedNote = vi.fn();
+ const loadEmbeddedNote = vi.fn();
installGlobMock({
- getComponentByEl: () => ({ loadIncludedNote })
+ getComponentByEl: () => ({ loadEmbeddedNote })
});
- editor = await createTestEditor([Essentials, Paragraph, Widget, IncludeNote, IncludeNoteBoxSizeDropdown, IncludeNoteToolbar]);
+ editor = await createTestEditor([Essentials, Paragraph, Widget, ContentEmbed, ContentEmbedBoxSizeDropdown, ContentEmbedToolbar]);
});
it("loads the plugin", () => {
- expect(editor.plugins.get(IncludeNoteToolbar)).toBeInstanceOf(IncludeNoteToolbar);
+ expect(editor.plugins.get(ContentEmbedToolbar)).toBeInstanceOf(ContentEmbedToolbar);
});
- it("declares the required plugins including WidgetToolbarRepository, IncludeNote, and IncludeNoteBoxSizeDropdown", () => {
- const requires = IncludeNoteToolbar.requires;
+ it("declares the required plugins including WidgetToolbarRepository, ContentEmbed, and ContentEmbedBoxSizeDropdown", () => {
+ const requires = ContentEmbedToolbar.requires;
expect(requires).toContain(WidgetToolbarRepository);
- expect(requires).toContain(IncludeNote);
- expect(requires).toContain(IncludeNoteBoxSizeDropdown);
+ expect(requires).toContain(ContentEmbed);
+ expect(requires).toContain(ContentEmbedBoxSizeDropdown);
});
it("offers the box size, the title, the caption, the link conversion and the menu", () => {
@@ -104,28 +104,28 @@ describe("IncludeNoteToolbar", () => {
_toolbarDefinitions: Map<string, { itemsConfig: string[] }>;
};
- expect(repository._toolbarDefinitions.get("includeNote")?.itemsConfig).toEqual([
- "includeNoteBoxSizeDropdown",
+ expect(repository._toolbarDefinitions.get("contentEmbed")?.itemsConfig).toEqual([
+ "contentEmbedBoxSizeDropdown",
TOGGLE_TITLE_COMMAND_NAME,
TOGGLE_CAPTION_COMMAND_NAME,
CONVERT_EMBED_TO_LINK_COMMAND,
- INCLUDE_NOTE_MENU
+ CONTENT_EMBED_MENU
]);
});
describe("getRelatedElement", () => {
- it("returns the include-note widget element when an includeNote model element is selected", () => {
+ it("returns the include-note widget element when an contentEmbed model element is selected", () => {
editor.model.change((writer) => {
const root = editor.model.document.getRoot();
if (!root) {
throw new Error("No root");
}
- const includeNoteEl = writer.createElement("includeNote", {
+ const embedEl = writer.createElement("contentEmbed", {
noteId: "test-note",
boxSize: "small"
});
- writer.insert(includeNoteEl, root, 0);
- writer.setSelection(includeNoteEl, "on");
+ writer.insert(embedEl, root, 0);
+ writer.setSelection(embedEl, "on");
});
const fn = getRelatedElementFn(editor);
@@ -134,12 +134,12 @@ describe("IncludeNoteToolbar", () => {
expect(result).not.toBeNull();
});
- it("stays on the include while its caption is edited", () => {
+ it("stays on the embed while its caption is edited", () => {
editor.setData("<figure class=\"include-note\" data-note-id=\"n1\""
+ " data-box-size=\"medium\"><figcaption>Caption</figcaption></figure>");
editor.model.change((writer) => {
- const include = editor.model.document.getRoot()?.getChild(0);
- const caption = include?.is("element") ? include.getChild(0) : null;
+ const embed = editor.model.document.getRoot()?.getChild(0);
+ const caption = embed?.is("element") ? embed.getChild(0) : null;
if (!caption?.is("element", "caption")) {
throw new Error("Expected a caption.");
}
@@ -170,16 +170,16 @@ describe("IncludeNoteToolbar", () => {
// Suite 2: a widget without a class attribute
// ---------------------------------------------------------------------------
-describe("isIncludeNoteWidget — widget without a class attribute", () => {
+describe("isContentEmbedWidget — widget without a class attribute", () => {
let editor: ClassicEditor;
beforeEach(async () => {
- const loadIncludedNote = vi.fn();
+ const loadEmbeddedNote = vi.fn();
installGlobMock({
- getComponentByEl: () => ({ loadIncludedNote })
+ getComponentByEl: () => ({ loadEmbeddedNote })
});
- editor = await createTestEditor([Essentials, Paragraph, Widget, IncludeNote, IncludeNoteBoxSizeDropdown, IncludeNoteToolbar, SectionNoClassWidget]);
+ editor = await createTestEditor([Essentials, Paragraph, Widget, ContentEmbed, ContentEmbedBoxSizeDropdown, ContentEmbedToolbar, SectionNoClassWidget]);
});
it("returns null for a selected widget that has no class attribute", () => {
@@ -200,17 +200,17 @@ describe("isIncludeNoteWidget — widget without a class attribute", () => {
});
// ---------------------------------------------------------------------------
-// Suite 3: real widgets that are not includes
+// Suite 3: real widgets that are not embeds
// ---------------------------------------------------------------------------
-describe("isIncludeNoteWidget — real non-include-note widgets", () => {
+describe("isContentEmbedWidget — real non-include-note widgets", () => {
let editor: ClassicEditor;
beforeEach(async () => {
- const loadIncludedNote = vi.fn();
+ const loadEmbeddedNote = vi.fn();
installGlobMock({
getComponentByEl: () => ({
- loadIncludedNote,
+ loadEmbeddedNote,
renderLinkEmbed: vi.fn(),
renderLinkMention: vi.fn(),
fetchLinkMetadata: async () => ({
@@ -226,7 +226,7 @@ describe("isIncludeNoteWidget — real non-include-note widgets", () => {
})
});
- editor = await createTestEditor([Essentials, Paragraph, Widget, IncludeNote, IncludeNoteBoxSizeDropdown, IncludeNoteToolbar, LinkEmbed]);
+ editor = await createTestEditor([Essentials, Paragraph, Widget, ContentEmbed, ContentEmbedBoxSizeDropdown, ContentEmbedToolbar, LinkEmbed]);
});
it("returns null when the selected element is not a widget", () => {
@@ -296,12 +296,12 @@ describe("isIncludeNoteWidget — real non-include-note widgets", () => {
if (!root) {
throw new Error("No root");
}
- const includeNoteEl = writer.createElement("includeNote", {
+ const embedEl = writer.createElement("contentEmbed", {
noteId: "abc",
boxSize: "full"
});
- writer.insert(includeNoteEl, root, 0);
- writer.setSelection(includeNoteEl, "on");
+ writer.insert(embedEl, root, 0);
+ writer.setSelection(embedEl, "on");
});
const fn = getRelatedElementFn(editor);
diff --git a/packages/ckeditor5/src/plugins/include_note_toolbar.ts b/packages/ckeditor5/src/plugins/content_embed/content_embed_toolbar.ts
similarity index 59%
rename from packages/ckeditor5/src/plugins/include_note_toolbar.ts
rename to packages/ckeditor5/src/plugins/content_embed/content_embed_toolbar.ts
index 5252cbd63e..cb6f2df006 100644
--- a/packages/ckeditor5/src/plugins/include_note_toolbar.ts
+++ b/packages/ckeditor5/src/plugins/content_embed/content_embed_toolbar.ts
@@ -1,41 +1,41 @@
import { Plugin, WidgetToolbarRepository, isWidget, type ViewElement } from "ckeditor5";
-import IncludeNote, {
+import ContentEmbed, {
CONVERT_EMBED_TO_LINK_COMMAND,
- INCLUDE_NOTE_MENU,
+ CONTENT_EMBED_MENU,
TOGGLE_CAPTION_COMMAND_NAME,
TOGGLE_TITLE_COMMAND_NAME
-} from "./includenote.js";
-import IncludeNoteBoxSizeDropdown from "./include_note_box_size_dropdown.js";
+} from "./content_embed.js";
+import ContentEmbedBoxSizeDropdown from "./content_embed_box_size_dropdown.js";
-export default class IncludeNoteToolbar extends Plugin {
+export default class ContentEmbedToolbar extends Plugin {
static get requires() {
- return [WidgetToolbarRepository, IncludeNote, IncludeNoteBoxSizeDropdown] as const;
+ return [WidgetToolbarRepository, ContentEmbed, ContentEmbedBoxSizeDropdown] as const;
}
afterInit() {
const editor = this.editor;
const widgetToolbarRepository = editor.plugins.get(WidgetToolbarRepository);
- widgetToolbarRepository.register("includeNote", {
+ widgetToolbarRepository.register("contentEmbed", {
items: [
- "includeNoteBoxSizeDropdown",
+ "contentEmbedBoxSizeDropdown",
TOGGLE_TITLE_COMMAND_NAME,
TOGGLE_CAPTION_COMMAND_NAME,
CONVERT_EMBED_TO_LINK_COMMAND,
- INCLUDE_NOTE_MENU
+ CONTENT_EMBED_MENU
],
balloonClassName: "ck-toolbar-container include-note-toolbar",
getRelatedElement(selection) {
const selectedElement = selection.getSelectedElement();
- if (selectedElement && isIncludeNoteWidget(selectedElement)) {
+ if (selectedElement && isContentEmbedWidget(selectedElement)) {
return selectedElement;
}
- // The toolbar stays on the include while its caption is edited.
+ // The toolbar stays on the embed while its caption is edited.
for (const ancestor of selection.getFirstPosition()?.getAncestors() ?? []) {
- if (ancestor.is("element") && isIncludeNoteWidget(ancestor)) {
+ if (ancestor.is("element") && isContentEmbedWidget(ancestor)) {
return ancestor;
}
}
@@ -47,6 +47,6 @@ export default class IncludeNoteToolbar extends Plugin {
}
-function isIncludeNoteWidget(element: ViewElement): boolean {
+function isContentEmbedWidget(element: ViewElement): boolean {
return isWidget(element) && element.hasClass("include-note");
}
diff --git a/packages/ckeditor5/src/plugins/file_upload/file_upload_ui.spec.ts b/packages/ckeditor5/src/plugins/file_upload/file_upload_ui.spec.ts
index 26c0ec2358..5b54b7a7ee 100644
--- a/packages/ckeditor5/src/plugins/file_upload/file_upload_ui.spec.ts
+++ b/packages/ckeditor5/src/plugins/file_upload/file_upload_ui.spec.ts
@@ -20,16 +20,16 @@ import FileUploadUI from "./file_upload_ui.js";
describe("FileUploadUI", () => {
let editor: ClassicEditor;
let command: Command;
- let includeCommand: Command;
+ let embedCommand: Command;
beforeEach(async () => {
editor = await createTestEditor([Essentials, Paragraph, FileUploadUI]);
command = new Command(editor);
command.refresh();
editor.commands.add("fileUpload", command);
- includeCommand = new Command(editor);
- includeCommand.refresh();
- editor.commands.add("insertIncludeNote", includeCommand);
+ embedCommand = new Command(editor);
+ embedCommand.refresh();
+ editor.commands.add("insertContentEmbed", embedCommand);
});
function createDropdown() {
@@ -120,12 +120,12 @@ describe("FileUploadUI", () => {
dropdown.destroy();
});
- it("follows the `fileUpload` command, and offers embeds only where an include can go", () => {
+ it("follows the `fileUpload` command, and offers embeds only where an embed can go", () => {
const { dropdown, actionView, items: [ linkItem, embedItem ] } = createDropdown();
expect([ dropdown.isEnabled, actionView.isEnabled ]).toEqual([ true, true ]);
expect([ linkItem.isEnabled, embedItem.isEnabled ]).toEqual([ true, true ]);
- includeCommand.forceDisabled("spec");
+ embedCommand.forceDisabled("spec");
expect([ linkItem.isEnabled, embedItem.isEnabled ]).toEqual([ true, false ]);
command.forceDisabled("spec");
diff --git a/packages/ckeditor5/src/plugins/file_upload/file_upload_ui.ts b/packages/ckeditor5/src/plugins/file_upload/file_upload_ui.ts
index faaad671c7..0756fc19b2 100644
--- a/packages/ckeditor5/src/plugins/file_upload/file_upload_ui.ts
+++ b/packages/ckeditor5/src/plugins/file_upload/file_upload_ui.ts
@@ -51,13 +51,13 @@ export default class FileUploadUI extends Plugin {
this.createListButton(locale, t("Attach file as a link"), bxLink, {})
];
- // Embedding goes wherever the "Include note" button can insert an include.
- const includeCommand = editor.commands.get("insertIncludeNote");
- if (includeCommand) {
+ // Embedding goes wherever the "Include note" button can insert an embed.
+ const embedCommand = editor.commands.get("insertContentEmbed");
+ if (embedCommand) {
const embedButton = this.createListButton(
locale, t("Attach and embed file"), bxShapeSquare, { asEmbed: true }
);
- embedButton.bind("isEnabled").to(includeCommand);
+ embedButton.bind("isEnabled").to(embedCommand);
buttons.push(embedButton);
}
diff --git a/packages/ckeditor5/src/plugins/file_upload/fileuploadcommand.spec.ts b/packages/ckeditor5/src/plugins/file_upload/fileuploadcommand.spec.ts
index 0c174fe9e7..7ea7e3cff4 100644
--- a/packages/ckeditor5/src/plugins/file_upload/fileuploadcommand.spec.ts
+++ b/packages/ckeditor5/src/plugins/file_upload/fileuploadcommand.spec.ts
@@ -15,7 +15,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
import { createTestEditor } from "../../../test/editor-kit.js";
import { installGlobMock } from "../../../test/globals-test-kit.js";
-import IncludeNote from "../includenote.js";
+import ContentEmbed from "../content_embed/content_embed.js";
import { isUploadAsLink } from "../uploadimage.js";
import FileUploadCommand from "./fileuploadcommand.js";
@@ -94,7 +94,7 @@ describe("FileUploadCommand", () => {
beforeEach(async () => {
editor = await createTestEditor([
- Essentials, Paragraph, FileRepository, ReferenceSchema, IncludeNote
+ Essentials, Paragraph, FileRepository, ReferenceSchema, ContentEmbed
]);
// Provide a minimal upload adapter so FileRepository.createLoader() succeeds.
@@ -164,10 +164,10 @@ describe("FileUploadCommand", () => {
expect(getModelData(editor.model)).toMatch(new RegExp(
"^<paragraph>foo</paragraph>" +
- "<includeNote boxSize=\"tiny\" uploadFileName=\"a.txt\" uploadId=\"\\w+\">" +
- "</includeNote>" +
- "<includeNote boxSize=\"medium\" uploadFileName=\"b.png\" uploadId=\"\\w+\">" +
- "</includeNote>" +
+ "<contentEmbed boxSize=\"tiny\" uploadFileName=\"a.txt\" uploadId=\"\\w+\">" +
+ "</contentEmbed>" +
+ "<contentEmbed boxSize=\"medium\" uploadFileName=\"b.png\" uploadId=\"\\w+\">" +
+ "</contentEmbed>" +
"<paragraph>\\[\\]bar</paragraph>$"
));
});
@@ -181,7 +181,7 @@ describe("FileUploadCommand", () => {
asEmbed: true
});
- expect(getModelData(editor.model)).toMatch(/^<includeNote boxSize="medium" /);
+ expect(getModelData(editor.model)).toMatch(/^<contentEmbed boxSize="medium" /);
});
it("marks the loader of every file to upload as a link, for an embed too", () => {
diff --git a/packages/ckeditor5/src/plugins/file_upload/fileuploadcommand.ts b/packages/ckeditor5/src/plugins/file_upload/fileuploadcommand.ts
index 72949bfaa3..d8f49bc2ab 100644
--- a/packages/ckeditor5/src/plugins/file_upload/fileuploadcommand.ts
+++ b/packages/ckeditor5/src/plugins/file_upload/fileuploadcommand.ts
@@ -67,7 +67,7 @@ function insertEmbedPlaceholder(
fileName: string,
boxSize: string
) {
- const placeholder = writer.createElement("includeNote", {
+ const placeholder = writer.createElement("contentEmbed", {
boxSize,
uploadId,
uploadFileName: fileName
diff --git a/packages/ckeditor5/src/plugins/file_upload/fileuploadediting.spec.ts b/packages/ckeditor5/src/plugins/file_upload/fileuploadediting.spec.ts
index f20f5ce265..bcbb78b9f3 100644
--- a/packages/ckeditor5/src/plugins/file_upload/fileuploadediting.spec.ts
+++ b/packages/ckeditor5/src/plugins/file_upload/fileuploadediting.spec.ts
@@ -21,7 +21,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
import { createTestEditor } from "../../../test/editor-kit.js";
import { installGlobMock } from "../../../test/globals-test-kit.js";
-import IncludeNote from "../includenote.js";
+import ContentEmbed from "../content_embed/content_embed.js";
import FileUploadEditing, {
isHtmlIncluded,
type FileUploadData,
@@ -590,16 +590,16 @@ class ReferenceSchema extends Plugin {
describe("FileUploadEditing with embeds", () => {
it("completes an embed placeholder with the attachment it uploaded", async () => {
- const loadIncludedAttachment = vi.fn();
+ const loadEmbeddedAttachment = vi.fn();
installGlobMock({
getComponentByEl: () => ({
getEmbedBoxSize: () => "small",
- loadIncludedAttachment
+ loadEmbeddedAttachment
})
});
const editor = await createTestEditor([
Essentials, Paragraph, FileRepository, Notification, Clipboard, ReferenceSchema,
- IncludeNote, FileUploadEditing
+ ContentEmbed, FileUploadEditing
]);
const controls = installUploadAdapter(editor);
setModelData(editor.model, "<paragraph>[]</paragraph>");
@@ -611,10 +611,10 @@ describe("FileUploadEditing with embeds", () => {
await waitFor(() => !getModelData(editor.model).includes("uploadId"));
expect(getModelData(editor.model)).toBe(
- "<includeNote attachmentId=\"att1\" boxSize=\"small\"></includeNote>" +
+ "<contentEmbed attachmentId=\"att1\" boxSize=\"small\"></contentEmbed>" +
"<paragraph>[]</paragraph>"
);
editor.editing.view.getDomRoot()?.querySelectorAll("div.include-note-wrapper");
- expect(loadIncludedAttachment).toHaveBeenCalledWith("att1", expect.anything(), "small");
+ expect(loadEmbeddedAttachment).toHaveBeenCalledWith("att1", expect.anything(), "small");
});
});
diff --git a/packages/ckeditor5/src/plugins/file_upload/fileuploadediting.ts b/packages/ckeditor5/src/plugins/file_upload/fileuploadediting.ts
index f711e3bf1b..3e4554142f 100644
--- a/packages/ckeditor5/src/plugins/file_upload/fileuploadediting.ts
+++ b/packages/ckeditor5/src/plugins/file_upload/fileuploadediting.ts
@@ -146,7 +146,7 @@ export default class FileUploadEditing extends Plugin {
} )
.then( data => {
model.enqueueChange( { isUndoable: false }, writer => {
- if ( fileElement.is( 'element', 'includeNote' ) ) {
+ if ( fileElement.is( 'element', 'contentEmbed' ) ) {
const attachmentId = getAttachmentId( data.default );
writer.setAttribute( 'attachmentId', attachmentId, fileElement );
} else {
@@ -211,5 +211,6 @@ export function isHtmlIncluded( dataTransfer: DataTransfer ) {
function getUploadPlaceholders( editor: Editor, item: ModelItem ) {
return Array.from( editor.model.createRangeOn( item ) )
.map( value => value.item )
- .filter( node => node.is( 'element', 'reference' ) || node.is( 'element', 'includeNote' ) );
+ .filter( node => node.is( 'element', 'reference' )
+ || node.is( 'element', 'contentEmbed' ) );
}
diff --git a/packages/ckeditor5/src/plugins/mention/slash_commands.spec.ts b/packages/ckeditor5/src/plugins/mention/slash_commands.spec.ts
index 37eb901701..0e6689367c 100644
--- a/packages/ckeditor5/src/plugins/mention/slash_commands.spec.ts
+++ b/packages/ckeditor5/src/plugins/mention/slash_commands.spec.ts
@@ -19,7 +19,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
import { createTestEditor } from "../../../test/editor-kit.js";
import { installGlobMock } from "../../../test/globals-test-kit.js";
-import { COMMAND_NAME as INCLUDE_NOTE_COMMAND } from "../includenote.js";
+import { COMMAND_NAME as CONTENT_EMBED_COMMAND } from "../content_embed/content_embed.js";
import { INSERT_ICON_COMMAND } from "../inline_icon/inline_icon_editing.js";
import InlineIconUI from "../inline_icon/inline_icon_ui.js";
import InsertDateTimePlugin, { COMMAND_NAME as INSERT_DATE_TIME_COMMAND, DATE_TIME_PRESETS } from "../insert_date_time.js";
@@ -624,7 +624,7 @@ describe("buildTriliumSlashCommands", () => {
[ "internal-link", "Internal link", INTERNAL_LINK_COMMAND ],
[ "attach-file", "Attach file as a link", "fileUpload" ],
[ "attach-and-embed-file", "Attach and embed file", "fileUpload" ],
- [ "include-note", "Include note", INCLUDE_NOTE_COMMAND ],
+ [ "content-embed", "Include note", CONTENT_EMBED_COMMAND ],
[ "page-break", "Page break", "pageBreak" ],
[ "markdown-import", "Markdown import", MARKDOWN_IMPORT_COMMAND ],
[ "icon", "Icon", INSERT_ICON_COMMAND ],
@@ -669,19 +669,19 @@ describe("buildTriliumSlashCommands", () => {
click.mockRestore();
});
- it("offers embedding a file only where both a file and an include can go", () => {
+ it("offers embedding a file only where both a file and an embed can go", () => {
const fileUpload = { isEnabled: true };
- const includeNote = { isEnabled: true };
+ const contentEmbed = { isEnabled: true };
const { fake } = makeFakeEditor({
- fileUpload, [INCLUDE_NOTE_COMMAND]: includeNote
+ fileUpload, [CONTENT_EMBED_COMMAND]: contentEmbed
});
const isEnabled = definition("attach-and-embed-file").isEnabled;
expect(isEnabled?.(fake)).toBe(true);
- includeNote.isEnabled = false;
+ contentEmbed.isEnabled = false;
expect(isEnabled?.(fake)).toBe(false);
- includeNote.isEnabled = true;
+ contentEmbed.isEnabled = true;
fileUpload.isEnabled = false;
expect(isEnabled?.(fake)).toBe(false);
diff --git a/packages/ckeditor5/src/plugins/mention/slash_commands.ts b/packages/ckeditor5/src/plugins/mention/slash_commands.ts
index 5ef2a925b1..d7a0ce6ec7 100644
--- a/packages/ckeditor5/src/plugins/mention/slash_commands.ts
+++ b/packages/ckeditor5/src/plugins/mention/slash_commands.ts
@@ -45,7 +45,7 @@ import internalLinkIcon from "../../icons/trilium.svg?raw";
import { ADMONITION_TYPE_NAMES, type AdmonitionType } from "../admonition/admonition_command.js";
import { getAdmonitionTitle } from "../admonition/admonition_ui.js";
import aiIcon from "../ai_assistant/theme/icons/ai.svg?raw";
-import { COMMAND_NAME as INCLUDE_NOTE_COMMAND } from "../includenote.js";
+import { COMMAND_NAME as CONTENT_EMBED_COMMAND } from "../content_embed/content_embed.js";
import { INSERT_ICON_COMMAND } from "../inline_icon/inline_icon_editing.js";
import InlineIconUI from "../inline_icon/inline_icon_ui.js";
import InsertDateTimePlugin, { COMMAND_NAME as INSERT_DATE_TIME_COMMAND, getDateTimeFormatOptions } from "../insert_date_time.js";
@@ -381,9 +381,9 @@ export function buildTriliumSlashCommands(editor: Editor): SlashCommandDefinitio
aliases: [ "attachment", "upload", "embed" ],
icon: IconPaperClip,
commandName: "fileUpload",
- // Embedding goes wherever the "Include note" button can insert an include.
+ // Embedding goes wherever the "Include note" button can insert an embed.
isEnabled: (target: Editor) => !!target.commands.get("fileUpload")?.isEnabled
- && !!target.commands.get(INCLUDE_NOTE_COMMAND)?.isEnabled,
+ && !!target.commands.get(CONTENT_EMBED_COMMAND)?.isEnabled,
execute: (target: Editor) => pickFiles("", (files) => {
target.execute("fileUpload", { file: files, asEmbed: true });
target.editing.view.focus();
@@ -398,11 +398,11 @@ export function buildTriliumSlashCommands(editor: Editor): SlashCommandDefinitio
execute: (target: Editor) => target.plugins.get(MathUI)._showUI()
},
{
- id: "include-note",
+ id: "content-embed",
title: t("Include note"),
description: t("Display the content of another note in this note"),
icon: noteIcon,
- commandName: INCLUDE_NOTE_COMMAND
+ commandName: CONTENT_EMBED_COMMAND
},
{
id: "page-break",
diff --git a/packages/ckeditor5/src/plugins/referencelink.ts b/packages/ckeditor5/src/plugins/referencelink.ts
index 4e5b7ba3a2..df75b0d9b7 100644
--- a/packages/ckeditor5/src/plugins/referencelink.ts
+++ b/packages/ckeditor5/src/plugins/referencelink.ts
@@ -92,7 +92,7 @@ export class ReferenceLinkEditing extends Plugin {
let attachmentId: unknown;
if ( item.is( 'element', 'reference' ) ) {
attachmentId = getAttachmentId( item.getAttribute( 'href' ) );
- } else if ( item.is( 'element', 'includeNote' ) ) {
+ } else if ( item.is( 'element', 'contentEmbed' ) ) {
attachmentId = item.getAttribute( 'attachmentId' );
} else {
continue;
diff --git a/packages/trilium-core/src/services/export/markdown.ts b/packages/trilium-core/src/services/export/markdown.ts
index 14587aab79..df10f50590 100644
--- a/packages/trilium-core/src/services/export/markdown.ts
+++ b/packages/trilium-core/src/services/export/markdown.ts
@@ -61,7 +61,7 @@ function toMarkdown(content: string, options: ToMarkdownOptions = {}) {
codeBlockStyle: "fenced",
headerlessTables,
blankReplacement(_content, node) {
- if (isIncludeNote(node)) {
+ if (isContentEmbed(node)) {
return node.outerHTML;
}
@@ -294,7 +294,7 @@ function buildFigureFilter(): Rule {
return {
filter(node, options) {
return (node.nodeName === "FIGURE" && node.classList.contains("image"))
- || isIncludeNote(node);
+ || isContentEmbed(node);
},
replacement(content, node) {
return (node as HTMLElement).outerHTML;
@@ -302,8 +302,8 @@ function buildFigureFilter(): Rule {
};
}
-/** Whether `node` is an include. Includes saved before captions existed are `<section>`s. */
-function isIncludeNote(node: Pick<LinkPreviewNodeLike, "nodeName" | "classList">) {
+/** Whether `node` is an embed. Embeds saved before captions existed are `<section>`s. */
+function isContentEmbed(node: Pick<LinkPreviewNodeLike, "nodeName" | "classList">) {
return (node.nodeName === "FIGURE" || node.nodeName === "SECTION")
&& node.classList.contains("include-note");
}
diff --git a/packages/trilium-core/src/share/content_renderer.spec.ts b/packages/trilium-core/src/share/content_renderer.spec.ts
index 8a7c579295..15cb60967e 100644
--- a/packages/trilium-core/src/share/content_renderer.spec.ts
+++ b/packages/trilium-core/src/share/content_renderer.spec.ts
@@ -45,7 +45,7 @@ describe("content_renderer", () => {
expect(result.content).toStrictEqual(content);
});
- it("renders included notes", () => {
+ it("renders embedded notes", () => {
buildShareNotes([
{ id: "subnote1", content: `<p>Foo</p><div>Bar</div>` },
{ id: "subnote2", content: `<strong>Baz</strong>` }
@@ -68,14 +68,14 @@ describe("content_renderer", () => {
`);
});
- it("keeps the caption of an include under its content, except on a Tiny one", () => {
+ it("keeps the caption of an embed under its content, except on a Tiny one", () => {
buildShareNotes([ { id: "subnote1", content: `<p>Foo</p>` } ]);
- const include = (boxSize: string) =>
+ const embed = (boxSize: string) =>
`<figure class="include-note" data-note-id="subnote1" data-box-size="${boxSize}">`
+ `<figcaption>A <strong>caption</strong></figcaption></figure>`;
const note = buildShareNote({
id: "note1",
- content: include("medium") + include("tiny")
+ content: embed("medium") + embed("tiny")
});
expect(getContent(note).content).toStrictEqual(
@@ -85,7 +85,7 @@ describe("content_renderer", () => {
);
});
- it("renders only the first level of nested includes on the share view (nested include becomes a reference link)", () => {
+ it("renders only the first level of nested embeds on the share view (nested embed becomes a reference link)", () => {
buildShareNote({ id: "nestC2", title: "Note C", content: "<p>C body</p>" });
buildShareNote({
id: "nestB2",
@@ -105,7 +105,7 @@ describe("content_renderer", () => {
expect(result.content).toContain("Note C");
});
- it("expands nested includes recursively when exporting (expandNestedIncludes)", () => {
+ it("expands nested embeds recursively when exporting (expandNestedEmbeds)", () => {
buildShareNote({ id: "expC", title: "Note C", content: "<p>C body</p>" });
buildShareNote({
id: "expB",
@@ -115,7 +115,7 @@ describe("content_renderer", () => {
id: "expA",
content: `<p>A body</p><section class="include-note" data-note-id="expB" data-box-size="medium">&nbsp;</section>`
});
- const result = getContent(noteA, { expandNestedIncludes: true });
+ const result = getContent(noteA, { expandNestedEmbeds: true });
if (typeof result.content !== "string") throw new Error("expected string content");
expect(result.content).toContain("B body");
expect(result.content).toContain("C body");
@@ -130,14 +130,14 @@ describe("content_renderer", () => {
id: "dagA",
content: `<section class="include-note" data-note-id="dagB" data-box-size="medium">&nbsp;</section><section class="include-note" data-note-id="dagC" data-box-size="medium">&nbsp;</section>`
});
- const result = getContent(noteA, { expandNestedIncludes: true });
+ const result = getContent(noteA, { expandNestedEmbeds: true });
if (typeof result.content !== "string") throw new Error("expected string content");
// Diamond A→{B,C}→D: D is not a cycle, so it expands in both branches.
expect((result.content.match(/D body/g) ?? []).length).toBe(2);
expect(result.content).not.toContain("reference-link");
});
- it("does not loop on a circular include chain when expanding recursively", () => {
+ it("does not loop on a circular embed chain when expanding recursively", () => {
buildShareNote({
id: "cycB",
content: `<p>B body</p><section class="include-note" data-note-id="cycA" data-box-size="medium">&nbsp;</section>`
@@ -146,15 +146,15 @@ describe("content_renderer", () => {
id: "cycA",
content: `<p>A body</p><section class="include-note" data-note-id="cycB" data-box-size="medium">&nbsp;</section>`
});
- const result = getContent(noteA, { expandNestedIncludes: true });
+ const result = getContent(noteA, { expandNestedEmbeds: true });
if (typeof result.content !== "string") throw new Error("expected string content");
- // A expands B; B's re-include of A is broken by the cycle guard (reference link), no hang.
+ // A expands B; B's re-embed of A is broken by the cycle guard (reference link), no hang.
expect(result.content).toContain("A body");
expect(result.content).toContain("B body");
expect(result.content).toContain("reference-link");
});
- it("replaces an include of a shareCredentials-protected note with a placeholder when the caller lacks access", () => {
+ it("replaces an embed of a shareCredentials-protected note with a placeholder when the caller lacks access", () => {
buildShareNote({
id: "credSecret",
title: "Quarterly figures",
@@ -166,20 +166,20 @@ describe("content_renderer", () => {
content: `<p>public</p><section class="include-note" data-note-id="credSecret" data-box-size="medium">&nbsp;</section>`
});
- const denied = getContent(host, { canAccessInclude: (note) => note.getCredentials().length === 0 });
+ const denied = getContent(host, { canAccessEmbed: (note) => note.getCredentials().length === 0 });
if (typeof denied.content !== "string") throw new Error("expected string content");
expect(denied.content).toContain("public");
expect(denied.content).not.toContain("secret body");
- // The title is withheld as well: an included note need not be visible in the share tree.
+ // The title is withheld as well: an embedded note need not be visible in the share tree.
expect(denied.content).not.toContain("Quarterly figures");
expect(denied.content).toContain("include-note-forbidden");
- const allowed = getContent(host, { canAccessInclude: () => true });
+ const allowed = getContent(host, { canAccessEmbed: () => true });
if (typeof allowed.content !== "string") throw new Error("expected string content");
expect(allowed.content).toContain("secret body");
});
- it("applies the include access check at every nesting level and to the reference-link fallback", () => {
+ it("applies the embed access check at every nesting level and to the reference-link fallback", () => {
buildShareNote({
id: "credDeep",
title: "Deep secret",
@@ -194,11 +194,11 @@ describe("content_renderer", () => {
id: "credOuter",
content: `<section class="include-note" data-note-id="credMiddle" data-box-size="medium">&nbsp;</section>`
});
- const canAccessInclude = (note: SNote) => note.getCredentials().length === 0;
+ const canAccessEmbed = (note: SNote) => note.getCredentials().length === 0;
// Live share view: the second level would degrade to a reference link, which must not
// leak the protected note's title either.
- const shareView = getContent(host, { canAccessInclude });
+ const shareView = getContent(host, { canAccessEmbed });
if (typeof shareView.content !== "string") throw new Error("expected string content");
expect(shareView.content).toContain("middle body");
expect(shareView.content).not.toContain("deep body");
@@ -206,7 +206,7 @@ describe("content_renderer", () => {
expect(shareView.content).not.toContain("reference-link");
// Recursive expansion carries the check down with it.
- const expanded = getContent(host, { expandNestedIncludes: true, canAccessInclude });
+ const expanded = getContent(host, { expandNestedEmbeds: true, canAccessEmbed });
if (typeof expanded.content !== "string") throw new Error("expected string content");
expect(expanded.content).toContain("middle body");
expect(expanded.content).not.toContain("deep body");
@@ -247,7 +247,7 @@ describe("content_renderer", () => {
expect(result.content).not.toContain("reference-link");
});
- it("renders an included large code note without hanging or re-parsing it as HTML (#9717)", () => {
+ it("renders an embedded large code note without hanging or re-parsing it as HTML (#9717)", () => {
// ~2 MiB of angle-bracket-heavy code that previously exploded node-html-parser.
const codeLine = `const x: Array<Map<string, List<number>>> = a < b && c > d; // <div>\n`;
const bigCode = codeLine.repeat(Math.ceil((2 * 1024 * 1024) / codeLine.length));
@@ -327,7 +327,7 @@ describe("content_renderer", () => {
expect(auto.innerHTML).toContain("hljs-tag");
});
- it("highlights an included code note in its own language", async () => {
+ it("highlights an embedded code note in its own language", async () => {
await ensureShareHighlighting();
buildShareNotes([
{ id: "pycode", type: "code", mime: "text/x-python", content: `<t t-name="x"></t>` }
diff --git a/packages/trilium-core/src/share/content_renderer.ts b/packages/trilium-core/src/share/content_renderer.ts
index 68f1c13ec7..5894037015 100644
--- a/packages/trilium-core/src/share/content_renderer.ts
+++ b/packages/trilium-core/src/share/content_renderer.ts
@@ -37,7 +37,7 @@ export const assetUrlFragment = `assets/v${appInfo.appVersion}`;
* Maximum number of lines a code block may have before server-side syntax highlighting is skipped.
* Mirrors the editor's per-block cutoff (HIGHLIGHT_MAX_BLOCK_COUNT in the ckeditor5 syntax
* highlighting plugin); beyond it `highlightAuto` is too slow and would block the event loop on
- * large shared/included code notes (#9717).
+ * large shared/embedded code notes (#9717).
*/
const HIGHLIGHT_MAX_LINE_COUNT = 500;
@@ -139,7 +139,7 @@ export function renderNoteForExport(note: BNote, parentBranch: BBranch, basePath
});
}
-export function renderNoteContent(note: SNote, canAccessInclude?: CanAccessInclude) {
+export function renderNoteContent(note: SNote, canAccessEmbed?: CanAccessEmbed) {
const subRoot = getSharedSubTreeRoot(note);
const ancestors: string[] = [];
@@ -183,7 +183,7 @@ export function renderNoteContent(note: SNote, canAccessInclude?: CanAccessInclu
logoUrl,
ancestors,
isStatic: false,
- canAccessInclude,
+ canAccessEmbed,
faviconUrl: note.hasRelation("shareFavicon") ? `api/notes/${note.getRelationValue("shareFavicon")}/download` : `../favicon.ico`,
iconPackCss: [
...iconPacks.map(p => iconPackService.generateCss(p, p.builtin
@@ -207,7 +207,7 @@ interface RenderArgs {
logoUrl: string;
ancestors: string[];
isStatic: boolean;
- canAccessInclude?: CanAccessInclude;
+ canAccessEmbed?: CanAccessEmbed;
faviconUrl: string;
iconPackCss: string;
iconPackSupportedPrefixes: string[];
@@ -223,10 +223,10 @@ function renderNoteContentInternal(note: SNote | BNote, renderArgs: RenderArgs)
return note.getContent() ?? "";
}
- // Static export preserves full include-note nesting; the live share view renders only the first level.
+ // Static export preserves full embed nesting; the live share view renders only the first level.
const { header, content, isEmpty } = getContent(note, {
- expandNestedIncludes: renderArgs.isStatic,
- canAccessInclude: renderArgs.canAccessInclude
+ expandNestedEmbeds: renderArgs.isStatic,
+ canAccessEmbed: renderArgs.canAccessEmbed
});
const showLoginInShareTheme = options.getOptionBool("showLoginInShareTheme");
const opts = {
@@ -301,27 +301,27 @@ function getShareAssetPath() {
}
/**
- * Decides whether the caller is allowed to read a note that an include pulls in. The share routes
- * pass their `shareCredentials` check here so that an include cannot hand out a note the same
+ * Decides whether the caller is allowed to read a note that an embed pulls in. The share routes
+ * pass their `shareCredentials` check here so that an embed cannot hand out a note the same
* caller would be refused on a direct request. Omitted by the static export, whose caller is the
* already-authenticated instance owner.
*/
-export type CanAccessInclude = (note: SNote) => boolean;
+export type CanAccessEmbed = (note: SNote) => boolean;
export interface ShareRenderOptions {
/**
- * Keep expanding includes recursively at every depth. Used for static export, which
+ * Keep expanding embeds recursively at every depth. Used for static export, which
* preserves full nesting. When false (the default for the on-screen share view), only the first
- * level of inclusion is rendered and deeper includes are replaced with a reference
+ * level of embedding is rendered and deeper embeds are replaced with a reference
* link.
*/
- expandNestedIncludes?: boolean;
- /** Internal: render this note's own includes as reference links instead of expanding. */
- includesAsReferenceLinks?: boolean;
- /** Internal: note IDs already rendered on the current include path, used as a recursion cycle guard. */
+ expandNestedEmbeds?: boolean;
+ /** Internal: render this note's own embeds as reference links instead of expanding. */
+ embedsAsReferenceLinks?: boolean;
+ /** Internal: note IDs already rendered on the current embed path, used as a recursion cycle guard. */
seenNoteIds?: Set<string>;
- /** See {@link CanAccessInclude}. When omitted, every included note is expanded. */
- canAccessInclude?: CanAccessInclude;
+ /** See {@link CanAccessEmbed}. When omitted, every embedded note is expanded. */
+ canAccessEmbed?: CanAccessEmbed;
}
export function getContent(note: SNote | BNote, options: ShareRenderOptions = {}) {
@@ -478,10 +478,10 @@ function renderText(result: Result, note: SNote | BNote, options: ShareRenderOpt
}
}
- // Process include notes. The share view renders only the first level of inclusion; static export
- // (expandNestedIncludes) keeps expanding recursively. seenNoteIds tracks the current ancestor
+ // Process embeds. The share view renders only the first level of embedding; static export
+ // (expandNestedEmbeds) keeps expanding recursively. seenNoteIds tracks the current ancestor
// path (cloned per descent below) so the recursive path can break cycles without treating a note
- // included in two sibling sub-trees as circular.
+ // embedded in two sibling sub-trees as circular.
const getNote: GetNoteFunction = note instanceof BNote
? (noteId: string) => becca.getNote(noteId)
: (noteId: string) => shaca.getNote(noteId);
@@ -491,50 +491,50 @@ function renderText(result: Result, note: SNote | BNote, options: ShareRenderOpt
const seenNoteIds = new Set(options.seenNoteIds);
seenNoteIds.add(note.noteId);
- for (const includeNoteEl of document.querySelectorAll(".include-note")) {
- const attachmentId = includeNoteEl.getAttribute("data-attachment-id");
+ for (const embedEl of document.querySelectorAll(".include-note")) {
+ const attachmentId = embedEl.getAttribute("data-attachment-id");
if (attachmentId) {
const attachment = getAttachment(attachmentId);
- const asLink = !!options.includesAsReferenceLinks;
+ const asLink = !!options.embedsAsReferenceLinks;
const html = attachment ? renderAttachmentEmbed(attachmentId, attachment, asLink) : "";
const embed = parse(html, parseOpts).childNodes;
if (attachment && !asLink && isImageAttachmentRole(attachment.role)) {
- replaceIncludeContent(includeNoteEl, embed);
+ replaceEmbedContent(embedEl, embed);
} else {
- includeNoteEl.replaceWith(...embed);
+ embedEl.replaceWith(...embed);
}
continue;
}
- const noteId = includeNoteEl.getAttribute("data-note-id");
+ const noteId = embedEl.getAttribute("data-note-id");
if (!noteId) continue;
- const includedNote = shaca.getNote(noteId);
- if (!includedNote) continue;
+ const embeddedNote = shaca.getNote(noteId);
+ if (!embeddedNote) continue;
- // An include must not disclose what a direct request for the same note would refuse: a note
+ // An embed must not disclose what a direct request for the same note would refuse: a note
// carrying `shareCredentials` the caller has not presented becomes a placeholder, and its
- // title is withheld too, since an included note need not appear in the visible share tree.
- if (options.canAccessInclude && !options.canAccessInclude(includedNote)) {
- includeNoteEl.replaceWith(...parse(`<p class="include-note-forbidden">${escapeHtml(t("content_renderer.included-note-requires-credentials"))}</p>`, parseOpts).childNodes);
+ // title is withheld too, since an embedded note need not appear in the visible share tree.
+ if (options.canAccessEmbed && !options.canAccessEmbed(embeddedNote)) {
+ embedEl.replaceWith(...parse(`<p class="include-note-forbidden">${escapeHtml(t("content_renderer.included-note-requires-credentials"))}</p>`, parseOpts).childNodes);
continue;
}
- // Deeper-than-first-level includes (and any cycle in the recursive path) degrade to a
+ // Deeper-than-first-level embeds (and any cycle in the recursive path) degrade to a
// reference link that the link-processing passes below resolve to the shared note.
- if (options.includesAsReferenceLinks || seenNoteIds.has(noteId)) {
- includeNoteEl.replaceWith(...parse(`<a class="reference-link" href="#root/${escapeHtml(noteId)}">${escapeHtml(includedNote.title)}</a>`, parseOpts).childNodes);
+ if (options.embedsAsReferenceLinks || seenNoteIds.has(noteId)) {
+ embedEl.replaceWith(...parse(`<a class="reference-link" href="#root/${escapeHtml(noteId)}">${escapeHtml(embeddedNote.title)}</a>`, parseOpts).childNodes);
continue;
}
- const includedResult = getContent(includedNote, options.expandNestedIncludes
- ? { expandNestedIncludes: true, seenNoteIds: new Set(seenNoteIds), canAccessInclude: options.canAccessInclude }
- : { includesAsReferenceLinks: true, seenNoteIds: new Set(seenNoteIds), canAccessInclude: options.canAccessInclude });
- if (typeof includedResult.content !== "string") continue;
+ const embeddedResult = getContent(embeddedNote, options.expandNestedEmbeds
+ ? { expandNestedEmbeds: true, seenNoteIds: new Set(seenNoteIds), canAccessEmbed: options.canAccessEmbed }
+ : { embedsAsReferenceLinks: true, seenNoteIds: new Set(seenNoteIds), canAccessEmbed: options.canAccessEmbed });
+ if (typeof embeddedResult.content !== "string") continue;
- const includedDocument = parse(includedResult.content, parseOpts).childNodes;
- if (includedDocument) {
- replaceIncludeContent(includeNoteEl, includedDocument);
+ const embeddedDocument = parse(embeddedResult.content, parseOpts).childNodes;
+ if (embeddedDocument) {
+ replaceEmbedContent(embedEl, embeddedDocument);
}
}
@@ -581,20 +581,20 @@ function renderText(result: Result, note: SNote | BNote, options: ShareRenderOpt
* The markup that stands in for an embedded attachment: a picture as an image, anything else as the
* attachment link that `handleAttachmentLink` then resolves.
*
- * @param asLink renders a picture as a link too, for an embed below the first level of inclusion.
+ * @param asLink renders a picture as a link too, for an embed below the first level of embedding.
*/
/**
- * Puts `content` in place of an include. An include with a caption stays a `<figure>`, holding
+ * Puts `content` in place of an embed. An embed with a caption stays a `<figure>`, holding
* `content` and then the caption.
*/
-function replaceIncludeContent(includeNoteEl: HTMLElement, content: ParsedNode[]) {
- const caption = includeNoteEl.getAttribute("data-box-size") !== "tiny"
- && includeNoteEl.childNodes.find((child) =>
+function replaceEmbedContent(embedEl: HTMLElement, content: ParsedNode[]) {
+ const caption = embedEl.getAttribute("data-box-size") !== "tiny"
+ && embedEl.childNodes.find((child) =>
child instanceof HTMLElement && child.tagName === "FIGCAPTION");
if (caption) {
- includeNoteEl.set_content([ ...content, caption ]);
+ embedEl.set_content([ ...content, caption ]);
} else {
- includeNoteEl.replaceWith(...content);
+ embedEl.replaceWith(...content);
}
}
@@ -818,7 +818,7 @@ export function renderCode(result: Result, mime?: string) {
result.isEmpty = true;
} else {
// Escape the raw code so that any `<`/`>` it contains are not later re-parsed as HTML.
- // When such a code note is included into a shared text note, renderText re-parses the
+ // When such a code note is embedded into a shared text note, renderText re-parses the
// resulting HTML; with unescaped angle brackets (e.g. generics, comparisons, JSX) a large
// code note would explode into a pathological node-html-parser tree and hang the event
// loop (#9717). The <code> wrapper and its `language-*` class additionally let renderText
diff --git a/packages/trilium-core/src/share/handlers.ts b/packages/trilium-core/src/share/handlers.ts
index 8fa836e013..88e3a1e764 100644
--- a/packages/trilium-core/src/share/handlers.ts
+++ b/packages/trilium-core/src/share/handlers.ts
@@ -154,7 +154,7 @@ function renderNote(note: SNote | undefined, req: ShareRequest): ShareReply {
return {
status: 200,
headers,
- body: renderNoteContent(note, (includedNote) => hasCredentialAccess(includedNote, req))
+ body: renderNoteContent(note, (embeddedNote) => hasCredentialAccess(embeddedNote, req))
};
}