✨ Innovative and open-source visualization application that transforms various data formats, such as JSON, YAML, XML and CSV into interactive graphs.
fix(jsoncrack-react): reliable fit-to-center and responsive viewport
AykutSarac957c07b5fc3a
diff --git a/packages/jsoncrack-react/CHANGELOG.md b/packages/jsoncrack-react/CHANGELOG.mdnew file mode 100644index 00000000..ae77e692--- /dev/null+++ b/packages/jsoncrack-react/CHANGELOG.md@@ -0,0 +1,28 @@+# Changelog++All notable changes to `jsoncrack-react` will be documented in this file.++The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),+and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).++## [1.0.2] - 2026-04-10++### Fixed++- Graph now lands correctly centered on initial load and on every Fit click.+- Graph re-centers when the host container is resized.+- Edge labels use a sans-serif font regardless of host-page CSS.++### Added++- Basic screen-reader affordance on the canvas (`role="img"` ++ `aria-label="JSON data visualization"`).++### Changed++- `json` prop type narrowed from `string | object | unknown[]` to+ `string | object`. Arrays are still accepted — no consumer action required.++## [1.0.1]++Initial published version.diff --git a/packages/jsoncrack-react/package.json b/packages/jsoncrack-react/package.jsonindex 282046c3..d3c2bbab 100644--- a/packages/jsoncrack-react/package.json+++ b/packages/jsoncrack-react/package.json@@ -1,6 +1,6 @@{"name": "jsoncrack-react",- "version": "1.0.1",+ "version": "1.0.2","description": "Reusable JSON Crack canvas as a React component","license": "Apache-2.0","author": "Aykut Saraç",@@ -29,7 +29,8 @@"./style.css": "./dist/index.css"},"files": [- "dist"+ "dist",+ "CHANGELOG.md"],"sideEffects": ["./dist/index.css"@@ -38,7 +39,9 @@"build": "vite build && tsc -p tsconfig.build.json","clean": "rm -rf dist","lint": "tsc -p tsconfig.build.json --noEmit && eslint src && prettier --check src",- "lint:fix": "eslint --fix src && prettier --write src"+ "lint:fix": "eslint --fix src && prettier --write src",+ "test": "vitest run",+ "test:watch": "vitest"},"peerDependencies": {"react": ">=18",@@ -65,6 +68,7 @@"prettier": "^3.8.1","typescript": "^5.9.3","typescript-eslint": "^8.57.1",- "vite": "^8.0.0"+ "vite": "^8.0.0",+ "vitest": "^2.1.9"}}diff --git a/packages/jsoncrack-react/src/JSONCrackComponent.tsx b/packages/jsoncrack-react/src/JSONCrackComponent.tsxindex 8f26c734..7e219b02 100644--- a/packages/jsoncrack-react/src/JSONCrackComponent.tsx+++ b/packages/jsoncrack-react/src/JSONCrackComponent.tsx@@ -1,17 +1,38 @@"use client";-import React from "react";+import {+ forwardRef,+ useCallback,+ useEffect,+ useImperativeHandle,+ useMemo,+ useRef,+ useState,+ type CSSProperties,+ type ReactNode,+} from "react";import type { ViewPort } from "react-zoomable-ui";import { Space } from "react-zoomable-ui";import { Canvas } from "reaflow";-import type { ElkRoot } from "reaflow";+import type { EdgeProps, ElkRoot, NodeProps } from "reaflow";import { useLongPress } from "use-long-press";import styles from "./JSONCrackStyles.module.css";+import {+ adjustViewPortZoom,+ buildCanvasClassName,+ buildCanvasStyle,+ buildEdgeTargetMap,+ fitGraphToViewPort,+ focusRootNode,+ parseJsonGraph,+ setCanvasDragging,+ setViewPortZoom,+ toJsonText,+ type JsonInput,+} from "./canvasHelpers";import { Controls } from "./components/Controls";import { CustomEdge } from "./components/CustomEdge";import { CustomNode } from "./components/CustomNode";-import { parseGraph } from "./parser";-import { themes } from "./theme";import type { CanvasThemeMode, GraphData, LayoutDirection, NodeData } from "./types";const layoutOptions = {@@ -20,50 +41,56 @@ const layoutOptions = {"elk.spacing.edgeLabel": "15",};-const objectJsonCache = new WeakMap<object, string>();-+/** Imperative handle exposed via the component ref for viewport control. */export interface JSONCrackRef {+ /** Nudge the current zoom factor up by one step while keeping center fixed. */zoomIn: () => void;+ /** Nudge the current zoom factor down by one step while keeping center fixed. */zoomOut: () => void;+ /** Set an absolute zoom factor at the current viewport center. */setZoom: (zoomFactor: number) => void;+ /** Fit-to-center the full graph inside the viewport. */centerView: () => void;+ /** Center and zoom on the root node of the graph. */focusFirstNode: () => void;}+/** Props accepted by the `JSONCrack` component. */export interface JSONCrackProps {- json: string | object | unknown[];+ /** JSON to visualize. Accepts a string or plain object. */+ json: JsonInput;+ /** Color theme applied to the canvas and nodes. Defaults to `dark`. */theme?: CanvasThemeMode;+ /** ELK layout direction for node placement. Defaults to `RIGHT`. */layoutDirection?: LayoutDirection;+ /** Whether to render the built-in zoom/focus control overlay. Defaults to `true`. */showControls?: boolean;+ /** Whether to draw the background grid. Defaults to `true`. */showGrid?: boolean;+ /** Treat two-finger trackpad gestures as touch (pinch-zoom, etc). Defaults to `false`. */trackpadZoom?: boolean;+ /** Auto fit-to-center after each ELK layout pass. Defaults to `true`. */centerOnLayout?: boolean;+ /** Hard cap on renderable nodes; exceeding it triggers the limit overlay. Defaults to `1500`. */maxRenderableNodes?: number;+ /** Additional class name appended to the canvas wrapper. */className?: string;- style?: React.CSSProperties;+ /** Additional inline style merged onto the canvas wrapper. */+ style?: CSSProperties;+ /** Called when a node is clicked. */onNodeClick?: (node: NodeData) => void;+ /** Called with parsed `nodes`/`edges` after each successful parse. */onParse?: (graph: GraphData) => void;+ /** Called with any error thrown during JSON parsing or graph construction. */onParseError?: (error: Error) => void;+ /** Called once the internal `ViewPort` is created, before the first render. */onViewportCreate?: (viewPort: ViewPort) => void;- renderNodeLimitExceeded?: (nodeCount: number, maxRenderableNodes: number) => React.ReactNode;+ /** Custom renderer shown when the graph exceeds `maxRenderableNodes`. */+ renderNodeLimitExceeded?: (nodeCount: number, maxRenderableNodes: number) => ReactNode;}-const toJsonText = (json: JSONCrackProps["json"]): string => {- if (typeof json === "string") return json;-- if (json && typeof json === "object") {- const cached = objectJsonCache.get(json);- if (cached) return cached;-- const serialized = JSON.stringify(json, null, 2);- objectJsonCache.set(json, serialized);- return serialized;- }-- return JSON.stringify(json, null, 2);-};--export const JSONCrack = React.forwardRef<JSONCrackRef, JSONCrackProps>(+/** Interactive JSON-to-graph visualization. Forwards a `JSONCrackRef` for imperative viewport control. */+export const JSONCrack = forwardRef<JSONCrackRef, JSONCrackProps>(({json,@@ -84,254 +111,184 @@ export const JSONCrack = React.forwardRef<JSONCrackRef, JSONCrackProps>(},ref) => {- const themeTokens = themes[theme];- const containerRef = React.useRef<HTMLDivElement | null>(null);- const [viewPort, setViewPort] = React.useState<ViewPort | null>(null);- const [nodes, setNodes] = React.useState<GraphData["nodes"]>([]);- const [edges, setEdges] = React.useState<GraphData["edges"]>([]);- const [loading, setLoading] = React.useState(true);- const [aboveSupportedLimit, setAboveSupportedLimit] = React.useState(false);- const [totalNodes, setTotalNodes] = React.useState(0);- const [paneWidth, setPaneWidth] = React.useState(2000);- const [paneHeight, setPaneHeight] = React.useState(2000);- const hasAutoFittedRef = React.useRef(false);- const previousLayoutAreaRef = React.useRef<number | null>(null);- const callbacksRef = React.useRef({ onParse, onParseError });- const onViewportCreateRef = React.useRef(onViewportCreate);- const lastParsedInputRef = React.useRef<{- jsonText: string;- maxRenderableNodes: number;- } | null>(null);-- React.useEffect(() => {+ const containerRef = useRef<HTMLDivElement | null>(null);+ const [viewPort, setViewPort] = useState<ViewPort | null>(null);+ const [nodes, setNodes] = useState<GraphData["nodes"]>([]);+ const [edges, setEdges] = useState<GraphData["edges"]>([]);+ const [loading, setLoading] = useState(true);+ const [initialFitDone, setInitialFitDone] = useState(false);+ const [aboveSupportedLimit, setAboveSupportedLimit] = useState(false);+ const [totalNodes, setTotalNodes] = useState(0);+ const [paneWidth, setPaneWidth] = useState(2000);+ const [paneHeight, setPaneHeight] = useState(2000);+ const layoutSizeRef = useRef<{ width: number; height: number } | null>(null);++ // Ref-mirror consumer callbacks so the parse effect / onCreate callbacks can read the latest without re-running.+ const callbacksRef = useRef({ onParse, onParseError });+ const onViewportCreateRef = useRef(onViewportCreate);+ useEffect(() => {callbacksRef.current = { onParse, onParseError };}, [onParse, onParseError]);-- React.useEffect(() => {+ useEffect(() => {onViewportCreateRef.current = onViewportCreate;}, [onViewportCreate]);- React.useEffect(() => {- hasAutoFittedRef.current = false;- previousLayoutAreaRef.current = null;- }, [layoutDirection]);+ // Memoize the class/style so reaflow doesn't see a new style object every render.+ const canvasClassName = useMemo(+ () => buildCanvasClassName(showGrid, className),+ [showGrid, className]+ );+ const canvasStyle = useMemo(() => buildCanvasStyle(theme, style), [theme, style]);- const centerView = React.useCallback(() => {- const nextViewPort = viewPort;- nextViewPort?.updateContainerSize();+ // Normalize `json` to a string once per reference. Memoized so the parse effect can depend on a primitive.+ const jsonText = useMemo(() => toJsonText(json), [json]);- const canvas = containerRef.current?.querySelector(".jsoncrack-canvas") as HTMLElement | null;- if (canvas) {- nextViewPort?.camera?.centerFitElementIntoView(canvas);- }- }, [viewPort]);-- const focusFirstNode = React.useCallback(() => {- const rootNode = containerRef.current?.querySelector("g[id$='node-1']") as HTMLElement | null;- if (!rootNode) return;+ // Parse → dispatch to React state. The pure helper keeps the effect body tiny.+ useEffect(() => {+ setLoading(true);+ setInitialFitDone(false);+ const result = parseJsonGraph(jsonText, maxRenderableNodes);- viewPort?.camera?.centerFitElementIntoView(rootNode, {- elementExtraMarginForZoom: 100,- });- }, [viewPort]);+ if (result.kind === "error") {+ setNodes([]);+ setEdges([]);+ setLoading(false);+ callbacksRef.current.onParseError?.(result.error);+ return;+ }- const setZoom = React.useCallback(- (zoomFactor: number) => {- if (!viewPort) return;- viewPort.camera?.recenter(viewPort.centerX, viewPort.centerY, zoomFactor);- },- [viewPort]- );+ if (result.kind === "above-limit") {+ setTotalNodes(result.total);+ setAboveSupportedLimit(true);+ setNodes([]);+ setEdges([]);+ setLoading(false);+ return;+ }- const zoomIn = React.useCallback(() => {+ const { graph, syntaxErrorCount } = result;+ if (syntaxErrorCount > 0) {+ callbacksRef.current.onParseError?.(+ new Error(`Failed to parse data (${syntaxErrorCount} syntax error(s)).`)+ );+ }+ setTotalNodes(graph.nodes.length);+ setAboveSupportedLimit(false);+ setNodes(graph.nodes);+ setEdges(graph.edges);+ callbacksRef.current.onParse?.({ nodes: graph.nodes, edges: graph.edges });+ if (graph.nodes.length === 0) setLoading(false);+ }, [jsonText, maxRenderableNodes]);++ // Keep the viewport in sync with container resizes — react-zoomable-ui snapshots dimensions at creation and does not re-measure on its own.+ useEffect(() => {if (!viewPort) return;- viewPort.camera?.recenter(viewPort.centerX, viewPort.centerY, viewPort.zoomFactor + 0.1);- }, [viewPort]);+ const container = containerRef.current;+ if (!container || typeof ResizeObserver === "undefined") return;- const zoomOut = React.useCallback(() => {- if (!viewPort) return;- viewPort.camera?.recenter(viewPort.centerX, viewPort.centerY, viewPort.zoomFactor - 0.1);+ const observer = new ResizeObserver(() => {+ if (container.clientWidth === 0 || container.clientHeight === 0) return;+ viewPort.updateContainerSize();+ });++ observer.observe(container);+ return () => observer.disconnect();}, [viewPort]);- React.useImperativeHandle(- ref,+ // Unified viewport API: all five methods only need `viewPort`, so build them together and expose the same object to both the imperative handle and the built-in Controls.+ const viewPortApi = useMemo<JSONCrackRef>(() => ({- zoomIn,- zoomOut,- setZoom,- centerView,- focusFirstNode,+ zoomIn: () => adjustViewPortZoom(viewPort, 0.1),+ zoomOut: () => adjustViewPortZoom(viewPort, -0.1),+ setZoom: zoomFactor => setViewPortZoom(viewPort, zoomFactor),+ centerView: () => fitGraphToViewPort(viewPort, containerRef.current, layoutSizeRef.current),+ focusFirstNode: () => focusRootNode(viewPort, containerRef.current),}),- [centerView, focusFirstNode, setZoom, zoomIn, zoomOut]+ [viewPort]);+ useImperativeHandle(ref, () => viewPortApi, [viewPortApi]);- React.useEffect(() => {- try {- const jsonText = toJsonText(json);- const lastParsedInput = lastParsedInputRef.current;-- if (- lastParsedInput &&- lastParsedInput.jsonText === jsonText &&- lastParsedInput.maxRenderableNodes === maxRenderableNodes- ) {- return;- }-- setLoading(true);+ const edgeTargetById = useMemo(() => buildEdgeTargetMap(edges), [edges]);- const graph = parseGraph(jsonText);-- if (graph.errors.length > 0) {- callbacksRef.current.onParseError?.(- new Error(`Failed to parse data (${graph.errors.length} syntax error(s)).`)- );- }-- setTotalNodes(graph.nodes.length);-- if (graph.nodes.length > maxRenderableNodes) {- setAboveSupportedLimit(true);- setNodes([]);- setEdges([]);- setLoading(false);- lastParsedInputRef.current = {- jsonText,- maxRenderableNodes,- };- return;- }-- setAboveSupportedLimit(false);- setNodes(graph.nodes);- setEdges(graph.edges);- callbacksRef.current.onParse?.({- nodes: graph.nodes,- edges: graph.edges,- });- lastParsedInputRef.current = {- jsonText,- maxRenderableNodes,- };-- if (graph.nodes.length === 0) {- setLoading(false);- }- } catch (error) {- setNodes([]);- setEdges([]);+ const onLayoutChange = useCallback((layout: ElkRoot) => {+ if (!layout.width || !layout.height) {setLoading(false);- callbacksRef.current.onParseError?.(- error instanceof Error ? error : new Error("Unable to parse data.")- );+ return;}- }, [json, maxRenderableNodes]);- const edgeTargetById = React.useMemo(() => {- const targetById = new Map<string, string>();+ layoutSizeRef.current = { width: layout.width, height: layout.height };+ setPaneWidth(layout.width + 50);+ setPaneHeight(layout.height + 50);+ setLoading(false);+ }, []);- for (let i = 0; i < edges.length; i += 1) {- const edge = edges[i];- targetById.set(edge.id, edge.to);+ // Auto-fit on initial load / new data. Gated on `paneWidth`/`paneHeight`+ // as deps: `onLayoutChange` batches the pane-size state updates with+ // `setLoading(false)` in the same commit, so by the time this effect+ // runs the svg has its final width/height attributes and reaflow has+ // finished reconciling. A single rAF then lets paint catch up before+ // measurement.+ useEffect(() => {+ if (initialFitDone) return;+ if (!centerOnLayout) {+ setInitialFitDone(true);+ return;}-- return targetById;- }, [edges]);-- const onLayoutChange = React.useCallback(- (layout: ElkRoot) => {- if (!layout.width || !layout.height) {- setLoading(false);- return;- }-- const currentLayoutArea = layout.width * layout.height;- const previousLayoutArea = previousLayoutAreaRef.current;- previousLayoutAreaRef.current = currentLayoutArea;-- setPaneWidth(layout.width + 50);- setPaneHeight(layout.height + 50);-- setTimeout(() => {- window.requestAnimationFrame(() => {- const isFirstAutoFit = !hasAutoFittedRef.current;- const hasLargeLayoutChange =- previousLayoutArea !== null &&- previousLayoutArea > 0 &&- Math.abs((currentLayoutArea * 100) / previousLayoutArea - 100) > 70;- const shouldAutoFit = centerOnLayout && (isFirstAutoFit || hasLargeLayoutChange);-- if (shouldAutoFit) {- centerView();- hasAutoFittedRef.current = true;- }-- setLoading(false);- });- }, 0);- },- [centerView, centerOnLayout]+ if (!viewPort || nodes.length === 0 || loading) return;+ if (!layoutSizeRef.current) return;++ let cancelled = false;+ const rafId = window.requestAnimationFrame(() => {+ if (cancelled) return;+ fitGraphToViewPort(viewPort, containerRef.current, layoutSizeRef.current);+ setInitialFitDone(true);+ });+ return () => {+ cancelled = true;+ window.cancelAnimationFrame(rafId);+ };+ }, [viewPort, nodes, loading, centerOnLayout, initialFitDone, paneWidth, paneHeight]);++ // Stable render factories so reaflow doesn't re-key nodes/edges on every parent render.+ const renderNode = useCallback(+ (nodeProps: NodeProps) => <CustomNode {...nodeProps} onNodeClick={onNodeClick} />,+ [onNodeClick]+ );+ const renderEdge = useCallback(+ (edgeProps: EdgeProps) => (+ <CustomEdge+ {...edgeProps}+ viewPort={viewPort}+ edgeTargetById={edgeTargetById}+ hostElement={containerRef.current}+ />+ ),+ [viewPort, edgeTargetById]);- const onLongPress = React.useCallback(() => {- const canvas = containerRef.current?.querySelector(".jsoncrack-canvas") as HTMLElement | null;- canvas?.classList.add("dragging");- }, []);-- const bindLongPress = useLongPress(onLongPress, {+ const bindLongPress = useLongPress(() => setCanvasDragging(containerRef.current, true), {threshold: 150,- onFinish: () => {- const canvas = containerRef.current?.querySelector(- ".jsoncrack-canvas"- ) as HTMLElement | null;- canvas?.classList.remove("dragging");- },+ onFinish: () => setCanvasDragging(containerRef.current, false),});const tooLargeContent = renderNodeLimitExceeded?.(totalNodes, maxRenderableNodes);- const canvasClassName = [styles.canvasWrapper, showGrid ? styles.showGrid : "", className]- .filter(Boolean)- .join(" ");- const canvasStyle = {- "--bg-color": themeTokens.GRID_BG_COLOR,- "--line-color-1": themeTokens.GRID_COLOR_PRIMARY,- "--line-color-2": themeTokens.GRID_COLOR_SECONDARY,- "--edge-stroke": theme === "dark" ? "#444444" : "#BCBEC0",- "--node-fill": theme === "dark" ? "#292929" : "#ffffff",- "--node-stroke": theme === "dark" ? "#424242" : "#BCBEC0",- "--interactive-normal": themeTokens.INTERACTIVE_NORMAL,- "--background-node": themeTokens.BACKGROUND_NODE,- "--node-text": themeTokens.NODE_COLORS.TEXT,- "--node-key": themeTokens.NODE_COLORS.NODE_KEY,- "--node-value": themeTokens.NODE_COLORS.NODE_VALUE,- "--node-integer": themeTokens.NODE_COLORS.INTEGER,- "--node-null": themeTokens.NODE_COLORS.NULL,- "--node-bool-true": themeTokens.NODE_COLORS.BOOL.TRUE,- "--node-bool-false": themeTokens.NODE_COLORS.BOOL.FALSE,- "--node-child-count": themeTokens.NODE_COLORS.CHILD_COUNT,- "--node-divider": themeTokens.NODE_COLORS.DIVIDER,- "--text-positive": themeTokens.TEXT_POSITIVE,- "--background-modifier-accent": themeTokens.BACKGROUND_MODIFIER_ACCENT,- "--spinner-track": theme === "dark" ? "rgba(255, 255, 255, 0.3)" : "rgba(17, 24, 39, 0.2)",- "--spinner-head": theme === "dark" ? "#FFFFFF" : "#111827",- "--overlay-bg": theme === "dark" ? "rgba(0, 0, 0, 0.2)" : "rgba(255, 255, 255, 0.38)",- ...style,- } as React.CSSProperties;return (<divref={containerRef}className={canvasClassName}style={canvasStyle}+ role="img"+ aria-label="JSON data visualization"onContextMenu={event => event.preventDefault()}{...bindLongPress()}>{showControls && (<Controls- onFocusRoot={focusFirstNode}- onCenterView={centerView}- onZoomOut={zoomOut}- onZoomIn={zoomIn}+ onFocusRoot={viewPortApi.focusFirstNode}+ onCenterView={viewPortApi.centerView}+ onZoomOut={viewPortApi.zoomOut}+ onZoomIn={viewPortApi.zoomIn}/>)}@@ -357,21 +314,14 @@ export const JSONCrack = React.forwardRef<JSONCrackRef, JSONCrackProps>(}}onContextMenu={event => event.preventDefault()}treatTwoFingerTrackPadGesturesLikeTouch={trackpadZoom}- pollForElementResizingclassName="jsoncrack-space"+ style={{ opacity: initialFitDone ? 1 : 0, transition: "opacity 120ms" }}><CanvasclassName="jsoncrack-canvas"onLayoutChange={onLayoutChange}- node={nodeProps => <CustomNode {...nodeProps} onNodeClick={onNodeClick} />}- edge={edgeProps => (- <CustomEdge- {...edgeProps}- viewPort={viewPort}- edgeTargetById={edgeTargetById}- hostElement={containerRef.current}- />- )}+ node={renderNode}+ edge={renderEdge}nodes={nodes}edges={edges}arrow={null}@@ -388,7 +338,17 @@ export const JSONCrack = React.forwardRef<JSONCrackRef, JSONCrackProps>(readonlydragEdge={null}dragNode={null}- fit+ // Disable reaflow's built-in auto-centering of content inside the+ // pane. The default is `CanvasPosition.CENTER`, which translates+ // the content group by `(pane - layout) / 2` on every layout+ // pass. That plays poorly with our own fit-to-viewport logic:+ // at fit time the content is offset by the centering transform+ // inside a 2000×2000 default pane, so our measured client rect+ // lands hundreds of pixels below the container top, and the fit+ // computes a zoom/center based on that offset. Passing a nullish+ // `defaultPosition` makes reaflow leave the group at the svg+ // origin so our rect math matches reality.+ defaultPosition={null as unknown as undefined}/></Space></div>diff --git a/packages/jsoncrack-react/src/JSONCrackStyles.module.css b/packages/jsoncrack-react/src/JSONCrackStyles.module.cssindex ef3354b3..ac48c16b 100644--- a/packages/jsoncrack-react/src/JSONCrackStyles.module.css+++ b/packages/jsoncrack-react/src/JSONCrackStyles.module.css@@ -38,6 +38,8 @@.canvasWrapper :global(text) {fill: var(--interactive-normal) !important;+ font-family:+ -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif !important;}.canvasWrapper :global(rect) {diff --git a/packages/jsoncrack-react/src/__tests__/canvasHelpers.test.ts b/packages/jsoncrack-react/src/__tests__/canvasHelpers.test.tsnew file mode 100644index 00000000..2fa6253d--- /dev/null+++ b/packages/jsoncrack-react/src/__tests__/canvasHelpers.test.ts@@ -0,0 +1,145 @@+import { describe, expect, it } from "vitest";+import {+ buildCanvasClassName,+ buildCanvasStyle,+ buildEdgeTargetMap,+ parseJsonGraph,+ toJsonText,+} from "../canvasHelpers";++describe("toJsonText", () => {+ it("returns strings as-is without re-stringifying", () => {+ const raw = '{"hello":"world"}';+ expect(toJsonText(raw)).toBe(raw);+ });++ it("serializes objects with 2-space indentation", () => {+ expect(toJsonText({ a: 1 })).toBe('{\n "a": 1\n}');+ });++ it("serializes arrays", () => {+ expect(toJsonText([1, 2, 3])).toBe("[\n 1,\n 2,\n 3\n]");+ });++ it("memoizes results per object reference", () => {+ const obj = { name: "Apple" };+ const first = toJsonText(obj);+ const second = toJsonText(obj);+ // Exact reference equality proves the WeakMap cache is hit.+ expect(second).toBe(first);+ });++ it("does not memoize across different object references with equal contents", () => {+ // Different references, same contents → both compute and produce equal+ // strings, but the cache does not conflate them.+ const a = toJsonText({ x: 1 });+ const b = toJsonText({ x: 1 });+ expect(a).toBe(b);+ });+});++describe("parseJsonGraph", () => {+ it("returns kind: 'ok' with graph and zero syntax errors for valid JSON", () => {+ const result = parseJsonGraph('{"a":1}', 1500);+ expect(result.kind).toBe("ok");+ if (result.kind !== "ok") return;+ expect(result.syntaxErrorCount).toBe(0);+ expect(result.graph.nodes.length).toBeGreaterThan(0);+ });++ it("returns kind: 'ok' with a non-zero syntaxErrorCount for partially-broken JSON", () => {+ const result = parseJsonGraph('{"broken": }', 1500);+ expect(result.kind).toBe("ok");+ if (result.kind !== "ok") return;+ expect(result.syntaxErrorCount).toBeGreaterThan(0);+ });++ it("returns kind: 'above-limit' with total count when over the node cap", () => {+ const big = { items: Array.from({ length: 10 }, (_, i) => ({ id: i })) };+ const result = parseJsonGraph(JSON.stringify(big), 3);+ expect(result.kind).toBe("above-limit");+ if (result.kind !== "above-limit") return;+ expect(result.total).toBeGreaterThan(3);+ });++ // NOTE: the `kind: "error"` branch is only reached on unexpected internal+ // exceptions in `parseGraph` — jsonc-parser is error-tolerant, so there is+ // no user-reachable JSON input that triggers it. Kept as a safety net in+ // the implementation, intentionally untested here.+});++describe("buildCanvasClassName", () => {+ it("includes the base wrapper class", () => {+ expect(buildCanvasClassName(false, undefined)).toContain("canvasWrapper");+ });++ it("adds the showGrid class when enabled", () => {+ const className = buildCanvasClassName(true, undefined);+ expect(className).toContain("showGrid");+ });++ it("omits the showGrid class when disabled", () => {+ const className = buildCanvasClassName(false, undefined);+ expect(className).not.toContain("showGrid");+ });++ it("appends caller-provided class names", () => {+ expect(buildCanvasClassName(false, "my-custom")).toContain("my-custom");+ });++ it("strips empty entries so undefined is safe", () => {+ const className = buildCanvasClassName(false, undefined);+ expect(className).not.toContain("undefined");+ expect(className.split(" ").every(part => part.length > 0)).toBe(true);+ });+});++describe("buildCanvasStyle", () => {+ it("projects all required theme CSS custom properties", () => {+ const style = buildCanvasStyle("dark", undefined) as Record<string, string>;+ // Spot-check a few that the component + stylesheets rely on. If any are+ // dropped from the helper they'd silently de-theme the graph.+ expect(style["--bg-color"]).toBeDefined();+ expect(style["--node-fill"]).toBeDefined();+ expect(style["--node-key"]).toBeDefined();+ expect(style["--node-value"]).toBeDefined();+ expect(style["--edge-stroke"]).toBeDefined();+ expect(style["--spinner-head"]).toBeDefined();+ expect(style["--overlay-bg"]).toBeDefined();+ });++ it("applies different colors for dark vs light themes", () => {+ const dark = buildCanvasStyle("dark", undefined) as Record<string, string>;+ const light = buildCanvasStyle("light", undefined) as Record<string, string>;+ expect(dark["--node-fill"]).not.toBe(light["--node-fill"]);+ });++ it("merges caller-provided styles on top of theme tokens", () => {+ const style = buildCanvasStyle("dark", { color: "red", "--bg-color": "blue" } as Record<+ string,+ string+ >) as Record<string, string>;+ expect(style.color).toBe("red");+ // Caller override wins over theme default.+ expect(style["--bg-color"]).toBe("blue");+ });+});++describe("buildEdgeTargetMap", () => {+ it("builds an id → target map for edge lookups", () => {+ const edges = [+ { id: "e1", from: "1", to: "2", text: "" },+ { id: "e2", from: "1", to: "3", text: "" },+ { id: "e3", from: "2", to: "4", text: "" },+ ];+ const map = buildEdgeTargetMap(edges);+ expect(map.size).toBe(3);+ expect(map.get("e1")).toBe("2");+ expect(map.get("e2")).toBe("3");+ expect(map.get("e3")).toBe("4");+ });++ it("returns an empty map for empty input", () => {+ expect(buildEdgeTargetMap([]).size).toBe(0);+ });+});diff --git a/packages/jsoncrack-react/src/__tests__/parser.test.ts b/packages/jsoncrack-react/src/__tests__/parser.test.tsnew file mode 100644index 00000000..61e8cb29--- /dev/null+++ b/packages/jsoncrack-react/src/__tests__/parser.test.ts@@ -0,0 +1,118 @@+import { describe, expect, it } from "vitest";+import { parseGraph } from "../parser";++describe("parseGraph", () => {+ it("returns empty graph for empty string", () => {+ const result = parseGraph("");+ expect(result.nodes).toEqual([]);+ expect(result.edges).toEqual([]);+ });++ it("parses a primitive into a single node with no edges", () => {+ const result = parseGraph('"hello"');+ expect(result.nodes).toHaveLength(1);+ expect(result.edges).toEqual([]);+ expect(result.nodes[0].text).toEqual([{ key: null, value: "hello", type: "string" }]);+ });++ it("parses a flat object into one node with typed rows and no edges", () => {+ const result = parseGraph('{"name":"Apple","count":3,"active":true,"tag":null}');+ expect(result.nodes).toHaveLength(1);+ expect(result.edges).toEqual([]);++ const rows = result.nodes[0].text;+ expect(rows).toEqual([+ { key: "name", value: "Apple", type: "string" },+ { key: "count", value: 3, type: "number" },+ { key: "active", value: true, type: "boolean" },+ { key: "tag", value: null, type: "null" },+ ]);+ });++ it("creates a child node and edge for a nested object", () => {+ const result = parseGraph('{"user":{"name":"Ada"}}');+ expect(result.nodes).toHaveLength(2);+ expect(result.edges).toHaveLength(1);++ const byId = new Map(result.nodes.map(n => [n.id, n]));+ const edge = result.edges[0];+ expect(byId.has(edge.from)).toBe(true);+ expect(byId.has(edge.to)).toBe(true);+ expect(edge.text).toBe("user");+ expect(byId.get(edge.to)?.text).toEqual([{ key: "name", value: "Ada", type: "string" }]);+ });++ it("creates one child node per array element with one edge each", () => {+ const result = parseGraph('{"fruits":["apple","banana","cherry"]}');+ // 1 root node + 3 array children = 4 nodes+ expect(result.nodes).toHaveLength(4);+ expect(result.edges).toHaveLength(3);++ const byId = new Map(result.nodes.map(n => [n.id, n]));+ // The parser pushes nodes in post-order (children before parent), so we+ // identify the root as the one not referenced by any edge's `to`.+ const targetIds = new Set(result.edges.map(e => e.to));+ const root = result.nodes.find(n => !targetIds.has(n.id));+ expect(root).toBeDefined();+ const rootId = root!.id;++ result.edges.forEach(edge => {+ expect(edge.from).toBe(rootId);+ expect(edge.text).toBe("fruits");+ });++ const childValues = result.edges.map(e => byId.get(e.to)?.text[0].value);+ expect(childValues).toEqual(["apple", "banana", "cherry"]);+ });++ it("renders a top-level array as a parent node with one child per element", () => {+ const result = parseGraph("[1,2,3]");+ expect(result.nodes).toHaveLength(4);+ expect(result.edges).toHaveLength(3);++ const targetIds = new Set(result.edges.map(e => e.to));+ const root = result.nodes.find(n => !targetIds.has(n.id));+ expect(root).toBeDefined();+ expect(root!.text[0]).toMatchObject({+ key: null,+ type: "array",+ childrenCount: 3,+ value: "[3 items]",+ });++ const byId = new Map(result.nodes.map(n => [n.id, n]));+ const childValues = result.edges.map(e => byId.get(e.to)?.text[0].value).sort();+ expect(childValues).toEqual([1, 2, 3]);+ });++ it("handles deeply nested structures", () => {+ const result = parseGraph('{"a":{"b":{"c":{"d":1}}}}');+ // 4 nested object nodes = 4 nodes, 3 edges+ expect(result.nodes).toHaveLength(4);+ expect(result.edges).toHaveLength(3);+ });++ it("reports parse errors but still returns a partial graph", () => {+ const result = parseGraph('{"broken": }');+ expect(result.errors.length).toBeGreaterThan(0);+ // jsonc-parser is error-tolerant and still produces a tree+ expect(result.nodes.length).toBeGreaterThanOrEqual(0);+ });++ it("assigns unique ids to every node and edge", () => {+ const result = parseGraph('{"users":[{"id":1},{"id":2}]}');+ const nodeIds = new Set(result.nodes.map(n => n.id));+ const edgeIds = new Set(result.edges.map(e => e.id));+ expect(nodeIds.size).toBe(result.nodes.length);+ expect(edgeIds.size).toBe(result.edges.length);+ });++ it("emits edges with from/to pointing at existing node ids", () => {+ const result = parseGraph('{"a":{"b":1},"c":[2,3]}');+ const nodeIds = new Set(result.nodes.map(n => n.id));+ result.edges.forEach(edge => {+ expect(nodeIds.has(edge.from)).toBe(true);+ expect(nodeIds.has(edge.to)).toBe(true);+ });+ });+});diff --git a/packages/jsoncrack-react/src/canvasHelpers.ts b/packages/jsoncrack-react/src/canvasHelpers.tsnew file mode 100644index 00000000..8cfd20f0--- /dev/null+++ b/packages/jsoncrack-react/src/canvasHelpers.ts@@ -0,0 +1,260 @@+import type { CSSProperties } from "react";+import type { ViewPort } from "react-zoomable-ui";+import styles from "./JSONCrackStyles.module.css";+import { parseGraph } from "./parser";+import { themes } from "./theme";+import type { CanvasThemeMode, GraphData } from "./types";++export type JsonInput = string | object;++const objectJsonCache = new WeakMap<object, string>();++/** Normalize the `json` prop to a string, memoizing per object instance to avoid re-stringifying unchanged references. */+export const toJsonText = (json: JsonInput): string => {+ if (typeof json === "string") return json;++ if (json && typeof json === "object") {+ const cached = objectJsonCache.get(json);+ if (cached) return cached;++ const serialized = JSON.stringify(json, null, 2);+ objectJsonCache.set(json, serialized);+ return serialized;+ }++ return JSON.stringify(json, null, 2);+};++/** Compose the `className` applied to the canvas wrapper, stripping empty entries. */+export const buildCanvasClassName = (showGrid: boolean, userClassName?: string): string =>+ [styles.canvasWrapper, showGrid ? styles.showGrid : "", userClassName].filter(Boolean).join(" ");++/** Project theme tokens onto CSS custom properties for the canvas wrapper, merging any caller-provided style on top. */+export const buildCanvasStyle = (+ theme: CanvasThemeMode,+ userStyle?: CSSProperties+): CSSProperties => {+ const themeTokens = themes[theme];+ const isDark = theme === "dark";++ return {+ "--bg-color": themeTokens.GRID_BG_COLOR,+ "--line-color-1": themeTokens.GRID_COLOR_PRIMARY,+ "--line-color-2": themeTokens.GRID_COLOR_SECONDARY,+ "--edge-stroke": isDark ? "#444444" : "#BCBEC0",+ "--node-fill": isDark ? "#292929" : "#ffffff",+ "--node-stroke": isDark ? "#424242" : "#BCBEC0",+ "--interactive-normal": themeTokens.INTERACTIVE_NORMAL,+ "--background-node": themeTokens.BACKGROUND_NODE,+ "--node-text": themeTokens.NODE_COLORS.TEXT,+ "--node-key": themeTokens.NODE_COLORS.NODE_KEY,+ "--node-value": themeTokens.NODE_COLORS.NODE_VALUE,+ "--node-integer": themeTokens.NODE_COLORS.INTEGER,+ "--node-null": themeTokens.NODE_COLORS.NULL,+ "--node-bool-true": themeTokens.NODE_COLORS.BOOL.TRUE,+ "--node-bool-false": themeTokens.NODE_COLORS.BOOL.FALSE,+ "--node-child-count": themeTokens.NODE_COLORS.CHILD_COUNT,+ "--node-divider": themeTokens.NODE_COLORS.DIVIDER,+ "--text-positive": themeTokens.TEXT_POSITIVE,+ "--background-modifier-accent": themeTokens.BACKGROUND_MODIFIER_ACCENT,+ "--spinner-track": isDark ? "rgba(255, 255, 255, 0.3)" : "rgba(17, 24, 39, 0.2)",+ "--spinner-head": isDark ? "#FFFFFF" : "#111827",+ "--overlay-bg": isDark ? "rgba(0, 0, 0, 0.2)" : "rgba(255, 255, 255, 0.38)",+ ...userStyle,+ } as CSSProperties;+};++/** Discriminated result of parsing JSON text into a graph. */+export type ParseJsonGraphResult =+ | { kind: "ok"; graph: GraphData; syntaxErrorCount: number }+ | { kind: "above-limit"; total: number }+ | { kind: "error"; error: Error };++/** Parse a JSON text into a graph, returning a discriminated result instead of throwing or touching React state. */+export const parseJsonGraph = (+ jsonText: string,+ maxRenderableNodes: number+): ParseJsonGraphResult => {+ try {+ const graph = parseGraph(jsonText);+ if (graph.nodes.length > maxRenderableNodes) {+ return { kind: "above-limit", total: graph.nodes.length };+ }+ return { kind: "ok", graph, syntaxErrorCount: graph.errors.length };+ } catch (error) {+ return {+ kind: "error",+ error: error instanceof Error ? error : new Error("Unable to parse data."),+ };+ }+};++/** Build a map from edge id → target node id for O(1) lookups in edge renderers. */+export const buildEdgeTargetMap = (edges: GraphData["edges"]): Map<string, string> => {+ const targetById = new Map<string, string>();+ for (let i = 0; i < edges.length; i += 1) {+ const edge = edges[i];+ targetById.set(edge.id, edge.to);+ }+ return targetById;+};++/** Toggle reaflow's `dragging` class on the canvas div to suppress pointer events during long-press panning. */+export const setCanvasDragging = (container: HTMLElement | null, dragging: boolean): void => {+ const canvas = container?.querySelector(".jsoncrack-canvas") as HTMLElement | null;+ if (!canvas) return;+ canvas.classList.toggle("dragging", dragging);+};++/** Breathing room around the measured graph rect, expressed as a fraction of the rect's own dimensions. Using a fraction (instead of a fixed pixel value) is scale-invariant: whether we measure the graph at zoom 1 or at zoom 0.27, the padded rect expands by the same *proportion*, so translating through `translateClientRectToVirtualSpace` produces the same virtual rect regardless of current zoom. A fixed client-pixel padding would blow up in virtual space as zoom decreases and make manual Fit clicks land at a different zoom than the initial auto-fit. */+const GRAPH_FIT_PADDING_RATIO = 0.02;++/** Union the on-screen client rects of every reaflow-assigned leaf (`g[id]`) inside the content group. Measuring leaves instead of the motion wrapper avoids two measurement bugs: (a) `getBoundingClientRect()` on the outer motion `<g>` can under-report stroke extents when framer-motion's CSS transform is applied, and (b) curved edge paths can bulge past the straight-line endpoint box. Each reaflow node/edge is wrapped in a `g` with an id; their leaf rects are stroke-inclusive and collectively cover everything that actually paints. */+const unionContentGroupLeafRects = (+ contentGroup: SVGGElement+): { left: number; top: number; width: number; height: number } | null => {+ const leaves = contentGroup.querySelectorAll("g[id]");+ let left = Number.POSITIVE_INFINITY;+ let top = Number.POSITIVE_INFINITY;+ let right = Number.NEGATIVE_INFINITY;+ let bottom = Number.NEGATIVE_INFINITY;+ let found = false;++ for (let i = 0; i < leaves.length; i += 1) {+ const rect = leaves[i].getBoundingClientRect();+ if (rect.width <= 0 || rect.height <= 0) continue;+ if (rect.left < left) left = rect.left;+ if (rect.top < top) top = rect.top;+ if (rect.right > right) right = rect.right;+ if (rect.bottom > bottom) bottom = rect.bottom;+ found = true;+ }++ if (!found) return null;+ return { left, top, width: right - left, height: bottom - top };+};++/** Project a user-space rectangle through a DOMMatrix to an axis-aligned client-space rect. */+const projectRectThroughMatrix = (+ svg: SVGSVGElement,+ matrix: DOMMatrix,+ x: number,+ y: number,+ width: number,+ height: number+): { left: number; top: number; width: number; height: number } => {+ const origin = svg.createSVGPoint();+ origin.x = x;+ origin.y = y;+ const corner = svg.createSVGPoint();+ corner.x = x + width;+ corner.y = y + height;+ const a = origin.matrixTransform(matrix);+ const b = corner.matrixTransform(matrix);+ return {+ left: Math.min(a.x, b.x),+ top: Math.min(a.y, b.y),+ width: Math.abs(b.x - a.x),+ height: Math.abs(b.y - a.y),+ };+};++/** Derive the graph's on-screen client rect. Measurement cascade: (1) union of each direct child of the reaflow content group's client rect — ground truth for whatever is actually painted; (2) `getBoundingClientRect()` on the content group itself — accurate for most shapes but under-reports curved-edge bulges on some browsers; (3) `getBBox()` projected through the group's `getScreenCTM()` — layout-based, works through `visibility: hidden`; (4) ELK layout box through the svg CTM — last-resort fallback before layout has geometry. The result is inflated by {@link GRAPH_FIT_PADDING_RATIO} on each side. */+export const computeGraphClientRect = (+ container: HTMLElement | null,+ layoutSize: { width: number; height: number } | null+): DOMRect | null => {+ if (!container) return null;++ const svg = container.querySelector(".jsoncrack-canvas svg") as SVGSVGElement | null;+ if (!svg) return null;++ let raw: { left: number; top: number; width: number; height: number } | null = null;+ const contentGroup = svg.querySelector(":scope > g") as SVGGElement | null;++ if (contentGroup) {+ raw = unionContentGroupLeafRects(contentGroup);+ }++ if (!raw && contentGroup) {+ const rect = contentGroup.getBoundingClientRect();+ if (rect.width > 0 && rect.height > 0) {+ raw = { left: rect.left, top: rect.top, width: rect.width, height: rect.height };+ }+ }++ if (!raw && contentGroup && typeof contentGroup.getScreenCTM === "function") {+ try {+ const bbox = contentGroup.getBBox();+ const ctm = contentGroup.getScreenCTM();+ if (ctm && bbox.width > 0 && bbox.height > 0) {+ raw = projectRectThroughMatrix(svg, ctm, bbox.x, bbox.y, bbox.width, bbox.height);+ }+ } catch {+ // getBBox can throw on detached / display:none elements; fall through.+ }+ }++ if (+ !raw &&+ layoutSize &&+ layoutSize.width > 0 &&+ layoutSize.height > 0 &&+ typeof svg.getScreenCTM === "function"+ ) {+ const ctm = svg.getScreenCTM();+ if (ctm) {+ raw = projectRectThroughMatrix(svg, ctm, 0, 0, layoutSize.width, layoutSize.height);+ }+ }++ if (!raw || raw.width <= 0 || raw.height <= 0) return null;++ const padX = raw.width * GRAPH_FIT_PADDING_RATIO;+ const padY = raw.height * GRAPH_FIT_PADDING_RATIO;+ return DOMRect.fromRect({+ x: raw.left - padX,+ y: raw.top - padY,+ width: raw.width + padX * 2,+ height: raw.height + padY * 2,+ });+};++/** Fit-to-center the graph inside the viewport using the derived content rect. No-op if the rect can't be computed — the caller is expected to retry on the next render. */+export const fitGraphToViewPort = (+ viewPort: ViewPort | null,+ container: HTMLElement | null,+ layoutSize: { width: number; height: number } | null+): void => {+ if (!viewPort || !container) return;++ viewPort.updateContainerSize();++ const rect = computeGraphClientRect(container, layoutSize);+ if (!rect) return;++ const virtualRect = viewPort.translateClientRectToVirtualSpace(rect);+ viewPort.camera?.centerFitAreaIntoView(virtualRect);+};++/** Center and zoom on the graph's root node with a 100px breathing margin. */+export const focusRootNode = (viewPort: ViewPort | null, container: HTMLElement | null): void => {+ if (!viewPort || !container) return;+ const rootNode = container.querySelector("g[id$='node-1']") as HTMLElement | null;+ if (!rootNode) return;+ viewPort.camera?.centerFitElementIntoView(rootNode, {+ elementExtraMarginForZoom: 100,+ });+};++/** Recenter the camera at its current center with a new absolute zoom factor. */+export const setViewPortZoom = (viewPort: ViewPort | null, zoomFactor: number): void => {+ if (!viewPort) return;+ viewPort.camera?.recenter(viewPort.centerX, viewPort.centerY, zoomFactor);+};++/** Nudge the current zoom factor by `delta` while keeping the center fixed. */+export const adjustViewPortZoom = (viewPort: ViewPort | null, delta: number): void => {+ if (!viewPort) return;+ viewPort.camera?.recenter(viewPort.centerX, viewPort.centerY, viewPort.zoomFactor + delta);+};