{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"bubble-wrap","type":"registry:component","title":"Bubble wrap","description":"Pop every bubble to clear the list, one click or one long swipe.","author":"Yash Bavadiya <https://xevrion.dev>","dependencies":["motion"],"registryDependencies":["utils"],"files":[{"path":"components/bubble-wrap.tsx","type":"registry:component","content":"\"use client\";\n\nimport { memo, useCallback, useRef, useState } from \"react\";\nimport { motion } from \"motion/react\";\nimport { useReducedMotion } from \"@/hooks/use-reduced-motion\";\nimport { cn } from \"@/lib/utils\";\n\n// Layout in sheet units; everything is placed in percentages of these, so\n// the sheet scales down on narrow screens without re-measuring.\nconst D = 48; // bubble diameter\nconst PITCH_X = 58;\n// Hex packing: rows sit sqrt(3)/2 of the pitch apart, offset by half.\nconst PITCH_Y = 51;\nconst PAD = 20;\nconst EASE_OUT = [0.23, 1, 0.32, 1] as const;\n// The squash is quick so a drag across a row reads as a string of pops,\n// not a queue of animations.\nconst POP = { duration: 0.18, times: [0, 0.35, 1], ease: EASE_OUT };\n// A little bounce as the air comes back: the one place it belongs.\nconst INFLATE = { type: \"spring\", duration: 0.4, bounce: 0.35 } as const;\n// Reset ripples diagonally from the top left corner.\nconst WAVE_STEP = 0.03;\n\n// Clear plastic is a physical material, so the dome is built from light\n// rather than a fill colour: a hard specular glint up top left, a softer\n// reflection low on the right, a bright rim where the film curves away, and\n// a shadow side. White and black at low alpha read as clear plastic on\n// either theme's surface.\nconst DOME = [\n  \"radial-gradient(ellipse 24% 14% at 36% 25%, light-dark(oklch(1 0 0 / 0.95), oklch(1 0 0 / 0.55)), oklch(1 0 0 / 0) 100%)\",\n  \"radial-gradient(ellipse 30% 9% at 58% 83%, light-dark(oklch(1 0 0 / 0.7), oklch(1 0 0 / 0.14)), oklch(1 0 0 / 0) 100%)\",\n  \"radial-gradient(circle at 40% 35%, light-dark(oklch(1 0 0 / 0.6), oklch(1 0 0 / 0.08)), light-dark(oklch(0 0 0 / 0.05), oklch(1 0 0 / 0.02)) 78%)\",\n].join(\", \");\nconst DOME_EDGE = [\n  \"inset 0 0 0 1px light-dark(oklch(0 0 0 / 0.09), oklch(1 0 0 / 0.14))\",\n  \"inset -3px -5px 9px light-dark(oklch(0 0 0 / 0.1), oklch(0 0 0 / 0.55))\",\n  \"inset 2px 3px 5px light-dark(oklch(1 0 0 / 1), oklch(1 0 0 / 0.07))\",\n  \"0 5px 9px -4px light-dark(oklch(0 0 0 / 0.22), oklch(0 0 0 / 0.8))\",\n].join(\", \");\n\ntype Cell = { row: number; col: number; x: number; y: number };\n\nfunction layout(rows: number, cols: number) {\n  const cells: Cell[] = [];\n  for (let row = 0; row < rows; row++) {\n    for (let col = 0; col < cols; col++) {\n      cells.push({\n        row,\n        col,\n        x: PAD + D / 2 + col * PITCH_X + (row % 2 ? PITCH_X / 2 : 0),\n        y: PAD + D / 2 + row * PITCH_Y,\n      });\n    }\n  }\n  return {\n    cells,\n    width: PAD * 2 + D + (cols - 1) * PITCH_X + PITCH_X / 2,\n    height: PAD * 2 + D + (rows - 1) * PITCH_Y,\n  };\n}\n\nexport function BubbleWrap({\n  rows = 4,\n  cols = 6,\n  label = \"Bubble wrap\",\n  onPop,\n  onComplete,\n  className,\n}: {\n  rows?: number;\n  cols?: number;\n  label?: string;\n  onPop?: (popped: number, total: number) => void;\n  onComplete?: () => void;\n  className?: string;\n}) {\n  const reduceMotion = !!useReducedMotion();\n  const [{ cells, width, height }] = useState(() => layout(rows, cols));\n  const total = cells.length;\n  const [popped, setPopped] = useState<boolean[]>(() =>\n    Array(total).fill(false),\n  );\n  const poppedRef = useRef(popped);\n  const [active, setActive] = useState(0);\n  const sheet = useRef<HTMLDivElement>(null);\n  const buttons = useRef<(HTMLButtonElement | null)[]>([]);\n  const drag = useRef<{ id: number; x: number; y: number } | null>(null);\n\n  const count = popped.filter(Boolean).length;\n\n  const register = useCallback((i: number, el: HTMLButtonElement | null) => {\n    buttons.current[i] = el;\n  }, []);\n\n  const pop = useCallback(\n    (i: number) => {\n      if (poppedRef.current[i]) return;\n      const next = poppedRef.current.slice();\n      next[i] = true;\n      poppedRef.current = next;\n      setPopped(next);\n      navigator.vibrate?.(8);\n      const n = next.filter(Boolean).length;\n      onPop?.(n, next.length);\n      if (n === next.length) onComplete?.();\n    },\n    [onPop, onComplete],\n  );\n\n  const reset = () => {\n    const next = Array(total).fill(false);\n    poppedRef.current = next;\n    setPopped(next);\n  };\n\n  // Pops every bubble within reach of the segment from a to b, sampled\n  // densely enough that a fast swipe can't jump over one.\n  const sweep = (ax: number, ay: number, bx: number, by: number) => {\n    const steps = Math.max(\n      1,\n      Math.ceil(Math.hypot(bx - ax, by - ay) / (D / 4)),\n    );\n    for (let s = 0; s <= steps; s++) {\n      const px = ax + ((bx - ax) * s) / steps;\n      const py = ay + ((by - ay) * s) / steps;\n      cells.forEach((c, i) => {\n        // 0.45 of the diameter: gaps between bubbles stay safe to touch.\n        if (Math.hypot(c.x - px, c.y - py) < D * 0.45) pop(i);\n      });\n    }\n  };\n\n  const toUnits = (e: React.PointerEvent) => {\n    const box = sheet.current!.getBoundingClientRect();\n    return {\n      x: ((e.clientX - box.left) / box.width) * width,\n      y: ((e.clientY - box.top) / box.height) * height,\n    };\n  };\n\n  const endDrag = (e: React.PointerEvent) => {\n    if (drag.current?.id === e.pointerId) drag.current = null;\n  };\n\n  const move = useCallback(\n    (i: number, key: string) => {\n      const c = cells[i];\n      const at = (row: number, col: number) =>\n        cells.findIndex((x) => x.row === row && x.col === col);\n      const next = {\n        ArrowLeft: at(c.row, Math.max(c.col - 1, 0)),\n        ArrowRight: at(c.row, Math.min(c.col + 1, cols - 1)),\n        ArrowUp: at(Math.max(c.row - 1, 0), c.col),\n        ArrowDown: at(Math.min(c.row + 1, rows - 1), c.col),\n        Home: at(c.row, 0),\n        End: at(c.row, cols - 1),\n      }[key];\n      if (next === undefined) return false;\n      setActive(next);\n      buttons.current[next]?.focus();\n      return true;\n    },\n    [cells, rows, cols],\n  );\n\n  const done = count === total;\n\n  return (\n    <div\n      className={cn(\n        \"flex w-[min(440px,100%)] flex-col gap-3 select-none\",\n        className,\n      )}\n    >\n      <div className=\"flex h-9 items-center justify-between gap-3 px-1\">\n        <p className=\"grid text-[15px]\">\n          <span\n            className={cn(\n              \"col-start-1 row-start-1 transition-[opacity,filter] duration-200 ease-out\",\n              done && \"opacity-0 blur-[4px]\",\n            )}\n          >\n            <span className=\"font-medium text-foreground tabular-nums\">\n              {count}\n            </span>\n            <span className=\"text-muted-foreground tabular-nums\"> / {total} popped</span>\n          </span>\n          <span\n            aria-live=\"polite\"\n            className={cn(\n              \"col-start-1 row-start-1 font-medium text-foreground transition-[opacity,filter] duration-200 ease-out\",\n              !done && \"opacity-0 blur-[4px]\",\n            )}\n          >\n            {done ? \"All clear\" : \"\"}\n          </span>\n        </p>\n        <button\n          type=\"button\"\n          onClick={reset}\n          disabled={count === 0}\n          className=\"h-9 rounded-full bg-muted px-4 text-sm font-medium text-foreground shadow-raised outline-hidden transition-[scale,opacity] duration-150 ease-out focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-foreground active:scale-[0.96] disabled:opacity-50 disabled:active:scale-100\"\n        >\n          Reset\n        </button>\n      </div>\n      <div\n        ref={sheet}\n        role=\"group\"\n        aria-label={`${label}, ${total - count} of ${total} left`}\n        className=\"relative w-full touch-none rounded-[22px] bg-muted inset-ring inset-ring-foreground/5\"\n        style={{ aspectRatio: `${width} / ${height}` }}\n        onPointerDown={(e) => {\n          if (e.button !== 0 || drag.current) return;\n          e.currentTarget.setPointerCapture(e.pointerId);\n          const p = toUnits(e);\n          drag.current = { id: e.pointerId, ...p };\n          sweep(p.x, p.y, p.x, p.y);\n        }}\n        onPointerMove={(e) => {\n          const d = drag.current;\n          if (!d || d.id !== e.pointerId) return;\n          const p = toUnits(e);\n          sweep(d.x, d.y, p.x, p.y);\n          d.x = p.x;\n          d.y = p.y;\n        }}\n        onPointerUp={endDrag}\n        onPointerCancel={endDrag}\n      >\n        {cells.map((c, i) => (\n          <Bubble\n            key={i}\n            register={register}\n            index={i}\n            cell={c}\n            popped={popped[i]}\n            focusable={i === active}\n            left={(c.x - D / 2) / width}\n            top={(c.y - D / 2) / height}\n            size={D / width}\n            delay={(c.row + c.col) * WAVE_STEP}\n            reduceMotion={reduceMotion}\n            onPop={pop}\n            onFocusIndex={setActive}\n            onMove={move}\n          />\n        ))}\n      </div>\n    </div>\n  );\n}\n\nconst Bubble = memo(function Bubble({\n  register,\n  index,\n  cell,\n  popped,\n  focusable,\n  left,\n  top,\n  size,\n  delay,\n  reduceMotion,\n  onPop,\n  onFocusIndex,\n  onMove,\n}: {\n  register: (i: number, el: HTMLButtonElement | null) => void;\n  index: number;\n  cell: Cell;\n  popped: boolean;\n  focusable: boolean;\n  left: number;\n  top: number;\n  size: number;\n  delay: number;\n  reduceMotion: boolean;\n  onPop: (i: number) => void;\n  onFocusIndex: (i: number) => void;\n  onMove: (i: number, key: string) => boolean;\n}) {\n  const squash = reduceMotion\n    ? { duration: 0 }\n    : popped\n      ? POP\n      : { ...INFLATE, delay };\n  // Each bubble's creases sit at a different angle so the popped sheet\n  // doesn't look stamped.\n  const twist = (index * 47) % 360;\n\n  return (\n    <button\n      ref={(el) => {\n        register(index, el);\n      }}\n      type=\"button\"\n      tabIndex={focusable ? 0 : -1}\n      aria-pressed={popped}\n      aria-label={`Bubble, row ${cell.row + 1}, column ${cell.col + 1}`}\n      onClick={() => onPop(index)}\n      onFocus={() => onFocusIndex(index)}\n      onKeyDown={(e) => {\n        if (onMove(index, e.key)) e.preventDefault();\n      }}\n      className=\"absolute cursor-pointer rounded-full outline-hidden focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-foreground\"\n      style={{\n        left: `${left * 100}%`,\n        top: `${top * 100}%`,\n        width: `${size * 100}%`,\n        aspectRatio: \"1\",\n      }}\n    >\n      {/* The flat plastic footprint, always there under the dome. */}\n      <span className=\"absolute inset-0 rounded-full bg-foreground/[0.03] inset-ring inset-ring-foreground/10\" />\n      <motion.span\n        aria-hidden\n        className=\"absolute inset-0\"\n        initial={false}\n        animate={\n          popped\n            ? { scaleX: [1, 1.1, 0.92], scaleY: [1, 0.84, 0.92] }\n            : { scaleX: 1, scaleY: 1 }\n        }\n        transition={squash}\n      >\n        <motion.span\n          className=\"absolute inset-0 rounded-full\"\n          style={{ background: DOME, boxShadow: DOME_EDGE }}\n          initial={false}\n          animate={{ opacity: popped ? 0 : 1 }}\n          // Air leaves fast; the dome refills over the same wave as the scale.\n          transition={\n            popped\n              ? { duration: reduceMotion ? 0.1 : 0.14, ease: EASE_OUT }\n              : {\n                  duration: 0.2,\n                  ease: EASE_OUT,\n                  delay: reduceMotion ? 0 : delay,\n                }\n          }\n        />\n        <motion.svg\n          viewBox=\"0 0 48 48\"\n          className=\"absolute inset-0 size-full\"\n          fill=\"none\"\n          strokeLinecap=\"round\"\n          strokeLinejoin=\"round\"\n          initial={false}\n          animate={{ opacity: popped ? 1 : 0 }}\n          transition={{ duration: popped ? 0.2 : 0.1, ease: EASE_OUT }}\n          style={{ rotate: twist }}\n        >\n          <path\n            d=\"M13 20l6 3 3-5 5 6 7-2M16 30l5-2 4 4 5-3 4 2M22 12l2 4\"\n            className=\"stroke-foreground/25\"\n            strokeWidth={1}\n          />\n        </motion.svg>\n      </motion.span>\n      {/* A faint ring flicks outward at the moment of the pop. */}\n      {!reduceMotion && (\n        <motion.span\n          aria-hidden\n          className=\"pointer-events-none absolute inset-0 rounded-full inset-ring-[1.5px] inset-ring-foreground/40\"\n          initial={false}\n          animate={\n            popped\n              ? { scale: [1, 1.3], opacity: [0.8, 0] }\n              : { scale: 1, opacity: 0 }\n          }\n          transition={{ duration: 0.25, ease: EASE_OUT }}\n        />\n      )}\n    </button>\n  );\n});\n\nexport default function BubbleWrapDemo() {\n  return <BubbleWrap label=\"Unread notifications\" />;\n}\n"},{"path":"hooks/use-reduced-motion.ts","type":"registry:hook","target":"hooks/use-reduced-motion.ts","content":"\"use client\";\n\nimport { useSyncExternalStore } from \"react\";\n\n// Motion's useReducedMotion reads the media query on the very first client\n// render, but the server can't know it, so every component that renders\n// differently under reduced motion broke hydration for those users. This\n// reports false during hydration, matching the server HTML, then the real\n// preference straight after, and follows it if it changes.\nconst query = \"(prefers-reduced-motion: reduce)\";\n\nfunction subscribe(onChange: () => void) {\n  const media = window.matchMedia(query);\n  media.addEventListener(\"change\", onChange);\n  return () => media.removeEventListener(\"change\", onChange);\n}\n\nexport function useReducedMotion() {\n  return useSyncExternalStore(\n    subscribe,\n    () => window.matchMedia(query).matches,\n    () => false,\n  );\n}\n"}],"cssVars":{"light":{"shadow-raised":"0 0 0 1px oklch(0 0 0 / 0.06), 0 1px 2px oklch(0 0 0 / 0.06), 0 6px 16px -6px oklch(0 0 0 / 0.12)"},"dark":{"shadow-raised":"0 0 0 1px oklch(1 0 0 / 0.08), 0 1px 2px oklch(0 0 0 / 0.4), 0 6px 16px -6px oklch(0 0 0 / 0.6)"},"theme":{"shadow-raised":"var(--shadow-raised)"}},"categories":["objects"],"docs":"From ui lab: https://lab.xevrion.dev/lab/bubble-wrap"}