{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "json-viewer",
  "title": "JSON Viewer",
  "description": "Collapsible JSON tree in your theme tokens, with object IDs rendered as links and the date behind unix timestamps on hover.",
  "dependencies": [
    "lucide-react"
  ],
  "registryDependencies": [
    "hover-card",
    "https://dentil.dev/r/date.json?via=json-viewer"
  ],
  "files": [
    {
      "path": "components/dentil/json-viewer/json-viewer.tsx",
      "content": "'use client';\n\nimport { Check, ChevronRight, Copy } from 'lucide-react';\nimport { useEffect, useRef, useState, type ComponentProps, type ElementType, type ReactNode } from 'react';\n\nimport { HoverCard, HoverCardContent, HoverCardTrigger } from '@/components/ui/hover-card';\nimport { cn } from '@/lib/utils';\n\nimport { formatDateParts, formatDateTime } from '../date/format';\nimport { isTimestamp, parseTimestamp, type JsonKey } from './timestamps';\n\n/** Long enough to move from the value onto the hover card across the offset gap. */\nconst HOVER_CLOSE_MS = 150;\n\n/** Props passed to a custom `linkComponent`. Compatible with `next/link`, an adapted React Router `Link`, or a plain `<a>`. */\nexport type JsonViewerLinkProps = { href: string; className?: string; children?: ReactNode };\n\nexport type JsonViewerLinkComponent = ElementType<JsonViewerLinkProps>;\n\nexport type JsonViewerProps = Omit<ComponentProps<'div'>, 'children'> & {\n  /** Any JSON-serializable value. `undefined` and functions are skipped, and a `Date` renders as its ISO string. */\n  data: unknown;\n  /** Objects and arrays nested shallower than this start expanded. `0` starts with everything collapsed. */\n  defaultExpandDepth?: number;\n  /** Return a URL to render a string value as a link, such as an object ID. */\n  getHref?: (value: string, key: JsonKey) => string | undefined;\n  /** Renders links from `getHref`, e.g. `next/link`. Defaults to `'a'`. */\n  linkComponent?: JsonViewerLinkComponent;\n  /** Underline timestamps and show the date on hover. Pass a function to choose which values count. */\n  timestamps?: boolean | ((value: string | number, key: JsonKey) => boolean);\n  /** IANA time zone the hover card shows beside UTC. Omit it to use the runtime zone. */\n  timezone?: string;\n  /** BCP 47 language tag for the hover card. Omit it to use the runtime locale. */\n  locale?: string;\n  /** Show a button in the top-right corner that copies `data` as indented JSON. */\n  copy?: boolean;\n  /** Called with the copied text after it reaches the clipboard. */\n  onCopy?: (text: string) => void;\n};\n\ntype NodeOptions = {\n  defaultExpandDepth: number;\n  getHref?: JsonViewerProps['getHref'];\n  linkComponent: JsonViewerLinkComponent;\n  isTimestamp?: (value: string | number, key: JsonKey) => boolean;\n  timezone?: string;\n  locale?: string;\n};\n\nexport function JsonViewer({\n  data,\n  defaultExpandDepth = Infinity,\n  getHref,\n  linkComponent = 'a',\n  timestamps = true,\n  timezone,\n  locale,\n  copy = false,\n  onCopy,\n  className,\n  ...props\n}: JsonViewerProps) {\n  const options: NodeOptions = {\n    defaultExpandDepth,\n    getHref,\n    linkComponent,\n    isTimestamp: timestamps === true ? isTimestamp : timestamps || undefined,\n    timezone,\n    locale,\n  };\n\n  return (\n    <div\n      data-slot=\"json-viewer\"\n      className={cn(\n        'text-foreground font-mono text-xs leading-5 wrap-anywhere',\n        // A lone value fills the first row, so keep it clear of the button. A tree's first row is just a brace.\n        copy && 'relative',\n        copy && !entriesOf(data) && 'pr-6',\n        className\n      )}\n      {...props}>\n      <JsonNode value={data} depth={0} last options={options} />\n      {copy ? <CopyButton data={data} onCopy={onCopy} /> : null}\n    </div>\n  );\n}\n\nfunction CopyButton({ data, onCopy }: { data: unknown; onCopy?: (text: string) => void }) {\n  const [copied, setCopied] = useState(false);\n  const timeout = useRef<ReturnType<typeof setTimeout>>(undefined);\n\n  useEffect(() => () => clearTimeout(timeout.current), []);\n\n  return (\n    <button\n      type=\"button\"\n      data-slot=\"json-viewer-copy-button\"\n      aria-label={copied ? 'Copied' : 'Copy JSON'}\n      className=\"text-muted-foreground hover:bg-muted hover:text-foreground focus-visible:ring-ring/50 absolute top-0 right-0 inline-flex size-5 items-center justify-center rounded-sm transition-colors outline-none focus-visible:ring-[3px]\"\n      onClick={() => {\n        // Same rules as the tree: `undefined` and functions drop out, and a `Date` becomes its ISO string.\n        const text = JSON.stringify(data, null, 2) ?? 'null';\n        void navigator.clipboard.writeText(text).then(() => {\n          setCopied(true);\n          onCopy?.(text);\n          clearTimeout(timeout.current);\n          timeout.current = setTimeout(() => setCopied(false), 1500);\n        });\n      }}>\n      <Check\n        aria-hidden\n        className={cn(\n          'absolute size-3.5 transition-[opacity,scale] duration-150 motion-reduce:transition-none',\n          copied ? 'scale-100 opacity-100' : 'scale-50 opacity-0'\n        )}\n      />\n      <Copy\n        aria-hidden\n        className={cn(\n          'absolute size-3.5 transition-[opacity,scale] duration-150 motion-reduce:transition-none',\n          copied ? 'scale-50 opacity-0' : 'scale-100 opacity-100'\n        )}\n      />\n    </button>\n  );\n}\n\nfunction entriesOf(value: unknown): [string | number, unknown][] | null {\n  if (Array.isArray(value)) return value.map((item, index) => [index, item]);\n  if (value === null || typeof value !== 'object' || value instanceof Date) return null;\n  return Object.entries(value).filter(([, item]) => !isSkipped(item));\n}\n\nfunction isSkipped(value: unknown) {\n  return value === undefined || typeof value === 'function' || typeof value === 'symbol';\n}\n\nfunction Punctuation({ children }: { children: ReactNode }) {\n  return <span className=\"text-muted-foreground/70\">{children}</span>;\n}\n\nfunction Label({ name }: { name: JsonKey }) {\n  if (typeof name !== 'string') return null;\n  return (\n    <>\n      <span data-slot=\"json-viewer-key\" className=\"text-muted-foreground\">\n        {JSON.stringify(name)}\n      </span>\n      <Punctuation>: </Punctuation>\n    </>\n  );\n}\n\nfunction Gutter() {\n  return <span aria-hidden className=\"w-4 shrink-0\" />;\n}\n\nfunction JsonNode({\n  name,\n  value,\n  depth,\n  last,\n  options,\n}: {\n  name?: JsonKey;\n  value: unknown;\n  depth: number;\n  last: boolean;\n  options: NodeOptions;\n}) {\n  const [open, setOpen] = useState(depth < options.defaultExpandDepth);\n  const entries = entriesOf(value);\n  const comma = last ? null : <Punctuation>,</Punctuation>;\n\n  if (!entries) {\n    return (\n      <div data-slot=\"json-viewer-row\" className=\"flex\">\n        <Gutter />\n        <span className=\"min-w-0\">\n          <Label name={name} />\n          <Value name={name} value={isSkipped(value) ? null : value} options={options} />\n          {comma}\n        </span>\n      </div>\n    );\n  }\n\n  const [openBrace, closeBrace] = Array.isArray(value) ? ['[', ']'] : ['{', '}'];\n\n  if (entries.length === 0) {\n    return (\n      <div data-slot=\"json-viewer-row\" className=\"flex\">\n        <Gutter />\n        <span className=\"min-w-0\">\n          <Label name={name} />\n          <Punctuation>\n            {openBrace}\n            {closeBrace}\n          </Punctuation>\n          {comma}\n        </span>\n      </div>\n    );\n  }\n\n  const count = Array.isArray(value)\n    ? `${entries.length} ${entries.length === 1 ? 'item' : 'items'}`\n    : `${entries.length} ${entries.length === 1 ? 'key' : 'keys'}`;\n\n  return (\n    <div data-slot=\"json-viewer-node\">\n      <button\n        type=\"button\"\n        data-slot=\"json-viewer-row\"\n        aria-expanded={open}\n        onClick={() => setOpen((current) => !current)}\n        className=\"hover:bg-muted/60 focus-visible:ring-ring/50 flex w-full cursor-pointer rounded-sm text-left transition-colors outline-none focus-visible:ring-[3px]\">\n        <span aria-hidden className=\"text-muted-foreground flex h-[1lh] w-4 shrink-0 items-center justify-center\">\n          <ChevronRight\n            className={cn(\n              'size-3.5 transition-transform duration-150 ease-out motion-reduce:transition-none',\n              open && 'rotate-90'\n            )}\n          />\n        </span>\n        <span className=\"min-w-0\">\n          <Label name={name} />\n          <Punctuation>{openBrace}</Punctuation>\n          {open ? null : (\n            <>\n              <span className=\"text-muted-foreground\"> {count} </span>\n              <Punctuation>{closeBrace}</Punctuation>\n              {comma}\n            </>\n          )}\n        </span>\n      </button>\n      {open ? (\n        <>\n          <div className=\"ml-2 border-l pl-2\">\n            {entries.map(([key, item], index) => (\n              <JsonNode\n                key={key}\n                name={key}\n                value={item}\n                depth={depth + 1}\n                last={index === entries.length - 1}\n                options={options}\n              />\n            ))}\n          </div>\n          <div className=\"flex\">\n            <Gutter />\n            <span>\n              <Punctuation>{closeBrace}</Punctuation>\n              {comma}\n            </span>\n          </div>\n        </>\n      ) : null}\n    </div>\n  );\n}\n\nfunction Value({ name, value, options }: { name: JsonKey; value: unknown; options: NodeOptions }) {\n  if (value === null) return <span className=\"text-muted-foreground\">null</span>;\n  if (value instanceof Date) return <Value name={name} value={value.toISOString()} options={options} />;\n\n  if (typeof value === 'string') {\n    const text = JSON.stringify(value).slice(1, -1);\n    const href = options.getHref?.(value, name);\n    const date = options.isTimestamp?.(value, name) ? parseTimestamp(value) : null;\n    const Anchor = options.linkComponent;\n\n    return (\n      <>\n        <Punctuation>&quot;</Punctuation>\n        {href ? (\n          <Anchor\n            href={href}\n            className=\"text-primary decoration-primary/40 hover:decoration-primary underline underline-offset-2 transition-colors\">\n            {text}\n          </Anchor>\n        ) : date ? (\n          <Timestamp date={date} options={options}>\n            {text}\n          </Timestamp>\n        ) : (\n          text\n        )}\n        <Punctuation>&quot;</Punctuation>\n      </>\n    );\n  }\n\n  if (typeof value === 'number') {\n    const date = options.isTimestamp?.(value, name) ? parseTimestamp(value) : null;\n    return date ? (\n      <Timestamp date={date} options={options}>\n        {String(value)}\n      </Timestamp>\n    ) : (\n      String(value)\n    );\n  }\n\n  return String(value);\n}\n\nfunction Timestamp({ date, options, children }: { date: Date; options: NodeOptions; children: ReactNode }) {\n  const [open, setOpen] = useState(false);\n  const closeTimer = useRef<number | undefined>(undefined);\n\n  useEffect(() => () => window.clearTimeout(closeTimer.current), []);\n\n  const zone =\n    formatDateParts(date, { timezone: options.timezone })?.timezone ?? Intl.DateTimeFormat().resolvedOptions().timeZone;\n\n  function openCard() {\n    window.clearTimeout(closeTimer.current);\n    setOpen(true);\n  }\n\n  function closeCard() {\n    window.clearTimeout(closeTimer.current);\n    closeTimer.current = window.setTimeout(() => setOpen(false), HOVER_CLOSE_MS);\n  }\n\n  function handleOpenChange(next: boolean) {\n    window.clearTimeout(closeTimer.current);\n    setOpen(next);\n  }\n\n  return (\n    <HoverCard open={open} onOpenChange={handleOpenChange}>\n      <HoverCardTrigger asChild>\n        <button\n          type=\"button\"\n          data-slot=\"json-viewer-timestamp\"\n          className=\"hover:bg-muted cursor-default rounded-sm underline decoration-dotted underline-offset-2 transition-colors\"\n          onMouseEnter={openCard}\n          onMouseLeave={closeCard}>\n          {children}\n        </button>\n      </HoverCardTrigger>\n      <HoverCardContent\n        align=\"start\"\n        side=\"top\"\n        sideOffset={8}\n        className=\"w-auto p-3 font-sans\"\n        onMouseEnter={openCard}\n        onMouseLeave={closeCard}>\n        <dl className=\"grid grid-cols-[auto_1fr] gap-x-6 gap-y-1 text-sm\">\n          <dt className=\"text-muted-foreground\">{zone}</dt>\n          <dd className=\"text-right\">{formatDateTime(date, zone, options.locale)}</dd>\n          <dt className=\"text-muted-foreground\">UTC</dt>\n          <dd className=\"text-right\">{formatDateTime(date, 'UTC', options.locale)}</dd>\n        </dl>\n      </HoverCardContent>\n    </HoverCard>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/dentil/json-viewer/json-viewer.tsx"
    },
    {
      "path": "components/dentil/json-viewer/timestamps.ts",
      "content": "/** Object key, array index, or `undefined` for the root value. */\nexport type JsonKey = string | number | undefined;\n\nconst UNIX_SECONDS_MIN = 946_684_800; // 2000-01-01\nconst UNIX_SECONDS_MAX = 4_102_444_800; // 2100-01-01\n\nconst TIMESTAMP_KEY =\n  /^(created|updated|deleted|timestamp|expires|available_on|billing_cycle_anchor|period_start|period_end|current_period_start|current_period_end|cancel_at|due|start|end)$|_(at|date|time|timestamp|until|from|on)$|[a-z](At|Date|Time|Timestamp)$/;\nconst AMOUNT_KEY =\n  /(amount|total|subtotal|balance|price|fee|quantity|count|limit|offset|index|tax|credit|debit|percent)/i;\n\n/** Date and time, such as `2026-11-07T09:14:00Z`. A date alone has no instant to show, so it doesn't match. */\nconst ISO_DATE_TIME = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}/;\n\nfunction toInteger(value: string | number) {\n  if (typeof value === 'number') return Number.isInteger(value) ? value : undefined;\n  return /^-?\\d+$/.test(value) ? Number(value) : undefined;\n}\n\n/** Unix seconds for an integer, or an integer string, between 2000 and 2100 in seconds or milliseconds. */\nexport function toUnixSeconds(value: string | number): number | undefined {\n  const integer = toInteger(value);\n  if (integer === undefined) return undefined;\n  if (integer >= UNIX_SECONDS_MIN && integer <= UNIX_SECONDS_MAX) return integer;\n  if (integer >= UNIX_SECONDS_MIN * 1000 && integer <= UNIX_SECONDS_MAX * 1000) return Math.floor(integer / 1000);\n  return undefined;\n}\n\n/** The instant a timestamp value refers to: unix seconds, unix milliseconds or an ISO 8601 date and time. */\nexport function parseTimestamp(value: string | number): Date | null {\n  const seconds = toUnixSeconds(value);\n  if (seconds !== undefined) return new Date(seconds * 1000);\n  if (typeof value !== 'string' || !ISO_DATE_TIME.test(value)) return null;\n\n  const date = new Date(value);\n  return Number.isNaN(date.getTime()) ? null : date;\n}\n\n/**\n * The default test for which values show a date on hover. ISO date-times always match. A unix timestamp matches when\n * its key looks like a date (`created`, `paid_at`, `dueDate`), never when it looks like money or a count (`amount`,\n * `quantity`), and otherwise only as a bare number in seconds.\n */\nexport function isTimestamp(value: string | number, key: JsonKey): boolean {\n  if (typeof value === 'string' && ISO_DATE_TIME.test(value)) return parseTimestamp(value) !== null;\n  if (toUnixSeconds(value) === undefined) return false;\n\n  const name = typeof key === 'string' ? key : '';\n  if (name && TIMESTAMP_KEY.test(name)) return true;\n  if (name && AMOUNT_KEY.test(name)) return false;\n\n  return typeof value === 'number' && value >= UNIX_SECONDS_MIN && value <= UNIX_SECONDS_MAX;\n}\n",
      "type": "registry:lib",
      "target": "components/dentil/json-viewer/timestamps.ts"
    }
  ],
  "type": "registry:component"
}
