{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"reactions","type":"registry:component","title":"Reactions","description":"Emoji reactions for comments and messages: press, slide along the tray and let go, and the emoji flies into its chip.","author":"Hairline UI","dependencies":[],"registryDependencies":["https://hairlineui.com/r/number-roll.json?as=dependency","https://hairlineui.com/r/text-morph.json?as=dependency"],"files":[{"path":"registry/reactions.tsx","type":"registry:component","content":"// Hairline UI · reactions · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n\"use client\";\n\nimport * as React from \"react\";\nimport { NumberRoll } from \"./number-roll\";\nimport { GLYPH, ReactionTray, TRAY_H, trayWidth, type ReactionChoice, type TrayHandle, type TrayPlacement } from \"./reactions-tray\";\nimport { EASE_OUT, EASE_THROW, INTERACTION_FOCUS, INTERACTION_PRESS, createSpring, useInteractionReducedMotion, type Spring } from \"./ui-interaction-motion\";\n\nexport type { ReactionChoice } from \"./reactions-tray\";\n\n/* ─────────────────────────────────────────────────────────\n * REACTIONS: the row under a comment or a message\n *\n *   pick     press the add button and drag along the tray without\n *            letting go: the emoji under the finger swells and its\n *            name glides above it; release to react. A tap opens\n *            the tray to click instead\n *   flight   the emoji you picked flies from the tray into its\n *            chip on springs, shrinking as it goes, and lands: the\n *            chip takes the weight, the count rolls up and a few\n *            copies spring out of it\n *   others   someone else's reaction bumps the chip and rolls the\n *            count; a new one opens its chip in place\n *   remove   pressing your own chip rolls the count down; at zero\n *            the emoji shrinks first and the gap closes after it\n *   fail     if onReact throws, the change is undone and the chip\n *            shakes\n *\n * Reduced motion: no swell, flight or burst; chips and counts change in place.\n * ───────────────────────────────────────────────────────── */\n\nexport interface Reaction {\n  emoji: string;\n  /** Everyone who reacted with it, you included. */\n  count: number;\n  /** You reacted with it. */\n  mine?: boolean;\n  /** Other people's names, for the tooltip; a count beyond them reads \"and N others\". */\n  people?: string[];\n}\n\nexport interface ReactionsHandle {\n  /** Plays the whole gesture for this emoji: the tray opens, the swell moves to it and it flies in (toggles it if yours). */\n  pick: (emoji: string) => void;\n}\n\nexport interface ReactionsProps {\n  value?: Reaction[];\n  defaultValue?: Reaction[];\n  onValueChange?: (value: Reaction[]) => void;\n  /** Save it. Called after the row has already changed; throw to undo the change. */\n  onReact?: (emoji: string, on: boolean) => Promise<unknown> | unknown;\n  /** The emoji in the tray, in order. */\n  choices?: ReactionChoice[];\n  /** The add button's name. */\n  label?: string;\n  className?: string;\n  ref?: React.Ref<ReactionsHandle>;\n}\n\nexport const DEFAULT_REACTION_CHOICES: ReactionChoice[] = [\n  { emoji: \"👍\", label: \"Thumbs up\" },\n  { emoji: \"❤️\", label: \"Love\" },\n  { emoji: \"😂\", label: \"Funny\" },\n  { emoji: \"🎉\", label: \"Celebrate\" },\n  { emoji: \"😮\", label: \"Surprised\" },\n  { emoji: \"🙏\", label: \"Thanks\" },\n  { emoji: \"👀\", label: \"Looking\" },\n];\n\nconst CHIP_GLYPH = 16;\nconst NONE: Reaction[] = [];\nconst ROLL_FORMAT: Intl.NumberFormatOptions = { maximumFractionDigits: 0 };\n// The flight: across a little faster than down, so the path bends instead of running straight. No overshoot, it's seen often.\nconst FLY_X = { stiffness: 360, damping: 36 };\nconst FLY_Y = { stiffness: 280, damping: 33 };\nconst FLY_S = { stiffness: 320, damping: 34 };\n// A chip that takes a weight dips and comes back once.\nconst GIVE = { stiffness: 640, damping: 30 };\n\nfunction toggle(list: Reaction[], emoji: string, on: boolean): Reaction[] {\n  const i = list.findIndex((r) => r.emoji === emoji);\n  if (i < 0) return on ? [...list, { emoji, count: 1, mine: true }] : list;\n  const r = list[i];\n  if (Boolean(r.mine) === on) return list;\n  const next = list.slice();\n  next[i] = { ...r, count: Math.max(0, r.count + (on ? 1 : -1)), mine: on };\n  return next;\n}\n\nfunction who(r: Reaction, label: string) {\n  const others = Math.max(0, r.count - (r.mine ? 1 : 0));\n  const named = (r.people ?? []).slice(0, others);\n  const names = [...(r.mine ? [\"You\"] : []), ...named.slice(0, r.mine ? 2 : 3)];\n  const rest = r.count - names.length;\n  if (!names.length) return `${r.count} ${r.count === 1 ? \"person\" : \"people\"} reacted with ${label}`;\n  const list = rest > 0 ? `${names.join(\", \")} and ${rest} ${rest === 1 ? \"other\" : \"others\"}` : names.length > 1 ? `${names.slice(0, -1).join(\", \")} and ${names.at(-1)}` : names[0];\n  return `${list} reacted with ${label}`;\n}\n\ninterface ChipApi {\n  slot: () => HTMLElement | null;\n  land: () => void;\n  shake: () => void;\n}\n\ninterface ChipProps {\n  reaction: Reaction;\n  label: string;\n  leaving: boolean;\n  animateIn: boolean;\n  awaiting: boolean;\n  quiet: boolean;\n  reduced: boolean;\n  register: (emoji: string, api: ChipApi | null) => void;\n  onToggle: (emoji: string) => void;\n}\n\nconst Chip = React.memo(function Chip({ reaction, label, leaving, animateIn, awaiting, quiet, reduced, register, onToggle }: ChipProps) {\n  const { emoji, count, mine = false } = reaction;\n  const [open, setOpen] = React.useState(() => !animateIn);\n  const button = React.useRef<HTMLButtonElement>(null);\n  const glyph = React.useRef<HTMLSpanElement>(null);\n  const give = React.useRef<Spring | null>(null);\n  const lastCount = React.useRef(count);\n  const tipId = React.useId();\n  const shown = open && !leaving;\n\n  React.useEffect(() => {\n    if (open || leaving) return;\n    let second = 0;\n    const first = requestAnimationFrame(() => {\n      second = requestAnimationFrame(() => setOpen(true));\n    });\n    return () => {\n      cancelAnimationFrame(first);\n      cancelAnimationFrame(second);\n    };\n  }, [open, leaving]);\n\n  React.useLayoutEffect(() => {\n    const paint = () => {\n      const v = give.current?.get() ?? 1;\n      if (button.current) button.current.style.transform = v === 1 ? \"\" : `scale(${v.toFixed(4)})`;\n      // The chip sinks under the weight while the emoji on it pops: one spring, two readings.\n      if (glyph.current) glyph.current.style.transform = v === 1 ? \"\" : `scale(${(1 + (1 - v) * 2.6).toFixed(4)})`;\n    };\n    const spring = createSpring(1, GIVE, paint, 0.0005);\n    give.current = spring;\n    const api: ChipApi = {\n      slot: () => glyph.current,\n      land: () => !reduced && spring.push(-2.6),\n      shake: () => {\n        if (reduced) return;\n        button.current?.animate([{ translate: \"0\" }, { translate: \"-4px\" }, { translate: \"4px\" }, { translate: \"-3px\" }, { translate: \"2px\" }, { translate: \"0\" }], { duration: 380, easing: \"ease-out\" });\n      },\n    };\n    register(emoji, api);\n    return () => {\n      spring.stop();\n      give.current = null;\n      register(emoji, null);\n    };\n  }, [emoji, reduced, register]);\n\n  // Someone else's reaction bumps it gently; yours lands with a heavier one when its flight arrives.\n  React.useEffect(() => {\n    const before = lastCount.current;\n    lastCount.current = count;\n    if (count > before && !awaiting && !reduced) give.current?.push(-1.4);\n  }, [count, awaiting, reduced]);\n\n  return (\n    <span\n      className=\"group/chip relative inline-grid\"\n      style={{\n        gridTemplateColumns: shown ? \"1fr\" : \"0fr\",\n        opacity: shown ? 1 : 0,\n        transition: reduced ? \"none\" : `grid-template-columns 340ms ${EASE_OUT} ${leaving ? \"110ms\" : \"0ms\"}, opacity ${shown ? \"220ms\" : \"180ms\"} ${EASE_OUT}`,\n      }}\n    >\n      <span className=\"min-w-0 [clip-path:inset(-8px_-3px)]\">\n        <span className=\"flex w-max py-0.5 pr-1.5\">\n          <button\n            ref={button}\n            type=\"button\"\n            aria-pressed={mine}\n            aria-label={`${label}, ${count} ${count === 1 ? \"reaction\" : \"reactions\"}${mine ? \", including yours\" : \"\"}`}\n            aria-describedby={tipId}\n            tabIndex={leaving ? -1 : undefined}\n            onClick={() => onToggle(emoji)}\n            className={`inline-flex h-8 cursor-pointer select-none items-center gap-1.5 rounded-full pl-2 pr-2.5 text-[13px] font-medium tabular-nums will-change-transform ${INTERACTION_PRESS} ${INTERACTION_FOCUS} ${\n              mine\n                ? \"bg-[color-mix(in_oklab,var(--foreground)_11%,var(--background))] text-foreground hover:bg-[color-mix(in_oklab,var(--foreground)_15%,var(--background))]\"\n                : \"bg-background text-muted-foreground shadow-[inset_0_0_0_1px_var(--border)] hover:bg-accent hover:text-foreground\"\n            }`}\n          >\n            <span\n              ref={glyph}\n              aria-hidden=\"true\"\n              className=\"block leading-none\"\n              style={{\n                fontSize: CHIP_GLYPH,\n                opacity: awaiting ? 0 : 1,\n                scale: shown ? 1 : 0.4,\n                transition: reduced ? \"none\" : `scale 420ms ${EASE_THROW}`,\n              }}\n            >\n              {emoji}\n            </span>\n            <NumberRoll value={count} format={ROLL_FORMAT} duration={620} aria-hidden=\"true\" />\n          </button>\n        </span>\n      </span>\n      <span\n        id={tipId}\n        role=\"tooltip\"\n        className={`pointer-events-none absolute bottom-full left-[calc(50%_-_3px)] z-10 mb-1 whitespace-nowrap rounded-[10px] bg-popover px-2 py-1 text-[12px] leading-[16px] text-popover-foreground opacity-0 shadow-[0_0_0_1px_var(--border)] transition-[opacity,translate] delay-0 duration-200 ease-[cubic-bezier(0.16,1,0.3,1)] [translate:-50%_4px] motion-reduce:transition-none ${\n          quiet || leaving ? \"\" : \"group-hover/chip:opacity-100 group-hover/chip:delay-300 group-hover/chip:[translate:-50%_0] group-has-[:focus-visible]/chip:opacity-100 group-has-[:focus-visible]/chip:[translate:-50%_0]\"\n        }`}\n      >\n        {who(reaction, label)}\n      </span>\n    </span>\n  );\n});\n\nfunction SmilePlus({ open, reduced }: { open: boolean; reduced: boolean }) {\n  const mouth = React.useRef<SVGPathElement>(null);\n  const plus = React.useRef<SVGGElement>(null);\n  const spring = React.useRef<Spring | null>(null);\n\n  React.useLayoutEffect(() => {\n    // A rig, not a swap: the mouth widens into a grin and the plus turns into a close mark, from one value.\n    const paint = () => {\n      const g = spring.current?.get() ?? 0;\n      mouth.current?.setAttribute(\"d\", `M${(7.7 - 0.5 * g).toFixed(2)} 14.6Q11 ${(17.6 + 1.8 * g).toFixed(2)} ${(14.3 + 0.5 * g).toFixed(2)} 14.6`);\n      plus.current?.setAttribute(\"transform\", `rotate(${(45 * g).toFixed(2)} 19 5)`);\n    };\n    spring.current = createSpring(0, { stiffness: 420, damping: 30 }, paint, 0.002);\n    paint();\n    return () => spring.current?.stop();\n  }, []);\n\n  React.useEffect(() => {\n    if (reduced) spring.current?.jump(open ? 1 : 0);\n    else spring.current?.set(open ? 1 : 0);\n  }, [open, reduced]);\n\n  return (\n    <svg viewBox=\"0 0 24 24\" aria-hidden=\"true\" className=\"size-[18px] overflow-visible\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.6\" strokeLinecap=\"round\">\n      <path d=\"M17.6 10.6A7.6 7.6 0 1 1 13.4 6\" />\n      <circle cx=\"8.4\" cy=\"11.4\" r=\"0.95\" fill=\"currentColor\" stroke=\"none\" />\n      <circle cx=\"13.6\" cy=\"11.4\" r=\"0.95\" fill=\"currentColor\" stroke=\"none\" />\n      <path ref={mouth} d=\"M7.7 14.6Q11 17.6 14.3 14.6\" />\n      <g ref={plus}>\n        <path d=\"M19 2.4v5.2M16.4 5h5.2\" />\n      </g>\n    </svg>\n  );\n}\n\ntype Phase = \"closed\" | \"open\" | \"closing\";\ntype Flight = { id: number; emoji: string; from: { x: number; y: number; s: number } };\ntype Press = { id: number; x: number; y: number; dragging: boolean; wasOpen: boolean; rootX: number; rootY: number };\n\nexport function Reactions({\n  value,\n  defaultValue = NONE,\n  onValueChange,\n  onReact,\n  choices = DEFAULT_REACTION_CHOICES,\n  label = \"Add reaction\",\n  className = \"\",\n  ref,\n}: ReactionsProps) {\n  const reduced = useInteractionReducedMotion();\n  const [internal, setInternal] = React.useState(defaultValue);\n  const raw = value ?? internal;\n  const list = React.useMemo(() => raw.filter((r) => r.count > 0), [raw]);\n\n  // Chips that just left stay a moment, so they can shrink away where they stood.\n  const [prevList, setPrevList] = React.useState(list);\n  const [ghosts, setGhosts] = React.useState<{ reaction: Reaction; index: number }[]>([]);\n  if (prevList !== list) {\n    setPrevList(list);\n    const gone = prevList.flatMap((reaction, index) => (list.some((r) => r.emoji === reaction.emoji) ? [] : [{ reaction, index }]));\n    setGhosts((current) => [...current.filter((g) => !list.some((r) => r.emoji === g.reaction.emoji) && !gone.some((n) => n.reaction.emoji === g.reaction.emoji)), ...gone]);\n  }\n  React.useEffect(() => {\n    if (!ghosts.length) return;\n    const timer = window.setTimeout(() => setGhosts([]), 520);\n    return () => window.clearTimeout(timer);\n  }, [ghosts]);\n\n  const rows = React.useMemo(() => {\n    const out = list.map((reaction) => ({ reaction, leaving: false }));\n    [...ghosts].sort((a, b) => a.index - b.index).forEach((g) => out.splice(Math.min(g.index, out.length), 0, { reaction: g.reaction, leaving: true }));\n    return out;\n  }, [list, ghosts]);\n\n  const mine = React.useMemo(() => new Set(list.filter((r) => r.mine).map((r) => r.emoji)), [list]);\n  const labelOf = React.useCallback((emoji: string) => choices.find((c) => c.emoji === emoji)?.label ?? emoji, [choices]);\n\n  const [phase, setPhase] = React.useState<Phase>(\"closed\");\n  const [place, setPlace] = React.useState<TrayPlacement | null>(null);\n  const [focusTray, setFocusTray] = React.useState(false);\n  const [flight, setFlight] = React.useState<Flight | null>(null);\n  const [ready, setReady] = React.useState(false);\n  const [said, setSaid] = React.useState(\"\");\n\n  const root = React.useRef<HTMLDivElement>(null);\n  const trigger = React.useRef<HTMLButtonElement>(null);\n  const tray = React.useRef<TrayHandle>(null);\n  const flyer = React.useRef<HTMLSpanElement>(null);\n  const sparks = React.useRef<HTMLSpanElement>(null);\n  const chips = React.useRef(new Map<string, ChipApi>());\n  const press = React.useRef<Press | null>(null);\n  const auto = React.useRef<number[]>([]);\n  const flights = React.useRef(0);\n  const trayId = React.useId();\n\n  // The latest state, for handlers and timers that outlive a render.\n  const latest = React.useRef({ list, phase, choices, reduced, onReact, onValueChange, controlled: value !== undefined });\n  React.useLayoutEffect(() => {\n    latest.current = { list, phase, choices, reduced, onReact, onValueChange, controlled: value !== undefined };\n  });\n\n  React.useEffect(() => {\n    const frame = requestAnimationFrame(() => setReady(true));\n    return () => cancelAnimationFrame(frame);\n  }, []);\n\n  React.useEffect(\n    () => () => {\n      auto.current.forEach(window.clearTimeout);\n    },\n    [],\n  );\n\n  const register = React.useCallback((emoji: string, api: ChipApi | null) => {\n    if (api) chips.current.set(emoji, api);\n    else chips.current.delete(emoji);\n  }, []);\n\n  const burst = React.useCallback((emoji: string, x: number, y: number) => {\n    const layer = sparks.current;\n    if (!layer || latest.current.reduced || layer.childElementCount > 12) return;\n    for (let k = 0; k < 5; k++) {\n      const el = document.createElement(\"span\");\n      el.textContent = emoji;\n      el.style.cssText = \"position:absolute;left:0;top:0;font-size:12px;line-height:1;will-change:transform;pointer-events:none\";\n      layer.appendChild(el);\n      const angle = -Math.PI / 2 + (k - 2) * 0.48 + (Math.random() - 0.5) * 0.3;\n      const speed = 150 + Math.random() * 70;\n      const vx = Math.cos(angle) * speed;\n      const vy = Math.sin(angle) * speed;\n      const spin = (Math.random() - 0.5) * 120;\n      const life = 0.6 + Math.random() * 0.12;\n      // A thrown thing under gravity, sampled into keyframes so the compositor runs it.\n      const frames = Array.from({ length: 13 }, (_, f) => {\n        const p = f / 12;\n        const t = p * life;\n        const px = x - 6 + vx * t;\n        const py = y - 6 + vy * t + 0.5 * 560 * t * t;\n        return { transform: `translate3d(${px.toFixed(1)}px, ${py.toFixed(1)}px, 0) rotate(${(spin * t).toFixed(1)}deg) scale(${f === 0 ? 0.4 : 1 - p * 0.25})`, opacity: p < 0.5 ? 1 : 1 - (p - 0.5) * 2, offset: p };\n      });\n      const run = el.animate(frames, { duration: life * 1000, easing: \"linear\", fill: \"forwards\" });\n      run.finished.then(\n        () => el.remove(),\n        () => el.remove(),\n      );\n    }\n  }, []);\n\n  const centre = React.useCallback((el: HTMLElement) => {\n    const r = root.current!.getBoundingClientRect();\n    const b = el.getBoundingClientRect();\n    return { x: b.left - r.left + b.width / 2, y: b.top - r.top + b.height / 2 };\n  }, []);\n\n  const commit = React.useCallback((next: Reaction[]) => {\n    const l = latest.current;\n    l.list = next;\n    if (!l.controlled) setInternal(next);\n    l.onValueChange?.(next);\n  }, []);\n\n  const react = React.useCallback(\n    async (emoji: string, on: boolean, from?: Flight[\"from\"]) => {\n      const l = latest.current;\n      commit(toggle(l.list, emoji, on));\n      const name = l.choices.find((c) => c.emoji === emoji)?.label ?? emoji;\n      setSaid(on ? `You reacted with ${name}` : `Removed your ${name} reaction`);\n      if (on && from && !l.reduced) setFlight({ id: ++flights.current, emoji, from });\n      else if (on && !l.reduced) {\n        const slot = chips.current.get(emoji)?.slot();\n        if (slot) {\n          const c = centre(slot);\n          burst(emoji, c.x, c.y);\n        }\n      }\n      try {\n        await l.onReact?.(emoji, on);\n      } catch {\n        commit(toggle(latest.current.list, emoji, !on));\n        setSaid(on ? `Couldn't add ${name}` : `Couldn't remove ${name}`);\n        // The chip is gone if the undo emptied it; then the add button shakes for it.\n        const chip = chips.current.get(emoji);\n        if (chip && latest.current.list.some((r) => r.emoji === emoji)) chip.shake();\n        else if (!latest.current.reduced) trigger.current?.animate([{ translate: \"0\" }, { translate: \"-4px\" }, { translate: \"4px\" }, { translate: \"-3px\" }, { translate: \"0\" }], { duration: 380, easing: \"ease-out\" });\n      }\n    },\n    [burst, centre, commit],\n  );\n\n  const openTray = React.useCallback((keyboard: boolean) => {\n    const r = root.current;\n    const t = trigger.current;\n    if (!r || !t) return;\n    const count = latest.current.choices.length;\n    const width = trayWidth(count);\n    const box = r.getBoundingClientRect();\n    const cx = t.offsetLeft + t.offsetWidth / 2;\n    // Stay inside the screen and inside whatever clips the row (a scrolling thread, a card with overflow hidden).\n    let minX = 0;\n    let maxX = document.documentElement.clientWidth;\n    let minY = 0;\n    for (let el = r.parentElement; el && el !== document.body; el = el.parentElement) {\n      const style = getComputedStyle(el);\n      if (style.overflowX === \"visible\" && style.overflowY === \"visible\") continue;\n      const clip = el.getBoundingClientRect();\n      minX = Math.max(minX, clip.left);\n      maxX = Math.min(maxX, clip.right);\n      minY = Math.max(minY, clip.top);\n    }\n    let left = cx - width / 2;\n    left = Math.min(left, maxX - 8 - box.left - width);\n    left = Math.max(left, minX + 8 - box.left);\n    const above = box.top + t.offsetTop - TRAY_H - 10 > minY + 8;\n    const top = above ? t.offsetTop - TRAY_H - 6 : t.offsetTop + t.offsetHeight + 6;\n    setPlace({ left, top, side: above ? \"top\" : \"bottom\", originX: cx - left, originY: above ? TRAY_H + 6 + t.offsetHeight / 2 : -6 - t.offsetHeight / 2 });\n    setFocusTray(keyboard);\n    setPhase(\"open\");\n  }, []);\n\n  const closeTray = React.useCallback((returnFocus: boolean) => {\n    if (latest.current.phase === \"closed\") return;\n    setPhase(\"closing\");\n    if (returnFocus) trigger.current?.focus({ preventScroll: true });\n  }, []);\n\n  const pickIndex = React.useCallback(\n    (index: number, keyboard: boolean) => {\n      const choice = latest.current.choices[index];\n      if (!choice) return;\n      const on = !latest.current.list.some((r) => r.emoji === choice.emoji && r.mine);\n      const from = tray.current?.origin(index);\n      closeTray(keyboard);\n      void react(choice.emoji, on, from);\n    },\n    [closeTray, react],\n  );\n\n  const stopAuto = React.useCallback(() => {\n    auto.current.forEach(window.clearTimeout);\n    auto.current = [];\n  }, []);\n\n  React.useImperativeHandle(\n    ref,\n    () => ({\n      pick(emoji) {\n        stopAuto();\n        const index = latest.current.choices.findIndex((c) => c.emoji === emoji);\n        if (index < 0) return;\n        if (latest.current.reduced) {\n          void react(emoji, !latest.current.list.some((r) => r.emoji === emoji && r.mine));\n          return;\n        }\n        if (latest.current.phase !== \"open\") openTray(false);\n        let at = 300;\n        for (let k = 0; k <= index; k++) {\n          auto.current.push(window.setTimeout(() => tray.current?.setActive(k), at));\n          at += 120;\n        }\n        auto.current.push(window.setTimeout(() => pickIndex(index, false), at + 320));\n      },\n    }),\n    [openTray, pickIndex, react, stopAuto],\n  );\n\n  // A press outside closes the tray.\n  React.useEffect(() => {\n    if (phase !== \"open\") return;\n    const away = (event: PointerEvent) => {\n      if (!root.current?.contains(event.target as Node)) closeTray(false);\n    };\n    document.addEventListener(\"pointerdown\", away);\n    return () => document.removeEventListener(\"pointerdown\", away);\n  }, [phase, closeTray]);\n\n  // The flight: springs from where the emoji is drawn in the tray to its slot in the chip, then the landing.\n  React.useLayoutEffect(() => {\n    if (!flight) return;\n    const el = flyer.current;\n    const slot = chips.current.get(flight.emoji)?.slot();\n    let landed = false;\n    const land = () => {\n      if (landed) return;\n      landed = true;\n      if (el) el.style.visibility = \"hidden\";\n      setFlight((f) => (f?.id === flight.id ? null : f));\n    };\n    if (!el || !slot || !root.current) {\n      const frame = requestAnimationFrame(land);\n      return () => cancelAnimationFrame(frame);\n    }\n    const to = centre(slot);\n    const s = { x: null as Spring | null, y: null as Spring | null, s: null as Spring | null };\n    const paint = () => {\n      if (!s.x || !s.y || !s.s) return;\n      el.style.transform = `translate3d(${(s.x.get() - GLYPH / 2).toFixed(2)}px, ${(s.y.get() - GLYPH / 2).toFixed(2)}px, 0) scale(${s.s.get().toFixed(4)})`;\n      const resting = [s.x, s.y, s.s].every((spring) => spring.get() === spring.getTarget() && spring.getVelocity() === 0);\n      if (resting && !landed) {\n        chips.current.get(flight.emoji)?.land();\n        burst(flight.emoji, to.x, to.y);\n        land();\n      }\n    };\n    s.x = createSpring(flight.from.x, FLY_X, paint, 0.4);\n    s.y = createSpring(flight.from.y, FLY_Y, paint, 0.4);\n    s.s = createSpring(flight.from.s, FLY_S, paint, 0.004);\n    el.textContent = flight.emoji;\n    el.style.visibility = \"visible\";\n    paint();\n    s.x.set(to.x);\n    s.y.set(to.y);\n    s.s.set(CHIP_GLYPH / GLYPH);\n    return () => {\n      s.x?.stop();\n      s.y?.stop();\n      s.s?.stop();\n      el.style.visibility = \"hidden\";\n    };\n  }, [flight, burst, centre]);\n\n  const toggleChip = React.useCallback(\n    (emoji: string) => {\n      stopAuto();\n      const on = !latest.current.list.some((r) => r.emoji === emoji && r.mine);\n      void react(emoji, on);\n    },\n    [react, stopAuto],\n  );\n\n  const open = phase === \"open\";\n\n  return (\n    <div ref={root} role=\"group\" aria-label=\"Reactions\" className={`relative flex flex-wrap items-center ${className}`}>\n      {rows.map(({ reaction, leaving }) => (\n        <Chip\n          key={reaction.emoji}\n          reaction={reaction}\n          label={labelOf(reaction.emoji)}\n          leaving={leaving}\n          animateIn={ready}\n          awaiting={flight?.emoji === reaction.emoji}\n          quiet={phase !== \"closed\"}\n          reduced={reduced}\n          register={register}\n          onToggle={toggleChip}\n        />\n      ))}\n\n      <span className=\"inline-flex py-0.5\">\n        <button\n          ref={trigger}\n          type=\"button\"\n          aria-label={label}\n          aria-haspopup=\"menu\"\n          aria-expanded={open}\n          aria-controls={open ? trayId : undefined}\n          className={`grid size-8 cursor-pointer touch-none select-none place-items-center rounded-full shadow-[inset_0_0_0_1px_var(--border)] transition-colors [-webkit-touch-callout:none] ${\n            open ? \"bg-accent text-foreground\" : \"bg-background text-muted-foreground hover:bg-accent hover:text-foreground\"\n          } ${INTERACTION_PRESS} ${INTERACTION_FOCUS}`}\n          onContextMenu={(event) => event.preventDefault()}\n          onPointerDown={(event) => {\n            if (event.button !== 0) return;\n            stopAuto();\n            const box = root.current?.getBoundingClientRect();\n            press.current = { id: event.pointerId, x: event.clientX, y: event.clientY, dragging: false, wasOpen: latest.current.phase === \"open\", rootX: box?.left ?? 0, rootY: box?.top ?? 0 };\n            if (latest.current.phase !== \"open\") openTray(false);\n            event.currentTarget.setPointerCapture(event.pointerId);\n          }}\n          onPointerMove={(event) => {\n            const p = press.current;\n            if (!p || p.id !== event.pointerId) return;\n            if (!p.dragging && Math.hypot(event.clientX - p.x, event.clientY - p.y) < 7) return;\n            p.dragging = true;\n            tray.current?.setActive(tray.current.indexAt(event.clientX - p.rootX, event.clientY - p.rootY));\n          }}\n          onPointerUp={(event) => {\n            const p = press.current;\n            press.current = null;\n            if (!p || p.id !== event.pointerId) return;\n            if (p.dragging) {\n              const index = tray.current?.indexAt(event.clientX - p.rootX, event.clientY - p.rootY) ?? -1;\n              if (index >= 0) pickIndex(index, false);\n              else closeTray(false);\n            } else if (p.wasOpen) closeTray(false);\n          }}\n          onPointerCancel={() => {\n            press.current = null;\n          }}\n          onClick={(event) => {\n            // Pointers are handled above; this is Enter or Space.\n            if (event.detail !== 0) return;\n            if (latest.current.phase === \"open\") closeTray(true);\n            else openTray(true);\n          }}\n          onKeyDown={(event) => {\n            if (event.key === \"Escape\" && open) {\n              event.preventDefault();\n              closeTray(true);\n            } else if ((event.key === \"ArrowUp\" || event.key === \"ArrowDown\" || event.key === \"ArrowRight\") && open) {\n              event.preventDefault();\n              tray.current?.focus(0);\n            } else if (event.key === \"ArrowUp\" && !open) {\n              event.preventDefault();\n              openTray(true);\n            }\n          }}\n        >\n          <SmilePlus open={open} reduced={reduced} />\n        </button>\n      </span>\n\n      {phase !== \"closed\" && place && (\n        <ReactionTray\n          ref={tray}\n          id={trayId}\n          choices={choices}\n          mine={mine}\n          place={place}\n          closing={phase === \"closing\"}\n          reduced={reduced}\n          autoFocus={focusTray}\n          onPick={pickIndex}\n          onClose={closeTray}\n          onClosed={() => setPhase((p) => (p === \"closing\" ? \"closed\" : p))}\n        />\n      )}\n\n      <span ref={flyer} aria-hidden=\"true\" className=\"pointer-events-none absolute left-0 top-0 z-30 flex justify-center leading-none will-change-transform\" style={{ fontSize: GLYPH, visibility: \"hidden\", width: GLYPH, height: GLYPH }} />\n      <span ref={sparks} aria-hidden=\"true\" className=\"pointer-events-none absolute left-0 top-0 z-30\" />\n      <span role=\"status\" className=\"sr-only\">\n        {said}\n      </span>\n    </div>\n  );\n}\n\nexport default Reactions;\n"},{"path":"registry/reactions-tray.tsx","type":"registry:component","content":"// Hairline UI · reactions · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n\"use client\";\n\nimport * as React from \"react\";\nimport { TextMorph } from \"./text-morph\";\nimport { INTERACTION_FOCUS, createSpring, type Spring } from \"./ui-interaction-motion\";\n\n/* The tray the reactions picker opens: the add button grows into a pill of emoji that swell under the finger. Its geometry is fixed (cells of\n * CELL px), so a drag that started on the add button can hit-test it by arithmetic, with no layout reads while moving. */\n\nexport interface ReactionChoice {\n  emoji: string;\n  /** Read out to screen readers and shown above the emoji under the finger. */\n  label: string;\n}\n\nexport interface TrayPlacement {\n  /** Root-local position of the tray's top left corner. */\n  left: number;\n  top: number;\n  /** Where it grows from, relative to the tray: the add button's centre. */\n  originX: number;\n  originY: number;\n  side: \"top\" | \"bottom\";\n}\n\nexport interface TrayHandle {\n  /** Swell the emoji at this index (−1 for none). */\n  setActive: (index: number) => void;\n  /** The cell under a root-local point, or −1. Generous above and below, strict at the ends. */\n  indexAt: (x: number, y: number) => number;\n  /** Where an emoji is drawn right now, root-local, and its scale against GLYPH. */\n  origin: (index: number) => { x: number; y: number; s: number };\n  focus: (index: number) => void;\n}\n\nexport const CELL = 42;\nexport const PAD = 4;\nexport const TRAY_H = 50;\n/** The add button's size: the tray grows out of it and folds back into it. */\nconst BUTTON = 32;\n/** Emoji are drawn at their largest size and scaled down at rest, so a swell never upscales a bitmap. */\nexport const GLYPH = 34;\nconst REST = 0.66;\nconst NEAR = 0.8;\nconst LIFT = -10;\nconst NEAR_LIFT = -3;\n\nexport const trayWidth = (count: number) => count * CELL + PAD * 2;\n\n// Opening is quick and only just overshoots; the swell is tighter still, since it runs every time a finger crosses a cell.\nconst OPEN = { stiffness: 320, damping: 29 };\nconst SWELL = { stiffness: 620, damping: 38 };\nconst TAG = { stiffness: 520, damping: 42 };\n\ninterface TrayProps {\n  id: string;\n  choices: ReactionChoice[];\n  mine: ReadonlySet<string>;\n  place: TrayPlacement;\n  closing: boolean;\n  reduced: boolean;\n  /** Put focus on the first emoji when it opens (it was opened from the keyboard). */\n  autoFocus: boolean;\n  onPick: (index: number, keyboard: boolean) => void;\n  onClose: (returnFocus: boolean) => void;\n  onClosed: () => void;\n  ref?: React.Ref<TrayHandle>;\n}\n\nexport function ReactionTray({ id, choices, mine, place, closing, reduced, autoFocus, onPick, onClose, onClosed, ref }: TrayProps) {\n  const surface = React.useRef<HTMLDivElement>(null);\n  const pill = React.useRef<HTMLSpanElement>(null);\n  const tag = React.useRef<HTMLSpanElement>(null);\n  const glyphs = React.useRef<(HTMLSpanElement | null)[]>([]);\n  const cells = React.useRef<(HTMLButtonElement | null)[]>([]);\n  const springs = React.useRef<{ open: Spring; tagX: Spring; scale: Spring[]; lift: Spring[] } | null>(null);\n  const active = React.useRef(-1);\n  const closingRef = React.useRef(closing);\n  const finished = React.useRef(false);\n  const closedRef = React.useRef(onClosed);\n  const [label, setLabel] = React.useState(-1);\n  const [focusIndex, setFocusIndex] = React.useState(0);\n  const count = choices.length;\n\n  React.useLayoutEffect(() => {\n    closedRef.current = onClosed;\n  });\n\n  const paint = React.useCallback(() => {\n    const s = springs.current;\n    const el = surface.current;\n    if (!s || !el) return;\n    const t = s.open.get();\n    // One surface: the pill starts as the add button, exactly over it, and stretches out and up into the tray (and back).\n    const W = trayWidth(count);\n    const g = Math.max(0, t);\n    const w = BUTTON + (W - BUTTON) * Math.min(g, 1.03);\n    const h = BUTTON + (TRAY_H - BUTTON) * Math.min(g, 1);\n    const cx = place.originX + (W / 2 - place.originX) * Math.min(g, 1);\n    const cy = place.originY + (TRAY_H / 2 - place.originY) * Math.min(g, 1);\n    const left = Math.max(-(w - W) / 2, Math.min(W - w + (w - W) / 2, cx - w / 2));\n    const top = cy - h / 2;\n    if (pill.current) {\n      pill.current.style.width = `${w.toFixed(2)}px`;\n      pill.current.style.height = `${h.toFixed(2)}px`;\n      pill.current.style.transform = `translate3d(${left.toFixed(2)}px, ${top.toFixed(2)}px, 0)`;\n      pill.current.style.opacity = `${Math.min(1, g * 6)}`;\n    }\n    s.scale.forEach((spring, i) => {\n      const glyph = glyphs.current[i];\n      if (!glyph) return;\n      glyph.style.transform = `translate3d(0, ${s.lift[i].get().toFixed(2)}px, 0) scale(${spring.get().toFixed(4)})`;\n      // An emoji shows once the pill has reached it, so nothing floats outside the surface while it grows.\n      const x = PAD + i * CELL + CELL / 2;\n      const inside = Math.min(x - left, left + w - x) - 6;\n      glyph.style.opacity = `${Math.max(0, Math.min(1, inside / 14, (h - BUTTON) / 8))}`;\n    });\n    if (tag.current) tag.current.style.transform = `translate3d(${s.tagX.get().toFixed(2)}px, 0, 0)`;\n    if (closingRef.current && t <= 0.02 && !finished.current) {\n      finished.current = true;\n      closedRef.current();\n    }\n  }, [count, place]);\n\n  const aim = React.useCallback(\n    (index: number) => {\n      const s = springs.current;\n      if (!s || index === active.current) return;\n      const was = active.current;\n      active.current = index;\n      s.scale.forEach((spring, i) => {\n        const d = index < 0 ? 9 : Math.abs(i - index);\n        const scale = d === 0 ? 1 : d === 1 ? NEAR : REST;\n        const lift = d === 0 ? LIFT : d === 1 ? NEAR_LIFT : 0;\n        if (reduced) {\n          spring.jump(scale);\n          s.lift[i].jump(lift);\n        } else {\n          spring.set(scale);\n          s.lift[i].set(lift);\n        }\n      });\n      if (index >= 0) {\n        const x = PAD + index * CELL + CELL / 2;\n        // The label appears where the finger is, then glides with it from cell to cell.\n        if (was < 0 || reduced) s.tagX.jump(x);\n        else s.tagX.set(x);\n      }\n      setLabel(index);\n    },\n    [reduced],\n  );\n\n  React.useLayoutEffect(() => {\n    const s = {\n      open: createSpring(0, OPEN, paint, 0.004),\n      tagX: createSpring(PAD + CELL / 2, TAG, paint, 0.2),\n      scale: choices.map(() => createSpring(0.3, SWELL, paint, 0.002)),\n      lift: choices.map(() => createSpring(8, SWELL, paint, 0.05)),\n    };\n    springs.current = s;\n    const timers: number[] = [];\n    if (reduced) {\n      s.open.jump(1);\n      s.scale.forEach((spring) => spring.jump(REST));\n      s.lift.forEach((spring) => spring.jump(0));\n    } else {\n      paint();\n      s.open.set(1);\n      // The emoji rise into the pill as it reaches them: a ripple outward from the add button.\n      s.scale.forEach((spring, i) =>\n        timers.push(\n          window.setTimeout(\n            () => {\n              if (active.current >= 0) return;\n              spring.set(REST);\n              s.lift[i].set(0);\n            },\n            30 + Math.abs(PAD + i * CELL + CELL / 2 - place.originX) * 0.42,\n          ),\n        ),\n      );\n    }\n    return () => {\n      timers.forEach(window.clearTimeout);\n      s.open.stop();\n      s.tagX.stop();\n      s.scale.forEach((spring) => spring.stop());\n      s.lift.forEach((spring) => spring.stop());\n      springs.current = null;\n    };\n    // Built once per opening; the choices don't change while it's open.\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, []);\n\n  React.useEffect(() => {\n    closingRef.current = closing;\n    const s = springs.current;\n    if (!s) return;\n    if (closing) {\n      finished.current = false;\n      if (reduced) s.open.jump(0);\n      else s.open.set(0);\n    } else {\n      finished.current = false;\n      if (reduced) s.open.jump(1);\n      else s.open.set(1);\n    }\n  }, [closing, reduced]);\n\n  React.useEffect(() => {\n    if (autoFocus) cells.current[0]?.focus({ preventScroll: true });\n  }, [autoFocus]);\n\n  React.useImperativeHandle(\n    ref,\n    () => ({\n      setActive: aim,\n      indexAt(x, y) {\n        const local = x - place.left - PAD;\n        if (local < -6 || local > count * CELL + 6) return -1;\n        if (y < place.top - 64 || y > place.top + TRAY_H + 64) return -1;\n        return Math.max(0, Math.min(count - 1, Math.floor(local / CELL)));\n      },\n      origin(index) {\n        const s = springs.current;\n        return {\n          x: place.left + PAD + index * CELL + CELL / 2,\n          y: place.top + TRAY_H / 2 + (s?.lift[index].get() ?? 0),\n          s: s?.scale[index].get() ?? REST,\n        };\n      },\n      focus(index) {\n        cells.current[index]?.focus({ preventScroll: true });\n      },\n    }),\n    [aim, place, count],\n  );\n\n  const move = (event: React.KeyboardEvent, index: number) => {\n    event.preventDefault();\n    const next = (index + count) % count;\n    cells.current[next]?.focus({ preventScroll: true });\n  };\n\n  return (\n    <>\n      <div\n        ref={surface}\n        id={id}\n        role=\"menu\"\n        aria-label=\"Add reaction\"\n        aria-orientation=\"horizontal\"\n        inert={closing}\n        className={`absolute z-20 flex p-1 text-popover-foreground ${closing ? \"pointer-events-none\" : \"\"}`}\n        style={{\n          left: place.left,\n          top: place.top,\n          height: TRAY_H,\n          width: trayWidth(count),\n        }}\n        onPointerLeave={(event) => {\n          if (event.pointerType === \"mouse\" && !surface.current?.contains(document.activeElement)) aim(-1);\n        }}\n        onKeyDown={(event) => {\n          const index = cells.current.findIndex((cell) => cell === document.activeElement);\n          if (event.key === \"ArrowRight\") move(event, index + 1);\n          else if (event.key === \"ArrowLeft\") move(event, index - 1);\n          else if (event.key === \"Home\") move(event, 0);\n          else if (event.key === \"End\") move(event, count - 1);\n          else if (event.key === \"Escape\") {\n            event.preventDefault();\n            event.stopPropagation();\n            onClose(true);\n          } else if (event.key === \"Tab\") onClose(false);\n        }}\n      >\n        {/* The surface itself: a hairline pill, drawn apart from the emoji so it can grow out of the add button. */}\n        <span\n          ref={pill}\n          aria-hidden=\"true\"\n          className=\"pointer-events-none absolute left-0 top-0 rounded-full bg-popover shadow-[0_0_0_1px_var(--border)] will-change-transform\"\n          style={{ width: BUTTON, height: BUTTON, opacity: 0 }}\n        />\n        {choices.map((choice, i) => {\n          const on = mine.has(choice.emoji);\n          return (\n            <button\n              key={choice.emoji}\n              ref={(el) => {\n                cells.current[i] = el;\n              }}\n              type=\"button\"\n              role=\"menuitemcheckbox\"\n              aria-checked={on}\n              aria-label={choice.label}\n              tabIndex={i === focusIndex ? 0 : -1}\n              className={`relative grid shrink-0 cursor-pointer place-items-center rounded-full outline-none ${INTERACTION_FOCUS} focus-visible:ring-offset-0`}\n              style={{ width: CELL, height: CELL }}\n              onFocus={() => {\n                setFocusIndex(i);\n                aim(i);\n              }}\n              onPointerMove={(event) => {\n                if (event.pointerType === \"mouse\") aim(i);\n              }}\n              onClick={(event) => onPick(i, event.detail === 0)}\n            >\n              {/* Yours already: a dot under it, and picking it again takes it back. */}\n              <span\n                aria-hidden=\"true\"\n                className=\"absolute bottom-[3px] size-1 rounded-full bg-foreground transition-[opacity,scale] duration-300 ease-[cubic-bezier(0.16,1,0.3,1)]\"\n                style={{ opacity: on ? 1 : 0, scale: on ? 1 : 0.4 }}\n              />\n              <span\n                ref={(el) => {\n                  glyphs.current[i] = el;\n                }}\n                aria-hidden=\"true\"\n                className=\"pointer-events-none block select-none text-center leading-none will-change-transform\"\n                style={{ fontSize: GLYPH, transform: `translate3d(0, 8px, 0) scale(0.3)`, opacity: 0 }}\n              >\n                {choice.emoji}\n              </span>\n            </button>\n          );\n        })}\n      </div>\n      {/* The name of the emoji under the finger, above the tray (below it when the tray opens\n            downward). A sibling of the tray, not inside its scaled, faded surface, so its glide stays on the compositor. */}\n      <span\n        ref={tag}\n        aria-hidden=\"true\"\n        className=\"pointer-events-none absolute z-20 will-change-transform\"\n        style={{ left: place.left, top: place.side === \"top\" ? place.top - 30 : place.top + TRAY_H + 8 }}\n      >\n        <span\n          className=\"block whitespace-nowrap rounded-full bg-foreground px-2 py-0.5 text-[11.5px] font-medium leading-[18px] text-background transition-[opacity,translate] duration-200 ease-[cubic-bezier(0.16,1,0.3,1)] motion-reduce:transition-none\"\n          style={{ opacity: label >= 0 && !closing ? 1 : 0, translate: label >= 0 && !closing ? \"-50% 0\" : `-50% ${place.side === \"top\" ? 4 : -4}px` }}\n        >\n          <TextMorph duration={300} animateWidth={false}>\n            {label >= 0 ? choices[label].label : choices[0].label}\n          </TextMorph>\n        </span>\n      </span>\n    </>\n  );\n}\n"},{"path":"registry/ui-interaction-motion.ts","type":"registry:component","content":"// Hairline UI · reactions · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n'use client';\n\nimport * as React from 'react';\n\nexport const EASE_OUT = 'cubic-bezier(0.16, 1, 0.3, 1)';\nexport const EASE_SETTLE = 'cubic-bezier(0.22, 1.18, 0.36, 1)';\n/** Thrown things (indicators, thumbs): a slight overshoot on transform only. */\nexport const EASE_THROW = 'cubic-bezier(0.34, 1.36, 0.64, 1)';\n/**\n * The press every button primitive shares: a 3% give that eases in and settles back.\n * Tailwind v4's scale-* writes the `scale` property, so `scale` has to be in the list\n * or the press snaps.\n */\nexport const INTERACTION_PRESS =\n  'transition-[background-color,color,box-shadow,opacity,scale] duration-200 ease-[cubic-bezier(0.16,1,0.3,1)] active:scale-[0.97] motion-reduce:transition-none motion-reduce:active:scale-100';\nexport const INTERACTION_FOCUS ='focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:ring-offset-2 focus-visible:ring-offset-background';\n\nconst query = '(prefers-reduced-motion: reduce)';\nconst subscribe = (notify: () => void) => {\n  const media = window.matchMedia(query);\n  media.addEventListener('change', notify);\n  return () => media.removeEventListener('change', notify);\n};\nexport const useInteractionReducedMotion = () => React.useSyncExternalStore(subscribe, () => window.matchMedia(query).matches, () => false);\n\nexport function useInteractionActivity<T extends Element>() {\n  const ref = React.useRef<T>(null);\n  const [visible, setVisible] = React.useState(false);\n  const [hidden, setHidden] = React.useState(false);\n  React.useEffect(() => {\n    const el = ref.current;\n    if (!el) return;\n    const observer = new IntersectionObserver(([entry]) => setVisible(entry.isIntersecting));\n    observer.observe(el);\n    const visibility = () => setHidden(document.hidden);\n    visibility(); document.addEventListener('visibilitychange', visibility);\n    return () => { observer.disconnect(); document.removeEventListener('visibilitychange', visibility); };\n  }, []);\n  return { ref, active: visible && !hidden };\n}\n\nexport function interactionIcon(on: boolean, reduced: boolean): React.CSSProperties {\n  return { opacity: on ? 1 : 0, transform: on ? 'none' : 'scale(0.6)', filter: on ? 'blur(0px)' : 'blur(3px)', transition: reduced ? 'none' : `opacity 220ms ${EASE_OUT}, transform 380ms ${EASE_OUT}, filter 220ms ${EASE_OUT}` };\n}\n\n/** A raised object: one tight contact shadow, one short ambient, a hairline of light on its top edge. */\nexport const MATERIAL_LIFT =\n  'shadow-[0_1px_1.5px_rgb(0_0_0/0.07),0_3px_8px_-2px_rgb(0_0_0/0.1),inset_0_0.5px_0_rgb(255_255_255/0.8)] dark:shadow-[0_1px_2px_rgb(0_0_0/0.5),0_4px_10px_-2px_rgb(0_0_0/0.35),inset_0_0.5px_0_rgb(255_255_255/0.1)]';\n/** A trough something sits in, shaded from above, lit along its bottom edge. */\nexport const MATERIAL_RECESS =\n  'shadow-[inset_0_1px_2.5px_rgb(0_0_0/0.09),inset_0_-0.5px_0_rgb(255_255_255/0.7)] dark:shadow-[inset_0_1px_3px_rgb(0_0_0/0.45),inset_0_-0.5px_0_rgb(255_255_255/0.07)]';\n\nexport type SpringConfig = { stiffness: number; damping: number; mass?: number };\nexport interface Spring {\n  get(): number;\n  getVelocity(): number;\n  getTarget(): number;\n  /** Aim somewhere new from wherever it is now, keeping its speed. */\n  set(target: number): void;\n  /** Add speed (units per second), on top of what it already has. */\n  push(velocity: number): void;\n  /** Be there now, at rest. */\n  jump(value: number): void;\n  configure(config: SpringConfig): void;\n  stop(): void;\n}\n\n// Every moving spring on the page shares one frame loop, which sleeps when the last one rests. Each spring's onFrame runs\n// once per frame after all of them have stepped, so several springs that draw one shape paint it once.\nconst SPRING_STEP = 1 / 240;\ntype Running = { step: () => void };\nconst runningSprings = new Set<Running>();\nconst springPainters = new Set<() => void>();\nlet springFrame = 0;\nlet springLast = 0;\nlet springSpare = 0;\n\nfunction springTick(now: number) {\n  // A hidden tab stops the frames, so the first one back must not count the whole gap as time passed.\n  springSpare += Math.min((now - springLast) / 1000, 0.05);\n  springLast = now;\n  while (springSpare >= SPRING_STEP) {\n    runningSprings.forEach((spring) => spring.step());\n    springSpare -= SPRING_STEP;\n  }\n  const painters = [...springPainters];\n  springPainters.clear();\n  painters.forEach((paint) => paint());\n  springFrame = runningSprings.size ? requestAnimationFrame(springTick) : 0;\n}\n\nfunction wakeSprings(spring: Running) {\n  runningSprings.add(spring);\n  if (springFrame) return;\n  springSpare = 0;\n  springFrame = requestAnimationFrame((now) => {\n    springLast = now - 1000 / 60;\n    springTick(now);\n  });\n}\n\n/**\n * A spring that carries its speed: re-aim it mid-flight and it curves on from where it is, push it while it swings and the\n * push adds to the swing. Use it for anything that can be interrupted; a curve restarts from a standstill every time.\n * `onFrame` should write straight to the DOM. `precision` is how close counts as there, in the value's own units.\n */\nexport function createSpring(initial: number, config: SpringConfig, onFrame: () => void, precision = 0.01): Spring {\n  let value = initial;\n  let velocity = 0;\n  let target = initial;\n  let { stiffness, damping, mass = 1 } = config;\n  const running: Running = {\n    step() {\n      velocity += ((-stiffness * (value - target) - damping * velocity) / mass) * SPRING_STEP;\n      value += velocity * SPRING_STEP;\n      if (Math.abs(value - target) < precision && Math.abs(velocity) < precision * 10) {\n        value = target;\n        velocity = 0;\n        runningSprings.delete(running);\n      }\n      springPainters.add(onFrame);\n    },\n  };\n  return {\n    get: () => value,\n    getVelocity: () => velocity,\n    getTarget: () => target,\n    set(next) {\n      if (next === target && !runningSprings.has(running)) return;\n      target = next;\n      wakeSprings(running);\n    },\n    push(speed) {\n      velocity += speed;\n      wakeSprings(running);\n    },\n    jump(next) {\n      value = next;\n      target = next;\n      velocity = 0;\n      runningSprings.delete(running);\n      onFrame();\n    },\n    configure(next) {\n      ({ stiffness, damping, mass = 1 } = next);\n    },\n    stop() {\n      runningSprings.delete(running);\n    },\n  };\n}\n\n/** Sample recent movement rather than averaging a long drag and losing its release velocity. */\nexport type PointerSample = { x: number; time: number };\nexport function samplePointer(samples: PointerSample[], x: number, time: number) {\n  samples.push({ x, time });\n  while (samples.length > 2 && time - samples[0].time > 100) samples.shift();\n}\nexport function releaseVelocity(samples: PointerSample[], now: number) {\n  if (samples.length < 2 || now - samples[samples.length - 1].time > 100) return 0;\n  const first = samples[0], last = samples[samples.length - 1];\n  return (last.x - first.x) / Math.max(1, last.time - first.time);\n}\n\n/** Smooth Apple/rational rubber-band curve: continuous exponential-like resistance without linear kinks. */\nexport function rubberBand(overshoot: number, dimension = 320, constant = 0.55): number {\n  const d = dimension || 320;\n  const abs = Math.abs(overshoot);\n  return Math.sign(overshoot) * (1 - 1 / ((abs * constant) / d + 1)) * d;\n}\n\n/** Projects resting travel from release velocity (velocity in px/ms; time in seconds). */\nexport function projectInertia(distance: number, velocity: number, time = 0.12): number {\n  return distance + velocity * 1000 * time;\n}\n\n/** Smooths incoming release velocity toward a boundary so springs don't slam or clip into walls. */\nexport function softenVelocity(velocity: number, distanceToTarget: number, factor = 10): number {\n  const maxAllowed = Math.abs(distanceToTarget) * factor;\n  return Math.sign(velocity) * Math.min(Math.abs(velocity), maxAllowed);\n}\n\n/** A damped spring sampled by WAAPI: tuned for organic lightness with a hint of life (3% breath). */\nexport function springFrames(\n  from: number,\n  to: number,\n  velocity = 0,\n  duration = 480,\n  config: { omega?: number; damping?: number; steps?: number } = {},\n) {\n  const { omega = 16, damping = 0.74, steps = 36 } = config;\n  const damped = omega * Math.sqrt(Math.max(0.001, 1 - damping * damping));\n  const displacement = from - to;\n  const coefficient = (velocity * 1000 + damping * omega * displacement) / damped;\n  return Array.from({ length: steps + 1 }, (_, i) => {\n    const t = (i / steps) * (duration / 1000);\n    const value = to + Math.exp(-damping * omega * t) * (displacement * Math.cos(damped * t) + coefficient * Math.sin(damped * t));\n    return { value: i === steps ? to : value, offset: i / steps };\n  });\n}\n\n"}],"css":{},"docs":"Docs and live preview: https://hairlineui.com/ui/reactions. MIT licensed: https://hairlineui.com/license#components","meta":{"license":"MIT"}}