Skip to content

Build your personal knowledge base with Trilium Notes

client: fix some issues

Adorian Doran87c5023fcd81
diff --git a/apps/client/src/components/tab_manager.spec.ts b/apps/client/src/components/tab_manager.spec.ts
index caf579e019..3f2b5a612e 100644
--- a/apps/client/src/components/tab_manager.spec.ts
+++ b/apps/client/src/components/tab_manager.spec.ts
@@ -379,4 +379,59 @@ describe("going to an entry of the navigation history", () => {
expect(reopened?.notePath).toBe("root/historyA");
expect(window.location.hash).toBe(`#root/historyA?ntxId=${reopened?.ntxId}`);
});
+
+ it("pushes a tab switch made while the entry is still loading", async () => {
+ const first = await tm.openEmptyTab();
+ const second = await tm.openEmptyTab();
+ await second.setNote("root/historyC");
+ await tm.activateNoteContext(first.ntxId);
+ await first.setNote("root/historyA");
+ await first.setNote("root/historyB");
+
+ window.history.replaceState(null, "", `#root/historyA?ntxId=${first.ntxId}`);
+ let showA: (notePath: string) => void = () => {};
+ vi.spyOn(first, "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(
+ first.ntxId, "root/historyA", { viewMode: "default" }
+ );
+ await tm.activateNoteContext(second.ntxId);
+ showA("root/historyA");
+ await restoring;
+
+ expect(replaceState).not.toHaveBeenCalled();
+ expect(pushState).toHaveBeenCalledOnce();
+ expect(window.location.hash).toBe(`#root/historyC?ntxId=${second.ntxId}`);
+ expect(first.notePath).toBe("root/historyA");
+ });
+
+ it("keeps rewriting entries when two of them load at once", async () => {
+ const tab = await tm.openEmptyTab();
+ await tm.activateNoteContext(tab.ntxId);
+ await tab.setNote("root/historyA");
+ await tab.setNote("root/historyB");
+ await tab.setNote("root/historyC");
+
+ let showB: (notePath: string) => void = () => {};
+ let showA: (notePath: string) => void = () => {};
+ vi.spyOn(tab, "getResolvedNotePath")
+ .mockReturnValueOnce(new Promise((resolve) => { showB = resolve; }))
+ .mockReturnValueOnce(new Promise((resolve) => { showA = resolve; }));
+ const pushState = vi.spyOn(window.history, "pushState");
+
+ // Back twice: the entry of A is reached before B has loaded.
+ const toB = tm.switchToHistoryEntry(tab.ntxId, "root/historyB", { viewMode: "default" });
+ const toA = tm.switchToHistoryEntry(tab.ntxId, "root/historyA", { viewMode: "default" });
+ showB("root/historyB");
+ await toB;
+ expect(window.location.hash).toBe(`#root/historyB?ntxId=${tab.ntxId}`);
+ showA("root/historyA");
+ await toA;
+
+ expect(pushState).not.toHaveBeenCalled();
+ expect(window.location.hash).toBe(`#root/historyA?ntxId=${tab.ntxId}`);
+ });
});
diff --git a/apps/client/src/components/tab_manager.ts b/apps/client/src/components/tab_manager.ts
index 41af25e9e3..8b54f7e0c9 100644
--- a/apps/client/src/components/tab_manager.ts
+++ b/apps/client/src/components/tab_manager.ts
@@ -37,8 +37,8 @@ export default class TabManager extends Component {
public activeNtxId: string | null;
public recentlyClosedTabs: TabState[];
public tabsUpdate: SpacedUpdate;
- /** Set while `switchToHistoryEntry()` runs: the history entry is replaced instead of pushed. */
- private isShowingHistoryEntry = false;
+ /** The note context that the latest `switchToHistoryEntry()` call shows. */
+ private historyEntry: { noteContext: NoteContext } | null = null;
constructor() {
super();
@@ -183,18 +183,23 @@ export default class TabManager extends Component {
setCurrentNavigationStateToHash() {
const calculatedHash = this.calculateHash();
+ const activeNoteContext = this.getActiveContext();
+
+ // Activating another note context is a new navigation, even while the history entry loads.
+ if (this.historyEntry?.noteContext !== activeNoteContext) {
+ this.historyEntry = null;
+ }
// update if it's the first history entry or there has been a change
if (window.history.length === 0 || calculatedHash !== window.location?.hash) {
// using pushState instead of directly modifying document.location because it does not trigger hashchange
- if (this.isShowingHistoryEntry) {
+ if (this.historyEntry) {
window.history.replaceState(null, "", calculatedHash);
} else {
window.history.pushState(null, "", calculatedHash);
}
}
- const activeNoteContext = this.getActiveContext();
this.updateDocumentTitle(activeNoteContext);
this.triggerEvent("activeNoteChanged", {ntxId:activeNoteContext?.ntxId}); // trigger this even in on popstate event
@@ -296,19 +301,26 @@ export default class TabManager extends Component {
}
/**
- * Shows the history entry the browser went to. The state this reaches replaces the entry, so
- * the entries after it stay reachable.
+ * Shows the history entry the browser went to. While its note context is active, the hash
+ * updates replace the entry instead of pushing one, so the entries after it stay reachable.
*/
async switchToHistoryEntry(
ntxId: string | null,
notePath: string,
viewScope: Record<string, any> = {}
) {
- this.isShowingHistoryEntry = true;
+ const noteContext = this.noteContexts.find((nc) => nc.ntxId === ntxId) ||
+ await this.openEmptyTab();
+ const historyEntry = { noteContext };
+ this.historyEntry = historyEntry;
+
try {
- await this.switchToNoteContext(ntxId, notePath, viewScope);
+ await this.activateNoteContext(noteContext.ntxId);
+ await noteContext.setNote(notePath, { viewScope });
} finally {
- this.isShowingHistoryEntry = false;
+ if (this.historyEntry === historyEntry) {
+ this.historyEntry = null;
+ }
}
}
diff --git a/apps/client/src/menus/tree_context_menu.spec.ts b/apps/client/src/menus/tree_context_menu.spec.ts
index e5e6395d30..ddbe38fa3f 100644
--- a/apps/client/src/menus/tree_context_menu.spec.ts
+++ b/apps/client/src/menus/tree_context_menu.spec.ts
@@ -12,7 +12,8 @@ vi.mock("../services/clipboard", () => ({ default: { getContents: vi.fn(() => nu
vi.mock("../components/app_context", () => ({ default: { tabManager: { getActiveContext: () => undefined } } }));
vi.mock("../services/i18n", () => ({
t: (key: string, options?: { count?: number }) =>
- (options?.count === undefined ? key : `${key} ${options.count}`)
+ (options?.count === undefined ? key : `${key} ${options.count}`),
+ translationsInitializedPromise: Promise.resolve()
}));
describe("buildTreeContextMenuItems", () => {
diff --git a/apps/client/src/widgets/react/hooks.spec.tsx b/apps/client/src/widgets/react/hooks.spec.tsx
index 3656b8154b..d60bb20cbe 100644
--- a/apps/client/src/widgets/react/hooks.spec.tsx
+++ b/apps/client/src/widgets/react/hooks.spec.tsx
@@ -844,6 +844,20 @@ describe("useHoldContextMenu", () => {
expect(onClick).toHaveBeenCalledOnce();
});
+ it("ends the hold when the press is released off the button", () => {
+ fire("pointerdown", { button: 0 });
+ vi.advanceTimersByTime(500);
+ fire("pointerleave");
+ document.body.dispatchEvent(new PointerEvent("pointerup", { bubbles: true, button: 0 }));
+ vi.runAllTimers();
+
+ // A keyboard click and the context menu key.
+ fire("click");
+ expect(onClick).toHaveBeenCalledOnce();
+ fire("contextmenu");
+ expect(handler).toHaveBeenCalledTimes(2);
+ });
+
it("leaves a short press, a press that slides off and another button alone", () => {
fire("pointerdown", { button: 0 });
vi.advanceTimersByTime(300);
diff --git a/apps/client/src/widgets/react/hooks.tsx b/apps/client/src/widgets/react/hooks.tsx
index 783f64b9ef..97bc681b0b 100644
--- a/apps/client/src/widgets/react/hooks.tsx
+++ b/apps/client/src/widgets/react/hooks.tsx
@@ -1971,7 +1971,15 @@ export function useHoldContextMenu(handler: (e: MouseEvent) => void, holdMs = 50
}
}, []);
- useEffect(() => clear, [clear]);
+ // The click of the press is dispatched in the same task as its `pointerup`, before the timeout.
+ const endHold = useCallback(() => {
+ window.setTimeout(() => heldRef.current = false);
+ }, []);
+
+ useEffect(() => () => {
+ clear();
+ window.removeEventListener("pointerup", endHold, true);
+ }, [clear, endHold]);
const onPointerDown = useCallback(
(e: PointerEvent) => {
@@ -1981,20 +1989,14 @@ export function useHoldContextMenu(handler: (e: MouseEvent) => void, holdMs = 50
timerRef.current = window.setTimeout(() => {
timerRef.current = null;
heldRef.current = true;
+ // The press can end off the element, which then receives no `pointerup`.
+ window.addEventListener("pointerup", endHold, { capture: true, once: true });
handler(e);
}, holdMs);
},
- [handler, holdMs, clear]
+ [handler, holdMs, clear, endHold]
);
- const onPointerUp = useCallback(() => {
- clear();
- // The click of this press is dispatched in the same task, before the timeout runs.
- if (heldRef.current) {
- window.setTimeout(() => heldRef.current = false);
- }
- }, [clear]);
-
const onContextMenu = useCallback(
(e: MouseEvent) => {
clear();
@@ -2016,7 +2018,7 @@ export function useHoldContextMenu(handler: (e: MouseEvent) => void, holdMs = 50
return {
onContextMenu,
onPointerDown,
- onPointerUp,
+ onPointerUp: clear,
onPointerLeave: clear,
onPointerCancel: clear,
onClickCapture