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
feat(mermaid): put the preview's zoom steps back on the new instance
Elian Doran123202773a00
diff --git a/apps/client/src/widgets/type_widgets/helpers/SplitEditor.css b/apps/client/src/widgets/type_widgets/helpers/SplitEditor.cssindex e71940c802..0c71a6aafa 100644--- a/apps/client/src/widgets/type_widgets/helpers/SplitEditor.css+++ b/apps/client/src/widgets/type_widgets/helpers/SplitEditor.css@@ -175,4 +175,10 @@ body.desktop .note-detail-split .note-detail-code-editor {height: 100%;max-width: 100% !important;}++/* OverlayControlGroup pins the controls to the corner its `placement` names; the z-index is what+ keeps them over the error card the preview can be dimmed behind. */+.note-detail-split.svg-editor .svg-preview-controls {+ z-index: 10;+}/* #endregion */diff --git a/apps/client/src/widgets/type_widgets/helpers/SvgSplitEditor.spec.tsx b/apps/client/src/widgets/type_widgets/helpers/SvgSplitEditor.spec.tsxindex 5abbb55153..5a01a20a94 100644--- a/apps/client/src/widgets/type_widgets/helpers/SvgSplitEditor.spec.tsx+++ b/apps/client/src/widgets/type_widgets/helpers/SvgSplitEditor.spec.tsx@@ -6,32 +6,63 @@ import { beforeEach, describe, expect, it, vi } from "vitest";import type { SplitEditorProps } from "./SplitEditor";import SvgSplitEditor from "./SvgSplitEditor";-// react-zoom-pan-pinch measures its boxes, which happy-dom cannot do. Render the children in place-// and capture the props so the bounds handed to the library can still be asserted.+// react-zoom-pan-pinch measures its boxes, which happy-dom cannot do. This fake keeps the parts the+// controls drive: `zoomIn`/`zoomOut` add their step to the current scale and clamp it to the bounds+// it was given (the library's own arithmetic — see handleCalculateButtonZoom), `resetTransform`+// returns to the fitted view, and every change is reported through `onTransform`, which is what the+// readout follows. The props are captured too, so what is handed to the library can be asserted.const { transformWrapperSpy } = vi.hoisted(() => ({ transformWrapperSpy: vi.fn() }));-vi.mock("react-zoom-pan-pinch", () => ({- TransformWrapper: (props: { children?: ComponentChildren }) => {- transformWrapperSpy(props);- return props.children;- },- TransformComponent: (props: { children?: ComponentChildren; wrapperClass?: string }) => (- <div className={props.wrapperClass}>{props.children}</div>- )-}));+vi.mock("react-zoom-pan-pinch", async () => {+ const { forwardRef, useImperativeHandle, useRef } = await import("preact/compat");++ interface FakeProps {+ children?: ComponentChildren;+ minScale: number;+ maxScale: number;+ onTransform?: (ref: unknown, state: { scale: number }) => void;+ }++ return {+ TransformWrapper: forwardRef((props: FakeProps, ref) => {+ transformWrapperSpy(props);+ const scale = useRef(1);+ const apply = (target: number) => {+ const rounded = Number(target.toFixed(3));+ scale.current = Math.min(props.maxScale, Math.max(props.minScale, rounded));+ props.onTransform?.(null, { scale: scale.current });+ };+ useImperativeHandle(ref, () => ({+ zoomIn: (step: number) => apply(scale.current + step),+ zoomOut: (step: number) => apply(scale.current - step),+ resetTransform: () => apply(1)+ }));+ return props.children;+ }),+ TransformComponent: (props: { children?: ComponentChildren; wrapperClass?: string }) => (+ <div className={props.wrapperClass}>{props.children}</div>+ )+ };+});// 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>;+ 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";const SVG_MARKUP = `<svg viewBox="${ORIGINAL_VIEW_BOX}" xmlns="http://www.w3.org/2000/svg">`+ `<rect width="10" height="10"/></svg>`;@@ -48,23 +79,59 @@ describe("SvgSplitEditor", () => {// — svg-pan-zoom used to, which shrank gantt charts to invisibility on a re-fit (#9749).expect(svgEl?.getAttribute("viewBox")).toBe(ORIGINAL_VIEW_BOX);+ expect(transformWrapperSpy).toHaveBeenCalledWith(+ expect.objectContaining({ minScale: 0.5, maxScale: 10 })+ );+unmount();container.remove();});- it("bounds the zoom as a multiple of the fitted view", async () => {- const { container, unmount } = await mount();+ 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 mount();- expect(transformWrapperSpy).toHaveBeenCalledWith(- expect.objectContaining({ minScale: 0.5, maxScale: 10 })- );+ expect(controls().readout.textContent).toBe("100%");++ act(() => controls().zoomIn.click());+ expect(controls().readout.textContent).toBe("120%");++ act(() => controls().zoomIn.click());+ expect(controls().readout.textContent).toBe("144%");++ 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 mount();++ expect(controls().zoomOut.disabled).toBe(false);++ // Far enough to be clamped at either end, so the readout sits exactly on the bound — 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 < 30; 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 rendered diagram to appear. */+/**+ * Mounts `SvgSplitEditor` and waits for the rendered diagram and the controls over it 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 mount() {const container = document.createElement("div");document.body.appendChild(container);@@ -73,9 +140,14 @@ async function mount() {render(<SvgSplitEditor {...svgSplitEditorProps(SVG_MARKUP)} />, container);});- await vi.waitFor(() => expect(container.querySelector("svg")).not.toBeNull());+ await vi.waitFor(() => expect(container.querySelectorAll(".svg-preview-controls button")).toHaveLength(3));++ const controls = () => {+ const [ zoomOut, readout, zoomIn ] = container.querySelectorAll<HTMLButtonElement>(".svg-preview-controls button");+ return { zoomOut, readout, zoomIn };+ };- return { container, unmount: () => act(() => render(null, container)) };+ return { container, controls, unmount: () => act(() => render(null, container)) };}/**diff --git a/apps/client/src/widgets/type_widgets/helpers/SvgSplitEditor.tsx b/apps/client/src/widgets/type_widgets/helpers/SvgSplitEditor.tsxindex 581f80743a..61160ef054 100644--- a/apps/client/src/widgets/type_widgets/helpers/SvgSplitEditor.tsx+++ b/apps/client/src/widgets/type_widgets/helpers/SvgSplitEditor.tsx@@ -1,11 +1,13 @@-import { useCallback, useEffect, useState } from "preact/hooks";-import { TransformComponent, TransformWrapper } from "react-zoom-pan-pinch";+import { RefObject } from "preact";+import { useCallback, useEffect, useRef, useState } from "preact/hooks";+import { type ReactZoomPanPinchRef, TransformComponent, TransformWrapper } from "react-zoom-pan-pinch";import { t } from "../../../services/i18n";import server from "../../../services/server";import toast from "../../../services/toast";import utils from "../../../services/utils";import { useTriliumEvent } from "../../react/hooks";+import OverlayControlGroup, { OverlayControlButton } from "../../react/OverlayControlGroup";import { RawHtmlBlock } from "../../react/RawHtml";import SplitEditor, { SplitEditorProps } from "./SplitEditor";@@ -39,12 +41,15 @@ interface SvgSplitEditorProps extends Omit<SplitEditorProps, "previewContent"> {export default function SvgSplitEditor({ ntxId, note, attachmentTitle, renderSvg, ...props }: SvgSplitEditorProps) {const [ svg, setSvg ] = useState<string>();const [ error, setError ] = useState<string | null | undefined>();+ const [ zoom, setZoom ] = useState(1);+ const zoomRef = useRef<ReactZoomPanPinchRef>(null);// Reset the render state when switching notes so a previous note's render (and the// "showing last valid render" badge) can't briefly carry over to a different note.useEffect(() => {setSvg(undefined);setError(undefined);+ setZoom(1);}, [ note.noteId ]);// Render the SVG.@@ -124,17 +129,20 @@ export default function SvgSplitEditor({ ntxId, note, attachmentTitle, renderSvg// The transform sits on an ancestor of the diagram, so it survives a re-render// of the same note. Keying it on the note drops it when a different one opens.key={note.noteId}+ ref={zoomRef}minScale={MIN_ZOOM}maxScale={MAX_ZOOM}centerOnInitcenterZoomedOutdoubleClick={{ mode: "reset" }}+ onTransform={(_ref, { scale }) => setZoom(scale)}><TransformComponent wrapperClass="svg-preview-viewport" contentClass="svg-preview-content"><RawHtmlBlock className="render-container" html={svg} /></TransformComponent></TransformWrapper>)}+ previewButtons={!!svg && <PreviewControls zoomRef={zoomRef} zoom={zoom} />}{...props}/>);@@ -149,3 +157,52 @@ export default function SvgSplitEditor({ ntxId, note, attachmentTitle, renderSvg*/const MIN_ZOOM = 0.5;const MAX_ZOOM = 10;+/** What one press of a zoom step multiplies the scale by. */+const ZOOM_STEP = 1.2;+/**+ * How near a bound counts as being on it. The zoom animation reaches its target by adding the whole+ * difference back to the scale it started from, which can land a float's width short of the bound.+ */+const ZOOM_LIMIT_TOLERANCE = 1e-6;++/**+ * The zoom controls in the corner of the rendered diagram: a step in each direction, and between+ * them a readout that fits the diagram back to the pane when pressed.+ *+ * They stand on the {@link OverlayControlGroup} the image viewer's zoom buttons stand on, as the+ * two maps' controls do. The readout is a percentage of the fitted view, so a diagram opens at 100%.+ */+function PreviewControls({ zoomRef, zoom }: { zoomRef: RefObject<ReactZoomPanPinchRef>; zoom: number }) {+ return (+ <OverlayControlGroup className="svg-preview-controls" placement="bottom-end">+ <OverlayControlButton+ title={t("svg.zoom_out")}+ icon="bx-minus-circle"+ disabled={zoom <= MIN_ZOOM * (1 + ZOOM_LIMIT_TOLERANCE)}+ onClick={() => zoomRef.current?.zoomOut(zoomStep(zoom, "out"))}+ />+ <OverlayControlButton+ title={t("svg.reset_zoom")}+ text={`${Math.round(zoom * 100)}%`}+ onClick={() => zoomRef.current?.resetTransform()}+ />+ <OverlayControlButton+ title={t("svg.zoom_in")}+ icon="bx-plus-circle"+ disabled={zoom >= MAX_ZOOM * (1 - ZOOM_LIMIT_TOLERANCE)}+ onClick={() => zoomRef.current?.zoomIn(zoomStep(zoom, "in"))}+ />+ </OverlayControlGroup>+ );+}++/**+ * The increment that takes `scale` one {@link ZOOM_STEP} in the given direction.+ *+ * react-zoom-pan-pinch adds the step to the current scale, so a fixed step would be a leap at the+ * bottom of the range and a crawl at the top. Scaling the step by the scale it applies to keeps+ * every press the same proportion of what is on screen.+ */+function zoomStep(scale: number, direction: "in" | "out") {+ return direction === "in" ? scale * (ZOOM_STEP - 1) : scale * (1 - 1 / ZOOM_STEP);+}