Skip to content

Build your personal knowledge base with Trilium Notes

fix(client): trigger a button's command for the note context it stands in

Elian Doran5f1d035f9b37
diff --git a/apps/client/src/components/app_context.ts b/apps/client/src/components/app_context.ts
index 2150073807..edbdcbe2c7 100644
--- a/apps/client/src/components/app_context.ts
+++ b/apps/client/src/components/app_context.ts
@@ -313,10 +313,7 @@ export type CommandMappings = {
zoomFactor: string;
};
- runActiveNote: CommandData & {
- /** The note to run, for a context that is not a tab, such as the quick edit popup; the active tab's note otherwise. */
- noteId?: string;
- };
+ runActiveNote: CommandData;
scrollContainerTo: CommandData & {
position: number;
};
diff --git a/apps/client/src/components/entrypoints.spec.ts b/apps/client/src/components/entrypoints.spec.ts
index 1537d6b2b2..8d74fb837f 100644
--- a/apps/client/src/components/entrypoints.spec.ts
+++ b/apps/client/src/components/entrypoints.spec.ts
@@ -85,20 +85,24 @@ describe("runActiveNoteCommand", () => {
vi.restoreAllMocks();
});
- it("runs the note the command names, in its own context, rather than the active tab's", async () => {
+ it("runs the note of the context the command names, rather than the active tab's", async () => {
buildNote({ id: "tabNote", title: "Tab", type: "code", mime: "text/x-sqlite;schema=trilium" });
buildNote({ id: "popupQuery", title: "Popup", type: "code", mime: "text/x-sqlite;schema=trilium" });
const tabContext = { ntxId: "tab", note: froca.getNoteFromCache("tabNote") } as NoteContext;
- appContext.tabManager = { getActiveContext: () => tabContext } as TabManager;
+ const popupContext = { ntxId: "_popup-editor", note: froca.getNoteFromCache("popupQuery") } as NoteContext;
+ appContext.tabManager = {
+ getActiveContext: () => tabContext,
+ getNoteContextById: (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);
vi.spyOn(toastService, "showMessage").mockImplementation(() => {});
- await entrypoints.runActiveNoteCommand({ ntxId: "_popup-editor", noteId: "popupQuery" });
+ await entrypoints.runActiveNoteCommand({ ntxId: "_popup-editor" });
expect(post).toHaveBeenCalledWith("sql/execute/popupQuery");
expect(triggerEvent).toHaveBeenCalledWith("sqlQueryResults", expect.objectContaining({ ntxId: "_popup-editor" }));
- // Without a note named, as the badges trigger it, the active tab's note runs.
+ // Without a context named, the active tab's note runs.
post.mockClear();
await entrypoints.runActiveNoteCommand();
expect(post).toHaveBeenCalledWith("sql/execute/tabNote");
diff --git a/apps/client/src/components/entrypoints.ts b/apps/client/src/components/entrypoints.ts
index 8e33e7870a..6fdbdd9634 100644
--- a/apps/client/src/components/entrypoints.ts
+++ b/apps/client/src/components/entrypoints.ts
@@ -171,10 +171,14 @@ export default class Entrypoints extends Component {
await appContext.tabManager.openInSameTab(todayNote.noteId);
}
- async runActiveNoteCommand({ ntxId: requestedNtxId, noteId }: CommandListenerData<"runActiveNote"> = {}) {
- const activeContext = appContext.tabManager.getActiveContext();
- const note = noteId ? await froca.getNote(noteId) : activeContext?.note;
- const ntxId = noteId ? requestedNtxId : activeContext?.ntxId;
+ async runActiveNoteCommand({ ntxId: requestedNtxId }: CommandListenerData<"runActiveNote"> = {}) {
+ const noteContext = requestedNtxId
+ ? appContext.tabManager.getNoteContextById(requestedNtxId)
+ : appContext.tabManager.getActiveContext();
+ if (!noteContext) {
+ return;
+ }
+ const { ntxId, note } = noteContext;
// ctrl+enter is also used elsewhere, so make sure we're running only when appropriate
if (!note || note.type !== "code") {
diff --git a/apps/client/src/components/tab_manager.spec.ts b/apps/client/src/components/tab_manager.spec.ts
index 99f7441a63..af9ae4a904 100644
--- a/apps/client/src/components/tab_manager.spec.ts
+++ b/apps/client/src/components/tab_manager.spec.ts
@@ -1,6 +1,7 @@
import { describe, expect, it, vi } from "vitest";
import appContext from "./app_context.js";
+import NoteContext from "./note_context.js";
import TabManager, { buildNoteContextStatesFromUrl } from "./tab_manager.js";
describe("TabManager tab placement", () => {
@@ -252,3 +253,15 @@ function openEmptyTabs(tm: TabManager, count: number) {
function ntxOrder(tm: TabManager) {
return tm.mainNoteContexts.map((nc) => nc.ntxId);
}
+
+describe("note contexts outside the tab row", () => {
+ it("resolves a registered context by its id without listing it among the tabs", async () => {
+ const tm = new TabManager();
+ await openEmptyTabs(tm, 1);
+ const popupContext = new NoteContext("_popup-editor");
+
+ tm.registerDetachedContext(popupContext);
+ expect(tm.getNoteContextById("_popup-editor")).toBe(popupContext);
+ expect(tm.getNoteContexts()).not.toContain(popupContext);
+ });
+});
diff --git a/apps/client/src/components/tab_manager.ts b/apps/client/src/components/tab_manager.ts
index c06838626e..cbcd9e9380 100644
--- a/apps/client/src/components/tab_manager.ts
+++ b/apps/client/src/components/tab_manager.ts
@@ -70,6 +70,15 @@ export default class TabManager extends Component {
return this.children;
}
+ /** Note contexts outside the tab row, such as the quick edit popup's, which commands can still name by `ntxId`. */
+ private detachedContexts = new Map<string, NoteContext>();
+
+ registerDetachedContext(noteContext: NoteContext) {
+ if (noteContext.ntxId) {
+ this.detachedContexts.set(noteContext.ntxId, noteContext);
+ }
+ }
+
get mainNoteContexts(): NoteContext[] {
return this.noteContexts.filter((nc) => !nc.mainNtxId);
}
@@ -201,7 +210,8 @@ export default class TabManager extends Component {
}
getNoteContextById(ntxId: string | null): NoteContext {
- const noteContext = this.noteContexts.find((nc) => nc.ntxId === ntxId);
+ const noteContext = this.noteContexts.find((nc) => nc.ntxId === ntxId)
+ ?? (ntxId ? this.detachedContexts.get(ntxId) : undefined);
if (!noteContext) {
throw new Error(`Cannot find noteContext id='${ntxId}'`);
diff --git a/apps/client/src/widgets/dialogs/PopupEditor.spec.tsx b/apps/client/src/widgets/dialogs/PopupEditor.spec.tsx
index 404de36cb9..ed473ceb86 100644
--- a/apps/client/src/widgets/dialogs/PopupEditor.spec.tsx
+++ b/apps/client/src/widgets/dialogs/PopupEditor.spec.tsx
@@ -9,6 +9,7 @@ const mocks = vi.hoisted(() => ({
triggerCommand: vi.fn(),
openInNewTab: vi.fn(),
openContextWithNote: vi.fn(),
+ registerDetachedContext: vi.fn(),
getNote: vi.fn(),
getAttachment: vi.fn(),
/** Every context the popup created, newest last — one is built per open. */
@@ -21,7 +22,8 @@ vi.mock("../../components/app_context", () => ({
triggerCommand: mocks.triggerCommand,
tabManager: {
openInNewTab: mocks.openInNewTab,
- openContextWithNote: mocks.openContextWithNote
+ openContextWithNote: mocks.openContextWithNote,
+ registerDetachedContext: mocks.registerDetachedContext
}
}
}));
@@ -212,6 +214,8 @@ describe("PopupEditor", () => {
});
expect(modal()?.dataset.shown).toBe("true");
expect(document.body.classList.contains("popup-editor-open")).toBe(true);
+ // Registered so that a command naming the popup's context can find it.
+ expect(mocks.registerDetachedContext).toHaveBeenCalledWith(lastContext());
mocks.getNote.mockResolvedValue(fakeNote([ "readOnly" ]));
await openPopup({ noteIdOrPath: "root/n2" });
diff --git a/apps/client/src/widgets/dialogs/PopupEditor.tsx b/apps/client/src/widgets/dialogs/PopupEditor.tsx
index 8e3c4d3d90..badafe0102 100644
--- a/apps/client/src/widgets/dialogs/PopupEditor.tsx
+++ b/apps/client/src/widgets/dialogs/PopupEditor.tsx
@@ -65,6 +65,7 @@ export default function PopupEditor() {
// Events triggered at note context level (e.g. the save indicator) would not work since the note context has no parent component. Propagate events to parent component so that they can be handled properly.
noteContext.triggerEvent = (name, data) => parentComponent?.handleEventInChildren(name, data);
+ appContext.tabManager.registerDetachedContext(noteContext);
setNoteContext(noteContext);
setShown(true);
});
diff --git a/apps/client/src/widgets/layout/ActiveContentBadges.tsx b/apps/client/src/widgets/layout/ActiveContentBadges.tsx
index 1138ec2a74..7f99ee146c 100644
--- a/apps/client/src/widgets/layout/ActiveContentBadges.tsx
+++ b/apps/client/src/widgets/layout/ActiveContentBadges.tsx
@@ -26,7 +26,7 @@ const executeOption: BookProperty = {
type: "button",
icon: "bx bx-play",
label: t("active_content_badges.menu_execute_now"),
- onClick: context => context.triggerCommand("runActiveNote")
+ onClick: context => context.triggerCommand("runActiveNote", { ntxId: context.ntxId })
};
const typeMappings: Record<ActiveContentInfo["type"], {
diff --git a/apps/client/src/widgets/layout/NoteBadges.tsx b/apps/client/src/widgets/layout/NoteBadges.tsx
index d0cd84907c..f805aa83da 100644
--- a/apps/client/src/widgets/layout/NoteBadges.tsx
+++ b/apps/client/src/widgets/layout/NoteBadges.tsx
@@ -166,7 +166,7 @@ function ClippedNoteBadge() {
}
export function ExecuteBadge() {
- const { note, parentComponent } = useNoteContext();
+ const { note, ntxId, parentComponent } = useNoteContext();
const isScript = note?.isTriliumScript();
const isSql = note?.isTriliumSqlite();
const isExecutable = isScript || isSql;
@@ -183,7 +183,7 @@ export function ExecuteBadge() {
icon="bx bx-play"
text={title || (isScript ? t("breadcrumb_badges.execute_script") : t("breadcrumb_badges.execute_sql"))}
tooltip={executeDescription || (isScript ? t("breadcrumb_badges.execute_script_description") : t("breadcrumb_badges.execute_sql_description"))}
- onClick={() => parentComponent.triggerCommand("runActiveNote")}
+ onClick={() => parentComponent.triggerCommand("runActiveNote", { ntxId })}
/>
);
}
diff --git a/apps/client/src/widgets/react/ActionButton.spec.tsx b/apps/client/src/widgets/react/ActionButton.spec.tsx
index ceb6f48140..4dad85b77b 100644
--- a/apps/client/src/widgets/react/ActionButton.spec.tsx
+++ b/apps/client/src/widgets/react/ActionButton.spec.tsx
@@ -3,7 +3,10 @@ import { render } from "preact";
import { act } from "preact/test-utils";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import Component from "../../components/component";
+import NoteContext from "../../components/note_context";
import ActionButton from "./ActionButton";
+import { NoteContextContext, ParentComponent } from "./react_utils";
describe("ActionButton", () => {
let container: HTMLElement;
@@ -21,6 +24,25 @@ describe("ActionButton", () => {
}
});
+ it("triggers its command from the surrounding component, naming the note context it stands in", () => {
+ const parentComponent = new Component();
+ const triggerCommand = vi.spyOn(parentComponent, "triggerCommand").mockReturnValue(undefined);
+
+ act(() => render(
+ <ParentComponent.Provider value={parentComponent}>
+ <NoteContextContext.Provider value={new NoteContext("_popup-editor")}>
+ <ActionButton icon="bx bx-play" text="Run" triggerCommand="runActiveNote" />
+ </NoteContextContext.Provider>
+ </ParentComponent.Provider>, container));
+
+ const button = container.querySelector("button");
+ expect(button).not.toBeNull();
+ act(() => button?.click());
+
+ expect(triggerCommand).toHaveBeenCalledWith("runActiveNote", { ntxId: "_popup-editor" });
+ });
+
+
it("dismisses its tooltip when pressed, so it cannot sit on top of what the press opened", async () => {
const onClick = vi.fn();
await act(async () => render(
diff --git a/apps/client/src/widgets/react/ActionButton.tsx b/apps/client/src/widgets/react/ActionButton.tsx
index fe31672739..c549a2a8cb 100644
--- a/apps/client/src/widgets/react/ActionButton.tsx
+++ b/apps/client/src/widgets/react/ActionButton.tsx
@@ -7,6 +7,7 @@ import keyboard_actions from "../../services/keyboard_actions";
import { formatShortcut, joinShortcut } from "../../services/keyboard_shortcut_display";
import { isMobile } from "../../services/utils";
import { useStaticTooltip } from "./hooks";
+import { useCommandTrigger } from "./react_utils";
export interface ActionButtonProps extends Pick<
HTMLAttributes<HTMLButtonElement>,
@@ -39,6 +40,7 @@ const cachedIsMobile = isMobile();
export default function ActionButton({ text, icon, className, triggerCommand, titlePosition, tooltipClass, tooltipHtml, noIconActionClass, noTooltipOnTouch, frame, active, disabled, ...restProps }: ActionButtonProps) {
const buttonRef = useRef<HTMLButtonElement>(null);
const [ keyboardShortcut, setKeyboardShortcut ] = useState<string[]>();
+ const triggerOwnCommand = useCommandTrigger(triggerCommand);
const title = keyboardShortcut?.length
? `${text} (${keyboardShortcut.map((shortcut) => joinShortcut(formatShortcut(shortcut))).join(", ")})`
@@ -84,7 +86,7 @@ export default function ActionButton({ text, icon, className, triggerCommand, ti
// (e.g. the error-dismiss button stealing the login form's Enter).
type="button"
class={`${className ?? ""} ${!noIconActionClass ? "icon-action" : "btn"} ${icon} ${frame ? "btn btn-primary" : ""} ${disabled ? "disabled" : ""} ${active ? "active" : ""}`}
- data-trigger-command={triggerCommand}
+ onClick={triggerOwnCommand}
// Only where the tooltip that would otherwise carry it has been declined: elsewhere the
// tooltip is the button's name, and a second one here would be read out beside it.
aria-label={declined ? title : undefined}
diff --git a/apps/client/src/widgets/react/Button.tsx b/apps/client/src/widgets/react/Button.tsx
index a8edcc4db6..9fab8db1a7 100644
--- a/apps/client/src/widgets/react/Button.tsx
+++ b/apps/client/src/widgets/react/Button.tsx
@@ -11,6 +11,7 @@ import ActionButton from "./ActionButton";
import Dropdown from "./Dropdown";
import { useStaticTooltip } from "./hooks";
import Icon from "./Icon";
+import { useCommandTrigger } from "./react_utils";
import { renderShortcutKbds } from "./shortcut_kbd";
const cachedIsMobile = isMobile();
@@ -42,6 +43,7 @@ export interface ButtonProps {
}
function Button({ name, buttonRef, className, text, onClick, keyboardShortcut, icon, kind, disabled, disabledTooltip, size, style, triggerCommand, ...restProps }: ButtonProps) {
+ const triggerOwnCommand = useCommandTrigger(triggerCommand);
// Memoize classes array to prevent recreation
const classes = useMemo(() => {
const classList: string[] = ["btn"];
@@ -86,11 +88,10 @@ function Button({ name, buttonRef, className, text, onClick, keyboardShortcut, i
name={name}
className={classes}
type={onClick || triggerCommand ? "button" : "submit"}
- onClick={onClick}
+ onClick={onClick ?? triggerOwnCommand}
ref={buttonRef}
disabled={disabled}
style={style}
- data-trigger-command={triggerCommand}
{...restProps}
>
{icon && <Icon icon={`bx ${icon}`} />}
diff --git a/apps/client/src/widgets/react/LinkButton.tsx b/apps/client/src/widgets/react/LinkButton.tsx
index 2dfffe7b32..daf864f47c 100644
--- a/apps/client/src/widgets/react/LinkButton.tsx
+++ b/apps/client/src/widgets/react/LinkButton.tsx
@@ -1,6 +1,7 @@
import clsx from "clsx";
import { ComponentChild, HTMLAttributes } from "preact";
import { CommandNames } from "../../components/app_context";
+import { useCommandTrigger } from "./react_utils";
interface LinkButtonProps {
onClick?: () => void;
@@ -10,18 +11,20 @@ interface LinkButtonProps {
}
export default function LinkButton({ onClick, text, triggerCommand, className }: LinkButtonProps) {
+ const triggerOwnCommand = useCommandTrigger(triggerCommand);
+ const handleClick = onClick ?? triggerOwnCommand;
+
return (
<a class={clsx("tn-link", className)} href="#"
- data-trigger-command={triggerCommand}
role="button"
onKeyDown={(e)=> {
if (e.code === "Space") {
- onClick?.();
+ handleClick?.();
}
}}
onClick={(e) => {
e.preventDefault();
- onClick?.();
+ handleClick?.();
}}>
{text}
</a>
diff --git a/apps/client/src/widgets/react/NotePropertyMenu.tsx b/apps/client/src/widgets/react/NotePropertyMenu.tsx
index 6c99f9c9a1..618993ccd1 100644
--- a/apps/client/src/widgets/react/NotePropertyMenu.tsx
+++ b/apps/client/src/widgets/react/NotePropertyMenu.tsx
@@ -9,10 +9,12 @@ import { FormDropdownDivider, FormDropdownSubmenu, FormListItem, FormListTogglea
import HelpTooltipButton from "./HelpTooltipButton";
import FormTextBox from "./FormTextBox";
import { useNoteLabel, useNoteLabelBoolean } from "./hooks";
-import { ParentComponent } from "./react_utils";
+import { NoteContextContext, ParentComponent } from "./react_utils";
export interface ClickContext {
note: FNote;
+ /** The note context the menu stands in, when it stands in one other than a split's. */
+ ntxId?: string | null;
triggerCommand: NoteContextAwareWidget["triggerCommand"];
}
@@ -187,6 +189,7 @@ function OptionGroupPropertyView({ note, property }: { note: FNote, property: Op
function ButtonPropertyView({ note, property }: { note: FNote, property: ButtonProperty }) {
const parentComponent = useContext(ParentComponent);
+ const noteContext = useContext(NoteContextContext);
return (
<FormListItem
@@ -196,6 +199,7 @@ function ButtonPropertyView({ note, property }: { note: FNote, property: ButtonP
if (!parentComponent) return;
property.onClick({
note,
+ ntxId: noteContext?.ntxId,
triggerCommand: parentComponent.triggerCommand.bind(parentComponent)
});
}}
@@ -206,8 +210,10 @@ function ButtonPropertyView({ note, property }: { note: FNote, property: ButtonP
function SplitButtonPropertyView({ note, property }: { note: FNote, property: SplitButtonProperty }) {
const parentComponent = useContext(ParentComponent);
const ItemsComponent = property.items;
+ const noteContext = useContext(NoteContextContext);
const clickContext = parentComponent && {
note,
+ ntxId: noteContext?.ntxId,
triggerCommand: parentComponent.triggerCommand.bind(parentComponent)
};
diff --git a/apps/client/src/widgets/react/react_utils.tsx b/apps/client/src/widgets/react/react_utils.tsx
index 751561f719..307c95e836 100644
--- a/apps/client/src/widgets/react/react_utils.tsx
+++ b/apps/client/src/widgets/react/react_utils.tsx
@@ -1,4 +1,7 @@
import { ComponentChild, createContext, render, type JSX, type RefObject } from "preact";
+import { useContext } from "preact/hooks";
+
+import type { CommandMappings, CommandNames } from "../../components/app_context";
import Component from "../../components/component";
import NoteContext from "../../components/note_context";
@@ -6,6 +9,20 @@ export const ParentComponent = createContext<Component | null>(null);
export const NoteContextContext = createContext<NoteContext | null>(null);
+/**
+ * A click handler that triggers `command` from the surrounding component with the `ntxId` of the
+ * surrounding `NoteContextContext`, so a handler can act on the note of a context that is not the
+ * active tab, such as the quick edit popup's. Undefined when there is no command to trigger.
+ */
+export function useCommandTrigger(command: CommandNames | undefined) {
+ const parentComponent = useContext(ParentComponent);
+ const noteContext = useContext(NoteContextContext);
+
+ return command && (() => {
+ parentComponent?.triggerCommand(command, { ntxId: noteContext?.ntxId } as CommandMappings[typeof command]);
+ });
+}
+
/**
* Whether the container (e.g. a dialog) holding the current note view is actually shown. False inside a dialog
* that's hidden but kept mounted in the DOM (e.g. the quick-edit popup with `keepInDom`), so descendants like
diff --git a/apps/client/src/widgets/type_widgets/code/Code.tsx b/apps/client/src/widgets/type_widgets/code/Code.tsx
index d48d2f5e69..b457b06c4b 100644
--- a/apps/client/src/widgets/type_widgets/code/Code.tsx
+++ b/apps/client/src/widgets/type_widgets/code/Code.tsx
@@ -138,7 +138,7 @@ export function EditableCode({ note, ntxId, noteContext, debounceUpdate, parentC
await spacedUpdate.updateNowIfNecessary();
}
- return await parentComponent?.parent?.triggerCommand("runActiveNote", { ...params, noteId: note.noteId });
+ return await parentComponent?.parent?.triggerCommand("runActiveNote", params);
}
});