{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "pin-drop",
  "type": "registry:ui",
  "title": "Pin Drop",
  "description": "A pin on a picture (a map, a floor plan, a diagram). On a phone, `PinDrop` lets each person place one pin by tap, drag or arrow keys. With an `answer` it is \"Where is it?\": once the host reveals, the answer appears, a line joins it to the viewer's pin, and…",
  "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/pin-drop.tsx",
      "target": "components/ui/games/pin-drop.tsx",
      "type": "registry:ui",
      "content": "'use client';\n\nimport * as React from 'react';\n\n// @interlace/pin-drop v1.0.0 — Interlace design system.\n// Docs, props and live preview: https://ds.interlace.tools/c/pin-drop\n// What changed since: https://ds.interlace.tools/c/pin-drop#history\n// Generated banner — keep it, the upgrade diff reads this version.\n\n/**\n * @interlace/ui — PinDrop and PinMap\n *\n * A pin on a picture (a map, a floor plan, a diagram). On a phone,\n * `PinDrop` lets each person place one pin by tap, drag or arrow keys. With\n * an `answer` it is \"Where is it?\": once the host reveals, the answer\n * appears, a line joins it to the viewer's pin, and the points say how\n * close it was. Without one it is \"Where are you?\" and the room's pins are\n * the result. `PinMap` is the shared screen: every pin, and the answer\n * once revealed.\n *\n * A pin is said in words: the named `regions` of the picture when given\n * (\"In the harbour\"), otherwise how far across and down it sits, so a\n * screen reader user places and hears the same pin. Pictures do not mirror\n * for right-to-left readers, so the pin and its arrow keys do not either.\n *\n * ## Anatomy\n *\n *   PinDrop                        (div — data-slot=\"pin-drop\", data-state=placing|placed|revealed)\n *     ├─ p                         (data-slot=\"pin-drop-prompt\")\n *     ├─ div role=\"group\"          (data-slot=\"pin-drop-pad\": the picture; tap or drag to move the pin)\n *     │   └─ button                (data-slot=\"pin-drop-pin\": named by its place, moved by arrow keys)\n *     ├─ div                       (data-slot=\"pin-drop-field\": after placing; pins, answer, line)\n *     ├─ p aria-hidden             (data-slot=\"pin-drop-legend\": you, the answer, the room)\n *     ├─ Button                    (data-slot=\"pin-drop-place\")\n *     ├─ span sr-only aria-live    (data-slot=\"pin-drop-announce\": the pin's place as it moves)\n *     └─ p tabIndex=-1 aria-live   (data-slot=\"pin-drop-result\")\n *\n *   PinMap                         (figure — data-slot=\"pin-map\")\n *     ├─ div                       (data-slot=\"pin-drop-field\")\n *     └─ figcaption                (data-slot=\"pin-map-summary\": \"24 pins. 5 on the spot.\")\n *\n * ## Motion\n *\n * A placed pin settles with a short drop (200ms, `ease-enter`). On the\n * reveal the answer scales in and the line to it fades in after (250ms),\n * so the eye goes from the answer to the gap. The room's pins fade in\n * together. Under reduced motion everything is simply there.\n *\n * ## MIN_VIEWPORT — 320\n *\n * | Rule | Concept                   | Where in this file                                   |\n * | ---- | ------------------------- | ---------------------------------------------------- |\n * | R4   | Extends native el         | `div` / `figure` props                               |\n * | R6   | data-slot per part        | pin-drop / -prompt / -pad / -pin / -field / -place / -announce / -result; pin-map / -summary |\n * | R7   | cn + ...rest              | `cn(…, className)` + `{...props}`                    |\n * | R8   | Enums, not booleans       | `size`                                               |\n * | R9   | Controlled + uncontrolled | `value` / `defaultValue` / `onPlace`                 |\n * | R14  | Declares min viewport     | `data-min-viewport` + exported const                 |\n * | R26  | A11y                      | pin named in words and moved by keys; result focused; field hidden, summary in text |\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  cleanPins,\n  nudgePin,\n  pinDistance,\n  pinPoints,\n  pinSpread,\n  regionOf,\n  type PinPoint,\n  type PinRegion,\n  type PinScoring,\n} from '@/components/ui/games/pin-drop-model';\n\nexport const MIN_VIEWPORT = 320 as const;\n\ninterface PinDropLabels {\n  /** @default 'Place my pin' */\n  place?: string;\n  /** A pin in words. @default region ? `In ${region}` : `${x}% across, ${y}% down` */\n  position?: (p: PinPoint, region: string | null) => string;\n  /** @default 'Tap the picture or use the arrow keys to move your pin.' */\n  hint?: string;\n  /** Placed, with no answer. @default (where, n) => `Placed: ${where}. ${n} pins so far.` */\n  placed?: (where: string, count: number, formatted: string) => string;\n  /** Placed, waiting for the reveal. @default 'Placed. Waiting for the answer.' */\n  waiting?: string;\n  /** On the reveal. `answer` is the answer's place in words. @default English: 'It was in {region}. You were on the spot. +{points} points.' */\n  revealed?: (r: {\n    answer: string;\n    region: string | null;\n    distance: number;\n    onSpot: boolean;\n    points: string;\n  }) => string;\n  /** The screen's summary. @default (n, onSpot) => `${n} pins.` + (onSpot === null ? '' : ` ${onSpot} on the spot.`) */\n  summary?: (count: string, onSpot: string | null) => string;\n  /** Names the answer marker. @default 'The answer' */\n  answer?: string;\n  /** The legend for the viewer's pin. @default 'You' */\n  you?: string;\n  /** The legend for everyone else's pins. @default 'The room' */\n  room?: string;\n}\n\nconst POSITION: NonNullable<PinDropLabels['position']> = (p, region) =>\n  region ? `In ${region}` : `${Math.round(p.x)}% across, ${Math.round(p.y)}% down`;\n\nconst REVEALED: NonNullable<PinDropLabels['revealed']> = ({ answer, region, distance, onSpot, points }) =>\n  (region ? `It was in ${region}. ` : `It was at ${answer}. `) +\n  (onSpot ? 'You were on the spot.' : `You were ${Math.round(distance)}% of the picture away.`) +\n  ` +${points} points.`;\n\nconst SUMMARY: NonNullable<PinDropLabels['summary']> = (count, onSpot) =>\n  `${count} ${count === '1' ? 'pin' : 'pins'}.` + (onSpot === null ? '' : ` ${onSpot} on the spot.`);\n\nconst at = (p: PinPoint): React.CSSProperties => ({ left: `${p.x}%`, top: `${p.y}%` });\nconst MARK = 'absolute -translate-x-1/2 -translate-y-1/2';\n\n// --- The picture with pins (shared by the phone, after placing, and the screen) -----\n\ninterface FieldProps {\n  src: string;\n  aspect: number;\n  pins: readonly PinPoint[];\n  mine?: PinPoint | null;\n  answer?: PinPoint | null;\n  arrive: boolean;\n  stage?: boolean;\n  answerLabel: string;\n}\n\nfunction PinField({ src, aspect, pins, mine, answer, arrive, stage, answerLabel }: FieldProps) {\n  const ref = React.useRef<HTMLDivElement>(null);\n  const shownAnswer = React.useRef(answer ?? null);\n\n  // The room's pins fade in together when they first appear: on arrival, or on the reveal.\n  const hasPins = pins.length > 0;\n  React.useEffect(() => {\n    const root = ref.current;\n    if (!arrive || !hasPins || !root) return;\n    root.querySelectorAll<HTMLElement>('[data-slot=\"pin-drop-room\"]').forEach((el) => {\n      if (typeof el.animate === 'function') el.animate([{ opacity: 0 }, { opacity: 1 }], { duration: 250 });\n    });\n    // When pins first appear.\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [hasPins]);\n\n  React.useEffect(() => {\n    const first = shownAnswer.current;\n    shownAnswer.current = answer ?? null;\n    const root = ref.current;\n    if (!arrive || !answer || first || !root) return;\n    const mark = root.querySelector<HTMLElement>('[data-slot=\"pin-drop-answer\"]');\n    const line = root.querySelector<SVGElement>('[data-slot=\"pin-drop-gap\"]');\n    if (mark && typeof mark.animate === 'function') {\n      mark.animate([{ transform: 'translate(-50%, -50%) scale(0)' }, { transform: 'translate(-50%, -50%) scale(1)' }], {\n        duration: 200,\n        easing: motionEase(mark, 'enter'),\n      });\n    }\n    if (line && typeof line.animate === 'function') {\n      line.animate([{ opacity: 0 }, { opacity: 0 }, { opacity: 1 }], { duration: 450, easing: 'ease-out' });\n    }\n  }, [answer, arrive]);\n\n  return (\n    <div\n      ref={ref}\n      aria-hidden\n      data-slot=\"pin-drop-field\"\n      className=\"bg-muted relative w-full overflow-hidden rounded-lg border\"\n      style={{ aspectRatio: String(aspect) }}\n    >\n      <img src={src} alt=\"\" draggable={false} className=\"absolute inset-0 size-full object-cover select-none\" />\n      {pins.map((p, i) => (\n        <span\n          // Pins have no identity beyond their place in the list.\n          key={`pin-${i}`}\n          data-slot=\"pin-drop-room\"\n          className={cn(MARK, 'bg-background ring-foreground/70 rounded-full ring-1', stage ? 'size-3' : 'size-2')}\n          style={at(p)}\n        />\n      ))}\n      {mine && answer ? (\n        <svg\n          data-slot=\"pin-drop-gap\"\n          className=\"absolute inset-0 size-full\"\n          viewBox=\"0 0 100 100\"\n          preserveAspectRatio=\"none\"\n        >\n          <line\n            x1={mine.x}\n            y1={mine.y}\n            x2={answer.x}\n            y2={answer.y}\n            className=\"stroke-foreground\"\n            strokeWidth={2}\n            strokeDasharray=\"4 3\"\n            vectorEffect=\"non-scaling-stroke\"\n          />\n        </svg>\n      ) : null}\n      {mine ? (\n        <span\n          data-slot=\"pin-drop-mine\"\n          className={cn(MARK, 'bg-primary ring-background size-5 rounded-full shadow-sm ring-2')}\n          style={at(mine)}\n        />\n      ) : null}\n      {answer ? (\n        <span\n          data-slot=\"pin-drop-answer\"\n          title={answerLabel}\n          className={cn(\n            MARK,\n            'bg-success ring-background grid place-items-center rounded-full shadow-sm ring-2',\n            stage ? 'size-9' : 'size-7',\n          )}\n          style={at(answer)}\n        >\n          <span className=\"bg-background size-2.5 rounded-full\" />\n        </span>\n      ) : null}\n    </div>\n  );\n}\n\n// --- PinDrop (phone) -----------------------------------------------------------------\n\ntype PinDropProps = Omit<React.ComponentProps<'div'>, 'children' | 'defaultValue'> & {\n  prompt: React.ReactNode;\n  /** The picture. */\n  src: string;\n  /** The picture in words. It must not give the answer away. */\n  alt: string;\n  /** The picture's width / height. @default 4 / 3 */\n  aspect?: number;\n  /** Named parts of the picture, so a pin is said in words. */\n  regions?: readonly PinRegion[];\n  /** Everyone's pins, shown once the viewer has placed. */\n  pins?: readonly PinPoint[];\n  /** `pins` already hold this viewer's pin. @default false */\n  pinsIncludeOwn?: boolean;\n  /** Where it really is, for \"Where is it?\". Shown only once `revealed`. */\n  answer?: PinPoint | null;\n  revealed?: boolean;\n  /** How close pays what. */\n  scoring?: PinScoring;\n  /** The viewer's placed pin, controlled. null while placing. */\n  value?: PinPoint | null;\n  /** The viewer's placed pin, uncontrolled. */\n  defaultValue?: PinPoint | null;\n  /** Called once, when the viewer places. */\n  onPlace?: (pin: PinPoint) => void;\n  /** How far an arrow key moves the pin. Shift moves by 1. @default 5 */\n  step?: number;\n  locale?: string;\n  labels?: PinDropLabels;\n};\n\nfunction PinDrop({\n  prompt,\n  src,\n  alt,\n  aspect = 4 / 3,\n  regions,\n  pins = [],\n  pinsIncludeOwn = false,\n  answer = null,\n  revealed = false,\n  scoring,\n  value: valueProp,\n  defaultValue = null,\n  onPlace,\n  step = 5,\n  locale,\n  labels,\n  className,\n  ...props\n}: PinDropProps) {\n  const reduced = useReducedMotion();\n  const nf = React.useMemo(() => new Intl.NumberFormat(locale), [locale]);\n  const [own, setOwn] = React.useState<PinPoint | null>(defaultValue);\n  const placedRaw = valueProp === undefined ? own : valueProp;\n  const placed = placedRaw && cleanPins([placedRaw])[0] ? (cleanPins([placedRaw])[0] as PinPoint) : null;\n  const [draft, setDraft] = React.useState<PinPoint>({ 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 pinRef = React.useRef<HTMLButtonElement>(null);\n  const resultRef = React.useRef<HTMLParagraphElement>(null);\n  const dragging = React.useRef(false);\n  const k = Number.isFinite(aspect) && aspect > 0 ? aspect : 4 / 3;\n\n  const target = revealed && answer ? (cleanPins([answer])[0] ?? null) : null;\n  const state = placed === null ? 'placing' : target ? 'revealed' : 'placed';\n  const room = cleanPins(placed && !pinsIncludeOwn ? [...pins, placed] : pins);\n  const words = (p: PinPoint) => (labels?.position ?? POSITION)(p, regionOf(p, regions)?.label ?? null);\n  const shownState = React.useRef(state);\n\n  // Focus the sentence when it changes because of this viewer, or a reveal they are waiting on.\n  React.useEffect(() => {\n    const before = shownState.current;\n    shownState.current = state;\n    if (before === state || state === 'placing') return;\n    if (state === 'placed' && !placedHere) return;\n    const active = document.activeElement;\n    const root = resultRef.current?.parentElement;\n    if (!active || active === document.body || root?.contains(active)) resultRef.current?.focus();\n  }, [state, placedHere]);\n\n  // A placed pin settles with a short drop.\n  React.useEffect(() => {\n    if (!placedHere || reduced) return;\n    const mine = resultRef.current?.parentElement?.querySelector<HTMLElement>('[data-slot=\"pin-drop-mine\"]');\n    if (mine && typeof mine.animate === 'function') {\n      mine.animate(\n        [\n          { transform: 'translate(-50%, calc(-50% - 12px))', opacity: 0 },\n          { transform: 'translate(-50%, -50%)', opacity: 1 },\n        ],\n        { duration: 200, easing: motionEase(mine, 'enter') },\n      );\n    }\n  }, [placedHere, reduced]);\n\n  const move = (next: PinPoint) => {\n    setDraft(next);\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 x = Math.round(((e.clientX - box.left) / box.width) * 100);\n    const y = Math.round(((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  let result = '';\n  if (state === 'revealed' && placed && target) {\n    const distance = pinDistance(placed, target, k);\n    const exact = scoring?.exact ?? 3;\n    result = (labels?.revealed ?? REVEALED)({\n      answer: words(target),\n      region: regionOf(target, regions)?.label ?? null,\n      distance,\n      onSpot: distance <= exact,\n      points: nf.format(pinPoints(distance, scoring)),\n    });\n  } else if (state === 'placed' && placed) {\n    result = answer\n      ? (labels?.waiting ?? 'Placed. Waiting for the answer.')\n      : (\n          labels?.placed ??\n          ((w: string, n: number, f: string) => `Placed: ${w}. ${f} ${n === 1 ? 'pin' : 'pins'} so far.`)\n        )(words(placed), room.length, nf.format(room.length));\n  }\n\n  return (\n    <div\n      data-slot=\"pin-drop\"\n      data-state={state}\n      data-min-viewport={String(MIN_VIEWPORT)}\n      className={cn('grid max-w-144 gap-4', className)}\n      {...props}\n    >\n      <p id={promptId} data-slot=\"pin-drop-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=\"pin-drop-pad\"\n          className=\"bg-muted relative w-full cursor-crosshair touch-none overflow-hidden rounded-lg border select-none\"\n          style={{ aspectRatio: String(k) }}\n          onPointerDown={(e) => {\n            dragging.current = true;\n            e.currentTarget.setPointerCapture?.(e.pointerId);\n            fromPointer(e);\n            pinRef.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          <img src={src} alt={alt} draggable={false} className=\"absolute inset-0 size-full object-cover select-none\" />\n          <button\n            ref={pinRef}\n            type=\"button\"\n            data-slot=\"pin-drop-pin\"\n            aria-label={words(draft)}\n            aria-describedby={hintId}\n            onKeyDown={(e) => {\n              const next = nudgePin(draft, e.key, e.shiftKey ? 1 : step);\n              if (!next) return;\n              e.preventDefault();\n              move(next);\n            }}\n            className={cn(\n              MARK,\n              'bg-primary ring-background focus-visible:outline-ring size-6 rounded-full shadow-md 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 picture or use the arrow keys to move your pin.'}\n          </span>\n        </div>\n      ) : (\n        <PinField\n          src={src}\n          aspect={k}\n          pins={answer ? (target ? room : []) : room}\n          mine={placed}\n          answer={target}\n          arrive={!reduced}\n          answerLabel={labels?.answer ?? 'The answer'}\n        />\n      )}\n\n      {placed !== null ? (\n        <p\n          aria-hidden\n          data-slot=\"pin-drop-legend\"\n          className=\"text-muted-foreground flex flex-wrap gap-x-4 gap-y-1 text-xs\"\n        >\n          <span className=\"flex items-center gap-1.5\">\n            <span className=\"bg-primary size-3 rounded-full\" />\n            {labels?.you ?? 'You'}\n          </span>\n          {target ? (\n            <span className=\"flex items-center gap-1.5\">\n              <span className=\"bg-success grid size-3 place-items-center rounded-full\">\n                <span className=\"bg-background size-1 rounded-full\" />\n              </span>\n              {labels?.answer ?? 'The answer'}\n            </span>\n          ) : null}\n          {target || !answer ? (\n            <span className=\"flex items-center gap-1.5\">\n              <span className=\"bg-background ring-foreground/70 size-2 rounded-full ring-1\" />\n              {labels?.room ?? 'The room'}\n            </span>\n          ) : null}\n        </p>\n      ) : null}\n\n      {placed === null ? (\n        <Button data-slot=\"pin-drop-place\" size=\"lg\" className=\"justify-self-start\" onClick={place}>\n          {labels?.place ?? 'Place my pin'}\n        </Button>\n      ) : null}\n\n      <span data-slot=\"pin-drop-announce\" aria-live=\"polite\" className=\"sr-only\">\n        {placed === null ? announce : ''}\n      </span>\n      <p\n        ref={resultRef}\n        tabIndex={-1}\n        data-slot=\"pin-drop-result\"\n        aria-live=\"polite\"\n        className={cn(\n          'focus-visible:outline-ring rounded-sm outline-offset-4 empty:hidden focus-visible:outline-2',\n          state === 'revealed' ? 'text-base font-semibold' : 'text-sm',\n        )}\n      >\n        {result}\n      </p>\n    </div>\n  );\n}\nPinDrop.displayName = 'PinDrop';\n\n// --- PinMap (screen) ---------------------------------------------------------------\n\ntype PinMapProps = Omit<React.ComponentProps<'figure'>, 'children'> & {\n  src: string;\n  /** The picture's width / height. @default 4 / 3 */\n  aspect?: number;\n  pins: readonly PinPoint[];\n  answer?: PinPoint | null;\n  /** Show the answer and how many landed on the spot. */\n  revealed?: boolean;\n  /** Within this distance a pin counts as on the spot. @default 3 */\n  exact?: number;\n  /** `stage` for a shared screen. @default 'default' */\n  size?: 'default' | 'stage';\n  locale?: string;\n  labels?: Pick<PinDropLabels, 'summary' | 'answer'>;\n};\n\nfunction PinMap({\n  src,\n  aspect = 4 / 3,\n  pins,\n  answer = null,\n  revealed = false,\n  exact = 3,\n  size = 'default',\n  locale,\n  labels,\n  className,\n  ...props\n}: PinMapProps) {\n  const reduced = useReducedMotion();\n  const nf = React.useMemo(() => new Intl.NumberFormat(locale), [locale]);\n  const k = Number.isFinite(aspect) && aspect > 0 ? aspect : 4 / 3;\n  const target = revealed && answer ? (cleanPins([answer])[0] ?? null) : null;\n  const clean = cleanPins(pins);\n  const spread = pinSpread(clean, { answer: target, aspect: k, exact });\n  const stage = size === 'stage';\n  return (\n    <figure\n      data-slot=\"pin-map\"\n      data-state={target ? 'revealed' : 'open'}\n      data-min-viewport={String(MIN_VIEWPORT)}\n      className={cn('grid gap-3', className)}\n      {...props}\n    >\n      <PinField\n        src={src}\n        aspect={k}\n        pins={clean}\n        answer={target}\n        arrive={!reduced}\n        stage={stage}\n        answerLabel={labels?.answer ?? 'The answer'}\n      />\n      <figcaption\n        data-slot=\"pin-map-summary\"\n        aria-live=\"polite\"\n        className={cn('text-muted-foreground tabular-nums', stage ? 'text-xl' : 'text-sm')}\n      >\n        {(labels?.summary ?? SUMMARY)(nf.format(spread.count), target ? nf.format(spread.onSpot) : null)}\n      </figcaption>\n    </figure>\n  );\n}\nPinMap.displayName = 'PinMap';\n\nexport { PinDrop, PinMap };\nexport type { PinDropProps, PinMapProps, PinDropLabels };\n"
    },
    {
      "path": "registry/interlace-ui/games/pin-drop-model.ts",
      "target": "components/ui/games/pin-drop-model.ts",
      "type": "registry:ui",
      "content": "export interface PinPoint {\n  /** Percent across, 0 at the left edge. */\n  x: number;\n  /** Percent down, 0 at the top edge. */\n  y: number;\n}\n\n/** A named part of the picture, so a pin can be said in words. */\nexport interface PinRegion {\n  /** A place name that reads after \"in\", e.g. \"the harbour\". */\n  label: string;\n  /** Left, top, right, bottom, in percents. */\n  box: readonly [number, number, number, number];\n}\n\nexport interface PinScoring {\n  /** Points for a pin on the spot. @default 1000 */\n  max?: number;\n  /** Within this distance a pin counts as on the spot. @default 3 */\n  exact?: number;\n  /** At or past this distance a pin scores nothing. @default 40 */\n  radius?: number;\n}\n\nexport interface PinSpread {\n  count: number;\n  /** The middle pin, by median of each axis. Null with no pins. */\n  middle: PinPoint | null;\n  /** With an answer: the median distance from it, and how many landed within `exact`. */\n  medianDistance: number | null;\n  onSpot: number;\n}\n\nconst clamp = (n: number) => Math.min(100, Math.max(0, n));\n\nfunction finite(p: unknown): p is PinPoint {\n  const q = p as PinPoint | null;\n  return !!q && Number.isFinite(q.x) && Number.isFinite(q.y);\n}\n\n/** Pins that make sense, held to the picture. */\nexport function cleanPins(pins: readonly PinPoint[]): PinPoint[] {\n  return pins.filter(finite).map((p) => ({ x: clamp(p.x), y: clamp(p.y) }));\n}\n\n/** How far apart two pins are, in percents of the picture's width. */\nexport function pinDistance(a: PinPoint, b: PinPoint, aspect = 1): number {\n  const k = Number.isFinite(aspect) && aspect > 0 ? Math.min(100, Math.max(0.01, aspect)) : 1;\n  return Math.hypot(a.x - b.x, (a.y - b.y) / k);\n}\n\n/** Points for a pin this far from the answer: all of them on the spot, none past `radius`, a straight line between. */\nexport function pinPoints(distance: number, scoring: PinScoring = {}): number {\n  const { max: ceiling = 1000, exact = 3, radius = 40 } = scoring;\n  const max = Number.isFinite(ceiling) ? Math.max(0, ceiling) : 0;\n  if (!Number.isFinite(distance)) return 0;\n  if (distance <= exact) return Math.round(max);\n  if (distance >= radius || radius <= exact) return 0;\n  return Math.round(max * (1 - (distance - exact) / (radius - exact)));\n}\n\n/** The first region holding the pin, or null. */\nexport function regionOf(p: PinPoint, regions: readonly PinRegion[] = []): PinRegion | null {\n  return regions.find(({ box: [l, t, r, b] }) => p.x >= l && p.x <= r && p.y >= t && p.y <= b) ?? null;\n}\n\n/** A pin moved by a key: arrows by `step`, Home and End to the side edges, Page Up and Down to the top and bottom. */\nexport function nudgePin(p: PinPoint, key: string, step = 5): PinPoint | null {\n  switch (key) {\n    case 'ArrowRight':\n      return { x: clamp(p.x + step), y: p.y };\n    case 'ArrowLeft':\n      return { x: clamp(p.x - step), 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: 0 };\n    case 'PageDown':\n      return { x: p.x, y: 100 };\n    default:\n      return null;\n  }\n}\n\nfunction median(sorted: readonly number[]): number {\n  const mid = Math.floor(sorted.length / 2);\n  return sorted.length % 2 ? (sorted[mid] as number) : ((sorted[mid - 1] as number) + (sorted[mid] as number)) / 2;\n}\n\n/** Where the room put its pins, and, with an answer, how close it came. */\nexport function pinSpread(\n  pins: readonly PinPoint[],\n  options: { answer?: PinPoint | null; aspect?: number; exact?: number } = {},\n): PinSpread {\n  const { answer = null, aspect = 1, exact = 3 } = options;\n  const clean = cleanPins(pins);\n  if (clean.length === 0) return { count: 0, middle: null, medianDistance: null, onSpot: 0 };\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  const target = finite(answer) ? { x: clamp(answer.x), y: clamp(answer.y) } : null;\n  const ds = target ? clean.map((p) => pinDistance(p, target, aspect)).sort((a, b) => a - b) : [];\n  return {\n    count: clean.length,\n    middle: { x: median(xs), y: median(ys) },\n    medianDistance: target ? median(ds) : null,\n    onSpot: ds.filter((d) => d <= exact).length,\n  };\n}\n\n/**\n * @interlace/ui — pin-drop-model\n *\n * A pin on a picture: a map, a floor plan, a diagram, a photo. Two games\n * use it. \"Where is it?\" has an answer, and a pin scores by how close it\n * lands. \"Where are you?\" (or \"where would you go?\") has none, and the\n * room's pins are the result.\n *\n * Places are percents of the picture from its top-left corner, `x` across\n * and `y` down, so they mean the same spot on every screen whatever its\n * size. A picture does not mirror for right-to-left readers, so neither do\n * pins. Distances are measured in percents of the picture's width, with\n * `aspect` (width / height) correcting for a picture that is not square.\n */\n"
    }
  ],
  "meta": {
    "tier": "game",
    "client": true,
    "minViewport": 320,
    "loading": false,
    "version": "1.0.0",
    "since": "2.0.0"
  },
  "docs": "## @interlace/pin-drop\n\nInstalled to `components/ui/games/pin-drop.tsx`.\n\n```tsx\nimport { /* … */ } from '@/components/ui/games/pin-drop';\n```\n\nProps, a11y contract, live preview and source: https://ds.interlace.tools/c/pin-drop\n\nRequires the `@interlace/interlace-base` CSS baseline (installed automatically as a registry dependency). For the Interlace look, also add `@interlace/theme`."
}
