{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "use-exposure",
  "title": "useExposure (exposure engine)",
  "description": "Headless navigation and playback engine for discrete histories: id-based selection, data-change rules, one-setTimeout playback clock (even, elapsed, flipbook timing), keyboard map, settle detection and rate-limited announcements. The engine behind ExposureScrubber.",
  "registryDependencies": [
    "https://frame12.dev/r/use-tempo.json",
    "https://frame12.dev/r/use-on-twos.json"
  ],
  "files": [
    {
      "path": "hooks/use-exposure.ts",
      "content": "'use client';\n\nimport * as React from 'react';\nimport { FRAME_MS } from '@/hooks/use-on-twos';\nimport { useTempo } from '@/hooks/use-tempo';\n\n// Bundlers statically replace `process.env.NODE_ENV`. Declared locally so consumers without\n// @types/node still type-check this file.\ndeclare const process: { env: { NODE_ENV?: string } };\n\n/**\n * useExposure: the headless navigation and playback engine behind `ExposureScrubber` (and, later,\n * `TraceTimeline`). It owns selection (by id), the playback clock, the data-change rules, the\n * keyboard map, settle detection and announcements. It renders nothing.\n *\n * See docs/architecture/exposure-engine.md.\n */\n\nexport type ExposureStatus = 'ok' | 'warn' | 'error' | 'pending';\nexport type ExposureTiming = 'even' | 'elapsed' | 'flipbook';\nexport type ExposureRate = 0.5 | 1 | 2 | 4;\nexport type ExposureValueReason =\n  | 'keyboard'\n  | 'pointer'\n  | 'row'\n  | 'marker'\n  | 'cause'\n  | 'playback'\n  | 'data';\nexport type ExposurePlayingReason =\n  | 'user'\n  | 'end'\n  | 'scrub'\n  | 'hidden'\n  | 'data'\n  | 'tempo'\n  | 'rejected';\n\nexport interface ExposureFrame {\n  /** Unique and stable; identity survives reorders and data changes. */\n  id: string;\n  /** Short action, e.g. \"tool call · write_file\". */\n  label: string;\n  /** ISO 8601. Unparseable → treated as missing. */\n  at?: string;\n  /** How long the step took, if known (≥ 0, finite). */\n  durationMs?: number;\n  /** Short tag, e.g. \"tool\", \"approval\", \"test\". */\n  kind?: string;\n  status?: ExposureStatus;\n  /** A moment that matters. */\n  marker?: boolean;\n  /** Ids of EARLIER frames that the data says led here. Never inferred. */\n  causes?: string[];\n  /** Exposure weight 1–12 (integer), default 1. */\n  hold?: number;\n  /** Plain-text summary, used in the table and without JS. */\n  detail?: string;\n}\n\n/** One frame after the input contract is applied. */\nexport interface ExposureEntry {\n  /** Internal unique key: the id, `id#2`/`id#3` for later duplicates, `#index` for a bad id. */\n  key: string;\n  index: number;\n  /** The frame object exactly as passed in (handed to `renderFrame`). */\n  source: ExposureFrame;\n  label: string;\n  detail?: string;\n  kind?: string;\n  status?: ExposureStatus;\n  marker: boolean;\n  /** 1–12. */\n  hold: number;\n  /** Valid `durationMs`, if any. */\n  durationMs?: number;\n  /** Parsed `at` (epoch ms), if valid. */\n  atMs?: number;\n  /** `atMs` relative to the first frame with a valid `at`. */\n  elapsedMs?: number;\n  /** The held time used by `elapsed` timing: `durationMs`, else the `at` gap to the next frame. */\n  gapMs?: number;\n  /** Indices of earlier frames this one names in `causes` (only valid, backward links). */\n  causes: number[];\n}\n\nexport interface ExposureNormalized {\n  entries: ExposureEntry[];\n  /** key → index */\n  keyIndex: Map<string, number>;\n  /** Distinct, human-readable problems with the input (dev errors). */\n  issues: string[];\n  /** True when at least one frame has a usable gap for the timing column. */\n  hasTiming: boolean;\n  /** Largest gap, for the log-scaled timing column (0 without timing data). */\n  maxGapMs: number;\n}\n\nexport const EXPOSURE_RATES: readonly ExposureRate[] = [0.5, 1, 2, 4];\nexport const EXPOSURE_TIMINGS: readonly ExposureTiming[] = ['even', 'elapsed', 'flipbook'];\n/** Supported maximum. Above it a dev error is logged; rendering is unchanged. */\nexport const EXPOSURE_MAX_FRAMES = 5000;\nexport const EXPOSURE_DEFAULT_STEP_MS = 1000;\nexport const EXPOSURE_MIN_STEP_MS = 250;\nexport const EXPOSURE_ELAPSED_MIN_MS = 250;\nexport const EXPOSURE_ELAPSED_MAX_MS = 3000;\n/** A keyboard scrub settles this long after the last key. */\nexport const EXPOSURE_SETTLE_MS = 500;\n/** At most one announcement per this interval. */\nexport const EXPOSURE_ANNOUNCE_GAP_MS = 1000;\n\nconst STATUSES: readonly ExposureStatus[] = ['ok', 'warn', 'error', 'pending'];\nexport const EXPOSURE_STATUS_WORDS: Record<ExposureStatus, string> = {\n  ok: 'ok',\n  warn: 'warning',\n  error: 'error',\n  pending: 'pending',\n};\n\nconst isFiniteNumber = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v);\n\n/** Applies the input contract. Pure and deterministic: array order is the truth. */\nexport function normalizeExposureFrames(frames: readonly ExposureFrame[]): ExposureNormalized {\n  const issues: string[] = [];\n  const list: readonly ExposureFrame[] = Array.isArray(frames) ? frames : [];\n  if (!Array.isArray(frames)) issues.push('`frames` must be an array; rendering an empty sheet.');\n  if (list.length > EXPOSURE_MAX_FRAMES) {\n    issues.push(\n      `${list.length} frames exceeds the supported maximum of ${EXPOSURE_MAX_FRAMES}; rendering is unchanged but performance is not guaranteed.`,\n    );\n  }\n  const keyIndex = new Map<string, number>();\n  const firstById = new Map<string, number>();\n  // Every real id is reserved up front, so a generated key (\"a#2\") never takes an id that a\n  // later frame really has.\n  const realIds = new Set<string>();\n  for (const f of list) if (typeof f?.id === 'string' && f.id.length > 0) realIds.add(f.id);\n  const dupCount = new Map<string, number>();\n  const entries: ExposureEntry[] = [];\n\n  for (let i = 0; i < list.length; i++) {\n    const f = (list[i] ?? {}) as ExposureFrame;\n    let key: string;\n    if (typeof f.id !== 'string' || f.id.length === 0) {\n      key = `#${i}`;\n      issues.push(`Frame at index ${i} has an empty or non-string id; keyed \"${key}\".`);\n    } else if (firstById.has(f.id)) {\n      let n = dupCount.get(f.id) ?? 1;\n      do n++;\n      while (realIds.has(`${f.id}#${n}`) || keyIndex.has(`${f.id}#${n}`));\n      dupCount.set(f.id, n);\n      key = `${f.id}#${n}`;\n      issues.push(`Duplicate frame id \"${f.id}\" at index ${i}; keyed \"${key}\". \\`value\\` \"${f.id}\" targets the first.`);\n    } else {\n      key = f.id;\n      firstById.set(f.id, i);\n    }\n    // A generated key could collide with a real id further on (\"a#2\" passed explicitly).\n    while (keyIndex.has(key)) key = `${key}#${i}`;\n    keyIndex.set(key, i);\n\n    let hold = 1;\n    if (f.hold !== undefined) {\n      const raw = f.hold as unknown;\n      const n = typeof raw === 'number' ? Math.round(raw) : NaN;\n      hold = Number.isFinite(n) ? Math.min(12, Math.max(1, n)) : 1;\n      if (raw !== hold) issues.push(`Frame \"${key}\" hold ${String(raw)} is outside 1–12 integers; using ${hold}.`);\n    }\n\n    let durationMs: number | undefined;\n    if (f.durationMs !== undefined) {\n      if (isFiniteNumber(f.durationMs) && f.durationMs >= 0) durationMs = f.durationMs;\n      else issues.push(`Frame \"${key}\" durationMs ${String(f.durationMs)} is negative or not finite; ignored.`);\n    }\n\n    let atMs: number | undefined;\n    if (f.at !== undefined) {\n      const parsed = typeof f.at === 'string' ? Date.parse(f.at) : NaN;\n      if (Number.isFinite(parsed)) atMs = parsed;\n      else issues.push(`Frame \"${key}\" at \"${String(f.at)}\" is not a parseable ISO 8601 time; treated as missing.`);\n    }\n\n    let status: ExposureStatus | undefined;\n    if (f.status !== undefined) {\n      if (STATUSES.includes(f.status)) status = f.status;\n      else issues.push(`Frame \"${key}\" status \"${String(f.status)}\" is not ok | warn | error | pending; ignored.`);\n    }\n\n    entries.push({\n      key,\n      index: i,\n      source: f,\n      label: typeof f.label === 'string' ? f.label : String(f.label ?? ''),\n      detail: typeof f.detail === 'string' && f.detail.length > 0 ? f.detail : undefined,\n      kind: typeof f.kind === 'string' && f.kind.length > 0 ? f.kind : undefined,\n      status,\n      marker: f.marker === true,\n      hold,\n      durationMs,\n      atMs,\n      causes: [],\n    });\n  }\n\n  // Causes: only links to EARLIER frames survive (by id → its first occurrence).\n  for (const e of entries) {\n    const causes = e.source.causes;\n    if (causes === undefined) continue;\n    if (!Array.isArray(causes)) {\n      issues.push(`Frame \"${e.key}\" causes must be an array of ids; ignored.`);\n      continue;\n    }\n    const seen = new Set<number>();\n    for (const c of causes) {\n      // Real ids only (first occurrence): a generated key (\"#3\", \"a#2\") is never a cause.\n      const target = typeof c === 'string' ? firstById.get(c) : undefined;\n      if (target === undefined) {\n        issues.push(`Frame \"${e.key}\" names unknown cause \"${String(c)}\"; link dropped.`);\n      } else if (target === e.index) {\n        issues.push(`Frame \"${e.key}\" names itself as a cause; link dropped.`);\n      } else if (target > e.index) {\n        issues.push(`Frame \"${e.key}\" names a later frame \"${String(c)}\" as a cause; causes only point backwards, link dropped.`);\n      } else if (!seen.has(target)) {\n        seen.add(target);\n        e.causes.push(target);\n      }\n    }\n  }\n\n  // Elapsed time relative to the first frame with a valid `at`, and the gap each step held.\n  const firstAt = entries.find((e) => e.atMs !== undefined)?.atMs;\n  let maxGapMs = 0;\n  let hasTiming = false;\n  for (let i = 0; i < entries.length; i++) {\n    const e = entries[i];\n    if (e.atMs !== undefined && firstAt !== undefined) e.elapsedMs = e.atMs - firstAt;\n    let gap = e.durationMs;\n    if (gap === undefined && e.atMs !== undefined) {\n      const next = entries[i + 1];\n      if (next?.atMs !== undefined && next.atMs - e.atMs >= 0) gap = next.atMs - e.atMs;\n    }\n    if (gap !== undefined) {\n      e.gapMs = gap;\n      hasTiming = true;\n      if (gap > maxGapMs) maxGapMs = gap;\n    }\n  }\n\n  return { entries, keyIndex, issues, hasTiming, maxGapMs };\n}\n\n/** `stepMs` < 250 → 250; non-finite → the default. */\nexport function normalizeStepMs(stepMs: unknown): number {\n  if (!isFiniteNumber(stepMs)) return EXPOSURE_DEFAULT_STEP_MS;\n  return Math.max(EXPOSURE_MIN_STEP_MS, stepMs);\n}\n\nexport function isExposureRate(v: unknown): v is ExposureRate {\n  return v === 0.5 || v === 1 || v === 2 || v === 4;\n}\n\n/**\n * How long `entry` is shown during playback.\n * - even:     stepMs × hold ÷ rate\n * - elapsed:  clamp(gap, 250, 3000) ÷ rate; a missing gap falls back to `even`\n * - flipbook: FRAME_MS × hold ÷ rate (12 poses per second at 1×)\n */\nexport function exposureStepDuration(\n  entry: Pick<ExposureEntry, 'hold' | 'gapMs'>,\n  timing: ExposureTiming,\n  rate: ExposureRate,\n  stepMs: number,\n): number {\n  if (timing === 'flipbook') return (FRAME_MS * entry.hold) / rate;\n  const even = (stepMs * entry.hold) / rate;\n  if (timing === 'elapsed') {\n    const g = entry.gapMs;\n    if (g === undefined || !(g >= 0)) return even;\n    return Math.min(EXPOSURE_ELAPSED_MAX_MS, Math.max(EXPOSURE_ELAPSED_MIN_MS, g)) / rate;\n  }\n  return even;\n}\n\n/** `F-01` … zero-padded to the digits of the total (minimum 2). */\nexport function formatFrameNumber(index: number, total: number): string {\n  const width = Math.max(2, String(Math.max(1, total)).length);\n  return `F-${String(index + 1).padStart(width, '0')}`;\n}\n\n/** `+mm:ss.s` (deterministic, locale-free). */\nexport function formatElapsed(ms: number): string {\n  const sign = ms < 0 ? '-' : '+';\n  const tenths = Math.floor(Math.abs(ms) / 100);\n  const minutes = Math.floor(tenths / 600);\n  const seconds = Math.floor((tenths % 600) / 10);\n  const t = tenths % 10;\n  return `${sign}${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}.${t}`;\n}\n\n/** `1.2s` / `340ms` (deterministic, locale-free). */\nexport function formatGap(ms: number): string {\n  if (ms < 1000) return `${Math.round(ms)}ms`;\n  if (ms < 60000) return `${(ms / 1000).toFixed(1)}s`;\n  return `${Math.floor(ms / 60000)}m${String(Math.floor((ms % 60000) / 1000)).padStart(2, '0')}s`;\n}\n\n/** \"Frame 7 of 42: tool call write_file, error\" */\nexport function describeExposureFrame(entry: ExposureEntry, total: number): string {\n  const status = entry.status ? `, ${EXPOSURE_STATUS_WORDS[entry.status]}` : '';\n  const marker = entry.marker ? ', marked' : '';\n  return `Frame ${entry.index + 1} of ${total}: ${entry.label}${status}${marker}`;\n}\n\n/** True for targets where single-key shortcuts must never fire. */\nexport function isEditableTarget(target: EventTarget | null): boolean {\n  if (!target || typeof (target as Element).closest !== 'function') return false;\n  const el = target as HTMLElement;\n  if (el.isContentEditable) return true;\n  const tag = el.tagName;\n  if (tag === 'TEXTAREA' || tag === 'SELECT') return true;\n  if (tag === 'INPUT') {\n    // A range input is a playhead, not a text field: j/k/p still apply there.\n    const type = (el as HTMLInputElement).type;\n    return type !== 'range' && type !== 'radio' && type !== 'checkbox' && type !== 'button';\n  }\n  return el.closest('[contenteditable=\"\"],[contenteditable=\"true\"],[contenteditable=\"plaintext-only\"]') !== null;\n}\n\nexport interface UseExposureOptions {\n  frames: readonly ExposureFrame[];\n  value?: string;\n  defaultValue?: string;\n  onValueChange?: (\n    id: string,\n    info: { index: number; reason: ExposureValueReason },\n  ) => void;\n  playing?: boolean;\n  onPlayingChange?: (playing: boolean, reason: ExposurePlayingReason) => void;\n  timing?: ExposureTiming;\n  rate?: ExposureRate;\n  defaultRate?: ExposureRate;\n  onRateChange?: (rate: ExposureRate) => void;\n  stepMs?: number;\n  loop?: boolean;\n  primaryMarker?: string;\n  /** Prefix for dev errors. */\n  name?: string;\n}\n\nexport interface ExposureState {\n  entries: readonly ExposureEntry[];\n  count: number;\n  /** Current index (-1 when there are no frames). */\n  index: number;\n  current: ExposureEntry | null;\n  playing: boolean;\n  /** The timing actually used (flipbook falls back to even when motion is unavailable). */\n  timing: ExposureTiming;\n  /** The timing the viewer (or the `timing` prop) asked for. */\n  requestedTiming: ExposureTiming;\n  setTiming: (timing: ExposureTiming) => void;\n  /** False when the effective tempo is `still` (OS reduced motion, still tempo or ancestor). */\n  flipbookAvailable: boolean;\n  /** Playing in flipbook timing: the panel shows a slate instead of updating. */\n  flipping: boolean;\n  /** The index the panel shows: frozen at the flip's start while flipping. */\n  panelIndex: number;\n  rate: ExposureRate;\n  setRate: (rate: ExposureRate) => void;\n  /** Pointer drag in progress, or a keyboard scrub that has not settled yet. */\n  scrubbing: boolean;\n  /** Not scrubbing and not flipping. */\n  settled: boolean;\n  hasTiming: boolean;\n  maxGapMs: number;\n  /** Indices of marker frames, in order. */\n  markers: readonly number[];\n  /** Index of the marker that gets marker yellow (-1 without markers). */\n  primaryMarkerIndex: number;\n  /** One-level history: where \"Back\" returns to after following a cause. */\n  back: ExposureEntry | null;\n  /** Polite live-region text. */\n  announcement: string;\n  select: (index: number, reason: ExposureValueReason) => void;\n  step: (delta: number, reason: ExposureValueReason) => void;\n  /** `via: 'pointer'` (a click) announces at once instead of starting a keyboard scrub. */\n  stepMarker: (direction: 1 | -1, via?: 'keyboard' | 'pointer') => void;\n  followCause: (index: number) => void;\n  goBack: () => void;\n  play: () => void;\n  pause: (reason: ExposurePlayingReason) => void;\n  toggle: () => void;\n  /** Call on pointer drag start / end. */\n  beginPointerScrub: () => void;\n  endPointerScrub: () => void;\n  /** Call after a keyboard navigation (starts / restarts the 500 ms settle timer). */\n  noteKeyScrub: () => void;\n  /** Announce the (new) current frame once it has rendered: a click is already settled. */\n  announceSettled: () => void;\n  /** The single-key shortcuts (`j`/`k`/`[`/`]`/`p`). Returns true when the key was handled. */\n  handleShortcut: (event: {\n    key: string;\n    target: EventTarget | null;\n    ctrlKey?: boolean;\n    metaKey?: boolean;\n    altKey?: boolean;\n  }) => boolean;\n  /** Roving-row keys (`↑/↓/Home/End`): the index to move to, or null. */\n  rowKeyTarget: (key: string, fromIndex: number) => number | null;\n}\n\nconst useIsoLayoutEffect = typeof window !== 'undefined' ? React.useLayoutEffect : React.useEffect;\n\nconst isDev = (): boolean => {\n  try {\n    return process.env.NODE_ENV !== 'production';\n  } catch {\n    return false;\n  }\n};\n\n/** One dev-only console.error per distinct message per instance. */\nfunction useDevErrors(name: string): (msg: string) => void {\n  const seen = React.useRef<Set<string>>(new Set());\n  return React.useCallback(\n    (msg: string) => {\n      if (!isDev() || seen.current.has(msg)) return;\n      seen.current.add(msg);\n      console.error(`[FRAME/12 ${name}] ${msg}`);\n    },\n    [name],\n  );\n}\n\nfunction resolveIndex(\n  requested: string | undefined,\n  keyIndex: Map<string, number>,\n  count: number,\n  prev: { key: string; index: number } | null,\n): number {\n  if (count === 0) return -1;\n  if (requested !== undefined) {\n    const i = keyIndex.get(requested);\n    if (i !== undefined) return i;\n  }\n  // The frame that was showing was removed: stay at its position (clamped).\n  if (prev && requested === prev.key) return Math.min(prev.index, count - 1);\n  return 0;\n}\n\nexport function useExposure(options: UseExposureOptions): ExposureState {\n  const {\n    frames,\n    value,\n    defaultValue,\n    onValueChange,\n    playing: playingProp,\n    onPlayingChange,\n    timing: timingProp = 'even',\n    rate: rateProp,\n    defaultRate,\n    onRateChange,\n    stepMs: stepMsProp,\n    loop = false,\n    primaryMarker,\n    name = 'useExposure',\n  } = options;\n  const devError = useDevErrors(name);\n\n  // ------------------------------------------------------------------ input contract\n  const normalized = React.useMemo(() => normalizeExposureFrames(frames), [frames]);\n  const { entries, keyIndex } = normalized;\n  const count = entries.length;\n  const stepMs = normalizeStepMs(stepMsProp);\n\n  React.useEffect(() => {\n    for (const issue of normalized.issues) devError(issue);\n  }, [normalized, devError]);\n  React.useEffect(() => {\n    if (stepMsProp === undefined) return;\n    if (!isFiniteNumber(stepMsProp)) devError(`stepMs ${String(stepMsProp)} is not finite; using ${EXPOSURE_DEFAULT_STEP_MS}.`);\n    else if (stepMsProp < EXPOSURE_MIN_STEP_MS) devError(`stepMs ${stepMsProp} is below ${EXPOSURE_MIN_STEP_MS}; clamped to ${EXPOSURE_MIN_STEP_MS}.`);\n  }, [stepMsProp, devError]);\n\n  // ------------------------------------------------------------------ controlled modes\n  const valueControlled = React.useRef(value !== undefined).current;\n  const playingControlled = React.useRef(playingProp !== undefined).current;\n  const rateControlled = React.useRef(rateProp !== undefined).current;\n  React.useEffect(() => {\n    if ((value !== undefined) !== valueControlled) {\n      devError(\n        `\\`value\\` switched from ${valueControlled ? 'controlled to uncontrolled' : 'uncontrolled to controlled'}; the first mode wins. Keep \\`value\\` defined (controlled) or undefined (uncontrolled) for the lifetime of the component.`,\n      );\n    }\n    if ((playingProp !== undefined) !== playingControlled) {\n      devError(`\\`playing\\` switched between controlled and uncontrolled; the first mode wins.`);\n    }\n    if ((rateProp !== undefined) !== rateControlled) {\n      devError(`\\`rate\\` switched between controlled and uncontrolled; the first mode wins.`);\n    }\n  }, [value, playingProp, rateProp, valueControlled, playingControlled, rateControlled, devError]);\n\n  // ------------------------------------------------------------------ selection\n  const [innerKey, setInnerKey] = React.useState<string | undefined>(defaultValue);\n  const requested = valueControlled ? value : innerKey;\n  const prevRef = React.useRef<{ key: string; index: number } | null>(null);\n  const index = resolveIndex(requested, keyIndex, count, prevRef.current);\n  const current = index >= 0 ? entries[index] : null;\n\n  // ------------------------------------------------------------------ playing\n  const [innerPlaying, setInnerPlaying] = React.useState(false);\n  const rawPlaying = playingControlled ? playingProp === true : innerPlaying;\n  const playing = rawPlaying && count > 1;\n\n  // ------------------------------------------------------------------ rate & timing\n  const [innerRate, setInnerRate] = React.useState<ExposureRate>(\n    isExposureRate(defaultRate) ? defaultRate : 1,\n  );\n  const rawRate = rateControlled ? rateProp : innerRate;\n  const rate: ExposureRate = isExposureRate(rawRate) ? rawRate : 1;\n  React.useEffect(() => {\n    if (rawRate !== undefined && !isExposureRate(rawRate)) devError(`rate ${String(rawRate)} is not 0.5 | 1 | 2 | 4; using 1.`);\n    if (defaultRate !== undefined && !isExposureRate(defaultRate)) devError(`defaultRate ${String(defaultRate)} is not 0.5 | 1 | 2 | 4; using 1.`);\n  }, [rawRate, defaultRate, devError]);\n\n  const validTimingProp: ExposureTiming = EXPOSURE_TIMINGS.includes(timingProp) ? timingProp : 'even';\n  const [timingState, setTimingState] = React.useState<{ prop: ExposureTiming; value: ExposureTiming }>(\n    () => ({ prop: validTimingProp, value: validTimingProp }),\n  );\n  // A new `timing` prop value resets the viewer's choice (derived state, no effect round-trip).\n  let requestedTiming = timingState.value;\n  if (timingState.prop !== validTimingProp) {\n    requestedTiming = validTimingProp;\n    setTimingState({ prop: validTimingProp, value: validTimingProp });\n  }\n  React.useEffect(() => {\n    if (!EXPOSURE_TIMINGS.includes(timingProp)) devError(`timing \"${String(timingProp)}\" is not even | elapsed | flipbook; using even.`);\n  }, [timingProp, devError]);\n\n  const { effectiveTempo } = useTempo();\n  const flipbookAvailable = effectiveTempo !== 'still';\n  const timing: ExposureTiming =\n    requestedTiming === 'flipbook' && !flipbookAvailable ? 'even' : requestedTiming;\n  const flipping = playing && timing === 'flipbook';\n\n  // ------------------------------------------------------------------ markers\n  const markers = React.useMemo(() => entries.filter((e) => e.marker).map((e) => e.index), [entries]);\n  const primaryMarkerIndex = React.useMemo(() => {\n    if (markers.length === 0) return -1;\n    if (primaryMarker !== undefined) {\n      const i = keyIndex.get(primaryMarker);\n      if (i !== undefined && entries[i].marker) return i;\n    }\n    return markers[0];\n  }, [markers, primaryMarker, keyIndex, entries]);\n  React.useEffect(() => {\n    if (!valueControlled && defaultValue !== undefined && count > 0 && !keyIndex.has(defaultValue)) {\n      devError(`defaultValue \"${defaultValue}\" is not a frame id; showing the first frame.`);\n    }\n    // Initial value only.\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, []);\n  React.useEffect(() => {\n    if (primaryMarker === undefined) return;\n    const i = keyIndex.get(primaryMarker);\n    if (i === undefined || !entries[i].marker) {\n      devError(`primaryMarker \"${primaryMarker}\" is not a marked frame; the first marker gets marker yellow.`);\n    }\n  }, [primaryMarker, keyIndex, entries, devError]);\n\n  // ------------------------------------------------------------------ latest-value refs\n  const latest = React.useRef({\n    entries,\n    index,\n    count,\n    playing,\n    rawPlaying,\n    loop,\n    valueControlled,\n    playingControlled,\n    onValueChange,\n    onPlayingChange,\n    timing,\n  });\n  latest.current = {\n    entries,\n    index,\n    count,\n    playing,\n    rawPlaying,\n    loop,\n    valueControlled,\n    playingControlled,\n    onValueChange,\n    onPlayingChange,\n    timing,\n  };\n\n  // ------------------------------------------------------------------ announcements\n  const [announcement, setAnnouncement] = React.useState('');\n  const announcer = React.useRef<{ lastAt: number; timer: ReturnType<typeof setTimeout> | null; pending: string | null; last: string }>(\n    { lastAt: -Infinity, timer: null, pending: null, last: '' },\n  );\n  // Nothing announces after unmount (a queued microtask or timer may still fire once).\n  const mounted = React.useRef(false);\n  React.useEffect(() => {\n    mounted.current = true;\n    return () => {\n      mounted.current = false;\n    };\n  }, []);\n  const announce = React.useCallback((text: string) => {\n    if (!mounted.current) return;\n    const a = announcer.current;\n    const emit = (t: string) => {\n      // Identical consecutive text would not be re-read; alternate a trailing no-break space.\n      const next = t === a.last.replace(/\\u00a0$/, '') && !a.last.endsWith('\\u00a0') ? `${t}\\u00a0` : t;\n      if (!mounted.current) return;\n      a.last = next;\n      a.lastAt = performance.now();\n      setAnnouncement(next);\n    };\n    const now = performance.now();\n    if (now - a.lastAt >= EXPOSURE_ANNOUNCE_GAP_MS && a.timer === null) {\n      emit(text);\n      return;\n    }\n    a.pending = text;\n    if (a.timer === null) {\n      a.timer = setTimeout(() => {\n        a.timer = null;\n        const p = a.pending;\n        a.pending = null;\n        if (p !== null) emit(p);\n      }, Math.max(0, a.lastAt + EXPOSURE_ANNOUNCE_GAP_MS - now));\n    }\n  }, []);\n\n  // ------------------------------------------------------------------ playing transitions\n  const setPlaying = React.useCallback(\n    (next: boolean, reason: ExposurePlayingReason, atIndex?: number) => {\n      const l = latest.current;\n      // Compare with the raw state: with fewer than 2 frames `playing` reads false while the\n      // underlying state may still be on, and that must be switched off (never resume later).\n      if (next === l.rawPlaying) return;\n      // Reflect the request at once so a second call in the same tick is a no-op.\n      l.rawPlaying = next;\n      l.playing = next && l.count > 1;\n      if (!l.playingControlled) setInnerPlaying(next);\n      l.onPlayingChange?.(next, reason);\n      if (next) {\n        announce('Playing');\n      } else {\n        const i = atIndex ?? l.index;\n        const where = `Paused at frame ${i + 1} of ${l.count}`;\n        announce(\n          reason === 'tempo'\n            ? `${where}. Flipbook needs motion; reduced motion or a still tempo is on.`\n            : where,\n        );\n      }\n    },\n    [announce],\n  );\n  const pause = React.useCallback((reason: ExposurePlayingReason) => setPlaying(false, reason), [setPlaying]);\n\n  // ------------------------------------------------------------------ selection transitions\n  const commit = React.useCallback((target: number, reason: ExposureValueReason) => {\n    const l = latest.current;\n    const entry = l.entries[target];\n    if (!entry || target === l.index) return;\n    if (!l.valueControlled) setInnerKey(entry.key);\n    l.onValueChange?.(entry.key, { index: target, reason });\n  }, []);\n\n  const [pointerScrub, setPointerScrub] = React.useState(false);\n  const [keyScrub, setKeyScrub] = React.useState(false);\n  const settleTimer = React.useRef<ReturnType<typeof setTimeout> | null>(null);\n  const announceCurrent = React.useCallback(() => {\n    const l = latest.current;\n    const e = l.entries[l.index];\n    if (e) announce(describeExposureFrame(e, l.count));\n  }, [announce]);\n\n  const select = React.useCallback(\n    (target: number, reason: ExposureValueReason) => {\n      const l = latest.current;\n      if (l.count === 0) return;\n      const t = Math.min(l.count - 1, Math.max(0, Math.round(target)));\n      if (reason !== 'playback' && reason !== 'data' && l.playing) setPlaying(false, 'scrub');\n      commit(t, reason);\n    },\n    [commit, setPlaying],\n  );\n\n  const noteKeyScrub = React.useCallback(() => {\n    setKeyScrub(true);\n    if (settleTimer.current !== null) clearTimeout(settleTimer.current);\n    settleTimer.current = setTimeout(() => {\n      settleTimer.current = null;\n      setKeyScrub(false);\n      announceCurrent();\n    }, EXPOSURE_SETTLE_MS);\n  }, [announceCurrent]);\n\n  const settleAnnounceTimer = React.useRef<ReturnType<typeof setTimeout> | null>(null);\n  const announceSettled = React.useCallback(() => {\n    // After React applies the selection (it commits before the next task). Tracked, so unmount\n    // cancels it.\n    if (settleAnnounceTimer.current !== null) clearTimeout(settleAnnounceTimer.current);\n    settleAnnounceTimer.current = setTimeout(() => {\n      settleAnnounceTimer.current = null;\n      announceCurrent();\n    }, 0);\n  }, [announceCurrent]);\n\n  const pointerScrubRef = React.useRef(false);\n  const beginPointerScrub = React.useCallback(() => {\n    if (pointerScrubRef.current) return;\n    pointerScrubRef.current = true;\n    setPointerScrub(true);\n    if (latest.current.playing) setPlaying(false, 'scrub');\n  }, [setPlaying]);\n  const endPointerScrub = React.useCallback(() => {\n    if (!pointerScrubRef.current) return;\n    pointerScrubRef.current = false;\n    setPointerScrub(false);\n    // Read the frame after React has applied the last move.\n    queueMicrotask(announceCurrent);\n  }, [announceCurrent]);\n\n  const step = React.useCallback(\n    (delta: number, reason: ExposureValueReason) => {\n      const l = latest.current;\n      if (l.count === 0) return;\n      select(Math.min(l.count - 1, Math.max(0, l.index + delta)), reason);\n    },\n    [select],\n  );\n\n  const stepMarker = React.useCallback(\n    (direction: 1 | -1, via: 'keyboard' | 'pointer' = 'keyboard') => {\n      const l = latest.current;\n      let target = -1;\n      for (const e of direction > 0 ? l.entries : [...l.entries].reverse()) {\n        if (e.marker && (direction > 0 ? e.index > l.index : e.index < l.index)) {\n          target = e.index;\n          break;\n        }\n      }\n      if (target >= 0) {\n        select(target, 'marker');\n        // A click is already settled; only key presses count as a scrub.\n        if (via === 'keyboard') noteKeyScrub();\n        else announceSettled();\n      }\n    },\n    [select, noteKeyScrub, announceSettled],\n  );\n\n  const [back, setBack] = React.useState<{ key: string; index: number } | null>(null);\n  const followCause = React.useCallback(\n    (target: number) => {\n      const l = latest.current;\n      const from = l.entries[l.index];\n      if (!from || !l.entries[target]) return;\n      setBack({ key: from.key, index: from.index });\n      select(target, 'cause');\n      announce(describeExposureFrame(l.entries[target], l.count));\n    },\n    [select, announce],\n  );\n  const goBack = React.useCallback(() => {\n    const l = latest.current;\n    if (!back) return;\n    const i = keyIndex.get(back.key);\n    setBack(null);\n    if (i === undefined) return;\n    select(i, 'cause');\n    const e = l.entries[i];\n    if (e) announce(describeExposureFrame(e, l.count));\n  }, [back, keyIndex, select, announce]);\n  // \"Back\" exists only while its frame still exists and is not the frame being shown (a reader\n  // who returns there another way no longer needs it). One rule for the button and goBack.\n  const backIndex = back ? keyIndex.get(back.key) : undefined;\n  const backEntry = backIndex !== undefined && backIndex !== index ? entries[backIndex] : null;\n  // Clear only when the reader MOVES to the back target (or it is gone), never merely because they\n  // are equal: a controlled parent that applies the cause jump later (a transition, router\n  // search params) commits once with `back` set and the old index first.\n  const prevIndexForBack = React.useRef(index);\n  React.useEffect(() => {\n    const moved = prevIndexForBack.current !== index;\n    prevIndexForBack.current = index;\n    if (back && (backIndex === undefined || (moved && backIndex === index))) setBack(null);\n  }, [back, backIndex, index]);\n\n  // ------------------------------------------------------------------ play / pause\n  const clock = React.useRef<{ deadline: number; pending: string | null }>({ deadline: 0, pending: null });\n  const [flipAnchor, setFlipAnchor] = React.useState(-1);\n  const play = React.useCallback(() => {\n    const l = latest.current;\n    if (l.count < 2 || l.playing) return;\n    // Play at the end restarts from the first frame.\n    if (l.index >= l.count - 1) commit(0, 'playback');\n    setPlaying(true, 'user');\n  }, [commit, setPlaying]);\n  const toggle = React.useCallback(() => {\n    if (latest.current.playing) pause('user');\n    else play();\n  }, [play, pause]);\n\n  // ------------------------------------------------------------------ data changes\n  const lastDataFire = React.useRef<string | null>(null);\n  useIsoLayoutEffect(() => {\n    const l = latest.current;\n    // Too few frames to play (shrunk by data): stop, so growing back never resumes on its own.\n    if (l.rawPlaying && count < 2) setPlaying(false, 'data', Math.max(0, index));\n    if (!current) return;\n    const prev = prevRef.current;\n    if (requested !== current.key) {\n      const removed = prev !== null && requested === prev.key && !keyIndex.has(prev.key);\n      if (!valueControlled) setInnerKey(current.key);\n      const sig = `${String(requested)}→${current.key}`;\n      const fire = valueControlled ? lastDataFire.current !== sig : removed;\n      if (fire) {\n        lastDataFire.current = sig;\n        onValueChange?.(current.key, { index, reason: 'data' });\n      }\n      if (removed && l.playing) setPlaying(false, 'data', index);\n      // Controlled: until the parent applies the survivor, keep resolving the removed id to the\n      // same position (instead of falling back to the first frame and firing again).\n      if (valueControlled && requested !== undefined && prev !== null && requested === prev.key) {\n        prevRef.current = { key: requested, index };\n        return;\n      }\n    } else {\n      lastDataFire.current = null;\n    }\n    prevRef.current = { key: current.key, index };\n  });\n\n  // ------------------------------------------------------------------ the clock\n  // Whenever playback starts (play(), or a controlled `playing` the parent turned on), the first\n  // deadline is measured from now.\n  React.useEffect(() => {\n    if (!playing) return;\n    clock.current = { deadline: performance.now(), pending: null };\n    setFlipAnchor(latest.current.index);\n  }, [playing]);\n  const currentKey = current?.key;\n  const stepDuration = current ? exposureStepDuration(current, timing, rate, stepMs) : 0;\n  React.useEffect(() => {\n    if (!playing || currentKey === undefined) return;\n    const c = clock.current;\n    if (c.pending !== null && c.pending === currentKey) c.pending = null;\n    let timer: ReturnType<typeof setTimeout> | null = null;\n    const schedule = (dur: number) => {\n      const now = performance.now();\n      let deadline = c.deadline + dur;\n      // After a stall (a long task, a throttled tab), rebase instead of catching up.\n      if (deadline < now) deadline = now;\n      timer = setTimeout(() => tick(deadline), Math.max(0, deadline - now));\n    };\n    const tick = (deadline: number) => {\n      timer = null;\n      const l = latest.current;\n      c.deadline = deadline;\n      if (c.pending !== null && l.entries[l.index]?.key === c.pending) c.pending = null; // applied; effect not re-run yet\n      if (c.pending !== null) {\n        // The controlled parent did not apply the previous advance by this deadline.\n        c.pending = null;\n        setPlaying(false, 'rejected');\n        return;\n      }\n      let target = l.index + 1;\n      if (target >= l.count) {\n        if (!l.loop) {\n          setPlaying(false, 'end');\n          return;\n        }\n        target = 0;\n      }\n      const t = l.entries[target];\n      if (!t) return;\n      c.pending = t.key;\n      commit(target, 'playback');\n      // Never more than one frame per tick: the next tick is the check (or the next advance if\n      // this component re-renders first, which cancels this timer).\n      schedule(exposureStepDuration(t, l.timing, rate, stepMs));\n    };\n    schedule(stepDuration);\n    return () => {\n      if (timer !== null) clearTimeout(timer);\n    };\n  }, [playing, currentKey, stepDuration, rate, stepMs, commit, setPlaying]);\n\n  // Hidden tab pauses; no auto-resume. Listener only exists while playing.\n  React.useEffect(() => {\n    if (!playing || typeof document === 'undefined') return;\n    const onVis = () => {\n      if (document.hidden) setPlaying(false, 'hidden');\n    };\n    document.addEventListener('visibilitychange', onVis);\n    return () => document.removeEventListener('visibilitychange', onVis);\n  }, [playing, setPlaying]);\n\n  // A flipbook in progress pauses when motion becomes unavailable.\n  // Only on the transition (available → unavailable): with flipbook selected under a still tempo,\n  // Play still plays (in even timing) instead of pausing at once.\n  const wasAvailable = React.useRef(flipbookAvailable);\n  React.useEffect(() => {\n    const was = wasAvailable.current;\n    wasAvailable.current = flipbookAvailable;\n    if (was && !flipbookAvailable && latest.current.playing && requestedTiming === 'flipbook') setPlaying(false, 'tempo');\n  }, [flipbookAvailable, requestedTiming, setPlaying]);\n\n  // Unmount: cancel every timer.\n  React.useEffect(\n    () => () => {\n      if (settleTimer.current !== null) clearTimeout(settleTimer.current);\n      if (settleAnnounceTimer.current !== null) clearTimeout(settleAnnounceTimer.current);\n      if (announcer.current.timer !== null) clearTimeout(announcer.current.timer);\n      settleTimer.current = null;\n      settleAnnounceTimer.current = null;\n      announcer.current.timer = null;\n    },\n    [],\n  );\n\n  const setRate = React.useCallback(\n    (r: ExposureRate) => {\n      if (!isExposureRate(r)) return;\n      if (!rateControlled) setInnerRate(r);\n      onRateChange?.(r);\n    },\n    [rateControlled, onRateChange],\n  );\n  const setTiming = React.useCallback(\n    (t: ExposureTiming) => {\n      if (!EXPOSURE_TIMINGS.includes(t)) return;\n      if (t === 'flipbook' && !flipbookAvailable) return;\n      if (t === 'flipbook' && latest.current.playing) setFlipAnchor(latest.current.index);\n      setTimingState((s) => ({ ...s, value: t }));\n    },\n    [flipbookAvailable],\n  );\n\n  const handleShortcut = React.useCallback<ExposureState['handleShortcut']>(\n    (e) => {\n      if (e.ctrlKey || e.metaKey || e.altKey) return false;\n      if (isEditableTarget(e.target)) return false;\n      switch (e.key) {\n        case 'j':\n          step(1, 'keyboard');\n          noteKeyScrub();\n          return true;\n        case 'k':\n          step(-1, 'keyboard');\n          noteKeyScrub();\n          return true;\n        case ']':\n          stepMarker(1);\n          return true;\n        case '[':\n          stepMarker(-1);\n          return true;\n        case 'p':\n          toggle();\n          return true;\n        default:\n          return false;\n      }\n    },\n    [step, stepMarker, toggle, noteKeyScrub],\n  );\n\n  const rowKeyTarget = React.useCallback((key: string, from: number): number | null => {\n    const n = latest.current.count;\n    if (n === 0) return null;\n    if (key === 'ArrowDown') return Math.min(n - 1, from + 1);\n    if (key === 'ArrowUp') return Math.max(0, from - 1);\n    if (key === 'Home') return 0;\n    if (key === 'End') return n - 1;\n    return null;\n  }, []);\n\n  const scrubbing = pointerScrub || keyScrub;\n  const panelIndex = flipping ? (flipAnchor >= 0 && flipAnchor < count ? flipAnchor : index) : index;\n\n  return {\n    entries,\n    count,\n    index,\n    current,\n    playing,\n    timing,\n    requestedTiming,\n    setTiming,\n    flipbookAvailable,\n    flipping,\n    panelIndex,\n    rate,\n    setRate,\n    scrubbing,\n    settled: !scrubbing && !flipping,\n    hasTiming: normalized.hasTiming,\n    maxGapMs: normalized.maxGapMs,\n    markers,\n    primaryMarkerIndex,\n    back: backEntry,\n    announcement,\n    select,\n    step,\n    stepMarker,\n    followCause,\n    goBack,\n    play,\n    pause,\n    toggle,\n    beginPointerScrub,\n    endPointerScrub,\n    noteKeyScrub,\n    announceSettled,\n    handleShortcut,\n    rowKeyTarget,\n  };\n}\n",
      "type": "registry:hook",
      "target": "hooks/use-exposure.ts"
    }
  ],
  "type": "registry:hook"
}