JSON Viewer
SaveA collapsible tree for tool inputs and outputs with type colored values, counts on folded objects and arrays, long string truncation, search, and copy value or copy path on every row.
- Category
- AI elements
- Version
- 0.1.0
- Frameworks
- Next.js, Vite + React
- Styling
- Tailwind CSS v4
Preview
JSON Viewer preview
search_docsoutput
Object, 5 keys
- query: "refund policy annual plan"
- took_ms: 184
- truncated: false
- results: 2 items
- 0: 7 keys
- id: "kb_4821"
- title: "Refunds for annual plans"
- url: "https://help.northwind.dev/billing/refunds-annual"
- score: 0.91
- excerpt: "Annual plans can be refunded in full within 30 days of purchase. After 30 days w…"
- tags: […]2 items
- updated_at: "2026-10-02T14:12:00Z"
- 1: 7 keys
- id: "kb_3307"
- title: "Switching from monthly to annual billing"
- url: "https://help.northwind.dev/billing/switch-annual"
- score: 0.74
- excerpt: "When you switch mid-cycle, the remaining days of the monthly plan are credited t…"
- tags: […]1 item
- updated_at: null
- filters: 3 keys
- locale: "en-US"
- audience: "admins"
- include_drafts: false
Installation
npx @shakenui/cli add json-viewerReview the plan first. A dry run lists every file and package without changing anything:
npx @shakenui/cli add json-viewer --dry-runUsage
json-viewer-example.tsx
"use client";
import { JsonViewer } from "@/components/shaken/agent/json-viewer";
const output = {
query: "refund policy annual plan",
took_ms: 184,
truncated: false,
results: [
{
id: "kb_4821",
title: "Refunds for annual plans",
url: "https://help.northwind.dev/billing/refunds-annual",
score: 0.91,
excerpt:
"Annual plans can be refunded in full within 30 days of purchase. After 30 days we refund the unused months as account credit, prorated to the day, and the invoice is reissued as a correction so finance teams see one clean document.",
tags: ["billing", "refunds"],
updated_at: "2026-10-02T14:12:00Z",
},
{
id: "kb_3307",
title: "Switching from monthly to annual billing",
url: "https://help.northwind.dev/billing/switch-annual",
score: 0.74,
excerpt: "When you switch mid-cycle, the remaining days of the monthly plan are credited toward the first annual invoice.",
tags: ["billing"],
updated_at: null,
},
],
filters: { locale: "en-US", audience: "admins", include_drafts: false },
};
export default function JsonViewerExample() {
return (
<div className="w-full max-w-xl">
<p className="mb-2 flex items-baseline gap-2 text-sm">
<span className="font-mono text-[13px] font-medium text-zinc-950 dark:text-white">search_docs</span>
<span className="text-zinc-500">output</span>
</p>
<JsonViewer data={output} rootName="output" label="search_docs output" defaultExpandDepth={2} searchable maxHeight={420} />
</div>
);
}States
Every state, rendered from local fixture data.
JSON Viewer states
Tool input without the toolbar
- repo: "northwind/billing"
- base: "main"
- title: "Round prorated invoices once"
- draft: true
- reviewers: 1 item
- 0: "priya-raman"
Array root, starts collapsed
Array, 2 items
- 0: {…}3 keys
- 1: {…}4 keys
A bare value
- "Pull request #482 opened against main."
Empty object
- Empty object
API
| Prop | Type | Default | Description |
|---|---|---|---|
| data | unknown | — | Any JSON-like value. Dates and bigints display as text. |
| defaultExpandDepth | number | 1 | Levels open at first. 0 starts collapsed, Infinity opens everything. |
| rootName | string | "" | Prefix for copied paths, for example input gives input.filters.status. |
| label | string | "JSON" | Accessible name of the tree. |
| maxStringLength | number | 80 | Longer strings are cut with a control that shows the rest. |
| searchable | boolean | false | Shows a search field that highlights matching keys and values, opens their branches, and counts matches. |
| search / onSearchChange | string | — | Controlled search text. |
| toolbar | boolean | true | Shows the summary with Expand all and Collapse. |
| onCopy | (text, kind: "value" | "path") => void | — | Called after a copy. |
| maxHeight | CSS max-height | — | Caps the tree height; it scrolls past this. |
Accessibility
- Follows the ARIA tree pattern: role="tree" with flat treeitems carrying aria-level, aria-setsize, aria-posinset, and aria-expanded on branches, and a single roving tab stop.
- Up and Down move between rows, Right opens a branch or enters it, Left closes it or moves to the parent, Home and End jump, Enter and Space toggle (or show a long string in full), and * opens every sibling branch.
- Mod+C copies the focused value and Mod+Shift+C its path (declared with aria-keyshortcuts); a polite live region confirms each copy. The hover copy buttons stay out of the tab order because the shortcuts cover them.
- In the search field, Enter or Down moves focus to the first match and Escape clears it; the match count is announced.
- Branches opened with the pointer reveal their children with a short stagger; opening from the keyboard is instant, and with reduced motion every reveal and chevron turn is instant.
Files
Installed into src/components/shaken, or components/shaken when the project has no src directory.
src/components/shaken/agent/json-viewer.tsxjson-viewer- npm packages: noneReact and Tailwind CSS v4 required
Source
The exact source the CLI installs, from /r/items/react/json-viewer/0.1.0.json.
agent/json-viewer.tsxShowHide
agent/json-viewer.tsx
"use client";
import { type ComponentProps, type CSSProperties, type KeyboardEvent, type ReactNode, useEffect, useId, useMemo, useRef, useState } from "react";
function cx(...classes: (string | false | null | undefined)[]) {
return classes.filter(Boolean).join(" ");
}
const ease = "ease-[cubic-bezier(0.23,1,0.32,1)]";
/*
* JSON viewer: a collapsible tree for tool inputs and outputs.
*
* Rows are a flat ARIA tree (role="tree", treeitems with aria-level) with a roving tab stop.
* Opening a branch with the pointer reveals its children with a short stagger; opening it from
* the keyboard is instant, and so is everything under reduced motion.
*/
type Kind = "object" | "array" | "string" | "number" | "boolean" | "null" | "undefined" | "other";
function kindOf(value: unknown): Kind {
if (value === null) return "null";
if (Array.isArray(value)) return "array";
if (value instanceof Date) return "other";
switch (typeof value) {
case "object":
return "object";
case "string":
return "string";
case "number":
case "bigint":
return "number";
case "boolean":
return "boolean";
case "undefined":
return "undefined";
default:
return "other";
}
}
const isBranch = (kind: Kind) => kind === "object" || kind === "array";
function entriesOf(value: unknown): [string | number, unknown][] {
if (Array.isArray(value)) return value.map((item, index) => [index, item]);
if (value && typeof value === "object") return Object.entries(value as Record<string, unknown>);
return [];
}
/** A JSON pointer segment, so ids never collide whatever the keys contain. */
const segment = (key: string | number) => `/${String(key).replace(/~/g, "~0").replace(/\//g, "~1")}`;
const identifier = /^[A-Za-z_$][\w$]*$/;
/** The path a developer would type: `results[0].title`, `headers["content-type"]`. */
function pathText(parent: string, key: string | number): string {
if (typeof key === "number") return `${parent}[${key}]`;
if (identifier.test(key)) return parent ? `${parent}.${key}` : key;
return `${parent}[${JSON.stringify(key)}]`;
}
function preview(value: unknown): string {
const kind = kindOf(value);
if (kind === "string") return value as string;
if (kind === "undefined") return "undefined";
if (value instanceof Date) return value.toISOString();
if (typeof value === "bigint") return `${value}n`;
if (typeof value === "function") return `ƒ ${(value as { name?: string }).name || "anonymous"}()`;
return String(value);
}
/** What copying a value puts on the clipboard: raw text for strings, formatted JSON for the rest. */
function copyText(value: unknown): string {
if (typeof value === "string") return value;
if (typeof value === "bigint") return String(value);
try {
return JSON.stringify(value, null, 2) ?? String(value);
} catch {
return String(value);
}
}
interface Row {
id: string;
key: string | number | null;
value: unknown;
kind: Kind;
path: string;
parent: string | null;
level: number;
setSize: number;
position: number;
count: number;
open: boolean;
}
function flatten(value: unknown, open: Set<string>, rootPath: string): Row[] {
const out: Row[] = [];
const walk = (node: unknown, id: string, path: string, level: number) => {
const entries = entriesOf(node);
entries.forEach(([key, child], index) => {
const childId = id + segment(key);
const kind = kindOf(child);
const branch = isBranch(kind);
const isOpen = branch && open.has(childId);
out.push({
id: childId,
key,
value: child,
kind,
path: pathText(path, key),
parent: id || null,
level,
setSize: entries.length,
position: index + 1,
count: branch ? entriesOf(child).length : 0,
open: isOpen,
});
if (isOpen) walk(child, childId, pathText(path, key), level + 1);
});
};
if (isBranch(kindOf(value))) walk(value, "", rootPath, 1);
else out.push({ id: "", key: null, value, kind: kindOf(value), path: rootPath, parent: null, level: 1, setSize: 1, position: 1, count: 0, open: false });
return out;
}
/** Every branch id down to `depth` levels (Infinity for all), stopping after `limit` nodes. */
function branchesTo(value: unknown, depth: number, limit = 5000): string[] {
const out: string[] = [];
let seen = 0;
const walk = (node: unknown, id: string, level: number) => {
for (const [key, child] of entriesOf(node)) {
if (++seen > limit) return;
if (!isBranch(kindOf(child)) || level > depth) continue;
const childId = id + segment(key);
out.push(childId);
walk(child, childId, level + 1);
}
};
walk(value, "", 1);
return out;
}
/** Ids of matching nodes and of every branch above them. */
function searchTree(value: unknown, query: string, limit = 10000) {
const matches = new Set<string>();
const ancestors = new Set<string>();
if (!query) return { matches, ancestors };
const q = query.toLowerCase();
let seen = 0;
const walk = (node: unknown, id: string, chain: string[]) => {
for (const [key, child] of entriesOf(node)) {
if (++seen > limit) return;
const childId = id + segment(key);
const kind = kindOf(child);
const hit = (typeof key === "string" && key.toLowerCase().includes(q)) || (!isBranch(kind) && preview(child).toLowerCase().includes(q));
if (hit) {
matches.add(childId);
for (const ancestor of chain) ancestors.add(ancestor);
}
if (isBranch(kind)) walk(child, childId, [...chain, childId]);
}
};
walk(value, "", []);
return { matches, ancestors };
}
export interface JsonViewerProps extends Omit<ComponentProps<"div">, "children" | "onCopy"> {
/** Any JSON-like value: objects, arrays, and primitives. Dates and bigints display as text. */
data: unknown;
/** Levels open at first. 0 starts fully collapsed; `Infinity` opens everything. */
defaultExpandDepth?: number;
/** Prefix for copied paths, for example `input` gives `input.filters.status`. */
rootName?: string;
/** Accessible name of the tree. */
label?: string;
/** Strings longer than this are cut with a control to show the rest. */
maxStringLength?: number;
/** Shows a search field that highlights matching keys and values and opens their branches. */
searchable?: boolean;
/** Controlled search text, for driving the highlight from outside. */
search?: string;
onSearchChange?: (search: string) => void;
/** Shows the summary, Expand all, and Collapse bar. */
toolbar?: boolean;
/** Called after a value or a path is copied. */
onCopy?: (text: string, kind: "value" | "path") => void;
/** Caps the tree height; it scrolls past this. */
maxHeight?: CSSProperties["maxHeight"];
}
/** A collapsible, searchable tree for JSON such as tool inputs and outputs, with copy value and copy path on every row. */
export function JsonViewer({
data,
defaultExpandDepth = 1,
rootName = "",
label = "JSON",
maxStringLength = 80,
searchable = false,
search: searchProp,
onSearchChange,
toolbar = true,
onCopy,
maxHeight,
className,
...props
}: JsonViewerProps) {
const [open, setOpen] = useState<Set<string>>(() => new Set(branchesTo(data, defaultExpandDepth)));
const [localSearch, setLocalSearch] = useState("");
const search = (searchProp ?? localSearch).trim();
const found = useMemo(() => searchTree(data, search), [data, search]);
const visibleOpen = useMemo(() => (search ? new Set([...open, ...found.ancestors]) : open), [open, found, search]);
const rows = useMemo(() => flatten(data, visibleOpen, rootName), [data, visibleOpen, rootName]);
const [focused, setFocused] = useState<string | null>(null);
const [expandedStrings, setExpandedStrings] = useState<Set<string>>(() => new Set());
// Rows revealed by the last pointer action stagger in; keyboard changes stay instant.
const [reveal, setReveal] = useState<string | null>(null);
const [announcement, setAnnouncement] = useState("");
const [copied, setCopied] = useState<{ id: string; kind: "value" | "path" } | null>(null);
const items = useRef(new Map<string, HTMLLIElement>());
const timer = useRef<ReturnType<typeof setTimeout>>(undefined);
const searchId = useId();
useEffect(() => () => clearTimeout(timer.current), []);
const tabStop = rows.find((row) => row.id === focused)?.id ?? rows[0]?.id;
const rootKind = kindOf(data);
const rootCount = entriesOf(data).length;
function setSearch(value: string) {
if (searchProp === undefined) setLocalSearch(value);
onSearchChange?.(value);
}
function toggle(row: Row, next = !row.open, pointer = false) {
if (!isBranch(row.kind) || next === row.open) return;
setOpen((current) => {
const copy = new Set(current);
if (next) copy.add(row.id);
else {
// Closing also drops open descendants so reopening starts tidy.
for (const id of copy) if (id === row.id || id.startsWith(`${row.id}/`)) copy.delete(id);
}
return copy;
});
setReveal(next && pointer ? row.id : null);
}
function setAll(next: boolean, pointer: boolean) {
setOpen(new Set(next ? branchesTo(data, Infinity) : []));
setReveal(next && pointer ? "*" : null);
if (!next) setFocused(null);
}
async function copy(row: Row, kind: "value" | "path") {
const text = kind === "value" ? copyText(row.value) : row.path;
try {
await navigator.clipboard.writeText(text);
setCopied({ id: row.id, kind });
setAnnouncement(kind === "value" ? "Copied value" : `Copied path ${text}`);
clearTimeout(timer.current);
timer.current = setTimeout(() => setCopied(null), 1400);
onCopy?.(text, kind);
} catch {
setAnnouncement("Could not copy");
}
}
function focusRow(id: string | undefined) {
if (id === undefined) return;
setFocused(id);
items.current.get(id)?.focus();
}
function onKeyDown(event: KeyboardEvent<HTMLLIElement>, row: Row, index: number) {
const mod = event.metaKey || event.ctrlKey;
if (mod && event.key.toLowerCase() === "c") {
if (window.getSelection()?.toString()) return;
event.preventDefault();
void copy(row, event.shiftKey ? "path" : "value");
return;
}
if (mod || event.altKey) return;
const branch = isBranch(row.kind);
switch (event.key) {
case "ArrowDown":
focusRow(rows[index + 1]?.id);
break;
case "ArrowUp":
focusRow(rows[index - 1]?.id);
break;
case "Home":
focusRow(rows[0]?.id);
break;
case "End":
focusRow(rows[rows.length - 1]?.id);
break;
case "ArrowRight":
if (branch && !row.open) toggle(row, true);
else if (branch && row.count > 0) focusRow(rows[index + 1]?.id);
else return;
break;
case "ArrowLeft":
if (branch && row.open) toggle(row, false);
else if (row.parent) focusRow(row.parent);
else return;
break;
case "Enter":
case " ":
if (branch) toggle(row);
else if (row.kind === "string" && (row.value as string).length > maxStringLength) toggleString(row.id);
else return;
break;
case "*": {
const siblings = rows.filter((other) => other.parent === row.parent && isBranch(other.kind));
setOpen((current) => new Set([...current, ...siblings.map((other) => other.id)]));
setReveal(null);
break;
}
default:
return;
}
event.preventDefault();
}
function toggleString(id: string) {
setExpandedStrings((current) => {
const copy = new Set(current);
if (copy.has(id)) copy.delete(id);
else copy.add(id);
return copy;
});
}
// Index among the rows the last pointer action revealed, for the stagger delay.
let revealIndex = 0;
return (
<div
className={cx(
"overflow-hidden rounded-lg border border-zinc-950/[0.07] bg-zinc-950/[0.02] text-left text-zinc-950 dark:border-white/[0.08] dark:bg-transparent dark:text-white",
className,
)}
{...props}
>
{searchable || (toolbar && isBranch(rootKind) && rootCount > 0) ? (
<div className="flex flex-wrap items-center gap-x-2 gap-y-1.5 border-b border-zinc-950/[0.07] px-2 py-1.5 dark:border-white/[0.08]">
<span className="min-w-0 flex-1 truncate pl-1 text-xs text-zinc-500">
{searchable && search ? (
<span aria-live="polite">
{found.matches.size} {found.matches.size === 1 ? "match" : "matches"}
</span>
) : isBranch(rootKind) ? (
<>
{rootKind === "array" ? "Array" : "Object"}, {rootCount} {rootKind === "array" ? (rootCount === 1 ? "item" : "items") : rootCount === 1 ? "key" : "keys"}
</>
) : (
"Value"
)}
</span>
{searchable ? (
<label htmlFor={searchId} className="relative order-last w-full min-[420px]:order-none min-[420px]:w-44">
<span className="sr-only">Search keys and values</span>
<svg aria-hidden="true" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" className="pointer-events-none absolute top-1/2 left-2 size-3.5 -translate-y-1/2 text-zinc-500">
<circle cx="7" cy="7" r="4.25" />
<path d="m10.25 10.25 3 3" />
</svg>
<input
id={searchId}
type="search"
value={searchProp ?? localSearch}
onChange={(event) => setSearch(event.target.value)}
onKeyDown={(event) => {
if (event.key === "Enter" || event.key === "ArrowDown") {
event.preventDefault();
const first = rows.find((row) => found.matches.has(row.id)) ?? rows[0];
focusRow(first?.id);
} else if (event.key === "Escape" && (searchProp ?? localSearch)) {
event.preventDefault();
setSearch("");
}
}}
placeholder="Search"
autoComplete="off"
spellCheck={false}
className={cx(
"h-7 w-full rounded-md border border-zinc-950/10 bg-white pr-2 pl-7 font-sans text-xs text-zinc-950 placeholder:text-zinc-500 [&::-webkit-search-cancel-button]:hidden",
"transition-[border-color] duration-150 ease-out hover:border-zinc-950/20 motion-reduce:transition-none",
"dark:border-white/10 dark:bg-black dark:text-white dark:hover:border-white/20",
"focus-visible:border-sky-500/60 focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-0 focus-visible:outline-sky-500/40",
)}
/>
</label>
) : null}
{toolbar && isBranch(rootKind) && rootCount > 0 ? (
<span className="flex items-center">
<ToolbarButton onClick={(event) => setAll(true, event.detail > 0)}>Expand all</ToolbarButton>
<ToolbarButton onClick={() => setAll(false, false)}>Collapse</ToolbarButton>
</span>
) : null}
</div>
) : null}
<ul
role="tree"
aria-label={label}
aria-keyshortcuts="Control+C Meta+C Control+Shift+C Meta+Shift+C"
style={{ maxHeight }}
className={cx("overflow-auto p-1 font-mono text-xs leading-6", maxHeight !== undefined && "overscroll-contain")}
>
{rows.map((row, index) => {
const branch = isBranch(row.kind);
const match = found.matches.has(row.id);
const revealed =
reveal !== null && (reveal === "*" ? row.level > 1 : row.id.startsWith(`${reveal}/`)) ? revealIndex++ : -1;
const isCopied = copied?.id === row.id ? copied.kind : null;
return (
<li
key={row.id || "root"}
ref={(el) => {
if (el) items.current.set(row.id, el);
else items.current.delete(row.id);
}}
role="treeitem"
aria-level={row.level}
aria-setsize={row.setSize}
aria-posinset={row.position}
aria-expanded={branch ? row.open : undefined}
tabIndex={row.id === tabStop ? 0 : -1}
onFocus={() => setFocused(row.id)}
onKeyDown={(event) => onKeyDown(event, row, index)}
onClick={(event) => {
if ((event.target as HTMLElement).closest("button")) return;
if (branch) toggle(row, !row.open, true);
}}
// Delays line up with transition-[background-color,opacity,translate]: hover stays instant.
style={revealed >= 0 ? { transitionDelay: `0ms, ${Math.min(revealed, 12) * 16}ms, ${Math.min(revealed, 12) * 16}ms` } : undefined}
className={cx(
"group/row relative flex min-h-6 items-start rounded-md pr-1",
branch && "cursor-pointer",
"hover:bg-zinc-950/[0.04] motion-reduce:transition-none dark:hover:bg-white/[0.06]",
revealed < 0 && "transition-[background-color] duration-150 ease-out",
"focus-visible:outline-2 focus-visible:outline-solid focus-visible:-outline-offset-2 focus-visible:outline-sky-500",
revealed >= 0 && cx("transition-[background-color,opacity,translate] duration-[260ms] motion-reduce:transition-none", ease, "starting:-translate-y-1 starting:opacity-0"),
)}
>
{/* Indent guides: one hairline per ancestor level, through the chevron's center. */}
{Array.from({ length: row.level - 1 }, (_, level) => (
<span key={level} aria-hidden="true" style={{ left: `${level * 16 + 12}px` }} className="absolute inset-y-0 w-px bg-zinc-950/[0.08] dark:bg-white/[0.09]" />
))}
<span aria-hidden="true" style={{ width: `${(row.level - 1) * 16 + 4}px` }} className="shrink-0" />
<span aria-hidden="true" className="flex h-6 w-4 shrink-0 items-center justify-center">
{branch ? (
<svg viewBox="0 0 16 16" fill="none" className={cx("size-3.5 text-zinc-400 transition-[rotate] duration-150 dark:text-zinc-500", ease, row.open && "rotate-90", "motion-reduce:transition-none")}>
<path d="m6.25 4.5 3.5 3.5-3.5 3.5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
</svg>
) : null}
</span>
<span className="min-w-0 flex-1 pl-1 wrap-anywhere">
{row.key !== null ? (
<>
<span className={typeof row.key === "number" ? "text-zinc-500 tabular-nums" : "text-zinc-800 dark:text-zinc-200"}>
<Highlight text={String(row.key)} query={typeof row.key === "string" ? search : ""} />
</span>
<span className="text-zinc-400 dark:text-zinc-600">: </span>
</>
) : null}
<Value
row={row}
query={match ? search : ""}
maxStringLength={maxStringLength}
expanded={expandedStrings.has(row.id)}
onToggleString={() => toggleString(row.id)}
/>
</span>
<span
className={cx(
"flex shrink-0 items-center gap-0.5 pl-2 opacity-0 transition-opacity duration-150 ease-out motion-reduce:transition-none",
"group-hover/row:opacity-100 group-focus-visible/row:opacity-100 [@media(hover:none)]:opacity-100",
isCopied && "opacity-100",
)}
>
<RowAction label={`Copy value of ${row.path || "root"}`} done={isCopied === "value"} onClick={() => copy(row, "value")}>
<rect x="5.25" y="5.25" width="8" height="8" rx="1.75" />
<path d="M10.75 5.25V3.5c0-.97-.78-1.75-1.75-1.75H3.5c-.97 0-1.75.78-1.75 1.75V9c0 .97.78 1.75 1.75 1.75h1.75" />
</RowAction>
{row.path ? (
<RowAction label={`Copy path ${row.path}`} done={isCopied === "path"} onClick={() => copy(row, "path")}>
<path d="M6.75 9.25a2.75 2.75 0 0 0 3.9 0l2-2a2.75 2.75 0 0 0-3.9-3.9l-.6.6M9.25 6.75a2.75 2.75 0 0 0-3.9 0l-2 2a2.75 2.75 0 0 0 3.9 3.9l.6-.6" />
</RowAction>
) : null}
</span>
</li>
);
})}
{rows.length === 0 ? (
<li role="none" className="px-2 py-1 font-sans text-zinc-500">
{rootKind === "array" ? "Empty array" : "Empty object"}
</li>
) : null}
</ul>
<span className="sr-only" aria-live="polite">
{announcement}
</span>
</div>
);
}
const valueTone: Record<Kind, string> = {
string: "text-emerald-700 dark:text-emerald-400",
number: "text-sky-700 dark:text-sky-400",
boolean: "text-amber-700 dark:text-amber-300",
null: "text-zinc-500",
undefined: "text-zinc-500",
other: "text-zinc-700 dark:text-zinc-300",
object: "",
array: "",
};
function Value({
row,
query,
maxStringLength,
expanded,
onToggleString,
}: {
row: Row;
query: string;
maxStringLength: number;
expanded: boolean;
onToggleString: () => void;
}) {
if (row.kind === "object" || row.kind === "array") {
const unit = row.kind === "array" ? (row.count === 1 ? "item" : "items") : row.count === 1 ? "key" : "keys";
const [open, close] = row.kind === "array" ? ["[", "]"] : ["{", "}"];
return (
<>
{row.open && row.count > 0 ? null : <span className="mr-2 text-zinc-400 dark:text-zinc-500">{row.count === 0 ? `${open}${close}` : `${open}…${close}`}</span>}
<span className="font-sans text-[11px] text-zinc-500 tabular-nums">
{row.count} {unit}
</span>
</>
);
}
if (row.kind === "string") {
const text = row.value as string;
const long = text.length > maxStringLength;
const shown = long && !expanded ? text.slice(0, maxStringLength) : text;
return (
<>
<span className={cx(valueTone.string, expanded ? "whitespace-pre-wrap" : "")}>
"<Highlight text={expanded ? shown : JSON.stringify(shown).slice(1, -1)} query={query} />
{long && !expanded ? "…" : ""}"
</span>
{long ? (
<button
type="button"
tabIndex={-1}
onClick={onToggleString}
className={cx(
"ml-2 cursor-pointer rounded px-1 font-sans text-[11px] text-zinc-500 tabular-nums",
"transition-colors duration-150 ease-out hover:bg-zinc-950/[0.05] hover:text-zinc-950 motion-reduce:transition-none dark:hover:bg-white/[0.08] dark:hover:text-white",
)}
>
{expanded ? "Show less" : `${(text.length - maxStringLength).toLocaleString("en-US")} more`}
</button>
) : null}
</>
);
}
return (
<span className={valueTone[row.kind]}>
<Highlight text={preview(row.value)} query={query} />
</span>
);
}
function Highlight({ text, query }: { text: string; query: string }) {
if (!query) return <>{text}</>;
const lower = text.toLowerCase();
const q = query.toLowerCase();
const parts: ReactNode[] = [];
let from = 0;
let at = lower.indexOf(q);
while (at >= 0) {
if (at > from) parts.push(text.slice(from, at));
parts.push(
<mark key={at} className="rounded-[3px] bg-sky-500/20 text-inherit shadow-[0_0_0_1px_rgb(14_165_233/0.35)] dark:bg-sky-400/20">
{text.slice(at, at + q.length)}
</mark>,
);
from = at + q.length;
at = lower.indexOf(q, from);
}
if (from < text.length) parts.push(text.slice(from));
return <>{parts}</>;
}
function ToolbarButton(props: ComponentProps<"button">) {
return (
<button
type="button"
{...props}
className={cx(
"inline-flex h-7 cursor-pointer items-center rounded-md px-2 font-sans text-xs font-medium whitespace-nowrap text-zinc-600 select-none",
"transition-[background-color,color,scale] duration-150 ease-out active:duration-100 motion-safe:active:scale-[0.97] motion-reduce:transition-none",
"hover:bg-zinc-950/[0.04] hover:text-zinc-950 dark:text-zinc-400 dark:hover:bg-white/[0.06] dark:hover:text-white",
"focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-sky-500",
)}
/>
);
}
/** A small row action. Out of the tab order: the tree's Mod+C and Mod+Shift+C shortcuts cover the keyboard. */
function RowAction({ label, done, onClick, children }: { label: string; done: boolean; onClick: () => void; children: ReactNode }) {
return (
<button
type="button"
tabIndex={-1}
aria-label={label}
title={label}
onClick={onClick}
className={cx(
"inline-flex size-6 cursor-pointer items-center justify-center rounded-md text-zinc-500",
"transition-[background-color,color,scale] duration-150 ease-out active:duration-100 motion-safe:active:scale-[0.94] motion-reduce:transition-none",
"hover:bg-zinc-950/[0.06] hover:text-zinc-950 dark:hover:bg-white/[0.08] dark:hover:text-white",
)}
>
<svg aria-hidden="true" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" className="size-3.5">
{done ? (
<path
d="m3.75 8.5 2.75 2.75 5.75-6.5"
pathLength={1}
className={cx("text-emerald-600 [stroke-dasharray:1] [stroke-dashoffset:0] transition-[stroke-dashoffset] duration-200 dark:text-emerald-400 motion-reduce:transition-none", ease, "starting:[stroke-dashoffset:1]")}
/>
) : (
children
)}
</svg>
</button>
);
}