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 diagram preview's zoom on the control group
Elian Doran7994cd31268b
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex e9e0d68e04..cb89348d43 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -3214,7 +3214,10 @@},"svg": {"export_to_png": "The diagram could not be exported to PNG.",- "export_to_svg": "The diagram could not be exported to SVG."+ "export_to_svg": "The diagram could not be exported to SVG.",+ "zoom_in": "Zoom in",+ "zoom_out": "Zoom out",+ "reset_zoom": "Reset zoom"},"code_theme": {"title": "Appearance",diff --git a/apps/client/src/widgets/react/OverlayToolbar.tsx b/apps/client/src/widgets/react/OverlayToolbar.tsxindex ab68a60fc0..afc7894312 100644--- a/apps/client/src/widgets/react/OverlayToolbar.tsx+++ b/apps/client/src/widgets/react/OverlayToolbar.tsx@@ -36,8 +36,8 @@ export default function OverlayToolbar({ className, titlePosition, children }: O}/**- * A button on such a bar, dressed as the buttons floating over a rendered diagram are (see- * SplitEditor's `PreviewButton`).+ * A button on such a bar, dressed as the buttons floating over a relation map are (see+ * {@link RelationMap}).** Its tooltip opens the way the bar it stands on says, so that a bar at the foot of a canvas does not* open its tooltips off the bottom edge — overridable per button where one of them is placeddiff --git a/apps/client/src/widgets/type_widgets/helpers/SplitEditor.css b/apps/client/src/widgets/type_widgets/helpers/SplitEditor.cssindex 58cde28989..a3414c711b 100644--- a/apps/client/src/widgets/type_widgets/helpers/SplitEditor.css+++ b/apps/client/src/widgets/type_widgets/helpers/SplitEditor.css@@ -166,4 +166,11 @@ body.desktop .note-detail-split .note-detail-code-editor {height: 100%;max-width: 100% !important;}++.note-detail-split.svg-editor .svg-preview-controls {+ position: absolute;+ inset-inline-end: var(--overlay-button-inset, 10px);+ bottom: var(--overlay-button-inset, 10px);+ z-index: 10;+}/* #endregion */diff --git a/apps/client/src/widgets/type_widgets/helpers/SplitEditor.tsx b/apps/client/src/widgets/type_widgets/helpers/SplitEditor.tsxindex 80e72433c4..a104c9f1b0 100644--- a/apps/client/src/widgets/type_widgets/helpers/SplitEditor.tsx+++ b/apps/client/src/widgets/type_widgets/helpers/SplitEditor.tsx@@ -7,7 +7,6 @@ import { useEffect, useRef } from "preact/hooks";import { t } from "../../../services/i18n";import { DEFAULT_GUTTER_SIZE } from "../../../services/resizer";import utils, { isMobile } from "../../../services/utils";-import ActionButton, { ActionButtonProps } from "../../react/ActionButton";import { ExtendedAdmonition } from "../../react/Admonition";import { Badge } from "../../react/Badge";import { useEffectiveReadOnly, useNoteBlob, useNoteLabel, useTriliumOption } from "../../react/hooks";@@ -157,9 +156,9 @@ function PreviewContainer({ error, previewStale, previewContent, previewButtonstext={t("split_editor.last_valid_render")}/>)}- <div className="btn-group btn-group-sm map-type-switcher content-floating-buttons preview-buttons bottom-right" role="group">- {previewButtons}- </div>+ {/* Placed by whoever supplies them: they stand on a group that brings its own surface+ and pins itself to a corner of the pane (see the SVG section of SplitEditor.css). */}+ {previewButtons}</div>);}@@ -182,15 +181,6 @@ function splitPreviewError(error: string): { summary: string; details?: string }};}-export function PreviewButton(props: Omit<ActionButtonProps, "titlePosition">) {- return <ActionButton- {...props}- className="tn-tool-button"- noIconActionClass- titlePosition="top"- />;-}-function useSplitOrientation(forceOrientation?: "horizontal" | "vertical") {const [ splitEditorOrientation ] = useTriliumOption("splitEditorOrientation");if (forceOrientation) return forceOrientation;diff --git a/apps/client/src/widgets/type_widgets/helpers/SvgSplitEditor.spec.tsx b/apps/client/src/widgets/type_widgets/helpers/SvgSplitEditor.spec.tsxindex c8663c4965..6befe1b422 100644--- a/apps/client/src/widgets/type_widgets/helpers/SvgSplitEditor.spec.tsx+++ b/apps/client/src/widgets/type_widgets/helpers/SvgSplitEditor.spec.tsx@@ -11,17 +11,31 @@ import type { SplitEditorProps } from "./SplitEditor";// never puts it back. `useResizer` (SvgSplitEditor.tsx) is responsible for restoring it itself;// this fake reproduces exactly that stripping-without-restoring behavior so the test exercises// the real bug shape rather than a strawman.+//+// It also keeps a scale, the way the library does: a step multiplies it by the library's own+// sensitivity and is clamped to the same bounds, a fit takes it back to the view it opened at, and+// every change is told to whoever asked to be told (`setOnZoom`) — which is what the readout follows.vi.mock("svg-pan-zoom", () => ({default: vi.fn((svgEl: SVGElement) => {svgEl.removeAttribute("viewBox");+ let zoom = 1;+ let onZoom: ((zoom: number) => void) | undefined;+ const setZoom = (value: number) => {+ zoom = Math.min(10, Math.max(0.5, value));+ onZoom?.(zoom);+ return instance;+ };const instance = {resize: () => instance,center: () => instance,- fit: () => instance,- zoom: () => instance,+ fit: () => setZoom(1),+ zoom: (value: number) => setZoom(value),+ zoomIn: () => setZoom(zoom * 1.2),+ zoomOut: () => setZoom(zoom / 1.2),pan: () => instance,getPan: () => ({ x: 0, y: 0 }),- getZoom: () => 1,+ getZoom: () => zoom,+ setOnZoom: (fn: (zoom: number) => void) => { onZoom = fn; return instance; },destroy: () => {}};return instance;@@ -29,16 +43,21 @@ vi.mock("svg-pan-zoom", () => ({}));// SplitEditor pulls in CodeMirror, Split.js and a Bootstrap ribbon that have nothing to do with-// the pan/zoom behavior under test; stub it down to just the preview pane, and fire the same-// `onContentChanged` callback the real editor would once content arrives.+// the pan/zoom behavior under test; stub it down to just the preview pane and the controls over it,+// and fire the same `onContentChanged` callback the real editor would once content arrives.vi.mock("./SplitEditor", () => ({- default: ({ previewContent, onContentChanged }: SplitEditorProps) => {+ default: ({ previewContent, previewButtons, onContentChanged }: SplitEditorProps) => {useEffect(() => {onContentChanged?.("gantt\nsection Test\nTask: 2024-01-01, 1d");}, []);- return <div>{previewContent}</div>;- },- PreviewButton: () => null+ return <div>{previewContent}{previewButtons}</div>;+ }+}));++// The bootstrap tooltip the control buttons wear needs real layout, which happy-dom hasn't.+vi.mock("../../react/hooks", async (importOriginal) => ({+ ...(await importOriginal<object>()),+ useStaticTooltip: () => {}}));const ORIGINAL_VIEW_BOX = "0 0 1234 56";@@ -63,8 +82,67 @@ describe("SvgSplitEditor", () => {expect(svgEl.getAttribute("viewBox")).toBeNull();});++ it("says the scale the diagram is drawn at, and fits it back to the pane when the readout is pressed", async () => {+ const { container, controls, unmount } = await mountControls();++ expect(controls().readout.textContent).toBe("100%");++ act(() => controls().zoomIn.click());+ expect(controls().readout.textContent).toBe("120%");++ act(() => controls().readout.click());+ expect(controls().readout.textContent).toBe("100%");++ unmount();+ container.remove();+ });++ it("leaves a step with no room left to it disabled", async () => {+ const { container, controls, unmount } = await mountControls();++ expect(controls().zoomOut.disabled).toBe(false);++ // Far enough to be clamped at either end, so the readout sits exactly on the limit — which+ // is where the rounding the tolerance covers would otherwise leave the button live.+ for (let i = 0; i < 20; i++) act(() => controls().zoomOut.click());+ expect(controls().readout.textContent).toBe("50%");+ expect(controls().zoomOut.disabled).toBe(true);+ expect(controls().zoomIn.disabled).toBe(false);++ for (let i = 0; i < 20; i++) act(() => controls().zoomIn.click());+ expect(controls().readout.textContent).toBe("1000%");+ expect(controls().zoomIn.disabled).toBe(true);+ expect(controls().zoomOut.disabled).toBe(false);++ unmount();+ container.remove();+ });});+/**+ * Mounts `SvgSplitEditor` and waits for the controls over the rendered diagram to appear, handing+ * back a reader for the three buttons. They are read afresh on every call, the group being drawn+ * anew whenever the scale changes.+ */+async function mountControls() {+ const container = document.createElement("div");+ document.body.appendChild(container);++ await act(async () => {+ render(<SvgSplitEditor {...svgSplitEditorProps(SVG_MARKUP)} />, container);+ });++ await vi.waitFor(() => expect(container.querySelectorAll(".tn-overlay-control-group button")).toHaveLength(3));++ const controls = () => {+ const [ zoomOut, readout, zoomIn ] = container.querySelectorAll<HTMLButtonElement>(".svg-preview-controls button");+ return { zoomOut, readout, zoomIn };+ };++ return { container, controls, unmount: () => act(() => render(null, container)) };+}+/*** Mounts `SvgSplitEditor` around the given SVG markup, waits for the SVG to render, runs the* optional pre-unmount assertion, then unmounts to trigger the effect cleanup under test anddiff --git a/apps/client/src/widgets/type_widgets/helpers/SvgSplitEditor.tsx b/apps/client/src/widgets/type_widgets/helpers/SvgSplitEditor.tsxindex 10847abb4f..98a38e8c03 100644--- a/apps/client/src/widgets/type_widgets/helpers/SvgSplitEditor.tsx+++ b/apps/client/src/widgets/type_widgets/helpers/SvgSplitEditor.tsx@@ -7,8 +7,9 @@ import server from "../../../services/server";import toast from "../../../services/toast";import utils from "../../../services/utils";import { useElementSize, useTriliumEvent } from "../../react/hooks";+import OverlayControlGroup, { OverlayControlButton } from "../../react/OverlayControlGroup";import { RawHtmlBlock } from "../../react/RawHtml";-import SplitEditor, { PreviewButton, SplitEditorProps } from "./SplitEditor";+import SplitEditor, { SplitEditorProps } from "./SplitEditor";interface SvgSplitEditorProps extends Omit<SplitEditorProps, "previewContent"> {/**@@ -113,7 +114,7 @@ export default function SvgSplitEditor({ ntxId, note, attachmentTitle, renderSvg});// Pan & zoom.- const zoomRef = useResizer(containerRef, note.noteId, svg);+ const panZoom = useResizer(containerRef, note.noteId, svg);return (<SplitEditor@@ -131,35 +132,102 @@ export default function SvgSplitEditor({ ntxId, note, attachmentTitle, renderSvghtml={svg}/>)}- previewButtons={- <>- <PreviewButton- icon="bx bx-zoom-in"- text={t("relation_map_buttons.zoom_in_title")}- onClick={() => zoomRef.current?.zoomIn()}- />- <PreviewButton- icon="bx bx-zoom-out"- text={t("relation_map_buttons.zoom_out_title")}- onClick={() => zoomRef.current?.zoomOut()}- />- <PreviewButton- icon="bx bx-crop"- text={t("relation_map_buttons.reset_pan_zoom_title")}- onClick={() => zoomRef.current?.fit().center()}- />- </>- }+ previewButtons={<PreviewControls panZoom={panZoom} />}{...props}/>);}+/**+ * How far in and out the rendered diagram may be taken, as a multiple of the view it opened at —+ * svg-pan-zoom's own defaults, said here so that the steps and the library agree on where the ends+ * are rather than one of them finding out by being clamped.+ */+const MIN_ZOOM = 0.5;+const MAX_ZOOM = 10;+/**+ * How near an end counts as being at it: the library clamps a step to the limit as an absolute scale,+ * and the trip back through the fitted scale can leave the readout a hair short of the round number.+ */+const ZOOM_LIMIT_TOLERANCE = 1e-6;++/**+ * The controls standing in the corner of a rendered diagram: how close in it is drawn, and the way+ * back to the view it opened at.+ *+ * They stand on the {@link OverlayControlGroup} the image viewer's zoom buttons stand on (see+ * {@link ImageViewer}), as the two maps' controls do, in place of the three floating buttons that+ * were here before. The readout between the steps says the scale the way the image viewer's does — a+ * hundred being the diagram at the size it was fitted to the pane at — and pressed, fits and centers+ * it there again, which is all the button wearing a crop mark used to do.+ *+ * Kept on mobile, unlike the image viewer's and the maps' steps: a pinch does nothing here — the+ * library follows a finger for panning and takes a double tap for a zoom in, and knows no pinch at+ * all — so the steps are the only way to settle on a scale. Absent until there is something to zoom,+ * an empty or not-yet-rendered diagram having no view to speak of.+ */+function PreviewControls({ panZoom }: { panZoom: SvgPanZoom.Instance | undefined }) {+ const zoom = usePanZoomScale(panZoom);++ if (!panZoom) return null;++ return (+ <OverlayControlGroup className="svg-preview-controls">+ <OverlayControlButton+ title={t("svg.zoom_out")}+ icon="bx-minus-circle"+ disabled={zoom <= MIN_ZOOM * (1 + ZOOM_LIMIT_TOLERANCE)}+ onClick={() => panZoom.zoomOut()}+ />+ <OverlayControlButton+ title={t("svg.reset_zoom")}+ text={`${Math.round(zoom * 100)}%`}+ onClick={() => panZoom.fit().center()}+ />+ <OverlayControlButton+ title={t("svg.zoom_in")}+ icon="bx-plus-circle"+ disabled={zoom >= MAX_ZOOM * (1 - ZOOM_LIMIT_TOLERANCE)}+ onClick={() => panZoom.zoomIn()}+ />+ </OverlayControlGroup>+ );+}++/**+ * The scale the diagram is drawn at, followed as it changes — by these buttons, by the wheel, or by+ * the diagram being fitted afresh. It is told as a multiple of the fitted view rather than of the+ * diagram's own coordinates, which is what makes a hundred mean the view the pane opened at.+ *+ * Nothing is unsubscribed on the way out: what stops the reports is the instance being destroyed by+ * the hook that made it, which drops the callback along with the rest of its options.+ */+function usePanZoomScale(panZoom: SvgPanZoom.Instance | undefined) {+ const [ zoom, setZoom ] = useState(1);++ useEffect(() => {+ if (!panZoom) return;++ // It is fitted as it is built, and may have been moved again before being listened to.+ setZoom(panZoom.getZoom());+ panZoom.setOnZoom(setZoom);+ }, [ panZoom ]);++ return zoom;+}++/**+ * Sets the rendered diagram up to be panned and zoomed, and hands the instance driving it back so+ * that the controls over it can drive it too — as state rather than as the ref the effects here+ * keep, so that the controls are drawn afresh when the diagram is fitted anew under a different+ * instance.+ */function useResizer(containerRef: RefObject<HTMLDivElement>, noteId: string, svg: string | undefined) {const lastPanZoom = useRef<{ pan: SvgPanZoom.Point, zoom: number }>();const lastNoteId = useRef<string>();const wasEmpty = useRef<boolean>(false);const zoomRef = useRef<SvgPanZoom.Instance>();+ const [ panZoom, setPanZoom ] = useState<SvgPanZoom.Instance>();const width = useElementSize(containerRef);// Set up pan & zoom.@@ -184,7 +252,9 @@ function useResizer(containerRef: RefObject<HTMLDivElement>, noteId: string, svgconst zoomInstance = svgPanZoom(svgEl, {zoomEnabled: true,- controlIconsEnabled: false+ controlIconsEnabled: false,+ minZoom: MIN_ZOOM,+ maxZoom: MAX_ZOOM});// Restore the previous pan/zoom if the user updates same note.@@ -197,6 +267,7 @@ function useResizer(containerRef: RefObject<HTMLDivElement>, noteId: string, svglastNoteId.current = noteId;zoomRef.current = zoomInstance;+ setPanZoom(zoomInstance);return () => {lastPanZoom.current = {@@ -204,6 +275,7 @@ function useResizer(containerRef: RefObject<HTMLDivElement>, noteId: string, svgzoom: zoomInstance.getZoom()};zoomRef.current = undefined;+ setPanZoom(undefined);zoomInstance.destroy();if (viewBox !== null) {svgEl.setAttribute("viewBox", viewBox);@@ -217,5 +289,5 @@ function useResizer(containerRef: RefObject<HTMLDivElement>, noteId: string, svgzoomRef.current.resize().fit().center();}, [ width ]);- return zoomRef;+ return panZoom;}