---
title: "JSON Tree View · Base UI — StyleX Blocks"
description: "Explore JSON as an expandable tree with type-colored values, previews, and full keyboard navigation."
url: "https://stylexblocks.com/components/base-ui/json-tree-view/"
agent:
  instructions: "Use this search API to find relevant components and blocks across this site with keywords or natural-language queries, instead of crawling individual pages. Results are returned in Markdown."
  endpoint: "https://stylexblocks.com/.well-known/search?q={query}"
  method: "GET"
  documentation: "https://developers.cloudflare.com/ai-search/how-to/search-for-agents/"
---

# JSON Tree View

Explore JSON as an expandable tree with type-colored values, previews, and full keyboard navigation.

- Behavior engine: Base UI
- Also available for: [Ark UI](https://stylexblocks.com/components/ark-ui/json-tree-view.md), [UI SDK](https://stylexblocks.com/components/ui-sdk/json-tree-view.md)
- Category: Display
- Variants: subtle, solid
- Sizes: xs, sm, md
- HTML page: https://stylexblocks.com/components/base-ui/json-tree-view/

## Install

Configure the project once (sets the behavior engine and import aliases):

```sh
npx stylexblocks init --style base-ui
```

Then add the item as source you own:

```sh
npx stylexblocks add json-tree-view
```

Equivalent: `npx shadcn add @stylexblocks/json-tree-view`. Registry item JSON: https://stylexblocks.com/r/base-ui/json-tree-view.json

## Usage

```tsx
import { JsonTreeView } from "#components/ui/base-ui/json-tree-view.tsx";

const data = {
  name: "Ada Lovelace",
  verified: true,
  manager: null,
  languages: ["English", "French"],
  address: { city: "London", country: "UK" },
};

export function Example() {
  return (
    // Base UI has no tree machine; the component carries expansion,
    // selection, and roving focus, and implements the WAI-ARIA tree keys:
    // Up/Down move, Right expands or enters, Left collapses or exits.
    <JsonTreeView.Root data={data} defaultExpandedDepth={2} size="md">
      <JsonTreeView.Tree aria-label="User" />
    </JsonTreeView.Root>
  );
}

// controlled: expandedValue={["$", "$.address"]} onExpandedChange={(d) => …}
```

## Examples

### Custom values

renderValue replaces a leaf's default rendering, here turning URLs into links; quotesOnKeys prints keys JSON-style.

```tsx
// renderValue swaps in custom leaf rendering; return undefined to keep the default
<JsonTreeView.Root data={response} defaultExpandedDepth={3} quotesOnKeys>
  <JsonTreeView.Tree
    aria-label="Response"
    renderValue={({ value, type }) =>
      type === "string" && value.startsWith("https://") ? (
        <a href={value} target="_blank" rel="noreferrer">"{value}"</a>
      ) : undefined
    }
  />
</JsonTreeView.Root>
```

## Source

`components/ui/base-ui/json-tree-view.tsx`

```tsx
import * as stylex from "@stylexjs/stylex";
import { createContext, useCallback, useContext, useId, useMemo, useRef, useState } from "react";
import type { CSSProperties } from "react";
import { mergeProps } from "@base-ui/react/merge-props";
import { useRender } from "@base-ui/react/use-render";
import { fonts } from "@stylexblocks/ui/tokens/fonts.stylex.ts";
import { createSlotRecipeContext } from "#lib/base-ui/create-slot-recipe-context.tsx";
import {
  defineSlotRecipe,
  fromMap,
  resolveSlotStyles,
  variantDataAttrs,
  type WithStyleOverrides,
} from "#lib/recipe-props.ts";
import { treeViewTreeIconVars } from '@stylexblocks/ui/slot-recipes/tree-view.stylex.ts'

import { colorPalette } from '@stylexblocks/ui/color-palette.stylex.ts'
import { durations } from '@stylexblocks/ui/tokens/durations.stylex.ts'
import { fontSizes } from '@stylexblocks/ui/tokens/font-sizes.stylex.ts'
import { fontWeights } from '@stylexblocks/ui/tokens/font-weights.stylex.ts'
import { lineHeights } from '@stylexblocks/ui/tokens/line-heights.stylex.ts'
import { semanticColors } from '@stylexblocks/ui/semantic-tokens/colors.stylex.ts'
import { semanticRadii } from '@stylexblocks/ui/semantic-tokens/radii.stylex.ts'
import { sizes } from '@stylexblocks/ui/tokens/sizes.stylex.ts'
import { spacing } from '@stylexblocks/ui/tokens/spacing.stylex.ts'


const treeViewRoot = stylex.create({
  base: {
    width: sizes.full,
    display: 'flex',
    flexDirection: 'column',
    gap: spacing._2,
  },
})

const treeViewTree = stylex.create({
  base: {
    display: 'flex',
    flexDirection: 'column',
    '--tree-item-gap': spacing._2,
    '--tree-indentation':
      'calc(var(--tree-indent-size) + var(--tree-icon-size) * 0.5)',
    [treeViewTreeIconVars.width]: 'var(--tree-icon-size)',
    [treeViewTreeIconVars.height]: 'var(--tree-icon-size)',
  },
})

const treeViewTreeSizes = stylex.create({
  md: {
    fontSize: fontSizes.sm,
    lineHeight: lineHeights.sm,
    '--tree-indent-size': spacing._4,
    '--tree-icon-size': spacing._4,
    '--tree-padding-inline': spacing._3,
    '--tree-padding-block': spacing._1_5,
  },
  sm: {
    fontSize: fontSizes.sm,
    lineHeight: lineHeights.sm,
    '--tree-indent-size': spacing._4,
    '--tree-icon-size': spacing._3,
    '--tree-padding-inline': spacing._3,
    '--tree-padding-block': spacing._1,
  },
  xs: {
    fontSize: fontSizes.xs,
    lineHeight: lineHeights.xs,
    '--tree-indent-size': spacing._4,
    '--tree-icon-size': spacing._3,
    '--tree-padding-inline': spacing._2,
    '--tree-padding-block': spacing._1,
  },
})

const treeViewTreeIcon = stylex.create({
  base: {
    width: treeViewTreeIconVars.width,
    height: treeViewTreeIconVars.height,
  },
})

const treeViewLabel = stylex.create({
  base: {
    fontWeight: fontWeights.medium,
    fontSize: fontSizes.sm,
    lineHeight: lineHeights.sm,
  },
})

const treeViewBranch = stylex.create({
  base: {
    position: 'relative',
  },
})

const treeViewBranchContent = stylex.create({
  base: {
    position: 'relative',
  },
})

const treeViewBranchContentAnimateContents = stylex.create({
  true: {
    overflow: 'hidden',
    animationName: {
      default: null,
      ':is([data-open], [data-state="open"])': 'expand-height, fade-in',
      ':is([data-closed], [data-state="closed"])': 'collapse-height, fade-out',
    },
    animationDuration: {
      default: null,
      ':is([data-open], [data-state="open"])': durations.moderate,
      ':is([data-closed], [data-state="closed"])': durations.moderate,
    },
  },
})

const treeViewBranchIndentGuide = stylex.create({
  base: {
    height: '100%',
    width: '1px',
    backgroundColor: semanticColors.border,
    position: 'absolute',
    '--tree-depth': 'calc(var(--depth) - 1)',
    '--tree-indentation-offset':
      'calc(var(--tree-indentation) * var(--tree-depth))',
    '--tree-offset':
      'calc(var(--tree-padding-inline) + var(--tree-indentation-offset))',
    insetInlineStart: 'calc(var(--tree-offset) + var(--tree-icon-size) * 0.5)',
    zIndex: 1,
  },
})

const treeViewBranchIndicator = stylex.create({
  base: {
    color: semanticColors.fgMuted,
    transformOrigin: 'center',
    transitionDuration: durations.moderate,
    transitionProperty: 'transform',
    transitionTimingFunction: 'ease-in-out',
  },
})

const treeViewBranchTrigger = stylex.create({
  base: {
    display: 'inline-flex',
    alignItems: 'center',
    justifyContent: 'center',
  },
})

const treeViewBranchControl = stylex.create({
  base: {
    display: 'flex',
    alignItems: 'center',
    gap: 'var(--tree-item-gap)',
    borderRadius: semanticRadii.controlMd,
    userSelect: 'none',
    position: 'relative',
    '--tree-depth': 'calc(var(--depth) - 1)',
    '--tree-indentation-offset':
      'calc(var(--tree-indentation) * var(--tree-depth))',
    '--tree-offset':
      'calc(var(--tree-padding-inline) + var(--tree-indentation-offset))',
    paddingInlineStart: 'var(--tree-offset)',
    paddingInlineEnd: 'var(--tree-padding-inline)',
    paddingBlock: 'var(--tree-padding-block)',
    outlineWidth: {
      default: null,
      ':focus-visible': 'var(--focus-ring-width, 0)',
    },
    outlineOffset: {
      default: null,
      ':focus-visible': '0px',
    },
    outlineStyle: {
      default: null,
      ':focus-visible': 'solid',
    },
    outlineColor: {
      default: null,
      ':focus-visible': colorPalette.focusRing,
    },
    '--focus-ring-color': semanticColors.borderEmphasized,
    '--focus-ring-width': '2px',
    opacity: {
      default: null,
      ':is(:disabled, [disabled], [data-disabled])': 0.5,
    },
    cursor: {
      default: null,
      ':is(:disabled, [disabled], [data-disabled])': 'not-allowed',
    },
  },
})

const treeViewBranchControlVariants = stylex.create({
  subtle: {},
  solid: {},
})

const treeViewItem = stylex.create({
  base: {
    display: 'flex',
    alignItems: 'center',
    gap: 'var(--tree-item-gap)',
    borderRadius: semanticRadii.controlMd,
    userSelect: 'none',
    position: 'relative',
    '--tree-depth': 'calc(var(--depth) - 1)',
    '--tree-indentation-offset':
      'calc(var(--tree-indentation) * var(--tree-depth))',
    '--tree-offset':
      'calc(var(--tree-padding-inline) + var(--tree-indentation-offset))',
    paddingInlineStart: 'var(--tree-offset)',
    paddingInlineEnd: 'var(--tree-padding-inline)',
    paddingBlock: 'var(--tree-padding-block)',
    outlineWidth: {
      default: null,
      ':focus-visible': 'var(--focus-ring-width, 0)',
    },
    outlineOffset: {
      default: null,
      ':focus-visible': '0px',
    },
    outlineStyle: {
      default: null,
      ':focus-visible': 'solid',
    },
    outlineColor: {
      default: null,
      ':focus-visible': colorPalette.focusRing,
    },
    '--focus-ring-color': semanticColors.borderEmphasized,
    '--focus-ring-width': '2px',
    opacity: {
      default: null,
      ':is(:disabled, [disabled], [data-disabled])': 0.5,
    },
    cursor: {
      default: null,
      ':is(:disabled, [disabled], [data-disabled])': 'not-allowed',
    },
  },
})

const treeViewItemVariants = stylex.create({
  subtle: {},
  solid: {},
})

const treeViewItemText = stylex.create({
  base: {
    flex: 1,
  },
})

const treeViewBranchText = stylex.create({
  base: {
    flex: 1,
  },
})

const treeViewNodeCheckbox = stylex.create({
  base: {
    display: 'inline-flex',
  },
})

export type TreeViewSize = keyof typeof treeViewTreeSizes

export type TreeViewVariant = keyof typeof treeViewBranchControlVariants

export type TreeViewAnimateContent =
  keyof typeof treeViewBranchContentAnimateContents

// The tree-view recipe carries the rows, indentation, and indent guides; this
// adds the JSON layer: monospace text, a palette-tinted key, and per-type value
// colors keyed off the semantic status palettes (string → success, number →
// info, boolean → warning, null/undefined → subtle).
const jsonStatic = stylex.create({
  tree: { fontFamily: fonts.mono },
  row: {
    cursor: "pointer",
    color: semanticColors.fg,
    backgroundColor: { default: "transparent", ":hover": semanticColors.bgMuted },
    // Inset ring: open branch content clips overflow (height animation).
    outlineOffset: { default: null, ":focus-visible": "-2px" },
  },
  text: { minWidth: 0, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" },
  key: { color: colorPalette.fg },
  colon: { color: semanticColors.fgMuted },
  indicatorExpanded: {
    transform: {
      default: null,
      ':is([data-state="open"])': "rotate(90deg)",
    },
  },
  arrow: {
    display: "inline-flex",
    flexShrink: 0,
    width: "var(--tree-icon-size)",
    height: "var(--tree-icon-size)",
  },
  leafSpacer: { flexShrink: 0, width: "var(--tree-icon-size)" },
});

const jsonValueTypes = stylex.create({
  string: { color: semanticColors.successFg },
  number: { color: semanticColors.infoFg },
  bigint: { color: semanticColors.infoFg },
  boolean: { color: semanticColors.warningFg },
  null: { color: semanticColors.fgSubtle, fontStyle: "italic" },
  undefined: { color: semanticColors.fgSubtle, fontStyle: "italic" },
  object: { color: semanticColors.fgMuted },
  array: { color: semanticColors.fgMuted },
  other: { color: semanticColors.fgMuted },
});

const jsonRowSelected = stylex.create({
  subtle: {
    backgroundColor: {
      default: null,
      ":is([data-selected])": colorPalette.muted,
    },
  },
  solid: {
    backgroundColor: {
      default: null,
      ":is([data-selected])": colorPalette.solid,
    },
    color: {
      default: null,
      ":is([data-selected])": colorPalette.contrast,
    },
  },
});

const treeViewRecipe = defineSlotRecipe({
  slots: {
    root: { styles: treeViewRoot },
    tree: { styles: treeViewTree, sizes: treeViewTreeSizes },
    branch: { styles: treeViewBranch },
    branchContent: { styles: treeViewBranchContent },
    branchIndentGuide: { styles: treeViewBranchIndentGuide },
    branchIndicator: { styles: treeViewBranchIndicator },
    branchControl: {
      styles: treeViewBranchControl,
      variants: treeViewBranchControlVariants,
    },
    branchText: { styles: treeViewBranchText },
    item: { styles: treeViewItem, variants: treeViewItemVariants },
    itemText: { styles: treeViewItemText },
  },
  defaultVariants: { size: "md", variant: "subtle" },
});

const { withProvider, withContext, VariantContext } =
  createSlotRecipeContext(treeViewRecipe);

// ---------------------------------------------------------------------------
// Value formatting (plain JSON plus the JS primitives JSON can't carry).

type JsonValueType = keyof typeof jsonValueTypes;

function typeOf(value: unknown): JsonValueType {
  if (value === null) return "null";
  if (Array.isArray(value)) return "array";
  const t = typeof value;
  if (t === "string" || t === "number" || t === "boolean" || t === "bigint" || t === "undefined") {
    return t;
  }
  if (t === "object") return "object";
  return "other";
}

function formatLeaf(value: unknown, type: JsonValueType, max = Infinity): string {
  if (type === "string") {
    const s = JSON.stringify(value) ?? "";
    return s.length - 2 > max ? `${s.slice(0, max + 1)}…"` : s;
  }
  if (type === "bigint") return `${String(value)}n`;
  if (type === "array") return `Array(${(value as unknown[]).length})`;
  if (type === "object") {
    if (value instanceof Date) return value.toISOString();
    return "{…}";
  }
  return String(value);
}

