{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "quadrant",
  "type": "registry:ui",
  "title": "Quadrant",
  "description": "A 2 x 2 grid: two questions at once (\"how hard / how important\"). Each person places one dot on a square pad, by tapping, dragging or the arrow keys, then sees the room on the same grid: where the dots crowd, how many sit in each quarter, the room's…",
  "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/use-reduced-motion.json"
  ],
  "files": [
    {
      "path": "registry/interlace-ui/games/quadrant.tsx",
      "target": "components/ui/games/quadrant.tsx",
      "type": "registry:ui",
      "content": "'use client';\n\nimport * as React from 'react';\n\n// @interlace/quadrant v1.0.0 — Interlace design system.\n// Docs, props and live preview: https://ds.interlace.tools/c/quadrant\n// What changed since: https://ds.interlace.tools/c/quadrant#history\n// Generated banner — keep it, the upgrade diff reads this version.\n\n/**\n * @interlace/ui — Quadrant and QuadrantMap\n *\n * A 2 x 2 grid: two questions at once (\"how hard / how important\"). Each\n * person places one dot on a square pad, by tapping, dragging or the arrow\n * keys, then sees the room on the same grid: where the dots crowd, how many\n * sit in each quarter, the room's middle, and, when asked before, where the\n * middle was then. `QuadrantMap` is the same picture for a shared screen.\n *\n * ## Anatomy\n *\n *   Quadrant                         (div — data-slot=\"quadrant\", data-state=placing|placed)\n *     ├─ p                           (data-slot=\"quadrant-prompt\")\n *     ├─ div role=group              (data-slot=\"quadrant-pad\": tap or drag to move the dot)\n *     │   ├─ axis lines, pole labels, corner names\n *     │   └─ button                  (data-slot=\"quadrant-dot\": arrow keys; its name is the place in words)\n *     ├─ QuadrantChart (placed)      (aria-hidden: everyone's dots, quarter counts, yours, the middle, before; a legend)\n *     ├─ Button (placing)            (data-slot=\"quadrant-place\")\n *     ├─ span sr-only aria-live      (data-slot=\"quadrant-announce\": the place in words, as it changes)\n *     └─ p tabIndex=-1 aria-live     (data-slot=\"quadrant-result\": the picture in one sentence)\n *   QuadrantMap                      (div — data-slot=\"quadrant-map\": the chart and its sentence)\n *\n * ## Data\n *\n * `x` runs 0 (the start pole) to 100 (the end pole); `y` runs 0 (the bottom\n * pole) to 100 (the top pole). In right-to-left the start pole sits on the\n * right, and the arrow keys follow what the eye sees. `points` are the\n * room's dots without this viewer's own unless `pointsIncludeOwn`;\n * `minResponses` hides the room until enough dots are in.\n *\n * ## Motion\n *\n * The room's dots fade in together (250ms) and the room's middle travels from the\n * viewer's dot to where the room is (400ms, `--ease-move`). Under reduced\n * motion the picture is simply there. The dot follows a finger or the keys\n * at once: input never waits on animation.\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        | quadrant / -prompt / -pad / -dot / -chart / -place / -announce / -result; quadrant-map |\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                      | dot moved by keys, its place in words; 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 {\n  cleanPoints,\n  nudgePoint,\n  QUARTERS,\n  quadrantShift,\n  summarizeQuadrant,\n  type QuadPoint,\n  type Quarter,\n} from '@/components/ui/games/quadrant-model';\n\nexport const MIN_VIEWPORT = 320 as const;\n\ninterface QuadrantAxes {\n  /** The horizontal axis, [start, end]. */\n  x: readonly [string, string];\n  /** The vertical axis, [bottom, top]. */\n  y: readonly [string, string];\n}\n\ninterface QuadrantLabels {\n  /** @default 'Place my dot' */\n  place?: string;\n  /** A place in words. @default 'Closer to {end}, closer to {top}', or 'In the middle' */\n  position?: (p: QuadPoint, axes: QuadrantAxes) => string;\n  /** How to move the dot. @default 'Tap the grid or use the arrow keys to move your dot.' */\n  hint?: string;\n  /** A quarter's name. @default (q, axes) => `${top or bottom} and ${start or end}` */\n  quarter?: (q: Quarter, axes: QuadrantAxes) => string;\n  /**\n   * The picture in one sentence. `most` is a quarter's name or null when\n   * the room is spread; `mine` is null on a screen.\n   */\n  result?: (r: { count: string; most: string | null; mine: string | null; moved: boolean }) => string;\n  /** @default (min) => `Thanks. The room shows once ${min} people have placed a dot.` */\n  pending?: (min: number) => string;\n  /** Legend: the viewer's dot. @default 'You' */\n  you?: string;\n  /** Legend: the room's middle. @default 'Room' */\n  middle?: string;\n  /** A screen with no dots yet. @default 'No dots yet.' */\n  empty?: string;\n  /** @default 'Before' */\n  before?: string;\n}\n\nconst POSITION: NonNullable<QuadrantLabels['position']> = (p, axes) => {\n  const x = p.x < 40 ? `closer to ${axes.x[0]}` : p.x > 60 ? `closer to ${axes.x[1]}` : null;\n  const y = p.y < 40 ? `closer to ${axes.y[0]}` : p.y > 60 ? `closer to ${axes.y[1]}` : null;\n  const words = [x, y].filter(Boolean).join(', ');\n  return words ? words.charAt(0).toUpperCase() + words.slice(1) : 'In the middle';\n};\nconst QUARTER: NonNullable<QuadrantLabels['quarter']> = (q, axes) => {\n  const [v, h] = q.split('-');\n  return `${v === 'top' ? axes.y[1] : axes.y[0]} and ${h === 'end' ? axes.x[1] : axes.x[0]}`;\n};\nconst RESULT: NonNullable<QuadrantLabels['result']> = ({ count, most, mine, moved }) =>\n  `${count} ${count === '1' ? 'person' : 'people'} placed a dot. ${most ? `Most are in ${most}.` : 'The room is spread out.'}${mine ? ` Yours: ${mine}.` : ''}${moved ? ' The middle has moved since before.' : ''}`;\nconst PENDING: NonNullable<QuadrantLabels['pending']> = (min) =>\n  `Thanks. The room shows once ${min} people have placed a dot.`;\n\n/** Places a mark at a point: inline-start for x (so it mirrors in RTL), top for y. */\nconst at = (p: QuadPoint): React.CSSProperties => ({ insetInlineStart: `${p.x}%`, top: `${100 - p.y}%` });\n/** The writing direction around an element: the nearest `dir`, else the computed style. */\nfunction directionOf(el: Element): 'ltr' | 'rtl' {\n  const dir = el.closest('[dir]')?.getAttribute('dir');\n  if (dir === 'rtl' || dir === 'ltr') return dir;\n  return getComputedStyle(el).direction === 'rtl' ? 'rtl' : 'ltr';\n}\n\nconst MARK = 'absolute -translate-x-1/2 -translate-y-1/2 rtl:translate-x-1/2';\n\nfunction Poles({ axes, stage }: { axes: QuadrantAxes; stage?: boolean }) {\n  const text = cn('text-muted-foreground absolute font-medium', stage ? 'text-sm' : 'text-xs');\n  return (\n    <>\n      <span className={cn(text, 'start-1/2 top-1 -translate-x-1/2 rtl:translate-x-1/2')}>{axes.y[1]}</span>\n      <span className={cn(text, 'start-1/2 bottom-1 -translate-x-1/2 rtl:translate-x-1/2')}>{axes.y[0]}</span>\n      <span className={cn(text, 'start-1.5 top-1/2 -translate-y-1/2')}>{axes.x[0]}</span>\n      <span className={cn(text, 'end-1.5 top-1/2 -translate-y-1/2')}>{axes.x[1]}</span>\n    </>\n  );\n}\n\nfunction Lines() {\n  return (\n    <>\n      <span aria-hidden className=\"bg-border absolute inset-y-0 start-1/2 w-px\" />\n      <span aria-hidden className=\"bg-border absolute inset-x-0 top-1/2 h-px\" />\n    </>\n  );\n}\n\ninterface ChartProps {\n  points: readonly QuadPoint[];\n  axes: QuadrantAxes;\n  mine?: QuadPoint | null;\n  before?: readonly QuadPoint[];\n  stage?: boolean;\n  /** Play the arrival: the dots fade in, the middle travels from `mine`. */\n  arrive: boolean;\n  locale?: string;\n  labels?: QuadrantLabels;\n}\n\nfunction QuadrantChart({ points, axes, mine, before, stage, arrive, locale, labels }: ChartProps) {\n  const ref = React.useRef<HTMLDivElement>(null);\n  const nf = React.useMemo(() => new Intl.NumberFormat(locale), [locale]);\n  const room = summarizeQuadrant(points);\n  const earlier = before && before.length > 0 ? summarizeQuadrant(before).median : null;\n\n  React.useEffect(() => {\n    const chart = ref.current;\n    if (!arrive || !chart || typeof chart.animate !== 'function') return;\n    chart\n      .querySelector<HTMLElement>('[data-slot=\"quadrant-dots\"]')\n      ?.animate([{ opacity: 0 }, { opacity: 1 }], { duration: 250, easing: motionEase(chart, 'enter') });\n    const marker = chart.querySelector<HTMLElement>('[data-slot=\"quadrant-middle\"]');\n    if (!marker || !mine || !room.median) return;\n    const box = chart.getBoundingClientRect();\n    const flip = directionOf(chart) === 'rtl' ? -1 : 1;\n    const dx = ((mine.x - room.median.x) / 100) * box.width * flip;\n    const dy = ((room.median.y - mine.y) / 100) * box.height;\n    marker.animate([{ transform: `translate(${dx}px, ${dy}px)` }, { transform: 'translate(0, 0)' }], {\n      duration: 400,\n      easing: motionEase(marker, 'move'),\n    });\n    // Once, when the picture arrives.\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [arrive]);\n\n  const key = cn('text-muted-foreground flex items-center gap-1.5', stage ? 'text-sm' : 'text-xs');\n  return (\n    <div ref={ref} aria-hidden data-slot=\"quadrant-chart\" className=\"grid gap-2\">\n      <div className=\"bg-card relative aspect-square w-full overflow-hidden rounded-lg border\">\n        <div data-slot=\"quadrant-dots\" className=\"absolute inset-0\">\n          {cleanPoints(points).map((p, i) => (\n            <span\n              // Dots carry no identity of their own; their order is the room's.\n              key={`dot-${i}`}\n              className={cn(MARK, 'bg-foreground/35 rounded-full', stage ? 'size-3' : 'size-2')}\n              style={at(p)}\n            />\n          ))}\n        </div>\n        <Lines />\n        {QUARTERS.map((q) => {\n          const [v, h] = q.split('-');\n          return (\n            <span\n              key={q}\n              data-slot=\"quadrant-count\"\n              data-quarter={q}\n              className={cn(\n                'text-foreground bg-card/80 absolute rounded-sm px-1 font-semibold tabular-nums',\n                v === 'top' ? 'top-2' : 'bottom-2',\n                h === 'end' ? 'end-2' : 'start-2',\n                stage ? 'text-xl' : 'text-sm',\n              )}\n            >\n              {nf.format(room.quarters[q])}\n            </span>\n          );\n        })}\n        <Poles axes={axes} stage={stage} />\n        {earlier ? (\n          <span\n            data-slot=\"quadrant-before\"\n            className={cn(MARK, 'border-muted-foreground size-5 rounded-full border-2 border-dashed')}\n            style={at(earlier)}\n          />\n        ) : null}\n        {mine ? (\n          <span\n            data-slot=\"quadrant-mine\"\n            className={cn(MARK, 'bg-primary ring-card size-3.5 rounded-full ring-2')}\n            style={at(mine)}\n          />\n        ) : null}\n        {room.median ? (\n          <span data-slot=\"quadrant-middle\" className={cn(MARK, 'flex flex-col items-center')} style={at(room.median)}>\n            <span className=\"border-foreground bg-card/70 size-6 rounded-full border-2\" />\n          </span>\n        ) : null}\n      </div>\n      <div data-slot=\"quadrant-legend\" className=\"flex flex-wrap gap-x-4 gap-y-1\">\n        {mine ? (\n          <span className={key}>\n            <span className=\"bg-primary size-2.5 rounded-full\" />\n            {labels?.you ?? 'You'}\n          </span>\n        ) : null}\n        <span className={key}>\n          <span className=\"border-foreground size-3 rounded-full border-2\" />\n          {labels?.middle ?? 'Room'}\n        </span>\n        {earlier ? (\n          <span className={key}>\n            <span className=\"border-muted-foreground size-3 rounded-full border-2 border-dashed\" />\n            {labels?.before ?? 'Before'}\n          </span>\n        ) : null}\n      </div>\n    </div>\n  );\n}\n\nfunction sentence(\n  points: readonly QuadPoint[],\n  axes: QuadrantAxes,\n  mine: QuadPoint | null,\n  before: readonly QuadPoint[] | undefined,\n  nf: Intl.NumberFormat,\n  labels: QuadrantLabels | undefined,\n): string {\n  const room = summarizeQuadrant(points);\n  if (room.count === 0) return labels?.empty ?? 'No dots yet.';\n  const shift = before && before.length > 0 ? quadrantShift(before, points) : null;\n  return (labels?.result ?? RESULT)({\n    count: nf.format(room.count),\n    most: room.most ? (labels?.quarter ?? QUARTER)(room.most, axes) : null,\n    mine: mine ? (labels?.position ?? POSITION)(mine, axes) : null,\n    moved: shift !== null && Math.hypot(shift.x, shift.y) >= 10,\n  });\n}\n\n// --- Quadrant (phone) -------------------------------------------------------------\n\ntype QuadrantProps = Omit<React.ComponentProps<'div'>, 'children' | 'defaultValue'> & {\n  prompt: React.ReactNode;\n  axes: QuadrantAxes;\n  /** The room's dots. */\n  points?: readonly QuadPoint[];\n  /** `points` already hold this viewer's dot. @default false */\n  pointsIncludeOwn?: boolean;\n  /** An earlier round, drawn as a dashed ring at its middle. */\n  before?: readonly QuadPoint[];\n  /** The viewer's placed dot, controlled. null while placing. */\n  value?: QuadPoint | null;\n  defaultValue?: QuadPoint | null;\n  /** Called once, when the viewer places their dot. */\n  onPlace?: (point: QuadPoint) => void;\n  /** Hide the room until this many dots are in. @default 1 */\n  minResponses?: number;\n  /** How far an arrow key moves the dot. @default 5 */\n  step?: number;\n  locale?: string;\n  labels?: QuadrantLabels;\n};\n\nfunction Quadrant({\n  prompt,\n  axes,\n  points = [],\n  pointsIncludeOwn = false,\n  before,\n  value: valueProp,\n  defaultValue = null,\n  onPlace,\n  minResponses = 1,\n  step = 5,\n  locale,\n  labels,\n  className,\n  ...props\n}: QuadrantProps) {\n  const reduced = useReducedMotion();\n  const [own, setOwn] = React.useState<QuadPoint | null>(defaultValue);\n  const placed = valueProp === undefined ? own : valueProp;\n  const [draft, setDraft] = React.useState<QuadPoint>({ x: 50, y: 50 });\n  const [placedHere, setPlacedHere] = React.useState(false);\n  const [announce, setAnnounce] = React.useState('');\n  const promptId = React.useId();\n  const hintId = React.useId();\n  const padRef = React.useRef<HTMLDivElement>(null);\n  const dotRef = React.useRef<HTMLButtonElement>(null);\n  const resultRef = React.useRef<HTMLParagraphElement>(null);\n  const dragging = React.useRef(false);\n  const nf = React.useMemo(() => new Intl.NumberFormat(locale), [locale]);\n\n  const all = placed === null || pointsIncludeOwn ? points : [...points, placed];\n  const count = summarizeQuadrant(all).count;\n  const shown = placed !== null && count >= minResponses;\n  const words = (p: QuadPoint) => (labels?.position ?? POSITION)(p, axes);\n\n  React.useEffect(() => {\n    if (shown && placedHere) resultRef.current?.focus();\n  }, [shown, placedHere]);\n\n  const move = (next: QuadPoint) => {\n    setDraft(next);\n    // Speak only when the words change, so a drag does not chatter.\n    const said = words(next);\n    setAnnounce((prev) => (prev === said ? prev : said));\n  };\n\n  const fromPointer = (e: React.PointerEvent) => {\n    const pad = padRef.current;\n    if (!pad) return;\n    const box = pad.getBoundingClientRect();\n    if (box.width === 0 || box.height === 0 || !Number.isFinite(e.clientX) || !Number.isFinite(e.clientY)) return;\n    const rtl = directionOf(pad) === 'rtl';\n    const fx = (e.clientX - box.left) / box.width;\n    const x = Math.round((rtl ? 1 - fx : fx) * 100);\n    const y = Math.round((1 - (e.clientY - box.top) / box.height) * 100);\n    move({ x: Math.min(100, Math.max(0, x)), y: Math.min(100, Math.max(0, y)) });\n  };\n\n  const place = () => {\n    if (placed !== null) return;\n    setPlacedHere(true);\n    if (valueProp === undefined) setOwn(draft);\n    onPlace?.(draft);\n  };\n\n  return (\n    <div\n      data-slot=\"quadrant\"\n      data-state={placed === null ? 'placing' : 'placed'}\n      data-min-viewport={String(MIN_VIEWPORT)}\n      className={cn('grid max-w-112 gap-4', className)}\n      {...props}\n    >\n      <p id={promptId} data-slot=\"quadrant-prompt\" className=\"font-heading text-lg font-semibold text-balance\">\n        {prompt}\n      </p>\n\n      {placed === null ? (\n        <div\n          ref={padRef}\n          role=\"group\"\n          aria-labelledby={promptId}\n          data-slot=\"quadrant-pad\"\n          className=\"bg-card relative aspect-square w-full cursor-crosshair touch-none overflow-hidden rounded-lg border select-none\"\n          onPointerDown={(e) => {\n            dragging.current = true;\n            e.currentTarget.setPointerCapture?.(e.pointerId);\n            fromPointer(e);\n            dotRef.current?.focus({ preventScroll: true });\n          }}\n          onPointerMove={(e) => {\n            if (dragging.current) fromPointer(e);\n          }}\n          onPointerUp={() => {\n            dragging.current = false;\n          }}\n          onPointerCancel={() => {\n            dragging.current = false;\n          }}\n        >\n          <Lines />\n          <span aria-hidden>\n            <Poles axes={axes} />\n          </span>\n          <button\n            ref={dotRef}\n            type=\"button\"\n            data-slot=\"quadrant-dot\"\n            aria-label={words(draft)}\n            aria-describedby={hintId}\n            onKeyDown={(e) => {\n              const dir = directionOf(e.currentTarget);\n              const next = nudgePoint(draft, e.key, e.shiftKey ? 1 : step, dir);\n              if (!next) return;\n              e.preventDefault();\n              move(next);\n            }}\n            className={cn(\n              MARK,\n              'bg-primary ring-card focus-visible:outline-ring size-6 rounded-full shadow-sm ring-2 outline-offset-2 focus-visible:outline-2',\n            )}\n            style={at(draft)}\n          />\n          <span id={hintId} className=\"sr-only\">\n            {labels?.hint ?? 'Tap the grid or use the arrow keys to move your dot.'}\n          </span>\n        </div>\n      ) : shown ? (\n        <QuadrantChart\n          points={all}\n          axes={axes}\n          mine={placed}\n          before={before}\n          arrive={placedHere && !reduced}\n          locale={locale}\n          labels={labels}\n        />\n      ) : null}\n\n      {placed === null ? (\n        <Button data-slot=\"quadrant-place\" size=\"lg\" className=\"justify-self-start\" onClick={place}>\n          {labels?.place ?? 'Place my dot'}\n        </Button>\n      ) : null}\n\n      <span data-slot=\"quadrant-announce\" aria-live=\"polite\" className=\"sr-only\">\n        {placed === null ? announce : ''}\n      </span>\n      <p\n        ref={resultRef}\n        tabIndex={-1}\n        data-slot=\"quadrant-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\n            ? sentence(all, axes, placed, before, nf, labels)\n            : (labels?.pending ?? PENDING)(minResponses)}\n      </p>\n    </div>\n  );\n}\nQuadrant.displayName = 'Quadrant';\n\n// --- QuadrantMap (screen) ---------------------------------------------------------\n\ntype QuadrantMapProps = Omit<React.ComponentProps<'div'>, 'children'> & {\n  axes: QuadrantAxes;\n  points: readonly QuadPoint[];\n  before?: readonly QuadPoint[];\n  /** `stage` for a shared screen. @default 'default' */\n  size?: 'default' | 'stage';\n  locale?: string;\n  labels?: QuadrantLabels;\n};\n\nfunction QuadrantMap({\n  axes,\n  points,\n  before,\n  size = 'default',\n  locale,\n  labels,\n  className,\n  ...props\n}: QuadrantMapProps) {\n  const nf = React.useMemo(() => new Intl.NumberFormat(locale), [locale]);\n  const stage = size === 'stage';\n  return (\n    <div\n      data-slot=\"quadrant-map\"\n      data-min-viewport={String(MIN_VIEWPORT)}\n      className={cn('grid gap-3', stage ? 'max-w-168' : 'max-w-112', className)}\n      {...props}\n    >\n      <QuadrantChart\n        points={points}\n        axes={axes}\n        before={before}\n        stage={stage}\n        arrive={false}\n        locale={locale}\n        labels={labels}\n      />\n      <p className={cn('text-muted-foreground', stage ? 'text-lg' : 'text-sm')}>\n        {sentence(points, axes, null, before, nf, labels)}\n      </p>\n    </div>\n  );\n}\nQuadrantMap.displayName = 'QuadrantMap';\n\nexport { Quadrant, QuadrantMap };\nexport type { QuadrantProps, QuadrantMapProps, QuadrantLabels, QuadrantAxes };\n"
    },
    {
      "path": "registry/interlace-ui/games/quadrant-model.ts",
      "target": "components/ui/games/quadrant-model.ts",
      "type": "registry:ui",
      "content": "export interface QuadPoint {\n  x: number;\n  y: number;\n}\n\nexport type Quarter = 'top-start' | 'top-end' | 'bottom-start' | 'bottom-end';\n\n/** Reading order: top row first, start before end. */\nexport const QUARTERS: readonly Quarter[] = ['top-start', 'top-end', 'bottom-start', 'bottom-end'];\n\nexport interface QuadrantSummary {\n  count: number;\n  quarters: Record<Quarter, number>;\n  /** The quarter with the most dots, or null when two or more tie (or none). */\n  most: Quarter | null;\n  /** Dots per cell, row by row from the top, start to end. */\n  cells: number[][];\n  /** The most dots in any one cell. */\n  peak: number;\n  mean: QuadPoint | null;\n  median: QuadPoint | null;\n}\n\n// ponytail: cap of 100 cells per side (10,000 cells), so a hostile or mistyped size cannot allocate a huge grid.\nconst MAX_CELLS = 100;\nconst DEFAULT_CELLS = 10;\n\n/** A grid side: a whole number from 1 to MAX_CELLS; anything that is not a number gets the default. */\nfunction gridSize(v: unknown): number {\n  if (typeof v !== 'number' || Number.isNaN(v)) return DEFAULT_CELLS;\n  return Math.min(MAX_CELLS, Math.max(1, Math.floor(v)));\n}\n\nconst clamp = (v: number) => Math.min(100, Math.max(0, v));\n\n/** Drops dots that are not two finite numbers and pulls the rest onto the grid. A non-array list is empty. */\nexport function cleanPoints(points: readonly QuadPoint[]): QuadPoint[] {\n  if (!Array.isArray(points)) return [];\n  return points\n    .filter((p) => p != null && Number.isFinite(p.x) && Number.isFinite(p.y))\n    .map((p) => ({ x: clamp(p.x), y: clamp(p.y) }));\n}\n\n/** The quarter a dot is in; the centre lines belong to the end and top halves. */\nexport function quarterOf(p: QuadPoint): Quarter {\n  return `${p.y >= 50 ? 'top' : 'bottom'}-${p.x >= 50 ? 'end' : 'start'}` as Quarter;\n}\n\nfunction median(sorted: readonly number[]): number {\n  const mid = (sorted.length - 1) / 2;\n  return ((sorted[Math.floor(mid)] as number) + (sorted[Math.ceil(mid)] as number)) / 2;\n}\n\n/** The cell a dot falls in, as [row from the top, column from the start]. */\nexport function cellOf(p: QuadPoint, cells = 10): [number, number] {\n  const n = gridSize(cells);\n  const col = Math.min(n - 1, Math.floor((clamp(p.x) / 100) * n));\n  const rowFromBottom = Math.min(n - 1, Math.floor((clamp(p.y) / 100) * n));\n  return [n - 1 - rowFromBottom, col];\n}\n\nexport function summarizeQuadrant(points: readonly QuadPoint[], options: { cells?: number } | null = {}): QuadrantSummary {\n  const n = gridSize(options?.cells);\n  const clean = cleanPoints(points);\n  const quarters: Record<Quarter, number> = { 'top-start': 0, 'top-end': 0, 'bottom-start': 0, 'bottom-end': 0 };\n  const cells = Array.from({ length: n }, () => Array.from({ length: n }, () => 0));\n  for (const p of clean) {\n    quarters[quarterOf(p)] += 1;\n    const [r, c] = cellOf(p, n);\n    (cells[r] as number[])[c] = ((cells[r] as number[])[c] as number) + 1;\n  }\n  const top = Math.max(...QUARTERS.map((q) => quarters[q]));\n  const leaders = QUARTERS.filter((q) => quarters[q] === top);\n  const most = top > 0 && leaders.length === 1 ? (leaders[0] as Quarter) : null;\n  if (clean.length === 0) return { count: 0, quarters, most, cells, peak: 0, mean: null, median: null };\n  const xs = clean.map((p) => p.x).sort((a, b) => a - b);\n  const ys = clean.map((p) => p.y).sort((a, b) => a - b);\n  return {\n    count: clean.length,\n    quarters,\n    most,\n    cells,\n    peak: Math.max(...cells.flat()),\n    mean: { x: xs.reduce((a, b) => a + b, 0) / xs.length, y: ys.reduce((a, b) => a + b, 0) / ys.length },\n    median: { x: median(xs), y: median(ys) },\n  };\n}\n\n/** How far the room's middle moved from `before` to `after`, or null when either is empty. */\nexport function quadrantShift(before: readonly QuadPoint[], after: readonly QuadPoint[]): QuadPoint | null {\n  const a = summarizeQuadrant(before).median;\n  const b = summarizeQuadrant(after).median;\n  return a === null || b === null ? null : { x: b.x - a.x, y: b.y - a.y };\n}\n\n/** A dot moved by a key: arrows by `step`, never off the grid. `dir` flips start and end. */\nexport function nudgePoint(p: QuadPoint, key: string, step = 5, dir: 'ltr' | 'rtl' = 'ltr'): QuadPoint | null {\n  // A dot or step that is not a finite number falls back to the centre and the default step.\n  const at = (v: unknown) => (Number.isFinite(v) ? clamp(v as number) : 50);\n  p = { x: at(p?.x), y: at(p?.y) };\n  if (!Number.isFinite(step)) step = 5;\n  const flip = dir === 'rtl' ? -1 : 1;\n  switch (key) {\n    case 'ArrowRight':\n      return { x: clamp(p.x + step * flip), y: p.y };\n    case 'ArrowLeft':\n      return { x: clamp(p.x - step * flip), y: p.y };\n    case 'ArrowUp':\n      return { x: p.x, y: clamp(p.y + step) };\n    case 'ArrowDown':\n      return { x: p.x, y: clamp(p.y - step) };\n    case 'Home':\n      return { x: 0, y: p.y };\n    case 'End':\n      return { x: 100, y: p.y };\n    case 'PageUp':\n      return { x: p.x, y: 100 };\n    case 'PageDown':\n      return { x: p.x, y: 0 };\n    default:\n      return null;\n  }\n}\n\n/**\n * @interlace/ui — quadrant-model\n *\n * Where a room sits on two questions at once: a 2 x 2 grid (\"how hard /\n * how important\", \"how much I knew / how much I care\"). Everyone places one\n * dot; `x` runs 0 (the start pole) to 100 (the end pole), `y` runs 0 (the\n * bottom pole) to 100 (the top pole). Pure, so a server, a screen and a\n * recap page draw the same picture.\n *\n * `summarizeQuadrant` counts dots per quarter, bins them into a square grid\n * of cells for a density picture, and finds the room's middle (the median\n * on each axis) and the mean. `quadrantShift` says how far the middle moved\n * between two rounds. A dot that is not two finite numbers is dropped;\n * anything off the grid is pulled to its edge.\n */\n"
    }
  ],
  "meta": {
    "tier": "game",
    "client": true,
    "minViewport": 320,
    "loading": false,
    "version": "1.0.0",
    "since": "2.0.0"
  },
  "docs": "## @interlace/quadrant\n\nInstalled to `components/ui/games/quadrant.tsx`.\n\n```tsx\nimport { /* … */ } from '@/components/ui/games/quadrant';\n```\n\nProps, a11y contract, live preview and source: https://ds.interlace.tools/c/quadrant\n\nRequires the `@interlace/interlace-base` CSS baseline (installed automatically as a registry dependency). For the Interlace look, also add `@interlace/theme`."
}
