Skip to content

Build your personal knowledge base with Trilium Notes

client: fix some issues

Adorian Doran2bd5ad05f85a
diff --git a/apps/client/src/components/note_context.ts b/apps/client/src/components/note_context.ts
index 72c86f2c22..d2d0ec0d41 100644
--- a/apps/client/src/components/note_context.ts
+++ b/apps/client/src/components/note_context.ts
@@ -18,6 +18,7 @@ import type { HeadingContext } from "../widgets/sidebar/TableOfContents.js";
import type { ChatHighlightsContext } from "../widgets/type_widgets/llm_chat/chat_highlights.js";
import appContext, { type EventData, type EventListener } from "./app_context.js";
import Component from "./component.js";
+import type { HistoryEntry } from "./tab_manager.js";
export interface SetNoteOpts {
triggerSwitchEvent?: unknown;
@@ -26,6 +27,8 @@ export interface SetNoteOpts {
keepActiveDialog?: boolean;
/** If true, the note is not added to the recent notes, as for an included note being edited. */
skipRecentNotes?: boolean;
+ /** The `switchToHistoryEntry()` call that shows the note. Pinned tabs pass it on. */
+ historyEntry?: HistoryEntry;
}
export type GetTextEditorCallback = (editor: CKTextEditor) => void;
@@ -202,7 +205,7 @@ class NoteContext extends Component implements EventListener<"entitiesReloaded">
activate: true,
viewScope,
hoistedNoteId: this.hoistedNoteId,
- redirectedFrom: this
+ historyEntry: opts.historyEntry
});
}
diff --git a/apps/client/src/components/tab_manager.spec.ts b/apps/client/src/components/tab_manager.spec.ts
index 122f59a53f..f0620a7d22 100644
--- a/apps/client/src/components/tab_manager.spec.ts
+++ b/apps/client/src/components/tab_manager.spec.ts
@@ -1,4 +1,4 @@
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { buildNote } from "../test/easy-froca.js";
import appContext from "./app_context.js";
@@ -315,6 +315,11 @@ describe("note contexts outside the tab row", () => {
describe("going to an entry of the navigation history", () => {
let tm: TabManager;
+ // Unlike browsers, happy-dom fires `hashchange` for `pushState()` and `replaceState()`.
+ const stopHashChange = (e: Event) => e.stopImmediatePropagation();
+ beforeAll(() => window.addEventListener("hashchange", stopHashChange, true));
+ afterAll(() => window.removeEventListener("hashchange", stopHashChange, true));
+
beforeEach(() => {
// `appContext.triggerEvent` passes on the note switch, and an earlier test mocks it.
vi.restoreAllMocks();
@@ -399,6 +404,36 @@ describe("going to an entry of the navigation history", () => {
expect(window.location.hash).toBe(`#root/historyA?ntxId=${opened?.ntxId}`);
});
+ it("pushes a note a pinned tab opens while the entry is still loading", async () => {
+ const pinnedTab = await tm.openEmptyTab();
+ await tm.activateNoteContext(pinnedTab.ntxId);
+ await pinnedTab.setNote("root/historyA");
+ await pinnedTab.setNote("root/historyB");
+ pinnedTab.pinned = true;
+
+ window.history.replaceState(null, "", `#root/historyA?ntxId=${pinnedTab.ntxId}`);
+ let showA: (notePath: string) => void = () => {};
+ const resolvePath = vi.spyOn(pinnedTab, "getResolvedNotePath")
+ .mockReturnValueOnce(new Promise((resolve) => { showA = resolve; }));
+ const pushState = vi.spyOn(window.history, "pushState");
+ const replaceState = vi.spyOn(window.history, "replaceState");
+
+ const restoring = tm.switchToHistoryEntry(
+ pinnedTab.ntxId, "root/historyA", { viewMode: "default" }
+ );
+ await vi.waitFor(() => expect(resolvePath).toHaveBeenCalledOnce());
+ // A click in the tree while the entry loads.
+ const clicked = await pinnedTab.setNote("root/historyC");
+ showA("root/historyA");
+ await restoring;
+
+ expect(replaceState).not.toHaveBeenCalled();
+ expect(pushState).toHaveBeenCalledTimes(2);
+ expect(pushState).toHaveBeenNthCalledWith(
+ 1, null, "", `#root/historyC?ntxId=${clicked?.ntxId}`
+ );
+ });
+
it("pushes a tab switch made while the entry is still loading", async () => {
const first = await tm.openEmptyTab();
const second = await tm.openEmptyTab();
diff --git a/apps/client/src/components/tab_manager.ts b/apps/client/src/components/tab_manager.ts
index 3d9c14605a..01a73bdf2f 100644
--- a/apps/client/src/components/tab_manager.ts
+++ b/apps/client/src/components/tab_manager.ts
@@ -31,14 +31,19 @@ export interface NoteContextState {
lastActiveNtxId?: string | null;
}
+/** A `switchToHistoryEntry()` call, and the note context that shows its entry. */
+export interface HistoryEntry {
+ noteContext: NoteContext;
+}
+
export default class TabManager extends Component {
public children: NoteContext[];
public mutex: Mutex;
public activeNtxId: string | null;
public recentlyClosedTabs: TabState[];
public tabsUpdate: SpacedUpdate;
- /** The note context that shows the entry of the latest `switchToHistoryEntry()` call. */
- private historyEntry: { noteContext: NoteContext } | null = null;
+ /** The current `switchToHistoryEntry()` call, until another note context is activated. */
+ private historyEntry: HistoryEntry | null = null;
constructor() {
super();
@@ -311,12 +316,12 @@ export default class TabManager extends Component {
) {
const noteContext = this.noteContexts.find((nc) => nc.ntxId === ntxId) ||
await this.openEmptyTab();
- const historyEntry = { noteContext };
+ const historyEntry: HistoryEntry = { noteContext };
this.historyEntry = historyEntry;
try {
await this.activateNoteContext(noteContext.ntxId);
- await noteContext.setNote(notePath, { viewScope });
+ await noteContext.setNote(notePath, { viewScope, historyEntry });
} finally {
if (this.historyEntry === historyEntry) {
this.historyEntry = null;
@@ -470,8 +475,8 @@ export default class TabManager extends Component {
pinned?: boolean | null;
/** Where the new tab is placed in the row. Defaults to `"end"`; link/middle-click opens pass `"afterCurrent"`. */
placement?: TabPlacement | null;
- /** The pinned note context whose navigation opens this tab. */
- redirectedFrom?: NoteContext | null;
+ /** The `switchToHistoryEntry()` call that opens this tab. */
+ historyEntry?: HistoryEntry | null;
} = {}
): Promise<NoteContext> {
const activate = !!opts.activate;
@@ -496,9 +501,9 @@ export default class TabManager extends Component {
}
if (activate && noteContext.notePath) {
- // The new tab continues the navigation of the history entry it was redirected from.
- if (opts.redirectedFrom && this.historyEntry?.noteContext === opts.redirectedFrom) {
- this.historyEntry.noteContext = noteContext;
+ // The new tab shows the history entry in place of the pinned tab.
+ if (opts.historyEntry) {
+ opts.historyEntry.noteContext = noteContext;
}
this.activateNoteContext(noteContext.ntxId, false);
diff --git a/apps/client/src/menus/launcher_button_context_menu.spec.ts b/apps/client/src/menus/launcher_button_context_menu.spec.ts
new file mode 100644
index 0000000000..8cab2904ac
--- /dev/null
+++ b/apps/client/src/menus/launcher_button_context_menu.spec.ts
@@ -0,0 +1,74 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import FBranch from "../entities/fbranch";
+import type FNote from "../entities/fnote";
+import froca from "../services/froca";
+import { buildNote } from "../test/easy-froca";
+import type { ContextMenuEvent, MenuItem } from "./context_menu";
+import { showLauncherContextMenu } from "./launcher_button_context_menu";
+
+const mocks = vi.hoisted(() => ({
+ show: vi.fn(),
+ put: vi.fn(async () => ({ success: true })),
+ moveToParentNote: vi.fn()
+}));
+
+vi.mock("./context_menu", () => ({ default: { show: mocks.show } }));
+vi.mock("../components/app_context", () => ({ default: {} }));
+vi.mock("../services/server", () => ({ default: { put: mocks.put } }));
+vi.mock("../services/branches", () => ({ default: { moveToParentNote: mocks.moveToParentNote } }));
+vi.mock("../services/options", () => ({ default: { get: () => "vertical" } }));
+vi.mock("../services/i18n", () => ({ t: (key: string) => key }));
+
+beforeEach(() => {
+ vi.clearAllMocks();
+});
+
+describe("Remove from launch bar", () => {
+ /** A note dropped onto the launch bar that is also bookmarked. */
+ function bookmarkedLauncher() {
+ buildNote({
+ id: "_lbVisibleLaunchers",
+ title: "Visible Launchers",
+ children: [ { id: "dropped", title: "Dropped" } ]
+ });
+ const note = froca.notes["dropped"];
+ froca.branches["_lbBookmarks_dropped"] = new FBranch(froca, {
+ branchId: "_lbBookmarks_dropped",
+ noteId: "dropped",
+ parentNoteId: "_lbBookmarks",
+ notePosition: 0,
+ fromSearchNote: false
+ });
+ note.addParent("_lbBookmarks", "_lbBookmarks_dropped", false);
+ return note;
+ }
+
+ async function remove(note: FNote, parentNoteId?: string) {
+ const event = { pageX: 0, pageY: 0, preventDefault: () => {} } as ContextMenuEvent;
+ await showLauncherContextMenu(note, event, { parentNoteId });
+ const { items, selectMenuItemHandler } = mocks.show.mock.lastCall?.[0] ?? {};
+ const removeTitle = "launcher_button_context_menu.remove_from_launch_bar";
+ const removeItem = (items as MenuItem<string>[])
+ .find((item) => "title" in item && item.title === removeTitle);
+ expect(removeItem).toBeDefined();
+ selectMenuItemHandler(removeItem);
+ }
+
+ it("removes the placement of the button that was clicked", async () => {
+ const note = bookmarkedLauncher();
+
+ await remove(note, "_lbVisibleLaunchers");
+ await vi.waitFor(() => expect(mocks.moveToParentNote).toHaveBeenCalledExactlyOnceWith(
+ [ "_lbVisibleLaunchers_dropped" ], "_lbRoot__lbAvailableLaunchers"
+ ));
+ expect(mocks.put).not.toHaveBeenCalled();
+
+ // A bookmark button names no section, so the bookmark goes.
+ await remove(note);
+ await vi.waitFor(() => expect(mocks.put).toHaveBeenCalledExactlyOnceWith(
+ "notes/dropped/toggle-in-parent/_lbBookmarks/false"
+ ));
+ expect(mocks.moveToParentNote).toHaveBeenCalledOnce();
+ });
+});
diff --git a/apps/client/src/menus/launcher_button_context_menu.ts b/apps/client/src/menus/launcher_button_context_menu.ts
index a839dfb8fb..a650f41d10 100644
--- a/apps/client/src/menus/launcher_button_context_menu.ts
+++ b/apps/client/src/menus/launcher_button_context_menu.ts
@@ -20,9 +20,23 @@ function getBookmarkBranch(launcherNote: FNote) {
return launcherNote.getParentBranches().find((b) => b.parentNoteId === "_lbBookmarks");
}
-async function removeFromLaunchBar(launcherNote: FNote) {
- const bookmarkBranch = getBookmarkBranch(launcherNote);
- if (bookmarkBranch) {
+/**
+ * Returns the branch that shows the note in the launch bar section `parentNoteId`. Without a
+ * section, a bookmark comes before a launcher.
+ */
+function getLaunchBarBranch(launcherNote: FNote, parentNoteId: string | undefined) {
+ if (parentNoteId) {
+ return launcherNote.getParentBranches().find((b) => b.parentNoteId === parentNoteId);
+ }
+
+ return getBookmarkBranch(launcherNote) ?? getVisibleLauncherBranch(launcherNote);
+}
+
+async function removeFromLaunchBar(launcherNote: FNote, parentNoteId: string | undefined) {
+ const launcherBranch = getLaunchBarBranch(launcherNote, parentNoteId);
+ if (!launcherBranch) return;
+
+ if (launcherBranch.parentNoteId === "_lbBookmarks") {
// Individual bookmarks are represented via a branch under `_lbBookmarks`; removing them
// from the launch bar is the same as unbookmarking the note.
const resp = await server.put<ToggleInParentResponse>(
@@ -34,9 +48,6 @@ async function removeFromLaunchBar(launcherNote: FNote) {
return;
}
- const launcherBranch = getVisibleLauncherBranch(launcherNote);
- if (!launcherBranch) return;
-
const isMobileLauncher = launcherBranch.parentNoteId === "_lbMobileVisibleLaunchers";
// Branch IDs in the hidden subtree follow the `${parentNoteId}_${noteId}` convention,
// so the branch linking `_lb(Mobile)?Root` to the "available" launchers root is predictable.
@@ -46,9 +57,12 @@ async function removeFromLaunchBar(launcherNote: FNote) {
await branchService.moveToParentNote([launcherBranch.branchId], targetBranchId);
}
-export function canRemoveFromLaunchBar(launcherNote: FNote | null | undefined) {
+export function canRemoveFromLaunchBar(
+ launcherNote: FNote | null | undefined,
+ parentNoteId?: string
+) {
if (!launcherNote) return false;
- return !!(getVisibleLauncherBranch(launcherNote) || getBookmarkBranch(launcherNote));
+ return !!getLaunchBarBranch(launcherNote, parentNoteId);
}
export interface ShowLauncherContextMenuOptions<T extends string> {
@@ -56,6 +70,8 @@ export interface ShowLauncherContextMenuOptions<T extends string> {
extraItems?: MenuItem<T>[];
/** Handler for the {@link extraItems}. The "Remove from launch bar" item is handled internally and will not be forwarded. */
onCommand?: (command: T | undefined) => void;
+ /** The launch bar section that shows the button. "Remove from launch bar" removes it there. */
+ parentNoteId?: string;
}
const REMOVE_COMMAND = "__removeFromLaunchBar__";
@@ -75,7 +91,7 @@ export async function showLauncherContextMenu<T extends string>(
// Widget-specific items (e.g. "Open in new tab" for note launchers, history entries, "Remove from launch bar").
const widgetItems = [...(options.extraItems ?? [])] as MenuItem<string>[];
- if (canRemoveFromLaunchBar(launcherNote)) {
+ if (canRemoveFromLaunchBar(launcherNote, options.parentNoteId)) {
if (widgetItems.length > 0) {
widgetItems.push({ kind: "separator" });
}
@@ -99,7 +115,7 @@ export async function showLauncherContextMenu<T extends string>(
selectMenuItemHandler: ({ command }) => {
if (command === REMOVE_COMMAND) {
if (launcherNote) {
- void removeFromLaunchBar(launcherNote);
+ void removeFromLaunchBar(launcherNote, options.parentNoteId);
}
return;
}
diff --git a/apps/client/src/widgets/launch_bar/GenericButtons.tsx b/apps/client/src/widgets/launch_bar/GenericButtons.tsx
index d09c2892b2..7fdfe0ff1a 100644
--- a/apps/client/src/widgets/launch_bar/GenericButtons.tsx
+++ b/apps/client/src/widgets/launch_bar/GenericButtons.tsx
@@ -13,8 +13,10 @@ export function CustomNoteLauncher(props: {
getTargetNoteId: (launcherNote: FNote) => string | null | Promise<string | null>;
getHoistedNoteId?: (launcherNote: FNote) => string | null;
keyboardShortcut?: string;
+ /** The launch bar section that shows the button. See `ShowLauncherContextMenuOptions`. */
+ parentNoteId?: string;
}) {
- const { launcherNote, getTargetNoteId, getHoistedNoteId } = props;
+ const { launcherNote, getTargetNoteId, getHoistedNoteId, parentNoteId } = props;
const { icon, title } = useLauncherIconAndTitle(launcherNote);
const launch = useCallback(async (evt: MouseEvent | KeyboardEvent) => {
@@ -39,6 +41,7 @@ export function CustomNoteLauncher(props: {
const hoistedNoteId = getHoistedNoteId?.(launcherNote) ?? null;
const linkItems = targetNoteId ? link_context_menu.getItems(evt) : [];
await showLauncherContextMenu<CommandNames>(launcherNote, evt, {
+ parentNoteId,
extraItems: linkItems,
onCommand: (command) => {
if (command && targetNoteId) {
diff --git a/apps/client/src/widgets/launch_bar/LauncherContainer.spec.tsx b/apps/client/src/widgets/launch_bar/LauncherContainer.spec.tsx
index d0c3fd6c41..eb1d6583b1 100644
--- a/apps/client/src/widgets/launch_bar/LauncherContainer.spec.tsx
+++ b/apps/client/src/widgets/launch_bar/LauncherContainer.spec.tsx
@@ -20,10 +20,17 @@ vi.mock("./RecordMeetingButton", () => ({
}));
vi.mock("./GenericButtons", async (importOriginal) => ({
...await importOriginal<typeof import("./GenericButtons")>(),
- CustomNoteLauncher: ({ launcherNote, getTargetNoteId }: {
+ CustomNoteLauncher: ({ launcherNote, getTargetNoteId, parentNoteId }: {
launcherNote: FNote,
- getTargetNoteId: (launcherNote: FNote) => unknown
- }) => <span className="custom-note-launcher" data-target={`${getTargetNoteId(launcherNote)}`} />
+ getTargetNoteId: (launcherNote: FNote) => unknown,
+ parentNoteId?: string
+ }) => (
+ <span
+ className="custom-note-launcher"
+ data-target={`${getTargetNoteId(launcherNote)}`}
+ data-parent={`${parentNoteId}`}
+ />
+ )
}));
let container: HTMLDivElement;
@@ -141,6 +148,8 @@ describe("LauncherContainer", () => {
const slot = container.querySelector(".launcher-slot[data-launcher-id='clonedNote']");
const launcher = slot?.querySelector(".custom-note-launcher");
expect(launcher?.getAttribute("data-target")).toBe("clonedNote");
+ // "Remove from launch bar" removes this placement, not a bookmark of the note.
+ expect(launcher?.getAttribute("data-parent")).toBe("_lbVisibleLaunchers");
const bar = container.querySelector("#launcher-container");
expect(bar).not.toBeNull();
diff --git a/apps/client/src/widgets/launch_bar/LauncherContainer.tsx b/apps/client/src/widgets/launch_bar/LauncherContainer.tsx
index 3994eae410..b13274337d 100644
--- a/apps/client/src/widgets/launch_bar/LauncherContainer.tsx
+++ b/apps/client/src/widgets/launch_bar/LauncherContainer.tsx
@@ -73,7 +73,13 @@ export default function LauncherContainer({ isHorizontalLayout }: { isHorizontal
function Launcher({ note, isHorizontalLayout }: { note: FNote, isHorizontalLayout: boolean }) {
// A note cloned into the launch bar opens itself.
if (note.type !== "launcher") {
- return <CustomNoteLauncher launcherNote={note} getTargetNoteId={() => note.noteId} />;
+ return (
+ <CustomNoteLauncher
+ launcherNote={note}
+ getTargetNoteId={() => note.noteId}
+ parentNoteId={getVisibleLaunchersRootId()}
+ />
+ );
}
const launcherType = note.getLabelValue("launcherType");