{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "db-readout",
  "title": "dB Readout",
  "description": "A numeric level label that updates at a readable rate, with a reserved width so the layout never shifts.",
  "registryDependencies": [
    "@audiocn/core",
    "@audiocn/use-frame-source"
  ],
  "files": [
    {
      "path": "components/ui/db-readout.tsx",
      "content": "\"use client\";\n\nimport { useEffect, useEffectEvent, useRef } from \"react\";\nimport type { ComponentProps, CSSProperties } from \"react\";\n\nimport { useFrameSource } from \"@/hooks/use-frame-source\";\nimport { formatDb, SILENCE_DB } from \"@/lib/audio/decibels\";\nimport type { FrameSource, MeterFrame, MeterZone } from \"@/lib/audio/types\";\nimport { DEFAULT_ZONES, zoneForDb } from \"@/lib/audio/zones\";\nimport { cn } from \"@/lib/utils\";\n\nconst DEFAULT_INTERVAL_MS = 250;\nconst DEFAULT_FLOOR_DB = -60;\n/** Two-digit levels, the widest a meter usually shows, on either side of 0. */\nconst WIDEST_MAGNITUDE_DB = 88.8;\n\nconst noop = () => {\n  // Nothing to wake before the ticker starts.\n};\n\n/**\n * An interval that stops itself once `step` reports nothing left to do, and\n * that `wake` starts again: a readout whose source went quiet costs no timer.\n */\nconst createTicker = (step: () => boolean, intervalMs: number) => {\n  let timer: ReturnType<typeof setInterval> | null = null;\n  const stop = () => {\n    if (timer !== null) {\n      clearInterval(timer);\n      timer = null;\n    }\n  };\n  const wake = () => {\n    if (timer === null) {\n      timer = setInterval(() => {\n        if (!step()) {\n          stop();\n        }\n      }, intervalMs);\n    }\n  };\n  return { stop, wake };\n};\n\nexport interface DbReadoutProps extends Omit<\n  ComponentProps<\"span\">,\n  \"children\"\n> {\n  /** A level in dB, for declarative use. */\n  value?: number;\n  /** A meter source; the readout updates itself without re-rendering React. */\n  source?: FrameSource<MeterFrame> | null;\n  /** Which measurement to show. Default `peak`. */\n  measure?: \"peak\" | \"rms\";\n  /** A channel index, or `max` for the loudest channel. Default `max`. */\n  channel?: number | \"max\";\n  /** How often the text changes. Default 250 ms. */\n  intervalMs?: number;\n  /** Show the highest value seen within this window. Default 0. */\n  holdMs?: number;\n  /** Digits after the decimal point. Default 1. */\n  decimals?: number;\n  /** Append \" dB\". Default true. */\n  unit?: boolean;\n  /** At or below this level, show \"−∞\". Default −60. */\n  floorDb?: number;\n  /** Zones used for `data-zone`. */\n  zones?: MeterZone[];\n  /** Replaces all formatting. */\n  format?: (db: number) => string;\n}\n\n/** The level a readout shows from one frame. */\nexport const readChannel = (\n  frame: MeterFrame,\n  measure: \"peak\" | \"rms\",\n  channel: number | \"max\"\n) => {\n  const read = (index: number) => {\n    const level = frame.channels[index];\n    if (!level) {\n      return SILENCE_DB;\n    }\n    return measure === \"rms\" ? (level.rmsDb ?? level.peakDb) : level.peakDb;\n  };\n  if (channel !== \"max\") {\n    return read(channel);\n  }\n  let loudest = SILENCE_DB;\n  for (let index = 0; index < frame.channels.length; index += 1) {\n    loudest = Math.max(loudest, read(index));\n  }\n  return loudest;\n};\n\nexport const DbReadout = ({\n  value,\n  source,\n  measure = \"peak\",\n  channel = \"max\",\n  intervalMs = DEFAULT_INTERVAL_MS,\n  holdMs = 0,\n  decimals = 1,\n  unit = true,\n  floorDb = DEFAULT_FLOOR_DB,\n  zones = DEFAULT_ZONES,\n  format,\n  className,\n  style,\n  ...props\n}: DbReadoutProps) => {\n  const elementRef = useRef<HTMLSpanElement>(null);\n  const peakRef = useRef(SILENCE_DB);\n  const peakAtRef = useRef(0);\n  const shownRef = useRef<string | null>(null);\n\n  const render = (db: number) =>\n    format ? format(db) : formatDb(db, { decimals, floorDb, unit });\n\n  const initialDb = value ?? SILENCE_DB;\n  // Size for the widest text the readout can show, so it never changes width.\n  // Values at or below the floor read as −∞, so measure just above it too.\n  const justAboveFloor = Number.isFinite(floorDb)\n    ? floorDb + 10 ** -decimals\n    : -WIDEST_MAGNITUDE_DB;\n  const widest = Math.max(\n    ...[\n      SILENCE_DB,\n      justAboveFloor,\n      -WIDEST_MAGNITUDE_DB,\n      WIDEST_MAGNITUDE_DB,\n    ].map((db) => render(db).length)\n  );\n\n  // Frames since the last tick, and the wake for a ticker that went quiet.\n  const freshRef = useRef(false);\n  const wakeRef = useRef<() => void>(noop);\n\n  useFrameSource(source, (frame) => {\n    const db = readChannel(frame, measure, channel);\n    const now = performance.now();\n    if (db >= peakRef.current || now - peakAtRef.current > holdMs) {\n      peakRef.current = db;\n      peakAtRef.current = now;\n    }\n    freshRef.current = true;\n    wakeRef.current();\n  });\n\n  // Reads the latest props on each tick, so an inline format or zones array\n  // doesn't restart the timer (and freeze the readout) on every render.\n  // Returns whether the ticker still has work: a quiet source whose readout\n  // stopped changing lets it stop, and the next frame starts it again.\n  const tick = useEffectEvent((): boolean => {\n    const element = elementRef.current;\n    if (!element) {\n      return false;\n    }\n    const db = peakRef.current;\n    const text = render(db);\n    const changed = text !== shownRef.current;\n    if (changed) {\n      shownRef.current = text;\n      if (element.firstChild) {\n        element.firstChild.nodeValue = text;\n      } else {\n        element.textContent = text;\n      }\n      element.dataset.zone = zoneForDb(db, zones);\n      element.toggleAttribute(\"data-silent\", db <= floorDb);\n    }\n    // Without a hold, a source that stops sending frames falls to −∞.\n    if (holdMs === 0) {\n      peakRef.current = SILENCE_DB;\n    }\n    const fresh = freshRef.current;\n    freshRef.current = false;\n    return changed || fresh;\n  });\n\n  useEffect(() => {\n    if (!source) {\n      return;\n    }\n    // The first tick always writes, whatever the span shows now.\n    shownRef.current = null;\n    const ticker = createTicker(() => tick(), intervalMs);\n    wakeRef.current = ticker.wake;\n    ticker.wake();\n    return () => {\n      wakeRef.current = noop;\n      ticker.stop();\n    };\n  }, [intervalMs, source]);\n\n  // The ticker writes text React does not know about. Switching between a\n  // source and a value swaps the span, so a value never shows the last live\n  // level and a returning source starts from a fresh first paint.\n  return (\n    <span\n      key={source ? \"source\" : \"value\"}\n      className={cn(\n        \"inline-block min-w-(--db-readout-width) text-end font-mono tabular-nums\",\n        className\n      )}\n      data-silent={initialDb <= floorDb ? \"\" : undefined}\n      data-slot=\"db-readout\"\n      data-zone={zoneForDb(initialDb, zones)}\n      ref={elementRef}\n      style={{ \"--db-readout-width\": `${widest}ch`, ...style } as CSSProperties}\n      {...props}\n    >\n      {render(initialDb)}\n    </span>\n  );\n};\n",
      "type": "registry:ui"
    }
  ],
  "type": "registry:ui"
}