Skip to content

Build your personal knowledge base with Trilium Notes

client/text editor/include notes: extend the context menu

Adorian Doran250973c730cd
diff --git a/apps/client/src/menus/link_context_menu.spec.ts b/apps/client/src/menus/link_context_menu.spec.ts
index 40c4dd5db3..9301f9e492 100644
--- a/apps/client/src/menus/link_context_menu.spec.ts
+++ b/apps/client/src/menus/link_context_menu.spec.ts
@@ -1,5 +1,6 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
+import type { ViewScope } from "../services/link";
import type { ContextMenuEvent } from "./context_menu";
const mocks = vi.hoisted(() => ({
@@ -40,6 +41,7 @@ vi.mock("../services/i18n", () => ({ t: (key: string) => key }));
vi.mock("../services/utils", () => ({
default: { isDesktop: mocks.isDesktop },
+ escapeHtml: (text: string) => text,
isMobile: mocks.isMobile
}));
@@ -309,94 +311,178 @@ describe("openContextMenu", () => {
expect(mocks.getTextEditorContaining).toHaveBeenCalledTimes(1);
});
- describe("from the title row of an attachment embed", () => {
+ describe("opened on an include in a note being edited", () => {
+ const CHECK = "bx bx-check";
const execute = vi.fn();
+ const focus = vi.fn();
const selectIncludeAt = vi.fn();
let hasPlugin = true;
- let hasCommand = true;
+ let state: Record<string, unknown> | null;
let editable: HTMLElement;
beforeEach(() => {
selectIncludeAt.mockReset().mockReturnValue(true);
- execute.mockClear();
hasPlugin = true;
- hasCommand = true;
+ state = {
+ boxSize: "medium", isTitleShown: false, isTitleToggleable: true,
+ hasCaption: true, isCaptionToggleable: true, isConvertibleToLink: true
+ };
mocks.getAttachmentOfNote.mockResolvedValue({ attachmentId: "att-1" });
mocks.getAttachmentActionGroups.mockReturnValue([
- [ { title: "Download", icon: "bx bx-download", run: vi.fn() } ]
+ [ { title: "Download", icon: "bx bx-download", run: vi.fn() } ],
+ [ { title: "Rename", icon: "bx bx-rename", run: vi.fn() } ]
]);
mocks.getTextEditorContaining.mockResolvedValue({
- plugins: { has: () => hasPlugin, get: () => ({ selectIncludeAt }) },
- commands: {
- get: (name: string) => (hasCommand && name === "convertEmbedToLink"
- ? { isEnabled: true }
- : undefined)
+ plugins: {
+ has: () => hasPlugin,
+ get: () => ({
+ selectIncludeAt,
+ getIncludeStateAt: () => state,
+ getBoxSizes: () => [
+ { value: "tiny", label: "Tiny" },
+ { value: "medium", label: "Medium" }
+ ]
+ })
},
- execute
+ commands: { get: () => undefined },
+ execute,
+ editing: { view: { focus } }
});
editable = document.createElement("div");
editable.className = "ck-editor__editable";
editable.setAttribute("contenteditable", "true");
- editable.innerHTML = `<section class="include-note" data-attachment-id="att-1">`
+ editable.innerHTML = `<figure class="include-note" data-attachment-id="att-1">`
+ `<div class="include-note-title-row">`
+ `<h4 class="include-note-title"><span><a href="#">report.pdf</a></span></h4>`
- + `<button class="include-note-menu"></button></div></section>`;
+ + `<button class="include-note-menu"></button></div>`
+ + `<div class="include-note-content"><a class="reference-link" href="#">x</a></div>`
+ + `</figure>`;
});
- /** Opens the menu as right-clicking `selector`, the title link by default, does. */
- async function openOnTitle(selector = "a") {
- const target = editable.querySelector<HTMLElement>(selector) ?? undefined;
- await linkContextMenu.openContextMenu("root/n1", contextMenuEvent(target), VIEW_SCOPE);
+ function include() {
+ const figure = editable.querySelector<HTMLElement>("figure");
+ if (!figure) throw new Error("Expected an include.");
+ return figure;
+ }
+
+ /** Opens the menu from `target`, as right-clicking the title link does by default. */
+ async function openOn(target: Element | null, viewScope: ViewScope = VIEW_SCOPE) {
+ await linkContextMenu.openContextMenu(
+ "root/n1", contextMenuEvent((target ?? undefined) as HTMLElement | undefined),
+ viewScope
+ );
return mocks.show.mock.lastCall?.[0].items;
}
- it("ends the menu with converting the embed, selected only once chosen", async () => {
- const titleRow = editable.querySelector(".include-note-title-row");
+ /** Picks `item`, and returns what it ran on the editor. */
+ function pick(item: { handler: () => void }) {
+ execute.mockClear();
+ focus.mockClear();
+ selectIncludeAt.mockClear();
+ item.handler();
+ expect(selectIncludeAt).toHaveBeenCalledWith(include());
+ expect(focus).toHaveBeenCalledOnce();
+ return execute.mock.calls;
+ }
- // Right-clicking the title, then pressing the menu button beside it.
- for (const selector of [ "a", "button.include-note-menu" ]) {
- selectIncludeAt.mockClear();
- execute.mockClear();
- const items = await openOnTitle(selector);
+ 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.
+ for (const target of [ "a", "button.include-note-menu", "figure" ]) {
+ const items = await openOn(editable.querySelector(target));
- expect(items.slice(4)).toMatchObject([
+ expect(items.slice(4), target).toMatchObject([
{ kind: "separator" },
{ title: "Download" },
+ { kind: "separator" },
+ {
+ title: "link_context_menu.include_size",
+ uiIcon: "bx bx-expand-vertical",
+ items: [
+ { title: "Tiny", trailingIcon: undefined },
+ { title: "Medium", trailingIcon: CHECK }
+ ]
+ },
+ {
+ title: "link_context_menu.show_title",
+ uiIcon: "bx bx-window-alt",
+ enabled: true,
+ trailingIcon: undefined
+ },
+ {
+ title: "link_context_menu.show_caption",
+ uiIcon: "bx bx-captions",
+ enabled: true,
+ trailingIcon: CHECK
+ },
+ { kind: "separator" },
+ { title: "Rename" },
{ title: "link_context_menu.convert_embed_to_link", uiIcon: "bx bx-link" }
]);
- expect(selectIncludeAt).not.toHaveBeenCalled();
-
- items.at(-1).handler();
- expect(selectIncludeAt).toHaveBeenCalledWith(titleRow);
- expect(execute).toHaveBeenCalledWith("convertEmbedToLink");
+ expect(items).toHaveLength(13);
}
+ expect(selectIncludeAt).not.toHaveBeenCalled();
- // An embed the editor cannot select is left as it is.
+ const items = await openOn(editable.querySelector("a"));
+ expect(pick(items[7].items[0]))
+ .toEqual([ [ "includeNoteBoxSize", { value: "tiny" } ] ]);
+ expect(pick(items[8])).toEqual([ [ "toggleIncludeNoteTitle", undefined ] ]);
+ expect(pick(items[9]))
+ .toEqual([ [ "toggleIncludeNoteCaption", { focusCaptionOnShow: true } ] ]);
+ expect(pick(items[12])).toEqual([ [ "convertEmbedToLink", undefined ] ]);
+
+ // An include the editor cannot select is left as it is.
selectIncludeAt.mockReturnValue(false);
execute.mockClear();
- (await openOnTitle()).at(-1).handler();
+ items[12].handler();
expect(execute).not.toHaveBeenCalled();
});
- it("leaves it out in a read-only note, or outside an attachment embed", async () => {
- hasPlugin = false;
- expect(await openOnTitle()).toHaveLength(6);
+ 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");
- hasPlugin = true;
- hasCommand = false;
- expect(await openOnTitle()).toHaveLength(6);
+ const items = await openOn(editable.querySelector("a"), {});
- hasCommand = true;
- const section = editable.querySelector("section");
- section?.removeAttribute("data-attachment-id");
- expect(await openOnTitle()).toHaveLength(6);
- expect(mocks.getTextEditorContaining).toHaveBeenCalledTimes(3);
+ expect(items.slice(4)).toMatchObject([
+ { kind: "separator" },
+ { title: "link_context_menu.include_size" },
+ { title: "link_context_menu.show_title" },
+ { title: "link_context_menu.show_caption" },
+ { kind: "separator" },
+ { title: "link_context_menu.convert_embed_to_link" }
+ ]);
+ expect(items).toHaveLength(10);
+ expect(mocks.getAttachmentOfNote).not.toHaveBeenCalled();
+ });
+
+ it("disables what the include cannot do, and offers nothing for no include", async () => {
+ include().removeAttribute("data-attachment-id");
+ state = {
+ boxSize: "tiny", isTitleShown: true, isTitleToggleable: false,
+ hasCaption: false, isCaptionToggleable: false, isConvertibleToLink: false
+ };
+ expect((await openOn(editable.querySelector("a"), {})).slice(4)).toMatchObject([
+ { kind: "separator" },
+ { title: "link_context_menu.include_size" },
+ { title: "link_context_menu.show_title", enabled: false, trailingIcon: CHECK },
+ { 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.
+ expect(await openOn(editable.querySelector(".include-note-content a"), {}))
+ .toHaveLength(4);
+ state = null;
+ expect(await openOn(editable.querySelector("a"), {})).toHaveLength(4);
+ hasPlugin = false;
+ expect(await openOn(editable.querySelector("a"), {})).toHaveLength(4);
+ expect(mocks.getTextEditorContaining).toHaveBeenCalledTimes(4);
// A read-only note is not looked up in the editor at all.
- section?.setAttribute("data-attachment-id", "att-1");
editable.removeAttribute("contenteditable");
- expect(await openOnTitle()).toHaveLength(6);
- expect(mocks.getTextEditorContaining).toHaveBeenCalledTimes(3);
+ expect(await openOn(editable.querySelector("a"), {})).toHaveLength(4);
+ expect(mocks.getTextEditorContaining).toHaveBeenCalledTimes(4);
expect(selectIncludeAt).not.toHaveBeenCalled();
});
});
diff --git a/apps/client/src/menus/link_context_menu.ts b/apps/client/src/menus/link_context_menu.ts
index 8297f5c131..336fe15afe 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 } from "@triliumnext/ckeditor5";
+import type { CKTextEditor, IncludeNoteState } from "@triliumnext/ckeditor5";
import type { GeoMouseEvent } from "../widgets/collections/geomap/map.js";
@@ -7,9 +7,10 @@ import type FAttachment from "../entities/fattachment.js";
import froca from "../services/froca.js";
import { t } from "../services/i18n.js";
import type { ViewScope } from "../services/link.js";
-import utils, { isMobile } from "../services/utils.js";
+import utils, { escapeHtml, isMobile } from "../services/utils.js";
import { getClosestNtxId } from "../widgets/widget_utils.js";
import contextMenu, { type ContextMenuOptions, type MenuItem } from "./context_menu.js";
+import { submenuItem } from "./context_menu_utils.js";
import { getTextEditorContaining } from "./text_editor_context_menu.js";
/**
@@ -18,6 +19,15 @@ 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 {
+ editor: CKTextEditor;
+ element: Element;
+ state: IncludeNoteState;
+}
+
+const CHECK_ICON = "bx bx-check";
+
let lastMenuRequest = 0;
async function openContextMenu(
@@ -29,7 +39,10 @@ async function openContextMenu(
const request = ++lastMenuRequest;
const noteId = notePath.split("/").at(-1) ?? notePath;
const editor = await getEditingTextEditor(getTarget(e));
- const attachmentItems = await getAttachmentItems(noteId, viewScope, e, editor);
+ const include = editor && getMenuInclude(e, editor);
+ const ownItems = viewScope.viewMode === "attachments" && viewScope.attachmentId
+ ? await getAttachmentItems(noteId, viewScope.attachmentId, e, editor, include)
+ : getIncludedNoteItems(include);
// A later right-click opened its own menu while this one waited for the editor or the
// attachment.
if (request !== lastMenuRequest) {
@@ -39,7 +52,7 @@ async function openContextMenu(
contextMenu.show({
x: e.pageX,
y: e.pageY,
- items: [ ...getItems(e), ...attachmentItems ],
+ items: [ ...getItems(e), ...ownItems ],
selectMenuItemHandler: ({ command }) => handleLinkContextMenuItem(command, e, notePath, viewScope, hoistedNoteId),
...(editor ? keepEditorFocused(editor) : {})
});
@@ -136,17 +149,17 @@ function handleLinkContextMenuItem(command: string | undefined, e: LinkMenuOrigi
return false;
}
-/** The actions on the attachment a link points to, each group after a separator. */
+/**
+ * The actions on the attachment a link points to, each group after a separator. A menu opened on
+ * an embed of it has the commands of the embed after the first group.
+ */
async function getAttachmentItems(
noteId: string,
- { viewMode, attachmentId }: ViewScope,
+ attachmentId: string,
e: LinkMenuOrigin,
- editor: CKTextEditor | null
+ editor: CKTextEditor | null,
+ include: MenuInclude | null
): Promise<MenuItem<CommandNames>[]> {
- if (viewMode !== "attachments" || !attachmentId) {
- return [];
- }
-
// Imported on demand: `attachment_actions` imports `link`, which imports this module.
const [ attachment, { getAttachmentActionGroups } ] = await Promise.all([
froca.getAttachmentOfNote(noteId, attachmentId),
@@ -156,23 +169,104 @@ async function getAttachmentItems(
return [];
}
- const groups = getAttachmentActionGroups(attachment);
- const actionItems = groups.flatMap((group): MenuItem<CommandNames>[] => [
- { kind: "separator" },
- ...group.map((action) => ({
+ const [ firstGroup = [], ...otherGroups ] = getAttachmentActionGroups(attachment)
+ .map((group) => group.map((action): MenuItem<CommandNames> => ({
title: action.title,
uiIcon: action.icon,
enabled: !action.disabledReason,
handler: () => void action.run()
- }))
- ]);
+ })));
+ const groups = [ firstGroup, include ? getIncludeItems(include) : [], ...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, getConvertToLinkItem(e, editor) ]
- .filter((item) => item !== null);
+ const conversionItems = [ embedItem, include && getConvertToLinkItem(include) ]
+ .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
+ * converting it in another.
+ */
+function getIncludedNoteItems(include: MenuInclude | null): MenuItem<CommandNames>[] {
+ if (!include) {
+ return [];
+ }
+
+ const linkItem = getConvertToLinkItem(include);
+ return [
+ { kind: "separator" },
+ ...getIncludeItems(include),
+ ...(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.
+ */
+function getMenuInclude(e: LinkMenuOrigin, editor: CKTextEditor): MenuInclude | 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")) {
+ return null;
+ }
+
+ const state = editor.plugins.get("IncludeNote").getIncludeStateAt(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()
+ .map(({ value, label }): MenuItem<CommandNames> => ({
+ title: escapeHtml(label),
+ trailingIcon: value === state.boxSize ? CHECK_ICON : undefined,
+ handler: () => runIncludeCommand(include, "includeNoteBoxSize", { value })
+ }));
+
+ return [
+ submenuItem({
+ title: t("link_context_menu.include_size"),
+ uiIcon: "bx bx-expand-vertical"
+ }, sizeItems),
+ {
+ title: t("link_context_menu.show_title"),
+ uiIcon: "bx bx-window-alt",
+ enabled: state.isTitleToggleable,
+ trailingIcon: state.isTitleShown ? CHECK_ICON : undefined,
+ handler: () => runIncludeCommand(include, "toggleIncludeNoteTitle")
+ },
+ {
+ title: t("link_context_menu.show_caption"),
+ uiIcon: "bx bx-captions",
+ enabled: state.isCaptionToggleable,
+ trailingIcon: state.hasCaption ? CHECK_ICON : undefined,
+ handler: () => runIncludeCommand(include, "toggleIncludeNoteCaption", {
+ focusCaptionOnShow: true
+ })
+ }
+ ];
+}
+
+/** Runs `command` on the include, which the commands act on once it is selected. */
+function runIncludeCommand(
+ { editor, element }: MenuInclude,
+ command: string,
+ options?: Record<string, unknown>
+) {
+ if (editor.plugins.get("IncludeNote").selectIncludeAt(element)) {
+ editor.execute(command, options);
+ editor.editing.view.focus();
+ }
+}
+
/** "Convert link to an embed", for an attachment link in a text note open for editing. */
async function getConvertToEmbedItem(
e: LinkMenuOrigin,
@@ -196,29 +290,16 @@ async function getConvertToEmbedItem(
};
}
-/**
- * "Convert to link", for a menu opened from the title row of an attachment embed in a text note
- * open for editing.
- */
-function getConvertToLinkItem(
- e: LinkMenuOrigin,
- editor: CKTextEditor | null
-): MenuItem<CommandNames> | null {
- const titleRow = getTarget(e)?.closest<HTMLElement>(".include-note-title-row");
- if (!titleRow?.closest(".include-note[data-attachment-id]")
- || !editor?.plugins.has("IncludeNote") || !editor.commands.get("convertEmbedToLink")) {
+/** "Convert to link", for an include that names a note or an attachment. */
+function getConvertToLinkItem(include: MenuInclude): MenuItem<CommandNames> | null {
+ if (!include.state.isConvertibleToLink) {
return null;
}
return {
title: t("link_context_menu.convert_embed_to_link"),
uiIcon: "bx bx-link",
- handler: () => {
- // `convertEmbedToLink` acts on the selected embed.
- if (editor.plugins.get("IncludeNote").selectIncludeAt(titleRow)) {
- editor.execute("convertEmbedToLink");
- }
- }
+ handler: () => runIncludeCommand(include, "convertEmbedToLink")
};
}
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 4a9a8c5f4e..fd8ebce1fe 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -3060,7 +3060,10 @@
"open_note_in_new_window": "Open note in a new window",
"open_note_in_popup": "Quick edit",
"convert_link_to_embed": "Convert link to an embed",
- "convert_embed_to_link": "Convert to link"
+ "convert_embed_to_link": "Convert to link",
+ "include_size": "Size",
+ "show_title": "Show title",
+ "show_caption": "Show caption"
},
"electron_integration": {
"desktop-application": "Desktop Application",
diff --git a/apps/client/src/widgets/type_widgets/text/IncludeNote.spec.tsx b/apps/client/src/widgets/type_widgets/text/IncludeNote.spec.tsx
index 34f65c5f97..bc3fce8cc2 100644
--- a/apps/client/src/widgets/type_widgets/text/IncludeNote.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/text/IncludeNote.spec.tsx
@@ -115,6 +115,25 @@ function tooltipOf(target: HTMLElement) {
return text;
}
+/**
+ * Right-clicks `target`, and tells whether the box opened the include's menu for it, taking the
+ * click from the browser and what surrounds the box.
+ */
+function rightClick(target: Element | null) {
+ if (!target) {
+ throw new Error("Nothing to right-click.");
+ }
+ openContextMenu.mockClear();
+ const event = new MouseEvent("contextmenu", { bubbles: true, cancelable: true });
+ const stopPropagation = vi.spyOn(event, "stopPropagation");
+ act(() => {
+ target.dispatchEvent(event);
+ });
+ const opened = openContextMenu.mock.calls.length === 1
+ && openContextMenu.mock.calls[0][1] === event;
+ return { opened, isTaken: event.defaultPrevented && stopPropagation.mock.calls.length > 0 };
+}
+
/** Clicks `target` and tells whether the click was kept from what surrounds the box. */
function click(target: HTMLElement) {
const event = new MouseEvent("click", { bubbles: true, cancelable: true });
@@ -258,6 +277,20 @@ describe("IncludeNote", () => {
Reflect.deleteProperty(document, "exitFullscreen");
});
+ it("opens its menu on a right click on the title row, leaving the title link its own", () => {
+ renderBox({ notePath: "owner", viewScope: ATTACHMENT_SCOPE });
+ const row = container.querySelector(".include-note-title-row");
+
+ for (const target of [ row, row?.querySelector("h4"), button("include-note-open") ]) {
+ expect(rightClick(target ?? null)).toEqual({ opened: true, isTaken: true });
+ expect(openContextMenu.mock.calls[0][2]).toEqual(ATTACHMENT_SCOPE);
+ }
+
+ // The title link opens the same menu, and a quick edit with Ctrl, through `link.ts`.
+ expect(rightClick(row?.querySelector("a") ?? null))
+ .toEqual({ opened: false, isTaken: false });
+ });
+
it("leaves the fullscreen controls out of a box that offers no fullscreen", () => {
renderBox({ boxSize: "small" });
expect(container.querySelector(".include-note-fullscreen-controls")).toBeNull();
@@ -302,6 +335,17 @@ describe("TinyIncludeNote", () => {
.toHaveBeenCalledWith("owner", { below: menu }, ATTACHMENT_SCOPE);
});
+ it("opens its menu on a right click on the row, leaving the title link its own", () => {
+ renderTinyBox({ notePath: "owner", viewScope: ATTACHMENT_SCOPE });
+ const row = container.querySelector(".include-note-title-row");
+
+ expect(rightClick(row?.querySelector(".include-note-icon") ?? null))
+ .toEqual({ opened: true, isTaken: true });
+ expect(openContextMenu.mock.calls[0][0]).toBe("owner");
+ expect(rightClick(row?.querySelector("a") ?? null))
+ .toEqual({ opened: false, isTaken: false });
+ });
+
it("leaves out the description line when there is none", () => {
renderTinyBox();
expect(container.querySelector(".include-note-description")).toBeNull();
diff --git a/apps/client/src/widgets/type_widgets/text/IncludeNote.tsx b/apps/client/src/widgets/type_widgets/text/IncludeNote.tsx
index 022f2197c9..da5c4f93f7 100644
--- a/apps/client/src/widgets/type_widgets/text/IncludeNote.tsx
+++ b/apps/client/src/widgets/type_widgets/text/IncludeNote.tsx
@@ -61,7 +61,10 @@ export default function IncludeNote({
return (
<>
- <div className="include-note-title-row">
+ <div
+ className="include-note-title-row"
+ onContextMenu={(e) => openMenuOnRightClick(e, notePath, viewScope)}
+ >
{isExpandable && (
<ActionButton
className={clsx("include-note-toggle", isExpanded && "expanded")}
@@ -128,7 +131,10 @@ export function TinyIncludeNote({
icon, title, description, notePath, viewScope, actions
}: TinyIncludeNoteProps) {
return (
- <div className="include-note-title-row">
+ <div
+ className="include-note-title-row"
+ onContextMenu={(e) => openMenuOnRightClick(e, notePath, viewScope)}
+ >
<Icon className="include-note-icon" icon={icon} />
<div className="include-note-heading">
<IncludeNoteTitle title={title} />
@@ -201,6 +207,20 @@ 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
+ * handler of every link, which opens the same menu, or a quick edit with Ctrl.
+ */
+function openMenuOnRightClick(e: MouseEvent, notePath: string, viewScope?: ViewScope) {
+ if (e.target instanceof Element && e.target.closest("a")) {
+ return;
+ }
+
+ e.preventDefault();
+ e.stopPropagation();
+ void linkContextMenu.openContextMenu(notePath, e, viewScope);
+}
+
function MoreActionsButton({ notePath, viewScope }: { notePath: string; viewScope?: ViewScope }) {
return (
<ActionButton
diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/Notes/Attachments.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/Notes/Attachments.html
index bb6e8c270c..71cdfcc4c2 100644
--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/Notes/Attachments.html
+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/Notes/Attachments.html
@@ -77,7 +77,8 @@
at the end of the menu.</li>
<li>An embed gets the box size that suits the attachment, as a new included
note does (see <em>Box sizes</em> there). To change its size, select the
- embed and use the box size menu in its toolbar.</li>
+ embed and use the box size menu in its toolbar, or the <em>Size</em> submenu
+ of its <span class="tn-icon bx bx-dots-vertical-rounded"></span> <em>More actions</em> menu.</li>
<li>An embed can have a caption, as an included note can (see <em>Caption</em> there).</li>
<li>To show only the attachment, select the embed and press the <span class="tn-icon bx bx-window-alt"></span> <em>Show title</em> button
in its toolbar, as for an included note (see <em>Title</em> there).</li>
@@ -92,7 +93,7 @@
the top-right corner, or <kbd>Esc</kbd>.</li>
<li>To turn the embed back into a link, select it and press the <span class="tn-icon cke cke-link"></span> <em>Convert to link</em> button
in its toolbar. <em>Convert to link</em> also ends the menu that right-clicking
- the title of the embed or pressing its <span class="tn-icon bx bx-dots-vertical-rounded"></span> <em>More actions</em> button
+ the title row of the embed or pressing its <span class="tn-icon bx bx-dots-vertical-rounded"></span> <em>More actions</em> button
opens.</li>
</ul>
<p>An embed follows its attachment like a link does. Converting the attachment
diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Include Note.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Include Note.html
index 9255e170ce..2657994dda 100644
--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Include Note.html
+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Include Note.html
@@ -32,7 +32,8 @@
</ul>
<p>The dialog that includes a note selects that size once the note is picked,
and you can choose another one there. To change the size later, select
- the include and use the <em>Box size</em> menu in its toolbar.</p>
+ the include and use the <em>Box size</em> menu in its toolbar, or the <em>Size</em> submenu
+ of its <em>More actions</em> menu.</p>
<h2>Caption</h2>
<p>An include can have a caption, shown centered at the bottom of its box.
The caption is part of the text note, so it can be formatted like the rest
@@ -62,9 +63,14 @@
<p>To open an included note in a new tab, press the <span class="tn-icon bx bx-link-external"></span> <em>Open in new tab</em> button
at the end of its title. An embedded attachment has the same button.</p>
<p>The <span class="tn-icon bx bx-dots-vertical-rounded"></span> <em>More actions</em> button
- at the end of the title row opens the same menu as right-clicking the title:
- the other places to open the note in and, for an embedded attachment, the
- actions on the attachment.</p>
+ at the end of the title row opens the same menu as right-clicking anywhere
+ on the title row: the other places to open the note in and, for an embedded
+ attachment, the actions on the attachment.</p>
+<p>In a note being edited, the menu also has the commands of the include's
+ toolbar: the <em>Size</em> submenu, <em>Show title</em> and <em>Show caption</em>,
+ each checked while it is in effect, and <em>Convert to link</em> at the end.
+ For an embedded attachment they follow its first group of actions; for
+ an included note they end the menu.</p>
<p>To show an include of size <em>Medium</em> or <em>Full</em> on the whole screen,
press the <span class="tn-icon bx bx-fullscreen"></span> <em>Fullscreen</em> button
at the end of its title. To return, press <span class="tn-icon bx bx-exit"></span> <em>Exit fullscreen</em> in
@@ -79,6 +85,11 @@
the file in another application, and <span class="tn-icon bx bx-download"></span> <em>Download</em> downloads
it. The size of the file is shown under its title.</li>
</ul>
+<h2>Converting an include to a link</h2>
+<p>To replace an include with a link to the included note, select it and
+ press the <span class="tn-icon cke cke-link"></span> <em>Convert to link</em> button
+ in its toolbar, or choose <em>Convert to link</em> at the end of its <em>More actions</em> menu.
+ An embedded attachment turns into a link to the attachment the same way.</p>
<h2>Included notes in the share functionality</h2>
<p>If a <a href="#root/_help_R9pX4DGra2Vt">shared note</a> contains one or
more included notes, they will be displayed in the content of the note
diff --git a/docs/User Guide/User Guide/Basic Concepts and Features/Notes/Attachments.md b/docs/User Guide/User Guide/Basic Concepts and Features/Notes/Attachments.md
index b298bc65ab..0d56150377 100644
--- a/docs/User Guide/User Guide/Basic Concepts and Features/Notes/Attachments.md
+++ b/docs/User Guide/User Guide/Basic Concepts and Features/Notes/Attachments.md
@@ -41,13 +41,13 @@ An attachment can be shown in the text instead of linked, the way <a class="ref
* To attach files and embed them straight away, select _Attach and embed file_ from the arrow beside the <span class="tn-icon cke cke-paper-clip"></span> _Attach file_ button. Each file gets an embed of its own, which shows the file name while the file uploads.
* To embed an attachment that is already linked, right-click a link to it in a text note being edited and select _Convert link to an embed_, at the end of the menu.
-* An embed gets the box size that suits the attachment, as a new included note does (see _Box sizes_ there). To change its size, select the embed and use the box size menu in its toolbar.
+* An embed gets the box size that suits the attachment, as a new included note does (see _Box sizes_ there). To change its size, select the embed and use the box size menu in its toolbar, or the _Size_ submenu of its <span class="tn-icon bx bx-dots-vertical-rounded"></span> _More actions_ menu.
* An embed can have a caption, as an included note can (see _Caption_ there).
* To show only the attachment, select the embed and press the <span class="tn-icon bx bx-window-alt"></span> _Show title_ button in its toolbar, as for an included note (see _Title_ there).
* To open the attachment in a new tab, press the <span class="tn-icon bx bx-link-external"></span> _Open in new tab_ button at the end of the embed's title.
* An embed of size _Tiny_ shows only the title of the attachment and its size, in a single row. Its buttons are <span class="tn-icon bx bx-file-find"></span> _Open externally_ and <span class="tn-icon bx bx-download"></span> _Download_.
* To show an embed of size _Medium_ or _Full_ on the whole screen, press the <span class="tn-icon bx bx-fullscreen"></span> _Fullscreen_ button at the end of its title. To return, press <span class="tn-icon bx bx-exit"></span> _Exit fullscreen_ in the top-right corner, or <kbd>Esc</kbd>.
-* To turn the embed back into a link, select it and press the <span class="tn-icon cke cke-link"></span> _Convert to link_ button in its toolbar. _Convert to link_ also ends the menu that right-clicking the title of the embed or pressing its <span class="tn-icon bx bx-dots-vertical-rounded"></span> _More actions_ button opens.
+* To turn the embed back into a link, select it and press the <span class="tn-icon cke cke-link"></span> _Convert to link_ button in its toolbar. _Convert to link_ also ends the menu that right-clicking the title row of the embed or pressing its <span class="tn-icon bx bx-dots-vertical-rounded"></span> _More actions_ button opens.
An embed follows its attachment like a link does. Converting the attachment into a note turns the embed into an included note. In a [shared note](../../Advanced%20Usage/Sharing.md), an embedded picture is displayed with its caption, and any other attachment appears as a link to download it.
diff --git a/docs/User Guide/User Guide/Note Types/Text/Include Note.md b/docs/User Guide/User Guide/Note Types/Text/Include Note.md
index 062b200112..25f77c1b42 100644
--- a/docs/User Guide/User Guide/Note Types/Text/Include Note.md
+++ b/docs/User Guide/User Guide/Note Types/Text/Include Note.md
@@ -25,7 +25,7 @@ A new include gets the size that suits what it shows:
* _Full_ for a code note.
* _Medium_ for anything else.
-The dialog that includes a note selects that size once the note is picked, and you can choose another one there. To change the size later, select the include and use the _Box size_ menu in its toolbar.
+The dialog that includes a note selects that size once the note is picked, and you can choose another one there. To change the size later, select the include and use the _Box size_ menu in its toolbar, or the _Size_ submenu of its _More actions_ menu.
## Caption
@@ -47,7 +47,9 @@ The title row of an include links to the included note and holds its buttons. To
To open an included note in a new tab, press the <span class="tn-icon bx bx-link-external"></span> _Open in new tab_ button at the end of its title. An embedded attachment has the same button.
-The <span class="tn-icon bx bx-dots-vertical-rounded"></span> _More actions_ button at the end of the title row opens the same menu as right-clicking the title: the other places to open the note in and, for an embedded attachment, the actions on the attachment.
+The <span class="tn-icon bx bx-dots-vertical-rounded"></span> _More actions_ button at the end of the title row opens the same menu as right-clicking anywhere on the title row: the other places to open the note in and, for an embedded attachment, the actions on the attachment.
+
+In a note being edited, the menu also has the commands of the include's toolbar: the _Size_ submenu, _Show title_ and _Show caption_, each checked while it is in effect, and _Convert to link_ at the end. For an embedded attachment they follow its first group of actions; for an included note they end the menu.
To show an include of size _Medium_ or _Full_ on the whole screen, press the <span class="tn-icon bx bx-fullscreen"></span> _Fullscreen_ button at the end of its title. To return, press <span class="tn-icon bx bx-exit"></span> _Exit fullscreen_ in the top-right corner, or <kbd>Esc</kbd>.
@@ -56,6 +58,10 @@ A _Tiny_ include has these buttons instead, followed by the same _More actions_
* For a note, <span class="tn-icon bx bx-edit"></span> _Quick edit_ opens the note in <a class="reference-link" href="../../Basic%20Concepts%20and%20Features/Navigation/Quick%20edit.md">Quick edit</a>, and <span class="tn-icon bx bx-link-external"></span> _Open in new tab_ opens it in a new tab.
* For an embedded attachment, <span class="tn-icon bx bx-file-find"></span> _Open externally_ opens the file in another application, and <span class="tn-icon bx bx-download"></span> _Download_ downloads it. The size of the file is shown under its title.
+## Converting an include to a link
+
+To replace an include with a link to the included note, select it and press the <span class="tn-icon cke cke-link"></span> _Convert to link_ button in its toolbar, or choose _Convert to link_ at the end of its _More actions_ menu. An embedded attachment turns into a link to the attachment the same way.
+
## Included notes in the share functionality
If a [shared note](../../Advanced%20Usage/Sharing.md) contains one or more included notes, they will be displayed in the content of the note as if they were part of the note itself. The caption of an include is shown under the included content.
diff --git a/packages/ckeditor5/src/index.ts b/packages/ckeditor5/src/index.ts
index 991a45e95f..8af13f3801 100644
--- a/packages/ckeditor5/src/index.ts
+++ b/packages/ckeditor5/src/index.ts
@@ -15,6 +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 { AttachmentLinkChange } from "./plugins/referencelink.js";
export type { SlashCommandConfig, SlashCommandDefinition } from "./plugins/mention/slash_commands.js";
export type { TriliumMentionFeed } from "./plugins/mention/types.js";
diff --git a/packages/ckeditor5/src/plugins/includenote.spec.ts b/packages/ckeditor5/src/plugins/includenote.spec.ts
index 5d4bd384fb..13b3c31f9e 100644
--- a/packages/ckeditor5/src/plugins/includenote.spec.ts
+++ b/packages/ckeditor5/src/plugins/includenote.spec.ts
@@ -704,7 +704,7 @@ describe("IncludeNote with attachments", () => {
expect(loadIncludedAttachment).not.toHaveBeenCalled();
});
- it("turns an attachment embed back into a link, and offers it only for one", async () => {
+ it("turns an embed or an included 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)) {
@@ -712,7 +712,8 @@ describe("IncludeNote with attachments", () => {
}
expect(button.label).toBe("Convert to link");
- insertIncludeNote(editor, "noteX", "small");
+ editor.setData("<figure class=\"include-note\" data-box-size=\"small\"></figure>");
+ selectEmbed();
expect(command?.isEnabled).toBe(false);
expect(button.isVisible).toBe(false);
@@ -726,6 +727,58 @@ describe("IncludeNote with attachments", () => {
expect(getAttachmentHref).toHaveBeenCalledWith("att1");
await vi.waitFor(() => expect(getModelData(editor.model, { withoutSelection: true }))
.toBe(`<paragraph><reference href="${LINK_HREF}"></reference></paragraph>`));
+
+ editor.setData("<figure class=\"include-note\" data-note-id=\"noteX\""
+ + " data-box-size=\"small\"></figure>");
+ selectEmbed();
+ expect(command?.isEnabled).toBe(true);
+ button.fire("execute");
+
+ await vi.waitFor(() => expect(getModelData(editor.model, { withoutSelection: true }))
+ .toBe("<paragraph><reference href=\"#root/noteX\"></reference></paragraph>"));
+ expect(getAttachmentHref).toHaveBeenCalledOnce();
+ });
+
+ it("describes the include 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>"
+ + "<figure class=\"include-note\" data-note-id=\"noteY\" data-box-size=\"tiny\""
+ + " data-hide-title=\"true\"></figure>"
+ + "<p>after</p>");
+ editor.model.change((writer) => {
+ const root = editor.model.document.getRoot();
+ const paragraph = root?.getChild(root.childCount - 1);
+ if (paragraph) {
+ writer.setSelection(paragraph, 0);
+ }
+ });
+ const [ embed, note, tiny ] = renderEmbeds() ?? [];
+ const plugin = editor.plugins.get("IncludeNote");
+
+ const states = [ embed, note, tiny ].map((wrapper) => plugin.getIncludeStateAt(wrapper));
+ expect(states).toEqual([ {
+ boxSize: "small", isTitleShown: true, isTitleToggleable: true,
+ hasCaption: false, isCaptionToggleable: true, isConvertibleToLink: true
+ }, {
+ boxSize: "medium", isTitleShown: false, isTitleToggleable: true,
+ hasCaption: true, isCaptionToggleable: true, isConvertibleToLink: true
+ }, {
+ boxSize: "tiny", isTitleShown: true, isTitleToggleable: false,
+ hasCaption: false, isCaptionToggleable: false, isConvertibleToLink: true
+ } ]);
+ const paragraph = editor.editing.view.getDomRoot()?.querySelector("p") ?? embed;
+ expect(plugin.getIncludeStateAt(paragraph)).toBeNull();
+ const position = editor.model.document.selection.getFirstPosition();
+ expect(position?.parent.is("element", "paragraph")).toBe(true);
+
+ expect(plugin.getBoxSizes()).toEqual([
+ { value: "tiny", label: "Tiny" },
+ { value: "small", label: "Small" },
+ { value: "medium", label: "Medium" },
+ { value: "full", label: "Full" },
+ { value: "expandable", label: "Expandable" }
+ ]);
});
it("converts the embed that selectIncludeAt() selects from its title row", async () => {
@@ -750,7 +803,7 @@ describe("IncludeNote with attachments", () => {
);
});
- it("converts nothing when no attachment embed is selected", async () => {
+ it("converts nothing when no include is selected", async () => {
editor.setData(embedHtml() + "<p>after</p>");
setModelData(editor.model, "<paragraph>foo[]bar</paragraph>");
const before = editor.getData();
diff --git a/packages/ckeditor5/src/plugins/includenote.ts b/packages/ckeditor5/src/plugins/includenote.ts
index e4096ca386..7b2d9deb5f 100644
--- a/packages/ckeditor5/src/plugins/includenote.ts
+++ b/packages/ckeditor5/src/plugins/includenote.ts
@@ -38,6 +38,17 @@ export const BOX_SIZES = [ 'tiny', 'small', 'medium', 'full', 'expandable' ] as
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 {
+ boxSize: BoxSizeValue | null;
+ /** Whether the title shows, which a Tiny or an Expandable include always does. */
+ isTitleShown: boolean;
+ isTitleToggleable: boolean;
+ hasCaption: boolean;
+ isCaptionToggleable: boolean;
+ isConvertibleToLink: boolean;
+}
+
/**
* The user-facing name of a box size, as shown by the widget toolbar's dropdown.
*
@@ -90,6 +101,33 @@ export default class IncludeNote extends Plugin {
} );
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.
+ */
+ getIncludeStateAt( domElement: Element ): IncludeNoteState | null {
+ const editor = this.editor;
+ const include = getIncludeNoteAt( editor, domElement );
+ if ( !include ) {
+ return null;
+ }
+
+ const isTitleToggleable = isIncludeTitleToggleable( include );
+ return {
+ boxSize: include.getAttribute( 'boxSize' ) as BoxSizeValue | undefined ?? null,
+ isTitleShown: !isTitleToggleable || !include.getAttribute( 'hideTitle' ),
+ isTitleToggleable,
+ hasCaption: !!getCaption( include ),
+ isCaptionToggleable: isIncludeCaptionToggleable( editor, include ),
+ isConvertibleToLink: isIncludeConvertibleToLink( editor, include )
+ };
+ }
+
+ /** The box sizes, with the labels the toolbar gives them. */
+ getBoxSizes(): { value: BoxSizeValue; label: string }[] {
+ return BOX_SIZES.map( value => ( { value, label: getBoxSizeLabel( this.editor.t, value ) } ) );
+ }
}
class IncludeNoteUI extends Plugin {
@@ -135,7 +173,7 @@ class IncludeNoteUI extends Plugin {
tooltip: true
} );
- // Shown only on an attachment embed, the one include the command applies to.
+ // Shown only on an include that names a note or an attachment.
if ( command ) {
buttonView.bind( 'isEnabled' ).to( command );
buttonView.bind( 'isVisible' ).to( command, 'isEnabled' );
@@ -577,8 +615,7 @@ export class ToggleIncludeNoteCaptionCommand extends Command {
override refresh() {
const include = getSelectedIncludeNote( this.editor );
- this.isEnabled = !!include && include.getAttribute( 'boxSize' ) !== 'tiny'
- && this.editor.model.schema.checkChild( include, 'caption' );
+ this.isEnabled = !!include && isIncludeCaptionToggleable( this.editor, include );
this.value = !!include && !!getCaption( include );
}
@@ -622,9 +659,8 @@ export class ToggleIncludeNoteTitleCommand extends Command {
override refresh() {
const include = getSelectedIncludeNote( this.editor );
- const boxSize = include?.getAttribute( 'boxSize' );
- this.isEnabled = !!include && boxSize !== 'tiny' && boxSize !== 'expandable';
+ this.isEnabled = !!include && isIncludeTitleToggleable( include );
this.value = !include?.getAttribute( 'hideTitle' );
}
@@ -674,26 +710,28 @@ class EmbedAttachmentLinkCommand extends Command {
}
}
-/** Replaces the selected attachment embed with a link to the attachment. */
+/** Replaces the selected include with a link to the note or attachment it shows. */
class ConvertEmbedToLinkCommand extends Command {
override refresh() {
const embed = getSelectedIncludeNote( this.editor );
- const canHoldLink = this.editor.model.schema.isRegistered( 'reference' );
- this.isEnabled = !!embed?.hasAttribute( 'attachmentId' ) && canHoldLink;
+ this.isEnabled = !!embed && isIncludeConvertibleToLink( this.editor, embed );
}
override async execute() {
const editor = this.editor;
const embed = getSelectedIncludeNote( editor );
const attachmentId = embed?.getAttribute( 'attachmentId' ) as string | undefined;
- if ( !embed || !attachmentId ) {
+ const noteId = embed?.getAttribute( 'noteId' ) as string | undefined;
+ if ( !embed || ( !attachmentId && !noteId ) ) {
return;
}
const editorEl = editor.editing.view.getDomRoot();
const component = glob.getComponentByEl<EditorComponent>( editorEl );
- const href = await component.getAttachmentHref( attachmentId );
+ const href = attachmentId
+ ? await component.getAttachmentHref( attachmentId )
+ : `#root/${ noteId }`;
// The embed can be removed while the host looks the link up.
const root = embed.root;
@@ -740,6 +778,24 @@ function isIncludeNote( node: ModelNode | ModelDocumentFragment | null ): node i
return !!node?.is( 'element', 'includeNote' );
}
+/** 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' );
+ 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 `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' ) )
+ && editor.model.schema.isRegistered( 'reference' );
+}
+
/** The caption of `include`, or `null`. */
function getCaption( include: ModelElement ) {
for ( const child of include.getChildren() ) {