{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "bubble-wrap",
  "title": "Bubble Wrap",
  "description": "A sheet of plastic air cells to press or sweep across. Each bubble squashes, pops with a short falling sound and a light haptic tick, and stays flat until the cleared sheet re-inflates in a ripple.",
  "dependencies": [
    "@rexa-developer/tiks",
    "motion",
    "web-haptics"
  ],
  "files": [
    {
      "path": "src/registry/components/bubble-wrap/bubble-wrap.tsx",
      "content": "\"use client\";\n\nimport { useTiks } from \"@rexa-developer/tiks/react\";\nimport {\n\ttype AnimationPlaybackControls,\n\tanimate,\n\ttype Easing,\n\tuseReducedMotion,\n} from \"motion/react\";\nimport {\n\ttype ComponentProps,\n\ttype CSSProperties,\n\ttype KeyboardEvent,\n\ttype MouseEvent,\n\tmemo,\n\ttype PointerEvent,\n\ttype Ref,\n\tuseEffect,\n\tuseId,\n\tuseImperativeHandle,\n\tuseLayoutEffect,\n\tuseRef,\n\tuseState,\n} from \"react\";\nimport { useWebHaptics } from \"web-haptics/react\";\nimport { cn } from \"@/lib/utils\";\n\n/** Smallest a bubble may get, in px. Columns drop on narrow sheets to keep it. */\nconst MIN_CELL_PX = 36;\n/** Largest a bubble gets at the sheet's default width, in px. */\nconst MAX_CELL_PX = 42;\nconst GAP_PX = 6;\nconst PADDING_PX = 12;\n/** A sweep pops a bubble once it passes this close to the center, as a fraction of the radius. */\nconst HIT_REACH = 0.92;\n/** Ripple delay per bubble of distance from its origin, and the longest delay, in ms. */\nconst RIPPLE_STEP_MS = 14;\nconst RIPPLE_MAX_MS = 320;\n/** Pause after the last pop before the sheet refills, in ms. */\nconst AUTO_RESET_MS = 900;\n/** Minimum ms between haptic ticks. */\nconst CUE_THROTTLE_MS = 35;\n/** Remaining counts are announced every this many bubbles. */\nconst ANNOUNCE_EVERY = 5;\n/** The clear flourish plays this long after the last pop, in ms. */\nconst FLOURISH_DELAY_MS = 120;\n\n/** Pop sound: a short sine thump that drops in pitch, under a filtered noise snap. */\nconst POP_SECONDS = 0.1;\nconst POP_START_HZ = 180;\nconst POP_END_HZ = 70;\nconst POP_SWEEP_SECONDS = 0.08;\nconst POP_PITCH_JITTER = 0.12;\n/** Fewest seconds between two pop sounds, and the most that may ring at once. */\nconst POP_MIN_GAP = 0.016;\nconst MAX_VOICES = 6;\n/** A pop that would start this many seconds late is dropped instead. */\nconst POP_MAX_LAG = 0.05;\n\n// A soft, low falling tick (tiks' toggle-off cue) for a cleared sheet.\nconst CLEAR_SOUND = {\n\tname: \"bubble-wrap-clear\",\n\tbaseFreq: 262,\n\tnoiseColor: \"pink\",\n\toscType: \"sine\",\n\tfilterFreq: 1200,\n\tfilterQ: 1,\n\tattack: 0.012,\n\tdecay: 4,\n\tbrightness: 1500,\n} as const;\n\n/** Fast in, no tail: a press that bottoms out at once. */\nconst squashEase = [0.2, 0.9, 0.3, 1] as const;\n/** The dome giving way speeds up, like a seal letting go. */\nconst giveEase = [0.6, 0, 0.9, 0.4] as const;\nconst settleEase = [0.23, 1, 0.32, 1] as const;\n/** A pressure wave races out, then dies away slowly. */\nconst waveEase = [0.1, 0.8, 0.25, 1] as const;\n\ntype TintName = \"clear\" | \"blue\" | \"pink\";\n\n/** Film tint as RGB channels and strength; `clear` has none. */\nconst tints: Record<TintName, string> = {\n\tclear:\n\t\t\"[--bubble-wrap-tint:148_163_184] [--bubble-wrap-tint-a:0] dark:[--bubble-wrap-tint-a:0]\",\n\tblue: \"[--bubble-wrap-tint:96_165_250] [--bubble-wrap-tint-a:0.11] dark:[--bubble-wrap-tint-a:0.1]\",\n\tpink: \"[--bubble-wrap-tint:244_114_182] [--bubble-wrap-tint-a:0.1] dark:[--bubble-wrap-tint-a:0.09]\",\n};\n\n/**\n * Surface colors, light first. `ink` is the RGB of shadows, `band` of the\n * plastic bending toward the rim, and `line` of the dome's hairline edge. On a\n * light tray the rim darkens; on a dark tray it catches the light instead, and\n * the body stays nearly invisible so the domes never turn chalky.\n */\nconst surfaceVars =\n\t\"[--bubble-wrap-ink:28_25_22] [--bubble-wrap-line:36_38_46] [--bubble-wrap-line-a:0.3] [--bubble-wrap-band:28_25_22] [--bubble-wrap-band-a:0.13] [--bubble-wrap-body-a:0.14] [--bubble-wrap-fill-a:0.4] [--bubble-wrap-spec-a:1] [--bubble-wrap-caustic-a:0.85] [--bubble-wrap-shadow-a:0.13] [--bubble-wrap-foot-a:0.7] [--bubble-wrap-flat-a:0.42] [--bubble-wrap-flat-rim-a:0.85] [--bubble-wrap-crease-a:0.13] [--bubble-wrap-crease-light:0.85] [--bubble-wrap-grain-a:0.5] [--bubble-wrap-wave-dark:0.1] [--bubble-wrap-wave-light:0.95] dark:[--bubble-wrap-ink:0_0_0] dark:[--bubble-wrap-line:255_255_255] dark:[--bubble-wrap-line-a:0.24] dark:[--bubble-wrap-band:255_255_255] dark:[--bubble-wrap-band-a:0.06] dark:[--bubble-wrap-body-a:0.05] dark:[--bubble-wrap-fill-a:0.08] dark:[--bubble-wrap-spec-a:0.8] dark:[--bubble-wrap-caustic-a:0.2] dark:[--bubble-wrap-shadow-a:0.5] dark:[--bubble-wrap-foot-a:0.07] dark:[--bubble-wrap-flat-a:0.055] dark:[--bubble-wrap-flat-rim-a:0.1] dark:[--bubble-wrap-crease-a:0.5] dark:[--bubble-wrap-crease-light:0.13] dark:[--bubble-wrap-grain-a:0.14] dark:[--bubble-wrap-wave-dark:0.45] dark:[--bubble-wrap-wave-light:0.2]\";\n\n/** A fine, tiling grain for the film, as a tiny inline SVG. */\nconst grain =\n\t\"url(\\\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='72' height='72'%3E%3Cfilter id='g'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.95' numOctaves='2' stitchTiles='stitch'/%3E%3CfeColorMatrix values='0 0 0 0 0.5 0 0 0 0 0.5 0 0 0 0 0.5 0 0 0 0.9 -0.3'/%3E%3C/filter%3E%3Crect width='72' height='72' filter='url(%23g)'/%3E%3C/svg%3E\\\")\";\n\nconst domeBodyStyle: CSSProperties = {\n\tbackground: [\n\t\t// Soft fill: the window's glow spread across the upper dome.\n\t\t\"radial-gradient(52% 44% at 34% 27%, rgb(255 255 255 / var(--bubble-wrap-fill-a)), rgb(255 255 255 / 0) 100%)\",\n\t\t// Clear in the middle; the plastic thickens and bends toward the rim and\n\t\t// ends in a thin hairline.\n\t\t\"radial-gradient(closest-side, rgb(var(--bubble-wrap-band) / 0) 60%, rgb(var(--bubble-wrap-band) / calc(var(--bubble-wrap-band-a) * 0.4)) 80%, rgb(var(--bubble-wrap-band) / var(--bubble-wrap-band-a)) 93%, rgb(var(--bubble-wrap-line) / var(--bubble-wrap-line-a)) 98.5%, rgb(var(--bubble-wrap-line) / 0) 100%)\",\n\t\t// The film's tint, densest where the plastic is thickest.\n\t\t\"radial-gradient(closest-side, rgb(var(--bubble-wrap-tint) / calc(var(--bubble-wrap-tint-a) * 0.3)) 30%, rgb(var(--bubble-wrap-tint) / calc(var(--bubble-wrap-tint-a) * 1.5)) 100%)\",\n\t\t\"linear-gradient(160deg, rgb(255 255 255 / var(--bubble-wrap-body-a)) 12%, rgb(255 255 255 / 0) 62%)\",\n\t].join(\", \"),\n};\n\nconst flatStyle: CSSProperties = {\n\tbackgroundImage: [\n\t\t// A flatter, sealed rim where the dome used to stand.\n\t\t\"radial-gradient(closest-side, rgb(255 255 255 / 0) 80%, rgb(255 255 255 / calc(var(--bubble-wrap-flat-rim-a) * 0.6)) 92%, rgb(var(--bubble-wrap-ink) / calc(var(--bubble-wrap-crease-a) * 0.7)) 100%)\",\n\t\t\"radial-gradient(closest-side, rgb(var(--bubble-wrap-tint) / calc(var(--bubble-wrap-tint-a) * 0.5)), rgb(var(--bubble-wrap-tint) / calc(var(--bubble-wrap-tint-a) * 1.1)))\",\n\t\t// Cloudy, stretched film.\n\t\t\"radial-gradient(closest-side at 54% 46%, rgb(255 255 255 / calc(var(--bubble-wrap-flat-a) * 0.55)), rgb(255 255 255 / var(--bubble-wrap-flat-a)))\",\n\t].join(\", \"),\n\tboxShadow: [\n\t\t\"inset 0 0 0 0.5px rgb(var(--bubble-wrap-line) / calc(var(--bubble-wrap-line-a) * 0.6))\",\n\t\t\"inset 0.5px 1px 1.5px rgb(var(--bubble-wrap-ink) / calc(var(--bubble-wrap-crease-a) * 0.9))\",\n\t\t\"0 0.5px 0 rgb(255 255 255 / calc(var(--bubble-wrap-flat-rim-a) * 0.5))\",\n\t].join(\", \"),\n};\n\n/**\n * The wrinkles of one popped bubble, in a 100 × 100 box: curved folds\n * radiating from an off-center tear, with soft facets between them. Hashed\n * by index, so each popped bubble creases its own way.\n */\nfunction wrinkles(index: number) {\n\tconst cx = 50 + hashUnit(index, 3) * 7;\n\tconst cy = 48 + hashUnit(index, 4) * 7;\n\tconst at = (radius: number, degrees: number) => {\n\t\tconst radians = (degrees * Math.PI) / 180;\n\t\treturn `${(cx + Math.cos(radians) * radius).toFixed(1)} ${(cy + Math.sin(radians) * radius).toFixed(1)}`;\n\t};\n\tconst count = 5 + Math.round(Math.abs(hashUnit(index, 5)) * 2);\n\tconst start = hashUnit(index, 2) * 180;\n\tlet folds = \"\";\n\tlet facets = \"\";\n\tfor (let fold = 0; fold < count; fold++) {\n\t\tconst angle =\n\t\t\tstart + (fold * 360) / count + hashUnit(index, 20 + fold) * 22;\n\t\tconst bend = hashUnit(index, 40 + fold) * 14;\n\t\tconst inner = 3 + Math.abs(hashUnit(index, 50 + fold)) * 8;\n\t\tconst reach = 22 + Math.abs(hashUnit(index, 30 + fold)) * 22;\n\t\tfolds += `M${at(inner, angle)}Q${at((inner + reach) / 2, angle + bend)} ${at(reach, angle + bend * 0.2)}`;\n\t\t// Soft facets between folds: one side lit, the other shaded.\n\t\tconst shade =\n\t\t\tfold % 2\n\t\t\t\t? \"255 255 255 / calc(var(--bubble-wrap-crease-light) * 0.55)\"\n\t\t\t\t: \"var(--bubble-wrap-ink) / calc(var(--bubble-wrap-crease-a) * 0.7)\";\n\t\tfacets += `, rgb(${shade}) ${(angle - start + 180 / count).toFixed(1)}deg`;\n\t}\n\tconst facetStyle: CSSProperties = {\n\t\tbackground: `conic-gradient(from ${start.toFixed(1)}deg at ${cx.toFixed(1)}% ${cy.toFixed(1)}%${facets}, rgb(255 255 255 / 0) 360deg)`,\n\t};\n\treturn { folds, tear: { cx, cy }, facetStyle };\n}\n\n/** A slightly uneven outline for each popped bubble, so no two look stamped. */\nfunction slackOutline(index: number) {\n\tconst a = 50 + hashUnit(index, 8) * 5;\n\tconst b = 50 + hashUnit(index, 9) * 5;\n\tconst c = 50 + hashUnit(index, 10) * 5;\n\tconst d = 50 + hashUnit(index, 11) * 5;\n\treturn `${a}% ${100 - a}% ${b}% ${100 - b}% / ${c}% ${d}% ${100 - d}% ${100 - c}%`;\n}\n\nfunction clamp(value: number, min: number, max: number) {\n\treturn Math.min(Math.max(value, min), max);\n}\n\n/** A fixed value in [-1, 1] for each index, so jitter is the same on server and client. */\nfunction hashUnit(index: number, salt: number) {\n\tlet state = Math.imul(index + 1, 0x9e3779b1) ^ Math.imul(salt, 0x85ebca6b);\n\tstate = Math.imul(state ^ (state >>> 15), 0x2c1b3c6d);\n\tstate = Math.imul(state ^ (state >>> 12), 0x297a2d39);\n\tstate ^= state >>> 15;\n\treturn ((state >>> 0) / 4294967295) * 2 - 1;\n}\n\nfunction columnsFor(width: number, columns: number) {\n\tif (width <= 0) return columns;\n\tconst fit = Math.floor((width + GAP_PX) / (MIN_CELL_PX + GAP_PX));\n\treturn clamp(fit, 1, columns);\n}\n\n/** Squared distance from (px, py) to the segment from (ax, ay) to (bx, by), and where along it. */\nfunction segmentHit(\n\tax: number,\n\tay: number,\n\tbx: number,\n\tby: number,\n\tpx: number,\n\tpy: number,\n) {\n\tconst dx = bx - ax;\n\tconst dy = by - ay;\n\tconst length = dx * dx + dy * dy;\n\tconst t = length\n\t\t? clamp(((px - ax) * dx + (py - ay) * dy) / length, 0, 1)\n\t\t: 0;\n\tconst x = ax + dx * t - px;\n\tconst y = ay + dy * t - py;\n\treturn { distance: x * x + y * y, t };\n}\n\ntype Keyframes = Record<string, (number | null)[]>;\n\ninterface HeldTiming {\n\tduration: number;\n\ttimes: number[];\n\tease: Easing[];\n}\n\n/**\n * Runs `keyframes` after `delayMs`, holding the first keyframe during the\n * delay. Holding (rather than a plain delay) means the bubble keeps its old\n * look until its turn in a ripple, even though its state already changed.\n */\nfunction animateHeld(\n\telement: HTMLElement,\n\tkeyframes: Keyframes,\n\t{ duration, times, ease }: HeldTiming,\n\tdelayMs: number,\n) {\n\tconst delay = delayMs / 1000;\n\tif (delay <= 0) {\n\t\treturn animate(element, keyframes, { duration, times, ease });\n\t}\n\tconst total = delay + duration;\n\tconst held: Keyframes = {};\n\tfor (const [key, values] of Object.entries(keyframes)) {\n\t\theld[key] = [values[0] ?? null, ...values];\n\t}\n\treturn animate(element, held, {\n\t\tduration: total,\n\t\ttimes: [0, ...times.map((time) => (delay + time * duration) / total)],\n\t\tease: [\"linear\", ...ease],\n\t});\n}\n\ninterface PopAudio {\n\tctx: AudioContext;\n\toutput: GainNode;\n\tnoise: AudioBuffer;\n\t/** End times of the pops still ringing, in context seconds. */\n\tvoices: number[];\n\tlastStart: number;\n}\n\nlet popAudio: PopAudio | null = null;\n\n/** One shared context for every sheet, created on the first press (a user gesture). */\nfunction getPopAudio() {\n\tif (popAudio && popAudio.ctx.state !== \"closed\") return popAudio;\n\tconst AudioContextClass =\n\t\twindow.AudioContext ??\n\t\t(window as unknown as { webkitAudioContext?: typeof AudioContext })\n\t\t\t.webkitAudioContext;\n\tif (!AudioContextClass) return null;\n\tconst ctx = new AudioContextClass();\n\t// A limiter after the mix, so a burst of pops never clips.\n\tconst limiter = ctx.createDynamicsCompressor();\n\tlimiter.threshold.value = -8;\n\tlimiter.knee.value = 4;\n\tlimiter.ratio.value = 12;\n\tlimiter.attack.value = 0.002;\n\tlimiter.release.value = 0.08;\n\tlimiter.connect(ctx.destination);\n\tconst output = ctx.createGain();\n\toutput.gain.value = 0.7;\n\toutput.connect(limiter);\n\tconst noise = ctx.createBuffer(\n\t\t1,\n\t\tMath.floor(ctx.sampleRate * 0.25),\n\t\tctx.sampleRate,\n\t);\n\tconst data = noise.getChannelData(0);\n\tfor (let index = 0; index < data.length; index++) {\n\t\tdata[index] = Math.random() * 2 - 1;\n\t}\n\tpopAudio = {\n\t\tctx,\n\t\toutput,\n\t\tnoise,\n\t\tvoices: [],\n\t\tlastStart: Number.NEGATIVE_INFINITY,\n\t};\n\treturn popAudio;\n}\n\n/**\n * Plays one pop, `delay` seconds from now. Pops are spaced at least\n * `POP_MIN_GAP` apart and at most `MAX_VOICES` ring at once; a pop that\n * can't fit soon enough is dropped. Every envelope starts and ends at zero.\n */\nfunction playPop(audio: PopAudio, delay = 0, loudness = 1) {\n\tconst { ctx } = audio;\n\tif (ctx.state === \"suspended\") void ctx.resume().catch(() => {});\n\tconst wanted = ctx.currentTime + 0.005 + delay;\n\tconst start = Math.max(wanted, audio.lastStart + POP_MIN_GAP);\n\tif (start - wanted > POP_MAX_LAG) return;\n\taudio.voices = audio.voices.filter((end) => end > start);\n\tif (audio.voices.length >= MAX_VOICES) return;\n\tconst end = start + POP_SECONDS;\n\taudio.voices.push(end + 0.01);\n\taudio.lastStart = start;\n\n\t// Each pop is a little higher or lower, so a sweep never sounds mechanical.\n\tconst pitch = 1 + (Math.random() * 2 - 1) * POP_PITCH_JITTER;\n\tconst level = loudness * (0.85 + Math.random() * 0.3);\n\n\tconst body = ctx.createOscillator();\n\tbody.type = \"sine\";\n\tbody.frequency.setValueAtTime(POP_START_HZ * pitch, start);\n\tbody.frequency.exponentialRampToValueAtTime(\n\t\tPOP_END_HZ * pitch,\n\t\tstart + POP_SWEEP_SECONDS,\n\t);\n\tconst bodyGain = ctx.createGain();\n\tbodyGain.gain.setValueAtTime(0, start);\n\tbodyGain.gain.linearRampToValueAtTime(0.55 * level, start + 0.003);\n\tbodyGain.gain.exponentialRampToValueAtTime(0.001, start + POP_SECONDS - 0.01);\n\tbodyGain.gain.linearRampToValueAtTime(0, start + POP_SECONDS);\n\tbody.connect(bodyGain);\n\tbodyGain.connect(audio.output);\n\tbody.start(start);\n\tbody.stop(end + 0.01);\n\n\t// The snap of the film giving way: a few ms of band-passed noise.\n\tconst snap = ctx.createBufferSource();\n\tsnap.buffer = audio.noise;\n\tconst band = ctx.createBiquadFilter();\n\tband.type = \"bandpass\";\n\tband.frequency.value = 1700 * pitch;\n\tband.Q.value = 1.1;\n\tconst snapGain = ctx.createGain();\n\tsnapGain.gain.setValueAtTime(0, start);\n\tsnapGain.gain.linearRampToValueAtTime(0.42 * level, start + 0.002);\n\tsnapGain.gain.exponentialRampToValueAtTime(0.001, start + 0.035);\n\tsnapGain.gain.linearRampToValueAtTime(0, start + 0.04);\n\tsnap.connect(band);\n\tband.connect(snapGain);\n\tsnapGain.connect(audio.output);\n\tconst offset = Math.random() * (audio.noise.duration - 0.06);\n\tsnap.start(start, offset, 0.045);\n}\n\ninterface Sweep {\n\tpointerId: number;\n\t/** Last pointer position, in client px relative to the grid. */\n\tx: number;\n\ty: number;\n\t/** Bubble centers relative to the grid, and the hit radius, in client px. */\n\tcenters: { x: number; y: number }[];\n\tradius: number;\n}\n\nexport interface BubbleWrapHandle {\n\t/** Re-inflates every bubble with a ripple. Silent. */\n\treset: () => void;\n\t/** Pops every bubble with a ripple. Silent. */\n\tpopAll: () => void;\n}\n\nexport interface BubbleWrapProps\n\textends Omit<ComponentProps<\"div\">, \"children\" | \"ref\"> {\n\t/** Rows of bubbles. */\n\trows?: number;\n\t/** Columns of bubbles. On narrow sheets fewer columns fit, and the bubbles wrap onto more rows. */\n\tcolumns?: number;\n\t/** Indexes of bubbles that start out popped, for example `[2, 9, 15]`. Read on mount. */\n\tdefaultPopped?: number[];\n\t/** Subtle tint of the plastic film. */\n\ttint?: TintName;\n\t/** Called once for each bubble that pops, with its index. */\n\tonPop?: (index: number) => void;\n\t/** Called once when the last bubble pops. */\n\tonClear?: () => void;\n\t/** Re-inflate the sheet shortly after every bubble is popped. */\n\tautoReset?: boolean;\n\t/** Show how many bubbles are popped under the sheet. */\n\tshowCount?: boolean;\n\t/** Play a pop sound for each bubble and a soft flourish on a full clear. */\n\tsound?: boolean;\n\t/** Trigger haptics on supported devices. */\n\thaptics?: boolean;\n\tref?: Ref<BubbleWrapHandle>;\n}\n\ninterface BubbleProps {\n\tindex: number;\n\tcount: number;\n\tpopped: boolean;\n\tfocusable: boolean;\n\tregister: (index: number, element: HTMLButtonElement | null) => void;\n\tonActivate: (index: number) => void;\n\tonFocusCell: (index: number) => void;\n}\n\nconst Bubble = memo(function Bubble({\n\tindex,\n\tcount,\n\tpopped,\n\tfocusable,\n\tregister,\n\tonActivate,\n\tonFocusCell,\n}: BubbleProps) {\n\t// A bubble's wrinkles and outline never change, so build them once.\n\tconst [creases] = useState(() => wrinkles(index));\n\tconst [outline] = useState(() => slackOutline(index));\n\n\treturn (\n\t\t<button\n\t\t\tref={(element) => register(index, element)}\n\t\t\ttype=\"button\"\n\t\t\ttabIndex={focusable ? 0 : -1}\n\t\t\taria-pressed={popped}\n\t\t\taria-label={`Bubble ${index + 1} of ${count}`}\n\t\t\tdata-bubble-index={index}\n\t\t\tdata-state={popped ? \"popped\" : \"inflated\"}\n\t\t\tonClick={(event: MouseEvent<HTMLButtonElement>) => {\n\t\t\t\t// Pointer presses pop on pointer down; this is the keyboard and screen reader path.\n\t\t\t\tif (event.detail === 0) onActivate(index);\n\t\t\t}}\n\t\t\tonFocus={() => onFocusCell(index)}\n\t\t\tclassName=\"group/bubble relative aspect-square cursor-pointer rounded-full outline-none [-webkit-tap-highlight-color:transparent] focus-visible:z-10 data-[state=popped]:cursor-default\"\n\t\t>\n\t\t\t<span\n\t\t\t\tdata-part=\"flat\"\n\t\t\t\taria-hidden\n\t\t\t\tclassName=\"pointer-events-none absolute inset-[7%] overflow-hidden opacity-0 group-data-[state=popped]/bubble:opacity-100\"\n\t\t\t\tstyle={{ ...flatStyle, borderRadius: outline }}\n\t\t\t>\n\t\t\t\t<span\n\t\t\t\t\tclassName=\"absolute inset-0 bg-size-[72px_72px] opacity-(--bubble-wrap-grain-a) mix-blend-overlay\"\n\t\t\t\t\tstyle={{ backgroundImage: grain }}\n\t\t\t\t/>\n\t\t\t\t<span\n\t\t\t\t\tclassName=\"absolute inset-0 blur-[1px]\"\n\t\t\t\t\tstyle={creases.facetStyle}\n\t\t\t\t/>\n\t\t\t\t<svg\n\t\t\t\t\tviewBox=\"0 0 100 100\"\n\t\t\t\t\tclassName=\"absolute inset-0 size-full fill-none blur-[0.3px]\"\n\t\t\t\t\tstrokeLinecap=\"round\"\n\t\t\t\t\tstrokeLinejoin=\"round\"\n\t\t\t\t>\n\t\t\t\t\t{/* Each fold is a lit ridge beside a shaded crease. */}\n\t\t\t\t\t<g\n\t\t\t\t\t\ttransform=\"translate(-0.9 -0.9)\"\n\t\t\t\t\t\tstrokeWidth={2.4}\n\t\t\t\t\t\tstyle={{\n\t\t\t\t\t\t\tstroke:\n\t\t\t\t\t\t\t\t\"rgb(255 255 255 / calc(var(--bubble-wrap-crease-light) * 0.6))\",\n\t\t\t\t\t\t}}\n\t\t\t\t\t>\n\t\t\t\t\t\t<path d={creases.folds} />\n\t\t\t\t\t</g>\n\t\t\t\t\t<g\n\t\t\t\t\t\tstrokeWidth={1}\n\t\t\t\t\t\tstyle={{\n\t\t\t\t\t\t\tstroke:\n\t\t\t\t\t\t\t\t\"rgb(var(--bubble-wrap-ink) / var(--bubble-wrap-crease-a))\",\n\t\t\t\t\t\t}}\n\t\t\t\t\t>\n\t\t\t\t\t\t<path d={creases.folds} />\n\t\t\t\t\t</g>\n\t\t\t\t\t<ellipse\n\t\t\t\t\t\tcx={creases.tear.cx}\n\t\t\t\t\t\tcy={creases.tear.cy}\n\t\t\t\t\t\trx={2.6}\n\t\t\t\t\t\try={1.8}\n\t\t\t\t\t\tstyle={{\n\t\t\t\t\t\t\tfill: \"rgb(var(--bubble-wrap-ink) / calc(var(--bubble-wrap-crease-a) * 0.8))\",\n\t\t\t\t\t\t}}\n\t\t\t\t\t/>\n\t\t\t\t</svg>\n\t\t\t</span>\n\t\t\t<span\n\t\t\t\tdata-part=\"dome\"\n\t\t\t\taria-hidden\n\t\t\t\tclassName=\"pointer-events-none absolute inset-0 rounded-full group-data-[state=popped]/bubble:opacity-0\"\n\t\t\t>\n\t\t\t\t{/* The dome's shadow on the tray. The dome itself is clear, so only the\n\t\t\t\t    crescent outside it shows, and light focused through the air pools\n\t\t\t\t    on the tray inside it. */}\n\t\t\t\t<span className=\"mask-[radial-gradient(closest-side_at_44%_41%,transparent_76%,#000_120%)] absolute inset-[2%] translate-x-[6%] translate-y-[9%] rounded-full bg-[rgb(var(--bubble-wrap-ink)/var(--bubble-wrap-shadow-a))] blur-[5px]\" />\n\t\t\t\t<span className=\"absolute top-[50%] left-[42%] h-[32%] w-[42%] -rotate-[38deg] rounded-[50%] bg-[radial-gradient(closest-side,rgb(255_255_255/var(--bubble-wrap-caustic-a)),rgb(255_255_255/0))] blur-[2px]\" />\n\t\t\t\t{/* Where the film lifts off the sheet, catching the light. */}\n\t\t\t\t<span className=\"absolute -inset-[2%] rounded-full shadow-[-0.5px_-0.75px_1.5px_rgb(255_255_255/var(--bubble-wrap-foot-a))]\" />\n\t\t\t\t<span className=\"absolute inset-0 rounded-full\" style={domeBodyStyle} />\n\t\t\t\t{/* Light caught along the inside of the lower rim. */}\n\t\t\t\t<span className=\"absolute inset-[6%] rounded-full shadow-[inset_-1.5px_-2px_2px_-1px_rgb(255_255_255/var(--bubble-wrap-caustic-a))]\" />\n\t\t\t\t{/* One crisp reflection of a window. */}\n\t\t\t\t<span className=\"absolute top-[16%] left-[23%] h-[13%] w-[28%] -rotate-[34deg] rounded-[50%] bg-[radial-gradient(closest-side,rgb(255_255_255/var(--bubble-wrap-spec-a))_58%,rgb(255_255_255/0))]\" />\n\t\t\t</span>\n\t\t\t<span\n\t\t\t\tdata-part=\"ring\"\n\t\t\t\taria-hidden\n\t\t\t\tclassName=\"pointer-events-none absolute -inset-[4%] rounded-full bg-[radial-gradient(closest-side,rgb(var(--bubble-wrap-ink)/0)_70%,rgb(var(--bubble-wrap-ink)/var(--bubble-wrap-wave-dark))_83%,rgb(255_255_255/var(--bubble-wrap-wave-light))_91%,rgb(255_255_255/0))] opacity-0\"\n\t\t\t/>\n\t\t\t<span\n\t\t\t\taria-hidden\n\t\t\t\tclassName=\"pointer-events-none absolute inset-0 rounded-full opacity-0 shadow-[0_0_0_2px_#fff,0_0_0_4px_#18181b] group-focus-visible/bubble:opacity-100\"\n\t\t\t/>\n\t\t</button>\n\t);\n});\n\nexport function BubbleWrap({\n\trows = 5,\n\tcolumns = 6,\n\tdefaultPopped,\n\ttint = \"clear\",\n\tonPop,\n\tonClear,\n\tautoReset = true,\n\tshowCount = false,\n\tsound = true,\n\thaptics = true,\n\tclassName,\n\tstyle,\n\tref,\n\t\"aria-label\": ariaLabel,\n\t\"aria-labelledby\": ariaLabelledBy,\n\tonKeyDown,\n\t...props\n}: BubbleWrapProps) {\n\tconst columnCount = Math.max(1, Math.floor(columns) || 1);\n\tconst rowCount = Math.max(1, Math.floor(rows) || 1);\n\tconst count = columnCount * rowCount;\n\n\tconst [initialPopped] = useState(() =>\n\t\tArray.from({ length: count }, (_, index) =>\n\t\t\tBoolean(defaultPopped?.includes(index)),\n\t\t),\n\t);\n\tconst [popped, setPopped] = useState(initialPopped);\n\tconst [fitColumns, setFitColumns] = useState(columnCount);\n\tconst [activeIndex, setActiveIndex] = useState(0);\n\tconst [announcement, setAnnouncement] = useState(\"\");\n\n\tconst reducedMotion = useReducedMotion() ?? false;\n\tconst { trigger: haptic } = useWebHaptics();\n\t// Sound stays on under reduced motion; only movement is reduced.\n\tconst { toggle: playToggle } = useTiks({\n\t\ttheme: CLEAR_SOUND,\n\t\trespectReducedMotion: false,\n\t});\n\n\tconst id = useId();\n\tconst titleId = `${id}-title`;\n\tconst countId = `${id}-count`;\n\n\tconst rootRef = useRef<HTMLDivElement>(null);\n\tconst gridRef = useRef<HTMLDivElement>(null);\n\tconst cellsRef = useRef<(HTMLButtonElement | null)[]>([]);\n\tconst poppedRef = useRef<boolean[]>(initialPopped.slice());\n\tconst clearedRef = useRef(initialPopped.every(Boolean));\n\tconst lastPoppedRef = useRef(defaultPopped?.at(-1) ?? 0);\n\tconst sweepRef = useRef<Sweep | null>(null);\n\tconst animationsRef = useRef(new Map<number, AnimationPlaybackControls[]>());\n\t/** Bubbles whose re-inflate animation is still running. */\n\tconst inflatingRef = useRef(new Set<number>());\n\tconst resetTimerRef = useRef<number | undefined>(undefined);\n\tconst flourishTimerRef = useRef<number | undefined>(undefined);\n\tconst lastHapticAtRef = useRef(Number.NEGATIVE_INFINITY);\n\tconst fitColumnsRef = useRef(fitColumns);\n\n\t// Event handlers and timers read the latest props through refs.\n\tconst latest = useRef({\n\t\tonPop,\n\t\tonClear,\n\t\tautoReset,\n\t\tsound,\n\t\thaptics,\n\t\treducedMotion,\n\t});\n\tuseLayoutEffect(() => {\n\t\tfitColumnsRef.current = fitColumns;\n\t\tlatest.current = {\n\t\t\tonPop,\n\t\t\tonClear,\n\t\t\tautoReset,\n\t\t\tsound,\n\t\t\thaptics,\n\t\t\treducedMotion,\n\t\t};\n\t});\n\n\tconst silent = () =>\n\t\ttypeof document !== \"undefined\" && document.visibilityState === \"hidden\";\n\n\tconst commit = () => setPopped(poppedRef.current.slice());\n\n\t// A new size keeps each bubble's state by index; added bubbles start inflated.\n\tuseLayoutEffect(() => {\n\t\tconst current = poppedRef.current;\n\t\tif (current.length === count) return;\n\t\tconst next = Array.from({ length: count }, (_, index) =>\n\t\t\tBoolean(current[index]),\n\t\t);\n\t\tpoppedRef.current = next;\n\t\tcellsRef.current.length = count;\n\t\tclearedRef.current = next.every(Boolean);\n\t\tsetPopped(next.slice());\n\t\tsetActiveIndex((index) => Math.min(index, count - 1));\n\t}, [count]);\n\n\t// Fewer columns fit on narrow sheets, so no bubble shrinks below MIN_CELL_PX.\n\tuseLayoutEffect(() => {\n\t\tconst grid = gridRef.current;\n\t\tif (!grid) return;\n\t\tconst update = () =>\n\t\t\tsetFitColumns(columnsFor(grid.clientWidth, columnCount));\n\t\tupdate();\n\t\tconst observer = new ResizeObserver(update);\n\t\tobserver.observe(grid);\n\t\treturn () => observer.disconnect();\n\t}, [columnCount]);\n\n\tuseEffect(\n\t\t() => () => {\n\t\t\twindow.clearTimeout(resetTimerRef.current);\n\t\t\twindow.clearTimeout(flourishTimerRef.current);\n\t\t\tfor (const controls of animationsRef.current.values()) {\n\t\t\t\tfor (const control of controls) control.stop();\n\t\t\t}\n\t\t},\n\t\t[],\n\t);\n\n\tconst parts = (index: number) => {\n\t\tconst cell = cellsRef.current[index];\n\t\tif (!cell) return null;\n\t\tconst dome = cell.querySelector<HTMLElement>('[data-part=\"dome\"]');\n\t\tconst flat = cell.querySelector<HTMLElement>('[data-part=\"flat\"]');\n\t\tconst ring = cell.querySelector<HTMLElement>('[data-part=\"ring\"]');\n\t\tif (!dome || !flat || !ring) return null;\n\t\treturn { dome, flat, ring };\n\t};\n\n\tconst stopAnimations = (index: number) => {\n\t\tconst controls = animationsRef.current.get(index);\n\t\tif (controls) for (const control of controls) control.stop();\n\t\tanimationsRef.current.delete(index);\n\t\tinflatingRef.current.delete(index);\n\t};\n\n\tconst animatePop = (index: number, delay: number) => {\n\t\tstopAnimations(index);\n\t\tconst elements = parts(index);\n\t\tif (!elements) return;\n\t\tconst { dome, flat, ring } = elements;\n\t\tif (latest.current.reducedMotion) {\n\t\t\tanimationsRef.current.set(index, [\n\t\t\t\tanimate(dome, { opacity: 0, scale: 1, rotate: 0 }, { duration: 0 }),\n\t\t\t\tanimate(flat, { opacity: 1, scale: 1 }, { duration: 0 }),\n\t\t\t\tanimate(ring, { opacity: 0 }, { duration: 0 }),\n\t\t\t]);\n\t\t\treturn;\n\t\t}\n\t\tconst jitter = hashUnit(index, 1) * 4;\n\t\tanimationsRef.current.set(index, [\n\t\t\t// A quick squash with a little twist, then the dome gives way.\n\t\t\tanimateHeld(\n\t\t\t\tdome,\n\t\t\t\t{\n\t\t\t\t\tscale: [null, 0.88, 0.8],\n\t\t\t\t\trotate: [null, jitter, jitter * 1.5],\n\t\t\t\t\t// Explicit, since the popped state already hides the dome in CSS.\n\t\t\t\t\topacity: [1, 1, 0],\n\t\t\t\t},\n\t\t\t\t{ duration: 0.12, times: [0, 0.55, 1], ease: [squashEase, giveEase] },\n\t\t\t\tdelay,\n\t\t\t),\n\t\t\t// The slack film spreads out flat and stops dead.\n\t\t\tanimateHeld(\n\t\t\t\tflat,\n\t\t\t\t{ opacity: [0, 0, 1], scale: [0.86, 0.86, 1] },\n\t\t\t\t{ duration: 0.2, times: [0, 0.3, 1], ease: [\"linear\", settleEase] },\n\t\t\t\tdelay,\n\t\t\t),\n\t\t\t// A pressure wave runs out through the film from the burst.\n\t\t\tanimateHeld(\n\t\t\t\tring,\n\t\t\t\t{ opacity: [0, 1, 0], scale: [0.9, 1.08, 1.5] },\n\t\t\t\t{ duration: 0.34, times: [0, 0.12, 1], ease: [\"easeOut\", waveEase] },\n\t\t\t\tdelay + 55,\n\t\t\t),\n\t\t]);\n\t};\n\n\tconst animateInflate = (index: number, delay: number) => {\n\t\tstopAnimations(index);\n\t\tconst elements = parts(index);\n\t\tif (!elements) return;\n\t\tconst { dome, flat, ring } = elements;\n\t\tinflatingRef.current.add(index);\n\t\tconst controls = latest.current.reducedMotion\n\t\t\t? [\n\t\t\t\t\tanimate(flat, { opacity: 0, scale: 1 }, { duration: 0 }),\n\t\t\t\t\tanimate(ring, { opacity: 0 }, { duration: 0 }),\n\t\t\t\t\tanimate(\n\t\t\t\t\t\tdome,\n\t\t\t\t\t\t{ opacity: [0, 1], scale: 1, rotate: 0 },\n\t\t\t\t\t\t{ duration: 0.2, ease: \"easeOut\" },\n\t\t\t\t\t),\n\t\t\t\t]\n\t\t\t: [\n\t\t\t\t\tanimate(ring, { opacity: 0 }, { duration: 0 }),\n\t\t\t\t\tanimateHeld(\n\t\t\t\t\t\tflat,\n\t\t\t\t\t\t{ opacity: [1, 0], scale: [1, 0.94] },\n\t\t\t\t\t\t{ duration: 0.14, times: [0, 1], ease: [\"easeOut\"] },\n\t\t\t\t\t\tdelay,\n\t\t\t\t\t),\n\t\t\t\t\t// Blooms back up past full, then settles dead still.\n\t\t\t\t\tanimateHeld(\n\t\t\t\t\t\tdome,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\topacity: [0, 1, 1, 1],\n\t\t\t\t\t\t\tscale: [0.72, 1.07, 0.99, 1],\n\t\t\t\t\t\t\trotate: [0, 0, 0, 0],\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tduration: 0.42,\n\t\t\t\t\t\t\ttimes: [0, 0.45, 0.75, 1],\n\t\t\t\t\t\t\tease: [settleEase, \"easeInOut\", \"easeOut\"],\n\t\t\t\t\t\t},\n\t\t\t\t\t\tdelay,\n\t\t\t\t\t),\n\t\t\t\t];\n\t\tanimationsRef.current.set(index, controls);\n\t\tvoid controls[controls.length - 1]?.finished.then(() => {\n\t\t\tif (animationsRef.current.get(index) === controls) {\n\t\t\t\tinflatingRef.current.delete(index);\n\t\t\t}\n\t\t});\n\t};\n\n\t/** Ripple delay of each bubble, by grid distance from `origin`. */\n\tconst rippleDelay = (index: number, origin: number) => {\n\t\tconst cols = fitColumnsRef.current;\n\t\tconst dx = (index % cols) - (origin % cols);\n\t\tconst dy = Math.floor(index / cols) - Math.floor(origin / cols);\n\t\treturn Math.min(Math.hypot(dx, dy) * RIPPLE_STEP_MS, RIPPLE_MAX_MS);\n\t};\n\n\tconst announceAfter = (before: number, after: number) => {\n\t\tif (after === 0) setAnnouncement(\"All popped\");\n\t\telse if (\n\t\t\tMath.floor((before - 1) / ANNOUNCE_EVERY) >\n\t\t\tMath.floor((after - 1) / ANNOUNCE_EVERY)\n\t\t) {\n\t\t\tsetAnnouncement(`${after} ${after === 1 ? \"bubble\" : \"bubbles\"} left`);\n\t\t}\n\t};\n\n\tconst scheduleAutoReset = (after: number) => {\n\t\twindow.clearTimeout(resetTimerRef.current);\n\t\tif (!latest.current.autoReset) return;\n\t\tresetTimerRef.current = window.setTimeout(() => {\n\t\t\tresetTimerRef.current = undefined;\n\t\t\tif (latest.current.autoReset) resetSheet(lastPoppedRef.current, true);\n\t\t}, after);\n\t};\n\n\t/**\n\t * Pops `indices` in order. With `ripple`, each waits for its distance from\n\t * the origin. `cue` plays sounds and haptics, for user input only.\n\t */\n\tconst pop = (\n\t\tindices: number[],\n\t\t{ cue, ripple }: { cue: boolean; ripple?: number },\n\t) => {\n\t\tconst state = poppedRef.current;\n\t\tconst delayOf = (index: number) =>\n\t\t\tripple === undefined ? 0 : rippleDelay(index, ripple);\n\t\tconst fresh = indices.filter((index) => index < count && !state[index]);\n\t\tif (!fresh.length) return;\n\t\t// Ripples pop, and schedule their sounds, nearest first.\n\t\tif (ripple !== undefined) fresh.sort((a, b) => delayOf(a) - delayOf(b));\n\t\tconst before = state.filter((value) => !value).length;\n\t\tconst {\n\t\t\tsound: soundOn,\n\t\t\thaptics: hapticsOn,\n\t\t\tonPop: handlePop,\n\t\t} = latest.current;\n\t\tconst audio = cue && soundOn && !silent() ? getPopAudio() : null;\n\t\tlet longest = 0;\n\t\tfor (const index of fresh) {\n\t\t\tstate[index] = true;\n\t\t\tconst delay = delayOf(index);\n\t\t\tlongest = Math.max(longest, delay);\n\t\t\tanimatePop(index, delay);\n\t\t\tif (audio) playPop(audio, delay / 1000, ripple === undefined ? 1 : 0.7);\n\t\t}\n\t\tlastPoppedRef.current = fresh[fresh.length - 1] ?? 0;\n\t\tcommit();\n\t\tfor (const index of fresh) handlePop?.(index);\n\n\t\tconst now = performance.now();\n\t\tif (\n\t\t\tcue &&\n\t\t\thapticsOn &&\n\t\t\t!silent() &&\n\t\t\tnow - lastHapticAtRef.current >= CUE_THROTTLE_MS\n\t\t) {\n\t\t\tlastHapticAtRef.current = now;\n\t\t\tvoid haptic(\"light\");\n\t\t}\n\n\t\tconst after = before - fresh.length;\n\t\tannounceAfter(before, after);\n\t\tif (after > 0 || clearedRef.current) return;\n\t\tclearedRef.current = true;\n\t\tlatest.current.onClear?.();\n\t\tif (cue && !silent()) {\n\t\t\twindow.clearTimeout(flourishTimerRef.current);\n\t\t\tflourishTimerRef.current = window.setTimeout(() => {\n\t\t\t\tif (latest.current.sound) playToggle(false);\n\t\t\t\tif (latest.current.haptics) void haptic(\"medium\");\n\t\t\t}, longest + FLOURISH_DELAY_MS);\n\t\t}\n\t\tscheduleAutoReset(longest + AUTO_RESET_MS);\n\t};\n\n\t/** Re-inflates popped bubbles, and restarts any ripple still running. Silent. */\n\tconst resetSheet = (origin: number, announce: boolean) => {\n\t\twindow.clearTimeout(resetTimerRef.current);\n\t\twindow.clearTimeout(flourishTimerRef.current);\n\t\tresetTimerRef.current = undefined;\n\t\tconst state = poppedRef.current;\n\t\tconst targets: number[] = [];\n\t\tfor (let index = 0; index < count; index++) {\n\t\t\tif (state[index] || inflatingRef.current.has(index)) targets.push(index);\n\t\t}\n\t\tclearedRef.current = false;\n\t\tif (!targets.length) return;\n\t\tconst wasPopped = state.some(Boolean);\n\t\tpoppedRef.current = Array(count).fill(false);\n\t\tfor (const index of targets)\n\t\t\tanimateInflate(index, rippleDelay(index, origin));\n\t\tcommit();\n\t\tif (announce && wasPopped) setAnnouncement(\"New sheet\");\n\t};\n\n\tconst popAll = (origin: number, cue: boolean) => {\n\t\tconst all = Array.from({ length: count }, (_, index) => index);\n\t\tpop(all, { cue, ripple: origin });\n\t};\n\n\tconst resetRef = useRef(resetSheet);\n\tconst popAllRef = useRef(popAll);\n\tuseLayoutEffect(() => {\n\t\tresetRef.current = resetSheet;\n\t\tpopAllRef.current = popAll;\n\t});\n\n\tuseImperativeHandle(ref, () => ({\n\t\treset: () => resetRef.current(lastPoppedRef.current, true),\n\t\tpopAll: () => popAllRef.current(0, false),\n\t}));\n\n\t// Turning autoReset on while the sheet is clear refills it after the pause.\n\tuseEffect(() => {\n\t\tif (!autoReset) window.clearTimeout(resetTimerRef.current);\n\t\telse if (clearedRef.current && resetTimerRef.current === undefined) {\n\t\t\tresetTimerRef.current = window.setTimeout(() => {\n\t\t\t\tresetTimerRef.current = undefined;\n\t\t\t\tresetRef.current(lastPoppedRef.current, true);\n\t\t\t}, AUTO_RESET_MS);\n\t\t}\n\t}, [autoReset]);\n\n\tconst endSweep = () => {\n\t\tconst sweep = sweepRef.current;\n\t\tif (!sweep) return;\n\t\tsweepRef.current = null;\n\t\tconst grid = gridRef.current;\n\t\tif (grid?.hasPointerCapture(sweep.pointerId)) {\n\t\t\tgrid.releasePointerCapture(sweep.pointerId);\n\t\t}\n\t\tif (rootRef.current) delete rootRef.current.dataset.sweeping;\n\t};\n\n\t// iOS can still scroll the page under a captured pointer; block it mid-sweep.\n\tuseEffect(() => {\n\t\tconst grid = gridRef.current;\n\t\tif (!grid) return;\n\t\tconst onTouchMove = (event: TouchEvent) => {\n\t\t\tif (sweepRef.current) event.preventDefault();\n\t\t};\n\t\tgrid.addEventListener(\"touchmove\", onTouchMove, { passive: false });\n\t\treturn () => grid.removeEventListener(\"touchmove\", onTouchMove);\n\t}, []);\n\n\tconst onPointerDown = (event: PointerEvent<HTMLDivElement>) => {\n\t\t// One finger sweeps; a second one, or a right click, is ignored.\n\t\tif (!event.isPrimary || sweepRef.current) return;\n\t\tif (event.pointerType === \"mouse\" && event.button !== 0) return;\n\t\tconst grid = gridRef.current;\n\t\tif (!grid) return;\n\t\tconst rect = grid.getBoundingClientRect();\n\t\tconst centers: Sweep[\"centers\"] = [];\n\t\tlet radius = 0;\n\t\tfor (let index = 0; index < count; index++) {\n\t\t\tconst cell = cellsRef.current[index]?.getBoundingClientRect();\n\t\t\tif (!cell) {\n\t\t\t\tcenters.push({ x: Number.NaN, y: Number.NaN });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tcenters.push({\n\t\t\t\tx: cell.left + cell.width / 2 - rect.left,\n\t\t\t\ty: cell.top + cell.height / 2 - rect.top,\n\t\t\t});\n\t\t\tradius = Math.max(radius, (cell.width / 2) * HIT_REACH);\n\t\t}\n\t\tconst x = event.clientX - rect.left;\n\t\tconst y = event.clientY - rect.top;\n\t\tsweepRef.current = { pointerId: event.pointerId, x, y, centers, radius };\n\t\tgrid.setPointerCapture(event.pointerId);\n\t\tif (rootRef.current) rootRef.current.dataset.sweeping = \"\";\n\t\t// Create the audio context inside the gesture so the first pop can play.\n\t\tif (latest.current.sound) getPopAudio();\n\t\t// A press anywhere on a bubble's square pops it.\n\t\tconst target = (event.target as Element).closest<HTMLElement>(\n\t\t\t\"[data-bubble-index]\",\n\t\t);\n\t\tconst index = target ? Number(target.dataset.bubbleIndex) : -1;\n\t\tif (index >= 0) pop([index], { cue: true });\n\t};\n\n\tconst onPointerMove = (event: PointerEvent<HTMLDivElement>) => {\n\t\tconst sweep = sweepRef.current;\n\t\tif (!sweep || event.pointerId !== sweep.pointerId) return;\n\t\tconst grid = gridRef.current;\n\t\tconst root = rootRef.current;\n\t\tif (!grid || !root) return;\n\t\tconst rect = grid.getBoundingClientRect();\n\t\tconst native = event.nativeEvent;\n\t\tconst coalesced = native.getCoalescedEvents?.() ?? [];\n\t\tconst points = coalesced.length ? coalesced : [native];\n\t\tconst reach = sweep.radius * sweep.radius;\n\t\tconst state = poppedRef.current;\n\t\tconst hits: { index: number; at: number }[] = [];\n\t\t// Test each segment between pointer samples, so fast sweeps skip nothing.\n\t\tpoints.forEach((point, step) => {\n\t\t\tconst x = point.clientX - rect.left;\n\t\t\tconst y = point.clientY - rect.top;\n\t\t\tsweep.centers.forEach((center, index) => {\n\t\t\t\tif (state[index] || hits.some((hit) => hit.index === index)) return;\n\t\t\t\tconst hit = segmentHit(sweep.x, sweep.y, x, y, center.x, center.y);\n\t\t\t\tif (hit.distance <= reach) hits.push({ index, at: step + hit.t });\n\t\t\t});\n\t\t\tsweep.x = x;\n\t\t\tsweep.y = y;\n\t\t});\n\t\tif (hits.length) {\n\t\t\thits.sort((a, b) => a.at - b.at);\n\t\t\tpop(\n\t\t\t\thits.map((hit) => hit.index),\n\t\t\t\t{ cue: true },\n\t\t\t);\n\t\t}\n\t\t// Leaving the sheet ends the sweep.\n\t\tconst bounds = root.getBoundingClientRect();\n\t\tif (\n\t\t\tevent.clientX < bounds.left ||\n\t\t\tevent.clientX > bounds.right ||\n\t\t\tevent.clientY < bounds.top ||\n\t\t\tevent.clientY > bounds.bottom\n\t\t) {\n\t\t\tendSweep();\n\t\t}\n\t};\n\n\tconst onPointerEnd = (event: PointerEvent<HTMLDivElement>) => {\n\t\tif (sweepRef.current?.pointerId !== event.pointerId) return;\n\t\tendSweep();\n\t};\n\n\tconst focusCell = (index: number) => {\n\t\tconst next = clamp(index, 0, count - 1);\n\t\tsetActiveIndex(next);\n\t\tcellsRef.current[next]?.focus();\n\t};\n\n\tconst onGridKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {\n\t\tconst target = (event.target as Element).closest<HTMLElement>(\n\t\t\t\"[data-bubble-index]\",\n\t\t);\n\t\tif (!target) return;\n\t\tconst index = Number(target.dataset.bubbleIndex);\n\t\tconst cols = fitColumnsRef.current;\n\t\tconst moves: Record<string, number> = {\n\t\t\tArrowRight: index + 1,\n\t\t\tArrowLeft: index - 1,\n\t\t\tArrowDown: index + cols < count ? index + cols : index,\n\t\t\tArrowUp: index - cols >= 0 ? index - cols : index,\n\t\t\tHome: 0,\n\t\t\tEnd: count - 1,\n\t\t};\n\t\tconst next = moves[event.key];\n\t\tif (next === undefined) return;\n\t\tevent.preventDefault();\n\t\tfocusCell(next);\n\t};\n\n\tconst register = useRef(\n\t\t(index: number, element: HTMLButtonElement | null) => {\n\t\t\tcellsRef.current[index] = element;\n\t\t},\n\t).current;\n\tconst activateRef = useRef((index: number) => {\n\t\tpopRef.current([index], { cue: true });\n\t}).current;\n\tconst popRef = useRef(pop);\n\tuseLayoutEffect(() => {\n\t\tpopRef.current = pop;\n\t});\n\tconst onFocusCell = useRef((index: number) => setActiveIndex(index)).current;\n\n\tconst poppedCount = popped.slice(0, count).filter(Boolean).length;\n\tconst labelledBy =\n\t\tariaLabelledBy ??\n\t\t(ariaLabel ? undefined : showCount ? `${titleId} ${countId}` : titleId);\n\n\treturn (\n\t\t<div\n\t\t\tref={rootRef}\n\t\t\trole=\"group\"\n\t\t\taria-label={ariaLabel}\n\t\t\taria-labelledby={labelledBy}\n\t\t\tdata-slot=\"bubble-wrap\"\n\t\t\tdata-tint={tint}\n\t\t\tdata-state={poppedCount === count ? \"clear\" : \"idle\"}\n\t\t\tonKeyDown={(event: KeyboardEvent<HTMLDivElement>) => {\n\t\t\t\tonKeyDown?.(event);\n\t\t\t\tif (!event.defaultPrevented) onGridKeyDown(event);\n\t\t\t}}\n\t\t\tstyle={\n\t\t\t\t{\n\t\t\t\t\t\"--bubble-wrap-width\": `${columnCount * MAX_CELL_PX + (columnCount - 1) * GAP_PX + PADDING_PX * 2 + 2}px`,\n\t\t\t\t\t...style,\n\t\t\t\t} as CSSProperties\n\t\t\t}\n\t\t\tclassName={cn(\n\t\t\t\t\"group/bubble-wrap relative isolate w-full max-w-(--bubble-wrap-width) select-none rounded-[20px] bg-[linear-gradient(180deg,#ece9e4,#e1ded8)] p-3 shadow-[inset_0_0_0_1px_rgb(0_0_0/0.05),0_1px_1px_rgb(0_0_0/0.04),0_2px_4px_-1px_rgb(0_0_0/0.05),0_14px_28px_-14px_rgb(0_0_0/0.22)] [-webkit-touch-callout:none] dark:bg-[linear-gradient(180deg,#1c1c1f,#161618)] dark:shadow-[inset_0_0_0_1px_rgb(255_255_255/0.06),inset_0_1px_0_rgb(255_255_255/0.05),0_1px_1px_rgb(0_0_0/0.4),0_14px_28px_-12px_rgb(0_0_0/0.7)]\",\n\t\t\t\tsurfaceVars,\n\t\t\t\ttints[tint] ?? tints.clear,\n\t\t\t\tclassName,\n\t\t\t)}\n\t\t\t{...props}\n\t\t>\n\t\t\t<span id={titleId} className=\"sr-only\">\n\t\t\t\tBubble wrap\n\t\t\t</span>\n\n\t\t\t<div className=\"relative\">\n\t\t\t\t{/* The plastic film the bubbles are molded into, sealed to the tray at its lip. */}\n\t\t\t\t<div\n\t\t\t\t\taria-hidden\n\t\t\t\t\tclassName=\"pointer-events-none absolute -inset-1.5 overflow-hidden rounded-[12px] bg-[linear-gradient(155deg,rgb(255_255_255/0.42),rgb(255_255_255/0.1)_38%,rgb(255_255_255/0.22)_56%,rgb(255_255_255/0.06))] shadow-[inset_0_0_0_1px_rgb(255_255_255/0.65),0_0_0_0.5px_rgb(0_0_0/0.06),0_1px_1.5px_rgb(0_0_0/0.05)] dark:bg-[linear-gradient(155deg,rgb(255_255_255/0.06),rgb(255_255_255/0.02)_38%,rgb(255_255_255/0.04)_56%,rgb(255_255_255/0.015))] dark:shadow-[inset_0_0_0_1px_rgb(255_255_255/0.06),0_0_0_0.5px_rgb(0_0_0/0.5),0_1px_2px_rgb(0_0_0/0.4)]\"\n\t\t\t\t>\n\t\t\t\t\t<div className=\"absolute inset-0 bg-[rgb(var(--bubble-wrap-tint)/calc(var(--bubble-wrap-tint-a)*0.45))]\" />\n\t\t\t\t\t<div\n\t\t\t\t\t\tclassName=\"absolute inset-0 bg-size-[72px_72px] opacity-[calc(var(--bubble-wrap-grain-a)*0.35)] mix-blend-overlay\"\n\t\t\t\t\t\tstyle={{ backgroundImage: grain }}\n\t\t\t\t\t/>\n\t\t\t\t</div>\n\n\t\t\t\t<div\n\t\t\t\t\tref={gridRef}\n\t\t\t\t\tonPointerDown={onPointerDown}\n\t\t\t\t\tonPointerMove={onPointerMove}\n\t\t\t\t\tonPointerUp={onPointerEnd}\n\t\t\t\t\tonPointerCancel={onPointerEnd}\n\t\t\t\t\tonLostPointerCapture={onPointerEnd}\n\t\t\t\t\tclassName=\"relative grid touch-none\"\n\t\t\t\t\tstyle={{\n\t\t\t\t\t\tgap: GAP_PX,\n\t\t\t\t\t\tgridTemplateColumns: `repeat(${fitColumns}, minmax(0, 1fr))`,\n\t\t\t\t\t}}\n\t\t\t\t>\n\t\t\t\t\t{Array.from({ length: count }, (_, index) => (\n\t\t\t\t\t\t<Bubble\n\t\t\t\t\t\t\tkey={index}\n\t\t\t\t\t\t\tindex={index}\n\t\t\t\t\t\t\tcount={count}\n\t\t\t\t\t\t\tpopped={Boolean(popped[index])}\n\t\t\t\t\t\t\tfocusable={index === Math.min(activeIndex, count - 1)}\n\t\t\t\t\t\t\tregister={register}\n\t\t\t\t\t\t\tonActivate={activateRef}\n\t\t\t\t\t\t\tonFocusCell={onFocusCell}\n\t\t\t\t\t\t/>\n\t\t\t\t\t))}\n\t\t\t\t</div>\n\t\t\t</div>\n\n\t\t\t{showCount ? (\n\t\t\t\t<p\n\t\t\t\t\tid={countId}\n\t\t\t\t\tclassName=\"mt-3 text-center text-muted-foreground text-xs tabular-nums\"\n\t\t\t\t>\n\t\t\t\t\t{poppedCount} of {count} popped\n\t\t\t\t</p>\n\t\t\t) : null}\n\n\t\t\t<button\n\t\t\t\ttype=\"button\"\n\t\t\t\tonClick={() => popAll(Math.min(activeIndex, count - 1), true)}\n\t\t\t\tclassName=\"pointer-events-none absolute bottom-3 left-1/2 z-20 inline-flex h-7 -translate-x-1/2 items-center whitespace-nowrap rounded-full bg-background px-3 font-medium text-foreground text-xs opacity-0 shadow-[0_1px_2px_rgb(0_0_0/0.12),0_4px_12px_-4px_rgb(0_0_0/0.25)] outline-none focus-visible:pointer-events-auto focus-visible:opacity-100 focus-visible:shadow-[0_0_0_2px_#fff,0_0_0_4px_#18181b] group-data-sweeping/bubble-wrap:invisible\"\n\t\t\t>\n\t\t\t\tPop all\n\t\t\t</button>\n\n\t\t\t<span role=\"status\" aria-live=\"polite\" className=\"sr-only\">\n\t\t\t\t{announcement}\n\t\t\t</span>\n\t\t</div>\n\t);\n}\n",
      "type": "registry:component",
      "target": "@components/bubble-wrap.tsx"
    }
  ],
  "meta": {
    "createdAt": "2026-11-05",
    "image": "https://cdn.tentui.com/images/components/bubble-wrap",
    "video": "https://cdn.tentui.com/videos/components/bubble-wrap"
  },
  "docs": "https://tentui.com/components/bubble-wrap",
  "categories": [],
  "type": "registry:component"
}