✨ Innovative and open-source visualization application that transforms various data formats, such as JSON, YAML, XML and CSV into interactive graphs.
feat: implement collapse/expand functionality
AykutSarac7a0fc44b0f25
diff --git a/apps/www/src/features/editor/views/GraphView/Toolbar/index.tsx b/apps/www/src/features/editor/views/GraphView/Toolbar/index.tsxindex 8a99567c..b565e47a 100644--- a/apps/www/src/features/editor/views/GraphView/Toolbar/index.tsx+++ b/apps/www/src/features/editor/views/GraphView/Toolbar/index.tsx@@ -6,10 +6,19 @@ import type { LayoutDirection } from "jsoncrack-react";import { event as gaEvent } from "nextjs-google-analytics";import { BsCheck2 } from "react-icons/bs";import { FaMoon, FaSun } from "react-icons/fa6";-import { LuImageDown, LuMinus, LuPlus, LuSearch, LuSettings2 } from "react-icons/lu";+import {+ LuCopyMinus,+ LuCopyPlus,+ LuImageDown,+ LuMinus,+ LuPlus,+ LuSearch,+ LuSettings2,+} from "react-icons/lu";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";@@ -73,6 +82,10 @@ 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 expandAll = useGraph(state => state.expandAll);+ const collapseAllDepth1 = useGraph(state => state.collapseAllDepth1);+ const json = useJson(state => state.json);const setVisible = useModal(state => state.setVisible);const darkmodeEnabled = useConfig(state => state.darkmodeEnabled);const toggleDarkMode = useConfig(state => state.toggleDarkMode);@@ -241,6 +254,36 @@ export const Toolbar = () => {</ActionIcon></Tooltip>+ <Tooltip+ label={+ collapsedPaths.length > 0+ ? `Expand all (${collapsedPaths.length} collapsed)`+ : "Collapse all"+ }+ position="top"+ withArrow+ openDelay={750}+ >+ <ActionIcon+ aria-label={collapsedPaths.length > 0 ? "expand all" : "collapse all"}+ size="lg"+ radius="md"+ variant="subtle"+ color="gray"+ onClick={() => {+ if (collapsedPaths.length > 0) {+ expandAll();+ gaEvent("expand_all");+ } else {+ collapseAllDepth1(json);+ gaEvent("collapse_all");+ }+ }}+ >+ {collapsedPaths.length > 0 ? <LuCopyPlus size={18} /> : <LuCopyMinus size={18} />}+ </ActionIcon>+ </Tooltip>+<Divider orientation="vertical" mx={2} /><Menu trigger="click" position="top-end">diff --git a/apps/www/src/features/editor/views/GraphView/index.tsx b/apps/www/src/features/editor/views/GraphView/index.tsxindex 3f7ef22d..97b99f8c 100644--- a/apps/www/src/features/editor/views/GraphView/index.tsx+++ b/apps/www/src/features/editor/views/GraphView/index.tsx@@ -4,6 +4,7 @@ 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";@@ -52,6 +53,9 @@ 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 gesturesEnabled = useConfig(state => state.gesturesEnabled);const rulersEnabled = useConfig(state => state.rulersEnabled);const darkmodeEnabled = useConfig(state => state.darkmodeEnabled);@@ -63,6 +67,12 @@ 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 blurOnClick = React.useCallback(() => {if ("activeElement" in document) {(document.activeElement as HTMLElement | null)?.blur();@@ -101,6 +111,8 @@ export const GraphView = ({ isWidget = false }: GraphProps) => {centerOnLayoutonViewportCreate={setViewPort}onNodeClick={handleNodeClick}+ collapsedPaths={collapsedPaths}+ onToggleCollapse={toggleCollapse}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 418b0094..2d467a8c 100644--- a/apps/www/src/features/editor/views/GraphView/stores/useGraph.ts+++ b/apps/www/src/features/editor/views/GraphView/stores/useGraph.ts@@ -1,4 +1,6 @@import type { RefObject } from "react";+import type { JSONPath } from "jsonc-parser";+import { pathKey } from "jsoncrack-react";import type { LayoutDirection, NodeData, JSONCrackRef } from "jsoncrack-react";import type { ViewPort } from "react-zoomable-ui";import { create } from "zustand";@@ -9,6 +11,7 @@ export interface Graph {direction: LayoutDirection;fullscreen: boolean;selectedNode: NodeData | null;+ collapsedPaths: string[];}const initialStates: Graph = {@@ -17,6 +20,7 @@ const initialStates: Graph = {direction: "RIGHT",fullscreen: false,selectedNode: null,+ collapsedPaths: [],};interface GraphActions {@@ -29,6 +33,10 @@ interface GraphActions {zoomIn: () => void;zoomOut: () => void;centerView: () => void;+ toggleCollapse: (path: JSONPath) => void;+ setCollapsedPaths: (paths: string[]) => void;+ expandAll: () => void;+ collapseAllDepth1: (json: string) => void;}const useGraph = create<Graph & GraphActions>((set, get) => ({@@ -53,6 +61,39 @@ const useGraph = create<Graph & GraphActions>((set, get) => ({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 });+ },+ setCollapsedPaths: paths => {+ const prev = get().collapsedPaths;+ if (prev.length === paths.length && prev.every((p, i) => p === paths[i])) return;+ set({ collapsedPaths: paths });+ },+ 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+ }+ },}));export default useGraph;diff --git a/apps/www/src/lib/utils/collapse.ts b/apps/www/src/lib/utils/collapse.tsnew file mode 100644index 00000000..a4bb9473--- /dev/null+++ b/apps/www/src/lib/utils/collapse.ts@@ -0,0 +1,38 @@+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 7e219b02..02de46ac 100644--- a/packages/jsoncrack-react/src/JSONCrackComponent.tsx+++ b/packages/jsoncrack-react/src/JSONCrackComponent.tsx@@ -11,6 +11,7 @@ import {type CSSProperties,type ReactNode,} from "react";+import type { JSONPath } from "jsonc-parser";import type { ViewPort } from "react-zoomable-ui";import { Space } from "react-zoomable-ui";import { Canvas } from "reaflow";@@ -30,6 +31,7 @@ import {toJsonText,type JsonInput,} from "./canvasHelpers";+import { CollapseContext, isNodeHidden } from "./components/CollapseContext";import { Controls } from "./components/Controls";import { CustomEdge } from "./components/CustomEdge";import { CustomNode } from "./components/CustomNode";@@ -87,6 +89,10 @@ 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. */+ collapsedPaths?: string[];+ /** Called with the `JSONPath` of a row's value when the user clicks a chevron. */+ onToggleCollapse?: (path: JSONPath) => void;}/** Interactive JSON-to-graph visualization. Forwards a `JSONCrackRef` for imperative viewport control. */@@ -108,6 +114,8 @@ export const JSONCrack = forwardRef<JSONCrackRef, JSONCrackProps>(onParseError,onViewportCreate,renderNodeLimitExceeded,+ collapsedPaths,+ onToggleCollapse,},ref) => {@@ -208,7 +216,102 @@ export const JSONCrack = forwardRef<JSONCrackRef, JSONCrackProps>();useImperativeHandle(ref, () => viewPortApi, [viewPortApi]);- const edgeTargetById = useMemo(() => buildEdgeTargetMap(edges), [edges]);+ const collapsedSet = useMemo(() => new Set(collapsedPaths ?? []), [collapsedPaths]);++ // Pre-parse the serialized paths once per collapsedSet change so the+ // per-node prefix check doesn't re-parse on every iteration.+ const collapsedPrefixes = useMemo<JSONPath[]>(() => {+ if (collapsedSet.size === 0) return [];+ const out: JSONPath[] = [];+ for (const key of collapsedSet) {+ try {+ out.push(JSON.parse(key) as JSONPath);+ } catch {+ // skip malformed entries+ }+ }+ return out;+ }, [collapsedSet]);++ const { visibleNodes, visibleEdges } = useMemo(() => {+ if (collapsedPrefixes.length === 0) return { visibleNodes: nodes, visibleEdges: edges };+ const hiddenIds = new Set<string>();+ const keptNodes: typeof nodes = [];+ for (const node of nodes) {+ if (isNodeHidden(collapsedPrefixes, node.path)) {+ hiddenIds.add(node.id);+ } else {+ keptNodes.push(node);+ }+ }+ const keptEdges = edges.filter(edge => !hiddenIds.has(edge.from) && !hiddenIds.has(edge.to));+ return { visibleNodes: keptNodes, visibleEdges: keptEdges };+ }, [nodes, edges, collapsedPrefixes]);++ // Remember where a collapse button sat on screen at click time so the+ // post-layout camera pan can pin it back under the cursor.+ const pendingRecenterRef = useRef<{+ key: string;+ clientX: number;+ clientY: number;+ } | null>(null);+ // While a collapse-toggle is mid-flight (ELK running, pan pending) we+ // fade the canvas to hide the intermediate shifted layout — otherwise the+ // user sees a flash of the un-pinned graph before the camera recenters.+ const [isRelayouting, setIsRelayouting] = useState(false);++ const findCollapseButton = useCallback((key: string): HTMLElement | null => {+ const container = containerRef.current;+ if (!container) return null;+ const buttons = container.querySelectorAll<HTMLElement>("[data-collapse-path]");+ for (let i = 0; i < buttons.length; i += 1) {+ if (buttons[i].getAttribute("data-collapse-path") === key) return buttons[i];+ }+ return null;+ }, []);++ const wrappedToggleCollapse = useCallback(+ (path: JSONPath) => {+ if (!onToggleCollapse) return;+ const key = JSON.stringify(path);+ const btn = findCollapseButton(key);+ if (btn) {+ const rect = btn.getBoundingClientRect();+ pendingRecenterRef.current = {+ key,+ clientX: rect.left + rect.width / 2,+ clientY: rect.top + rect.height / 2,+ };+ setIsRelayouting(true);+ } else {+ pendingRecenterRef.current = null;+ }+ onToggleCollapse(path);+ },+ [onToggleCollapse, findCollapseButton]+ );++ const collapseContextValue = useMemo(+ () => ({ collapsedSet, onToggleCollapse: wrappedToggleCollapse }),+ [collapsedSet, wrappedToggleCollapse]+ );++ const edgeTargetById = useMemo(() => buildEdgeTargetMap(visibleEdges), [visibleEdges]);++ // Signal "relayouting" whenever the collapsed-set changes so the spinner+ // appears immediately on collapse/expand. JSON edits already route+ // through the parse effect which handles `setLoading(true)` on its own,+ // so we scope this trigger to collapse toggles only.+ const visibleNodesRef = useRef(visibleNodes);+ visibleNodesRef.current = visibleNodes;+ const isFirstCollapsedPassRef = useRef(true);+ useEffect(() => {+ if (isFirstCollapsedPassRef.current) {+ isFirstCollapsedPassRef.current = false;+ return;+ }+ if (visibleNodesRef.current.length > 0) setLoading(true);+ }, [collapsedSet]);const onLayoutChange = useCallback((layout: ElkRoot) => {if (!layout.width || !layout.height) {@@ -222,6 +325,78 @@ export const JSONCrack = forwardRef<JSONCrackRef, JSONCrackProps>(setLoading(false);}, []);+ // After a collapse toggle triggers relayout, pin the clicked button back+ // under the cursor. We poll each rAF until the button's rect is stable+ // for two consecutive frames (reaflow runs ELK + framer-motion commits+ // the new transforms over several frames on large graphs), then shift+ // the camera by the measured screen-pixel delta.+ useEffect(() => {+ const pending = pendingRecenterRef.current;+ if (!pending) return;+ pendingRecenterRef.current = null;++ let cancelled = false;+ let attempts = 0;+ let lastX: number | null = null;+ let lastY: number | null = null;+ let movementSeen = false;+ const MAX_ATTEMPTS = 180;++ const finish = (x?: number, y?: number) => {+ if (x !== undefined && y !== undefined) {+ const dx = x - pending.clientX;+ const dy = y - pending.clientY;+ if (Math.abs(dx) >= 1 || Math.abs(dy) >= 1) {+ viewPort?.camera?.moveByInClientSpace(dx, dy);+ }+ }+ setIsRelayouting(false);+ };++ const tick = () => {+ if (cancelled) return;+ attempts += 1;+ const btn = findCollapseButton(pending.key);+ if (!btn) {+ if (attempts < MAX_ATTEMPTS) requestAnimationFrame(tick);+ else finish();+ return;+ }+ const rect = btn.getBoundingClientRect();+ const x = rect.left + rect.width / 2;+ const y = rect.top + rect.height / 2;++ if (lastX !== null) {+ const moved = Math.abs(x - lastX) >= 0.5 || Math.abs(y - (lastY ?? 0)) >= 0.5;+ if (moved) {+ movementSeen = true;+ } else if (movementSeen) {+ // Stabilised after detected movement — safe to apply.+ finish(x, y);+ return;+ }+ }++ lastX = x;+ lastY = y;++ if (attempts < MAX_ATTEMPTS) {+ requestAnimationFrame(tick);+ } else if (movementSeen) {+ finish(x, y);+ } else {+ finish();+ }+ };++ const rafId = requestAnimationFrame(tick);+ return () => {+ cancelled = true;+ cancelAnimationFrame(rafId);+ setIsRelayouting(false);+ };+ }, [visibleNodes, visibleEdges, viewPort, findCollapseButton]);+// 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@@ -234,7 +409,7 @@ export const JSONCrack = forwardRef<JSONCrackRef, JSONCrackProps>(setInitialFitDone(true);return;}- if (!viewPort || nodes.length === 0 || loading) return;+ if (!viewPort || visibleNodes.length === 0 || loading) return;if (!layoutSizeRef.current) return;let cancelled = false;@@ -247,7 +422,7 @@ export const JSONCrack = forwardRef<JSONCrackRef, JSONCrackProps>(cancelled = true;window.cancelAnimationFrame(rafId);};- }, [viewPort, nodes, loading, centerOnLayout, initialFitDone, paneWidth, paneHeight]);+ }, [viewPort, visibleNodes, loading, centerOnLayout, initialFitDone, paneWidth, paneHeight]);// Stable render factories so reaflow doesn't re-key nodes/edges on every parent render.const renderNode = useCallback(@@ -315,41 +490,41 @@ export const JSONCrack = forwardRef<JSONCrackRef, JSONCrackProps>(onContextMenu={event => event.preventDefault()}treatTwoFingerTrackPadGesturesLikeTouch={trackpadZoom}className="jsoncrack-space"- style={{ opacity: initialFitDone ? 1 : 0, transition: "opacity 120ms" }}+ style={{+ opacity: initialFitDone && !isRelayouting ? 1 : 0,+ visibility: isRelayouting ? "hidden" : "visible",+ transition: "opacity 120ms",+ }}>- <Canvas- className="jsoncrack-canvas"- onLayoutChange={onLayoutChange}- node={renderNode}- edge={renderEdge}- nodes={nodes}- edges={edges}- arrow={null}- maxHeight={paneHeight}- maxWidth={paneWidth}- height={paneHeight}- width={paneWidth}- direction={layoutDirection}- layoutOptions={layoutOptions}- key={layoutDirection}- pannable={false}- zoomable={false}- animated={false}- readonly- dragEdge={null}- dragNode={null}- // 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}- />+ <CollapseContext.Provider value={collapseContextValue}>+ <Canvas+ className="jsoncrack-canvas"+ onLayoutChange={onLayoutChange}+ node={renderNode}+ edge={renderEdge}+ nodes={visibleNodes}+ edges={visibleEdges}+ arrow={null}+ maxHeight={paneHeight}+ maxWidth={paneWidth}+ height={paneHeight}+ width={paneWidth}+ direction={layoutDirection}+ layoutOptions={layoutOptions}+ key={layoutDirection}+ pannable={false}+ zoomable={false}+ animated={false}+ readonly+ dragEdge={null}+ dragNode={null}+ // Disable reaflow's built-in auto-centering of content inside the+ // pane. Passing a nullish `defaultPosition` makes reaflow leave+ // the group at the svg origin so our fit-to-viewport rect math+ // matches reality.+ defaultPosition={null as unknown as undefined}+ />+ </CollapseContext.Provider></Space></div>);diff --git a/packages/jsoncrack-react/src/JSONCrackStyles.module.css b/packages/jsoncrack-react/src/JSONCrackStyles.module.cssindex ac48c16b..2dbd5f7a 100644--- a/packages/jsoncrack-react/src/JSONCrackStyles.module.css+++ b/packages/jsoncrack-react/src/JSONCrackStyles.module.css@@ -53,8 +53,10 @@display: flex;align-items: center;justify-content: center;- pointer-events: none;- background: radial-gradient(circle at center, var(--overlay-bg) 0 44px, transparent 96px);+ pointer-events: all;+ background: rgba(0, 0, 0, 0.1);+ backdrop-filter: blur(6px) saturate(110%);+ -webkit-backdrop-filter: blur(6px) saturate(110%);}.spinner {diff --git a/packages/jsoncrack-react/src/components/CollapseContext.ts b/packages/jsoncrack-react/src/components/CollapseContext.tsnew file mode 100644index 00000000..5f459f01--- /dev/null+++ b/packages/jsoncrack-react/src/components/CollapseContext.ts@@ -0,0 +1,37 @@+import { createContext, useContext } from "react";+import type { JSONPath } from "jsonc-parser";++export interface CollapseContextValue {+ collapsedSet: Set<string>;+ onToggleCollapse?: (path: JSONPath) => void;+}++const EMPTY: CollapseContextValue = { collapsedSet: new Set() };++export const CollapseContext = createContext<CollapseContextValue>(EMPTY);++export const useCollapseContext = (): CollapseContextValue => useContext(CollapseContext);++export const pathKey = (path: JSONPath): string => JSON.stringify(path);++export const isPathCollapsed = (collapsedSet: Set<string>, path: JSONPath): boolean =>+ collapsedSet.has(pathKey(path));++export const isNodeHidden = (+ collapsedPrefixes: readonly JSONPath[],+ nodePath: JSONPath | undefined+): boolean => {+ if (!nodePath || collapsedPrefixes.length === 0) return false;+ for (const prefix of collapsedPrefixes) {+ if (prefix.length > nodePath.length) continue;+ let matches = true;+ for (let i = 0; i < prefix.length; i += 1) {+ if (prefix[i] !== nodePath[i]) {+ matches = false;+ break;+ }+ }+ if (matches) return true;+ }+ return false;+};diff --git a/packages/jsoncrack-react/src/components/Node.module.css b/packages/jsoncrack-react/src/components/Node.module.cssindex c341fbfd..41705fba 100644--- a/packages/jsoncrack-react/src/components/Node.module.css+++ b/packages/jsoncrack-react/src/components/Node.module.css@@ -33,6 +33,41 @@box-sizing: border-box;}+.row.collapsed {+ font-style: italic;+ opacity: 0.7;+}++.collapseButton {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ width: 14px;+ height: 14px;+ margin-right: 6px;+ margin-top: -2px;+ font-size: 11px;+ font-weight: 600;+ line-height: 1;+ color: var(--interactive-normal);+ background: transparent;+ border: 1px solid var(--node-divider);+ border-radius: 3px;+ opacity: 0.6;+ pointer-events: all;+ cursor: pointer;+ user-select: none;+ vertical-align: middle;+ transition:+ opacity 120ms ease,+ background 120ms ease;+}++.collapseButton:hover {+ opacity: 1;+ background: var(--node-divider);+}+.row:last-of-type {border-bottom: none;}diff --git a/packages/jsoncrack-react/src/components/ObjectNode.tsx b/packages/jsoncrack-react/src/components/ObjectNode.tsxindex a922d21d..4ab8f352 100644--- a/packages/jsoncrack-react/src/components/ObjectNode.tsx+++ b/packages/jsoncrack-react/src/components/ObjectNode.tsx@@ -1,5 +1,7 @@import React from "react";+import type { JSONPath } from "jsonc-parser";import type { NodeData } from "../types";+import { isPathCollapsed, useCollapseContext } from "./CollapseContext";import styles from "./Node.module.css";import { TextRenderer } from "./TextRenderer";import { getTextColor } from "./nodeStyles";@@ -15,22 +17,47 @@ type RowProps = {x: number;y: number;index: number;+ parentPath: JSONPath;};const ROW_HEIGHT = 30;-const Row = ({ row, x, y, index }: RowProps) => {+const Row = ({ row, x, y, index, parentPath }: RowProps) => {const rowPosition = index * ROW_HEIGHT;+ const { collapsedSet, onToggleCollapse } = useCollapseContext();++ const isContainer =+ (row.type === "object" || row.type === "array") && (row.childrenCount ?? 0) > 0;+ const rowPath: JSONPath | null = React.useMemo(+ () => (isContainer && row.key != null ? [...parentPath, row.key] : null),+ [isContainer, parentPath, row.key]+ );+ const collapsed = rowPath != null && isPathCollapsed(collapsedSet, rowPath);const getRowText = () => {- if (row.type === "object") return `{${row.childrenCount ?? 0} keys}`;- if (row.type === "array") return `[${row.childrenCount ?? 0} items]`;+ if (row.type === "object") {+ const count = row.childrenCount ?? 0;+ return collapsed ? `⋯ ${count} keys` : `{${count} keys}`;+ }+ if (row.type === "array") {+ const count = row.childrenCount ?? 0;+ return collapsed ? `⋯ ${count} items` : `[${count} items]`;+ }return row.value;};+ const handleToggle = (event: React.MouseEvent) => {+ if (!rowPath || !onToggleCollapse) return;+ event.stopPropagation();+ event.preventDefault();+ onToggleCollapse(rowPath);+ };++ const rowClassName = collapsed ? `${styles.row} ${styles.collapsed}` : styles.row;+return (<span- className={styles.row}+ className={rowClassName}style={{color: getTextColor({ value: row.value, type: typeof row.value }),}}@@ -38,6 +65,19 @@ const Row = ({ row, x, y, index }: RowProps) => {data-x={x}data-y={y + rowPosition}>+ {isContainer && rowPath && (+ <span+ role="button"+ aria-label={collapsed ? "Expand" : "Collapse"}+ aria-expanded={!collapsed}+ className={styles.collapseButton}+ data-collapse-path={JSON.stringify(rowPath)}+ onClick={handleToggle}+ onMouseDown={event => event.stopPropagation()}+ >+ {collapsed ? "+" : "−"}+ </span>+ )}<spanclassName={styles.key}style={{ color: getTextColor({ type: "object", value: row.value }) }}@@ -49,20 +89,30 @@ const Row = ({ row, x, y, index }: RowProps) => {);};-const ObjectNodeBase = ({ node, x, y }: ObjectNodeProps) => (- <foreignObject- className={`${styles.foreignObject} ${styles.objectForeignObject}`}- data-id={`node-${node.id}`}- width={node.width}- height={node.height}- x={0}- y={0}- >- {node.text.map((row, index) => (- <Row key={`${node.id}-${index}`} row={row} x={x} y={y} index={index} />- ))}- </foreignObject>-);+const ObjectNodeBase = ({ node, x, y }: ObjectNodeProps) => {+ const parentPath = node.path ?? [];+ return (+ <foreignObject+ className={`${styles.foreignObject} ${styles.objectForeignObject}`}+ data-id={`node-${node.id}`}+ width={node.width}+ height={node.height}+ x={0}+ y={0}+ >+ {node.text.map((row, index) => (+ <Row+ key={`${node.id}-${index}`}+ row={row}+ x={x}+ y={y}+ index={index}+ parentPath={parentPath}+ />+ ))}+ </foreignObject>+ );+};const areRowTargetsEqual = (prevTargets?: string[], nextTargets?: string[]) => {if (prevTargets === nextTargets) return true;@@ -98,10 +148,21 @@ const areRowsEqual = (prevRows: NodeData["text"], nextRows: NodeData["text"]) =>return true;};+const arePathsEqual = (a?: JSONPath, b?: JSONPath) => {+ if (a === b) return true;+ if (!a || !b) return false;+ if (a.length !== b.length) return false;+ for (let i = 0; i < a.length; i += 1) {+ if (a[i] !== b[i]) return false;+ }+ return true;+};+const propsAreEqual = (prev: ObjectNodeProps, next: ObjectNodeProps) => {return (prev.node.width === next.node.width &&prev.node.height === next.node.height &&+ arePathsEqual(prev.node.path, next.node.path) &&areRowsEqual(prev.node.text, next.node.text));};diff --git a/packages/jsoncrack-react/src/index.ts b/packages/jsoncrack-react/src/index.tsindex d2824ea1..0d2fccae 100644--- a/packages/jsoncrack-react/src/index.ts+++ b/packages/jsoncrack-react/src/index.ts@@ -1,5 +1,6 @@export { JSONCrack } from "./JSONCrackComponent";export { parseGraph } from "./parser";+export { pathKey } from "./components/CollapseContext";export type { JSONCrackProps, JSONCrackRef } from "./JSONCrackComponent";export type { ParseGraphResult } from "./parser";export type {