interface JsonOptions {
  quotesOnKeys: boolean;
  maxPreviewItems: number;
  collapseStringsAfterLength: number;
}

function formatPreview(value: unknown, type: JsonValueType, opts: JsonOptions) {
  const max = opts.maxPreviewItems;
  const mini = (v: unknown) => {
    const t = typeOf(v);
    return t === "array" ? "[…]" : formatLeaf(v, t, opts.collapseStringsAfterLength);
  };
  if (type === "array") {
    const items = value as unknown[];
    const shown = items.slice(0, max).map(mini);
    if (items.length > max) shown.push("…");
    return `${items.length > 0 ? `(${items.length}) ` : ""}[${shown.join(", ")}]`;
  }
  const entries = Object.entries(value as Record<string, unknown>);
  const shown = entries.slice(0, max).map(([k, v]) => `${k}: ${mini(v)}`);
  if (entries.length > max) shown.push("…");
  return `{${shown.join(", ")}}`;
}

// ---------------------------------------------------------------------------
// The tree model: one node per value, keyed by its path from the root.

interface JsonNode {
  /** Path from the root, e.g. `$.user.tags.0`; the node's identity. */
  path: string;
  /** Path of the parent node, `null` for the root. */
  parent: string | null;
  key: string | null;
  value: unknown;
  type: JsonValueType;
  depth: number;
  children?: JsonNode[];
}

