{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "type-answer",
  "type": "registry:ui",
  "title": "Type Answer",
  "description": "A quiz round where people type the answer. Harder than picking, and fairer than it looks: case, accents, punctuation and a slip of a letter in a long word are forgiven, while a different number never is (see `typed-answer-model`). The reveal marks the…",
  "author": "ofri-peretz <https://github.com/ofri-peretz>",
  "categories": [
    "games",
    "game"
  ],
  "dependencies": [],
  "registryDependencies": [
    "https://ds.interlace.tools/r/interlace-base.json",
    "https://ds.interlace.tools/r/button.json",
    "https://ds.interlace.tools/r/cn.json",
    "https://ds.interlace.tools/r/input.json",
    "https://ds.interlace.tools/r/motion-token.json",
    "https://ds.interlace.tools/r/tally-bars.json",
    "https://ds.interlace.tools/r/timer-ring.json",
    "https://ds.interlace.tools/r/use-reduced-motion.json"
  ],
  "files": [
    {
      "path": "registry/interlace-ui/games/type-answer.tsx",
      "target": "components/ui/games/type-answer.tsx",
      "type": "registry:ui",
      "content": "'use client';\n\nimport * as React from 'react';\n\n// @interlace/type-answer v1.1.0 — Interlace design system.\n// Docs, props and live preview: https://ds.interlace.tools/c/type-answer\n// What changed since: https://ds.interlace.tools/c/type-answer#history\n// Generated banner — keep it, the upgrade diff reads this version.\n\n/**\n * @interlace/ui — TypeAnswer\n *\n * A quiz round where people type the answer. Harder than picking, and\n * fairer than it looks: case, accents, punctuation and a slip of a letter in\n * a long word are forgiven, while a different number never is (see\n * `typed-answer-model`). The reveal marks the answer, says in words how you\n * did (and the right spelling when you were close), and shows what the room\n * typed, folded together, so a common wrong answer becomes the talking\n * point.\n *\n * ## Anatomy\n *\n *   TypeAnswer                       (div — data-slot=\"type-answer\", data-state=asking|revealed, data-outcome)\n *     ├─ div                         (data-slot=\"type-answer-header\": meta, clock and \"Stop the clock\")\n *     ├─ p                           (data-slot=\"type-answer-prompt\", labels the field)\n *     ├─ form                        (data-slot=\"type-answer-form\": Input + Answer; Enter sends)\n *     ├─ p tabIndex=-1 aria-live     (data-slot=\"type-answer-result\")\n *     ├─ TallyBars                   (data-slot=\"type-answer-spread\": what the room typed, optional)\n *     └─ div                         (data-slot=\"type-answer-explanation\": opens on reveal)\n *\n * ## The clock\n *\n * As in `QuizQuestion`: `timeLimit` starts a TimerRing when the round is on\n * screen; running out sends whatever is typed so far (an empty field is no\n * answer). \"Stop the clock\" turns it off (WCAG 2.2.1) and scores without\n * the speed share. Typing takes longer than tapping: give it more seconds.\n *\n * ## Motion\n *\n * On the reveal the field settles with a small lift when right and a short\n * sideways shake when wrong (250ms, transform), and the room's bars grow.\n * Under reduced motion all of it is in its end state.\n *\n * ## MIN_VIEWPORT — 320\n *\n * | Rule | Concept                   | Where in this file                                    |\n * | ---- | ------------------------- | ----------------------------------------------------- |\n * | R4   | Extends native el         | `div` props                                           |\n * | R6   | data-slot per part        | type-answer / -header / -prompt / -form / -field / -send / -result / -spread / -explanation |\n * | R7   | cn + ...rest              | `cn(…, className)` + `{...props}`                     |\n * | R9   | Controlled + uncontrolled | `result` / `defaultResult` / `onAnswer`               |\n * | R14  | Declares min viewport     | `data-min-viewport` + exported const                  |\n * | R26  | A11y                      | labelled field; outcome in words; result focused; a close answer spelled out |\n */\n\nimport { cn } from '@/lib/utils';\nimport { motionEase } from '@/lib/motion-token';\nimport { useReducedMotion } from '@/hooks/use-reduced-motion';\nimport { Button } from '@/components/ui/button';\nimport { Input } from '@/components/ui/input';\nimport type { QuizScoreOptions } from '@/components/ui/games/quiz-model';\nimport { TallyBars, type TallyBarsLabels, type TallyMark } from '@/components/ui/games/tally-bars';\nimport { tally } from '@/components/ui/games/tally-model';\nimport { TimerRing, type TimerRingLabels } from '@/components/ui/games/timer-ring';\nimport { groupTyped, normalizeAnswer, scoreTyped, type TypedResult, type TypedRules } from '@/components/ui/games/typed-answer-model';\n\nexport const MIN_VIEWPORT = 320 as const;\n\ninterface TypeAnswerLabels {\n  /** @default 'Answer' */\n  send?: string;\n  /** The field's placeholder. @default 'Type your answer' */\n  placeholder?: string;\n  /** The result sentence. `answer` is the first accepted answer. */\n  result?: (r: { outcome: 'exact' | 'close' | 'wrong' | 'timeout'; points: number; answer: string }) => string;\n  /** @default 'Stop the clock' */\n  stopClock?: string;\n  /** @default 'Clock stopped' */\n  clockStopped?: string;\n  /** Names the room's answers. @default 'What the room typed' */\n  spread?: string;\n  /** The row that folds the rest together. @default 'Something else' */\n  other?: string;\n  timer?: TimerRingLabels;\n  tally?: TallyBarsLabels;\n}\n\ntype TypeAnswerProps = Omit<React.ComponentProps<'div'>, 'children' | 'onChange'> &\n  TypedRules & {\n    question: React.ReactNode;\n    /** Every answer that counts, the main one first. Keep them off the client until the reveal if the game is competitive. */\n    accepted: readonly string[];\n    /** Seconds to answer. Leave out for no clock. */\n    timeLimit?: number;\n    result?: TypedResult | null;\n    defaultResult?: TypedResult | null;\n    /** Called once, when the player sends or time runs out. */\n    onAnswer?: (result: TypedResult) => void;\n    /** What everyone else typed, shown after the reveal. */\n    room?: readonly string[];\n    /** `room` already holds this player's answer. @default false */\n    roomIncludesAnswer?: boolean;\n    /** Rows in the room's answers before the rest fold into one. @default 5 */\n    spreadRows?: number;\n    /** @default 60 */\n    maxLength?: number;\n    meta?: React.ReactNode;\n    explanation?: React.ReactNode;\n    score?: QuizScoreOptions;\n    locale?: string;\n    labels?: TypeAnswerLabels;\n  };\n\nconst RESULT: NonNullable<TypeAnswerLabels['result']> = ({ outcome, points, answer }) =>\n  outcome === 'exact'\n    ? `Right. +${points} points.`\n    : outcome === 'close'\n      ? `Right, it is spelled ${answer}. +${points} points.`\n      : outcome === 'timeout'\n        ? `Time's up. The answer is ${answer}.`\n        : `Not this time. The answer is ${answer}.`;\n\nfunction TypeAnswer({\n  question,\n  accepted,\n  timeLimit,\n  result: resultProp,\n  defaultResult = null,\n  onAnswer,\n  room,\n  roomIncludesAnswer = false,\n  spreadRows = 5,\n  maxLength = 60,\n  meta,\n  explanation,\n  score,\n  tolerance,\n  ignore,\n  locale,\n  labels,\n  className,\n  ...props\n}: TypeAnswerProps) {\n  const [uncontrolled, setUncontrolled] = React.useState<TypedResult | null>(defaultResult);\n  const result = resultProp === undefined ? uncontrolled : resultProp;\n  const revealed = result !== null && result !== undefined;\n  const reduced = useReducedMotion();\n  const timed = typeof timeLimit === 'number' && timeLimit > 0;\n  const [text, setText] = React.useState('');\n  const [deadline, setDeadline] = React.useState<number | null>(null);\n  const [stopped, setStopped] = React.useState(false);\n  const startRef = React.useRef<number | null>(null);\n  const sent = React.useRef(revealed);\n  const animate = React.useRef(false);\n  const promptId = React.useId();\n  const explanationId = React.useId();\n  const fieldRef = React.useRef<HTMLInputElement>(null);\n  const resultRef = React.useRef<HTMLParagraphElement>(null);\n  const rules = { tolerance, ignore };\n\n  React.useEffect(() => {\n    if (!timed || revealed) return;\n    const start = Date.now();\n    startRef.current = start;\n    setDeadline(start + (timeLimit as number) * 1000);\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [timed, timeLimit]);\n\n  React.useEffect(() => {\n    if (!revealed) sent.current = false;\n  }, [revealed]);\n\n  const answer = (typed: string | null) => {\n    if (revealed || sent.current) return;\n    sent.current = true;\n    animate.current = true;\n    const limitMs = timed ? (timeLimit as number) * 1000 : undefined;\n    const elapsedMs = timed && !stopped && startRef.current !== null ? Date.now() - startRef.current : undefined;\n    const scored = scoreTyped({ text: typed, limitMs, elapsedMs }, accepted, { ...score, ...rules });\n    setDeadline(null);\n    if (resultProp === undefined) setUncontrolled(scored);\n    onAnswer?.(scored);\n  };\n\n  React.useEffect(() => {\n    if (!revealed || !animate.current) return;\n    animate.current = false;\n    // Take focus from the field (or from nowhere, on a timeout); never from elsewhere on the page.\n    const active = document.activeElement;\n    if (!active || active === document.body || fieldRef.current?.form?.contains(active)) resultRef.current?.focus();\n    const field = fieldRef.current;\n    if (reduced || !field || typeof field.animate !== 'function') return;\n    const timing = { duration: 250, easing: motionEase(field, 'move') };\n    if (result.outcome === 'correct') {\n      field.animate([{ transform: 'none' }, { transform: 'translateY(-3px)' }, { transform: 'none' }], timing);\n    } else if (result.outcome === 'wrong') {\n      field.animate(\n        [\n          { transform: 'none' },\n          { transform: 'translateX(-4px)' },\n          { transform: 'translateX(4px)' },\n          { transform: 'translateX(-2px)' },\n          { transform: 'none' },\n        ],\n        timing,\n      );\n    }\n    // Once, on the reveal.\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [revealed]);\n\n  const main = accepted[0] ?? '';\n  const mark: TallyMark | undefined = !revealed ? undefined : result.outcome === 'correct' ? 'correct' : 'wrong';\n  const shownText = revealed ? (result.text ?? '') : text;\n\n  const spread = React.useMemo(() => {\n    if (!revealed || !room) return null;\n    const own = result.text && normalizeAnswer(result.text, ignore) ? result.text : null;\n    const all = own && !roomIncludesAnswer ? [...room, own] : [...room];\n    const groups = groupTyped(all, accepted, rules);\n    if (groups.length === 0) return null;\n    const keep = Math.max(1, spreadRows);\n    // The right answer always has a row, even when few typed it.\n    const right = groups.find((g) => g.correct);\n    let top = groups.slice(0, keep);\n    if (right && !top.includes(right)) top = [...top.slice(0, keep - 1), right];\n    const rest = groups.filter((g) => !top.includes(g)).reduce((n, g) => n + g.count, 0);\n    const ids = top.map((_, i) => `g${i}`).concat(rest > 0 ? ['other'] : []);\n    const counts: Record<string, number> = Object.fromEntries(top.map((g, i) => [`g${i}`, g.count]));\n    if (rest > 0) counts.other = rest;\n    const mine =\n      own === null\n        ? null\n        : result.outcome === 'correct'\n          ? `g${top.indexOf(right as (typeof groups)[number])}`\n          : (() => {\n              const i = top.findIndex(\n                (g) => !g.correct && normalizeAnswer(g.text, ignore) === normalizeAnswer(own, ignore),\n              );\n              return i >= 0 ? `g${i}` : rest > 0 ? 'other' : null;\n            })();\n    const names: Record<string, React.ReactNode> = Object.fromEntries(top.map((g, i) => [`g${i}`, g.text]));\n    names.other = labels?.other ?? 'Something else';\n    const marks: Record<string, TallyMark> = {};\n    top.forEach((g, i) => {\n      if (g.correct) marks[`g${i}`] = 'correct';\n    });\n    if (mine && !marks[mine]) marks[mine] = 'wrong';\n    return { rows: tally(ids, counts, { vote: mine, countsIncludeVote: true }).rows, names, marks };\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [revealed, result, room, roomIncludesAnswer, accepted, spreadRows, tolerance, ignore, labels?.other]);\n\n  return (\n    <div\n      data-slot=\"type-answer\"\n      data-state={revealed ? 'revealed' : 'asking'}\n      data-outcome={revealed ? result.outcome : undefined}\n      data-min-viewport={String(MIN_VIEWPORT)}\n      className={cn('grid gap-5', className)}\n      {...props}\n    >\n      {meta || timed ? (\n        <div data-slot=\"type-answer-header\" className=\"flex min-h-10 flex-wrap items-center justify-between gap-3\">\n          <div className=\"text-muted-foreground text-sm font-medium\">{meta}</div>\n          {timed && !revealed ? (\n            <div className=\"flex items-center gap-2\">\n              {stopped ? (\n                <span className=\"text-muted-foreground text-sm\">{labels?.clockStopped ?? 'Clock stopped'}</span>\n              ) : (\n                <>\n                  <Button\n                    type=\"button\"\n                    variant=\"ghost\"\n                    size=\"sm\"\n                    onClick={() => {\n                      setStopped(true);\n                      setDeadline(null);\n                    }}\n                  >\n                    {labels?.stopClock ?? 'Stop the clock'}\n                  </Button>\n                  <TimerRing\n                    seconds={timeLimit as number}\n                    deadline={deadline}\n                    onExpire={() => answer(text.trim() ? text : null)}\n                    labels={labels?.timer}\n                  />\n                </>\n              )}\n            </div>\n          ) : null}\n        </div>\n      ) : null}\n\n      <p id={promptId} data-slot=\"type-answer-prompt\" className=\"font-heading text-xl font-semibold text-balance\">\n        {question}\n      </p>\n\n      <form\n        data-slot=\"type-answer-form\"\n        className=\"flex flex-wrap gap-2\"\n        onSubmit={(e) => {\n          e.preventDefault();\n          if (text.trim()) answer(text);\n          else fieldRef.current?.focus();\n        }}\n      >\n        <Input\n          ref={fieldRef}\n          data-slot=\"type-answer-field\"\n          aria-labelledby={promptId}\n          value={shownText}\n          onChange={(e) => setText(e.target.value)}\n          readOnly={revealed}\n          maxLength={maxLength}\n          autoComplete=\"off\"\n          autoCapitalize=\"off\"\n          autoCorrect=\"off\"\n          spellCheck={false}\n          enterKeyHint=\"send\"\n          placeholder={revealed ? undefined : (labels?.placeholder ?? 'Type your answer')}\n          className={cn(\n            'min-w-0 flex-1 basis-48',\n            mark === 'correct' && 'border-success bg-success/10',\n            mark === 'wrong' && 'border-destructive bg-destructive/10',\n          )}\n        />\n        {revealed ? null : (\n          <Button data-slot=\"type-answer-send\" type=\"submit\">\n            {labels?.send ?? 'Answer'}\n          </Button>\n        )}\n      </form>\n\n      <p\n        ref={resultRef}\n        tabIndex={-1}\n        data-slot=\"type-answer-result\"\n        aria-live=\"polite\"\n        aria-describedby={revealed && explanation ? explanationId : undefined}\n        className={cn(\n          'focus-visible:outline-ring rounded-sm text-base font-semibold outline-offset-4 empty:hidden focus-visible:outline-2',\n          revealed && result.outcome === 'correct' ? 'text-success' : 'text-foreground',\n        )}\n      >\n        {revealed\n          ? (labels?.result ?? RESULT)({\n              outcome:\n                result.outcome === 'timeout'\n                  ? 'timeout'\n                  : result.outcome === 'wrong'\n                    ? 'wrong'\n                    : result.match.outcome === 'close'\n                      ? 'close'\n                      : 'exact',\n              points: result.points,\n              answer: result.match.matched ?? main,\n            })\n          : ''}\n      </p>\n\n      {spread ? (\n        <section\n          data-slot=\"type-answer-spread\"\n          aria-label={labels?.spread ?? 'What the room typed'}\n          className=\"grid gap-2\"\n        >\n          <p className=\"text-muted-foreground text-xs font-semibold tracking-wide uppercase\">\n            {labels?.spread ?? 'What the room typed'}\n          </p>\n          <TallyBars\n            rows={spread.rows}\n            optionLabels={spread.names}\n            marks={spread.marks}\n            locale={locale}\n            labels={labels?.tally}\n          />\n        </section>\n      ) : null}\n\n      {explanation ? (\n        <div\n          data-slot=\"type-answer-explanation\"\n          className={cn(\n            'grid',\n            'motion-safe:transition-[grid-template-rows,opacity] motion-safe:duration-(--duration-medium) motion-safe:ease-enter',\n            revealed ? 'grid-rows-[1fr] opacity-100' : 'grid-rows-[0fr] opacity-0',\n          )}\n          inert={revealed ? undefined : true}\n        >\n          <div\n            id={explanationId}\n            className=\"text-muted-foreground -m-1 min-h-0 overflow-hidden p-1 text-sm leading-relaxed\"\n          >\n            {explanation}\n          </div>\n        </div>\n      ) : null}\n    </div>\n  );\n}\nTypeAnswer.displayName = 'TypeAnswer';\n\nexport { TypeAnswer };\nexport type { TypeAnswerProps, TypeAnswerLabels };\n"
    },
    {
      "path": "registry/interlace-ui/games/quiz-model.ts",
      "target": "components/ui/games/quiz-model.ts",
      "type": "registry:ui",
      "content": "export type QuizOutcome = 'correct' | 'wrong' | 'timeout';\n\nexport interface QuizScoreOptions {\n  /** Points for a right answer given at once. @default 1000 */\n  maxPoints?: number;\n  /** Share of the points that depends on speed, 0–1. @default 0.5 */\n  speedShare?: number;\n}\n\nexport interface QuizAnswerInput {\n  /** The chosen option's id; null when time ran out first. */\n  choice: string | null;\n  /** Milliseconds from the start to the answer. Leave out when the clock was stopped. */\n  elapsedMs?: number;\n  /** The question's time limit in milliseconds. Leave out for an untimed question. */\n  limitMs?: number;\n}\n\nexport interface QuizResult {\n  choice: string | null;\n  correct: string;\n  outcome: QuizOutcome;\n  points: number;\n  /** Whether the answer raced a running clock (the speed share was in play). */\n  timed: boolean;\n  elapsedMs?: number;\n}\n\nconst clamp01 = (n: number) => Math.min(1, Math.max(0, n));\n\n/** Score one answer against the right option's id. */\nexport function scoreAnswer(input: QuizAnswerInput, correct: string, options: QuizScoreOptions = {}): QuizResult {\n  // A host config that is NaN, infinite or negative would score NaN and poison the standings: use the defaults.\n  const maxPoints = Number.isFinite(options.maxPoints) && (options.maxPoints as number) >= 0 ? (options.maxPoints as number) : 1000;\n  const speedShare = clamp01(Number.isFinite(options.speedShare) ? (options.speedShare as number) : 0.5);\n  const { choice, elapsedMs, limitMs } = input;\n  const limited = typeof limitMs === 'number' && limitMs > 0;\n  const timed = limited && Number.isFinite(elapsedMs);\n  const outcome: QuizOutcome = choice === null ? 'timeout' : choice === correct ? 'correct' : 'wrong';\n  let points = 0;\n  if (outcome === 'correct') {\n    const base = limited ? maxPoints * (1 - speedShare) : maxPoints;\n    const speed = timed ? maxPoints * speedShare * (1 - clamp01((elapsedMs as number) / (limitMs as number))) : 0;\n    points = Math.round(base + speed);\n  }\n  return { choice, correct, outcome, points, timed, ...(timed ? { elapsedMs } : {}) };\n}\n\n/**\n * @interlace/ui — games/quiz-model\n *\n * Scoring for a multiple-choice question, with an optional clock. Pure, so a\n * server can score the same answer and a share card can show right or wrong\n * without the answer itself.\n *\n * ## Points\n *\n * A right answer is worth `maxPoints`. When the question was timed, part of\n * that (`speedShare`, half by default) depends on speed: answering at once\n * keeps all of it, answering as the clock runs out keeps none of it. A wrong\n * answer, or no answer before time ran out, is worth 0.\n *\n * A question with no time limit is worth the full `maxPoints`. When a timed\n * question's clock was stopped (a player can always stop it; see QuizQuestion)\n * the answer keeps the part that does not depend on speed, so stopping the\n * clock is always available and never pays more than racing it.\n */\n"
    },
    {
      "path": "registry/interlace-ui/games/tally-model.ts",
      "target": "components/ui/games/tally-model.ts",
      "type": "registry:ui",
      "content": "export interface TallyRow {\n  id: string;\n  count: number;\n  /** count / total, 0–1. 0 when nobody has voted. */\n  share: number;\n  /** Whole percent; the rows sum to 100 when total > 0. */\n  percent: number;\n  /** The viewer's own choice. */\n  mine: boolean;\n  /** Has the highest count (ties all lead). False when nobody has voted. */\n  leading: boolean;\n}\n\nexport interface TallyOptions {\n  /** The viewer's choice, if any. */\n  vote?: string | null;\n  /** The counts already include the viewer's vote. @default false */\n  countsIncludeVote?: boolean;\n}\n\nexport interface Tally {\n  rows: TallyRow[];\n  total: number;\n}\n\n/** Largest count kept per option, so a hostile 1e308 can never push a total to Infinity. */\nconst MAX_COUNT = 1e12;\n\nconst clampCount = (n: number): number =>\n  Number.isFinite(n) ? Math.min(Math.max(Math.floor(n), 0), MAX_COUNT) : 0;\n\n/** Whole percents that sum to 100 (largest remainder). All 0 when the total is 0. */\nexport function wholePercents(input: readonly number[]): number[] {\n  const counts = input.map(clampCount);\n  const total = counts.reduce((a, b) => a + b, 0);\n  if (!(total > 0)) return counts.map(() => 0);\n  const exact = counts.map((c) => (c / total) * 100);\n  const out = exact.map(Math.floor);\n  let left = 100 - out.reduce((a, b) => a + b, 0);\n  const order = exact\n    .map((e, i) => ({ i, rest: e - Math.floor(e) }))\n    // Biggest remainder first; on a tie the earlier option wins, so the result is stable.\n    .sort((a, b) => b.rest - a.rest || a.i - b.i);\n  for (const { i } of order) {\n    if (left <= 0) break;\n    out[i] = (out[i] as number) + 1;\n    left -= 1;\n  }\n  return out;\n}\n\n/** The rows for `ids`, in that order. Unknown ids count 0; negative or non-finite counts count 0. */\nexport function tally(\n  ids: readonly string[],\n  counts: Readonly<Record<string, number>> = {},\n  options: TallyOptions = {},\n): Tally {\n  const { vote = null, countsIncludeVote = false } = options;\n  // A repeated id would be counted twice; an inherited count is not a vote.\n  ids = [...new Set(ids)];\n  const raw = ids.map((id) => {\n    const n = Object.prototype.hasOwnProperty.call(counts, id) ? (counts[id] as number) : 0;\n    const base = clampCount(n);\n    return id === vote && !countsIncludeVote ? base + 1 : base;\n  });\n  const total = raw.reduce((a, b) => a + b, 0);\n  const percents = wholePercents(raw);\n  const top = raw.reduce((a, b) => Math.max(a, b), -Infinity);\n  return {\n    total,\n    rows: ids.map((id, i) => ({\n      id,\n      count: raw[i] as number,\n      share: total > 0 ? (raw[i] as number) / total : 0,\n      percent: percents[i] as number,\n      mine: vote !== null && id === vote,\n      leading: (raw[i] as number) > 0 && raw[i] === top,\n    })),\n  };\n}\n\n/**\n * @interlace/ui — games/tally-model\n *\n * Counts per option turned into shares a reader can trust: whole percents\n * that add up to exactly 100, the viewer's own choice included once, and the\n * leading option named. Pure, so a server can return the same numbers the\n * client draws, and a poll and a quiz share one rule.\n *\n * ## Percents that add up\n *\n * Rounding each share on its own can give 33 + 33 + 33 = 99. The largest\n * remainder method hands the missing points to the options that lost the\n * most to rounding, so the column always sums to 100 (or to 0 when nobody\n * has voted).\n *\n * ## The viewer's vote\n *\n * A poll usually knows the tally from the server and the viewer's choice\n * from the tap that just happened. Pass the server counts with\n * `countsIncludeVote: false` (the default) and the viewer's vote is added\n * once, so the bars move the moment they tap. When the server's counts\n * already hold it (a reload), pass `countsIncludeVote: true`.\n */\n"
    },
    {
      "path": "registry/interlace-ui/games/typed-answer-model.ts",
      "target": "components/ui/games/typed-answer-model.ts",
      "type": "registry:ui",
      "content": "import { scoreAnswer, type QuizResult, type QuizScoreOptions } from '@/components/ui/games/quiz-model';\n\n/**\n * @interlace/ui — typed-answer-model\n *\n * A quiz round where people type the answer instead of picking it. The\n * hard part is fairness: \"Tel-Aviv\", \"tel aviv\" and \"Tel Aviv.\" are the\n * same answer, and a slip of one letter in a long word should still count,\n * while a different number never does (\"1948\" is not \"1949\").\n *\n * `normalizeAnswer` folds case, accents and punctuation and collapses\n * spaces. `matchAnswer` compares against every accepted answer: an exact\n * match after folding, or one within a small number of edits that grows\n * with the answer's length (none up to 4 letters, 1 up to 8, then 2).\n * Answers with digits must match exactly. `scoreTyped` scores with the same\n * clock rules as a multiple-choice question (`scoreAnswer`), so the two\n * kinds of round can share a leaderboard. `groupTyped` counts what the room\n * typed, folded together, for the reveal.\n */\n\nexport type TypedOutcome = 'exact' | 'close' | 'wrong' | 'empty';\n\nexport interface TypedMatch {\n  outcome: TypedOutcome;\n  /** The accepted answer it matched, as written, or null. */\n  matched: string | null;\n  /** Edits from the nearest accepted answer, after folding. */\n  distance: number;\n}\n\nexport interface TypedRules {\n  /** 'exact' turns typo tolerance off. @default 'close' */\n  tolerance?: 'exact' | 'close';\n  /** Words to ignore anywhere, e.g. ['the', 'a'] for English. @default [] */\n  ignore?: readonly string[];\n}\n\n// ponytail: caps on what one phone or a host config can make the comparison chew on.\n// 500 characters is longer than any typed answer; edit distance is quadratic in length.\nconst MAX_TEXT = 500;\n// 100 accepted answers and 50 ignored words cover any real question.\nconst MAX_ACCEPTED = 100;\nconst MAX_IGNORE = 50;\n// A room answers once per player, far under 10000; the cap bounds the grouping loop.\nconst MAX_TEXTS = 10000;\n\n/** Folds case, accents and punctuation; keeps letters, digits, and a point or comma between digits. */\nexport function normalizeAnswer(text: string, ignore: readonly string[] = []): string {\n  if (typeof text !== 'string') return '';\n  const words = Array.isArray(ignore) ? ignore.slice(0, MAX_IGNORE) : [];\n  const folded = text\n    .slice(0, MAX_TEXT)\n    .normalize('NFKD')\n    .replace(/\\p{M}/gu, '')\n    .toLocaleLowerCase()\n    .replace(/(?<=\\d)[.,](?=\\d)/g, '\\uE000')\n    .replace(/[\\p{P}\\p{S}]/gu, ' ')\n    .replace(/\\uE000/g, '.');\n  const skip = new Set(words.map((w) => normalizeAnswer(w)));\n  return folded\n    .split(/\\s+/)\n    .filter((w) => w && !skip.has(w))\n    .join(' ');\n}\n\n/** Edits (insert, delete, change, swap two neighbours) between two strings, stopping past `max`. */\nexport function editDistance(a: string, b: string, max = Infinity): number {\n  const s = [...a];\n  const t = [...b];\n  if (Math.abs(s.length - t.length) > max) return max + 1;\n  let prev2: number[] = [];\n  let prev = Array.from({ length: t.length + 1 }, (_, j) => j);\n  for (let i = 1; i <= s.length; i++) {\n    const row = [i];\n    let best = i;\n    for (let j = 1; j <= t.length; j++) {\n      const cost = s[i - 1] === t[j - 1] ? 0 : 1;\n      let d = Math.min((prev[j] as number) + 1, (row[j - 1] as number) + 1, (prev[j - 1] as number) + cost);\n      if (i > 1 && j > 1 && s[i - 1] === t[j - 2] && s[i - 2] === t[j - 1]) {\n        d = Math.min(d, (prev2[j - 2] as number) + 1);\n      }\n      row[j] = d;\n      best = Math.min(best, d);\n    }\n    if (best > max) return max + 1;\n    prev2 = prev;\n    prev = row;\n  }\n  return prev[t.length] as number;\n}\n\n/** Edits allowed for an accepted answer of this folded length. */\nexport function allowedEdits(folded: string): number {\n  if (typeof folded !== 'string') return 0;\n  if (/\\d/.test(folded)) return 0;\n  const n = [...folded.replace(/\\s/g, '')].length;\n  return n <= 4 ? 0 : n <= 8 ? 1 : 2;\n}\n\nexport function matchAnswer(text: string, accepted: readonly string[], rules: TypedRules = {}): TypedMatch {\n  const { tolerance = 'close', ignore = [] } = rules ?? {};\n  const typed = normalizeAnswer(text, ignore);\n  if (!typed) return { outcome: 'empty', matched: null, distance: Infinity };\n  let best: TypedMatch = { outcome: 'wrong', matched: null, distance: Infinity };\n  for (const answer of Array.isArray(accepted) ? accepted.slice(0, MAX_ACCEPTED) : []) {\n    const target = normalizeAnswer(answer, ignore);\n    if (!target) continue;\n    const limit = tolerance === 'exact' ? 0 : allowedEdits(target);\n    const d = editDistance(typed, target, Math.max(limit, 2));\n    if (d === 0) return { outcome: 'exact', matched: answer, distance: 0 };\n    if (d <= limit && d < best.distance) best = { outcome: 'close', matched: answer, distance: d };\n    else if (best.outcome === 'wrong' && d < best.distance) best = { ...best, distance: d };\n  }\n  return best;\n}\n\nexport interface TypedResult extends QuizResult {\n  /** What was typed; null when time ran out first. */\n  text: string | null;\n  match: TypedMatch;\n}\n\n/** Scores a typed answer with the quiz clock rules. An empty answer counts as no answer. */\nexport function scoreTyped(\n  input: { text: string | null; elapsedMs?: number; limitMs?: number },\n  accepted: readonly string[],\n  options: QuizScoreOptions & TypedRules = {},\n): TypedResult {\n  const match: TypedMatch =\n    input.text === null\n      ? { outcome: 'empty', matched: null, distance: Infinity }\n      : matchAnswer(input.text, accepted, options);\n  const choice = match.outcome === 'empty' ? null : match.outcome === 'wrong' ? 'wrong' : 'right';\n  const scored = scoreAnswer({ choice, elapsedMs: input.elapsedMs, limitMs: input.limitMs }, 'right', options);\n  return { ...scored, text: typeof input.text === 'string' ? input.text : null, match };\n}\n\nexport interface TypedGroup {\n  /** The first way it was written. */\n  text: string;\n  count: number;\n  correct: boolean;\n}\n\n/** What the room typed, folded together, most common first; right answers fold into one row. */\nexport function groupTyped(\n  texts: readonly string[],\n  accepted: readonly string[],\n  rules: TypedRules = {},\n): TypedGroup[] {\n  const groups = new Map<string, TypedGroup & { first: number }>();\n  (Array.isArray(texts) ? texts.slice(0, MAX_TEXTS) : []).forEach((text, i) => {\n    if (typeof text !== 'string') return;\n    const m = matchAnswer(text, accepted, rules);\n    if (m.outcome === 'empty') return;\n    const right = m.outcome !== 'wrong';\n    // A right answer matched something, so there is a first accepted answer to name the row.\n    const main = accepted[0] as string;\n    const key = right ? `\\uE000${main}` : normalizeAnswer(text, rules.ignore);\n    const g = groups.get(key);\n    if (g) g.count += 1;\n    else groups.set(key, { text: right ? main : text.trim().slice(0, MAX_TEXT), count: 1, correct: right, first: i });\n  });\n  return [...groups.values()]\n    .sort((a, b) => b.count - a.count || a.first - b.first)\n    .map(({ text, count, correct }) => ({ text, count, correct }));\n}\n"
    }
  ],
  "meta": {
    "tier": "game",
    "client": true,
    "minViewport": 320,
    "loading": false,
    "version": "1.1.0",
    "since": "2.0.0"
  },
  "docs": "## @interlace/type-answer\n\nInstalled to `components/ui/games/type-answer.tsx`.\n\n```tsx\nimport { /* … */ } from '@/components/ui/games/type-answer';\n```\n\nProps, a11y contract, live preview and source: https://ds.interlace.tools/c/type-answer\n\nRequires the `@interlace/interlace-base` CSS baseline (installed automatically as a registry dependency). For the Interlace look, also add `@interlace/theme`."
}
