{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "closer-game",
  "type": "registry:ui",
  "title": "Closer Game",
  "description": "Guess a number by sliding to it. The player sets a value on a slider (or types it), locks it in, and the answer slides out from their guess to where it really is, with the gap between them shaded and said in words: \"900 off. Close.\" Scoring lives in…",
  "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/slider.json",
    "https://ds.interlace.tools/r/use-reduced-motion.json"
  ],
  "files": [
    {
      "path": "registry/interlace-ui/games/closer-game.tsx",
      "target": "components/ui/games/closer-game.tsx",
      "type": "registry:ui",
      "content": "'use client';\n\nimport * as React from 'react';\n\n// @interlace/closer-game v1.1.1 — Interlace design system.\n// Docs, props and live preview: https://ds.interlace.tools/c/closer-game\n// What changed since: https://ds.interlace.tools/c/closer-game#history\n// Generated banner — keep it, the upgrade diff reads this version.\n\n/**\n * @interlace/ui — CloserGame\n *\n * Guess a number by sliding to it. The player sets a value on a slider (or\n * types it), locks it in, and the answer slides out from their guess to\n * where it really is, with the gap between them shaded and said in words:\n * \"900 off. Close.\" Scoring lives in `closer-model.ts` and is exported, so a\n * server can score the same guess and a share card can draw the band\n * without the number.\n *\n * ## Anatomy\n *\n *   CloserGame                       (div — data-slot=\"closer-game\", data-state=guessing|revealed, data-band)\n *     ├─ p                           (data-slot=\"closer-game-question\", id ← slider + input label)\n *     ├─ output                      (data-slot=\"closer-game-value\": the guess, formatted)\n *     ├─ div                         (data-slot=\"closer-game-scale\")\n *     │   ├─ Slider                  (Base UI: arrows, PageUp/PageDown, Home/End, drag)\n *     │   ├─ span                    (data-slot=\"closer-game-gap\": guess to answer, after the reveal)\n *     │   └─ span                    (data-slot=\"closer-game-answer\": the answer's mark, after the reveal)\n *     ├─ div                         (data-slot=\"closer-game-ends\": min and max)\n *     ├─ form                        (data-slot=\"closer-game-form\": typed value + Lock in)\n *     ├─ p aria-live=\"polite\"        (data-slot=\"closer-game-result\")\n *     └─ div                         (data-slot=\"closer-game-explanation\": opens on reveal)\n *\n * ## Controlled or not\n *\n * `guess` / `defaultGuess` hold the locked-in value (null for none yet), so\n * a page that stored today's guess restores the revealed state on reload.\n * `onGuess` fires once, with the scored result.\n *\n * ## Motion\n *\n * The answer's mark travels from the guess to the answer (400ms,\n * `--ease-move`) and the gap fills behind it. Under reduced motion both are\n * simply in place. Nothing moves before the reveal.\n *\n * ## Log scales\n *\n * `range.scale = 'log'` lays the slider out in orders of magnitude, so\n * 1,000 and 1,000,000 are both easy to reach. The slider then moves in\n * 1/1000ths of the track and the typed field takes any value.\n *\n * ## MIN_VIEWPORT — 320\n *\n * | Rule | Concept                   | Where in this file                                    |\n * | ---- | ------------------------- | ----------------------------------------------------- |\n * | R4   | Extends native el         | `React.ComponentProps<'div'>`                         |\n * | R6   | data-slot per part        | closer-game / -question / -value / -scale / -gap / -answer / -ends / -form / -result / -explanation |\n * | R7   | cn + ...rest              | `cn(…, className)` + `{...props}`                     |\n * | R9   | Controlled + uncontrolled | `guess` / `defaultGuess` / `onGuess`                  |\n * | R14  | Declares min viewport     | `data-min-viewport` + exported const                  |\n * | R19  | Tokens only               | primary, success, input, muted                        |\n * | R26  | A11y                      | labelled slider with value text; live result; band in words, not colour |\n */\n\nimport { cn } from '@/lib/utils';\nimport { useReducedMotion } from '@/hooks/use-reduced-motion';\nimport { motionDuration, motionEase } from '@/lib/motion-token';\nimport { Button } from '@/components/ui/button';\nimport { Input } from '@/components/ui/input';\nimport { Slider, SliderControl, SliderIndicator, SliderThumb, SliderTrack } from '@/components/ui/slider';\nimport {\n  fromPosition,\n  scoreGuess,\n  snap,\n  toPosition,\n  type CloserBand,\n  type CloserRange,\n  type CloserResult,\n  type CloserScoreOptions,\n} from '@/components/ui/games/closer-model';\n\nexport const MIN_VIEWPORT = 320 as const;\n\nconst LOG_STEPS = 1000;\n\ninterface CloserGameLabels {\n  /** Names the slider and the typed field. @default 'Your guess' */\n  guess?: string;\n  /** The lock-in button. @default 'Lock in' */\n  submit?: string;\n  /** The typed field's visible label. @default 'Or type it' */\n  type?: string;\n  /** Band words. */\n  band?: Partial<Record<CloserBand, string>>;\n  /** The result sentence. Receives formatted numbers. */\n  result?: (r: { guess: string; answer: string; distance: string; band: string; points: number }) => string;\n  /** The answer mark's visible caption. @default 'Answer' */\n  answer?: string;\n}\n\ntype CloserGameProps = Omit<React.ComponentProps<'div'>, 'children' | 'onChange'> & {\n  question: React.ReactNode;\n  /** The answer. Keep it off the client until the reveal if the game is competitive. */\n  answer: number;\n  range: CloserRange;\n  /** Locked-in guess, controlled. null for none yet. */\n  guess?: number | null;\n  /** Locked-in guess, uncontrolled. */\n  defaultGuess?: number | null;\n  /** Where the slider starts. @default the middle of the range */\n  defaultValue?: number;\n  /** Called once when the player locks in. */\n  onGuess?: (result: CloserResult) => void;\n  /** Shown after the reveal: what the number is and where it comes from. */\n  explanation?: React.ReactNode;\n  /** `Intl.NumberFormat` options for every number shown (a unit, a currency, compact notation). */\n  format?: Intl.NumberFormatOptions;\n  /** BCP 47 locale for numbers. */\n  locale?: string;\n  score?: CloserScoreOptions;\n  labels?: CloserGameLabels;\n};\n\nconst BAND: Record<CloserBand, string> = {\n  exact: 'Spot on.',\n  close: 'Close.',\n  near: 'Not far.',\n  far: 'Far off.',\n};\n\nconst RESULT: NonNullable<CloserGameLabels['result']> = ({ guess, answer, distance, band, points }) =>\n  guess === answer\n    ? `You said ${guess}. The answer is ${answer}. ${band} ${points} points.`\n    : `You said ${guess}. The answer is ${answer}, ${distance} off. ${band} ${points} points.`;\n\nfunction CloserGame({\n  question,\n  answer,\n  range,\n  guess: guessProp,\n  defaultGuess = null,\n  defaultValue,\n  onGuess,\n  explanation,\n  format,\n  locale,\n  score,\n  labels,\n  className,\n  ...props\n}: CloserGameProps) {\n  const isLog = range.scale === 'log';\n  const middle = fromPosition(0.5, range);\n  const [draft, setDraft] = React.useState(() => snap(defaultValue ?? middle, range));\n  const [typed, setTyped] = React.useState<string | null>(null);\n  const [uncontrolled, setUncontrolled] = React.useState<number | null>(defaultGuess);\n  const locked = guessProp === undefined ? uncontrolled : guessProp;\n  const revealed = locked !== null && locked !== undefined;\n  const reduced = useReducedMotion();\n  const questionId = React.useId();\n  const inputId = React.useId();\n  const explanationId = React.useId();\n  const answerRef = React.useRef<HTMLSpanElement>(null);\n  const gapRef = React.useRef<HTMLSpanElement>(null);\n  const animate = React.useRef(false);\n  const sentRef = React.useRef(revealed);\n  const resultRef = React.useRef<HTMLParagraphElement>(null);\n  const formRef = React.useRef<HTMLFormElement>(null);\n  const moveFocus = React.useRef(false);\n\n  const nf = React.useMemo(() => new Intl.NumberFormat(locale, format), [locale, format]);\n  const result = revealed ? scoreGuess(locked, answer, range, score) : null;\n  const shown = revealed ? locked : draft;\n  const words = { ...BAND, ...labels?.band };\n\n  React.useEffect(() => {\n    if (!revealed) sentRef.current = false;\n  }, [revealed]);\n\n  const lockIn = (value: number) => {\n    if (revealed || sentRef.current) return;\n    sentRef.current = true;\n    animate.current = true;\n    // The form goes away on reveal: if focus was in it, the result takes it.\n    moveFocus.current = !!formRef.current?.contains(document.activeElement);\n    const v = snap(value, range);\n    if (guessProp === undefined) setUncontrolled(v);\n    onGuess?.(scoreGuess(v, answer, range, score));\n  };\n\n  const guessPos = toPosition(shown, range) * 100;\n  const answerPos = toPosition(answer, range) * 100;\n\n  // The answer travels from the guess to where it is; the gap fills behind it.\n  React.useEffect(() => {\n    if (!revealed || !moveFocus.current) return;\n    moveFocus.current = false;\n    resultRef.current?.focus();\n  }, [revealed]);\n\n  React.useEffect(() => {\n    if (!revealed || !animate.current) return;\n    animate.current = false;\n    const mark = answerRef.current;\n    const gap = gapRef.current;\n    if (reduced || !mark || typeof mark.animate !== 'function') return;\n    const rtl = getComputedStyle(mark).direction === 'rtl';\n    const track = mark.parentElement?.getBoundingClientRect().width ?? 0;\n    const dx = ((guessPos - answerPos) / 100) * track * (rtl ? -1 : 1);\n    const timing = { duration: motionDuration(mark, 'slow'), easing: motionEase(mark, 'move') };\n    mark.animate([{ transform: `translateX(${dx}px)` }, { transform: 'translateX(0)' }], timing);\n    gap?.animate([{ transform: 'scaleX(0)' }, { transform: 'scaleX(1)' }], timing);\n  }, [revealed, reduced, guessPos, answerPos]);\n\n  const setFromSlider = (v: number) => {\n    setTyped(null);\n    setDraft(isLog ? fromPosition(v / LOG_STEPS, range) : snap(v, range));\n  };\n\n  const commitTyped = () => {\n    if (typed === null) return draft;\n    const n = Number(typed);\n    const v = Number.isFinite(n) && typed.trim() !== '' ? snap(n, range) : draft;\n    setDraft(v);\n    setTyped(null);\n    return v;\n  };\n\n  const gapStart = Math.min(guessPos, answerPos);\n  const gapWidth = Math.abs(guessPos - answerPos);\n\n  return (\n    <div\n      data-slot=\"closer-game\"\n      data-state={revealed ? 'revealed' : 'guessing'}\n      data-band={result?.band}\n      data-min-viewport={String(MIN_VIEWPORT)}\n      className={cn('grid gap-4', className)}\n      {...props}\n    >\n      <p id={questionId} data-slot=\"closer-game-question\" className=\"font-heading text-lg font-semibold text-balance\">\n        {question}\n      </p>\n\n      <output\n        data-slot=\"closer-game-value\"\n        htmlFor={inputId}\n        aria-hidden\n        className=\"font-heading text-h2 leading-none font-semibold tabular-nums\"\n      >\n        {nf.format(shown)}\n      </output>\n\n      <div data-slot=\"closer-game-scale\" className=\"relative py-3\">\n        <Slider\n          value={isLog ? Math.round(toPosition(shown, range) * LOG_STEPS) : shown}\n          min={isLog ? 0 : range.min}\n          max={isLog ? LOG_STEPS : range.max}\n          step={isLog ? 1 : (range.step ?? 1)}\n          disabled={revealed}\n          onValueChange={(v) => setFromSlider(Array.isArray(v) ? (v[0] as number) : (v as number))}\n          aria-labelledby={questionId}\n        >\n          <SliderControl>\n            <SliderTrack>\n              <SliderIndicator />\n            </SliderTrack>\n            <SliderThumb\n              getAriaLabel={() => labels?.guess ?? 'Your guess'}\n              getAriaValueText={() => nf.format(revealed ? locked : draft)}\n              className={cn(revealed && 'disabled:opacity-100')}\n            />\n          </SliderControl>\n        </Slider>\n        {result ? (\n          <>\n            <span\n              ref={gapRef}\n              aria-hidden\n              data-slot=\"closer-game-gap\"\n              className={cn(\n                'pointer-events-none absolute top-1/2 h-2 -translate-y-1/2 rounded-full',\n                'bg-[repeating-linear-gradient(135deg,var(--foreground)_0_2px,transparent_2px_6px)] opacity-60',\n                answerPos >= guessPos ? 'origin-left rtl:origin-right' : 'origin-right rtl:origin-left',\n              )}\n              // Stops short of the guess's thumb (10px each side) so the hatching never\n              // runs under it.\n              style={{\n                insetInlineStart: `calc(${gapStart}% + ${answerPos < guessPos ? 0 : 10}px)`,\n                width: `max(0px, calc(${gapWidth}% - 10px))`,\n              }}\n            />\n            <span\n              ref={answerRef}\n              data-slot=\"closer-game-answer\"\n              className=\"pointer-events-none absolute top-1/2 grid -translate-y-1/2 justify-items-center rtl:translate-x-1/2 ltr:-translate-x-1/2\"\n              style={{ insetInlineStart: `${answerPos}%` }}\n            >\n              <span aria-hidden className=\"bg-success border-background block size-5 rotate-45 rounded-[3px] border-2\" />\n              <span className=\"text-success absolute top-full mt-1 text-xs font-semibold whitespace-nowrap\">\n                {labels?.answer ?? 'Answer'}\n              </span>\n            </span>\n          </>\n        ) : null}\n      </div>\n\n      <div\n        data-slot=\"closer-game-ends\"\n        aria-hidden\n        className=\"text-muted-foreground -mt-2 flex justify-between text-xs tabular-nums\"\n      >\n        <span>{nf.format(range.min)}</span>\n        <span>{nf.format(range.max)}</span>\n      </div>\n\n      {!revealed ? (\n        <form\n          ref={formRef}\n          data-slot=\"closer-game-form\"\n          className=\"flex flex-wrap items-end gap-3\"\n          onSubmit={(e) => {\n            e.preventDefault();\n            lockIn(commitTyped());\n          }}\n        >\n          <div className=\"grid min-w-0 flex-1 basis-36 gap-1.5\">\n            <label htmlFor={inputId} className=\"text-muted-foreground text-sm\">\n              {labels?.type ?? 'Or type it'}\n            </label>\n            <Input\n              id={inputId}\n              type=\"number\"\n              inputMode=\"decimal\"\n              min={range.min}\n              max={range.max}\n              step={range.step ?? 'any'}\n              value={typed ?? String(draft)}\n              onChange={(e) => setTyped(e.target.value)}\n              onBlur={commitTyped}\n            />\n          </div>\n          <Button type=\"submit\" className=\"flex-none\">\n            {labels?.submit ?? 'Lock in'}\n          </Button>\n        </form>\n      ) : null}\n\n      <p\n        ref={resultRef}\n        tabIndex={-1}\n        data-slot=\"closer-game-result\"\n        aria-live=\"polite\"\n        aria-describedby={result && explanation ? explanationId : undefined}\n        className=\"focus-visible:outline-ring rounded-sm text-sm font-semibold outline-offset-4 empty:hidden focus-visible:outline-2\"\n      >\n        {result\n          ? (labels?.result ?? RESULT)({\n              guess: nf.format(result.guess),\n              answer: nf.format(result.answer),\n              distance: nf.format(result.distance),\n              band: words[result.band],\n              points: result.points,\n            })\n          : ''}\n      </p>\n\n      {explanation ? (\n        <div\n          data-slot=\"closer-game-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 id={explanationId} className=\"text-muted-foreground -m-1 min-h-0 overflow-hidden p-1 text-sm leading-relaxed\">\n            {explanation}\n          </div>\n        </div>\n      ) : null}\n    </div>\n  );\n}\nCloserGame.displayName = 'CloserGame';\n\nexport { CloserGame };\nexport type { CloserGameProps, CloserGameLabels };\n"
    },
    {
      "path": "registry/interlace-ui/games/closer-model.ts",
      "target": "components/ui/games/closer-model.ts",
      "type": "registry:ui",
      "content": "export interface CloserRange {\n  min: number;\n  max: number;\n  /** Slider step. @default 1 */\n  step?: number;\n  /** `log` for answers that span orders of magnitude; needs `min > 0`. @default 'linear' */\n  scale?: 'linear' | 'log';\n}\n\nexport type CloserBand = 'exact' | 'close' | 'near' | 'far';\n\nexport interface CloserScoreOptions {\n  /** Points for a perfect guess. @default 100 */\n  maxPoints?: number;\n  /**\n   * Absolute distance that still counts as exact. @default half of `step`\n   *\n   * On a log range, set this or `step`: a slider moving by share of the\n   * range rarely lands within half a unit of the answer.\n   */\n  tolerance?: number;\n  /** Band edges, as shares of the range (0–1). @default { close: 0.05, near: 0.15 } */\n  bands?: { close?: number; near?: number };\n  /** Share of the range at which points reach 0. @default 0.5 */\n  zeroAt?: number;\n}\n\nexport interface CloserResult {\n  guess: number;\n  answer: number;\n  /** |guess − answer|, in the answer's units. */\n  distance: number;\n  /** Distance as a share of the range on its scale, 0–1. */\n  error: number;\n  band: CloserBand;\n  /** Whole points, 0 to `maxPoints`. */\n  points: number;\n  /** Where the answer sits from the guess: `higher`, `lower` or `exact`. */\n  direction: 'higher' | 'lower' | 'exact';\n}\n\nconst clamp = (n: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, n));\n\nfunction assertRange(range: CloserRange) {\n  if (!(range.max > range.min)) throw new RangeError('A range needs max > min');\n  if (range.scale === 'log' && range.min <= 0) throw new RangeError('A log range needs min > 0');\n}\n\n/** Where `value` sits on the range, 0 at `min` to 1 at `max`, clamped. */\nexport function toPosition(value: number, range: CloserRange): number {\n  assertRange(range);\n  if (range.scale === 'log') {\n    const v = Math.max(value, range.min);\n    return clamp(Math.log(v / range.min) / Math.log(range.max / range.min), 0, 1);\n  }\n  return clamp((value - range.min) / (range.max - range.min), 0, 1);\n}\n\n/** The value at a position (0–1), snapped to `step` and clamped to the range. */\nexport function fromPosition(position: number, range: CloserRange): number {\n  assertRange(range);\n  const p = clamp(position, 0, 1);\n  const raw =\n    range.scale === 'log'\n      ? range.min * Math.pow(range.max / range.min, p)\n      : range.min + p * (range.max - range.min);\n  return snap(raw, range);\n}\n\n/** `value` snapped to the range's step, from `min`, and clamped to the range. */\nexport function snap(value: number, range: CloserRange): number {\n  const step = range.step ?? 1;\n  const snapped = step > 0 ? range.min + Math.round((value - range.min) / step) * step : value;\n  // Clean the float tail a step like 0.1 leaves behind.\n  const decimals = Math.max(0, -Math.floor(Math.log10(step > 0 ? step : 1)));\n  return clamp(Number(snapped.toFixed(Math.min(decimals + 2, 12))), range.min, range.max);\n}\n\n/** Score a guess against the answer on the given range. */\nexport function scoreGuess(\n  guess: number,\n  answer: number,\n  range: CloserRange,\n  options: CloserScoreOptions = {},\n): CloserResult {\n  const { maxPoints = 100, zeroAt = 0.5 } = options;\n  // Without this guard, toPosition would clamp the answer and score a guess at the end of the track as close.\n  if (!(answer >= range.min && answer <= range.max)) throw new RangeError('answer must be within the range');\n  if (!Number.isFinite(guess)) throw new RangeError('guess must be a finite number');\n  const tolerance = options.tolerance ?? (range.step ?? 1) / 2;\n  const close = options.bands?.close ?? 0.05;\n  const near = options.bands?.near ?? 0.15;\n  const distance = Math.abs(guess - answer);\n  const exact = distance <= tolerance;\n  const error = exact ? 0 : Math.abs(toPosition(guess, range) - toPosition(answer, range));\n  const band: CloserBand = exact ? 'exact' : error <= close ? 'close' : error <= near ? 'near' : 'far';\n  const points = exact ? maxPoints : Math.round(maxPoints * clamp(1 - error / zeroAt, 0, 1));\n  const direction = exact ? 'exact' : answer > guess ? 'higher' : 'lower';\n  return { guess, answer, distance, error, band, points, direction };\n}\n\n/**\n * @interlace/ui — games/closer-model\n *\n * Scoring for a number guess: the player slides to a value, the game shows\n * how far off it was. Pure, so a server can score the same guess and a share\n * card can show the band without the number.\n *\n * ## Distance on the player's scale\n *\n * \"How far off\" is measured as a share of the range the player was given,\n * because 900 off is close on a slider from 0 to 100,000 and far on one from\n * 0 to 1,000. With `scale: 'log'` (for answers that span orders of\n * magnitude, such as populations) the share is taken on the log scale, so\n * 900 instead of 1,000 and 900,000 instead of 1,000,000 score the same.\n *\n * ## Bands\n *\n * Every result lands in a band, so a game can say \"Close.\" in words and a\n * share card can draw a mark per round without saying the number:\n *\n * | Band      | Default: off by at most        |\n * | --------- | ------------------------------ |\n * | `exact`   | `tolerance` (default: half a step, or 0) |\n * | `close`   | 5% of the range                |\n * | `near`    | 15% of the range               |\n * | `far`     | anything more                  |\n */\n"
    }
  ],
  "meta": {
    "tier": "game",
    "client": true,
    "minViewport": 320,
    "loading": false,
    "version": "1.1.1",
    "since": "2.0.0"
  },
  "docs": "## @interlace/closer-game\n\nInstalled to `components/ui/games/closer-game.tsx`.\n\n```tsx\nimport { /* … */ } from '@/components/ui/games/closer-game';\n```\n\nProps, a11y contract, live preview and source: https://ds.interlace.tools/c/closer-game\n\nRequires the `@interlace/interlace-base` CSS baseline (installed automatically as a registry dependency). For the Interlace look, also add `@interlace/theme`."
}