function isBranchValue(value: unknown) {
  return (
    value !== null &&
    typeof value === "object" &&
    !(value instanceof Date) &&
    Object.keys(value as object).length > 0
  );
}

// Keys are URI-encoded (dots included) so paths stay unambiguous and usable
// as element ids.
const segment = (key: string) => encodeURIComponent(key).replaceAll(".", "%2E");

function indexNodes(node: JsonNode, out = new Map<string, JsonNode>()) {
  out.set(node.path, node);
  for (const child of node.children ?? []) indexNodes(child, out);
  return out;
}

function toNode(
  value: unknown,
  key: string | null,
  path: string,
  parent: string | null,
  depth: number,
  seen: WeakSet<object>,
): JsonNode {
  const type = typeOf(value);
  const node: JsonNode = { path, parent, key, value, type, depth };
  if (isBranchValue(value)) {
    if (seen.has(value as object)) return { ...node, value: "[Circular]", type: "other" };
    seen.add(value as object);
    node.children = Object.entries(value as Record<string, unknown>).map(([k, v]) =>
      toNode(v, k, `${path}.${segment(k)}`, path, depth + 1, seen),
    );
  }
  return node;
}

function branchPathsUpTo(node: JsonNode, maxDepth: number, out: string[] = []) {
  if (node.children && node.depth <= maxDepth) {
    out.push(node.path);
    for (const child of node.children) branchPathsUpTo(child, maxDepth, out);
  }
  return out;
}

