✨ Innovative and open-source visualization application that transforms various data formats, such as JSON, YAML, XML and CSV into interactive graphs.
feat: move collapse/expand feature to jsoncrack-react package
AykutSarac16b1cd2c1c56
diff --git a/apps/www/src/features/editor/views/GraphView/Toolbar/index.tsx b/apps/www/src/features/editor/views/GraphView/Toolbar/index.tsxindex 9794dad3..118d4ca9 100644--- a/apps/www/src/features/editor/views/GraphView/Toolbar/index.tsx+++ b/apps/www/src/features/editor/views/GraphView/Toolbar/index.tsx@@ -18,7 +18,6 @@ import {import { MdFullscreen, MdOutlineCenterFocusStrong } from "react-icons/md";import { TbArrowsLeftRight } from "react-icons/tb";import useConfig from "../../../../../store/useConfig";-import useJson from "../../../../../store/useJson";import { useModal } from "../../../../../store/useModal";import { SearchInput } from "../../../Toolbar/SearchInput";import useGraph from "../stores/useGraph";@@ -99,10 +98,9 @@ export const Toolbar = () => {const focusFirstNode = useGraph(state => state.focusFirstNode);const direction = useGraph(state => state.direction);const setDirection = useGraph(state => state.setDirection);- const collapsedPaths = useGraph(state => state.collapsedPaths);+ const collapsedCount = useGraph(state => state.collapsedCount);const expandAll = useGraph(state => state.expandAll);- const collapseAllDepth1 = useGraph(state => state.collapseAllDepth1);- const json = useJson(state => state.json);+ const collapseAll = useGraph(state => state.collapseAll);const setVisible = useModal(state => state.setVisible);const darkmodeEnabled = useConfig(state => state.darkmodeEnabled);const toggleDarkMode = useConfig(state => state.toggleDarkMode);@@ -253,32 +251,28 @@ export const Toolbar = () => {</Tooltip><Tooltip- label={- collapsedPaths.length > 0- ? `Expand all (${collapsedPaths.length} collapsed)`- : "Collapse all"- }+ label={collapsedCount > 0 ? `Expand all (${collapsedCount} collapsed)` : "Collapse all"}position="top"withArrowopenDelay={750}><ActionIcon- aria-label={collapsedPaths.length > 0 ? "expand all" : "collapse all"}+ aria-label={collapsedCount > 0 ? "expand all" : "collapse all"}size="lg"radius="md"variant="subtle"color="gray"onClick={() => {- if (collapsedPaths.length > 0) {+ if (collapsedCount > 0) {expandAll();gaEvent("expand_all");} else {- collapseAllDepth1(json);+ collapseAll();gaEvent("collapse_all");}}}>- {collapsedPaths.length > 0 ? <LuCopyPlus size={18} /> : <LuCopyMinus size={18} />}+ {collapsedCount > 0 ? <LuCopyPlus size={18} /> : <LuCopyMinus size={18} />}</ActionIcon></Tooltip>diff --git a/apps/www/src/features/editor/views/GraphView/index.tsx b/apps/www/src/features/editor/views/GraphView/index.tsxindex 97b99f8c..cf4af9e6 100644--- a/apps/www/src/features/editor/views/GraphView/index.tsx+++ b/apps/www/src/features/editor/views/GraphView/index.tsx@@ -4,7 +4,6 @@ import styled from "styled-components";import { JSONCrack } from "jsoncrack-react";import type { JSONCrackRef, NodeData } from "jsoncrack-react";import { SUPPORTED_LIMIT } from "../../../../constants/graph";-import { pruneInvalidPaths } from "../../../../lib/utils/collapse";import useConfig from "../../../../store/useConfig";import useJson from "../../../../store/useJson";import { useModal } from "../../../../store/useModal";@@ -53,9 +52,7 @@ export const GraphView = ({ isWidget = false }: GraphProps) => {const setJsonCrackRef = useGraph(state => state.setJsonCrackRef);const direction = useGraph(state => state.direction);const setSelectedNode = useGraph(state => state.setSelectedNode);- const collapsedPaths = useGraph(state => state.collapsedPaths);- const toggleCollapse = useGraph(state => state.toggleCollapse);- const setCollapsedPaths = useGraph(state => state.setCollapsedPaths);+ const setCollapsedCount = useGraph(state => state.setCollapsedCount);const gesturesEnabled = useConfig(state => state.gesturesEnabled);const rulersEnabled = useConfig(state => state.rulersEnabled);const darkmodeEnabled = useConfig(state => state.darkmodeEnabled);@@ -67,11 +64,10 @@ export const GraphView = ({ isWidget = false }: GraphProps) => {setJsonCrackRef(jsonCrackRef);}, [setJsonCrackRef]);- React.useEffect(() => {- if (!collapsedPaths.length) return;- const pruned = pruneInvalidPaths(json, collapsedPaths);- if (pruned.length !== collapsedPaths.length) setCollapsedPaths(pruned);- }, [json, collapsedPaths, setCollapsedPaths]);+ const handleCollapseChange = React.useCallback(+ (paths: string[]) => setCollapsedCount(paths.length),+ [setCollapsedCount]+ );const blurOnClick = React.useCallback(() => {if ("activeElement" in document) {@@ -111,8 +107,7 @@ export const GraphView = ({ isWidget = false }: GraphProps) => {centerOnLayoutonViewportCreate={setViewPort}onNodeClick={handleNodeClick}- collapsedPaths={collapsedPaths}- onToggleCollapse={toggleCollapse}+ onCollapseChange={handleCollapseChange}renderNodeLimitExceeded={() => <NotSupported />}/></StyledEditorWrapper>diff --git a/apps/www/src/features/editor/views/GraphView/stores/useGraph.ts b/apps/www/src/features/editor/views/GraphView/stores/useGraph.tsindex 884fb29f..33823ec9 100644--- a/apps/www/src/features/editor/views/GraphView/stores/useGraph.ts+++ b/apps/www/src/features/editor/views/GraphView/stores/useGraph.ts@@ -1,18 +1,15 @@import type { RefObject } from "react";-import type { JSONPath } from "jsonc-parser";import type { LayoutDirection, NodeData, JSONCrackRef } from "jsoncrack-react";import type { ViewPort } from "react-zoomable-ui";import { create } from "zustand";-const pathKey = (path: JSONPath): string => JSON.stringify(path);-export interface Graph {viewPort: ViewPort | null;jsonCrackRef: RefObject<JSONCrackRef | null> | null;direction: LayoutDirection;fullscreen: boolean;selectedNode: NodeData | null;- collapsedPaths: string[];+ collapsedCount: number;}const initialStates: Graph = {@@ -21,7 +18,7 @@ const initialStates: Graph = {direction: "RIGHT",fullscreen: false,selectedNode: null,- collapsedPaths: [],+ collapsedCount: 0,};interface GraphActions {@@ -34,10 +31,9 @@ interface GraphActions {zoomIn: () => void;zoomOut: () => void;centerView: () => void;- toggleCollapse: (path: JSONPath) => void;- setCollapsedPaths: (paths: string[]) => void;expandAll: () => void;- collapseAllDepth1: (json: string) => void;+ collapseAll: () => void;+ setCollapsedCount: (count: number) => void;}const useGraph = create<Graph & GraphActions>((set, get) => ({@@ -59,42 +55,19 @@ const useGraph = create<Graph & GraphActions>((set, get) => ({centerView: () => {get().jsonCrackRef?.current?.centerView();},- toggleFullscreen: fullscreen => set({ fullscreen }),- setViewPort: viewPort => set({ viewPort }),- setJsonCrackRef: jsonCrackRef => set({ jsonCrackRef }),- toggleCollapse: path => {- const key = pathKey(path);- const current = get().collapsedPaths;- const next = current.includes(key) ? current.filter(p => p !== key) : [...current, key];- set({ collapsedPaths: next });+ expandAll: () => {+ get().jsonCrackRef?.current?.expandAll();},- setCollapsedPaths: paths => {- const prev = get().collapsedPaths;- if (prev.length === paths.length && prev.every((p, i) => p === paths[i])) return;- set({ collapsedPaths: paths });+ collapseAll: () => {+ get().jsonCrackRef?.current?.collapseAll();},- expandAll: () => set({ collapsedPaths: [] }),- collapseAllDepth1: json => {- try {- const parsed = JSON.parse(json);- if (!parsed || typeof parsed !== "object") return;- const keys = Array.isArray(parsed)- ? parsed.map((_, i) => i)- : Object.keys(parsed as Record<string, unknown>);- const paths: string[] = [];- for (const key of keys) {- const value = (parsed as Record<string | number, unknown>)[key as any];- if (value && typeof value === "object") {- if (Array.isArray(value) && value.length === 0) continue;- if (!Array.isArray(value) && Object.keys(value).length === 0) continue;- paths.push(pathKey([key]));- }- }- set({ collapsedPaths: paths });- } catch {- // ignore invalid JSON- }+ setCollapsedCount: count => {+ if (get().collapsedCount === count) return;+ set({ collapsedCount: count });},+ toggleFullscreen: fullscreen => set({ fullscreen }),+ setViewPort: viewPort => set({ viewPort }),+ setJsonCrackRef: jsonCrackRef => set({ jsonCrackRef }),}));export default useGraph;diff --git a/apps/www/src/lib/utils/collapse.ts b/apps/www/src/lib/utils/collapse.tsdeleted file mode 100644index a4bb9473..00000000--- a/apps/www/src/lib/utils/collapse.ts+++ /dev/null@@ -1,38 +0,0 @@-import type { JSONPath } from "jsonc-parser";--const resolveAtPath = (root: unknown, path: JSONPath): unknown => {- let current: unknown = root;- for (const segment of path) {- if (current == null || typeof current !== "object") return undefined;- current = (current as Record<string | number, unknown>)[segment as any];- }- return current;-};--/**- * Drop collapsed paths that no longer resolve to an object/array in the current JSON.- * Returns the input verbatim if the JSON cannot be parsed — we prefer to preserve- * user intent through a transient syntax error over nuking state.- */-export const pruneInvalidPaths = (json: string, paths: string[]): string[] => {- if (!paths.length) return paths;- let parsed: unknown;- try {- parsed = JSON.parse(json);- } catch {- return paths;- }-- const kept: string[] = [];- for (const serialized of paths) {- let path: JSONPath;- try {- path = JSON.parse(serialized) as JSONPath;- } catch {- continue;- }- const value = resolveAtPath(parsed, path);- if (value && typeof value === "object") kept.push(serialized);- }- return kept;-};diff --git a/packages/jsoncrack-react/src/JSONCrackComponent.tsx b/packages/jsoncrack-react/src/JSONCrackComponent.tsxindex 02de46ac..3cd01faa 100644--- a/packages/jsoncrack-react/src/JSONCrackComponent.tsx+++ b/packages/jsoncrack-react/src/JSONCrackComponent.tsx@@ -31,7 +31,7 @@ import {toJsonText,type JsonInput,} from "./canvasHelpers";-import { CollapseContext, isNodeHidden } from "./components/CollapseContext";+import { CollapseContext, isNodeHidden, prunePaths } from "./components/CollapseContext";import { Controls } from "./components/Controls";import { CustomEdge } from "./components/CustomEdge";import { CustomNode } from "./components/CustomNode";@@ -55,6 +55,14 @@ export interface JSONCrackRef {centerView: () => void;/** Center and zoom on the root node of the graph. */focusFirstNode: () => void;+ /** Toggle collapse for a specific JSON path (uncontrolled mode only). */+ toggleCollapse: (path: JSONPath) => void;+ /** Collapse every first-level container of the root (uncontrolled mode only). */+ collapseAll: () => void;+ /** Clear all collapsed paths (uncontrolled mode only). */+ expandAll: () => void;+ /** Current collapsed-paths snapshot (serialized keys). */+ getCollapsedPaths: () => string[];}/** Props accepted by the `JSONCrack` component. */@@ -89,10 +97,17 @@ export interface JSONCrackProps {onViewportCreate?: (viewPort: ViewPort) => void;/** Custom renderer shown when the graph exceeds `maxRenderableNodes`. */renderNodeLimitExceeded?: (nodeCount: number, maxRenderableNodes: number) => ReactNode;- /** Serialized JSON paths (via `JSON.stringify`) whose subtrees should be folded away. */+ /**+ * Controlled collapsed-paths set (serialized via `pathKey` / `JSON.stringify`).+ * When provided, the component becomes controlled for collapse state and+ * `onToggleCollapse` is required to mutate it. When omitted, the component+ * manages collapse state internally.+ */collapsedPaths?: string[];- /** Called with the `JSONPath` of a row's value when the user clicks a chevron. */+ /** Called with the `JSONPath` of a row's value when the user clicks a chevron (controlled mode). */onToggleCollapse?: (path: JSONPath) => void;+ /** Observe the internal collapsed-paths set (uncontrolled mode). */+ onCollapseChange?: (collapsedPaths: string[]) => void;}/** Interactive JSON-to-graph visualization. Forwards a `JSONCrackRef` for imperative viewport control. */@@ -114,8 +129,9 @@ export const JSONCrack = forwardRef<JSONCrackRef, JSONCrackProps>(onParseError,onViewportCreate,renderNodeLimitExceeded,- collapsedPaths,- onToggleCollapse,+ collapsedPaths: controlledCollapsedPaths,+ onToggleCollapse: controlledOnToggle,+ onCollapseChange,},ref) => {@@ -203,18 +219,35 @@ export const JSONCrack = forwardRef<JSONCrackRef, JSONCrackProps>(return () => observer.disconnect();}, [viewPort]);- // 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>(+ const viewPortApi = useMemo(() => ({zoomIn: () => adjustViewPortZoom(viewPort, 0.1),zoomOut: () => adjustViewPortZoom(viewPort, -0.1),- setZoom: zoomFactor => setViewPortZoom(viewPort, zoomFactor),+ setZoom: (zoomFactor: number) => setViewPortZoom(viewPort, zoomFactor),centerView: () => fitGraphToViewPort(viewPort, containerRef.current, layoutSizeRef.current),focusFirstNode: () => focusRootNode(viewPort, containerRef.current),}),[viewPort]);- useImperativeHandle(ref, () => viewPortApi, [viewPortApi]);++ // Uncontrolled collapse state. `controlledCollapsedPaths` takes precedence when provided.+ const [internalCollapsedPaths, setInternalCollapsedPaths] = useState<string[]>([]);+ const isControlled = controlledCollapsedPaths !== undefined;+ const collapsedPaths = isControlled ? controlledCollapsedPaths : internalCollapsedPaths;++ const onCollapseChangeRef = useRef(onCollapseChange);+ useEffect(() => {+ onCollapseChangeRef.current = onCollapseChange;+ }, [onCollapseChange]);++ // Prune internally-held collapsed paths that no longer resolve to an+ // object/array in the current data (e.g., after a JSON edit).+ useEffect(() => {+ if (isControlled) return;+ if (internalCollapsedPaths.length === 0) return;+ const kept = prunePaths(jsonText, internalCollapsedPaths);+ if (kept.length !== internalCollapsedPaths.length) setInternalCollapsedPaths(kept);+ }, [jsonText, internalCollapsedPaths, isControlled]);const collapsedSet = useMemo(() => new Set(collapsedPaths ?? []), [collapsedPaths]);@@ -272,7 +305,6 @@ export const JSONCrack = forwardRef<JSONCrackRef, JSONCrackProps>(const wrappedToggleCollapse = useCallback((path: JSONPath) => {- if (!onToggleCollapse) return;const key = JSON.stringify(path);const btn = findCollapseButton(key);if (btn) {@@ -286,9 +318,17 @@ export const JSONCrack = forwardRef<JSONCrackRef, JSONCrackProps>(} else {pendingRecenterRef.current = null;}- onToggleCollapse(path);+ if (isControlled) {+ controlledOnToggle?.(path);+ return;+ }+ setInternalCollapsedPaths(prev => {+ const next = prev.includes(key) ? prev.filter(p => p !== key) : [...prev, key];+ onCollapseChangeRef.current?.(next);+ return next;+ });},- [onToggleCollapse, findCollapseButton]+ [isControlled, controlledOnToggle, findCollapseButton]);const collapseContextValue = useMemo(@@ -296,6 +336,51 @@ export const JSONCrack = forwardRef<JSONCrackRef, JSONCrackProps>([collapsedSet, wrappedToggleCollapse]);+ const collapsedPathsRef = useRef(collapsedPaths);+ collapsedPathsRef.current = collapsedPaths;++ const collapseApi = useMemo(+ () => ({+ toggleCollapse: (path: JSONPath) => wrappedToggleCollapse(path),+ collapseAll: () => {+ if (isControlled) return;+ let parsed: unknown;+ try {+ parsed = JSON.parse(jsonText);+ } catch {+ return;+ }+ if (!parsed || typeof parsed !== "object") return;+ const keys = Array.isArray(parsed)+ ? parsed.map((_, i) => i)+ : Object.keys(parsed as Record<string, unknown>);+ const next: string[] = [];+ for (const k of keys) {+ const v = (parsed as Record<string | number, unknown>)[k as string & number];+ if (v && typeof v === "object") {+ if (Array.isArray(v) && v.length === 0) continue;+ if (!Array.isArray(v) && Object.keys(v).length === 0) continue;+ next.push(JSON.stringify([k]));+ }+ }+ setInternalCollapsedPaths(next);+ onCollapseChangeRef.current?.(next);+ },+ expandAll: () => {+ if (isControlled) return;+ setInternalCollapsedPaths([]);+ onCollapseChangeRef.current?.([]);+ },+ getCollapsedPaths: () => collapsedPathsRef.current ?? [],+ }),+ [isControlled, jsonText, wrappedToggleCollapse]+ );++ useImperativeHandle(ref, () => ({ ...viewPortApi, ...collapseApi }), [+ viewPortApi,+ collapseApi,+ ]);+const edgeTargetById = useMemo(() => buildEdgeTargetMap(visibleEdges), [visibleEdges]);// Signal "relayouting" whenever the collapsed-set changes so the spinnerdiff --git a/packages/jsoncrack-react/src/__tests__/CollapseContext.test.ts b/packages/jsoncrack-react/src/__tests__/CollapseContext.test.tsnew file mode 100644index 00000000..04fa874a--- /dev/null+++ b/packages/jsoncrack-react/src/__tests__/CollapseContext.test.ts@@ -0,0 +1,105 @@+import { describe, expect, it } from "vitest";+import { isNodeHidden, pathKey, prunePaths } from "../components/CollapseContext";++describe("pathKey", () => {+ it("serializes a JSONPath to a stable JSON string", () => {+ expect(pathKey([])).toBe("[]");+ expect(pathKey(["users"])).toBe('["users"]');+ expect(pathKey(["users", 0, "address"])).toBe('["users",0,"address"]');+ });++ it("round-trips through JSON.parse", () => {+ const path = ["a", 1, "b"];+ expect(JSON.parse(pathKey(path))).toEqual(path);+ });+});++describe("isNodeHidden", () => {+ it("returns false when no prefixes are collapsed", () => {+ expect(isNodeHidden([], ["users"])).toBe(false);+ });++ it("returns false when nodePath is undefined", () => {+ expect(isNodeHidden([["users"]], undefined)).toBe(false);+ });++ it("hides the node whose path exactly matches a collapsed prefix", () => {+ expect(isNodeHidden([["users"]], ["users"])).toBe(true);+ });++ it("hides descendant nodes", () => {+ expect(isNodeHidden([["users"]], ["users", 0])).toBe(true);+ expect(isNodeHidden([["users"]], ["users", 0, "address"])).toBe(true);+ });++ it("does not hide sibling paths", () => {+ expect(isNodeHidden([["users"]], ["posts"])).toBe(false);+ expect(isNodeHidden([["users"]], ["usersOther"])).toBe(false);+ });++ it("does not hide ancestors of a collapsed path", () => {+ expect(isNodeHidden([["users", 0, "address"]], ["users", 0])).toBe(false);+ expect(isNodeHidden([["users", 0, "address"]], [])).toBe(false);+ });++ it("respects multiple prefixes (OR semantics)", () => {+ const prefixes = [["users"], ["config", "theme"]];+ expect(isNodeHidden(prefixes, ["users", 1])).toBe(true);+ expect(isNodeHidden(prefixes, ["config", "theme", "dark"])).toBe(true);+ expect(isNodeHidden(prefixes, ["config", "locale"])).toBe(false);+ });++ it("distinguishes numeric from string segments at the same position", () => {+ expect(isNodeHidden([[0]], ["0"])).toBe(false);+ expect(isNodeHidden([["0"]], [0])).toBe(false);+ });++ it("never hides the root", () => {+ expect(isNodeHidden([["users"]], [])).toBe(false);+ });+});++describe("prunePaths", () => {+ const json = JSON.stringify({+ users: [{ name: "Alice" }, { name: "Bob" }],+ config: { theme: { mode: "dark" } },+ count: 2,+ });++ it("returns the input verbatim when empty", () => {+ const input: string[] = [];+ expect(prunePaths(json, input)).toEqual([]);+ });++ it("keeps paths resolving to objects", () => {+ const input = [pathKey(["config"]), pathKey(["config", "theme"])];+ expect(prunePaths(json, input)).toEqual(input);+ });++ it("keeps paths resolving to arrays", () => {+ expect(prunePaths(json, [pathKey(["users"])])).toEqual([pathKey(["users"])]);+ });++ it("drops paths resolving to primitives", () => {+ expect(prunePaths(json, [pathKey(["count"])])).toEqual([]);+ });++ it("drops paths resolving to missing keys", () => {+ expect(prunePaths(json, [pathKey(["missing"])])).toEqual([]);+ expect(prunePaths(json, [pathKey(["users", 99, "name"])])).toEqual([]);+ });++ it("drops malformed serialized entries", () => {+ expect(prunePaths(json, ["not-json"])).toEqual([]);+ });++ it("returns input verbatim when JSON is invalid (preserves intent through transient errors)", () => {+ const input = [pathKey(["config"])];+ expect(prunePaths("{ broken", input)).toEqual(input);+ });++ it("keeps only still-valid paths when mixed", () => {+ const input = [pathKey(["config"]), pathKey(["count"]), pathKey(["missing"])];+ expect(prunePaths(json, input)).toEqual([pathKey(["config"])]);+ });+});diff --git a/packages/jsoncrack-react/src/components/CollapseContext.ts b/packages/jsoncrack-react/src/components/CollapseContext.tsindex 5f459f01..e7b89d1c 100644--- a/packages/jsoncrack-react/src/components/CollapseContext.ts+++ b/packages/jsoncrack-react/src/components/CollapseContext.ts@@ -35,3 +35,38 @@ export const isNodeHidden = (}return false;};++/**+ * Drop serialized collapsed-paths that no longer resolve to an object/array+ * in the given JSON. Invalid JSON returns the input verbatim so a transient+ * edit error doesn't nuke state.+ */+export const prunePaths = (jsonText: string, paths: readonly string[]): string[] => {+ if (paths.length === 0) return paths as string[];+ let parsed: unknown;+ try {+ parsed = JSON.parse(jsonText);+ } catch {+ return paths as string[];+ }+ const kept: string[] = [];+ for (const key of paths) {+ let path: JSONPath;+ try {+ path = JSON.parse(key) as JSONPath;+ } catch {+ continue;+ }+ let cur: unknown = parsed;+ let ok = true;+ for (const seg of path) {+ if (cur == null || typeof cur !== "object") {+ ok = false;+ break;+ }+ cur = (cur as Record<string | number, unknown>)[seg as string & number];+ }+ if (ok && cur != null && typeof cur === "object") kept.push(key);+ }+ return kept;+};