{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "review-bar",
  "type": "registry:ui",
  "title": "Review Bar",
  "description": "The review-bar primitive.",
  "dependencies": [],
  "registryDependencies": [
    "https://ui.klarhimmel.com/r/theme.json",
    "https://ui.klarhimmel.com/r/utils.json"
  ],
  "files": [
    {
      "path": "src/ui/review-bar.tsx",
      "type": "registry:file",
      "target": "components/klarhimmel/ui/review-bar.tsx",
      "content": "// Preview-only chrome: flip between versions of a page, say like or don't like for each version and for each section of it, and pick a final\n// version, all relayed to the agent that asked (docs/review-bar.md).\n// It is not a block and never ships on a published page: it draws nothing unless `preview` is set or the address has ?review=1.\n// The wire format is docs/answer-contract.md, the same as scripts/report-answer.js: POST {relay}/answers, GET {relay}/status, the copy line.\nimport { useCallback, useEffect, useId, useLayoutEffect, useRef, useState } from 'react';\nimport { cn } from '../lib/utils';\n\nexport interface ReviewVersion { id: string; label: string; href: string }\nexport interface ReviewRelay { url: string; token: string }\nexport interface ReviewAddress { seat: string; repo: string; session: string; page: string; askedAt?: string }\nexport type ReviewChoice = 'like' | 'dislike';\nexport type ReviewStatus = 'open' | 'defaulted' | 'answered' | 'applied' | 'superseded';\n\n/** Only an http address on this machine, no credentials: 127.0.0.1, localhost or [::1]. Nothing else is ever contacted. */\nexport function isLocalRelay(raw: string | undefined): boolean {\n  if (!raw) return false;\n  let u: URL;\n  try { u = new URL(raw); } catch { return false; }\n  return u.protocol === 'http:' && !u.username && !u.password && (u.hostname === '127.0.0.1' || u.hostname === 'localhost' || u.hostname === '[::1]');\n}\n\nexport interface ReviewSection { id: string; label: string }\n\n/** `<decisionPrefix>-<versionId>`: each version is one answerable decision. */\nexport const decisionId = (prefix: string, versionId: string) => `${prefix}-${versionId}`;\n/** `<decisionPrefix>-<versionId>-<sectionId>`: each (version, section) pair is one. */\nexport const sectionDecisionId = (prefix: string, versionId: string, sectionId: string) => `${prefix}-${versionId}-${sectionId}`;\n/** `<decisionPrefix>-pick`: the final pick between the versions. */\nexport const pickId = (prefix: string) => `${prefix}-pick`;\n\n/** The body of POST {relay}/answers. `choice` is `like` or `dislike` (for the final pick: the label of the version picked), `text` the note. */\nexport function answerPayload(a: { id: string; address: ReviewAddress; choice: string; note: string; now?: Date }) {\n  return { id: a.id, version: 1, seat: a.address.seat, repo: a.address.repo, session: a.address.session, choice: a.choice, text: a.note.trim(), answeredAt: (a.now ?? new Date()).toISOString(), page: a.address.page };\n}\n\n/** ANSWER <id> v1 to <seat> (session <session>): <choice>, <note> */\nexport function copyLine(a: { id: string; address: ReviewAddress; choice: string; note: string }): string {\n  return `ANSWER ${a.id} v1 to ${a.address.seat || '-'} (session ${a.address.session || '-'}): ${[a.choice, a.note.trim()].filter(Boolean).join(', ')}`;\n}\n\nconst STATUS_WORDS: Record<ReviewStatus, string> = { open: 'Open', defaulted: 'Defaulted', answered: 'Answered', applied: 'Applied', superseded: 'Superseded' };\nconst DOT: Record<ReviewStatus, string> = {\n  open: 'rounded-kh-pill border-2 border-kh-muted',\n  defaulted: 'rotate-45 border-2 border-kh-muted',\n  answered: 'rounded-kh-pill bg-kh-accent',\n  applied: 'bg-kh-accent',\n  superseded: 'rounded-kh-pill border-2 border-kh-muted bg-kh-surface-3',\n};\nconst POLL_MS = 5000;\nconst OFFLINE_POLL_MS = 30000;\n\nconst isPreview = (preview: boolean | undefined) =>\n  !!preview || (typeof window !== 'undefined' && new URLSearchParams(window.location.search).get('review') === '1');\n\nconst btn = 'inline-flex min-h-11 items-center justify-center rounded-kh border px-3 text-kh-small font-medium focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-(--kh-focus)';\n\n/** The element a section marker is anchored to: `[data-kh-section=\"<id>\"]`. A lookup by attribute value, so an odd id is never a selector. */\nconst sectionElement = (id: string): HTMLElement | null => [...document.querySelectorAll<HTMLElement>('[data-kh-section]')].find((e) => e.getAttribute('data-kh-section') === id) ?? null;\n\nexport function ReviewBar({ versions, current, relay, address, decisionPrefix, preview, sections, final }: {\n  versions: ReviewVersion[]; current: string; relay?: ReviewRelay; address: ReviewAddress; decisionPrefix: string; preview?: boolean;\n  /** Sections of the page to review one by one: each is found as `[data-kh-section=\"<id>\"]` and gets a marker (an id that is not on the page is skipped). */\n  sections?: ReviewSection[];\n  /** A final pick between the versions: one decision `<decisionPrefix>-pick`, the options are the version labels, plus a note. */\n  final?: { question: string };\n}) {\n  const uid = useId();\n  const [open, setOpen] = useState(false);\n  const [choices, setChoices] = useState<Record<string, string>>({});\n  const [notes, setNotes] = useState<Record<string, string>>({});\n  const [status, setStatus] = useState<Record<string, ReviewStatus>>({});\n  const [messages, setMessages] = useState<Record<string, string>>({});\n  const [sending, setSending] = useState<string>('');\n  const live = isPreview(preview);\n  const ok = isLocalRelay(relay?.url) && !!relay?.token;\n  const base = ok ? relay!.url.replace(/\\/+$/, '') : '';\n  const here = versions.find((v) => v.id === current) ?? versions[0];\n  const secs = sections ?? [];\n  // every decision on this page: the versions, each (version, section) pair, and the pick\n  const ids = [\n    ...versions.map((v) => decisionId(decisionPrefix, v.id)),\n    ...versions.flatMap((v) => secs.map((x) => sectionDecisionId(decisionPrefix, v.id, x.id))),\n    ...(final ? [pickId(decisionPrefix)] : []),\n  ];\n  const idsKey = ids.join(',');\n  const failures = useRef(0);\n\n  // Live status of every decision, from the relay: on load and every 5 s (30 s after three failures, and not while the tab is hidden).\n  useEffect(() => {\n    if (!live || !base) return;\n    let stop = false;\n    let timer = 0;\n    const tick = async () => {\n      if (!document.hidden) {\n        try {\n          const r = await fetch(`${base}/status?ids=${encodeURIComponent(idsKey)}`, { headers: { 'X-KH-Token': relay!.token }, credentials: 'omit', redirect: 'error', cache: 'no-store' });\n          if (!r.ok) throw new Error(String(r.status));\n          const list = (await r.json()) as { id: string; status: string }[];\n          failures.current = 0;\n          if (!stop) setStatus((s) => ({ ...s, ...Object.fromEntries((Array.isArray(list) ? list : []).filter((x) => idsKey.split(',').includes(x.id)).map((x) => [x.id, (x.status in STATUS_WORDS ? x.status : 'open') as ReviewStatus])) }));\n        } catch { failures.current++; }\n      }\n      if (!stop) timer = window.setTimeout(tick, failures.current > 2 ? OFFLINE_POLL_MS : POLL_MS);\n    };\n    void tick();\n    return () => { stop = true; window.clearTimeout(timer); };\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [live, base, idsKey]);\n\n  if (!live || !here) return null;\n\n  const lineOf = (id: string) => copyLine({ id, address, choice: choices[id] ?? '', note: notes[id] ?? '' });\n  const say = (id: string, m: string) => setMessages((x) => ({ ...x, [id]: m }));\n  const send = async (id: string) => {\n    const choice = choices[id] ?? '';\n    const note = notes[id] ?? '';\n    if (!choice) { say(id, id === pickId(decisionPrefix) ? 'Pick a version first.' : 'Pick like or don\\'t like first.'); return; }\n    const fallback = async (why: string) => {\n      try { await navigator.clipboard.writeText(lineOf(id)); say(id, `${why} The answer line is copied: paste it to the agent.`); } catch { say(id, `${why} Copy the answer line and paste it to the agent.`); }\n    };\n    if (!base) { await fallback(relay?.url && !isLocalRelay(relay.url) ? 'The relay address is not on this machine, so it is not used.' : 'No relay is set.'); return; }\n    setSending(id);\n    say(id, 'Sending…');\n    try {\n      const r = await fetch(`${base}/answers`, { method: 'POST', headers: { 'X-KH-Token': relay!.token, 'Content-Type': 'application/json' }, body: JSON.stringify(answerPayload({ id, address, choice, note })), credentials: 'omit', redirect: 'error', cache: 'no-store' });\n      if (!r.ok) throw Object.assign(new Error('http'), { http: r.status });\n      const j = (await r.json().catch(() => ({}))) as { status?: string };\n      const st = (j.status && j.status in STATUS_WORDS ? j.status : 'answered') as ReviewStatus;\n      setStatus((x) => ({ ...x, [id]: st }));\n      say(id, `Sent. ${STATUS_WORDS[st]}.`);\n    } catch (e) {\n      const http = (e as { http?: number }).http;\n      await fallback(http === 401 || http === 403 ? 'The relay refused this page\\'s token.' : http ? `The relay answered ${http}.` : 'The relay is not reachable.');\n    } finally { setSending(''); }\n  };\n  const setChoice = (id: string, c: string) => setChoices((s) => ({ ...s, [id]: s[id] === c ? '' : c }));\n  const setNote = (id: string, n: string) => setNotes((s) => ({ ...s, [id]: n }));\n\n  const id = decisionId(decisionPrefix, here.id);\n  const choice = choices[id] ?? '';\n  const note = notes[id] ?? '';\n  const line = lineOf(id);\n  const pid = pickId(decisionPrefix);\n\n  return (\n    <>\n      {/* For `answer register <page.html>`: the same attributes as a report page, hidden. A hidden <main> beside the page's own is valid HTML. */}\n      <main hidden data-kh-relay={relay?.url ?? ''} data-kh-token={relay?.token ?? ''} data-kh-page={address.page}>\n        <ul>\n          {versions.map((v) => (\n            <li key={v.id} data-kh-decision data-id={decisionId(decisionPrefix, v.id)} data-version=\"1\" data-seat={address.seat} data-repo={address.repo} data-session={address.session} data-asked-at={address.askedAt ?? ''}>\n              <h3>{`Version ${v.label}: like or don't like?`}</h3>\n            </li>\n          ))}\n          {versions.flatMap((v) => secs.map((x) => (\n            <li key={`${v.id}-${x.id}`} data-kh-decision data-id={sectionDecisionId(decisionPrefix, v.id, x.id)} data-version=\"1\" data-seat={address.seat} data-repo={address.repo} data-session={address.session} data-asked-at={address.askedAt ?? ''}>\n              <h3>{`Version ${v.label}, ${x.label}: like or don't like?`}</h3>\n            </li>\n          )))}\n          {final && (\n            <li data-kh-decision data-id={pid} data-version=\"1\" data-seat={address.seat} data-repo={address.repo} data-session={address.session} data-asked-at={address.askedAt ?? ''}>\n              <h3>{final.question}</h3>\n            </li>\n          )}\n        </ul>\n      </main>\n      {secs.length > 0 && (\n        <SectionMarkers sections={secs} versionLabel={here.label} choices={choices} notes={notes} status={status} messages={messages} sending={sending}\n          idOf={(sid) => sectionDecisionId(decisionPrefix, here.id, sid)} setChoice={setChoice} setNote={setNote} send={send} />\n      )}\n      <aside aria-label=\"Review\" data-kh-review-bar className=\"@container fixed inset-x-0 bottom-0 z-50 max-h-[85vh] overflow-y-auto border-t border-kh-line-strong bg-kh-surface pb-[env(safe-area-inset-bottom)] text-kh-ink shadow-kh-2\">\n        <div className=\"mx-auto flex max-w-kh-page flex-col gap-2 px-kh-gutter py-2\">\n          <div className=\"flex items-center justify-between gap-3 @2xl:hidden\">\n            <button type=\"button\" aria-expanded={open} aria-controls={`${uid}-panel`} onClick={() => setOpen((o) => !o)} className={cn(btn, 'border-kh-line-strong bg-kh-surface')}>\n              Review: {here.label}\n            </button>\n            <StatusDot status={status[id]} />\n          </div>\n          <div id={`${uid}-panel`} className={cn('flex-col gap-3 @2xl:flex', open ? 'flex' : 'hidden')}>\n            <div className=\"flex flex-col gap-3 @2xl:flex-row @2xl:items-center\">\n              <nav aria-label=\"Versions\" className=\"flex flex-wrap gap-2\">\n                {versions.map((v) => {\n                  const vid = decisionId(decisionPrefix, v.id);\n                  return (\n                    <a key={v.id} href={v.href} aria-current={v.id === here.id ? 'page' : undefined} className={cn(btn, 'gap-2 no-underline', v.id === here.id ? 'border-kh-ink bg-kh-ink text-kh-on-ink' : 'border-kh-line-strong bg-kh-surface text-kh-ink')}>\n                      {v.label}\n                      <StatusDot status={status[vid]} />\n                    </a>\n                  );\n                })}\n              </nav>\n              <div role=\"group\" aria-label={`Verdict on ${here.label}`} className=\"flex gap-2\">\n                {(['like', 'dislike'] as const).map((c) => (\n                  <button key={c} type=\"button\" aria-pressed={choice === c} onClick={() => setChoice(id, c)} className={cn(btn, choice === c ? 'border-kh-ink bg-kh-ink text-kh-on-ink' : 'border-kh-line-strong bg-kh-surface')}>\n                    {c === 'like' ? 'Like' : 'Don\\'t like'}\n                  </button>\n                ))}\n              </div>\n              <label className=\"flex min-w-0 flex-1 flex-col gap-1 text-kh-caption text-kh-muted @2xl:flex-row @2xl:items-center\">\n                <span className=\"sr-only @2xl:not-sr-only @2xl:shrink-0\">Note</span>\n                <input type=\"text\" value={note} onChange={(e) => setNote(id, e.target.value)} aria-label={`Note on ${here.label}`} placeholder=\"Note (optional)\" className=\"min-h-11 min-w-0 flex-1 rounded-kh border border-kh-line-strong bg-kh-canvas px-3 text-kh-small text-kh-ink\" />\n              </label>\n              <button type=\"button\" disabled={sending === id} onClick={() => void send(id)} className={cn(btn, 'border-kh-ink bg-kh-ink text-kh-on-ink disabled:opacity-50')}>Send</button>\n            </div>\n            {messages[id] && <p role=\"status\" className=\"text-kh-caption text-kh-ink-2 [overflow-wrap:anywhere]\">{messages[id]}</p>}\n            {final && (\n              <fieldset data-kh-pick className=\"flex flex-col gap-2 rounded-kh border border-kh-line p-3 @2xl:flex-row @2xl:flex-wrap @2xl:items-center\">\n                <legend className=\"px-1 text-kh-small font-medium\">{final.question} <StatusDot status={status[pid]} /></legend>\n                <div role=\"radiogroup\" aria-label={final.question} className=\"flex flex-wrap gap-2\">\n                  {versions.map((v) => (\n                    <label key={v.id} className={cn(btn, 'cursor-pointer gap-2 has-[:focus-visible]:outline-2 has-[:focus-visible]:outline-offset-2 has-[:focus-visible]:outline-(--kh-focus)', choices[pid] === v.label ? 'border-kh-ink bg-kh-ink text-kh-on-ink' : 'border-kh-line-strong bg-kh-surface')}>\n                      <input type=\"radio\" name={`${uid}-pick`} value={v.label} checked={choices[pid] === v.label} onChange={() => setChoices((s) => ({ ...s, [pid]: v.label }))} className=\"sr-only\" />\n                      {v.label}\n                    </label>\n                  ))}\n                </div>\n                <label className=\"flex min-w-0 flex-1 flex-col gap-1\">\n                  <span className=\"sr-only\">Which version, and what to take from the others</span>\n                  <input type=\"text\" value={notes[pid] ?? ''} onChange={(e) => setNote(pid, e.target.value)} placeholder=\"Which version, and what to take from the others\" className=\"min-h-11 min-w-0 flex-1 rounded-kh border border-kh-line-strong bg-kh-canvas px-3 text-kh-small text-kh-ink @2xl:min-w-64\" />\n                </label>\n                <button type=\"button\" disabled={sending === pid} onClick={() => void send(pid)} className={cn(btn, 'border-kh-ink bg-kh-ink text-kh-on-ink disabled:opacity-50')}>Send pick</button>\n                {messages[pid] && <p role=\"status\" className=\"w-full text-kh-caption text-kh-ink-2 [overflow-wrap:anywhere]\">{messages[pid]}</p>}\n              </fieldset>\n            )}\n          </div>\n          <details className=\"text-kh-caption text-kh-muted\">\n            <summary className=\"inline-flex min-h-6 cursor-pointer items-center\">Answer by copying</summary>\n            <code className=\"mt-1 block [overflow-wrap:anywhere]\" data-kh-copy-line>{line}</code>\n          </details>\n        </div>\n      </aside>\n    </>\n  );\n}\n\n/**\n * One marker per section that is on the page: a button \"Review <label>\" in the section's top right corner (fixed, kept in view while the section is, updated on\n * scroll and resize through the CSSOM, so no inline style is ever written into the HTML) that opens a small panel for the current version of that section.\n * Markers are in page order, so the keyboard reaches them in that order; a section id that is not on the page draws nothing.\n */\nfunction SectionMarkers({ sections, versionLabel, idOf, choices, notes, status, messages, sending, setChoice, setNote, send }: {\n  sections: ReviewSection[]; versionLabel: string; idOf: (sectionId: string) => string;\n  choices: Record<string, string>; notes: Record<string, string>; status: Record<string, ReviewStatus>; messages: Record<string, string>; sending: string;\n  setChoice: (id: string, c: string) => void; setNote: (id: string, n: string) => void; send: (id: string) => Promise<void>;\n}) {\n  const uid = useId();\n  const [found, setFound] = useState<ReviewSection[]>([]);\n  const [openId, setOpenId] = useState('');\n  const nodes = useRef(new Map<string, HTMLElement>());\n  const key = sections.map((s) => s.id).join('\\n');\n\n  // which sections are on the page, in document order (looked up once the page is there, and again when sections change)\n  useEffect(() => {\n    const els = sections.map((s) => ({ s, el: sectionElement(s.id) })).filter((x): x is { s: ReviewSection; el: HTMLElement } => !!x.el);\n    els.sort((a, b) => (a.el.compareDocumentPosition(b.el) & Node.DOCUMENT_POSITION_FOLLOWING ? -1 : 1));\n    setFound(els.map((x) => x.s));\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [key]);\n\n  const place = useCallback(() => {\n    for (const s of found) {\n      const el = sectionElement(s.id);\n      const node = nodes.current.get(s.id);\n      if (!el || !node) continue;\n      const r = el.getBoundingClientRect();\n      const top = Math.min(Math.max(r.top + 8, 8), Math.max(8, r.bottom - 48));\n      const shown = r.bottom > 56 && r.top < window.innerHeight - 96;\n      node.style.top = `${Math.round(top)}px`;\n      node.style.visibility = shown || openId === s.id ? 'visible' : 'hidden';\n      node.dataset.up = top > window.innerHeight * 0.45 ? 'true' : 'false';\n    }\n  }, [found, openId]);\n  useLayoutEffect(() => {\n    place();\n    let raf = 0;\n    const on = () => { cancelAnimationFrame(raf); raf = requestAnimationFrame(place); };\n    window.addEventListener('scroll', on, { passive: true });\n    window.addEventListener('resize', on);\n    return () => { cancelAnimationFrame(raf); window.removeEventListener('scroll', on); window.removeEventListener('resize', on); };\n  }, [place]);\n\n  return (\n    <>\n      {found.map((s) => {\n        const id = idOf(s.id);\n        const isOpen = openId === s.id;\n        const choice = choices[id] ?? '';\n        return (\n          <div key={s.id} ref={(n) => { if (n) nodes.current.set(s.id, n); else nodes.current.delete(s.id); }} data-kh-marker={s.id} data-up=\"false\"\n            className=\"group fixed right-2 z-40 invisible\"\n            onKeyDown={(e) => { if (e.key === 'Escape' && isOpen) { setOpenId(''); (e.currentTarget.querySelector('button[aria-expanded]') as HTMLElement | null)?.focus(); } }}>\n            <button type=\"button\" aria-expanded={isOpen} aria-controls={`${uid}-${s.id}`} onClick={() => setOpenId(isOpen ? '' : s.id)}\n              className={cn(btn, 'min-h-9 gap-2 border-kh-ink bg-kh-surface px-2.5 text-kh-caption shadow-kh-2')}>\n              Review {s.label}\n              <StatusDot status={status[id]} />\n            </button>\n            {isOpen && (\n              <div id={`${uid}-${s.id}`} role=\"group\" aria-label={`Review ${s.label}, version ${versionLabel}`}\n                className=\"absolute right-0 top-full mt-1 flex w-72 max-w-[calc(100vw-1rem)] flex-col gap-2 rounded-kh-lg border border-kh-line-strong bg-kh-surface p-3 shadow-kh-3 group-data-[up=true]:bottom-full group-data-[up=true]:top-auto group-data-[up=true]:mb-1 group-data-[up=true]:mt-0\">\n                <p className=\"text-kh-small font-medium\">{s.label}, version {versionLabel}</p>\n                <div role=\"group\" aria-label={`Verdict on ${s.label}`} className=\"flex gap-2\">\n                  {(['like', 'dislike'] as const).map((c) => (\n                    <button key={c} type=\"button\" aria-pressed={choice === c} onClick={() => setChoice(id, c)} className={cn(btn, 'flex-1', choice === c ? 'border-kh-ink bg-kh-ink text-kh-on-ink' : 'border-kh-line-strong bg-kh-surface')}>\n                      {c === 'like' ? 'Like' : 'Don\\'t like'}\n                    </button>\n                  ))}\n                </div>\n                <input type=\"text\" value={notes[id] ?? ''} onChange={(e) => setNote(id, e.target.value)} aria-label={`Note on ${s.label}`} placeholder=\"Note (optional)\" className=\"min-h-11 rounded-kh border border-kh-line-strong bg-kh-canvas px-3 text-kh-small text-kh-ink\" />\n                <button type=\"button\" disabled={sending === id} onClick={() => void send(id)} className={cn(btn, 'border-kh-ink bg-kh-ink text-kh-on-ink disabled:opacity-50')}>Send</button>\n                {messages[id] && <p role=\"status\" className=\"text-kh-caption text-kh-ink-2 [overflow-wrap:anywhere]\">{messages[id]}</p>}\n              </div>\n            )}\n          </div>\n        );\n      })}\n    </>\n  );\n}\n\n/** A dot with a shape and a word (never colour alone) for the relay's status of one decision; nothing until the relay has said. */\nfunction StatusDot({ status }: { status: ReviewStatus | undefined }) {\n  if (!status) return null;\n  return (\n    <span className=\"inline-flex items-center gap-1 text-kh-caption\" title={STATUS_WORDS[status]}>\n      <span aria-hidden data-state={status} className={cn('inline-block size-2.5', DOT[status])} />\n      <span className=\"sr-only\">{STATUS_WORDS[status]}</span>\n    </span>\n  );\n}\n"
    }
  ]
}
