From 2b090273683f9f2f4d4ff61e42b3cb6c113e811a Mon Sep 17 00:00:00 2001 From: Michael Herzner Date: Sun, 8 Dec 2024 20:17:59 +0100 Subject: [PATCH] chore: center graph with sensible defaults on load --- .../package/(_islands)/DependencyGraph.tsx | 38 ++++++++++++++----- 1 file changed, 28 insertions(+), 10 deletions(-) diff --git a/frontend/routes/package/(_islands)/DependencyGraph.tsx b/frontend/routes/package/(_islands)/DependencyGraph.tsx index 044389fe..8778f634 100644 --- a/frontend/routes/package/(_islands)/DependencyGraph.tsx +++ b/frontend/routes/package/(_islands)/DependencyGraph.tsx @@ -117,6 +117,22 @@ function useDigraph(dependencies: DependencyGraphProps["dependencies"]) { const svg = useRef(null); const viz = useSignal(undefined); + const center = useCallback(() => { + if (svg.current && ref.current) { + const { width: sWidth, height: sHeight } = svg.current + .getBoundingClientRect(); + const { width: rWidth, height: rHeight } = ref.current + .getBoundingClientRect(); + + controls.value.pan.x = (rWidth - sWidth) / 2; + controls.value.pan.y = (rHeight - sHeight) / 2; + controls.value.zoom = Math.min(rWidth / sWidth, rHeight / sHeight); + + svg.current.style.transform = + `translate(${controls.value.pan.x}px, ${controls.value.pan.y}px) scale(${controls.value.zoom})`; + } + }, []); + const pan = useCallback((x: number, y: number) => { controls.value.pan.x += x; controls.value.pan.y += y; @@ -153,7 +169,9 @@ function useDigraph(dependencies: DependencyGraphProps["dependencies"]) { const digraph = createDigraph(dependencies); svg.current = viz.value.renderSVGElement(digraph); - ref.current.appendChild(svg.current); + ref.current.prepend(svg.current); + + center(); } })(); }, [dependencies]); @@ -205,15 +223,15 @@ export function DependencyGraph(props: DependencyGraphProps) { } return ( -
-
+
{/* zoom */}