Skip to content

Build your personal knowledge base with Trilium Notes

fix(right-pane): keep the selected tab to the window that picked it

Elian Dorane60571c68616
diff --git a/apps/client/src/widgets/sidebar/RightPanelContainer.spec.tsx b/apps/client/src/widgets/sidebar/RightPanelContainer.spec.tsx
index fc9f6a61eb..7937d4a59c 100644
--- a/apps/client/src/widgets/sidebar/RightPanelContainer.spec.tsx
+++ b/apps/client/src/widgets/sidebar/RightPanelContainer.spec.tsx
@@ -1,6 +1,47 @@
-import { describe, expect, it } from "vitest";
+import { render } from "preact";
+import { act } from "preact/test-utils";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { groupIntoTabs, RightPanelWidgetDefinition } from "./RightPanelContainer";
+import FNote from "../../entities/fnote";
+
+// The container follows whichever note is being read; the tests hand it one directly.
+const shownNote = vi.hoisted(() => ({ current: null as FNote | null }));
+// The tabs' names live in tooltips only; Bootstrap's own machinery is not what is under test here.
+const useStaticTooltip = vi.hoisted(() => vi.fn());
+vi.mock("../react/hooks", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("../react/hooks")>()),
+ useActiveNoteContext: () => ({ note: shownNote.current }),
+ useStaticTooltip
+}));
+
+// The tabs' bodies are widgets with specs of their own: bare boxes stand in for them, the strip and
+// the choice between the tabs being what is under test here.
+vi.mock("./AttributeList", () => stubWidget("attribute-list-stub"));
+vi.mock("./TableOfContents", () => stubWidget("toc-stub"));
+vi.mock("./HighlightsList", () => stubWidget("highlights-stub"));
+vi.mock("./ChatHighlightsList", () => stubWidget("chat-highlights-stub"));
+vi.mock("./pdf/PdfPages", () => stubWidget("pdf-pages-stub"));
+vi.mock("./pdf/PdfAttachments", () => stubWidget("pdf-attachments-stub"));
+vi.mock("./pdf/PdfLayers", () => stubWidget("pdf-layers-stub"));
+vi.mock("./pdf/PdfAnnotations", () => stubWidget("pdf-annotations-stub"));
+vi.mock("./RightPanePeekButton", () => stubWidget("peek-button-stub"));
+vi.mock("../../services/keyboard_actions", () => ({
+ default: { getAction: vi.fn().mockResolvedValue({ effectiveShortcuts: [] }) }
+}));
+
+async function stubWidget(className: string) {
+ const { h } = await import("preact");
+ return { default: () => h("div", { className }) };
+}
+
+import appContext from "../../components/app_context";
+import type Component from "../../components/component";
+import type LoadResults from "../../services/load_results";
+import options from "../../services/options";
+import { buildNote } from "../../test/easy-froca";
+import { ParentComponent } from "../react/react_utils";
+import RightPanelContainer, { groupIntoTabs, RightPanelWidgetDefinition } from "./RightPanelContainer";
+import { RIGHT_PANE_TABS } from "./RightPaneTabs";
describe("groupIntoTabs", () => {
it("keeps the enabled widgets only, in position order, and drops the tabs left empty", () => {
@@ -40,6 +81,117 @@ describe("groupIntoTabs", () => {
});
});
+describe("RightPanelContainer", () => {
+ let container: HTMLElement;
+ /** What the pane subscribed to, when rendered under a parent component that can tell it. */
+ let eventHandlers: Map<string, Set<(data: unknown) => void>>;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ options.set("rightPaneVisible", "true");
+ options.set("rightPaneWidth", "25");
+ options.set("rightPaneSelectedTab", "attributes");
+ options.set("highlightsList", "[]");
+ options.set("aiEnabled", "false");
+ appContext.tabManager = { getActiveContext: () => null } as typeof appContext.tabManager;
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ });
+
+ afterEach(() => {
+ render(null, container);
+ container.remove();
+ });
+
+ it("treats the tab as the window's own: a press writes the choice back, another window's is not followed", () => {
+ shownNote.current = buildNote({ title: "Read" });
+ renderContainer();
+
+ // A text note offers the outline and the attributes; the pane is on the tab last chosen here.
+ expect(shownTabIcons()).toEqual([ icon("outline"), icon("attributes") ]);
+ expect(activeTabIcon()).toBe(icon("attributes"));
+
+ // A press of this window's own switches the pane and writes the choice back, which is what
+ // a window opened later starts from.
+ act(() => {
+ tabButton(icon("outline"))?.click();
+ });
+ expect(activeTabIcon()).toBe(icon("outline"));
+ expect(options.get("rightPaneSelectedTab")).toBe("outline");
+
+ // Another window picking a tab of its own arrives as the shared option's change: the cache
+ // is rewritten first and the reload announced after, as the sync updater delivers it.
+ act(() => {
+ options.set("rightPaneSelectedTab", "attributes");
+ fireEntitiesReloaded([ "rightPaneSelectedTab" ]);
+ });
+
+ // The choice belongs to the window it was made in: this pane stays where it was put.
+ expect(activeTabIcon()).toBe(icon("outline"));
+ });
+
+ function renderContainer() {
+ eventHandlers = new Map();
+ const parent = {
+ componentId: "pane-cid",
+ registerHandler: (name: string, callback: (data: unknown) => void) => {
+ if (!eventHandlers.has(name)) {
+ eventHandlers.set(name, new Set());
+ }
+ eventHandlers.get(name)?.add(callback);
+ },
+ removeHandler: (name: string, callback: (data: unknown) => void) => {
+ eventHandlers.get(name)?.delete(callback);
+ }
+ } as unknown as Component;
+ const widgetsByParent = {
+ getLegacyWidgets: () => [],
+ getPreactWidgets: () => []
+ } as unknown as Parameters<typeof RightPanelContainer>[0]["widgetsByParent"];
+
+ act(() => render(
+ <ParentComponent.Provider value={parent}>
+ <RightPanelContainer widgetsByParent={widgetsByParent} />
+ </ParentComponent.Provider>,
+ container
+ ));
+ }
+
+ /** Hands the pane a reload naming the given options, as a change made in another window arrives. */
+ function fireEntitiesReloaded(optionNames: string[]) {
+ const loadResults = {
+ getOptionNames: () => optionNames,
+ isNoteReloaded: () => false
+ } as unknown as LoadResults;
+ for (const handler of eventHandlers.get("entitiesReloaded") ?? []) {
+ handler({ loadResults });
+ }
+ }
+
+ function tabButton(iconClass: string) {
+ return [ ...container.querySelectorAll<HTMLButtonElement>("[role=tab]") ]
+ .find((button) => button.querySelector("span")?.className.includes(iconClass));
+ }
+
+ /** The strip names no tab in words, so the icon is what tells them apart here. */
+ function icon(tabId: string) {
+ const tab = RIGHT_PANE_TABS.find((definition) => definition.id === tabId);
+ expect(tab, tabId).toBeDefined();
+ return tab?.icon ?? "";
+ }
+
+ function shownTabIcons() {
+ return [ ...container.querySelectorAll("[role=tab] span") ]
+ .map((span) => span.className.replace("right-pane-tab-icon tn-icon ", ""));
+ }
+
+ function activeTabIcon() {
+ const active = container.querySelector("[role=tab][aria-selected=true] span");
+ expect(active).not.toBeNull();
+ return (active?.className ?? "").replace("right-pane-tab-icon tn-icon ", "");
+ }
+});
+
function widget(tab: RightPanelWidgetDefinition["tab"], overrides: Partial<RightPanelWidgetDefinition> = {}) {
return { el: <div class={tab} />, enabled: true, tab, ...overrides };
}
diff --git a/apps/client/src/widgets/sidebar/RightPanelContainer.tsx b/apps/client/src/widgets/sidebar/RightPanelContainer.tsx
index 4298c6c356..033f06120e 100644
--- a/apps/client/src/widgets/sidebar/RightPanelContainer.tsx
+++ b/apps/client/src/widgets/sidebar/RightPanelContainer.tsx
@@ -4,7 +4,7 @@ import "./RightPanelContainer.css";
import Split from "@triliumnext/split.js";
import clsx from "clsx";
import { VNode } from "preact";
-import { useLayoutEffect, useRef } from "preact/hooks";
+import { useCallback, useLayoutEffect, useRef, useState } from "preact/hooks";
import appContext from "../../components/app_context";
import { WidgetsByParent } from "../../services/bundle";
@@ -14,7 +14,7 @@ import { DEFAULT_GUTTER_SIZE } from "../../services/resizer";
import { isStandalone } from "../../services/utils";
import ActionButton from "../react/ActionButton";
import Button from "../react/Button";
-import { useActiveNoteContext, useGetContextData, useLegacyWidget, useNoteProperty, useTriliumEvent, useTriliumOption, useTriliumOptionBool, useTriliumOptionJson } from "../react/hooks";
+import { useActiveNoteContext, useGetContextData, useLegacyWidget, useNoteProperty, useTriliumEvent, useTriliumOptionBool, useTriliumOptionJson } from "../react/hooks";
import LazyComponent from "../react/LazyComponent";
import NoItems from "../react/NoItems";
import { PaneMode, usePaneMode, usePeekDismiss } from "../react/peek_pane";
@@ -50,7 +50,14 @@ export interface RightPaneTabContents extends RightPaneTabDefinition {
export default function RightPanelContainer({ widgetsByParent }: { widgetsByParent: WidgetsByParent }) {
const { mode, visible, mounted, togglePeek, toggleDocked, dock, close, dismiss } = usePaneMode("rightPaneVisible");
const tabs = useItems(mounted, widgetsByParent);
- const [ selectedTabId, setSelectedTabId ] = useTriliumOption("rightPaneSelectedTab");
+ // This window's own choice, seeded from the option and written back for the next window to start
+ // from — the same treatment usePaneMode gives the pane's visibility. Subscribing to the option
+ // (useTriliumOption) would let a click in one window flip the strip in every other.
+ const [ selectedTabId, setSelectedTabIdState ] = useState(() => options.get("rightPaneSelectedTab"));
+ const setSelectedTabId = useCallback((tabId: RightPaneTabId) => {
+ setSelectedTabIdState(tabId);
+ void options.save("rightPaneSelectedTab", tabId);
+ }, []);
useSplit(mode);
// The chosen tab may have nothing to show for this note (or may have gone away entirely, e.g. the
@@ -80,7 +87,7 @@ export default function RightPanelContainer({ widgetsByParent }: { widgetsByPare
return;
}
- void setSelectedTabId(tabId);
+ setSelectedTabId(tabId);
if (!visible) {
toggleDocked();
}
@@ -123,7 +130,7 @@ export default function RightPanelContainer({ widgetsByParent }: { widgetsByPare
<RightPaneTabs
tabs={tabs}
activeTabId={activeTab?.id}
- onSelect={(tabId) => void setSelectedTabId(tabId)}
+ onSelect={setSelectedTabId}
/>
{tabs.filter((tab) => openedTabs.current.has(tab.id)).map((tab) => (