function describe(node: JsonNode) {
  const text = node.children
    ? `${node.type === "array" ? `Array(${(node.value as unknown[]).length})` : "Object"}, expandable with ${node.children.length} entries`
    : formatLeaf(node.value, node.type);
  return [node.key, text].filter(Boolean).join(": ");
}

// Base UI has no tree machine; the Root owns expansion, selection, and the
// roving focus, and the Tree handles the WAI-ARIA tree keyboard pattern over
// the rendered rows (collapsed branches render no children, so the DOM order
// of `[data-json-row]` is the visible order).
interface TreeState {
  root: JsonNode;
  options: JsonOptions;
  idBase: string;
  expanded: ReadonlySet<string>;
  setExpanded: (path: string, open: boolean) => void;
  selected: string | null;
  select: (path: string) => void;
  focused: string;
  setFocused: (path: string) => void;
}

const TreeContext = createContext<TreeState | null>(null);

function useTree() {
  const ctx = useContext(TreeContext);
  if (!ctx) throw new Error("JsonTreeView parts must be rendered inside <JsonTreeView.Root>");
  return ctx;
}

export type JsonTreeViewRootProps = WithStyleOverrides<useRender.ComponentProps<"div">> & {
  variant?: "subtle" | "solid";
  size?: "md" | "sm" | "xs";
  /** The data to display. */
  data: unknown;
  /** Branches up to this depth start expanded (1 = the root). */
  defaultExpandedDepth?: number;
  /** Controlled expanded paths (`$`, `$.user`, …). */
  expandedValue?: string[];
  onExpandedChange?: (details: { expandedValue: string[] }) => void;
  /** Controlled selected path. */
  selectedValue?: string | null;
  onSelectionChange?: (details: { selectedValue: string | null; value: unknown }) => void;
  /** Wrap keys in double quotes. */
  quotesOnKeys?: boolean;
  /** Entries shown in an object/array preview. */
  maxPreviewItems?: number;
  /** Strings longer than this are cut with "…" inside previews. */
  collapseStringsAfterLength?: number;
};

