Skip to content

Build your personal knowledge base with Trilium Notes

fix(client): run the note menu's actions on the quick edit popup's note

Elian Dorana333f44e6d1e
diff --git a/apps/client/src/components/entrypoints.spec.ts b/apps/client/src/components/entrypoints.spec.ts
index 8d74fb837f..7aeed44883 100644
--- a/apps/client/src/components/entrypoints.spec.ts
+++ b/apps/client/src/components/entrypoints.spec.ts
@@ -1,6 +1,7 @@
import type { ElectronApi } from "@triliumnext/commons";
import { beforeEach, describe, expect, it, vi } from "vitest";
+import dialog from "../services/dialog.js";
import froca from "../services/froca.js";
import server from "../services/server.js";
import toastService from "../services/toast.js";
@@ -91,8 +92,7 @@ describe("runActiveNoteCommand", () => {
const tabContext = { ntxId: "tab", note: froca.getNoteFromCache("tabNote") } as NoteContext;
const popupContext = { ntxId: "_popup-editor", note: froca.getNoteFromCache("popupQuery") } as NoteContext;
appContext.tabManager = {
- getActiveContext: () => tabContext,
- getNoteContextById: (ntxId: string | null) => (ntxId === popupContext.ntxId ? popupContext : tabContext)
+ getCommandContext: (ntxId?: string | null) => (ntxId === popupContext.ntxId ? popupContext : tabContext)
} as TabManager;
const post = vi.spyOn(server, "post").mockResolvedValue({ success: true, results: [] });
const triggerEvent = vi.spyOn(appContext, "triggerEvent").mockResolvedValue(undefined);
@@ -108,3 +108,31 @@ describe("runActiveNoteCommand", () => {
expect(post).toHaveBeenCalledWith("sql/execute/tabNote");
});
});
+
+describe("revision commands", () => {
+ const entrypoints = new Entrypoints();
+
+ beforeEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it("save a revision of the note in the context with the command's ntxId, rather than the active tab's", async () => {
+ const tabContext = { ntxId: "tab", noteId: "tabNote" } as NoteContext;
+ const popupContext = { ntxId: "_popup-editor", noteId: "popupNote" } as NoteContext;
+ appContext.tabManager = {
+ getCommandContext: (ntxId?: string | null) => (ntxId === popupContext.ntxId ? popupContext : tabContext)
+ } as TabManager;
+ const post = vi.spyOn(server, "post").mockResolvedValue({});
+ vi.spyOn(toastService, "showMessage").mockImplementation(() => {});
+ vi.spyOn(dialog, "prompt").mockResolvedValue("Milestone");
+
+ await entrypoints.forceSaveRevisionCommand({ ntxId: "_popup-editor" });
+ expect(post).toHaveBeenLastCalledWith("notes/popupNote/revision");
+
+ await entrypoints.saveNamedRevisionCommand({ ntxId: "_popup-editor" });
+ expect(post).toHaveBeenLastCalledWith("notes/popupNote/revision", { description: "Milestone" });
+
+ await entrypoints.forceSaveRevisionCommand();
+ expect(post).toHaveBeenLastCalledWith("notes/tabNote/revision");
+ });
+});
diff --git a/apps/client/src/components/entrypoints.ts b/apps/client/src/components/entrypoints.ts
index 6fdbdd9634..e50ed79ff5 100644
--- a/apps/client/src/components/entrypoints.ts
+++ b/apps/client/src/components/entrypoints.ts
@@ -172,9 +172,7 @@ export default class Entrypoints extends Component {
}
async runActiveNoteCommand({ ntxId: requestedNtxId }: CommandListenerData<"runActiveNote"> = {}) {
- const noteContext = requestedNtxId
- ? appContext.tabManager.getNoteContextById(requestedNtxId)
- : appContext.tabManager.getActiveContext();
+ const noteContext = appContext.tabManager.getCommandContext(requestedNtxId);
if (!noteContext) {
return;
}
@@ -215,16 +213,16 @@ export default class Entrypoints extends Component {
toastService.showMessage(t("entrypoints.note-executed"));
}
- async forceSaveRevisionCommand() {
- const noteId = appContext.tabManager.getActiveContextNoteId();
+ async forceSaveRevisionCommand({ ntxId }: CommandListenerData<"forceSaveRevision"> = {}) {
+ const noteId = appContext.tabManager.getCommandContext(ntxId)?.noteId;
await server.post(`notes/${noteId}/revision`);
toastService.showMessage(t("entrypoints.note-revision-created"));
}
- async saveNamedRevisionCommand() {
- const noteId = appContext.tabManager.getActiveContextNoteId();
+ async saveNamedRevisionCommand({ ntxId }: CommandListenerData<"saveNamedRevision"> = {}) {
+ const noteId = appContext.tabManager.getCommandContext(ntxId)?.noteId;
if (!noteId) return;
const name = await dialog.prompt({
diff --git a/apps/client/src/components/note_context.spec.ts b/apps/client/src/components/note_context.spec.ts
index 75861a93f1..7c0ffa62ea 100644
--- a/apps/client/src/components/note_context.spec.ts
+++ b/apps/client/src/components/note_context.spec.ts
@@ -1,7 +1,27 @@
import { beforeEach, describe, expect, it } from "vitest";
import { buildNote } from "../test/easy-froca.js";
+import appContext from "./app_context.js";
import NoteContext from "./note_context.js";
+import type TabManager from "./tab_manager.js";
+
+describe("NoteContext.isCommandTarget", () => {
+ it("matches a command with its own ntxId, or one without an ntxId while it is the active context", () => {
+ const tabManager = appContext.tabManager;
+ appContext.tabManager = { activeNtxId: "tab" } as TabManager;
+ try {
+ const tab = new NoteContext("tab");
+ const popup = new NoteContext("_popup-editor");
+
+ expect(popup.isCommandTarget("_popup-editor")).toBe(true);
+ expect(tab.isCommandTarget("_popup-editor")).toBe(false);
+ expect(tab.isCommandTarget(undefined)).toBe(true);
+ expect(popup.isCommandTarget(undefined)).toBe(false);
+ } finally {
+ appContext.tabManager = tabManager;
+ }
+ });
+});
describe("NoteContext read-only capability", () => {
let noteContext: NoteContext;
diff --git a/apps/client/src/components/note_context.ts b/apps/client/src/components/note_context.ts
index ba0fdb8575..46fab596bf 100644
--- a/apps/client/src/components/note_context.ts
+++ b/apps/client/src/components/note_context.ts
@@ -333,6 +333,11 @@ class NoteContext extends Component implements EventListener<"entitiesReloaded">
return appContext.tabManager.activeNtxId === this.ntxId;
}
+ /** Whether a command with the given `ntxId` targets this context: `ntxId` is this context's, or is empty while this context is active. */
+ isCommandTarget(ntxId: string | null | undefined) {
+ return ntxId ? ntxId === this.ntxId : this.isActive();
+ }
+
getPojoState() {
if (this.hoistedNoteId !== "root") {
// keeping empty hoisted tab is esp. important for mobile (e.g. opened launcher config)
diff --git a/apps/client/src/components/root_command_executor.ts b/apps/client/src/components/root_command_executor.ts
index 10089addd5..a8dc70c366 100644
--- a/apps/client/src/components/root_command_executor.ts
+++ b/apps/client/src/components/root_command_executor.ts
@@ -54,24 +54,22 @@ export default class RootCommandExecutor extends Component {
this.searchNotesCommand({ ancestorNoteId: noteId });
}
- openNoteExternallyCommand() {
- const noteId = appContext.tabManager.getActiveContextNoteId();
- const mime = appContext.tabManager.getActiveContextNoteMime();
- if (noteId) {
- openService.openNoteExternally(noteId, mime || "");
+ openNoteExternallyCommand({ ntxId }: CommandListenerData<"openNoteExternally">) {
+ const note = appContext.tabManager.getCommandContext(ntxId)?.note;
+ if (note) {
+ openService.openNoteExternally(note.noteId, note.mime);
}
}
- openNoteCustomCommand() {
- const noteId = appContext.tabManager.getActiveContextNoteId();
- const mime = appContext.tabManager.getActiveContextNoteMime();
- if (noteId) {
- openService.openNoteCustom(noteId, mime || "");
+ openNoteCustomCommand({ ntxId }: CommandListenerData<"openNoteCustom">) {
+ const note = appContext.tabManager.getCommandContext(ntxId)?.note;
+ if (note) {
+ openService.openNoteCustom(note.noteId, note.mime);
}
}
- openNoteOnServerCommand() {
- const noteId = appContext.tabManager.getActiveContextNoteId();
+ openNoteOnServerCommand({ ntxId }: CommandListenerData<"openNoteOnServer">) {
+ const noteId = appContext.tabManager.getCommandContext(ntxId)?.noteId;
if (noteId) {
openService.openNoteOnServer(noteId);
}
@@ -137,8 +135,8 @@ export default class RootCommandExecutor extends Component {
});
}
- async showNoteSourceCommand() {
- const notePath = appContext.tabManager.getActiveContextNotePath();
+ async showNoteSourceCommand({ ntxId }: CommandListenerData<"showNoteSource">) {
+ const notePath = appContext.tabManager.getCommandContext(ntxId)?.notePath;
if (notePath) {
await appContext.tabManager.openTabWithNoteWithHoisting(notePath, {
@@ -150,8 +148,8 @@ export default class RootCommandExecutor extends Component {
}
}
- showNoteOCRTextCommand() {
- const noteId = appContext.tabManager.getActiveContextNoteId();
+ showNoteOCRTextCommand({ ntxId }: CommandListenerData<"showNoteOCRText">) {
+ const noteId = appContext.tabManager.getCommandContext(ntxId)?.noteId;
if (noteId) {
appContext.triggerCommand("showOcrTextDialog", {
textUrl: `ocr/notes/${noteId}/text`,
@@ -160,8 +158,8 @@ export default class RootCommandExecutor extends Component {
}
}
- async showAttachmentsCommand() {
- const notePath = appContext.tabManager.getActiveContextNotePath();
+ async showAttachmentsCommand({ ntxId }: CommandListenerData<"showAttachments">) {
+ const notePath = appContext.tabManager.getCommandContext(ntxId)?.notePath;
if (notePath) {
await appContext.tabManager.openTabWithNoteWithHoisting(notePath, {
diff --git a/apps/client/src/components/tab_manager.spec.ts b/apps/client/src/components/tab_manager.spec.ts
index af9ae4a904..1451ee6817 100644
--- a/apps/client/src/components/tab_manager.spec.ts
+++ b/apps/client/src/components/tab_manager.spec.ts
@@ -263,5 +263,11 @@ describe("note contexts outside the tab row", () => {
tm.registerDetachedContext(popupContext);
expect(tm.getNoteContextById("_popup-editor")).toBe(popupContext);
expect(tm.getNoteContexts()).not.toContain(popupContext);
+
+ // `getCommandContext()` returns the context with the given `ntxId`, or the active one without it.
+ const [ tab ] = tm.getNoteContexts();
+ tm.activeNtxId = tab.ntxId;
+ expect(tm.getCommandContext("_popup-editor")).toBe(popupContext);
+ expect(tm.getCommandContext(undefined)).toBe(tab);
});
});
diff --git a/apps/client/src/components/tab_manager.ts b/apps/client/src/components/tab_manager.ts
index cbcd9e9380..86a18c01f1 100644
--- a/apps/client/src/components/tab_manager.ts
+++ b/apps/client/src/components/tab_manager.ts
@@ -228,6 +228,11 @@ export default class TabManager extends Component {
return this.activeNtxId ? this.getNoteContextById(this.activeNtxId).getMainContext() : null;
}
+ /** Returns the note context with the given `ntxId`, or the active one when `ntxId` is empty. */
+ getCommandContext(ntxId: string | null | undefined): NoteContext | null {
+ return ntxId ? this.getNoteContextById(ntxId) : this.getActiveContext();
+ }
+
getActiveContextNotePath(): string | null {
const activeContext = this.getActiveContext();
return activeContext?.notePath ?? null;
diff --git a/apps/client/src/widgets/NoteDetail.tsx b/apps/client/src/widgets/NoteDetail.tsx
index 7612c39391..4ea0379e01 100644
--- a/apps/client/src/widgets/NoteDetail.tsx
+++ b/apps/client/src/widgets/NoteDetail.tsx
@@ -176,8 +176,8 @@ export default function NoteDetail() {
resolve(component);
});
- useTriliumEvent("printActiveNote", () => {
- if (!noteContext?.isActive() || !note) return;
+ useTriliumEvent("printActiveNote", ({ ntxId }) => {
+ if (!noteContext?.isCommandTarget(ntxId) || !note) return;
// PDF printing is handled by the PDF viewer's own print mechanism.
if (note.type === "file" && note.mime === "application/pdf") return;
diff --git a/apps/client/src/widgets/dialogs/revisions.tsx b/apps/client/src/widgets/dialogs/revisions.tsx
index 7afa15f2e5..6db3a9c0ae 100644
--- a/apps/client/src/widgets/dialogs/revisions.tsx
+++ b/apps/client/src/widgets/dialogs/revisions.tsx
@@ -47,8 +47,8 @@ export default function RevisionsDialog() {
const { isMasterDetail, mobileView, switchMobileView, resetMobileView } = useMobileMasterDetail(modalRef);
const isMobile = utils.isMobile();
- useTriliumEvent("showRevisions", async ({ noteId }) => {
- const note = await getNote(noteId);
+ useTriliumEvent("showRevisions", async ({ noteId, ntxId }) => {
+ const note = await getNote(noteId, ntxId);
if (note) {
setNote(note);
// Mobile opens on the revision list; selecting one slides to its detail.
@@ -854,10 +854,10 @@ function FilePreviewInner({ revisionItem, fullRevision }: { revisionItem: Revisi
return t("revisions.preview_not_available");
}
-async function getNote(noteId?: string | null) {
+async function getNote(noteId: string | null | undefined, ntxId: string | null | undefined) {
if (noteId) {
return await froca.getNote(noteId);
}
- return appContext.tabManager.getActiveContextNote();
+ return appContext.tabManager.getCommandContext(ntxId)?.note;
}
diff --git a/apps/client/src/widgets/layout/NoteActions.spec.tsx b/apps/client/src/widgets/layout/NoteActions.spec.tsx
index 2e82815964..d70b79a774 100644
--- a/apps/client/src/widgets/layout/NoteActions.spec.tsx
+++ b/apps/client/src/widgets/layout/NoteActions.spec.tsx
@@ -2,8 +2,9 @@ import { render } from "preact";
import { afterEach, describe, expect, it, vi } from "vitest";
import Component from "../../components/component";
+import NoteContext from "../../components/note_context";
import Dropdown from "../react/Dropdown";
-import { ParentComponent } from "../react/react_utils";
+import { NoteContextContext, ParentComponent } from "../react/react_utils";
import { CommandItem } from "./NoteActions";
// A dialog's focus trap would pull focus out of a menu portaled over it.
@@ -35,13 +36,33 @@ describe("CommandItem", () => {
toggle.click();
await vi.waitFor(() => expect(row()).toBeTruthy());
row()?.click();
- expect(triggerCommand).toHaveBeenCalledExactlyOnceWith("showRevisions");
+ expect(triggerCommand).toHaveBeenCalledExactlyOnceWith("showRevisions", { ntxId: undefined });
await vi.waitFor(() => expect(popup()).toBeNull());
toggle.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowDown", bubbles: true }));
await vi.waitFor(() => expect(row()?.classList.contains("tn-menu-active")).toBe(true));
popup()?.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true }));
expect(triggerCommand).toHaveBeenCalledTimes(2);
- expect(triggerCommand).toHaveBeenLastCalledWith("showRevisions");
+ expect(triggerCommand).toHaveBeenLastCalledWith("showRevisions", { ntxId: undefined });
+ });
+
+ it("passes the ntxId of the surrounding note context", async () => {
+ const parent = new Component();
+ const triggerCommand = vi.spyOn(parent, "triggerCommand").mockReturnValue(undefined);
+ render((
+ <ParentComponent.Provider value={parent}>
+ <NoteContextContext.Provider value={{ ntxId: "_popup-editor" } as NoteContext}>
+ <Dropdown text="Actions">
+ <CommandItem command="printActiveNote" icon="bx bx-printer" text="Print" />
+ </Dropdown>
+ </NoteContextContext.Provider>
+ </ParentComponent.Provider>
+ ), host);
+ host.querySelector<HTMLButtonElement>("button")?.click();
+ const row = () => document.querySelector<HTMLElement>(".tn-popup li.dropdown-item");
+ await vi.waitFor(() => expect(row()).toBeTruthy());
+
+ row()?.click();
+ expect(triggerCommand).toHaveBeenCalledExactlyOnceWith("printActiveNote", { ntxId: "_popup-editor" });
});
});
diff --git a/apps/client/src/widgets/layout/NoteActions.tsx b/apps/client/src/widgets/layout/NoteActions.tsx
index 7d019b7a52..5aad4becf0 100644
--- a/apps/client/src/widgets/layout/NoteActions.tsx
+++ b/apps/client/src/widgets/layout/NoteActions.tsx
@@ -24,7 +24,7 @@ import { isAlwaysFullWidthByType } from "../note_wrapper";
import Dropdown, { type DropdownHandle } from "../react/Dropdown";
import { FormDropdownDivider, FormDropdownSubmenu, FormListHeader, FormListItem, FormListToggleableItem } from "../react/FormList";
import { useIsNoteReadOnly, useNoteContext, useNoteLabel, useNoteLabelBoolean, useNoteLabelOptionalBool, useNoteProperty, useSyncedRef, useTriliumEvent, useTriliumOption } from "../react/hooks";
-import { ParentComponent } from "../react/react_utils";
+import { ParentComponent, useCommandTrigger } from "../react/react_utils";
import NoteActionsCustom from "./NoteActionsCustom";
import { useShareState } from "./NoteBadges";
import { NoteTypeDropdownContent } from "./NoteTypeSwitcher";
@@ -342,11 +342,11 @@ function DevelopmentActions({ note, noteContext }: { note: FNote, noteContext?:
}
export function CommandItem({ icon, text, title, command, disabled }: { icon: string, text: string, title?: string, command: CommandNames | (() => void), disabled?: boolean, destructive?: boolean }) {
- const parentComponent = useContext(ParentComponent);
+ const triggerOwnCommand = useCommandTrigger(typeof command === "string" ? command : undefined);
return <FormListItem
icon={icon}
title={title}
- onClick={typeof command === "function" ? command : () => void parentComponent?.triggerCommand(command)}
+ onClick={typeof command === "function" ? command : triggerOwnCommand}
disabled={disabled}
>{text}</FormListItem>;
}
diff --git a/apps/client/src/widgets/type_widgets/Render.tsx b/apps/client/src/widgets/type_widgets/Render.tsx
index c25b8da43a..abad54b060 100644
--- a/apps/client/src/widgets/type_widgets/Render.tsx
+++ b/apps/client/src/widgets/type_widgets/Render.tsx
@@ -59,8 +59,8 @@ function RenderContent({ note, noteContext, ntxId }: TypeWidgetProps) {
useEffect(refresh, [ note ]);
// Keyboard shortcut.
- useTriliumEvent("renderActiveNote", () => {
- if (!noteContext?.isActive()) return;
+ useTriliumEvent("renderActiveNote", ({ ntxId: eventNtxId }) => {
+ if (!noteContext?.isCommandTarget(eventNtxId)) return;
refresh();
});
diff --git a/apps/client/src/widgets/type_widgets/file/Pdf.spec.tsx b/apps/client/src/widgets/type_widgets/file/Pdf.spec.tsx
index e80d446c5c..bb7f10b72b 100644
--- a/apps/client/src/widgets/type_widgets/file/Pdf.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/file/Pdf.spec.tsx
@@ -68,7 +68,8 @@ beforeEach(() => {
viewScope: {},
setContextData: vi.fn((key: string, value: unknown) => { contextData[key] = value; }),
getContextData: vi.fn((key: string) => contextData[key]),
- isActive: () => true
+ isActive: () => true,
+ isCommandTarget: (ntxId?: string | null) => (ntxId ? ntxId === noteContext.ntxId : noteContext.isActive())
} as unknown as NoteContext;
container = document.createElement("div");
diff --git a/apps/client/src/widgets/type_widgets/file/Pdf.tsx b/apps/client/src/widgets/type_widgets/file/Pdf.tsx
index 3e32b35c22..1e192737e8 100644
--- a/apps/client/src/widgets/type_widgets/file/Pdf.tsx
+++ b/apps/client/src/widgets/type_widgets/file/Pdf.tsx
@@ -320,8 +320,8 @@ export default function PdfPreview({ note, blob, componentId, noteContext, isVis
open.download(url);
});
- useTriliumEvent("printActiveNote", () => {
- if (!noteContext.isActive()) return;
+ useTriliumEvent("printActiveNote", ({ ntxId }) => {
+ if (!noteContext.isCommandTarget(ntxId)) return;
iframeRef.current?.contentWindow?.postMessage({
type: "trilium-print"
}, window.location.origin);