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): put the geo map's two toolbars on the control group
Elian Doran5b85248a939a
diff --git a/apps/client/src/widgets/collections/geomap/EditToolbar.tsx b/apps/client/src/widgets/collections/geomap/EditToolbar.tsxindex 2b2a00c817..d2cd08585a 100644--- a/apps/client/src/widgets/collections/geomap/EditToolbar.tsx+++ b/apps/client/src/widgets/collections/geomap/EditToolbar.tsx@@ -1,16 +1,16 @@import "./EditToolbar.css";-import { useContext, useRef } from "preact/hooks";+import { useContext } from "preact/hooks";import { t } from "../../../services/i18n";-import { useStaticTooltip } from "../../react/hooks";+import OverlayControlGroup, { OverlayControlButton } from "../../react/OverlayControlGroup";import { ParentMap } from "./map";interface EditToolbarProps {/** The map may not be edited, which is every one of these buttons refused at once. */isReadOnly: boolean;/** The map is armed for the next click to place a new note, which the button wears as held- * down (see the overlay buttons' active styling in theme-next/forms.css). */+ * down (see `active` on {@link OverlayControlButton}). */placing: boolean;/** Arms the map for a note to be placed, or stands it down again — the visible counterpart of* the Escape the instruction toast offers (see index.tsx). */@@ -20,10 +20,9 @@ interface EditToolbarProps {}/**- * The editing actions, standing in the middle of the map's foot on a control group of their own- * (`tn-overlay-control-group`, the surface every group over this map stands on): adding a marker and- * bringing in a GPX track today, with room along the row for whatever editing the map comes to offer- * next.+ * The editing actions, standing in the middle of the map's foot on an {@link OverlayControlGroup} of+ * their own — the surface every group over this map stands on: adding a marker and bringing in a GPX+ * track today, with room along the row for whatever editing the map comes to offer next.** A group of its own rather than more buttons on {@link MapToolbar}: that one is the camera — how* close in the map is drawn, how much screen it gets — and what changes the map is another kind of@@ -38,50 +37,31 @@ interface EditToolbarProps {*/export default function EditToolbar({ isReadOnly, placing, onTogglePlacement, onAddGpxTrack }: EditToolbarProps) {const map = useContext(ParentMap);- const addMarkerRef = useRef<HTMLButtonElement>(null);- const gpxRef = useRef<HTMLButtonElement>(null);-- // Standing at the foot of the map, the tooltips open away from that edge, where they would- // otherwise fall off.- useStaticTooltip(addMarkerRef, {- title: placing ? t("geo-map.create-child-note-cancel") : t("geo-map.create-child-note-title"),- placement: "top"- });- useStaticTooltip(gpxRef, { title: t("geo-map.add-gpx-track"), placement: "top" });// No group over a map that could not be drawn (see the WebGL fallback in map.tsx).if (!map) return null;return (- <div- className="geo-edit-toolbar tn-overlay-control-group"- /* Keep a press on the controls from reaching the canvas underneath, which would- otherwise take it for the start of a drag. */- onMouseDown={(e) => e.stopPropagation()}- >- <button- ref={addMarkerRef}- type="button"- className={`tn-overlay-text-button geo-add-marker-button ${placing ? "active" : ""}`}+ <OverlayControlGroup className="geo-edit-toolbar" overCanvas>+ {/* The pin a note dropped on the map wears (see CHILD_NOTE_ICON in api.ts) — the button+ shows the very thing it drops, which is also the ghost that will follow the pointer+ once armed. The words beside it are what names the button; the tooltip says at more+ length what it does. */}+ <OverlayControlButton+ title={placing ? t("geo-map.create-child-note-cancel") : t("geo-map.create-child-note-title")}+ icon="bx-pin"+ text={placing ? t("geo-map.add-marker-cancel") : t("geo-map.add-marker")}+ className="geo-add-marker-button"+ active={placing}disabled={isReadOnly}onClick={onTogglePlacement}- >- {/* The pin a note dropped on the map wears (see CHILD_NOTE_ICON in api.ts) — the- button shows the very thing it drops, which is also the ghost that will follow- the pointer once armed. A child rather than a class on the button: the boxicons- class sets the icon font on whatever wears it, and the words beside it are to- stay words. */}- <span className="bx bx-pin" aria-hidden="true"></span>- {placing ? t("geo-map.add-marker-cancel") : t("geo-map.add-marker")}- </button>- <button- ref={gpxRef}- type="button"- className="tn-overlay-icon-button bx bx-trip"- aria-label={t("geo-map.add-gpx-track")}+ />+ <OverlayControlButton+ title={t("geo-map.add-gpx-track")}+ icon="bx-trip"disabled={isReadOnly}onClick={onAddGpxTrack}/>- </div>+ </OverlayControlGroup>);}diff --git a/apps/client/src/widgets/collections/geomap/MapToolbar.tsx b/apps/client/src/widgets/collections/geomap/MapToolbar.tsxindex 785ca0b687..e5beef28ab 100644--- a/apps/client/src/widgets/collections/geomap/MapToolbar.tsx+++ b/apps/client/src/widgets/collections/geomap/MapToolbar.tsx@@ -1,11 +1,12 @@import "./MapToolbar.css";import type { Map as MapLibreGLMap } from "maplibre-gl";-import { useContext, useEffect, useRef, useState } from "preact/hooks";+import { useContext, useEffect, useState } from "preact/hooks";import { t } from "../../../services/i18n";import { isMobile } from "../../../services/utils";-import { useFullscreen, useStaticTooltip } from "../../react/hooks";+import { useFullscreen } from "../../react/hooks";+import OverlayControlGroup, { OverlayControlButton } from "../../react/OverlayControlGroup";import { ParentMap, useMapPitch } from "./map";/**@@ -15,8 +16,8 @@ import { ParentMap, useMapPitch } from "./map";* MapLibre offers bars of its own for both (`NavigationControl`, which is what stood here, and* `FullscreenControl`), dressed in neither Trilium's buttons nor Trilium's colors — a white box with* hairline-separated squares in it, on a map that may well be dark. What they do is done here- * instead, on the control group the image viewer's zoom buttons stand on (`tn-overlay-control-group`,- * see {@link ImageViewer}). No readout between the steps, though: a map's zoom level is a number+ * instead, on the {@link OverlayControlGroup} the image viewer's zoom buttons stand on (see+ * {@link ImageViewer}). No readout between the steps, though: a map's zoom level is a number* out of the cartographer's toolbox, not the reader's, and a map has no fitted view a readout* could offer back the way an image has.*@@ -44,78 +45,45 @@ export default function MapToolbar() {// everything the bar above the map offers is on the map's right-click menu as well.const [ isFullscreen, toggleFullscreen ] = useFullscreen(map?.getContainer());- const tiltRef = useRef<HTMLButtonElement>(null);- const zoomOutRef = useRef<HTMLButtonElement>(null);- const zoomInRef = useRef<HTMLButtonElement>(null);- const fullscreenRef = useRef<HTMLButtonElement>(null);-- // Whether the reader is in a 3D view however they got there — the button, or Ctrl and a drag.- const isTilted = (pitch ?? map?.getPitch() ?? 0) > 0;-- // The group stands at the foot of the map, so its tooltips open away from that edge, where- // they would otherwise fall off.- useStaticTooltip(tiltRef, {- title: isTilted ? t("geo-map.exit-3d") : t("geo-map.enter-3d"),- placement: "top"- });- useStaticTooltip(zoomOutRef, { title: t("geo-map.zoom-out"), placement: "top" });- useStaticTooltip(zoomInRef, { title: t("geo-map.zoom-in"), placement: "top" });- useStaticTooltip(fullscreenRef, {- title: isFullscreen ? t("geo-map.exit-fullscreen") : t("geo-map.fullscreen"),- placement: "top"- });-if (!map) return null;+ // Whether the reader is in a 3D view however they got there — the button, or Ctrl and a drag.+ const isTilted = (pitch ?? map.getPitch()) > 0;// Before the first report, which follows the very next tick: what the map already says it is.const current = zoom ?? map.getZoom();return (- <div- className="geo-map-toolbar tn-overlay-control-group"- /* Keep a press on the controls from reaching the canvas underneath, which would- otherwise take it for the start of a drag. */- onMouseDown={(e) => e.stopPropagation()}- >+ <OverlayControlGroup className="geo-map-toolbar" overCanvas>{/* Its face names the view it offers, not the one in force — Google Maps's way round. */}- <button- ref={tiltRef}- type="button"- className="tn-overlay-text-button geo-map-tilt-button"- aria-label={isTilted ? t("geo-map.exit-3d") : t("geo-map.enter-3d")}+ <OverlayControlButton+ title={isTilted ? t("geo-map.exit-3d") : t("geo-map.enter-3d")}+ text={isTilted ? "2D" : "3D"}+ className="geo-map-tilt-button"onClick={() => map.easeTo({ pitch: isTilted ? 0 : TILTED_PITCH })}- >- {isTilted ? "2D" : "3D"}- </button>+ />{!isMobile() && <>- <button- ref={zoomOutRef}- type="button"- className="tn-overlay-icon-button bx bx-minus-circle"- aria-label={t("geo-map.zoom-out")}+ <OverlayControlButton+ title={t("geo-map.zoom-out")}+ icon="bx-minus-circle"disabled={current <= map.getMinZoom()}onClick={() => map.zoomOut()}/>- <button- ref={zoomInRef}- type="button"- className="tn-overlay-icon-button bx bx-plus-circle"- aria-label={t("geo-map.zoom-in")}+ <OverlayControlButton+ title={t("geo-map.zoom-in")}+ icon="bx-plus-circle"disabled={current >= map.getMaxZoom()}onClick={() => map.zoomIn()}/></>}- <button- ref={fullscreenRef}- type="button"- className={`tn-overlay-icon-button bx ${isFullscreen ? "bx-exit-fullscreen" : "bx-fullscreen"}`}- aria-label={isFullscreen ? t("geo-map.exit-fullscreen") : t("geo-map.fullscreen")}+ <OverlayControlButton+ title={isFullscreen ? t("geo-map.exit-fullscreen") : t("geo-map.fullscreen")}+ icon={isFullscreen ? "bx-exit-fullscreen" : "bx-fullscreen"}// Nothing here is measured across the change: the map keeps the middle of its view// through a resize of its own accord, and it is told of the new size by the view// itself (see `useElementSize` in map.tsx).onClick={() => void toggleFullscreen()}/>- </div>+ </OverlayControlGroup>);}diff --git a/apps/client/src/widgets/react/ImageViewer.tsx b/apps/client/src/widgets/react/ImageViewer.tsxindex bf08fcd0b4..3158b44bba 100644--- a/apps/client/src/widgets/react/ImageViewer.tsx+++ b/apps/client/src/widgets/react/ImageViewer.tsx@@ -197,11 +197,10 @@ export default function ImageViewer({ src, imgClassName, alt = "", minScale = 0./><OverlayControlButtontitle={t("image_buttons.reset_zoom")}+ text={`${zoomPercent}%`}className="image-viewer-zoom-level"onClick={() => zoomRef.current?.resetTransform()}- >- {zoomPercent}%- </OverlayControlButton>+ /><OverlayControlButtontitle={t("image_buttons.zoom_in")}icon="bx-plus-circle"diff --git a/apps/client/src/widgets/react/OverlayControlGroup.spec.tsx b/apps/client/src/widgets/react/OverlayControlGroup.spec.tsxindex c205600fb3..a9b81e0c21 100644--- a/apps/client/src/widgets/react/OverlayControlGroup.spec.tsx+++ b/apps/client/src/widgets/react/OverlayControlGroup.spec.tsx@@ -32,11 +32,11 @@ function tooltipFor(label: string) {}describe("OverlayControlGroup", () => {- it("renders a group of icon and text buttons, each labelled by its title", () => {+ it("draws a button wearing a mark at an icon's width, and one wearing words at a word's", () => {mount(<OverlayControlGroup className="my-position"><OverlayControlButton title="Zoom out" icon="bx-minus-circle" />- <OverlayControlButton title="Reset zoom" className="my-readout">100%</OverlayControlButton>+ <OverlayControlButton title="Reset zoom" text="100%" className="my-readout" /></OverlayControlGroup>);@@ -45,28 +45,106 @@ describe("OverlayControlGroup", () => {// 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("leaves a readout to be named by what it shows, with nothing to say on hover", () => {+ it("names a button by the words it wears, and one wearing only a mark by its title", () => {mount(<OverlayControlGroup>- <OverlayControlButton className="my-readout" disabled>3/12</OverlayControlButton>+ <OverlayControlButton title="Zoom out" icon="bx-minus-circle" />+ <OverlayControlButton title="Create a new child note and add it to the map" text="Add marker" />+ </OverlayControlGroup>+ );++ const [ mark, words ] = container.querySelectorAll("button");+ // Nothing to read on it, so what it is called has to be said outright.+ expect(mark.getAttribute("aria-label")).toBe("Zoom out");+ // A title saying more at length would otherwise speak over the words on the face of it.+ expect(words.hasAttribute("aria-label")).toBe(false);+ expect(staticTooltipSpy.mock.calls.at(-1)?.[1]?.title).toBe("Create a new child note and add it to the map");+ });++ it("stands a mark beside the words where it is given both", () => {+ mount(+ <OverlayControlGroup>+ <OverlayControlButton title="Create a new child note" icon="bx-pin" text="Add marker" />+ </OverlayControlGroup>+ );++ const button = container.querySelector("button");+ // The button keeps a word's width; the mark is a child, so the boxicons font it sets does+ // not fall on the words beside it.+ expect(button?.className).toContain("tn-overlay-text-button");+ expect(button?.className).not.toContain("bx-pin");+ const mark = button?.querySelector(".bx.bx-pin");+ expect(mark?.getAttribute("aria-hidden")).toBe("true");+ expect(button?.textContent).toBe("Add marker");+ });++ it("stays a worded button where the words it was handed came back empty", () => {+ // A translation resolved before the catalogue is loaded, which must not quietly narrow the+ // button to a mark's width and take its name with it.+ mount(+ <OverlayControlGroup>+ <OverlayControlButton title="Create a new child note" icon="bx-pin" text={undefined} />+ </OverlayControlGroup>+ );++ const button = container.querySelector("button");+ expect(button?.className).toContain("tn-overlay-text-button");+ expect(button?.querySelector(".bx.bx-pin")).not.toBeNull();+ });++ it("lets a caller name a button whose face is neither words nor a mark", () => {+ mount(+ <OverlayControlGroup>+ <OverlayControlButton+ title="Show keyboard shortcuts"+ aria-label="Show keyboard shortcuts"+ text={<kbd>?</kbd>}+ />+ </OverlayControlGroup>+ );++ const button = container.querySelector("button");+ expect(button?.getAttribute("aria-label")).toBe("Show keyboard shortcuts");+ expect(button?.querySelector("kbd")?.textContent).toBe("?");+ });++ it("says nothing on hover where there is no title to say", () => {+ mount(+ <OverlayControlGroup>+ <OverlayControlButton text="3/12" className="my-readout" disabled /></OverlayControlGroup>);const readout = container.querySelector("button");expect(readout?.hasAttribute("aria-label")).toBe(false);expect(readout?.textContent).toBe("3/12");- // No title, so the hook finds nothing to build a tooltip from.expect(staticTooltipSpy.mock.calls.at(-1)?.[1]?.title).toBeUndefined();});+ it("keeps a press from reaching the canvas underneath only where it stands over one", () => {+ const onMouseDown = vi.fn();+ const group = (overCanvas: boolean) => (+ <OverlayControlGroup overCanvas={overCanvas}>+ <OverlayControlButton title="Zoom in" icon="bx-plus-circle" />+ </OverlayControlGroup>+ );+ mount(group(true));+ container.addEventListener("mousedown", onMouseDown);++ container.querySelector("button")?.dispatchEvent(new MouseEvent("mousedown", { bubbles: true }));+ expect(onMouseDown).not.toHaveBeenCalled();++ // A group over something that is not dragged lets the press through, as any button would.+ act(() => render(group(false), container));+ container.querySelector("button")?.dispatchEvent(new MouseEvent("mousedown", { bubbles: true }));+ expect(onMouseDown).toHaveBeenCalledTimes(1);+ });+it("marks a button held down or refused when asked to", () => {mount(<OverlayControlGroup>@@ -107,7 +185,7 @@ describe("OverlayControlGroup", () => {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>+ <OverlayControlButton title="Reset zoom" text={label} /></OverlayControlGroup>);mount(group("100%"));diff --git a/apps/client/src/widgets/react/OverlayControlGroup.tsx b/apps/client/src/widgets/react/OverlayControlGroup.tsxindex 4ba3cbd3d2..6578c2859b 100644--- a/apps/client/src/widgets/react/OverlayControlGroup.tsx+++ b/apps/client/src/widgets/react/OverlayControlGroup.tsx@@ -10,6 +10,11 @@ interface OverlayControlGroupProps {className?: string;/** Which way the buttons' tooltips open — away from the edge the group is pinned to. */titlePosition?: ActionButtonProps["titlePosition"];+ /**+ * Keeps a press on the group from reaching what it stands on, for a group over a canvas that is+ * dragged: a map would otherwise take a press on a button for the start of a drag.+ */+ overCanvas?: boolean;children: ComponentChildren;}@@ -25,9 +30,12 @@ interface OverlayControlGroupProps {* 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) {+export default function OverlayControlGroup({ className, titlePosition, overCanvas, children }: OverlayControlGroupProps) {return (- <div className={clsx("tn-overlay-control-group", className)}>+ <div+ className={clsx("tn-overlay-control-group", className)}+ onMouseDown={overCanvas ? (e) => e.stopPropagation() : undefined}+ ><TooltipDirection.Provider value={titlePosition ?? "top"}>{children}</TooltipDirection.Provider>@@ -35,19 +43,13 @@ export default function OverlayControlGroup({ className, titlePosition, children);}-interface OverlayControlButtonProps extends Pick<HTMLAttributes<HTMLButtonElement>, "onClick"> {- /**- * What the button does: shown as its tooltip, and read out as its accessible name. A readout that- * says what it is through its own children — an index, a percentage — needs none, and is left to- * be named by what it shows.- */+interface OverlayControlButtonProps extends Pick<HTMLAttributes<HTMLButtonElement>, "onClick" | "aria-label"> {+ /** What the button does, said on hover. Where the button wears nothing to read, it is its name too. */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.- */+ /** The boxicons name of the mark it wears (`bx-plus-circle`). */icon?: string;+ /** What stands inside the button: the words it wears, or the value it shows. */+ text?: ComponentChildren;/** Extra class for whatever is peculiar to this one button. */className?: string;/** Shown held down, for a button standing for a choice in force. */@@ -55,19 +57,28 @@ interface OverlayControlButtonProps extends Pick<HTMLAttributes<HTMLButtonElemendisabled?: 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.+ * A button on such a group, in one of two shapes: a mark, drawn at an icon's width, or something to+ * read, drawn at a word's. Given both, the mark stands beside the words — as a child rather than as a+ * class on the button, the boxicons class setting the icon font on whatever wears it and the words+ * beside it being meant to stay words.+ *+ * What it is called follows from that: a button wearing words is named by them, and one wearing only a+ * mark by its title, so that a title saying more at length never speaks over the words on the face of+ * the button. Where what it wears is neither — a keycap, a glyph standing for itself — say so with a+ * plain `aria-label`.+ *+ * Its tooltip 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) {+export function OverlayControlButton(props: OverlayControlButtonProps) {+ const { title, icon, text, className, active, disabled, titlePosition, ...restProps } = props;const buttonRef = useRef<HTMLButtonElement>(null);const groupDirection = useContext(TooltipDirection);const placement = titlePosition ?? groupDirection;+ const hasText = "text" in props;// 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.@@ -80,12 +91,14 @@ export function OverlayControlButton({ title, icon, className, active, disabled,// 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}+ className={clsx(hasText ? "tn-overlay-text-button" : [ "tn-overlay-icon-button bx", icon ], active && "active", className)}+ // A caller passing one of its own wins, for a face that is neither words nor a mark.+ aria-label={hasText ? undefined : title}disabled={disabled}{...restProps}>- {children}+ {hasText && icon && <span className={clsx("bx", icon)} aria-hidden="true" />}+ {text}</button>);}diff --git a/apps/client/src/widgets/react/SiblingNavigator.tsx b/apps/client/src/widgets/react/SiblingNavigator.tsxindex bda60be20a..8e9bb66067 100644--- a/apps/client/src/widgets/react/SiblingNavigator.tsx+++ b/apps/client/src/widgets/react/SiblingNavigator.tsx@@ -91,9 +91,11 @@ export default function SiblingNavigator({ note, noteContext, viewScope, siblingonClick={() => navigation.navigatePrevious()}/>- <OverlayControlButton className="sibling-navigator-index" disabled>- {navigation.index}/{navigation.total}- </OverlayControlButton>+ <OverlayControlButton+ text={`${navigation.index}/${navigation.total}`}+ className="sibling-navigator-index"+ disabled+ /><OverlayControlButtontitle={t(nextTooltipI18nKey, { title: navigation.nextTitle })}diff --git a/apps/client/src/widgets/shortcut_hints/shortcut_hint_button.tsx b/apps/client/src/widgets/shortcut_hints/shortcut_hint_button.tsxindex 4fc885a52a..34a1a02d82 100644--- a/apps/client/src/widgets/shortcut_hints/shortcut_hint_button.tsx+++ b/apps/client/src/widgets/shortcut_hints/shortcut_hint_button.tsx@@ -54,11 +54,15 @@ export function ShortcutHintOverlayButton() {return (<OverlayControlButtontitle={t("shortcut_hints.show_button")}+ // A keycap standing for itself rather than words that would name the button, so what it+ // is called is said outright.+ aria-label={t("shortcut_hints.show_button")}+ text={<>+ <kbd>?</kbd>+ <span className="shortcut-hint-button-key">{shortcut}</span>+ </>}className="shortcut-hint-button tn-shortcut-hints-kbd"onClick={onClick}- >- <kbd>?</kbd>- <span className="shortcut-hint-button-key">{shortcut}</span>- </OverlayControlButton>+ />);}