{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "rating",
  "type": "registry:ui",
  "title": "Rating",
  "description": "A scale question for a room: how familiar, how likely to recommend, how are you feeling. Each person picks one step and sends it; then they see the room's answers on the same scale, their own step marked, the room's average, and, when the question was…",
  "author": "ofri-peretz <https://github.com/ofri-peretz>",
  "categories": [
    "games",
    "game"
  ],
  "dependencies": [
    "@base-ui/react"
  ],
  "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/use-reduced-motion.json"
  ],
  "files": [
    {
      "path": "registry/interlace-ui/games/rating.tsx",
      "target": "components/ui/games/rating.tsx",
      "type": "registry:ui",
      "content": "'use client';\n\nimport { Radio } from '@base-ui/react/radio';\n\n// @interlace/rating v1.0.0 — Interlace design system.\n// Docs, props and live preview: https://ds.interlace.tools/c/rating\n// What changed since: https://ds.interlace.tools/c/rating#history\n// Generated banner — keep it, the upgrade diff reads this version.\n\n/**\n * @interlace/ui — Rating\n *\n * A scale question for a room: how familiar, how likely to recommend, how\n * are you feeling. Each person picks one step and sends it; then they see\n * the room's answers on the same scale, their own step marked, the room's\n * average, and, when the question was asked before, where the room stood\n * then. A 0 to 10 scale also shows the recommend score.\n *\n * ## Anatomy\n *\n *   Rating                         (div — data-slot=\"rating\", data-state=choosing|sent)\n *     ├─ p                         (data-slot=\"rating-question\")\n *     ├─ RadioGroup (choosing)     (data-slot=\"rating-steps\": one radio per step, arrows move)\n *     ├─ div aria-hidden (sent)    (data-slot=\"rating-chart\": a bar per step, a ghost bar for before)\n *     ├─ div                       (data-slot=\"rating-ends\": the words for each end)\n *     ├─ Button (choosing)         (data-slot=\"rating-send\")\n *     └─ p tabIndex=-1 aria-live  (data-slot=\"rating-result\": the picture in one sentence)\n *\n * ## Data\n *\n * `values` are the room's ratings from your store, without this viewer's\n * own unless `valuesIncludeOwn`. `before` is an earlier round. `faces`\n * replaces the numbers with icons (a mood check); each still has a name\n * for screen readers. `minResponses` keeps the room hidden until enough\n * people have answered. The rules live in `games/rating-model`.\n *\n * ## Motion\n *\n * Bars are each round's shares on one scale, so rounds of different sizes\n * compare fairly. On sending, the bars grow from the baseline together (250ms, transform).\n * Under reduced motion the chart 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        | rating / -question / -steps / -chart / -ends / -send / -result |\n * | R7   | cn + ...rest              | `cn(…, className)` + `{...props}`                     |\n * | R9   | Controlled + uncontrolled | `value` / `defaultValue` / `onRate`                   |\n * | R14  | Declares min viewport     | `data-min-viewport` + exported const                  |\n * | R26  | A11y                      | a radio group with names; chart hidden, result sentence focused |\n */\n\nimport { RadioGroup } from '@base-ui/react/radio-group';\nimport * as React from 'react';\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 { ratingSteps, summarizeRatings } from '@/components/ui/games/rating-model';\n\nexport const MIN_VIEWPORT = 320 as const;\n\ninterface RatingFace {\n  icon: React.ReactNode;\n  /** What the face means, for screen readers and the result sentence. */\n  name: string;\n}\n\ninterface RatingLabels {\n  /** @default 'Send' */\n  send?: string;\n  /**\n   * After sending. `mine` and `average` are step names (the number, or the\n   * face's name); `before` is the earlier average, when there is one.\n   * @default English: '{count} people answered. Yours: {mine}. The room's average: {average}.'\n   */\n  result?: (r: {\n    count: string;\n    mine: string;\n    average: string;\n    before: string | null;\n    recommend: string | null;\n  }) => string;\n  /** While fewer than `minResponses` are in. @default (min) => `Thanks. The room shows once ${min} people have answered.` */\n  pending?: (min: number) => string;\n  /** The legend for the earlier round. @default 'Before' */\n  before?: string;\n}\n\ntype RatingProps = Omit<React.ComponentProps<'div'>, 'children' | 'defaultValue'> & {\n  question: React.ReactNode;\n  /** @default 1 */\n  min?: number;\n  /** @default 5 */\n  max?: number;\n  /** Words for the two ends, as `[low, high]`. */\n  ends?: readonly [string, string];\n  /** Icons instead of numbers, one per step, low to high. */\n  faces?: readonly RatingFace[];\n  /** The room's ratings. */\n  values?: readonly number[];\n  /** `values` already hold this viewer's rating. @default false */\n  valuesIncludeOwn?: boolean;\n  /** An earlier round of the same question. */\n  before?: readonly number[];\n  /** The viewer's sent rating, controlled. null while choosing. */\n  value?: number | null;\n  /** The viewer's sent rating, uncontrolled. */\n  defaultValue?: number | null;\n  /** Called once, when the viewer sends. */\n  onRate?: (value: number) => void;\n  /** Hide the room until this many have answered. @default 1 */\n  minResponses?: number;\n  locale?: string;\n  labels?: RatingLabels;\n};\n\nconst RESULT: NonNullable<RatingLabels['result']> = ({ count, mine, average, before, recommend }) =>\n  `${count} ${count === '1' ? 'person' : 'people'} answered. Yours: ${mine}. The room's average: ${average}.` +\n  (before ? ` Before: ${before}.` : '') +\n  (recommend ? ` Recommend score: ${recommend}.` : '');\n\nfunction Rating({\n  question,\n  min = 1,\n  max = 5,\n  ends,\n  faces,\n  values = [],\n  valuesIncludeOwn = false,\n  before,\n  value: valueProp,\n  defaultValue = null,\n  onRate,\n  minResponses = 1,\n  locale,\n  labels,\n  className,\n  ...props\n}: RatingProps) {\n  const reduced = useReducedMotion();\n  const scale = { min, max };\n  const steps = ratingSteps(scale);\n  const first = steps[0] ?? min;\n  const [own, setOwn] = React.useState<number | null>(defaultValue);\n  const sent = valueProp === undefined ? own : valueProp;\n  const [draft, setDraft] = React.useState<number | null>(null);\n  const [sentHere, setSentHere] = React.useState(false);\n  const questionId = React.useId();\n  const resultRef = React.useRef<HTMLParagraphElement>(null);\n  const chartRef = React.useRef<HTMLDivElement>(null);\n  const one = React.useMemo(() => new Intl.NumberFormat(locale, { maximumFractionDigits: 1 }), [locale]);\n  const signed = React.useMemo(() => new Intl.NumberFormat(locale, { signDisplay: 'exceptZero' }), [locale]);\n\n  const all = sent === null || valuesIncludeOwn ? values : [...values, sent];\n  const room = summarizeRatings(all, scale);\n  const earlier = before && before.length > 0 ? summarizeRatings(before, scale) : null;\n  const shown = sent !== null && room.count >= minResponses;\n  const nameOf = (v: number) => faces?.[v - first]?.name ?? one.format(v);\n  const averageName = (mean: number) => (faces ? nameOf(Math.round(mean)) : one.format(mean));\n\n  React.useEffect(() => {\n    if (!shown || !sentHere) return;\n    resultRef.current?.focus();\n    if (reduced) return;\n    chartRef.current?.querySelectorAll<HTMLElement>('[data-slot=\"rating-bar\"]').forEach((bar) => {\n      if (typeof bar.animate !== 'function') return;\n      bar.animate([{ transform: 'scaleY(0)' }, { transform: 'scaleY(1)' }], {\n        duration: 250,\n        easing: motionEase(bar, 'enter'),\n      });\n    });\n    // Once, when this viewer's rating lands.\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [shown, sentHere]);\n\n  const send = () => {\n    if (sent !== null || draft === null) return;\n    setSentHere(true);\n    if (valueProp === undefined) setOwn(draft);\n    onRate?.(draft);\n  };\n\n  // Bars are shares of each round, on one scale, so two rounds of different sizes compare fairly.\n  const share = (n: number, total: number) => (total > 0 ? n / total : 0);\n  const top = Math.max(share(room.peak, room.count), earlier ? share(earlier.peak, earlier.count) : 0, Number.EPSILON);\n\n  return (\n    <div\n      data-slot=\"rating\"\n      data-state={sent === null ? 'choosing' : 'sent'}\n      data-min-viewport={String(MIN_VIEWPORT)}\n      className={cn('grid gap-4', className)}\n      {...props}\n    >\n      <p id={questionId} data-slot=\"rating-question\" className=\"font-heading text-lg font-semibold text-balance\">\n        {question}\n      </p>\n\n      {sent === null ? (\n        <RadioGroup\n          data-slot=\"rating-steps\"\n          aria-labelledby={questionId}\n          value={draft}\n          onValueChange={(v) => setDraft(v as number)}\n          className=\"flex gap-1.5\"\n        >\n          {steps.map((v) => (\n            <Radio.Root\n              key={v}\n              value={v}\n              aria-label={nameOf(v)}\n              data-slot=\"rating-step\"\n              className={cn(\n                'bg-background text-foreground grid min-h-11 min-w-0 flex-1 place-items-center rounded-md border text-base font-semibold tabular-nums',\n                'motion-safe:transition-colors motion-safe:duration-(--duration-fast) hover:bg-muted',\n                'data-[checked]:bg-primary data-[checked]:text-primary-foreground data-[checked]:border-primary',\n                'focus-visible:outline-ring outline-offset-2 focus-visible:outline-2',\n                faces && '[&_svg]:size-6',\n              )}\n            >\n              {faces ? faces[v - first]?.icon : one.format(v)}\n            </Radio.Root>\n          ))}\n        </RadioGroup>\n      ) : shown ? (\n        <div ref={chartRef} aria-hidden data-slot=\"rating-chart\" className=\"grid gap-1\">\n          <div className=\"flex h-24 items-end gap-1.5 border-b\">\n            {room.counts.map((n, i) => {\n              const v = steps[i] as number;\n              const ghost = earlier ? share(earlier.counts[i] as number, earlier.count) / top : 0;\n              return (\n                <div key={v} className=\"relative flex h-full flex-1 items-end justify-center\">\n                  {earlier ? (\n                    <span\n                      data-slot=\"rating-before\"\n                      className=\"border-muted-foreground/60 absolute inset-x-1 bottom-0 rounded-t-sm border border-b-0 border-dashed\"\n                      style={{ height: `${ghost * 100}%` }}\n                    />\n                  ) : null}\n                  <span\n                    data-slot=\"rating-bar\"\n                    data-mine={v === sent ? '' : undefined}\n                    className={cn(\n                      'relative block w-full origin-bottom rounded-t-sm',\n                      v === sent ? 'bg-primary' : 'bg-foreground/25',\n                    )}\n                    style={{ height: `${(share(n, room.count) / top) * 100}%` }}\n                  />\n                </div>\n              );\n            })}\n          </div>\n          <div className=\"text-muted-foreground flex gap-1.5 text-center text-xs tabular-nums [&_svg]:mx-auto [&_svg]:size-4\">\n            {steps.map((v) => (\n              <span key={v} className=\"flex-1\">\n                {faces ? faces[v - first]?.icon : one.format(v)}\n              </span>\n            ))}\n          </div>\n          {earlier ? (\n            <p className=\"text-muted-foreground flex items-center gap-2 text-xs\">\n              <span className=\"border-muted-foreground/60 inline-block size-3 rounded-sm border border-dashed\" />\n              {labels?.before ?? 'Before'}\n            </p>\n          ) : null}\n        </div>\n      ) : null}\n\n      {ends ? (\n        <div data-slot=\"rating-ends\" className=\"text-muted-foreground flex justify-between gap-4 text-sm\">\n          <span className=\"max-w-[45%]\">{ends[0]}</span>\n          <span className=\"max-w-[45%] text-end\">{ends[1]}</span>\n        </div>\n      ) : null}\n\n      {sent === null ? (\n        <Button\n          data-slot=\"rating-send\"\n          size=\"lg\"\n          className=\"justify-self-start\"\n          disabled={draft === null}\n          onClick={send}\n        >\n          {labels?.send ?? 'Send'}\n        </Button>\n      ) : null}\n\n      <p\n        ref={resultRef}\n        tabIndex={-1}\n        data-slot=\"rating-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        {sent === null\n          ? ''\n          : shown && room.mean !== null\n            ? (labels?.result ?? RESULT)({\n                count: one.format(room.count),\n                mine: nameOf(sent),\n                average: averageName(room.mean),\n                before: earlier?.mean != null ? averageName(earlier.mean) : null,\n                recommend: room.recommend === null ? null : signed.format(room.recommend),\n              })\n            : (labels?.pending ?? ((n: number) => `Thanks. The room shows once ${n} people have answered.`))(\n                minResponses,\n              )}\n      </p>\n    </div>\n  );\n}\nRating.displayName = 'Rating';\n\nexport { Rating };\nexport type { RatingProps, RatingLabels, RatingFace };\n"
    },
    {
      "path": "registry/interlace-ui/games/rating-model.ts",
      "target": "components/ui/games/rating-model.ts",
      "type": "registry:ui",
      "content": "export interface RatingScale {\n  /** @default 1 */\n  min?: number;\n  /** @default 5 */\n  max?: number;\n}\n\nexport interface RatingSummary {\n  count: number;\n  /** One count per step, from `min` to `max`. */\n  counts: number[];\n  /** The largest count, for drawing bars. */\n  peak: number;\n  mean: number | null;\n  median: number | null;\n  /** Only for a 0 to 10 scale: % at 9 to 10 minus % at 0 to 6, rounded. */\n  recommend: number | null;\n}\n\n// ponytail: MAX_STEPS = 1000, far past any real scale (1 to 5, 0 to 10, 1 to 100); it stops a\n// host-config scale of Infinity or 1e9 from building an endless step list.\nconst MAX_STEPS = 1000;\n\n/** A scale the host sent, held to finite bounds and at most MAX_STEPS steps. */\nfunction bounds(scale: RatingScale): { min: number; max: number } {\n  const min = Number.isFinite(scale.min) ? (scale.min as number) : 1;\n  const max = Number.isFinite(scale.max) ? (scale.max as number) : 5;\n  return { min, max: Math.min(max, Math.ceil(min) + MAX_STEPS - 1) };\n}\n\n/** The steps of a scale, `min` to `max`. */\nexport function ratingSteps(scale: RatingScale = {}): number[] {\n  const { min, max } = bounds(scale);\n  const out: number[] = [];\n  for (let v = Math.ceil(min); v <= max; v++) out.push(v);\n  return out;\n}\n\n/** Keeps whole steps on the scale; drops anything else. */\nexport function cleanRatings(values: readonly number[], scale: RatingScale = {}): number[] {\n  const { min, max } = bounds(scale);\n  return values.filter((v) => Number.isInteger(v) && v >= min && v <= max);\n}\n\nexport function summarizeRatings(values: readonly number[], scale: RatingScale = {}): RatingSummary {\n  const { min, max } = bounds(scale);\n  const steps = ratingSteps(scale);\n  const clean = cleanRatings(values, scale);\n  const counts = steps.map(() => 0);\n  for (const v of clean) counts[v - Math.ceil(min)] = (counts[v - Math.ceil(min)] as number) + 1;\n  const peak = Math.max(0, ...counts);\n  if (clean.length === 0) return { count: 0, counts, peak, mean: null, median: null, recommend: null };\n  const sorted = [...clean].sort((a, b) => a - b);\n  const mid = (sorted.length - 1) / 2;\n  const median = ((sorted[Math.floor(mid)] as number) + (sorted[Math.ceil(mid)] as number)) / 2;\n  const mean = clean.reduce((a, b) => a + b, 0) / clean.length;\n  let recommend: number | null = null;\n  if (min === 0 && max === 10) {\n    const promoters = clean.filter((v) => v >= 9).length;\n    const detractors = clean.filter((v) => v <= 6).length;\n    recommend = Math.round(((promoters - detractors) / clean.length) * 100);\n  }\n  return { count: clean.length, counts, peak, mean, median, recommend };\n}\n\n/** How far the mean moved from `before` to `after`, or null when either is empty. */\nexport function ratingShift(\n  before: readonly number[],\n  after: readonly number[],\n  scale: RatingScale = {},\n): number | null {\n  const a = summarizeRatings(before, scale).mean;\n  const b = summarizeRatings(after, scale).mean;\n  return a === null || b === null ? null : b - a;\n}\n\n/**\n * @interlace/ui — rating-model\n *\n * A rating scale and what a room's ratings say. One model covers a 1 to 5\n * familiarity check, a 0 to 10 recommend score, a mood check with faces and\n * the same question asked before and after a session.\n *\n * `summarizeRatings` counts each step, finds the mean and median, and, for a\n * 0 to 10 scale, the recommend score (the share at 9 or 10 minus the share\n * at 0 to 6, from -100 to 100). `ratingShift` says how far the mean moved\n * between two rounds. Values off the scale, or not whole steps, are dropped,\n * so a bad message cannot skew the room.\n */\n"
    }
  ],
  "meta": {
    "tier": "game",
    "client": true,
    "minViewport": 320,
    "loading": false,
    "version": "1.0.0",
    "since": "2.0.0"
  },
  "docs": "## @interlace/rating\n\nInstalled to `components/ui/games/rating.tsx`.\n\n```tsx\nimport { /* … */ } from '@/components/ui/games/rating';\n```\n\nProps, a11y contract, live preview and source: https://ds.interlace.tools/c/rating\n\nRequires the `@interlace/interlace-base` CSS baseline (installed automatically as a registry dependency). For the Interlace look, also add `@interlace/theme`."
}
