{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "queue-triage-ratchet",
  "title": "Queue Triage Ratchet",
  "description": "Card-triage queue driven by a literal one-way ratchet: deciding a card clicks a toothed rail forward one notch; undo means visibly lifting the pawl before the rail eases back.",
  "dependencies": [],
  "files": [
    {
      "path": "registry/core/queue-triage-ratchet/component.tsx",
      "content": "\"use client\";\n\n// PawlClick — a card-triage queue whose progress is a literal ratchet. Below\n// the flat (no-3D) card stack sits a horizontal SVG rack of sawtooth teeth\n// and a pawl. Deciding a card (archive or keep) fires the card out with a\n// spring, and the rack advances exactly one tooth-width under a fixed pawl\n// with a hard-stop ease — zero overshoot, sharp settle, unmistakably a click\n// that only goes one way. Undo is deliberately a different kind of gesture:\n// the pawl rotates up ~20deg and holds — visibly disengaging the mechanism —\n// before the rack is allowed to ease backward one tooth, slowly and with\n// visible effort, and only then does the pawl drop again. Undo always plays\n// the lift/hold/drop gesture on request (never a disabled dead end); it only\n// additionally restores a card and eases the rack when there is something in\n// history to restore.\n//\n// Cards are a listbox: the stack is role=\"listbox\" with roving\n// aria-activedescendant onto the top card (role=\"option\"). Left/Right arrows\n// or J/K triage (archive/keep), U or Cmd/Ctrl+Z undoes — every gesture also\n// has an on-screen button, nothing requires drag. A polite aria-live region\n// announces each outcome (\"Archived. 6 remaining. Press U to undo.\"). The\n// rack + pawl SVG is aria-hidden — purely decorative reinforcement of a\n// state that's already fully described in text.\n//\n// Reduced motion: card exit becomes a fast plain fade, the rack steps\n// instantly (no transition), and the pawl's lift/drop is an instant\n// attribute flip with no rotation tween — semantics (and the aria-live\n// announcements) are unchanged either way.\n//\n// Pure DOM/SVG/CSS, no canvas. Colors are CSS custom properties only:\n// --foreground for ink/ the engaged tooth, --border for resting teeth and\n// hairlines, --ns-muted for secondary text, --ns-accent for focus rings only.\n\nimport { useCallback, useEffect, useId, useMemo, useRef, useState } from \"react\";\n\nexport interface PawlClickCard {\n  id: string;\n  title: string;\n  subtitle?: string;\n  body?: string;\n}\n\nexport interface PawlClickProps {\n  /** Initial queue, top of stack first. Managed internally after mount. */\n  cards: PawlClickCard[];\n  /** Called with the card whenever it's archived. */\n  onArchive?: (card: PawlClickCard) => void;\n  /** Called with the card whenever it's kept. */\n  onKeep?: (card: PawlClickCard) => void;\n  /** Called with the card whenever an archive/keep is undone. */\n  onUndo?: (card: PawlClickCard) => void;\n  /** Called once the queue is fully drained. */\n  onEmpty?: () => void;\n  /** extra classes merged onto the rendered root element */\n  className?: string;\n}\n\ntype Decision = \"archived\" | \"kept\";\ntype Phase = \"idle\" | \"commit\" | \"undo-lift\" | \"undo-ease\";\n\ninterface HistoryEntry {\n  card: PawlClickCard;\n  decision: Decision;\n}\n\nconst TOOTH = 26; // px, tooth pitch\nconst RACK_PAD = 12; // px, left padding before the first tooth\nconst PAWL_X = RACK_PAD + 10; // px, fixed screen x the pawl tip engages at\n\nconst COMMIT_RACK_MS = 260; // hard-stop ease, zero overshoot\nconst COMMIT_EXIT_MS = 320; // card spring exit\nconst PAWL_FLEX_MS = 200; // brief flex-over-tooth on drop\n\nconst LIFT_MS = 240; // pawl rotates up and holds\nconst EASE_MS = 680; // slow, effortful rack ease backward\nconst EMPTY_HOLD_MS = 320; // lift-and-drop with nothing to undo\n\nconst RACK_EASE_FWD = \"cubic-bezier(0.16, 1, 0.3, 1)\"; // sharp settle, no overshoot\nconst RACK_EASE_BACK = \"cubic-bezier(0.65, 0, 0.35, 1)\"; // slow, labored\nconst CARD_EXIT_EASE = \"cubic-bezier(0.34, 1.56, 0.64, 1)\"; // spring-ish snap\n\nfunction useReducedMotion() {\n  const [reduced, setReduced] = useState(false);\n  useEffect(() => {\n    const mq = window.matchMedia(\"(prefers-reduced-motion: reduce)\");\n    setReduced(mq.matches);\n    const onChange = () => setReduced(mq.matches);\n    mq.addEventListener(\"change\", onChange);\n    return () => mq.removeEventListener(\"change\", onChange);\n  }, []);\n  return reduced;\n}\n\nexport function PawlClick({\n  cards,\n  onArchive,\n  onKeep,\n  onUndo,\n  onEmpty,\n  className = \"\",\n}: PawlClickProps) {\n  const uid = useId();\n  const reducedMotion = useReducedMotion();\n\n  const initialRef = useRef(cards);\n  const totalRef = useRef(Math.max(1, cards.length));\n  const teethCount = totalRef.current;\n\n  const [queue, setQueue] = useState<PawlClickCard[]>(initialRef.current);\n  const [history, setHistory] = useState<HistoryEntry[]>([]);\n  const [notch, setNotch] = useState(0);\n  const [phase, setPhase] = useState<Phase>(\"idle\");\n  const [exiting, setExiting] = useState<{ card: PawlClickCard; dir: \"left\" | \"right\" } | null>(\n    null,\n  );\n  const [announcement, setAnnouncement] = useState(\"\");\n  const [busy, setBusy] = useState(false); // gates Archive/Keep only\n\n  const timersRef = useRef<Set<ReturnType<typeof setTimeout>>>(new Set());\n  const undoBusyRef = useRef(false);\n  const emptyFiredRef = useRef(false);\n\n  const addTimer = useCallback((fn: () => void, ms: number) => {\n    const id = setTimeout(() => {\n      timersRef.current.delete(id);\n      fn();\n    }, ms);\n    timersRef.current.add(id);\n    return id;\n  }, []);\n\n  const clearAllTimers = useCallback(() => {\n    timersRef.current.forEach((id) => clearTimeout(id));\n    timersRef.current.clear();\n  }, []);\n\n  useEffect(() => clearAllTimers, [clearAllTimers]);\n\n  useEffect(() => {\n    if (queue.length === 0 && !emptyFiredRef.current) {\n      emptyFiredRef.current = true;\n      onEmpty?.();\n    } else if (queue.length > 0) {\n      emptyFiredRef.current = false;\n    }\n  }, [queue.length, onEmpty]);\n\n  const commit = useCallback(\n    (decision: Decision) => {\n      if (busy || queue.length === 0) return;\n      const card = queue[0];\n      const dir: \"left\" | \"right\" = decision === \"archived\" ? \"left\" : \"right\";\n\n      setBusy(true);\n      setPhase(\"commit\");\n      setExiting({ card, dir });\n      setQueue((q) => q.slice(1));\n      setHistory((h) => [...h, { card, decision }]);\n      setNotch((n) => Math.min(teethCount - 1, n + 1));\n\n      const remaining = queue.length - 1;\n      const label = decision === \"archived\" ? \"Archived\" : \"Kept\";\n      setAnnouncement(\n        remaining > 0\n          ? `${label}. ${remaining} remaining. Press U to undo.`\n          : `${label}. Queue clear. Press U to undo.`,\n      );\n\n      if (decision === \"archived\") onArchive?.(card);\n      else onKeep?.(card);\n\n      const exitMs = reducedMotion ? 120 : COMMIT_EXIT_MS;\n      const rackMs = reducedMotion ? 0 : COMMIT_RACK_MS + PAWL_FLEX_MS;\n      const settleMs = Math.max(exitMs, rackMs);\n\n      addTimer(() => {\n        setExiting(null);\n        setPhase(\"idle\");\n        setBusy(false);\n      }, settleMs);\n    },\n    [busy, queue, teethCount, reducedMotion, addTimer, onArchive, onKeep],\n  );\n\n  const undo = useCallback(() => {\n    if (undoBusyRef.current) return;\n    undoBusyRef.current = true;\n    // clearAllTimers cancels any pending commit-settle timer too — reconcile\n    // that lock immediately rather than leaving Archive/Keep dead forever if\n    // undo interrupts a still-animating commit.\n    clearAllTimers();\n    setBusy(false);\n    setExiting(null);\n    setPhase(\"undo-lift\");\n\n    // captured from this render's closure, not read back out of a state\n    // updater — updaters must stay pure (StrictMode invokes them twice),\n    // so every side effect below runs in a plain timer callback instead.\n    const entry = history[history.length - 1];\n    const queueLenAtClick = queue.length;\n\n    // The CSS transition duration is zeroed under reduced motion (an\n    // instant step, no tween) but the *state* still holds briefly either\n    // way — \"lifted\" has to be a real, observable moment, not motion.\n    const liftMs = reducedMotion ? 180 : LIFT_MS;\n    addTimer(() => {\n      if (!entry) {\n        setAnnouncement(\"Nothing to undo.\");\n        const holdMs = reducedMotion ? 150 : EMPTY_HOLD_MS;\n        addTimer(() => {\n          setPhase(\"idle\");\n          undoBusyRef.current = false;\n        }, holdMs);\n        return;\n      }\n      setPhase(\"undo-ease\");\n      setHistory((h) => h.slice(0, -1));\n      setQueue((q) => [entry.card, ...q]);\n      setNotch((n) => Math.max(0, n - 1));\n      onUndo?.(entry.card);\n      setAnnouncement(`Undone. ${entry.card.title} restored. ${queueLenAtClick + 1} remaining.`);\n      const easeMs = reducedMotion ? 220 : EASE_MS;\n      addTimer(() => {\n        setPhase(\"idle\");\n        undoBusyRef.current = false;\n      }, easeMs);\n    }, liftMs);\n  }, [history, queue, reducedMotion, addTimer, clearAllTimers, onUndo]);\n\n  const onKeyDown = useCallback(\n    (e: React.KeyboardEvent<HTMLDivElement>) => {\n      const key = e.key.toLowerCase();\n      if (key === \"arrowleft\" || key === \"j\") {\n        e.preventDefault();\n        commit(\"archived\");\n      } else if (key === \"arrowright\" || key === \"k\") {\n        e.preventDefault();\n        commit(\"kept\");\n      } else if (key === \"u\" || ((e.metaKey || e.ctrlKey) && key === \"z\")) {\n        e.preventDefault();\n        undo();\n      }\n    },\n    [commit, undo],\n  );\n\n  const engagedTooth = Math.min(notch, teethCount - 1);\n  const rackTranslate = PAWL_X - (engagedTooth * TOOTH + RACK_PAD);\n  const rackDuration = reducedMotion\n    ? 0\n    : phase === \"undo-ease\"\n      ? EASE_MS\n      : COMMIT_RACK_MS;\n  const rackEase = phase === \"undo-ease\" ? RACK_EASE_BACK : RACK_EASE_FWD;\n\n  const pawlLifted = phase === \"undo-lift\" || phase === \"undo-ease\";\n  const pawlAngle = pawlLifted ? -20 : 0;\n  const pawlDuration = reducedMotion ? 0 : phase === \"undo-ease\" ? 0 : LIFT_MS;\n\n  const teeth = useMemo(() => {\n    const out: { x: number; d: string }[] = [];\n    for (let i = 0; i < teethCount; i++) {\n      const x = RACK_PAD + i * TOOTH;\n      // asymmetric sawtooth: shallow climbing ramp, then a steep blocking\n      // face — the geometry itself reads \"this only turns one way\".\n      const d = `M ${x} 30 L ${x + TOOTH * 0.72} 8 L ${x + TOOTH} 8 L ${x + TOOTH} 30 Z`;\n      out.push({ x, d });\n    }\n    return out;\n  }, [teethCount]);\n\n  const rackWidth = RACK_PAD + teethCount * TOOTH + RACK_PAD;\n\n  const topCard = queue[0];\n  const stackVisible = queue.slice(0, 3);\n  const optionId = (id: string) => `${uid}-opt-${id}`;\n  const busyOrEmpty = busy || queue.length === 0;\n\n  return (\n    <div className={[\"mx-auto flex w-full max-w-md flex-col gap-5\", className].join(\" \")}>\n      <div\n        role=\"listbox\"\n        aria-label=\"Card triage queue\"\n        aria-activedescendant={topCard ? optionId(topCard.id) : undefined}\n        tabIndex={0}\n        onKeyDown={onKeyDown}\n        className=\"ns-pw-stack relative rounded-md focus:outline-none focus-visible:ring-2 focus-visible:ring-ns-accent focus-visible:ring-offset-2 focus-visible:ring-offset-background\"\n        style={{ height: 176 }}\n      >\n        {stackVisible\n          .slice()\n          .reverse()\n          .map((card, ri) => {\n            const i = stackVisible.length - 1 - ri;\n            const isTop = i === 0;\n            return (\n              <div\n                key={card.id}\n                id={optionId(card.id)}\n                role=\"option\"\n                aria-selected={isTop}\n                className=\"ns-pw-card absolute inset-x-0 top-0 flex flex-col gap-1.5 rounded-md border border-border bg-surface p-5 shadow-sm\"\n                style={{\n                  transform: `translateY(${i * 10}px) scale(${1 - i * 0.03})`,\n                  opacity: 1 - i * 0.22,\n                  zIndex: 10 - i,\n                }}\n              >\n                <h3 className=\"text-sm font-semibold text-foreground\">{card.title}</h3>\n                {card.subtitle && (\n                  <p className=\"text-xs text-ns-muted\">{card.subtitle}</p>\n                )}\n                {card.body && isTop && (\n                  <p className=\"mt-1 text-sm leading-relaxed text-foreground/90\">{card.body}</p>\n                )}\n              </div>\n            );\n          })}\n\n        {exiting && (\n          <div\n            aria-hidden\n            className=\"ns-pw-card ns-pw-exit absolute inset-x-0 top-0 flex flex-col gap-1.5 rounded-md border border-border bg-surface p-5 shadow-sm\"\n            data-dir={exiting.dir}\n            data-reduced={reducedMotion || undefined}\n            style={{ zIndex: 20 }}\n          >\n            <h3 className=\"text-sm font-semibold text-foreground\">{exiting.card.title}</h3>\n            {exiting.card.subtitle && (\n              <p className=\"text-xs text-ns-muted\">{exiting.card.subtitle}</p>\n            )}\n          </div>\n        )}\n\n        {!topCard && (\n          <div className=\"absolute inset-0 flex items-center justify-center rounded-md border border-dashed border-border\">\n            <p className=\"text-sm text-ns-muted\">Queue clear</p>\n          </div>\n        )}\n      </div>\n\n      {/* rack + pawl — decorative, fully described by the live region above */}\n      <div aria-hidden=\"true\" className=\"relative h-9 w-full\">\n        <div className=\"absolute inset-0 overflow-hidden rounded-sm border border-border bg-background\">\n          <svg\n            width={rackWidth}\n            height={38}\n            viewBox={`0 0 ${rackWidth} 38`}\n            className=\"absolute inset-y-0\"\n            style={{\n              transform: `translateX(${rackTranslate}px)`,\n              transitionProperty: \"transform\",\n              transitionDuration: `${rackDuration}ms`,\n              transitionTimingFunction: rackEase,\n            }}\n          >\n            {teeth.map((t, i) => (\n              <path\n                key={t.x}\n                d={t.d}\n                fill={i === engagedTooth ? \"var(--foreground)\" : \"none\"}\n                fillOpacity={i === engagedTooth ? 0.14 : 1}\n                stroke={i === engagedTooth ? \"var(--foreground)\" : \"var(--border)\"}\n                strokeWidth={i === engagedTooth ? 1.75 : 1.25}\n              />\n            ))}\n          </svg>\n        </div>\n\n        <svg\n          width={22}\n          height={26}\n          viewBox=\"0 0 22 26\"\n          className=\"pointer-events-none absolute -top-3\"\n          style={{\n            left: PAWL_X - 5,\n            transform: `rotate(${pawlAngle}deg)`,\n            transformOrigin: \"4px 5px\",\n            transitionProperty: \"transform\",\n            transitionDuration: `${pawlDuration}ms`,\n            transitionTimingFunction: \"cubic-bezier(0.34, 1.56, 0.64, 1)\",\n          }}\n        >\n          <path\n            d=\"M4 4 L4 15 Q4 19 9 19 L16 19\"\n            fill=\"none\"\n            stroke=\"var(--foreground)\"\n            strokeWidth={2.25}\n            strokeLinecap=\"round\"\n            strokeLinejoin=\"round\"\n          />\n          <circle cx={4} cy={4} r={2} fill=\"var(--foreground)\" />\n        </svg>\n\n        {/* Real (non-decorative, hit-testable) \"armed to reverse\" marker —\n            the pawl svg above is pointer-events-none and its stroke is thin\n            enough that a screenshot/gate hit-test at its own center can\n            land on empty space, so the gate's `expect` target is this\n            plain, normally-painted node instead, not the svg. */}\n        {pawlLifted && (\n          <div\n            data-pawl-lifted=\"true\"\n            aria-hidden=\"true\"\n            className=\"absolute h-2.5 w-2.5 rounded-full bg-foreground\"\n            style={{ left: PAWL_X - 6, top: -10 }}\n          />\n        )}\n      </div>\n\n      <div className=\"flex items-center gap-2\">\n        <button\n          type=\"button\"\n          onClick={() => commit(\"archived\")}\n          disabled={busyOrEmpty}\n          className=\"ns-pw-btn flex-1 rounded-sm border border-border bg-surface px-3 py-2 text-sm font-medium text-foreground transition-colors hover:enabled:border-ns-muted hover:enabled:bg-border/60 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ns-accent disabled:cursor-not-allowed disabled:opacity-45\"\n        >\n          Archive\n        </button>\n        <button\n          type=\"button\"\n          onClick={() => commit(\"kept\")}\n          disabled={busyOrEmpty}\n          className=\"ns-pw-btn flex-1 rounded-sm border border-border bg-surface px-3 py-2 text-sm font-medium text-foreground transition-colors hover:enabled:border-ns-muted hover:enabled:bg-border/60 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ns-accent disabled:cursor-not-allowed disabled:opacity-45\"\n        >\n          Keep\n        </button>\n        <button\n          type=\"button\"\n          data-pawl-undo\n          onClick={undo}\n          className=\"ns-pw-btn rounded-sm border border-border bg-surface px-3 py-2 text-sm font-medium text-ns-muted transition-colors hover:border-ns-muted hover:bg-border/60 hover:text-foreground focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ns-accent\"\n        >\n          Undo\n        </button>\n      </div>\n\n      <p className=\"text-xs text-ns-muted\">\n        Left/Right or J/K to triage, U (or Cmd/Ctrl+Z) to undo — undo lifts the pawl before the\n        rack eases back.\n      </p>\n\n      <div role=\"status\" aria-live=\"polite\" className=\"sr-only\">\n        {announcement}\n      </div>\n\n      <style>{`\n        .ns-pw-card {\n          transition: transform 260ms ${CARD_EXIT_EASE}, opacity 260ms ease;\n        }\n        .ns-pw-exit[data-dir=\"left\"] {\n          animation: ns-pw-exit-left ${COMMIT_EXIT_MS}ms ${CARD_EXIT_EASE} both;\n        }\n        .ns-pw-exit[data-dir=\"right\"] {\n          animation: ns-pw-exit-right ${COMMIT_EXIT_MS}ms ${CARD_EXIT_EASE} both;\n        }\n        @keyframes ns-pw-exit-left {\n          to { transform: translateX(-135%) rotate(-8deg); opacity: 0; }\n        }\n        @keyframes ns-pw-exit-right {\n          to { transform: translateX(135%) rotate(8deg); opacity: 0; }\n        }\n        .ns-pw-exit[data-reduced][data-dir] {\n          animation: ns-pw-exit-fade 120ms ease both;\n        }\n        @keyframes ns-pw-exit-fade {\n          to { opacity: 0; }\n        }\n      `}</style>\n    </div>\n  );\n}\n",
      "type": "registry:ui",
      "target": "components/ui/queue-triage-ratchet.tsx"
    }
  ],
  "cssVars": {
    "theme": {
      "color-ns-muted": "var(--ns-muted)",
      "color-ns-accent": "var(--ns-accent)",
      "color-surface": "var(--surface)"
    },
    "light": {
      "ns-muted": "#4d4d4d",
      "ns-accent": "#006bff",
      "surface": "#fafafa"
    },
    "dark": {
      "ns-muted": "#8f8f8f",
      "surface": "#171717"
    }
  },
  "meta": {
    "collection": "core",
    "tags": [
      "queue",
      "triage",
      "ratchet",
      "undo",
      "listbox",
      "keyboard",
      "card-stack",
      "irreversibility",
      "aria-live"
    ],
    "instruction": "A card-triage queue for decision flows (inbox triage, review/approve, flashcards) where progress should feel earned rather than ambient. Cards sit in a flat, stacked layout — no 3D tilt, just a shallow translateY/scale/opacity falloff for the two cards behind the top one — inside a role=listbox with roving aria-activedescendant onto the top card (role=option, aria-selected on the top). Beneath the stack sits a horizontal SVG rack: an asymmetric sawtooth strip (shallow climbing ramp, steep blocking face — the geometry alone reads 'this only turns one way'), teeth stroked in --border, with a fixed pawl (a small hooked SVG path) engaging the current tooth from above; the engaged tooth's stroke switches to --foreground with a faint --foreground fill so progress is legible even as a static screenshot. Deciding a card — Archive or Keep, via on-screen buttons, Left/Right arrows, or J/K — fires the card off-stage with a spring-ish snap (cubic-bezier(0.34,1.56,0.64,1), translateX + slight rotate + fade) while the rack itself translates exactly one tooth-width to bring the next tooth under the fixed pawl, on a hard-stop ease (cubic-bezier(0.16,1,0.3,1)) with zero overshoot and a sharp settle — a firm click-snap, not a glide. Undo (button, U, or Cmd/Ctrl+Z) is a deliberately different gesture: the pawl first rotates up about 20 degrees and holds — visibly disengaging from the tooth — and only once it's lifted does the rack ease backward one tooth, slowly and on a labored curve (cubic-bezier(0.65,0,0.35,1), ~2.5x the forward duration) before the pawl drops again; undo always plays this lift/hold/drop gesture when pressed (it is never a dead, disabled control) and additionally restores the archived/kept card to the top of the queue and eases the rack only when there is actually something in history — pressing it with nothing to undo still lifts and drops the pawl, honestly showing the mechanism finding nothing to release. Every outcome is spoken through a single polite aria-live status region ('Archived. 6 remaining. Press U to undo.' / 'Kept. 5 remaining. Press U to undo.' / 'Undone. <title> restored. 6 remaining.' / 'Nothing to undo.'), so the queue is fully legible without ever looking at the rack — the rack (including the pawl) is aria-hidden, a redundant reinforcing visual, not a source of information. Every gesture has a single-keystroke and a visible-button equivalent; nothing requires drag. Reduced motion: the card exit collapses to a fast plain opacity fade (no translate/rotate/spring), the rack's transform transition duration drops to 0 (steps instantly to its new tooth), and the pawl's rotation is an instant attribute flip with no tween — all the same state changes and the same aria-live announcements, just without the motion. Pure DOM/SVG/CSS, no canvas; every color is a CSS custom property (--foreground for ink and the engaged tooth, --border for resting teeth and hairlines, --ns-muted for secondary text, --ns-accent reserved for the keyboard focus ring only). Distinct from avatar-stack-flock (a milling boids avatar formation with no commit/undo semantics at all) and segmented-control-fling (an elastic drag-to-fling segmented control with no notion of irreversibility) — queue-triage-ratchet's whole point is the one-way mechanical grammar of teeth, pawl, and notch-advance; the card stack is just the cargo riding on top of it."
  },
  "type": "registry:ui"
}