Skip to content

Build your personal knowledge base with Trilium Notes

client/text editor/include notes: focus the widget when its actions buttons are pressed

Adorian Doran62c0cb0ec0ea
diff --git a/apps/client/src/menus/context_menu.spec.ts b/apps/client/src/menus/context_menu.spec.ts
index cf050d18d0..5546763c8b 100644
--- a/apps/client/src/menus/context_menu.spec.ts
+++ b/apps/client/src/menus/context_menu.spec.ts
@@ -75,11 +75,28 @@ describe("contextMenu", () => {
buildPage();
const contextMenu = await buildContextMenu();
const onHide = vi.fn();
+ // What the container holds when `onShow` gets it, before the menu takes focus inside it.
+ let shownContainer: { element: HTMLElement; isConnected: boolean; isEmpty: boolean } | null
+ = null;
+ const onShow = (element: HTMLElement) => {
+ shownContainer = {
+ element,
+ isConnected: element.isConnected,
+ isEmpty: !element.hasChildNodes()
+ };
+ };
- await contextMenu.show({ x: 10, y: 20, items, selectMenuItemHandler: () => {}, onHide });
+ await contextMenu.show({
+ x: 10, y: 20, items, selectMenuItemHandler: () => {}, onShow, onHide
+ });
const menu = menuElement();
expect(menu?.parentElement?.parentElement).toBe(document.body);
+ expect(shownContainer).toEqual({
+ element: menu?.parentElement,
+ isConnected: true,
+ isEmpty: true
+ });
expect(menu?.getAttribute("role")).toBe("menu");
// The classes the old menu carried, which the stylesheets and themes style it by.
expect([ ...menu?.classList ?? [] ]).toEqual(expect.arrayContaining([
diff --git a/apps/client/src/menus/context_menu.ts b/apps/client/src/menus/context_menu.ts
index d1373e4f6a..82435b3e47 100644
--- a/apps/client/src/menus/context_menu.ts
+++ b/apps/client/src/menus/context_menu.ts
@@ -14,6 +14,8 @@ export interface ContextMenuOptions<T> {
items: MenuItem<T>[];
/** On mobile, if set to `true` then the context menu is shown near the element. If `false` (default), then the context menu is shown at the bottom of the screen. */
forcePositionOnMobile?: boolean;
+ /** Called with the element the menu renders into, before the menu takes the focus. */
+ onShow?: (container: HTMLElement) => void;
onHide?: () => void;
}
@@ -148,6 +150,7 @@ class ContextMenu {
// inside it.
this.host = document.createElement("div");
(document.fullscreenElement ?? document.body).append(this.host);
+ options.onShow?.(this.host);
this.cover?.classList.add("show");
document.body.classList.add("context-menu-shown");
// A mobile menu is a sheet or placed at the press depending on the layout, decided here,
diff --git a/apps/client/src/menus/link_context_menu.spec.ts b/apps/client/src/menus/link_context_menu.spec.ts
index a0a56b253a..e969aa8527 100644
--- a/apps/client/src/menus/link_context_menu.spec.ts
+++ b/apps/client/src/menus/link_context_menu.spec.ts
@@ -369,21 +369,47 @@ describe("openContextMenu", () => {
hasCommand = false;
expect(await openOnTitle()).toHaveLength(6);
- // A title row outside an attachment embed is not looked up in the editor at all.
hasCommand = true;
const section = editable.querySelector("section");
section?.removeAttribute("data-attachment-id");
expect(await openOnTitle()).toHaveLength(6);
- expect(mocks.getTextEditorContaining).toHaveBeenCalledTimes(2);
+ expect(mocks.getTextEditorContaining).toHaveBeenCalledTimes(3);
+ // 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(2);
+ expect(mocks.getTextEditorContaining).toHaveBeenCalledTimes(3);
expect(selectIncludeAt).not.toHaveBeenCalled();
});
});
+ it("keeps the text editor it opens from focused while it is up", async () => {
+ const focusTracker = { add: vi.fn(), remove: vi.fn() };
+ mocks.getTextEditorContaining.mockResolvedValue({ ui: { focusTracker } });
+ const editable = document.createElement("div");
+ editable.className = "ck-editor__editable";
+ editable.setAttribute("contenteditable", "true");
+ editable.innerHTML = `<div class="include-note-title-row"><button></button></div>`;
+ const button = editable.querySelector("button") ?? undefined;
+
+ await linkContextMenu.openContextMenu("root/n1", contextMenuEvent(button));
+
+ const shown = mocks.show.mock.calls[0][0];
+ const container = document.createElement("div");
+ shown.onShow(container);
+ expect(focusTracker.add).toHaveBeenCalledWith(container);
+ expect(focusTracker.remove).not.toHaveBeenCalled();
+ shown.onHide();
+ expect(focusTracker.remove).toHaveBeenCalledWith(container);
+
+ // A note shown read-only has no editor to keep focused.
+ editable.removeAttribute("contenteditable");
+ await linkContextMenu.openContextMenu("root/n1", contextMenuEvent(button));
+ expect(mocks.show.mock.calls[1][0]).not.toHaveProperty("onShow");
+ expect(mocks.getTextEditorContaining).toHaveBeenCalledTimes(1);
+ });
+
it("adds nothing for a link to a note, or to an attachment that no longer exists", async () => {
await linkContextMenu.openContextMenu("root/n1", contextMenuEvent());
expect(mocks.getAttachmentOfNote).not.toHaveBeenCalled();
diff --git a/apps/client/src/menus/link_context_menu.ts b/apps/client/src/menus/link_context_menu.ts
index ac912c244e..eca6f0777c 100644
--- a/apps/client/src/menus/link_context_menu.ts
+++ b/apps/client/src/menus/link_context_menu.ts
@@ -1,3 +1,5 @@
+import type { CKTextEditor } from "@triliumnext/ckeditor5";
+
import type { GeoMouseEvent } from "../widgets/collections/geomap/map.js";
import appContext, { type CommandNames } from "../components/app_context.js";
@@ -7,7 +9,11 @@ import type { ViewScope } from "../services/link.js";
import options from "../services/options.js";
import utils, { isMobile } from "../services/utils.js";
import { getClosestNtxId } from "../widgets/widget_utils.js";
-import contextMenu, { type ContextMenuEvent, type MenuItem } from "./context_menu.js";
+import contextMenu, {
+ type ContextMenuEvent,
+ type ContextMenuOptions,
+ type MenuItem
+} from "./context_menu.js";
import { getTextEditorContaining } from "./text_editor_context_menu.js";
let lastMenuRequest = 0;
@@ -20,8 +26,10 @@ async function openContextMenu(
) {
const request = ++lastMenuRequest;
const noteId = notePath.split("/").at(-1) ?? notePath;
- const attachmentItems = await getAttachmentItems(noteId, viewScope, e);
- // A later right-click opened its own menu while this one waited for the attachment.
+ const editor = await getEditingTextEditor(getTarget(e));
+ const attachmentItems = await getAttachmentItems(noteId, viewScope, e, editor);
+ // A later right-click opened its own menu while this one waited for the editor or the
+ // attachment.
if (request !== lastMenuRequest) {
return;
}
@@ -30,10 +38,33 @@ async function openContextMenu(
x: e.pageX,
y: e.pageY,
items: [ ...getItems(e), ...attachmentItems ],
- selectMenuItemHandler: ({ command }) => handleLinkContextMenuItem(command, e, notePath, viewScope, hoistedNoteId)
+ selectMenuItemHandler: ({ command }) => handleLinkContextMenuItem(command, e, notePath, viewScope, hoistedNoteId),
+ ...(editor ? keepEditorFocused(editor) : {})
});
}
+/**
+ * Menu options adding the menu to the focus tracker of `editor`, so that the editor stays focused
+ * while the menu is up.
+ */
+function keepEditorFocused(
+ editor: CKTextEditor
+): Pick<ContextMenuOptions<CommandNames>, "onShow" | "onHide"> {
+ let menuContainer: HTMLElement | null = null;
+
+ return {
+ onShow: (container) => {
+ menuContainer = container;
+ editor.ui.focusTracker.add(container);
+ },
+ onHide: () => {
+ if (menuContainer) {
+ editor.ui.focusTracker.remove(menuContainer);
+ }
+ }
+ };
+}
+
function getItems(e: ContextMenuEvent | GeoMouseEvent): MenuItem<CommandNames>[] {
return [ ...getOpenItems(e), getQuickEditItem() ];
}
@@ -101,18 +132,17 @@ function handleLinkContextMenuItem(command: string | undefined, e: ContextMenuEv
async function getAttachmentItems(
noteId: string,
{ viewMode, attachmentId }: ViewScope,
- e: ContextMenuEvent
+ e: ContextMenuEvent,
+ editor: CKTextEditor | null
): Promise<MenuItem<CommandNames>[]> {
if (viewMode !== "attachments" || !attachmentId) {
return [];
}
// Imported on demand: `attachment_actions` imports `link`, which imports this module.
- const [ attachment, { getAttachmentActionGroups }, embedItem, linkItem ] = await Promise.all([
+ const [ attachment, { getAttachmentActionGroups } ] = await Promise.all([
froca.getAttachmentOfNote(noteId, attachmentId),
- import("../services/attachment_actions.js"),
- getConvertToEmbedItem(e),
- getConvertToLinkItem(e)
+ import("../services/attachment_actions.js")
]);
if (!attachment) {
return [];
@@ -129,16 +159,17 @@ async function getAttachmentItems(
}))
]);
- const conversionItems = [ embedItem, linkItem ].filter((item) => item !== null);
+ const conversionItems = [ getConvertToEmbedItem(e, editor), getConvertToLinkItem(e, editor) ]
+ .filter((item) => item !== null);
return [ ...actionItems, ...conversionItems ];
}
/** "Convert link to an embed", for an attachment link in a text note open for editing. */
-async function getConvertToEmbedItem(e: ContextMenuEvent): Promise<MenuItem<CommandNames> | null> {
- const link = e.target instanceof Element
- ? e.target.closest<HTMLElement>("a.reference-link")
- : null;
- const editor = await getEditingTextEditor(link);
+function getConvertToEmbedItem(
+ e: ContextMenuEvent,
+ editor: CKTextEditor | null
+): MenuItem<CommandNames> | null {
+ const link = getTarget(e)?.closest<HTMLElement>("a.reference-link");
if (!link || !editor?.commands.get("embedAttachmentLink")?.isEnabled) {
return null;
}
@@ -157,15 +188,13 @@ async function getConvertToEmbedItem(e: ContextMenuEvent): Promise<MenuItem<Comm
* "Convert to link", for a menu opened from the title row of an attachment embed in a text note
* open for editing.
*/
-async function getConvertToLinkItem(e: ContextMenuEvent): Promise<MenuItem<CommandNames> | null> {
- const titleRow = e.target instanceof Element
- ? e.target.closest<HTMLElement>(".include-note-title-row")
- : null;
- const editor = titleRow?.closest("section.include-note[data-attachment-id]")
- ? await getEditingTextEditor(titleRow)
- : null;
- if (!titleRow || !editor?.plugins.has("IncludeNote")
- || !editor.commands.get("convertEmbedToLink")) {
+function getConvertToLinkItem(
+ e: ContextMenuEvent,
+ editor: CKTextEditor | null
+): MenuItem<CommandNames> | null {
+ const titleRow = getTarget(e)?.closest<HTMLElement>(".include-note-title-row");
+ if (!titleRow?.closest("section.include-note[data-attachment-id]")
+ || !editor?.plugins.has("IncludeNote") || !editor.commands.get("convertEmbedToLink")) {
return null;
}
@@ -181,6 +210,10 @@ async function getConvertToLinkItem(e: ContextMenuEvent): Promise<MenuItem<Comma
};
}
+function getTarget(e: ContextMenuEvent) {
+ return e.target instanceof Element ? e.target : null;
+}
+
/** The text editor containing `element`, or `null` when there is none or it is read-only. */
async function getEditingTextEditor(element: Element | null) {
// Checked first: a note shown read-only has no editor, and asking for one waits for a timeout.
diff --git a/packages/ckeditor5/src/plugins/includenote.spec.ts b/packages/ckeditor5/src/plugins/includenote.spec.ts
index c7ac017834..f1f73e4c72 100644
--- a/packages/ckeditor5/src/plugins/includenote.spec.ts
+++ b/packages/ckeditor5/src/plugins/includenote.spec.ts
@@ -333,6 +333,43 @@ describe("IncludeNote", () => {
expect(linkStop).not.toHaveBeenCalled();
});
+ 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");
+ editor.model.change((writer) => {
+ const paragraph = include.nextSibling;
+ if (!paragraph) {
+ throw new Error("Expected a paragraph after the include.");
+ }
+ writer.setSelection(paragraph, 0);
+ });
+
+ const domRoot = editor.editing.view.getDomRoot();
+ const wrapper = domRoot?.querySelector("div.include-note-wrapper");
+ expect(wrapper).not.toBeNull();
+ if (!domRoot || !wrapper) {
+ return;
+ }
+ wrapper.innerHTML = `<div class="include-note-title-row"><button><span></span></button></div>`
+ + `<div class="include-note-content"><button></button></div>`;
+ const [ titleRowButton, contentButton ] = wrapper.querySelectorAll("button");
+
+ // A button of the rendered content keeps its native handling.
+ const contentEvt = new MouseEvent("mousedown", { bubbles: true, cancelable: true });
+ contentButton.dispatchEvent(contentEvt);
+ expect(contentEvt.defaultPrevented).toBe(false);
+ expect(editor.model.document.selection.getSelectedElement()).toBeNull();
+
+ const evt = new MouseEvent("mousedown", { bubbles: true, cancelable: true });
+ const stop = vi.spyOn(evt, "stopPropagation");
+ titleRowButton.querySelector("span")?.dispatchEvent(evt);
+
+ expect(editor.model.document.selection.getSelectedElement()).toBe(include);
+ expect(document.activeElement).toBe(domRoot);
+ // No focus for the button itself; its click still runs.
+ expect(evt.defaultPrevented).toBe(true);
+ expect(stop).not.toHaveBeenCalled();
+ });
+
it("leaves a mousedown inside an embedded collection untouched so the live widget keeps working", () => {
insertIncludeNote(editor, "noteColl", "full");
diff --git a/packages/ckeditor5/src/plugins/includenote.ts b/packages/ckeditor5/src/plugins/includenote.ts
index deb3a205af..3891b5b205 100644
--- a/packages/ckeditor5/src/plugins/includenote.ts
+++ b/packages/ckeditor5/src/plugins/includenote.ts
@@ -487,6 +487,14 @@ 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
+ // in the editor instead of the button, and the click still fires.
+ if ( isTitleRowButton( evt.target ) ) {
+ evt.preventDefault();
+ selectIncludeNoteWidget( domElement, editor );
+ return;
+ }
+
// Interactive embedded content — links, form controls, and live widgets such as collections
// (geo map, calendar, board, table) — needs the browser's native event handling to remain
// usable, e.g. dragging a geo-map marker relies on the mousedown reaching Leaflet. Leave those
@@ -546,6 +554,11 @@ function isInteractiveTarget( target: EventTarget | null, boundary: HTMLElement
return !!match && boundary.contains( match );
}
+/** Whether `target` is in a button of the title row that the host renders above the content. */
+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 );
if ( !modelElement ) {