Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
client/right pane: refactor, make the peek pane logic reusable
Adorian Doran2b3bbc9c3127
diff --git a/apps/client/src/widgets/react/peek_pane.spec.tsx b/apps/client/src/widgets/react/peek_pane.spec.tsxnew file mode 100644index 0000000000..582c5d547d--- /dev/null+++ b/apps/client/src/widgets/react/peek_pane.spec.tsx@@ -0,0 +1,116 @@+import { render } from "preact";+import { act } from "preact/test-utils";+import { afterEach, describe, expect, it, vi } from "vitest";++import { isWithinPeek, persistedPaneVisible, reducePaneMode, usePeekDismiss } from "./peek_pane";++describe("reducePaneMode", () => {+ it("opens as peek from closed and closes otherwise", () => {+ expect(reducePaneMode("closed", "togglePeek")).toBe("peek");+ expect(reducePaneMode("peek", "togglePeek")).toBe("closed");+ expect(reducePaneMode("docked", "togglePeek")).toBe("closed");+ });++ it("opens as docked from closed and closes otherwise", () => {+ expect(reducePaneMode("closed", "toggleDocked")).toBe("docked");+ expect(reducePaneMode("peek", "toggleDocked")).toBe("closed");+ expect(reducePaneMode("docked", "toggleDocked")).toBe("closed");+ });++ it("docks and closes unconditionally", () => {+ for (const prev of ["closed", "peek", "docked"] as const) {+ expect(reducePaneMode(prev, "dock")).toBe("docked");+ expect(reducePaneMode(prev, "close")).toBe("closed");+ }+ });+});++describe("persistedPaneVisible", () => {+ it("persists only when the docked/closed distinction changes", () => {+ // No docked-ness change -> no write (peek is ephemeral).+ expect(persistedPaneVisible("closed", "peek")).toBe(null);+ expect(persistedPaneVisible("peek", "closed")).toBe(null);+ // Becoming docked persists true; leaving docked persists false.+ expect(persistedPaneVisible("closed", "docked")).toBe(true);+ expect(persistedPaneVisible("peek", "docked")).toBe(true);+ expect(persistedPaneVisible("docked", "closed")).toBe(false);+ expect(persistedPaneVisible("docked", "peek")).toBe(false);+ });+});++describe("isWithinPeek", () => {+ afterEach(() => {+ document.body.innerHTML = "";+ });++ const selector = "#right-pane, .my-peek-button";++ it("matches elements inside the allowlisted selector, not outside it or non-elements", () => {+ document.body.innerHTML = `+ <div id="right-pane"><span class="item">x</span></div>+ <button class="my-peek-button"></button>+ <div id="center-pane"><p class="editor">z</p></div>+ `;+ expect(isWithinPeek(document.querySelector(".item"), selector)).toBe(true);+ expect(isWithinPeek(document.querySelector(".my-peek-button"), selector)).toBe(true);+ expect(isWithinPeek(document.querySelector(".editor"), selector)).toBe(false);+ expect(isWithinPeek(document.body, selector)).toBe(false);+ expect(isWithinPeek(null, selector)).toBe(false);+ expect(isWithinPeek(document, selector)).toBe(false);+ });+});++describe("usePeekDismiss", () => {+ afterEach(() => {+ document.body.innerHTML = "";+ });++ function renderHook(active: boolean, onDismiss: () => void, keepOpenSelector = "#right-pane") {+ const host = document.createElement("div");+ document.body.appendChild(host);+ function Harness() {+ usePeekDismiss(active, onDismiss, { keepOpenSelector });+ return null;+ }+ // act() flushes the effect so the document listeners are attached before we dispatch.+ act(() => render(<Harness />, host));+ return () => act(() => render(null, host)); // unmount+ }++ it("keeps the peek open for the instance selector and default popups, dismisses outside", () => {+ document.body.innerHTML = `+ <div id="right-pane"></div>+ <ul class="dropdown-menu"></ul>+ <div id="center-pane"></div>+ `;+ const onDismiss = vi.fn();+ const unmount = renderHook(true, onDismiss);++ // Inside the instance selector keeps it open...+ document.querySelector("#right-pane")?.dispatchEvent(new MouseEvent("pointerdown", { bubbles: true }));+ // ...as does a default popup root (not in keepOpenSelector, but in the built-in allowlist).+ document.querySelector(".dropdown-menu")?.dispatchEvent(new MouseEvent("pointerdown", { bubbles: true }));+ expect(onDismiss).not.toHaveBeenCalled();++ // A press anywhere else dismisses.+ document.querySelector("#center-pane")?.dispatchEvent(new MouseEvent("pointerdown", { bubbles: true }));+ expect(onDismiss).toHaveBeenCalledTimes(1);++ unmount();+ });++ it("dismisses on Escape, and does nothing while inactive", () => {+ const onDismiss = vi.fn();++ const unmountInactive = renderHook(false, onDismiss);+ document.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape" }));+ document.dispatchEvent(new MouseEvent("pointerdown", { bubbles: true }));+ expect(onDismiss).not.toHaveBeenCalled();+ unmountInactive();++ const unmountActive = renderHook(true, onDismiss);+ document.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape" }));+ expect(onDismiss).toHaveBeenCalledTimes(1);+ unmountActive();+ });+});diff --git a/apps/client/src/widgets/react/peek_pane.ts b/apps/client/src/widgets/react/peek_pane.tsnew file mode 100644index 0000000000..1b0dfe7faf--- /dev/null+++ b/apps/client/src/widgets/react/peek_pane.ts@@ -0,0 +1,124 @@+import { OptionNames } from "@triliumnext/commons";+import { useCallback, useEffect, useRef, useState } from "preact/hooks";++import options from "../../services/options";++/**+ * A reusable side pane that can be in one of three modes:+ * - `closed`: hidden.+ * - `docked`: a persistent pane that reflows the content (resizable).+ * - `peek`: a transient pane that floats over the content without reflowing it, dismissed on outside+ * interaction or Escape.+ *+ * These primitives are side-agnostic (left/right) and content-agnostic; a consumer supplies the+ * persisted option key, the commands/keyboard actions, and the DOM (see RightPanelContainer for the+ * reference implementation). Only the docked/closed distinction is persisted — peek is runtime-only.+ */+export type PaneMode = "closed" | "peek" | "docked";+export type PaneAction = "togglePeek" | "toggleDocked" | "dock" | "close";++/** The next mode for a given action (pure). `toggle*` open from closed and close otherwise. */+export function reducePaneMode(prev: PaneMode, action: PaneAction): PaneMode {+ switch (action) {+ case "togglePeek": return prev === "closed" ? "peek" : "closed";+ case "toggleDocked": return prev === "closed" ? "docked" : "closed";+ case "dock": return "docked";+ case "close": return "closed";+ }+}++/**+ * The value to write to the persisted visibility option for a transition, or null when it shouldn't+ * change — only the docked/closed distinction is persisted; peek is runtime-only.+ */+export function persistedPaneVisible(prev: PaneMode, next: PaneMode): boolean | null {+ return (prev === "docked") !== (next === "docked") ? next === "docked" : null;+}++export interface PaneModeController {+ mode: PaneMode;+ visible: boolean;+ togglePeek: () => void;+ toggleDocked: () => void;+ dock: () => void;+ close: () => void;+}++/**+ * Owns a pane's mode and its persistence. `visibleOption` stores only the docked/closed distinction.+ * The state updater stays pure (it can run more than once, e.g. in Strict Mode); persistence runs in+ * an effect so it isn't duplicated by re-invoked updaters.+ */+export function usePaneMode(visibleOption: OptionNames): PaneModeController {+ const [ mode, setMode ] = useState<PaneMode>(() => options.is(visibleOption) ? "docked" : "closed");++ const apply = useCallback((action: PaneAction) => {+ setMode(prev => reducePaneMode(prev, action));+ }, []);++ const prevModeRef = useRef<PaneMode>(mode);+ useEffect(() => {+ const prev = prevModeRef.current;+ if (prev !== mode) {+ const persist = persistedPaneVisible(prev, mode);+ if (persist !== null) {+ options.save(visibleOption, persist.toString());+ }+ prevModeRef.current = mode;+ }+ }, [ mode, visibleOption ]);++ const togglePeek = useCallback(() => apply("togglePeek"), [ apply ]);+ const toggleDocked = useCallback(() => apply("toggleDocked"), [ apply ]);+ const dock = useCallback(() => apply("dock"), [ apply ]);+ const close = useCallback(() => apply("close"), [ apply ]);++ return { mode, visible: mode !== "closed", togglePeek, toggleDocked, dock, close };+}++// App-wide popup roots that render outside the pane (on document.body) but must NOT dismiss a peek:+// resize gutters, Bootstrap dropdowns/tooltips/modals/popovers, CKEditor balloons, Flatpickr calendars.+const DEFAULT_KEEP_OPEN_SELECTOR = ".gutter, .dropdown-menu, .tooltip, .modal, .popover, .ck-balloon-panel, .ck-body, .flatpickr-calendar";++/** Whether an event target lies within the peek pane or an allowlisted popup (i.e. should keep it open). */+export function isWithinPeek(target: EventTarget | null, keepOpenSelector: string): boolean {+ return target instanceof Element && target.closest(keepOpenSelector) !== null;+}++export interface PeekDismissOptions {+ /** Instance selectors whose clicks keep the peek open — typically the pane element and its button. */+ keepOpenSelector: string;+ /** Element focused after Escape closes the peek (e.g. the peek button), for keyboard return. */+ focusSelector?: string;+}++/**+ * While `active`, closes the peek on an outside press or Escape. Presses over the content area land+ * on the pane's backdrop and so reach this listener; presses on chrome the backdrop doesn't cover+ * (tree, toolbar, tabs) are caught directly. Capture phase so a child's `stopPropagation` can't keep+ * a stale peek open.+ */+export function usePeekDismiss(active: boolean, onDismiss: () => void, { keepOpenSelector, focusSelector }: PeekDismissOptions) {+ useEffect(() => {+ if (!active) return;++ const selector = `${keepOpenSelector}, ${DEFAULT_KEEP_OPEN_SELECTOR}`;+ const onPointerDown = (e: PointerEvent) => {+ if (!isWithinPeek(e.target, selector)) onDismiss();+ };+ const onKeyDown = (e: KeyboardEvent) => {+ // Skip if an inner element already handled Escape (e.g. closed a dropdown or cleared an input).+ if (e.key === "Escape" && !e.defaultPrevented) {+ onDismiss();+ if (focusSelector) document.querySelector<HTMLElement>(focusSelector)?.focus();+ }+ };++ document.addEventListener("pointerdown", onPointerDown, true);+ document.addEventListener("keydown", onKeyDown);+ return () => {+ document.removeEventListener("pointerdown", onPointerDown, true);+ document.removeEventListener("keydown", onKeyDown);+ };+ }, [ active, onDismiss, keepOpenSelector, focusSelector ]);+}diff --git a/apps/client/src/widgets/sidebar/RightPaneToggleHandle.css b/apps/client/src/widgets/sidebar/RightPanePeekButton.csssimilarity index 68%rename from apps/client/src/widgets/sidebar/RightPaneToggleHandle.cssrename to apps/client/src/widgets/sidebar/RightPanePeekButton.cssindex dcbb3c2469..a2304abc62 100644--- a/apps/client/src/widgets/sidebar/RightPaneToggleHandle.css+++ b/apps/client/src/widgets/sidebar/RightPanePeekButton.css@@ -1,14 +1,14 @@-/* The handle is absolutely positioned in a reserved gutter on the right edge of+/* The peek button is absolutely positioned in a reserved gutter on the right edge of#vertical-main-container, so it stays fixed at the viewport's right side and fully- owns its background — independent of whether the panel is open or collapsed. */-.right-pane-toggle-handle {+ owns its background — independent of whether the right pane is open or collapsed. */+.right-pane-peek-button {/* Pinned to the reserved gutter (see #vertical-main-container in RightPanelContainer.css);- width inherits --right-pane-handle-width, with a fallback for safety. */+ width inherits --right-pane-peek-button-width, with a fallback for safety. */position: absolute;inset-inline-end: 0;top: 0;bottom: 0;- width: var(--right-pane-handle-width, 12px);+ width: var(--right-pane-peek-button-width, 12px);z-index: 1;display: flex;align-items: center;@@ -22,11 +22,11 @@color: var(--muted-text-color);transition: background 250ms ease-in, color 250ms ease-in;- &.right-pane-toggle-handle-action-expand {+ &.right-pane-peek-button-action-expand {background: var(--note-split-background-color, var(--main-background-color));}- &.right-pane-toggle-handle-action-collapse {+ &.right-pane-peek-button-action-collapse {background: var(--right-pane-background-color);}diff --git a/apps/client/src/widgets/sidebar/RightPaneToggleHandle.tsx b/apps/client/src/widgets/sidebar/RightPanePeekButton.tsxsimilarity index 70%rename from apps/client/src/widgets/sidebar/RightPaneToggleHandle.tsxrename to apps/client/src/widgets/sidebar/RightPanePeekButton.tsxindex f6b8da0c37..50026342e9 100644--- a/apps/client/src/widgets/sidebar/RightPaneToggleHandle.tsx+++ b/apps/client/src/widgets/sidebar/RightPanePeekButton.tsx@@ -1,4 +1,4 @@-import "./RightPaneToggleHandle.css";+import "./RightPanePeekButton.css";import { Tooltip } from "bootstrap";import clsx from "clsx";@@ -7,20 +7,20 @@ import { useCallback, useMemo, useRef } from "preact/hooks";import { t } from "../../services/i18n";import { useStaticTooltip } from "../react/hooks";-// Gap (px) between the handle and its tooltip, so the tooltip can't overlap the handle.+// Gap (px) between the peek button and its tooltip, so the tooltip can't overlap the button.const TOOLTIP_MARGIN_PX = 8;-interface RightPaneToggleHandleProps {+interface RightPanePeekButtonProps {/** Owned and persisted by RightPanelContainer; this component only reflects it. */rightPaneVisible: boolean;- /** Toggles the pane (opens it as an overlay, or closes it); owned by RightPanelContainer. */+ /** Toggles the right pane (peeks it open, or closes it); owned by RightPanelContainer. */onToggle: () => void;}-export default function RightPaneToggleHandle({ rightPaneVisible, onToggle }: RightPaneToggleHandleProps) {+export default function RightPanePeekButton({ rightPaneVisible, onToggle }: RightPanePeekButtonProps) {const buttonRef = useRef<HTMLButtonElement>(null);// Pointer's vertical position captured once on hover; null until the mouse enters- // (e.g. on keyboard focus) so the tooltip falls back to the handle's centre.+ // (e.g. on keyboard focus) so the tooltip falls back to the button's centre.const pointerY = useRef<number | null>(null);const handleClick = useCallback(() => {@@ -34,32 +34,34 @@ export default function RightPaneToggleHandle({ rightPaneVisible, onToggle }: Ri}}, [ onToggle ]);+ // Open: a click hides it. Closed: a click peeks it (the pin then docks it).+ const label = rightPaneVisible ? t("right_pane.hide") : t("right_pane.peek");+// Anchor the tooltip to the pointer's entry height rather than the centre of the- // full-height handle, by shifting it along the cross axis. Not tracked: `pointerY`+ // full-height button, by shifting it along the cross axis. Not tracked: `pointerY`// is only updated on mouse enter, and the offset is recomputed from it on show.- // The `distance` (second value) keeps the tooltip clear of the handle so it can't+ // The `distance` (second value) keeps the tooltip clear of the button so it can't// overlap it and cause hover flicker.const tooltipConfig = useMemo(() => ({- // Open: a click hides it. Closed: a click peeks it (the transient overlay; the pin docks it).- title: rightPaneVisible ? t("right_pane.hide") : t("right_pane.peek"),+ title: label,placement: "left" as const,offset: () => {const rect = buttonRef.current?.getBoundingClientRect();if (!rect || pointerY.current === null) return [ 0, TOOLTIP_MARGIN_PX ] as [number, number];return [ pointerY.current - (rect.top + rect.height / 2), TOOLTIP_MARGIN_PX ] as [number, number];}- }), [ rightPaneVisible ]);+ }), [ label ]);useStaticTooltip(buttonRef, tooltipConfig);return (<buttonref={buttonRef}type="button"- aria-label={t("right_pane.toggle")}+ aria-label={label}class={clsx(- "right-pane-toggle-handle bx",+ "right-pane-peek-button bx",rightPaneVisible ? "bx-chevron-right" : "bx-chevron-left",- rightPaneVisible ? "right-pane-toggle-handle-action-collapse" : "right-pane-toggle-handle-action-expand"+ rightPaneVisible ? "right-pane-peek-button-action-collapse" : "right-pane-peek-button-action-expand")}onMouseEnter={(e) => { pointerY.current = e.clientY; }}onMouseLeave={() => { pointerY.current = null; }}diff --git a/apps/client/src/widgets/sidebar/RightPanelContainer.css b/apps/client/src/widgets/sidebar/RightPanelContainer.cssindex a469035638..2700792d3c 100644--- a/apps/client/src/widgets/sidebar/RightPanelContainer.css+++ b/apps/client/src/widgets/sidebar/RightPanelContainer.css@@ -1,17 +1,17 @@-/* Reserve a fixed-width gutter on the viewport's right edge for the toggle handle, which is- absolutely positioned within it (see RightPaneToggleHandle.css). Split sizes the panes- inside the padded content box, so they never sit under the handle, and the handle stays put- regardless of whether the panel is open. */+/* Reserve a fixed-width gutter on the viewport's right edge for the peek button, which is+ absolutely positioned within it (see RightPanePeekButton.css). Split sizes the panes+ inside the padded content box, so they never sit under the button, and the button stays put+ regardless of whether the right pane is open. */body.experimental-feature-new-layout #vertical-main-container {- --right-pane-handle-width: 12px;- /* +4px leaves a small gap between the panel (and #center-pane) and the handle. */- --right-pane-handle-gutter: calc(var(--right-pane-handle-width) + 4px);+ --right-pane-peek-button-width: 12px;+ /* +4px leaves a small gap between the right pane (and #center-pane) and the peek button. */+ --right-pane-peek-button-gutter: calc(var(--right-pane-peek-button-width) + 4px);position: relative;- padding-inline-end: var(--right-pane-handle-gutter);+ padding-inline-end: var(--right-pane-peek-button-gutter);}/* Persistent host wrapping the spacer + #right-pane (see RightPanelContainer.tsx), so #right-pane- never reparents between modes. A flex row: docked it fills with the pane (spacer hidden); overlay+ never reparents between modes. A flex row: docked it fills with the pane (spacer hidden); peekit lays out [spacer | gutter | pane]. */body.experimental-feature-new-layout #right-pane-host {display: flex;@@ -19,57 +19,57 @@ body.experimental-feature-new-layout #right-pane-host {}/* Docked: #right-pane fills the host (which Split sizes against #center-pane). */-body.experimental-feature-new-layout #right-pane-host:not(.overlay) > #right-pane {+body.experimental-feature-new-layout #right-pane-host:not(.peek) > #right-pane {flex: 1 1 0;min-width: 0;}-/* When closing the overlay, the host goes in-flow a frame before Split.destroy (run in an effect)- removes its resize gutter. Keep any gutter inside a non-overlay host out of the flow so that+/* When closing the peek, the host goes in-flow a frame before Split.destroy (run in an effect)+ removes its resize gutter. Keep any gutter inside a non-peek host out of the flow so thatlingering 5px gutter can't briefly widen the host and reflow the content. */-body.experimental-feature-new-layout #right-pane-host:not(.overlay) > .gutter {+body.experimental-feature-new-layout #right-pane-host:not(.peek) > .gutter {display: none;}-/* Overlay: float the host above the content as an absolute layer, so the content never reflows. */-body.experimental-feature-new-layout #right-pane-host.overlay {+/* Peek: float the host above the content as an absolute layer, so the content never reflows. */+body.experimental-feature-new-layout #right-pane-host.peek {position: absolute;inset-block: 0;inset-inline-start: 0;- inset-inline-end: var(--right-pane-handle-gutter);+ inset-inline-end: var(--right-pane-peek-button-gutter);z-index: 15;- animation: right-pane-overlay-in 150ms ease;+ animation: right-pane-peek-in 150ms ease;}-@keyframes right-pane-overlay-in {+@keyframes right-pane-peek-in {from { opacity: 0; }to { opacity: 1; }}-/* Overlay: Split sizes the spacer and the pane via inline widths, so flex must not override them. */-body.experimental-feature-new-layout #right-pane-host.overlay > .right-pane-overlay-spacer,-body.experimental-feature-new-layout #right-pane-host.overlay > #right-pane {+/* Peek: Split sizes the spacer and the pane via inline widths, so flex must not override them. */+body.experimental-feature-new-layout #right-pane-host.peek > .right-pane-peek-spacer,+body.experimental-feature-new-layout #right-pane-host.peek > #right-pane {flex: 0 0 auto;}-body.experimental-feature-new-layout #right-pane-host.overlay > #right-pane {+body.experimental-feature-new-layout #right-pane-host.peek > #right-pane {border-inline-start: 1px solid var(--main-border-color);box-shadow: -4px 0 12px rgba(0, 0, 0, 0.18);}-/* The spacer is the left Split target and, in overlay mode, the faint click-to-dismiss backdrop+/* The spacer is the left Split target and, in peek mode, the faint click-to-dismiss backdropover the content (it also shields the PDF iframe during a resize drag). Hidden when docked. */-body.experimental-feature-new-layout .right-pane-overlay-spacer {+body.experimental-feature-new-layout .right-pane-peek-spacer {display: none;}-body.experimental-feature-new-layout #right-pane-host.overlay > .right-pane-overlay-spacer {+body.experimental-feature-new-layout #right-pane-host.peek > .right-pane-peek-spacer {display: block;min-width: 0;background: rgba(0, 0, 0, 0.05);}-/* Pin/close controls, shown whenever the pane is open (pin only in overlay mode). */+/* Pin/close controls, shown whenever the pane is open (pin only in peek mode). */body.experimental-feature-new-layout #right-pane .right-pane-actions {position: absolute;top: 4px;diff --git a/apps/client/src/widgets/sidebar/RightPanelContainer.spec.tsx b/apps/client/src/widgets/sidebar/RightPanelContainer.spec.tsxdeleted file mode 100644index c94f236c68..0000000000--- a/apps/client/src/widgets/sidebar/RightPanelContainer.spec.tsx+++ /dev/null@@ -1,124 +0,0 @@-import { render } from "preact";-import { act } from "preact/test-utils";-import { afterEach, describe, expect, it, vi } from "vitest";--import { isWithinOverlay, persistedRightPaneVisible, reduceRightPaneMode, useOverlayDismiss } from "./RightPanelContainer";--describe("reduceRightPaneMode", () => {- it("opens as overlay from closed and closes otherwise", () => {- expect(reduceRightPaneMode("closed", "toggleOverlay")).toBe("overlay");- expect(reduceRightPaneMode("overlay", "toggleOverlay")).toBe("closed");- expect(reduceRightPaneMode("docked", "toggleOverlay")).toBe("closed");- });-- it("opens as docked from closed and closes otherwise", () => {- expect(reduceRightPaneMode("closed", "toggleDocked")).toBe("docked");- expect(reduceRightPaneMode("overlay", "toggleDocked")).toBe("closed");- expect(reduceRightPaneMode("docked", "toggleDocked")).toBe("closed");- });-- it("docks and closes unconditionally", () => {- for (const prev of ["closed", "overlay", "docked"] as const) {- expect(reduceRightPaneMode(prev, "dock")).toBe("docked");- expect(reduceRightPaneMode(prev, "close")).toBe("closed");- }- });-});--describe("persistedRightPaneVisible", () => {- it("persists only when the docked/closed distinction changes", () => {- // No docked-ness change -> no write (overlay is ephemeral).- expect(persistedRightPaneVisible("closed", "overlay")).toBe(null);- expect(persistedRightPaneVisible("overlay", "closed")).toBe(null);- // Becoming docked persists true; leaving docked persists false.- expect(persistedRightPaneVisible("closed", "docked")).toBe(true);- expect(persistedRightPaneVisible("overlay", "docked")).toBe(true);- expect(persistedRightPaneVisible("docked", "closed")).toBe(false);- expect(persistedRightPaneVisible("docked", "overlay")).toBe(false);- });-});--describe("isWithinOverlay", () => {- afterEach(() => {- document.body.innerHTML = "";- });-- it("keeps the overlay open for the pane, the handle, the resize gutter, and allowlisted popups", () => {- document.body.innerHTML = `- <div id="right-pane"><span class="toc-item">x</span></div>- <button class="right-pane-toggle-handle"></button>- <div class="gutter gutter-horizontal"></div>- <ul class="dropdown-menu"><li class="dropdown-item">y</li></ul>- <div class="tooltip">t</div>- <div class="ck-balloon-panel"><span class="ck-button">b</span></div>- <div class="flatpickr-calendar"><span class="flatpickr-day">1</span></div>- `;- const inside = [".toc-item", ".right-pane-toggle-handle", ".gutter", ".dropdown-item", ".tooltip", ".ck-button", ".flatpickr-day"];- for (const selector of inside) {- expect(isWithinOverlay(document.querySelector(selector)), selector).toBe(true);- }- });-- it("dismisses for the spacer/backdrop, surrounding chrome, and non-elements", () => {- document.body.innerHTML = `- <div class="right-pane-overlay-spacer"></div>- <div id="center-pane"><p class="editor">z</p></div>- <div class="tab-row-container"><span class="tab">t</span></div>- <div id="left-pane"><span class="tree-item">n</span></div>- `;- // The spacer/backdrop is deliberately outside the allowlist, so clicking the covered content dismisses.- for (const selector of [".right-pane-overlay-spacer", ".editor", ".tab", ".tree-item"]) {- expect(isWithinOverlay(document.querySelector(selector)), selector).toBe(false);- }- expect(isWithinOverlay(document.body)).toBe(false);- expect(isWithinOverlay(null)).toBe(false);- expect(isWithinOverlay(document)).toBe(false);- });-});--describe("useOverlayDismiss", () => {- afterEach(() => {- document.body.innerHTML = "";- });-- function renderHook(active: boolean, onDismiss: () => void) {- const host = document.createElement("div");- document.body.appendChild(host);- function Harness() {- useOverlayDismiss(active, onDismiss);- return null;- }- // act() flushes the effect so the document listeners are attached before we dispatch.- act(() => render(<Harness />, host));- return () => act(() => render(null, host)); // unmount- }-- it("dismisses on an outside press but not on a press within the overlay", () => {- document.body.innerHTML = `<div id="right-pane"></div><div id="center-pane"></div>`;- const onDismiss = vi.fn();- const unmount = renderHook(true, onDismiss);-- document.querySelector("#right-pane")?.dispatchEvent(new MouseEvent("pointerdown", { bubbles: true }));- expect(onDismiss).not.toHaveBeenCalled();-- document.querySelector("#center-pane")?.dispatchEvent(new MouseEvent("pointerdown", { bubbles: true }));- expect(onDismiss).toHaveBeenCalledTimes(1);-- unmount();- });-- it("dismisses on Escape, and does nothing while inactive", () => {- const onDismiss = vi.fn();-- const unmountInactive = renderHook(false, onDismiss);- document.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape" }));- document.dispatchEvent(new MouseEvent("pointerdown", { bubbles: true }));- expect(onDismiss).not.toHaveBeenCalled();- unmountInactive();-- const unmountActive = renderHook(true, onDismiss);- document.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape" }));- expect(onDismiss).toHaveBeenCalledTimes(1);- unmountActive();- });-});diff --git a/apps/client/src/widgets/sidebar/RightPanelContainer.tsx b/apps/client/src/widgets/sidebar/RightPanelContainer.tsxindex 785046b910..56e46c24ec 100644--- a/apps/client/src/widgets/sidebar/RightPanelContainer.tsx+++ b/apps/client/src/widgets/sidebar/RightPanelContainer.tsx@@ -3,7 +3,7 @@ import "./RightPanelContainer.css";import Split from "@triliumnext/split.js";import { VNode } from "preact";-import { useCallback, useEffect, useRef, useState } from "preact/hooks";+import { useEffect, useRef } from "preact/hooks";import appContext from "../../components/app_context";import { WidgetsByParent } from "../../services/bundle";@@ -16,26 +16,20 @@ import Button from "../react/Button";import { useActiveNoteContext, 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";import LegacyRightPanelWidget from "../right_panel_widget";import HighlightsList from "./HighlightsList";import PdfAnnotations from "./pdf/PdfAnnotations";import PdfAttachments from "./pdf/PdfAttachments";import PdfLayers from "./pdf/PdfLayers";import PdfPages from "./pdf/PdfPages";-import RightPaneToggleHandle from "./RightPaneToggleHandle";+import RightPanePeekButton from "./RightPanePeekButton";import RightPanelWidget from "./RightPanelWidget";import TableOfContents from "./TableOfContents";const MIN_WIDTH_PERCENT = 5;const MAX_WIDTH_PERCENT = 90;-/**- * - `closed`: hidden. - `docked`: a flex pane that reflows the content (resizable via Split).- * - `overlay`: floats above the content without reflowing it; transient (closed on focus loss).- * Only the docked/closed distinction is persisted (`rightPaneVisible`); overlay is runtime-only.- */-type RightPaneMode = "closed" | "overlay" | "docked";-interface RightPanelWidgetDefinition {el: VNode;enabled: boolean;@@ -43,62 +37,40 @@ interface RightPanelWidgetDefinition {}export default function RightPanelContainer({ widgetsByParent }: { widgetsByParent: WidgetsByParent }) {- const [ mode, setMode ] = useState<RightPaneMode>(() => options.is("rightPaneVisible") ? "docked" : "closed");- const visible = mode !== "closed";+ const { mode, visible, togglePeek, toggleDocked, dock, close } = usePaneMode("rightPaneVisible");const items = useItems(visible, widgetsByParent);useSplit(mode);- // Apply a transition. The state updater stays pure (it can run more than once, e.g. in Strict- // Mode); persistence is handled in the effect below.- const apply = useCallback((action: RightPaneAction) => {- setMode(prev => reduceRightPaneMode(prev, action));- }, []);-- // Persist only when the docked/closed distinction changes (overlay is ephemeral, so it never- // writes the option). Kept out of the updater to avoid duplicate writes from re-invoked updaters.- const prevModeRef = useRef<RightPaneMode>(mode);- useEffect(() => {- const prev = prevModeRef.current;- if (prev !== mode) {- const persist = persistedRightPaneVisible(prev, mode);- if (persist !== null) {- options.save("rightPaneVisible", persist.toString());- }- prevModeRef.current = mode;- }- }, [ mode ]);-- const toggleOverlay = useCallback(() => apply("toggleOverlay"), [ apply ]);- const dock = useCallback(() => apply("dock"), [ apply ]);- const close = useCallback(() => apply("close"), [ apply ]);+ // Legacy entry points (tab-row toggle, empty-state button) open/close the *docked* pane;+ // the keyboard shortcut peeks it (same as clicking the peek button).+ useTriliumEvent("toggleRightPane", toggleDocked);+ useTriliumEvent("peekRightPane", togglePeek);- // Legacy entry points (tab-row toggle, empty-state button) open/close the *docked* pane.- useTriliumEvent("toggleRightPane", useCallback(() => apply("toggleDocked"), [ apply ]));- // Keyboard shortcut: peek the pane as an overlay (same as clicking the handle).- useTriliumEvent("peekRightPane", useCallback(() => apply("toggleOverlay"), [ apply ]));-- useOverlayDismiss(mode === "overlay", close);+ usePeekDismiss(mode === "peek", close, {+ keepOpenSelector: "#right-pane, .right-pane-peek-button",+ focusSelector: ".right-pane-peek-button"+ });return (<>{/* Absolutely positioned in a reserved gutter on the viewport's right edge, so it- stays put regardless of the panel's open/collapsed state (see RightPanelContainer.css). */}- <RightPaneToggleHandle rightPaneVisible={visible} onToggle={toggleOverlay} />+ stays put regardless of the right pane's open/collapsed state (see RightPanelContainer.css). */}+ <RightPanePeekButton rightPaneVisible={visible} onToggle={togglePeek} />{/* Persistent host so #right-pane never reparents between modes (which would remount the- sidebar widgets). Docked: an in-flow flex child Split resizes against #center-pane.- Overlay: an absolute layer over the content where Split resizes the spacer vs the pane. */}- <div id="right-pane-host" class={mode === "overlay" ? "overlay" : undefined}>- {/* The spacer is both the left Split target and the dismiss backdrop in overlay mode:+ right pane widgets). Docked: an in-flow flex child Split resizes against #center-pane.+ Peek: an absolute layer over the content where Split resizes the spacer vs the pane. */}+ <div id="right-pane-host" class={mode === "peek" ? "peek" : undefined}>+ {/* The spacer is both the left Split target and the dismiss backdrop in peek mode:it covers the content (a click dismisses) and shields the PDF iframe so Split'sdrag tracking isn't interrupted. Always rendered + CSS-toggled to keep the host'schild list structurally stable for Split's gutter injection. */}- <div class="right-pane-overlay-spacer" />- {/* Mode class (right-pane-mode-docked / -overlay) as a styling hook; none when closed. */}+ <div class="right-pane-peek-spacer" />+ {/* Mode class (right-pane-mode-docked / -peek) as a styling hook; none when closed. */}<div id="right-pane" class={visible ? `right-pane-mode-${mode}` : undefined}>{visible && (<div class="right-pane-actions">- {/* Pin only applies while overlaying (it docks the pane); close shows in both modes. */}- {mode === "overlay" && <ActionButton icon="bx bx-pin" text={t("right_pane.dock")} onClick={dock} />}+ {/* Pin only applies while peeking (it docks the pane); close shows in both modes. */}+ {mode === "peek" && <ActionButton icon="bx bx-pin" text={t("right_pane.dock")} onClick={dock} />}<ActionButton icon="bx bx-x" text={t("right_pane.close")} onClick={close} /></div>)}@@ -110,8 +82,8 @@ export default function RightPanelContainer({ widgetsByParent }: { widgetsByPareicon="bx bx-sidebar"text={t("right_pane.empty_message")}>- {/* The overlay auto-closes (outside click / focus loss / Esc), so a manual hide button is redundant there. */}- {mode !== "overlay" && (+ {/* The peek auto-closes (outside click / focus loss / Esc), so a manual hide button is redundant there. */}+ {mode !== "peek" && (<Buttontext={t("right_pane.empty_button")}triggerCommand="toggleRightPane"@@ -131,7 +103,7 @@ function useItems(rightPaneVisible: boolean, widgetsByParent: WidgetsByParent) {const noteType = useNoteProperty(note, "type");const noteMime = useNoteProperty(note, "mime");const [ highlightsList ] = useTriliumOptionJson<string[]>("highlightsList");- // Subscribe to the AI toggle so the LLM sidebar is added/removed reactively without a page reload.+ // Subscribe to the AI toggle so the LLM chat is added/removed reactively without a page reload.const [ aiEnabled ] = useTriliumOptionBool("aiEnabled");const isPdf = noteType === "file" && noteMime === "application/pdf";@@ -198,7 +170,7 @@ function useItems(rightPaneVisible: boolean, widgetsByParent: WidgetsByParent) {.map(e => e.el);}-function useSplit(mode: RightPaneMode) {+function useSplit(mode: PaneMode) {useEffect(() => {if (mode === "closed") return;@@ -216,7 +188,7 @@ function useSplit(mode: RightPaneMode) {const onDragEnd = (sizes: number[]) => options.save("rightPaneWidth", Math.round(sizes[1]));// Docked: resize the host (and thus the content) against #center-pane.- // Overlay: resize the pane against the spacer inside the absolute host — the content (#center-pane)+ // Peek: resize the pane against the spacer inside the absolute host — the content (#center-pane)// is untouched, so it never reflows.splitInstance = mode === "docked"? Split(["#center-pane", "#right-pane-host"], {@@ -227,7 +199,7 @@ function useSplit(mode: RightPaneMode) {onDrag,onDragEnd})- : Split([".right-pane-overlay-spacer", "#right-pane"], {+ : Split([".right-pane-peek-spacer", "#right-pane"], {sizes: [100 - rightPaneWidth, rightPaneWidth],gutterSize: DEFAULT_GUTTER_SIZE,minSize: [0, 180],@@ -239,65 +211,6 @@ function useSplit(mode: RightPaneMode) {}, [ mode ]);}-type RightPaneAction = "toggleOverlay" | "toggleDocked" | "dock" | "close";--/** The next mode for a given action (pure). `toggle*` open from closed and close otherwise. */-export function reduceRightPaneMode(prev: RightPaneMode, action: RightPaneAction): RightPaneMode {- switch (action) {- case "toggleOverlay": return prev === "closed" ? "overlay" : "closed";- case "toggleDocked": return prev === "closed" ? "docked" : "closed";- case "dock": return "docked";- case "close": return "closed";- }-}--/**- * The value to write to the persisted `rightPaneVisible` option for a transition, or null when it- * shouldn't change — only the docked/closed distinction is persisted; overlay is runtime-only.- */-export function persistedRightPaneVisible(prev: RightPaneMode, next: RightPaneMode): boolean | null {- return (prev === "docked") !== (next === "docked") ? next === "docked" : null;-}--// Clicks within these keep the overlay open: the pane, the toggle handle, the resize gutter, and-// popups that sidebar content renders into portals on document.body, outside #right-pane — dropdowns,-// tooltips, modals, CKEditor balloons (chat input) and Flatpickr calendars (date attributes). The-// spacer/backdrop is intentionally NOT listed, so clicking the covered content area dismisses.-const OVERLAY_KEEP_OPEN_SELECTOR = "#right-pane, .right-pane-toggle-handle, .gutter, .dropdown-menu, .tooltip, .modal, .popover, .ck-balloon-panel, .ck-body, .flatpickr-calendar";--/** Whether an event target lies within the overlay or an allowlisted popup (i.e. should keep it open). */-export function isWithinOverlay(target: EventTarget | null): boolean {- return target instanceof Element && target.closest(OVERLAY_KEEP_OPEN_SELECTOR) !== null;-}--/**- * While `active`, closes the overlay on an outside press or Escape. Presses over the content area- * (including the PDF iframe) land on the backdrop element and so reach this listener; presses on- * chrome the backdrop doesn't cover (tree, toolbar, tabs) are caught directly. Capture phase so a- * child's `stopPropagation` can't keep a stale overlay open.- */-export function useOverlayDismiss(active: boolean, onDismiss: () => void) {- useEffect(() => {- if (!active) return;- const onPointerDown = (e: PointerEvent) => {- if (!isWithinOverlay(e.target)) onDismiss();- };- const onKeyDown = (e: KeyboardEvent) => {- // Skip if an inner element already handled Escape (e.g. closed a dropdown or cleared an input).- if (e.key === "Escape" && !e.defaultPrevented) {- onDismiss();- document.querySelector<HTMLElement>(".right-pane-toggle-handle")?.focus();- }- };- document.addEventListener("pointerdown", onPointerDown, true);- document.addEventListener("keydown", onKeyDown);- return () => {- document.removeEventListener("pointerdown", onPointerDown, true);- document.removeEventListener("keydown", onKeyDown);- };- }, [ active, onDismiss ]);-}-function CustomLegacyWidget({ originalWidget }: { originalWidget: LegacyRightPanelWidget }) {const containerRef = useRef<HTMLDivElement>(null);diff --git a/apps/server/src/assets/translations/en/server.json b/apps/server/src/assets/translations/en/server.jsonindex 652374d81c..cd3a79ec4d 100644--- a/apps/server/src/assets/translations/en/server.json+++ b/apps/server/src/assets/translations/en/server.json@@ -53,7 +53,7 @@"toggle-link-map": "Toggle Link Map","other": "Other","toggle-right-pane": "Toggle the display of the right pane, which includes Table of Contents and Highlights",- "peek-right-pane": "Peek the right pane as a temporary overlay that floats over the content and closes when it loses focus",+ "peek-right-pane": "Peek the right pane as a temporary panel that floats over the content and closes when it loses focus","open-note-externally": "Open note as a file with default application","render-active-note": "Render (re-render) active note","run-active-note": "Run active JavaScript (frontend/backend) code note",