{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "spectrum",
  "type": "registry:ui",
  "title": "Spectrum",
  "description": "Where do you stand? A statement, two poles, and a line between them. Each person places one dot, then sees the whole room spread along the same line, their own bin marked, the room's middle drawn, and, when the statement was asked before, where the middle…",
  "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/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/spectrum.tsx",
      "target": "components/ui/games/spectrum.tsx",
      "type": "registry:ui",
      "content": "'use client';\n\nimport * as React from 'react';\n\n// @interlace/spectrum v1.0.0 — Interlace design system.\n// Docs, props and live preview: https://ds.interlace.tools/c/spectrum\n// What changed since: https://ds.interlace.tools/c/spectrum#history\n// Generated banner — keep it, the upgrade diff reads this version.\n\n/**\n * @interlace/ui — Spectrum\n *\n * Where do you stand? A statement, two poles, and a line between them.\n * Each person places one dot, then sees the whole room spread along the\n * same line, their own bin marked, the room's middle drawn, and, when the\n * statement was asked before, where the middle was then. It shows a room as\n * it is: rarely two camps, usually a spread.\n *\n * ## Anatomy\n *\n *   Spectrum                          (div — data-slot=\"spectrum\", data-state=placing|placed)\n *     ├─ p                            (data-slot=\"spectrum-statement\")\n *     ├─ Slider (placing)             (Base UI: arrows, Page keys, Home/End, drag; value in words)\n *     ├─ div aria-hidden (placed)     (data-slot=\"spectrum-chart\": bins as bars, the middle, before)\n *     ├─ div                          (data-slot=\"spectrum-poles\": the two pole labels under the line)\n *     ├─ Button (placing)             (data-slot=\"spectrum-place\")\n *     └─ p tabIndex=-1 aria-live     (data-slot=\"spectrum-result\": the picture in one sentence)\n *\n * ## Data\n *\n * Values run 0 (the first pole) to 100 (the second). `values` are the\n * room's dots from your store, without this viewer's own unless\n * `valuesIncludeOwn`. `before` draws an earlier round of the same\n * statement as a dashed marker. `minResponses` keeps the picture hidden\n * until enough people have placed a dot, so nobody's answer is guessable.\n *\n * ## Motion\n *\n * On placing, the bars grow up from the line together (400ms, transform)\n * and the middle marker slides from the viewer's dot to the room's (400ms,\n * `--ease-move`): the viewer sees where they are, then where the room is.\n * Under reduced motion the picture is simply there.\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        | spectrum / -statement / -chart / -poles / -place / -result |\n * | R7   | cn + ...rest              | `cn(…, className)` + `{...props}`                   |\n * | R9   | Controlled + uncontrolled | `value` / `defaultValue` / `onPlace`                |\n * | R14  | Declares min viewport     | `data-min-viewport` + exported const                |\n * | R26  | A11y                      | slider with words for its value; chart hidden, result sentence focused |\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 { Slider, SliderControl, SliderIndicator, SliderThumb, SliderTrack } from '@/components/ui/slider';\nimport { binOf, summarizeSpectrum } from '@/components/ui/games/spectrum-model';\n\nexport const MIN_VIEWPORT = 320 as const;\n\ninterface SpectrumLabels {\n  /** @default 'Place my dot' */\n  place?: string;\n  /** The slider's value in words. @default by position: 'Closer to {start}', 'In the middle', 'Closer to {end}' */\n  position?: (value: number, start: string, end: string) => string;\n  /**\n   * After placing. `mine` and `middle` are `position` words; `shift` is the\n   * signed move of the middle since `before`, on the 0 to 100 line.\n   * @default ({ mine, middle, count }) => `${count} people placed a dot. Yours: ${mine}. The room's middle: ${middle}.`\n   */\n  result?: (r: { mine: string; middle: string; count: string; shift: string | null }) => string;\n  /** While fewer than `minResponses` are in. @default (min) => `Thanks. The room shows once ${min} people have placed a dot.` */\n  pending?: (min: number) => string;\n  /** The marker for the room's middle. @default 'Room' */\n  middle?: string;\n  /** The marker for the earlier round. @default 'Before' */\n  before?: string;\n}\n\ntype SpectrumProps = Omit<React.ComponentProps<'div'>, 'children' | 'defaultValue'> & {\n  statement: React.ReactNode;\n  /** The two ends of the line, as plain words. */\n  poles: readonly [string, string];\n  /** The room's dots, 0 to 100. */\n  values?: readonly number[];\n  /** `values` already hold this viewer's dot. @default false */\n  valuesIncludeOwn?: boolean;\n  /** An earlier round of the same statement, drawn as a dashed marker. */\n  before?: readonly number[];\n  /** The viewer's placed dot, controlled. null while placing. */\n  value?: number | null;\n  /** The viewer's placed dot, uncontrolled. */\n  defaultValue?: number | null;\n  /** Called once, when the viewer places their dot. */\n  onPlace?: (value: number) => void;\n  /** Hide the room until this many dots are in. @default 1 */\n  minResponses?: number;\n  /** Bars along the line. @default 10 */\n  bins?: number;\n  locale?: string;\n  labels?: SpectrumLabels;\n};\n\nconst POSITION: NonNullable<SpectrumLabels['position']> = (v, start, end) =>\n  v < 40 ? `Closer to ${start}` : v > 60 ? `Closer to ${end}` : 'In the middle';\nconst RESULT: NonNullable<SpectrumLabels['result']> = ({ mine, middle, count, shift }) =>\n  `${count} ${count === '1' ? 'person' : 'people'} placed a dot. Yours: ${mine}. The room's middle: ${middle}.${shift ? ` It moved ${shift} points since before.` : ''}`;\nconst PENDING: NonNullable<SpectrumLabels['pending']> = (min) =>\n  `Thanks. The room shows once ${min} people have placed a dot.`;\n\nfunction Spectrum({\n  statement,\n  poles,\n  values = [],\n  valuesIncludeOwn = false,\n  before,\n  value: valueProp,\n  defaultValue = null,\n  onPlace,\n  minResponses = 1,\n  bins = 10,\n  locale,\n  labels,\n  className,\n  ...props\n}: SpectrumProps) {\n  const reduced = useReducedMotion();\n  const [own, setOwn] = React.useState<number | null>(defaultValue);\n  const placed = valueProp === undefined ? own : valueProp;\n  const [draft, setDraft] = React.useState(50);\n  const [placedHere, setPlacedHere] = React.useState(false);\n  const statementId = React.useId();\n  const resultRef = React.useRef<HTMLParagraphElement>(null);\n  const chartRef = React.useRef<HTMLDivElement>(null);\n  const nf = React.useMemo(() => new Intl.NumberFormat(locale, { maximumFractionDigits: 0 }), [locale]);\n  const signed = React.useMemo(\n    () => new Intl.NumberFormat(locale, { maximumFractionDigits: 0, signDisplay: 'exceptZero' }),\n    [locale],\n  );\n\n  const all = placed === null || valuesIncludeOwn ? values : [...values, placed];\n  const room = summarizeSpectrum(all, { bins });\n  const earlier = before && before.length > 0 ? summarizeSpectrum(before, { bins }) : null;\n  const shown = placed !== null && room.count >= minResponses;\n  const mineBin = placed === null ? -1 : binOf(placed, { bins });\n\n  React.useEffect(() => {\n    if (!shown || !placedHere) return;\n    resultRef.current?.focus();\n    if (reduced) return;\n    const chart = chartRef.current;\n    chart?.querySelectorAll<HTMLElement>('[data-slot=\"spectrum-bar\"]').forEach((bar) => {\n      if (typeof bar.animate !== 'function') return;\n      bar.animate([{ transform: 'scaleY(0)' }, { transform: 'scaleY(1)' }], {\n        duration: 400,\n        easing: motionEase(bar, 'enter'),\n      });\n    });\n    const marker = chart?.querySelector<HTMLElement>('[data-slot=\"spectrum-middle\"]');\n    if (marker && typeof marker.animate === 'function' && placed !== null && room.median !== null) {\n      const width = chart?.getBoundingClientRect().width ?? 0;\n      const from = ((placed - room.median) / 100) * width;\n      marker.animate([{ transform: `translateX(${from}px)` }, { transform: 'translateX(0)' }], {\n        duration: 400,\n        easing: motionEase(marker, 'move'),\n      });\n    }\n    // Once, when this viewer's dot lands.\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [shown, placedHere]);\n\n  const place = () => {\n    if (placed !== null) return;\n    setPlacedHere(true);\n    if (valueProp === undefined) setOwn(draft);\n    onPlace?.(draft);\n  };\n\n  const shift =\n    earlier && earlier.median !== null && room.median !== null ? signed.format(room.median - earlier.median) : null;\n\n  return (\n    <div\n      data-slot=\"spectrum\"\n      data-state={placed === null ? 'placing' : 'placed'}\n      data-min-viewport={String(MIN_VIEWPORT)}\n      className={cn('grid gap-4', className)}\n      {...props}\n    >\n      <p id={statementId} data-slot=\"spectrum-statement\" className=\"font-heading text-lg font-semibold text-balance\">\n        {statement}\n      </p>\n\n      {placed === null ? (\n        <div className=\"py-3\">\n          <Slider\n            value={draft}\n            min={0}\n            max={100}\n            step={1}\n            onValueChange={(v) => setDraft(Array.isArray(v) ? (v[0] as number) : (v as number))}\n            aria-labelledby={statementId}\n          >\n            <SliderControl>\n              <SliderTrack>\n                <SliderIndicator className=\"bg-transparent\" />\n              </SliderTrack>\n              <SliderThumb\n                getAriaLabel={() => `${poles[0]} to ${poles[1]}`}\n                getAriaValueText={() => (labels?.position ?? POSITION)(draft, poles[0], poles[1])}\n              />\n            </SliderControl>\n          </Slider>\n        </div>\n      ) : shown ? (\n        <div ref={chartRef} aria-hidden data-slot=\"spectrum-chart\" className=\"relative h-28 pt-5\">\n          <div className=\"flex h-full items-end gap-1 border-b\">\n            {room.bins.map((n, i) => (\n              <span\n                // Bins are fixed positions on the line: the index is their identity.\n                key={`bin-${i}`}\n                data-slot=\"spectrum-bar\"\n                data-mine={i === mineBin ? '' : undefined}\n                className={cn(\n                  'block flex-1 origin-bottom rounded-t-sm',\n                  i === mineBin ? 'bg-primary' : 'bg-foreground/25',\n                )}\n                style={{ height: room.peak > 0 ? `${(n / room.peak) * 100}%` : '0%' }}\n              />\n            ))}\n          </div>\n          {earlier?.median != null ? (\n            <span\n              data-slot=\"spectrum-before\"\n              className=\"text-muted-foreground absolute top-0 bottom-0 flex -translate-x-1/2 flex-col items-center rtl:translate-x-1/2\"\n              style={{ insetInlineStart: `${earlier.median}%` }}\n            >\n              <span className=\"text-xs leading-none whitespace-nowrap\">{labels?.before ?? 'Before'}</span>\n              <span className=\"mt-1 w-0 flex-1 border-s border-dashed border-current\" />\n            </span>\n          ) : null}\n          {room.median !== null ? (\n            <span\n              data-slot=\"spectrum-middle\"\n              className=\"text-foreground absolute top-0 bottom-0 flex -translate-x-1/2 flex-col items-center rtl:translate-x-1/2\"\n              style={{ insetInlineStart: `${room.median}%` }}\n            >\n              <span className=\"text-xs leading-none font-semibold whitespace-nowrap\">{labels?.middle ?? 'Room'}</span>\n              <span className=\"mt-1 w-0.5 flex-1 rounded-full bg-current\" />\n            </span>\n          ) : null}\n        </div>\n      ) : null}\n\n      <div data-slot=\"spectrum-poles\" className=\"text-muted-foreground flex justify-between gap-4 text-sm\">\n        <span className=\"max-w-[45%]\">{poles[0]}</span>\n        <span className=\"max-w-[45%] text-end\">{poles[1]}</span>\n      </div>\n\n      {placed === null ? (\n        <Button data-slot=\"spectrum-place\" size=\"lg\" className=\"justify-self-start\" onClick={place}>\n          {labels?.place ?? 'Place my dot'}\n        </Button>\n      ) : null}\n\n      <p\n        ref={resultRef}\n        tabIndex={-1}\n        data-slot=\"spectrum-result\"\n        aria-live=\"polite\"\n        className=\"focus-visible:outline-ring rounded-sm text-sm outline-offset-4 empty:hidden focus-visible:outline-2\"\n      >\n        {placed === null\n          ? ''\n          : shown && room.median !== null\n            ? (labels?.result ?? RESULT)({\n                mine: (labels?.position ?? POSITION)(placed, poles[0], poles[1]),\n                middle: (labels?.position ?? POSITION)(room.median, poles[0], poles[1]),\n                count: nf.format(room.count),\n                shift,\n              })\n            : (labels?.pending ?? PENDING)(minResponses)}\n      </p>\n    </div>\n  );\n}\nSpectrum.displayName = 'Spectrum';\n\nexport { Spectrum };\nexport type { SpectrumProps, SpectrumLabels };\n"
    },
    {
      "path": "registry/interlace-ui/games/spectrum-model.ts",
      "target": "components/ui/games/spectrum-model.ts",
      "type": "registry:ui",
      "content": "export interface SpectrumSummary {\n  count: number;\n  /** Dots per bin, left to right. */\n  bins: number[];\n  /** The most dots in any one bin. */\n  peak: number;\n  mean: number | null;\n  median: number | null;\n  /** The middle half of the room, from the lower to the upper quartile. */\n  middle: [number, number] | null;\n}\n\nexport interface SpectrumOptions {\n  /** @default 10 */\n  bins?: number;\n  /** @default 0 */\n  min?: number;\n  /** @default 100 */\n  max?: number;\n}\n\n/** The most bins one summary draws; a forged count cannot make the room allocate more. */\nconst MAX_BINS = 1000;\n\n/** The line and its bins, with every forged or non-finite option replaced by its default. */\nfunction lineOf(options: SpectrumOptions) {\n  const { bins, min, max } = options;\n  const n = Number.isFinite(bins) ? Math.floor(bins as number) : 10;\n  return {\n    count: Math.min(MAX_BINS, Math.max(1, n)),\n    min: Number.isFinite(min) ? (min as number) : 0,\n    max: Number.isFinite(max) ? (max as number) : 100,\n  };\n}\n\nfunction quantile(sorted: readonly number[], q: number): number {\n  const pos = (sorted.length - 1) * q;\n  const lo = Math.floor(pos);\n  const hi = Math.ceil(pos);\n  const a = sorted[lo] as number;\n  const b = sorted[hi] as number;\n  return a + (b - a) * (pos - lo);\n}\n\n/** Clamps to the line; non-numbers are dropped. */\nexport function cleanValues(values: readonly number[], options: SpectrumOptions = {}): number[] {\n  const { min, max } = lineOf(options);\n  if (!Array.isArray(values)) return [];\n  return values.filter((v) => Number.isFinite(v)).map((v) => Math.min(max, Math.max(min, v)));\n}\n\nexport function summarizeSpectrum(values: readonly number[], options: SpectrumOptions = {}): SpectrumSummary {\n  const { count, min, max } = lineOf(options);\n  const clean = cleanValues(values, options);\n  const bins = Array.from({ length: count }, () => 0);\n  const span = max - min || 1;\n  for (const v of clean) {\n    const i = Math.min(count - 1, Math.floor(((v - min) / span) * count));\n    bins[i] = (bins[i] as number) + 1;\n  }\n  if (clean.length === 0) return { count: 0, bins, peak: 0, mean: null, median: null, middle: null };\n  const sorted = [...clean].sort((a, b) => a - b);\n  return {\n    count: clean.length,\n    bins,\n    peak: Math.max(...bins),\n    mean: clean.reduce((a, b) => a + b, 0) / clean.length,\n    median: quantile(sorted, 0.5),\n    middle: [quantile(sorted, 0.25), quantile(sorted, 0.75)],\n  };\n}\n\n/** How far the median moved from `before` to `after`, or null when either is empty. */\nexport function spectrumShift(\n  before: readonly number[],\n  after: readonly number[],\n  options: SpectrumOptions = {},\n): number | null {\n  const a = summarizeSpectrum(before, options).median;\n  const b = summarizeSpectrum(after, options).median;\n  return a === null || b === null ? null : b - a;\n}\n\n/** The bin a value falls in, or -1 for a value that is not a number. */\nexport function binOf(value: number, options: SpectrumOptions = {}): number {\n  const { count, min, max } = lineOf(options);\n  if (typeof value !== 'number' || Number.isNaN(value)) return -1;\n  const v = Math.min(max, Math.max(min, value));\n  return Math.min(count - 1, Math.floor(((v - min) / (max - min || 1)) * count));\n}\n\n/**\n * @interlace/ui — spectrum-model\n *\n * Where a room stands between two poles. Everyone places a dot on a line\n * from 0 to 100; the room sees the spread, not just a winner, which is the\n * point: most rooms are not split in two. Pure, so a server and a recap\n * page draw the same picture, and a before-and-after pair can be compared.\n *\n * `summarizeSpectrum` bins the dots (10 bins by default), finds the median\n * and the middle half (the quartiles), and the mean. `spectrumShift` says how\n * far the room's median moved between two rounds of the same statement.\n */\n"
    }
  ],
  "meta": {
    "tier": "game",
    "client": true,
    "minViewport": 320,
    "loading": false,
    "version": "1.0.0",
    "since": "2.0.0"
  },
  "docs": "## @interlace/spectrum\n\nInstalled to `components/ui/games/spectrum.tsx`.\n\n```tsx\nimport { /* … */ } from '@/components/ui/games/spectrum';\n```\n\nProps, a11y contract, live preview and source: https://ds.interlace.tools/c/spectrum\n\nRequires the `@interlace/interlace-base` CSS baseline (installed automatically as a registry dependency). For the Interlace look, also add `@interlace/theme`."
}