function RootNode({
  render,
  data,
  defaultExpandedDepth = 1,
  expandedValue,
  onExpandedChange,
  selectedValue,
  onSelectionChange,
  quotesOnKeys = false,
  maxPreviewItems = 3,
  collapseStringsAfterLength = 30,
  ...rest
}: Omit<JsonTreeViewRootProps, "variant" | "size" | "palette" | "style">) {
  const v = useContext(VariantContext);
  const idBase = useId();
  const root = useMemo(() => toNode(data, null, "$", null, 1, new WeakSet()), [data]);
  const nodes = useMemo(() => indexNodes(root), [root]);
  const [innerExpanded, setInnerExpanded] = useState<string[]>(() =>
    branchPathsUpTo(root, defaultExpandedDepth),
  );
  const expandedList = expandedValue ?? innerExpanded;
  const expanded = useMemo(() => new Set(expandedList), [expandedList]);
  const [innerSelected, setInnerSelected] = useState<string | null>(null);
  const selected = selectedValue !== undefined ? selectedValue : innerSelected;
  const [focused, setFocused] = useState("$");

  const latest = useRef({ expandedList, onExpandedChange, onSelectionChange, nodes });
  latest.current = { expandedList, onExpandedChange, onSelectionChange, nodes };

  const setExpanded = useCallback((path: string, open: boolean) => {
    const prev = latest.current.expandedList;
    if (prev.includes(path) === open) return;
    const next = open ? [...prev, path] : prev.filter((p) => p !== path);
    setInnerExpanded(next);
    latest.current.onExpandedChange?.({ expandedValue: next });
  }, []);

  const select = useCallback((path: string) => {
    setInnerSelected(path);
    latest.current.onSelectionChange?.({
      selectedValue: path,
      value: latest.current.nodes.get(path)?.value,
    });
  }, []);

  const state = useMemo<TreeState>(
    () => ({
      root,
      options: { quotesOnKeys, maxPreviewItems, collapseStringsAfterLength },
      idBase,
      expanded,
      setExpanded,
      selected,
      select,
      focused,
      setFocused,
    }),
    [root, quotesOnKeys, maxPreviewItems, collapseStringsAfterLength, idBase, expanded, setExpanded, selected, select, focused],
  );

  const element = useRender({
    defaultTagName: "div",
    render: render as useRender.RenderProp,
    state: v,
    props: mergeProps({ ...variantDataAttrs(v) }, rest),
  });
  return <TreeContext.Provider value={state}>{element}</TreeContext.Provider>;
}

