Skip to content

Build your personal knowledge base with Trilium Notes

client/text editor/include notes: allow toggling the visibility of the title bar

Adorian Doran2e9398349f1a
diff --git a/apps/client/src/menus/link_context_menu.ts b/apps/client/src/menus/link_context_menu.ts
index bd8c3ac59a..dfd2f52fdb 100644
--- a/apps/client/src/menus/link_context_menu.ts
+++ b/apps/client/src/menus/link_context_menu.ts
@@ -9,18 +9,20 @@ import { t } from "../services/i18n.js";
import type { ViewScope } from "../services/link.js";
import utils, { isMobile } from "../services/utils.js";
import { getClosestNtxId } from "../widgets/widget_utils.js";
-import contextMenu, {
- type ContextMenuEvent,
- type ContextMenuOptions,
- type MenuItem
-} from "./context_menu.js";
+import contextMenu, { type ContextMenuOptions, type MenuItem } from "./context_menu.js";
import { getTextEditorContaining } from "./text_editor_context_menu.js";
+/**
+ * Where a link menu opens, and the element it is opened from. A mouse event is one; a control
+ * acting on something shown elsewhere passes that thing as `target`.
+ */
+export type LinkMenuOrigin = Pick<MouseEvent, "pageX" | "pageY" | "target">;
+
let lastMenuRequest = 0;
async function openContextMenu(
notePath: string,
- e: ContextMenuEvent,
+ e: LinkMenuOrigin,
viewScope: ViewScope = {},
hoistedNoteId: string | null = null
) {
@@ -65,12 +67,12 @@ function keepEditorFocused(
};
}
-function getItems(e: ContextMenuEvent | GeoMouseEvent): MenuItem<CommandNames>[] {
+function getItems(e: LinkMenuOrigin | GeoMouseEvent): MenuItem<CommandNames>[] {
return [ ...getOpenItems(e), getQuickEditItem() ];
}
/** The places the note can be opened in, without the quick edit popup. */
-function getOpenItems(e: ContextMenuEvent | GeoMouseEvent): MenuItem<CommandNames>[] {
+function getOpenItems(e: LinkMenuOrigin | GeoMouseEvent): MenuItem<CommandNames>[] {
const ntxId = getNtxId(e);
const isMobileSplitOpen = isMobile() && appContext.tabManager.getNoteContextById(ntxId).getMainContext().getSubContexts().length > 1;
@@ -93,7 +95,7 @@ function getQuickEditItem(): MenuItem<CommandNames> {
* does from the top level. The entry carries the first of those commands itself, so that picking it
* opens a new tab without going into the submenu for the place it is opened in most often.
*/
-function getOpenNoteItem(e: ContextMenuEvent | GeoMouseEvent): MenuItem<CommandNames> {
+function getOpenNoteItem(e: LinkMenuOrigin | GeoMouseEvent): MenuItem<CommandNames> {
return {
title: t("link_context_menu.open_note"),
uiIcon: "bx bx-link-external",
@@ -102,7 +104,7 @@ function getOpenNoteItem(e: ContextMenuEvent | GeoMouseEvent): MenuItem<CommandN
};
}
-function handleLinkContextMenuItem(command: string | undefined, e: ContextMenuEvent | GeoMouseEvent, notePath: string, viewScope = {}, hoistedNoteId: string | null = null) {
+function handleLinkContextMenuItem(command: string | undefined, e: LinkMenuOrigin | GeoMouseEvent, notePath: string, viewScope = {}, hoistedNoteId: string | null = null) {
if (!hoistedNoteId) {
hoistedNoteId = appContext.tabManager.getActiveContext()?.hoistedNoteId ?? null;
}
@@ -132,7 +134,7 @@ function handleLinkContextMenuItem(command: string | undefined, e: ContextMenuEv
async function getAttachmentItems(
noteId: string,
{ viewMode, attachmentId }: ViewScope,
- e: ContextMenuEvent,
+ e: LinkMenuOrigin,
editor: CKTextEditor | null
): Promise<MenuItem<CommandNames>[]> {
if (viewMode !== "attachments" || !attachmentId) {
@@ -167,7 +169,7 @@ async function getAttachmentItems(
/** "Convert link to an embed", for an attachment link in a text note open for editing. */
async function getConvertToEmbedItem(
- e: ContextMenuEvent,
+ e: LinkMenuOrigin,
editor: CKTextEditor | null,
attachment: FAttachment
): Promise<MenuItem<CommandNames> | null> {
@@ -193,7 +195,7 @@ async function getConvertToEmbedItem(
* open for editing.
*/
function getConvertToLinkItem(
- e: ContextMenuEvent,
+ e: LinkMenuOrigin,
editor: CKTextEditor | null
): MenuItem<CommandNames> | null {
const titleRow = getTarget(e)?.closest<HTMLElement>(".include-note-title-row");
@@ -214,7 +216,7 @@ function getConvertToLinkItem(
};
}
-function getTarget(e: ContextMenuEvent) {
+function getTarget(e: LinkMenuOrigin) {
return e.target instanceof Element ? e.target : null;
}
@@ -228,7 +230,7 @@ async function getEditingTextEditor(element: Element | null) {
return getTextEditorContaining(element);
}
-function getNtxId(e: ContextMenuEvent | GeoMouseEvent) {
+function getNtxId(e: LinkMenuOrigin | GeoMouseEvent) {
if (utils.isDesktop()) {
const subContexts = appContext.tabManager.getActiveContext()?.getSubContexts();
if (!subContexts) return null;
diff --git a/apps/client/src/stylesheets/style.css b/apps/client/src/stylesheets/style.css
index 2fec442409..7552fdbfa8 100644
--- a/apps/client/src/stylesheets/style.css
+++ b/apps/client/src/stylesheets/style.css
@@ -1700,6 +1700,18 @@ body.mobile .modal-content-with-sidebar > .modal-main > .modal-header > .modal-t
margin-bottom: 0;
}
+.include-note[data-hide-title="true"]:not([data-box-size="tiny"], [data-box-size="expandable"]) {
+ > .include-note-wrapper > .include-note-title-row {
+ display: none;
+ }
+
+ > .include-note-wrapper > .include-note-content:not(:fullscreen) {
+ border-top: none;
+ border-radius: var(--_include-note-top-border-radius, 8px)
+ var(--_include-note-top-border-radius, 8px) 0 0;
+ }
+}
+
/* Media that renders edge-to-edge (iframes, images, video, full-height collection views) shouldn't
be inset. List/grid collections keep their padding (they are content-driven, not full-height). */
.include-note-content.type-pdf,
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index f98f14a026..4a9a8c5f4e 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -4409,7 +4409,9 @@
"ascending": "Ascending",
"descending": "Descending",
"some-rows-were-sorted-together-because-merged-cells-tie-them-to-each-other": "Some rows were sorted together because merged cells tie them to each other",
- "tiny": "Tiny"
+ "tiny": "Tiny",
+ "show-title": "Show title",
+ "more-actions": "More actions"
},
"task-state-dropped-title": "Invalid task states",
"task-state-dropped-message_one": "A custom task state definition is invalid and was ignored.",
diff --git a/apps/client/src/widgets/type_widgets/text/EditableText.tsx b/apps/client/src/widgets/type_widgets/text/EditableText.tsx
index bffefc6b3c..0ff01688bf 100644
--- a/apps/client/src/widgets/type_widgets/text/EditableText.tsx
+++ b/apps/client/src/widgets/type_widgets/text/EditableText.tsx
@@ -39,6 +39,7 @@ import {
getAttachmentHref,
loadIncludedAttachment,
loadIncludedNote,
+ openIncludeNoteMenu,
refreshIncludedNote,
setupImageOpening,
watchIncludedNotes
@@ -198,6 +199,7 @@ export default function EditableText({ note, parentComponent, ntxId, noteContext
return note.noteId;
},
getEmbedBoxSize: getUploadBoxSize,
+ openIncludeNoteMenu,
// 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) {
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 c054810d0b..6223d11d2c 100644
--- a/apps/client/src/widgets/type_widgets/text/utils.spec.ts
+++ b/apps/client/src/widgets/type_widgets/text/utils.spec.ts
@@ -27,7 +27,11 @@ vi.mock("../../../services/attachment_actions", () => ({
getOpenExternallyAction: vi.fn(),
getDownloadAction: vi.fn()
}));
+vi.mock("../../../menus/link_context_menu", () => ({
+ default: { openContextMenu: vi.fn() }
+}));
+import linkContextMenu from "../../../menus/link_context_menu";
import { getDownloadAction, getOpenExternallyAction } from "../../../services/attachment_actions";
import content_renderer from "../../../services/content_renderer";
import froca from "../../../services/froca";
@@ -43,6 +47,7 @@ import {
getAttachmentHref,
loadIncludedAttachment,
loadIncludedNote,
+ openIncludeNoteMenu,
refreshIncludedNote,
watchIncludedNotes
} from "./utils";
@@ -340,6 +345,37 @@ describe("watchIncludedNotes", () => {
});
});
+describe("openIncludeNoteMenu", () => {
+ it("opens the menu of the note or attachment an include shows, below the anchor", async () => {
+ const anchor = document.createElement("button");
+ anchor.getBoundingClientRect = () => ({ left: 40, bottom: 70 }) as DOMRect;
+ const origin = { pageX: 40 + window.scrollX, pageY: 70 + window.scrollY };
+ const noteInclude = document.createElement("figure");
+ noteInclude.dataset.noteId = "noteY";
+ const embed = document.createElement("figure");
+ embed.dataset.attachmentId = "att1";
+
+ await openIncludeNoteMenu(noteInclude, anchor);
+ await openIncludeNoteMenu(embed, anchor);
+
+ expect(vi.mocked(linkContextMenu.openContextMenu).mock.calls).toEqual([
+ [ "noteY", { ...origin, target: noteInclude }, {} ],
+ [ "owner", { ...origin, target: embed }, ATTACHMENT_SCOPE ]
+ ]);
+ });
+
+ it("opens nothing for an include of a deleted attachment, or of nothing", async () => {
+ vi.mocked(froca.getAttachment).mockResolvedValue(null);
+ const embed = document.createElement("figure");
+ embed.dataset.attachmentId = "att1";
+
+ await openIncludeNoteMenu(embed, document.createElement("button"));
+ await openIncludeNoteMenu(document.createElement("figure"), document.createElement("button"));
+
+ expect(linkContextMenu.openContextMenu).not.toHaveBeenCalled();
+ });
+});
+
describe("getAttachmentHref", () => {
it("links to the attachment in its note, or to nothing once it is deleted", async () => {
vi.mocked(froca.getAttachment)
diff --git a/apps/client/src/widgets/type_widgets/text/utils.ts b/apps/client/src/widgets/type_widgets/text/utils.ts
index f25b79cae5..b0ccd36014 100644
--- a/apps/client/src/widgets/type_widgets/text/utils.ts
+++ b/apps/client/src/widgets/type_widgets/text/utils.ts
@@ -2,6 +2,7 @@ import { attachmentIcon } from "@triliumnext/commons";
import { h } 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 froca from "../../../services/froca";
@@ -137,6 +138,32 @@ function getWrapper(el: HTMLElement) {
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.
+ */
+export async function openIncludeNoteMenu(include: HTMLElement, anchor: HTMLElement) {
+ const { noteId, attachmentId } = include.dataset;
+ const { left, bottom } = anchor.getBoundingClientRect();
+ const origin = {
+ pageX: left + window.scrollX,
+ pageY: bottom + window.scrollY,
+ target: include
+ };
+
+ if (attachmentId) {
+ const attachment = await froca.getAttachment(attachmentId, true);
+ if (attachment) {
+ await linkContextMenu.openContextMenu(attachment.ownerId, origin, {
+ viewMode: "attachments",
+ attachmentId
+ });
+ }
+ } else if (noteId) {
+ await linkContextMenu.openContextMenu(noteId, origin, {});
+ }
+}
+
/** The href of a reference link to the attachment, or `null` once it is deleted. */
export async function getAttachmentHref(attachmentId: string) {
const attachment = await froca.getAttachment(attachmentId, true);
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 4ad801c4d8..bb6e8c270c 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
@@ -79,6 +79,8 @@
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>
<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>
<li>To open the attachment 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 the embed's title.</li>
<li>An embed of size <em>Tiny</em> shows only the title of the attachment and
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 2b1716f310..9255e170ce 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
@@ -48,6 +48,16 @@
<li>An <em>Expandable</em> include shows its caption under the title while the
content is collapsed, and under the content once it is expanded.</li>
</ul>
+<h2>Title</h2>
+<p>The title row of an include links to the included note and holds its buttons.
+ To show only the content, select the include and press the <span class="tn-icon bx bx-window-alt"></span> <em>Show title</em> button
+ in its toolbar. Pressing it again shows the title.</p>
+<ul>
+ <li>While the title is hidden, the <span class="tn-icon cke cke-three-vertical-dots"></span> <em>More actions</em> button
+ in the toolbar of the include opens the menu of the included note.</li>
+ <li>A <em>Tiny</em> or <em>Expandable</em> include always shows its title, and
+ its toolbar has no <em>Show title</em> button.</li>
+</ul>
<h2>Opening an included note</h2>
<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>
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 c9309c5824..b298bc65ab 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
@@ -43,6 +43,7 @@ An attachment can be shown in the text instead of linked, the way <a class="ref
* 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 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>.
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 429edbafc6..062b200112 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
@@ -36,6 +36,13 @@ An include can have a caption, shown centered at the bottom of its box. The capt
* A _Tiny_ include has no caption. Switching an include to _Tiny_ removes its caption, and switching it back to a larger size restores the caption, as long as the note stays open.
* An _Expandable_ include shows its caption under the title while the content is collapsed, and under the content once it is expanded.
+## Title
+
+The title row of an include links to the included note and holds its buttons. To show only the content, select the include and press the <span class="tn-icon bx bx-window-alt"></span> _Show title_ button in its toolbar. Pressing it again shows the title.
+
+* While the title is hidden, the <span class="tn-icon cke cke-three-vertical-dots"></span> _More actions_ button in the toolbar of the include opens the menu of the included note.
+* A _Tiny_ or _Expandable_ include always shows its title, and its toolbar has no _Show title_ button.
+
## Opening an included note
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.
diff --git a/packages/ckeditor5/src/augmentation.ts b/packages/ckeditor5/src/augmentation.ts
index cb8b10efca..1ddc60b9dc 100644
--- a/packages/ckeditor5/src/augmentation.ts
+++ b/packages/ckeditor5/src/augmentation.ts
@@ -58,6 +58,11 @@ declare global {
* includes leave it out.
*/
getEmbedBoxSize?(mime: string): string;
+ /**
+ * Opens the context menu of what `include` shows, below `anchor`. Hosts without includes
+ * leave it out.
+ */
+ openIncludeNoteMenu?(include: 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/plugins/include_note_toolbar.spec.ts b/packages/ckeditor5/src/plugins/include_note_toolbar.spec.ts
index 8a5a090278..0d7a639dc5 100644
--- a/packages/ckeditor5/src/plugins/include_note_toolbar.spec.ts
+++ b/packages/ckeditor5/src/plugins/include_note_toolbar.spec.ts
@@ -5,7 +5,9 @@ import { createTestEditor } from "../../test/editor-kit.js";
import { installGlobMock } from "../../test/globals-test-kit.js";
import IncludeNote, {
CONVERT_EMBED_TO_LINK_COMMAND,
- TOGGLE_CAPTION_COMMAND_NAME
+ INCLUDE_NOTE_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";
@@ -97,15 +99,17 @@ describe("IncludeNoteToolbar", () => {
expect(requires).toContain(IncludeNoteBoxSizeDropdown);
});
- it("offers the box size, the caption, and turning an attachment embed into a link", () => {
+ it("offers the box size, the title, the caption, the link conversion and the menu", () => {
const repository = editor.plugins.get(WidgetToolbarRepository) as unknown as {
_toolbarDefinitions: Map<string, { itemsConfig: string[] }>;
};
expect(repository._toolbarDefinitions.get("includeNote")?.itemsConfig).toEqual([
"includeNoteBoxSizeDropdown",
+ TOGGLE_TITLE_COMMAND_NAME,
TOGGLE_CAPTION_COMMAND_NAME,
- CONVERT_EMBED_TO_LINK_COMMAND
+ CONVERT_EMBED_TO_LINK_COMMAND,
+ INCLUDE_NOTE_MENU
]);
});
diff --git a/packages/ckeditor5/src/plugins/include_note_toolbar.ts b/packages/ckeditor5/src/plugins/include_note_toolbar.ts
index e21dea1bab..5252cbd63e 100644
--- a/packages/ckeditor5/src/plugins/include_note_toolbar.ts
+++ b/packages/ckeditor5/src/plugins/include_note_toolbar.ts
@@ -1,7 +1,9 @@
import { Plugin, WidgetToolbarRepository, isWidget, type ViewElement } from "ckeditor5";
import IncludeNote, {
CONVERT_EMBED_TO_LINK_COMMAND,
- TOGGLE_CAPTION_COMMAND_NAME
+ INCLUDE_NOTE_MENU,
+ TOGGLE_CAPTION_COMMAND_NAME,
+ TOGGLE_TITLE_COMMAND_NAME
} from "./includenote.js";
import IncludeNoteBoxSizeDropdown from "./include_note_box_size_dropdown.js";
@@ -18,8 +20,10 @@ export default class IncludeNoteToolbar extends Plugin {
widgetToolbarRepository.register("includeNote", {
items: [
"includeNoteBoxSizeDropdown",
+ TOGGLE_TITLE_COMMAND_NAME,
TOGGLE_CAPTION_COMMAND_NAME,
- CONVERT_EMBED_TO_LINK_COMMAND
+ CONVERT_EMBED_TO_LINK_COMMAND,
+ INCLUDE_NOTE_MENU
],
balloonClassName: "ck-toolbar-container include-note-toolbar",
getRelatedElement(selection) {
diff --git a/packages/ckeditor5/src/plugins/includenote.spec.ts b/packages/ckeditor5/src/plugins/includenote.spec.ts
index b343a6048e..5d4bd384fb 100644
--- a/packages/ckeditor5/src/plugins/includenote.spec.ts
+++ b/packages/ckeditor5/src/plugins/includenote.spec.ts
@@ -8,10 +8,12 @@ import {
Essentials,
LinkEditing,
Paragraph,
+ SwitchButtonView,
Undo,
Widget,
type ModelElement
} from "ckeditor5";
+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";
@@ -22,7 +24,9 @@ import IncludeNote, {
COMMAND_NAME,
EMBED_ATTACHMENT_LINK_COMMAND,
CONVERT_EMBED_TO_LINK_COMMAND,
- TOGGLE_CAPTION_COMMAND_NAME
+ INCLUDE_NOTE_MENU,
+ TOGGLE_CAPTION_COMMAND_NAME,
+ TOGGLE_TITLE_COMMAND_NAME
} from "./includenote.js";
import ReferenceLink from "./referencelink.js";
@@ -960,6 +964,113 @@ describe("IncludeNote captions", () => {
});
});
+describe("IncludeNote 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>;
+
+ beforeEach(async () => {
+ loadIncludedNote = vi.fn();
+ openIncludeNoteMenu = vi.fn();
+ installGlobMock({
+ getComponentByEl: () => ({ loadIncludedNote, openIncludeNoteMenu })
+ });
+
+ editor = await createTestEditor([ Essentials, Paragraph, Undo, Widget, IncludeNote ]);
+ });
+
+ function getCommand() {
+ const command = editor.commands.get(TOGGLE_TITLE_COMMAND_NAME);
+ if (!command) {
+ throw new Error("Expected the title command.");
+ }
+ return command;
+ }
+
+ function getRenderedInclude() {
+ const include = editor.editing.view.getDomRoot()?.querySelector("figure.include-note");
+ if (!include) {
+ throw new Error("Expected a rendered include.");
+ }
+ return include;
+ }
+
+ it("loads and saves a hidden title, and marks the include it renders", () => {
+ editor.setData(UNTITLED);
+
+ expect(getModelData(editor.model, { withoutSelection: true })).toBe(
+ "<includeNote boxSize=\"medium\" hideTitle=\"true\" noteId=\"n1\"></includeNote>"
+ );
+ expect(editor.getData()).toBe(UNTITLED);
+ expect(getRenderedInclude().getAttribute("data-hide-title")).toBe("true");
+
+ editor.setData(UNTITLED.replace(" data-hide-title=\"true\"", ""));
+ expect(getModelData(editor.model, { withoutSelection: true })).not.toContain("hideTitle");
+ expect(editor.getData()).not.toContain("data-hide-title");
+ });
+
+ it("hides the title and shows it again, keeping the rendered content", () => {
+ insertIncludeNote(editor, "n1", "medium");
+ const wrapper = getRenderedInclude().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(editor.getData()).toContain("data-hide-title=\"true\"");
+ expect(editor.model.document.selection.getSelectedElement()?.name).toBe("includeNote");
+
+ editor.execute(TOGGLE_TITLE_COMMAND_NAME);
+ expect(command.value).toBe(true);
+ expect(getRenderedInclude().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);
+ });
+
+ it("is disabled with no include selected, and on a Tiny or Expandable include", () => {
+ 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);
+ 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);
+ if (!(toggle instanceof ButtonView) || toggle instanceof SwitchButtonView
+ || !(menu instanceof ButtonView)) {
+ throw new Error("Expected two buttons.");
+ }
+ menu.render();
+ insertIncludeNote(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 ]);
+ expect([ menu.label, menu.isVisible ]).toEqual([ "More actions", false ]);
+
+ toggle.fire("execute");
+ expect(toggle.isOn).toBe(false);
+ expect(menu.isVisible).toBe(true);
+
+ menu.fire("execute");
+ expect(openIncludeNoteMenu).toHaveBeenCalledWith(getRenderedInclude(), menu.element);
+
+ editor.execute(BOX_SIZE_COMMAND_NAME, { value: "tiny" });
+ expect([ toggle.isVisible, menu.isVisible ]).toEqual([ false, false ]);
+ });
+});
+
function findIncludeNote(editor: ClassicEditor): ModelElement | undefined {
const root = editor.model.document.getRoot();
if (!root) {
diff --git a/packages/ckeditor5/src/plugins/includenote.ts b/packages/ckeditor5/src/plugins/includenote.ts
index 089c978c37..e4096ca386 100644
--- a/packages/ckeditor5/src/plugins/includenote.ts
+++ b/packages/ckeditor5/src/plugins/includenote.ts
@@ -6,6 +6,7 @@ import {
enableViewPlaceholder,
IconCaption,
IconLink,
+ IconThreeVerticalDots,
type MapperModelToViewPositionEvent,
ModelElement,
type ModelNode,
@@ -20,6 +21,7 @@ import {
Widget,
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';
@@ -28,6 +30,9 @@ export const BOX_SIZE_COMMAND_NAME = 'includeNoteBoxSize';
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 BOX_SIZES = [ 'tiny', 'small', 'medium', 'full', 'expandable' ] as const;
@@ -167,6 +172,54 @@ class IncludeNoteUI extends Plugin {
return buttonView;
} );
+
+ editor.ui.componentFactory.add( TOGGLE_TITLE_COMMAND_NAME, locale => {
+ const command = editor.commands.get( TOGGLE_TITLE_COMMAND_NAME );
+ const buttonView = new ButtonView( locale );
+
+ buttonView.set( {
+ label: t( 'Show title' ),
+ icon: windowIcon,
+ tooltip: true,
+ isToggleable: true
+ } );
+
+ if ( command ) {
+ buttonView.bind( 'isOn', 'isEnabled' ).to( command, 'value', 'isEnabled' );
+ buttonView.bind( 'isVisible' ).to( command, 'isEnabled' );
+ }
+
+ this.listenTo( buttonView, 'execute', () => {
+ editor.execute( TOGGLE_TITLE_COMMAND_NAME );
+ editor.editing.view.focus();
+ } );
+
+ return buttonView;
+ } );
+
+ editor.ui.componentFactory.add( INCLUDE_NOTE_MENU, locale => {
+ const command = editor.commands.get( TOGGLE_TITLE_COMMAND_NAME );
+ const buttonView = new ButtonView( locale );
+
+ buttonView.set( {
+ label: t( 'More actions' ),
+ icon: IconThreeVerticalDots,
+ tooltip: true
+ } );
+
+ // Replaces the menu button of the title row while the title is hidden.
+ if ( command ) {
+ buttonView.bind( 'isEnabled' ).to( command );
+ buttonView.bind( 'isVisible' ).to( command, 'isEnabled', command, 'value',
+ ( isEnabled, isTitleShown ) => isEnabled && !isTitleShown );
+ }
+
+ this.listenTo( buttonView, 'execute', () => {
+ openIncludeNoteMenu( editor, buttonView.element );
+ } );
+
+ return buttonView;
+ } );
}
}
@@ -196,6 +249,7 @@ class IncludeNoteEditing extends Plugin {
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 ) );
editor.model.document.registerPostFixer( writer => this.removeTinyCaptions( writer ) );
}
@@ -227,7 +281,8 @@ class IncludeNoteEditing extends Plugin {
// An include shows either a note or, as an embed, an attachment. An embed that
// `FileUploadEditing` is uploading carries the upload attributes instead of its id.
allowAttributes: [
- 'noteId', 'attachmentId', 'boxSize', 'uploadId', 'uploadStatus', 'uploadFileName'
+ 'noteId', 'attachmentId', 'boxSize', 'hideTitle', 'uploadId', 'uploadStatus',
+ 'uploadFileName'
],
// Allow in places where other blocks are allowed (e.g. directly in the root).
@@ -262,6 +317,9 @@ class IncludeNoteEditing extends Plugin {
return modelWriter.createElement( 'includeNote', {
...included,
boxSize: viewElement.getAttribute( 'data-box-size' ),
+ ...( viewElement.getAttribute( 'data-hide-title' ) === 'true'
+ ? { hideTitle: true }
+ : {} )
} );
},
// Includes saved before captions existed are `<section>` elements.
@@ -277,6 +335,7 @@ class IncludeNoteEditing extends Plugin {
class: 'include-note',
...getIncludedEntityAttributes( modelElement ),
'data-box-size': modelElement.getAttribute( 'boxSize' ),
+ ...getTitleAttributes( modelElement )
} );
}
} );
@@ -289,7 +348,8 @@ class IncludeNoteEditing extends Plugin {
const figure = viewWriter.createContainerElement( 'figure', {
class: 'include-note box-size-' + boxSize,
...getIncludedEntityAttributes( modelElement ),
- 'data-box-size': boxSize
+ 'data-box-size': boxSize,
+ ...getTitleAttributes( modelElement )
} );
const includedNoteWrapper = viewWriter.createUIElement( 'div', {
@@ -346,6 +406,20 @@ class IncludeNoteEditing extends Plugin {
}
} );
+ // Shows or hides the title without drawing the content again.
+ dispatcher.on( 'attribute:hideTitle:includeNote', ( _evt, data, conversionApi ) => {
+ const viewElement = conversionApi.mapper.toViewElement( data.item as ModelElement );
+ if ( !viewElement ) {
+ return;
+ }
+
+ if ( data.attributeNewValue ) {
+ conversionApi.writer.setAttribute( 'data-hide-title', 'true', viewElement );
+ } else {
+ conversionApi.writer.removeAttribute( 'data-hide-title', viewElement );
+ }
+ } );
+
// 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
// a caption toggle.
@@ -538,6 +612,38 @@ export class ToggleIncludeNoteCaptionCommand extends Command {
}
}
+/**
+ * Shows or hides the title row of the selected include. A Tiny or an Expandable include always
+ * shows it.
+ */
+export class ToggleIncludeNoteTitleCommand extends Command {
+ /** Whether the title shows. */
+ declare value: boolean;
+
+ override refresh() {
+ const include = getSelectedIncludeNote( this.editor );
+ const boxSize = include?.getAttribute( 'boxSize' );
+
+ this.isEnabled = !!include && boxSize !== 'tiny' && boxSize !== 'expandable';
+ this.value = !include?.getAttribute( 'hideTitle' );
+ }
+
+ override execute() {
+ const include = getSelectedIncludeNote( this.editor );
+ if ( !include ) {
+ return;
+ }
+
+ this.editor.model.change( writer => {
+ if ( include.getAttribute( 'hideTitle' ) ) {
+ writer.removeAttribute( 'hideTitle', include );
+ } else {
+ writer.setAttribute( 'hideTitle', true, include );
+ }
+ } );
+ }
+}
+
/** Replaces an attachment link with an embed of the attachment, in the same place. */
class EmbedAttachmentLinkCommand extends Command {
/**
@@ -692,6 +798,24 @@ 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. */
+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 );
+ 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 );
+}
+
/** The title of an embed whose upload is under way: a spinner and the name of the file. */
function createUploadTitle( domDocument: Document, fileName: string ) {
const title = domDocument.createElement( 'h4' );
@@ -908,5 +1032,6 @@ declare module 'ckeditor5' {
interface CommandsMap {
toggleIncludeNoteCaption: ToggleIncludeNoteCaptionCommand;
+ toggleIncludeNoteTitle: ToggleIncludeNoteTitleCommand;
}
}