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
refactor(client/overlay): give the overlay control group a component
Elian Doranc76537406ad3
diff --git a/apps/client/src/widgets/react/ImageViewer.tsx b/apps/client/src/widgets/react/ImageViewer.tsxindex 0fb7b0c385..bf08fcd0b4 100644--- a/apps/client/src/widgets/react/ImageViewer.tsx+++ b/apps/client/src/widgets/react/ImageViewer.tsx@@ -9,8 +9,9 @@ import type { ShortcutHintDefinition } from "../../services/shortcut_hints";import { isMobile } from "../../services/utils";import ShortcutHintButton from "../shortcut_hints/shortcut_hint_button";import ContentErrorMessage from "./ContentErrorMessage";-import { useContextualShortcutHints, useStaticTooltip } from "./hooks";+import { useContextualShortcutHints } from "./hooks";import { useImageViewerKeyboard } from "./image_viewer_keyboard";+import OverlayControlGroup, { OverlayControlButton } from "./OverlayControlGroup";interface ImageViewerProps {src: string;@@ -85,9 +86,6 @@ export default function ImageViewer({ src, imgClassName, alt = "", minScale = 0.const imgRef = useRef<HTMLImageElement>(null);const rootRef = useRef<HTMLDivElement>(null);const zoomRef = useRef<ReactZoomPanPinchRef>(null);- const zoomOutRef = useRef<HTMLButtonElement>(null);- const zoomLevelRef = useRef<HTMLButtonElement>(null);- const zoomInRef = useRef<HTMLButtonElement>(null);// Keep our own ref to drive keyboard control, while still forwarding to the caller's apiRef.const setZoomRef = useCallback((instance: ReactZoomPanPinchRef | null) => {@@ -147,9 +145,6 @@ export default function ImageViewer({ src, imgClassName, alt = "", minScale = 0.useImageViewerKeyboard(zoomRef, rootRef);useContextualShortcutHints(IMAGE_VIEWER_HINTS);- useStaticTooltip(zoomOutRef, { title: t("image_buttons.zoom_out"), placement: "top" });- useStaticTooltip(zoomLevelRef, { title: t("image_buttons.reset_zoom"), placement: "top" });- useStaticTooltip(zoomInRef, { title: t("image_buttons.zoom_in"), placement: "top" });const wrapperClass = ["image-viewer-viewport",@@ -194,31 +189,25 @@ export default function ImageViewer({ src, imgClassName, alt = "", minScale = 0.)}{!isMobile() && loaded && (- <div className="image-viewer-controls tn-overlay-control-group">- <button- ref={zoomOutRef}- type="button"- className="tn-overlay-icon-button bx bx-minus-circle"- aria-label={t("image_buttons.zoom_out")}+ <OverlayControlGroup className="image-viewer-controls">+ <OverlayControlButton+ title={t("image_buttons.zoom_out")}+ icon="bx-minus-circle"onClick={() => zoomRef.current?.zoomOut(BUTTON_ZOOM_STEP)}/>- <button- ref={zoomLevelRef}- type="button"- className="tn-overlay-text-button image-viewer-zoom-level"- aria-label={t("image_buttons.reset_zoom")}+ <OverlayControlButton+ title={t("image_buttons.reset_zoom")}+ className="image-viewer-zoom-level"onClick={() => zoomRef.current?.resetTransform()}>{zoomPercent}%- </button>- <button- ref={zoomInRef}- type="button"- className="tn-overlay-icon-button bx bx-plus-circle"- aria-label={t("image_buttons.zoom_in")}+ </OverlayControlButton>+ <OverlayControlButton+ title={t("image_buttons.zoom_in")}+ icon="bx-plus-circle"onClick={() => zoomRef.current?.zoomIn(BUTTON_ZOOM_STEP)}/>- </div>+ </OverlayControlGroup>)}</div>);diff --git a/apps/client/src/widgets/react/OverlayControlGroup.spec.tsx b/apps/client/src/widgets/react/OverlayControlGroup.spec.tsxnew file mode 100644index 0000000000..f40884fd0f--- /dev/null+++ b/apps/client/src/widgets/react/OverlayControlGroup.spec.tsx@@ -0,0 +1,108 @@+import { type ComponentChildren, render, type RefObject } from "preact";+import { act } from "preact/test-utils";+import { afterEach, describe, expect, it, vi } from "vitest";++// The bootstrap tooltip needs real layout; capture what it would have been given instead.+const { staticTooltipSpy } = vi.hoisted(() => ({ staticTooltipSpy: vi.fn() }));+vi.mock("./hooks", () => ({ useStaticTooltip: staticTooltipSpy }));++import OverlayControlGroup, { OverlayControlButton } from "./OverlayControlGroup";++let container: HTMLDivElement;++afterEach(() => {+ act(() => render(null, container));+ container.remove();+ staticTooltipSpy.mockClear();+});++function mount(children: ComponentChildren) {+ container = document.createElement("div");+ document.body.appendChild(container);+ act(() => render(children, container));+ return container;+}++/** The tooltip config the hook was handed for the button bearing the given accessible name. */+function tooltipFor(label: string) {+ const call = staticTooltipSpy.mock.calls.find(+ (args) => (args[0] as RefObject<HTMLElement>).current?.getAttribute("aria-label") === label+ );+ return call?.[1] as { title: string; placement: string } | undefined;+}++describe("OverlayControlGroup", () => {+ it("renders a group of icon and text buttons, each labelled by its title", () => {+ mount(+ <OverlayControlGroup className="my-position">+ <OverlayControlButton title="Zoom out" icon="bx-minus-circle" />+ <OverlayControlButton title="Reset zoom" className="my-readout">100%</OverlayControlButton>+ </OverlayControlGroup>+ );++ expect(container.querySelector(".tn-overlay-control-group.my-position")).not.toBeNull();+ const [ icon, text ] = container.querySelectorAll("button");+ // A button is driven by its onClick and must never submit a form it happens to stand in.+ expect(icon.getAttribute("type")).toBe("button");+ expect(icon.className.split(" ")).toEqual(expect.arrayContaining([ "tn-overlay-icon-button", "bx", "bx-minus-circle" ]));+ expect(icon.getAttribute("aria-label")).toBe("Zoom out");+ // No icon given: drawn at a word's width, saying what it has to say through its children.+ expect(text.className.split(" ")).toEqual(expect.arrayContaining([ "tn-overlay-text-button", "my-readout" ]));+ expect(text.className).not.toContain("tn-overlay-icon-button");+ expect(text.getAttribute("aria-label")).toBe("Reset zoom");+ expect(text.textContent).toBe("100%");+ });++ it("marks a button held down or refused when asked to", () => {+ mount(+ <OverlayControlGroup>+ <OverlayControlButton title="Placing" icon="bx-pin" active />+ <OverlayControlButton title="Refused" icon="bx-trip" disabled />+ </OverlayControlGroup>+ );++ const [ active, refused ] = container.querySelectorAll("button");+ expect(active.classList.contains("active")).toBe(true);+ expect(refused.disabled).toBe(true);+ expect(refused.classList.contains("active")).toBe(false);+ });++ it("gives each button a tooltip saying what its label does, opening the way the group says", () => {+ mount(+ <OverlayControlGroup titlePosition="bottom">+ <OverlayControlButton title="Zoom out" icon="bx-minus-circle" />+ <OverlayControlButton title="Elsewhere" icon="bx-pin" titlePosition="left" />+ </OverlayControlGroup>+ );++ expect(tooltipFor("Zoom out")).toEqual({ title: "Zoom out", placement: "bottom" });+ // A button placed unlike its neighbours overrides what the group hands down.+ expect(tooltipFor("Elsewhere")).toEqual({ title: "Elsewhere", placement: "left" });+ });++ it("opens tooltips away from the bottom edge unless told otherwise", () => {+ mount(+ <OverlayControlGroup>+ <OverlayControlButton title="Zoom in" icon="bx-plus-circle" />+ </OverlayControlGroup>+ );++ expect(tooltipFor("Zoom in")?.placement).toBe("top");+ });++ it("keeps the same tooltip config across renders that don't change it, so it isn't rebuilt", () => {+ const group = (label: string) => (+ <OverlayControlGroup>+ <OverlayControlButton title="Reset zoom">{label}</OverlayControlButton>+ </OverlayControlGroup>+ );+ mount(group("100%"));+ const first = staticTooltipSpy.mock.calls.at(-1)?.[1];++ // Only the readout changes — what the tooltip says and where it opens are untouched.+ act(() => render(group("250%"), container));++ expect(container.querySelector("button")?.textContent).toBe("250%");+ expect(staticTooltipSpy.mock.calls.at(-1)?.[1]).toBe(first);+ });+});diff --git a/apps/client/src/widgets/react/OverlayControlGroup.tsx b/apps/client/src/widgets/react/OverlayControlGroup.tsxnew file mode 100644index 0000000000..d63e889001--- /dev/null+++ b/apps/client/src/widgets/react/OverlayControlGroup.tsx@@ -0,0 +1,90 @@+import clsx from "clsx";+import { type ComponentChildren, createContext, type HTMLAttributes } from "preact";+import { useContext, useMemo, useRef } from "preact/hooks";++import type { ActionButtonProps } from "./ActionButton";+import { useStaticTooltip } from "./hooks";++interface OverlayControlGroupProps {+ /** Where the group stands and what else is peculiar to it, styled by whoever puts it there. */+ className?: string;+ /** Which way the buttons' tooltips open — away from the edge the group is pinned to. */+ titlePosition?: ActionButtonProps["titlePosition"];+ children: ComponentChildren;+}++/**+ * A run of buttons standing over content, joined edge to edge into one segmented chip: the image+ * viewer's zoom steps, and the like.+ *+ * The surface, the seams and the rounding of the two ends come from the theme (see the overlay+ * buttons in theme-next/forms.css); where the group stands is left to the caller, which is the one+ * thing that differs between them.+ *+ * Not to be confused with {@link OverlayToolbar}, the other thing that floats over content: that one+ * is a bar of separate buttons on a pane of glass, and it brings its own surface with it. This is a+ * single chip with no gaps, and it is what the app's zoom and navigation controls are built from.+ */+export default function OverlayControlGroup({ className, titlePosition, children }: OverlayControlGroupProps) {+ return (+ <div className={clsx("tn-overlay-control-group", className)}>+ <TooltipDirection.Provider value={titlePosition ?? "top"}>+ {children}+ </TooltipDirection.Provider>+ </div>+ );+}++interface OverlayControlButtonProps extends Pick<HTMLAttributes<HTMLButtonElement>, "onClick"> {+ /** What the button does: shown as its tooltip, and read out as its accessible name. */+ title: string;+ /**+ * The boxicons name of the mark it wears (`bx-plus-circle`), for a button that speaks in a glyph.+ * Given one, the button is drawn at an icon's width; without one it is drawn at a word's, and+ * says what it has to say through its children.+ */+ icon?: string;+ /** Extra class for whatever is peculiar to this one button. */+ className?: string;+ /** Shown held down, for a button standing for a choice in force. */+ active?: boolean;+ disabled?: boolean;+ /** Overrides the direction the group hands down, for a button placed unlike its neighbours. */+ titlePosition?: ActionButtonProps["titlePosition"];+ children?: ComponentChildren;+}++/**+ * A button on such a group. It carries its own tooltip, which says the same thing its accessible name+ * does — one `title` rather than the two that would otherwise have to be kept in step — and opens the+ * way the group it stands on says, so that a group at the foot of the content does not open its+ * tooltips off the bottom edge.+ */+export function OverlayControlButton({ title, icon, className, active, disabled, titlePosition, children, ...restProps }: OverlayControlButtonProps) {+ const buttonRef = useRef<HTMLButtonElement>(null);+ const groupDirection = useContext(TooltipDirection);+ const placement = titlePosition ?? groupDirection;++ // Memoized so the tooltip is only rebuilt when what it says (or where it opens) actually changes,+ // rather than on every render of the group.+ const tooltipConfig = useMemo(() => ({ title, placement }), [ title, placement ]);+ useStaticTooltip(buttonRef, tooltipConfig);++ return (+ <button+ ref={buttonRef}+ // Driven by its onClick, so it must never act as a form's implicit submit button+ // (a <button> defaults to type="submit").+ type="button"+ className={clsx(icon ? "tn-overlay-icon-button bx" : "tn-overlay-text-button", icon, active && "active", className)}+ aria-label={title}+ disabled={disabled}+ {...restProps}+ >+ {children}+ </button>+ );+}++/** Which way the tooltips on a group open, handed down by the group rather than repeated on each button. */+const TooltipDirection = createContext<ActionButtonProps["titlePosition"]>("top");