function DefaultArrow() {
  return (
    <svg viewBox="0 0 16 16" fill="none" width="100%" height="100%" aria-hidden="true">
      <path
        d="M6 3.5 10.5 8 6 12.5"
        stroke="currentColor"
        strokeWidth="1.5"
        strokeLinecap="round"
        strokeLinejoin="round"
      />
    </svg>
  );
}

interface NodeRenderProps {
  /** Branch arrow; defaults to a chevron. */
  arrow?: React.ReactNode;
  /** Vertical guides along open branches. */
  indentGuide?: boolean;
  /** Custom leaf value rendering; return `undefined` to keep the default. */
  renderValue?: (details: { value: unknown; type: JsonValueType }) => React.ReactNode;
}

// Hosts that set the recipe's `--depth` custom property inline (the part's
// `style` prop is the StyleX override, so depth travels as its own prop).
function DepthDiv({ depth, style, ...rest }: React.ComponentProps<"div"> & { depth: number }) {
  return <div {...rest} style={{ ...style, "--depth": depth } as CSSProperties} />;
}

function DepthSpan({ depth, style, ...rest }: React.ComponentProps<"span"> & { depth: number }) {
  return <span {...rest} style={{ ...style, "--depth": depth } as CSSProperties} />;
}

// Styled row primitives, resolved from the recipe through context.
const Row = withContext(
  DepthDiv,
  (v) => [
    ...resolveSlotStyles(treeViewRecipe.slots.branchControl, v),
    jsonStatic.row,
    fromMap(jsonRowSelected, v.variant),
  ],
  "JsonTreeViewRow",
);
const LeafRow = withContext(
  DepthDiv,
  (v) => [
    ...resolveSlotStyles(treeViewRecipe.slots.item, v),
    jsonStatic.row,
    fromMap(jsonRowSelected, v.variant),
  ],
  "JsonTreeViewItem",
);
const Branch = withContext("div", "branch", "JsonTreeViewBranch");
const BranchContent = withContext("div", "branchContent", "JsonTreeViewBranchContent");
const BranchIndentGuide = withContext(DepthSpan, "branchIndentGuide", "JsonTreeViewBranchIndentGuide");
const BranchIndicator = withContext(
  "span",
  () => [treeViewBranchIndicator.base, jsonStatic.arrow, jsonStatic.indicatorExpanded],
  "JsonTreeViewBranchIndicator",
);
const RowText = withContext(
  "span",
  () => [treeViewBranchText.base, jsonStatic.text],
  "JsonTreeViewText",
);

function JsonValue({ node, renderValue }: { node: JsonNode } & Pick<NodeRenderProps, "renderValue">) {
  const { options } = useTree();
  const custom = node.children ? undefined : renderValue?.({ value: node.value, type: node.type });
  return (
    <>
      {node.key !== null ? (
        <>
          <span data-kind="key" {...stylex.props(jsonStatic.key)}>
            {options.quotesOnKeys ? `"${node.key}"` : node.key}
          </span>
          <span data-kind="colon" {...stylex.props(jsonStatic.colon)}>
            {": "}
          </span>
        </>
      ) : null}
      <span data-type={node.type} {...stylex.props(jsonValueTypes[node.type])}>
        {custom ??
          (node.children
            ? formatPreview(node.value, node.type, options)
            : formatLeaf(node.value, node.type))}
      </span>
    </>
  );
}

function JsonTreeNode({
  node,
  posinset,
  setsize,
  ...renderProps
}: { node: JsonNode; posinset: number; setsize: number } & NodeRenderProps) {
  const tree = useTree();
  const { arrow, indentGuide = true, renderValue } = renderProps;
  const selected = tree.selected === node.path;
  const rowProps = {
    role: "treeitem" as const,
    "data-json-row": "",
    "data-path": node.path,
    "data-parent": node.parent ?? undefined,
    "data-depth": node.depth,
    "aria-level": node.depth,
    "aria-posinset": posinset,
    "aria-setsize": setsize,
    "aria-selected": selected,
    "aria-label": describe(node),
    "data-selected": selected ? "" : undefined,
    tabIndex: tree.focused === node.path ? 0 : -1,
    depth: node.depth,
    onFocus: () => tree.setFocused(node.path),
  };

  if (!node.children) {
    return (
      <LeafRow {...rowProps} onClick={() => tree.select(node.path)}>
        <span aria-hidden="true" {...stylex.props(jsonStatic.leafSpacer)} />
        <RowText>
          <JsonValue node={node} renderValue={renderValue} />
        </RowText>
      </LeafRow>
    );
  }

  const open = tree.expanded.has(node.path);
  const groupId = `${tree.idBase}-${node.path}`;
  return (
    <Branch role="none" data-state={open ? "open" : "closed"}>
      <Row
        {...rowProps}
        aria-expanded={open}
        aria-owns={open ? groupId : undefined}
        data-state={open ? "open" : "closed"}
        onClick={() => {
          tree.select(node.path);
          tree.setExpanded(node.path, !open);
        }}
      >
        <BranchIndicator aria-hidden="true" data-state={open ? "open" : "closed"}>
          {arrow ?? <DefaultArrow />}
        </BranchIndicator>
        <RowText>
          <JsonValue node={node} />
        </RowText>
      </Row>
      {open ? (
        <BranchContent role="group" id={groupId} data-state="open">
          {indentGuide ? (
            <BranchIndentGuide aria-hidden="true" depth={node.depth} />
          ) : null}
          {node.children.map((child, index) => (
            <JsonTreeNode
              key={child.path}
              node={child}
              posinset={index + 1}
              setsize={node.children!.length}
              {...renderProps}
            />
          ))}
        </BranchContent>
      ) : null}
    </Branch>
  );
}

function TreeNode({
  render,
  arrow,
  indentGuide,
  renderValue,
  ...rest
}: useRender.ComponentProps<"div"> & NodeRenderProps) {
  const tree = useTree();
  const ref = useRef<HTMLDivElement>(null);

  const onKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {
    const container = ref.current;
    if (!container) return;
    const rows = Array.from(container.querySelectorAll<HTMLElement>("[data-json-row]"));
    const current = (event.target as HTMLElement).closest<HTMLElement>("[data-json-row]");
    if (!current) return;
    const index = rows.indexOf(current);
    const path = current.dataset.path!;
    const isBranch = current.hasAttribute("aria-expanded");
    const open = current.getAttribute("aria-expanded") === "true";
    const focusRow = (row: HTMLElement | undefined) => {
      if (!row) return;
      tree.setFocused(row.dataset.path!);
      row.focus();
    };
    switch (event.key) {
      case "ArrowDown":
        focusRow(rows[index + 1]);
        break;
      case "ArrowUp":
        focusRow(rows[index - 1]);
        break;
      case "Home":
        focusRow(rows[0]);
        break;
      case "End":
        focusRow(rows[rows.length - 1]);
        break;
      case "ArrowRight":
        if (!isBranch) return;
        if (!open) tree.setExpanded(path, true);
        else focusRow(rows[index + 1]);
        break;
      case "ArrowLeft": {
        if (isBranch && open) {
          tree.setExpanded(path, false);
          break;
        }
        const parent = current.dataset.parent;
        if (parent) focusRow(rows.find((row) => row.dataset.path === parent));
        break;
      }
      case "Enter":
      case " ":
        tree.select(path);
        if (isBranch) tree.setExpanded(path, !open);
        break;
      default:
        return;
    }
    event.preventDefault();
  };

  return useRender({
    defaultTagName: "div",
    render: render as useRender.RenderProp,
    ref,
    state: {},
    props: mergeProps<"div">(
      {
        role: "tree",
        onKeyDown,
        children: (
          <JsonTreeNode
            node={tree.root}
            posinset={1}
            setsize={1}
            arrow={arrow}
            indentGuide={indentGuide}
            renderValue={renderValue}
          />
        ),
      },
      rest,
    ),
  });
}

/**
 * JsonTreeView — the `tree-view` recipe composed through Base UI's
 * `useRender` / `mergeProps` primitives into a hand-built JSON viewer.
 * `<JsonTreeView.Root data defaultExpandedDepth variant size>` parses the data
 * into a path-keyed tree and resolves the recipe once; `<JsonTreeView.Tree>`
 * renders it as a WAI-ARIA tree (`role="tree"` / `"treeitem"` / `"group"`,
 * `aria-expanded`, roving focus) with Up/Down to move, Right to expand or
 * enter, Left to collapse or exit, Home/End, and Enter/Space to toggle and
 * select. Values carry `data-type` and type colors. `expandedValue` /
 * `onExpandedChange` and `selectedValue` / `onSelectionChange` control state;
 * `quotesOnKeys`, `maxPreviewItems`, and `collapseStringsAfterLength` tune
 * the text; `arrow`, `indentGuide`, and `renderValue` on Tree tune the rows.
 * Composition per part via `render`.
 */
export const JsonTreeView = {
  Root: withProvider(RootNode, "root", "JsonTreeViewRoot"),
  Tree: withContext(
    TreeNode,
    (v) => [...resolveSlotStyles(treeViewRecipe.slots.tree, v), jsonStatic.tree],
    "JsonTreeViewTree",
  ),
};
```
