{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"lasso","type":"registry:component","title":"Lasso","description":"Select a loose group by drawing round it: let go and the band pulls tight like an elastic round exactly what it caught, bending in round what it didn’t.","author":"Hairline UI","dependencies":["lucide-react"],"registryDependencies":["https://hairlineui.com/r/number-roll.json?as=dependency"],"files":[{"path":"registry/lasso.tsx","type":"registry:component","content":"// Hairline UI · lasso · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n\"use client\";\n\nimport * as React from \"react\";\nimport { X } from \"lucide-react\";\nimport { NumberRoll } from \"./number-roll\";\nimport { INTERACTION_FOCUS, INTERACTION_PRESS } from \"./ui-interaction-motion\";\nimport { playSound } from \"./ui-sounds\";\n\n/* ─────────────────────────────────────────────────────────\n * LASSO: select a loose group of things and see exactly what\n * got caught\n *\n *   draw      drag across the empty space round your items and a\n *             band follows the hand; anything whose middle is\n *             inside the loop is caught as you go: a ring and a\n *             check pop onto it\n *   tighten   let go and the band pulls tight like an elastic\n *             round exactly what it caught, bending in round\n *             anything it didn't, and settles with a little give;\n *             a chip riding the band says how many\n *   add       hold Shift (or start inside the band) to draw\n *             another loop: both bands tighten round the lot\n *   let go    click empty space, press Esc or the chip's × and\n *             the band snaps and is gone\n *\n * Your items are yours: mark them with data-lasso-id and read the\n * ids from onSelectedChange. The band is a small rope simulation\n * on one canvas over them; it sleeps once it's taut.\n * ───────────────────────────────────────────────────────── */\n\nexport interface LassoProps extends Omit<React.HTMLAttributes<HTMLDivElement>, \"onChange\"> {\n  children: React.ReactNode;\n  /** Selected ids, controlled. Leave out to let the lasso keep them. */\n  selected?: string[];\n  defaultSelected?: string[];\n  onSelectedChange?: (ids: string[]) => void;\n  /** What can be caught. Each must carry data-lasso-id. */\n  itemSelector?: string;\n  /** The band and the rings: any CSS colour. */\n  color?: string;\n  /** The chip's words. */\n  label?: (count: number) => string;\n  /** A soft snap as the band tightens, off by default. */\n  sound?: boolean;\n}\n\nconst N = 120; // points on the band\nconst PAD = 5; // how far the band sits off what it wraps\nconst SLIP = 2; // how close it may pass what it didn't catch\nconst LINK = 26; // items closer than this share a band\nconst OVER = 18; // the canvas reaches past the container for the band\nconst EASE = \"cubic-bezier(0.16,1,0.3,1)\";\nconst NO_IDS: string[] = [];\n\nconst reducedQuery = \"(prefers-reduced-motion: reduce)\";\nconst subscribeReduced = (onChange: () => void) => {\n  const query = window.matchMedia(reducedQuery);\n  query.addEventListener(\"change\", onChange);\n  return () => query.removeEventListener(\"change\", onChange);\n};\nconst useReducedMotion = () => React.useSyncExternalStore(subscribeReduced, () => window.matchMedia(reducedQuery).matches, () => false);\n\nconst clamp = (v: number, a: number, b: number) => (v < a ? a : v > b ? b : v);\nconst backOut = (t: number) => 1 + 2.4 * (t - 1) ** 3 + 1.4 * (t - 1) ** 2;\n\ntype RGB = [number, number, number];\nconst mix = (a: RGB, b: RGB, t: number): RGB => [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, a[2] + (b[2] - a[2]) * t];\nconst css = (c: RGB, alpha = 1) => `rgba(${Math.round(c[0])},${Math.round(c[1])},${Math.round(c[2])},${alpha})`;\nconst lum = (c: RGB) => (0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2]) / 255;\nlet probe: CanvasRenderingContext2D | null = null;\nfunction toRgb(color: string, fallback: RGB): RGB {\n  if (typeof document === \"undefined\" || !color) return fallback;\n  probe ??= document.createElement(\"canvas\").getContext(\"2d\", { willReadFrequently: true });\n  if (!probe) return fallback;\n  probe.clearRect(0, 0, 1, 1);\n  probe.fillStyle = \"#000\";\n  probe.fillStyle = color;\n  probe.fillRect(0, 0, 1, 1);\n  const [r, g, b, a] = probe.getImageData(0, 0, 1, 1).data;\n  return a === 0 ? fallback : [r, g, b];\n}\n\n/* ── geometry ── */\n\ntype Item = { id: string; el: HTMLElement; x: number; y: number; w: number; h: number; r: number };\n\n/** Signed distance from a point to an item grown by pad: negative inside. */\nfunction sdItem(it: Item, px: number, py: number, pad = PAD) {\n  const r = it.r + pad;\n  const qx = Math.abs(px - (it.x + it.w / 2)) - it.w / 2 - pad + r;\n  const qy = Math.abs(py - (it.y + it.h / 2)) - it.h / 2 - pad + r;\n  return Math.hypot(Math.max(qx, 0), Math.max(qy, 0)) + Math.min(Math.max(qx, qy), 0) - r;\n}\n\nfunction inside(xs: ArrayLike<number>, ys: ArrayLike<number>, n: number, px: number, py: number) {\n  let hit = false;\n  for (let i = 0, j = n - 1; i < n; j = i++) {\n    if (ys[i] > py !== ys[j] > py && px < ((xs[j] - xs[i]) * (py - ys[i])) / (ys[j] - ys[i]) + xs[i]) hit = !hit;\n  }\n  return hit;\n}\n\n/** Evenly spaced points round a closed path. */\nfunction resample(xs: ArrayLike<number>, ys: ArrayLike<number>, n: number, count: number) {\n  const len: number[] = [0];\n  for (let i = 1; i <= n; i++) {\n    const a = i - 1;\n    const b = i % n;\n    len.push(len[a] + Math.hypot(xs[b] - xs[a], ys[b] - ys[a]));\n  }\n  const total = len[n] || 1;\n  const ox = new Float32Array(count);\n  const oy = new Float32Array(count);\n  let seg = 0;\n  for (let k = 0; k < count; k++) {\n    const at = (k / count) * total;\n    while (seg < n - 1 && len[seg + 1] < at) seg++;\n    const a = seg;\n    const b = (seg + 1) % n;\n    const span = len[seg + 1] - len[seg] || 1;\n    const t = (at - len[seg]) / span;\n    ox[k] = xs[a] + (xs[b] - xs[a]) * t;\n    oy[k] = ys[a] + (ys[b] - ys[a]) * t;\n  }\n  return { xs: ox, ys: oy, total };\n}\n\n/* ── the engine ── */\n\ntype Band = { x: Float32Array; y: Float32Array; px: Float32Array; py: Float32Array; born: number; still: number; alpha: number; dying: boolean; ids: Set<string>; key: string };\ninterface Engine {\n  root: HTMLDivElement | null;\n  canvas: HTMLCanvasElement | null;\n  chip: HTMLDivElement | null;\n  width: number;\n  height: number;\n  dpr: number;\n  items: Item[];\n  path: { x: number[]; y: number[] } | null; // while drawing\n  bands: Band[];\n  caught: Set<string>; // under the loop being drawn\n  selected: Set<string>;\n  badges: Map<string, { t: number; on: boolean }>;\n  hold: { x: number; y: number; t: number } | null; // a touch held before drawing\n  color: RGB;\n  hi: RGB;\n  dark: boolean;\n  frame: number;\n  last: number;\n  reduced: boolean;\n  sound: boolean;\n}\n\nfunction measure(e: Engine, selector: string) {\n  const root = e.root;\n  if (!root) return;\n  const base = root.getBoundingClientRect();\n  e.width = base.width;\n  e.height = base.height;\n  e.dpr = Math.min(3, window.devicePixelRatio || 1);\n  e.items = Array.from(root.querySelectorAll<HTMLElement>(selector)).map((el) => {\n    const r = el.getBoundingClientRect();\n    const radius = parseFloat(getComputedStyle(el).borderTopLeftRadius) || 0;\n    return { id: el.dataset.lassoId ?? \"\", el, x: r.left - base.left, y: r.top - base.top, w: r.width, h: r.height, r: Math.min(radius, r.width / 2, r.height / 2) };\n  });\n}\n\nfunction makeBand(xs: ArrayLike<number>, ys: ArrayLike<number>, n: number, now: number, ids: Set<string>): Band {\n  const { xs: x, ys: y } = resample(xs, ys, n, N);\n  return { x, y, px: Float32Array.from(x), py: Float32Array.from(y), born: now, still: 0, alpha: 1, dying: false, ids, key: [...ids].sort().join(\"\\u0000\") };\n}\n\n/** Selected items that sit next to each other share a band; one far away gets its own. */\nfunction groups(e: Engine) {\n  const its = e.items.filter((it) => e.selected.has(it.id));\n  const parent = its.map((_, i) => i);\n  const find = (i: number): number => (parent[i] === i ? i : (parent[i] = find(parent[i])));\n  for (let i = 0; i < its.length; i++) {\n    for (let j = i + 1; j < its.length; j++) {\n      const a = its[i];\n      const b = its[j];\n      const gx = Math.max(0, Math.abs(a.x + a.w / 2 - (b.x + b.w / 2)) - (a.w + b.w) / 2);\n      const gy = Math.max(0, Math.abs(a.y + a.h / 2 - (b.y + b.h / 2)) - (a.h + b.h) / 2);\n      // Side by side (not just touching at a corner) and close: one band.\n      if ((gx <= LINK && gy === 0) || (gy <= LINK && gx === 0)) parent[find(i)] = find(j);\n    }\n  }\n  const out = new Map<number, Set<string>>();\n  its.forEach((it, i) => {\n    const root = find(i);\n    if (!out.has(root)) out.set(root, new Set());\n    out.get(root)!.add(it.id);\n  });\n  return [...out.values()];\n}\n\nconst DIRS = [\n  [1, 0],\n  [1, 1],\n  [0, 1],\n  [-1, 1],\n  [-1, 0],\n  [-1, -1],\n  [0, -1],\n  [1, -1],\n];\n\n/** A loop that follows a group's own outline at a distance (concave where the group is), traced on a coarse grid. */\nfunction outline(e: Engine, ids: Set<string>, extra: number) {\n  const its = e.items.filter((it) => ids.has(it.id));\n  if (!its.length) return null;\n  const S = 4;\n  const margin = PAD + extra + 10;\n  const x0 = Math.min(...its.map((i) => i.x)) - margin;\n  const y0 = Math.min(...its.map((i) => i.y)) - margin;\n  const W = Math.ceil((Math.max(...its.map((i) => i.x + i.w)) + margin - x0) / S) + 1;\n  const H = Math.ceil((Math.max(...its.map((i) => i.y + i.h)) + margin - y0) / S) + 1;\n  const grid = new Uint8Array(W * H);\n  for (let gy = 0; gy < H; gy++) {\n    for (let gx = 0; gx < W; gx++) {\n      let d = Infinity;\n      for (const it of its) d = Math.min(d, sdItem(it, x0 + gx * S, y0 + gy * S) - extra);\n      grid[gy * W + gx] = d < 0 ? 1 : 0;\n    }\n  }\n  const filled = (x: number, y: number) => x >= 0 && y >= 0 && x < W && y < H && grid[y * W + x] === 1;\n  let sx = -1;\n  let sy = -1;\n  for (let i = 0; i < W * H && sx < 0; i++) if (grid[i]) [sx, sy] = [i % W, Math.floor(i / W)];\n  if (sx < 0) return null;\n  // Moore-neighbour tracing, clockwise, starting with the outside cell to the west as the one we came from.\n  const xs: number[] = [];\n  const ys: number[] = [];\n  let cx = sx;\n  let cy = sy;\n  let back = 4;\n  for (let guard = 0; guard < W * H * 4; guard++) {\n    xs.push(x0 + cx * S);\n    ys.push(y0 + cy * S);\n    let moved = false;\n    for (let k = 1; k <= 8; k++) {\n      const d = (back + k) % 8;\n      const nx = cx + DIRS[d][0];\n      const ny = cy + DIRS[d][1];\n      if (filled(nx, ny)) {\n        const pd = (d + 7) % 8;\n        const bx = cx + DIRS[pd][0] - nx;\n        const by = cy + DIRS[pd][1] - ny;\n        back = DIRS.findIndex(([ax, ay]) => ax === bx && ay === by);\n        cx = nx;\n        cy = ny;\n        moved = true;\n        break;\n      }\n    }\n    if (!moved || (cx === sx && cy === sy && xs.length > 2)) break;\n  }\n  // Smooth off the grid's steps.\n  const n = xs.length;\n  for (let pass = 0; pass < 4; pass++) {\n    const ox = xs.slice();\n    const oy = ys.slice();\n    for (let i = 0; i < n; i++) {\n      xs[i] = (ox[(i + n - 1) % n] + ox[i] * 2 + ox[(i + 1) % n]) / 4;\n      ys[i] = (oy[(i + n - 1) % n] + oy[i] * 2 + oy[(i + 1) % n]) / 4;\n    }\n  }\n  return { xs, ys };\n}\n\n/** Matches the bands to the selection's groups: a band that already holds a group stays; the loop just drawn becomes\n * the band of the group it caught; any other group gets a band that starts loose round its outline and tightens. */\nfunction rebuild(e: Engine, now: number, drawn?: { xs: number[]; ys: number[]; ids: Set<string> }) {\n  const want = groups(e);\n  const keys = new Set(want.map((g) => [...g].sort().join(\"\\u0000\")));\n  e.bands.forEach((b) => {\n    if (!keys.has(b.key)) b.dying = true;\n  });\n  for (const g of want) {\n    const key = [...g].sort().join(\"\\u0000\");\n    if (e.bands.some((b) => !b.dying && b.key === key)) continue;\n    const same = drawn && drawn.ids.size === g.size && [...g].every((id) => drawn.ids.has(id));\n    const loop = same ? drawn : outline(e, g, 20);\n    if (loop && loop.xs.length > 2) e.bands.push(makeBand(loop.xs, loop.ys, loop.xs.length, now, g));\n  }\n  if (e.reduced) {\n    e.bands.forEach((b) => (b.dying ? (b.alpha = 0) : settleNow(e, b)));\n  }\n}\n\n/** One step of a band (1/120 s): inertia, an elastic pull that shortens it, and every item pushing it out. */\nfunction stepBand(e: Engine, b: Band, solid: { item: Item; pad: number }[]) {\n  const damp = 0.84;\n  let move = 0;\n  for (let i = 0; i < N; i++) {\n    const vx = (b.x[i] - b.px[i]) * damp;\n    const vy = (b.y[i] - b.py[i]) * damp;\n    b.px[i] = b.x[i];\n    b.py[i] = b.y[i];\n    b.x[i] += vx;\n    b.y[i] += vy;\n  }\n  let cx = 0;\n  let cy = 0;\n  for (let i = 0; i < N; i++) {\n    cx += b.x[i];\n    cy += b.y[i];\n  }\n  cx /= N;\n  cy /= N;\n  for (let it = 0; it < 3; it++) {\n    for (let i = 0; i < N; i++) {\n      const a = (i + N - 1) % N;\n      const c = (i + 1) % N;\n      // Tension only: each point moves towards the middle of its neighbours, which straightens and shortens the band\n      // (a band with nothing inside it runs down to a point); nothing pulls it into the gaps between what it holds.\n      const mx = (b.x[a] + b.x[c]) / 2 - b.x[i];\n      const my = (b.y[a] + b.y[c]) / 2 - b.y[i];\n      const pull = b.ids.size ? 0 : 0.25;\n      const dx = cx - b.x[i];\n      const dy = cy - b.y[i];\n      const d = Math.hypot(dx, dy) || 1;\n      b.x[i] += mx * 0.45 + (dx / d) * pull;\n      b.y[i] += my * 0.45 + (dy / d) * pull;\n    }\n    // Items are solid: anything the band presses into pushes it back out to their edge.\n    if (!b.dying) {\n      for (let i = 0; i < N; i++) {\n        for (const { item, pad } of solid) {\n          const sd = sdItem(item, b.x[i], b.y[i], pad);\n          if (sd >= 0) continue;\n          const h = 0.5;\n          const gx = sdItem(item, b.x[i] + h, b.y[i], pad) - sdItem(item, b.x[i] - h, b.y[i], pad);\n          const gy = sdItem(item, b.x[i], b.y[i] + h, pad) - sdItem(item, b.x[i], b.y[i] - h, pad);\n          const gl = Math.hypot(gx, gy) || 1;\n          b.x[i] -= (gx / gl) * sd;\n          b.y[i] -= (gy / gl) * sd;\n        }\n      }\n    }\n  }\n  for (let i = 0; i < N; i++) move = Math.max(move, Math.abs(b.x[i] - b.px[i]) + Math.abs(b.y[i] - b.py[i]));\n  b.still = move < 0.03 ? b.still + 1 : 0;\n}\n\n/** What the band can't pass through: what it caught, and anything outside it (so it bends in round what it didn't catch). */\nfunction solidFor(e: Engine, b: Band) {\n  const out: { item: Item; pad: number }[] = [];\n  for (const it of e.items) {\n    if (b.ids.has(it.id)) out.push({ item: it, pad: PAD });\n    else if (!inside(b.x, b.y, N, it.x + it.w / 2, it.y + it.h / 2)) out.push({ item: it, pad: SLIP });\n  }\n  return out;\n}\n\nfunction perimeter(b: Band) {\n  let p = 0;\n  for (let i = 0; i < N; i++) p += Math.hypot(b.x[(i + 1) % N] - b.x[i], b.y[(i + 1) % N] - b.y[i]);\n  return p;\n}\n\nfunction strokeLoop(ctx: CanvasRenderingContext2D, xs: ArrayLike<number>, ys: ArrayLike<number>, n: number, closed: boolean) {\n  ctx.beginPath();\n  // A smooth curve through the points: midpoints joined by quadratic curves.\n  const at = (k: number) => (closed ? ((k % n) + n) % n : clamp(k, 0, n - 1));\n  ctx.moveTo((xs[at(0)] + xs[at(1)]) / 2, (ys[at(0)] + ys[at(1)]) / 2);\n  const end = closed ? n : n - 1;\n  for (let k = 1; k < end; k++) {\n    const a = at(k);\n    const b = at(k + 1);\n    ctx.quadraticCurveTo(xs[a], ys[a], (xs[a] + xs[b]) / 2, (ys[a] + ys[b]) / 2);\n  }\n  if (closed) ctx.closePath();\n}\n\n/** The band: a rubber cord in your colour with a lit top and a small contact shadow on the surface it lies on. */\nfunction drawBand(ctx: CanvasRenderingContext2D, e: Engine, xs: ArrayLike<number>, ys: ArrayLike<number>, n: number, closed: boolean, alpha: number, width: number) {\n  ctx.save();\n  ctx.globalAlpha = alpha;\n  ctx.lineCap = \"round\";\n  ctx.lineJoin = \"round\";\n  ctx.save();\n  ctx.shadowColor = css([0, 0, 0], e.dark ? 0.55 : 0.22);\n  ctx.shadowBlur = 3;\n  ctx.shadowOffsetY = 1.5;\n  strokeLoop(ctx, xs, ys, n, closed);\n  ctx.strokeStyle = css(mix(e.color, [0, 0, 0], 0.12));\n  ctx.lineWidth = width;\n  ctx.stroke();\n  ctx.restore();\n  ctx.translate(-0.25, -0.6);\n  strokeLoop(ctx, xs, ys, n, closed);\n  ctx.strokeStyle = css(e.hi, 0.75);\n  ctx.lineWidth = Math.max(0.8, width * 0.32);\n  ctx.stroke();\n  ctx.restore();\n}\n\nfunction roundRectPath(ctx: CanvasRenderingContext2D, x: number, y: number, w: number, h: number, r: number) {\n  const rr = Math.max(0, Math.min(r, w / 2, h / 2));\n  ctx.beginPath();\n  ctx.moveTo(x + rr, y);\n  ctx.arcTo(x + w, y, x + w, y + h, rr);\n  ctx.arcTo(x + w, y + h, x, y + h, rr);\n  ctx.arcTo(x, y + h, x, y, rr);\n  ctx.arcTo(x, y, x + w, y, rr);\n  ctx.closePath();\n}\n\nfunction draw(e: Engine, now: number) {\n  const canvas = e.canvas;\n  const ctx = canvas?.getContext(\"2d\");\n  if (!canvas || !ctx) return false;\n  const W = e.width + OVER * 2;\n  const H = e.height + OVER * 2;\n  if (canvas.width !== Math.round(W * e.dpr) || canvas.height !== Math.round(H * e.dpr)) {\n    canvas.width = Math.round(W * e.dpr);\n    canvas.height = Math.round(H * e.dpr);\n  }\n  ctx.setTransform(e.dpr, 0, 0, e.dpr, e.dpr * OVER, e.dpr * OVER);\n  ctx.clearRect(-OVER, -OVER, W, H);\n  let busy = false;\n\n  // Rings and checks on what's caught (while drawing) or selected (after).\n  const shown = e.path ? new Set([...e.selected, ...e.caught]) : e.selected;\n  for (const it of e.items) {\n    const want = shown.has(it.id);\n    const badge = e.badges.get(it.id);\n    if (want && (!badge || !badge.on)) e.badges.set(it.id, { t: now, on: true });\n    if (!want && badge?.on) e.badges.set(it.id, { t: now, on: false });\n    const b = e.badges.get(it.id);\n    if (!b) continue;\n    const k = clamp((now - b.t) / (b.on ? 260 : 160), 0, 1);\n    if (k < 1) busy = true;\n    const s = e.reduced ? (b.on ? 1 : 0) : b.on ? backOut(k) : 1 - k;\n    if (s <= 0.01) {\n      if (!b.on) e.badges.delete(it.id);\n      continue;\n    }\n    ctx.save();\n    ctx.globalAlpha = clamp(s, 0, 1);\n    // While drawing, a ring shows what's caught; once let go, the band itself outlines the selection.\n    if (e.path) {\n      roundRectPath(ctx, it.x - 3, it.y - 3, it.w + 6, it.h + 6, it.r + 3);\n      ctx.strokeStyle = css(e.color);\n      ctx.lineWidth = 2;\n      ctx.stroke();\n    }\n    const bx = it.x + it.w - 13;\n    const by = it.y + 13;\n    ctx.translate(bx, by);\n    ctx.scale(s, s);\n    ctx.beginPath();\n    ctx.arc(0, 0, 9.5, 0, Math.PI * 2);\n    ctx.fillStyle = css([255, 255, 255]);\n    ctx.fill();\n    ctx.beginPath();\n    ctx.arc(0, 0, 8, 0, Math.PI * 2);\n    ctx.fillStyle = css(e.color);\n    ctx.fill();\n    ctx.beginPath();\n    ctx.moveTo(-3.6, 0.2);\n    ctx.lineTo(-1.1, 2.7);\n    ctx.lineTo(3.8, -2.4);\n    ctx.strokeStyle = css([255, 255, 255]);\n    ctx.lineWidth = 1.9;\n    ctx.lineCap = \"round\";\n    ctx.lineJoin = \"round\";\n    ctx.stroke();\n    ctx.restore();\n  }\n\n  // The loop being drawn: a slack cord from where it started to the hand, the closing gap shown faintly.\n  if (e.path && e.path.x.length > 1) {\n    const { x, y } = e.path;\n    drawBand(ctx, e, x, y, x.length, false, 1, 3.4);\n    ctx.save();\n    ctx.setLineDash([3, 5]);\n    ctx.beginPath();\n    ctx.moveTo(x[x.length - 1], y[y.length - 1]);\n    ctx.lineTo(x[0], y[0]);\n    ctx.strokeStyle = css(e.color, 0.45);\n    ctx.lineWidth = 1.5;\n    ctx.stroke();\n    ctx.restore();\n  }\n\n  // A touch held before drawing: a ring fills under the finger.\n  if (e.hold) {\n    const k = clamp((now - e.hold.t) / 280, 0, 1);\n    busy = true;\n    ctx.beginPath();\n    ctx.arc(e.hold.x, e.hold.y, 18, -Math.PI / 2, -Math.PI / 2 + k * Math.PI * 2);\n    ctx.strokeStyle = css(e.color, 0.8);\n    ctx.lineWidth = 3;\n    ctx.stroke();\n  }\n\n  for (const b of e.bands) drawBand(ctx, e, b.x, b.y, N, true, b.alpha, 3);\n  return busy;\n}\n\nfunction frame(e: Engine, now: number, onSettle: () => void) {\n  e.frame = 0;\n  const steps = clamp(Math.round(((now - e.last) / 1000) * 120), 1, 6);\n  e.last = now;\n  let busy = false;\n  for (const b of e.bands) {\n    if (b.dying) {\n      // Snapped: it shrinks to the middle and fades.\n      b.alpha = Math.max(0, b.alpha - 0.09);\n      for (let s = 0; s < steps; s++) stepBand(e, b, []);\n      busy = busy || b.alpha > 0;\n      continue;\n    }\n    for (let s = 0; s < steps; s++) stepBand(e, b, solidFor(e, b));\n    const age = now - b.born;\n    // A band that caught nothing runs down to nothing.\n    if (perimeter(b) < 14) {\n      b.dying = true;\n      busy = true;\n      continue;\n    }\n    if (b.still < 30 && age < 2400) busy = true;\n  }\n  const before = e.bands.length;\n  e.bands = e.bands.filter((b) => !(b.dying && b.alpha <= 0));\n  if (draw(e, now)) busy = true;\n  placeChip(e);\n  if (before && !busy) onSettle();\n  if (busy) e.frame = requestAnimationFrame((t) => frame(e, t, onSettle));\n}\n\n/** The chip sits centred above the bands. */\nfunction placeChip(e: Engine) {\n  const chip = e.chip;\n  if (!chip) return;\n  let x0 = Infinity;\n  let x1 = -Infinity;\n  let y0 = Infinity;\n  for (const b of e.bands) {\n    if (b.dying) continue;\n    for (let i = 0; i < N; i++) {\n      if (b.x[i] < x0) x0 = b.x[i];\n      if (b.x[i] > x1) x1 = b.x[i];\n      if (b.y[i] < y0) y0 = b.y[i];\n    }\n  }\n  if (!isFinite(y0) || !e.selected.size || e.path) {\n    chip.style.opacity = \"0\";\n    chip.style.pointerEvents = \"none\";\n    return;\n  }\n  const x = clamp((x0 + x1) / 2, 56, Math.max(56, e.width - 56));\n  chip.style.opacity = \"1\";\n  chip.style.pointerEvents = \"auto\";\n  chip.style.transform = `translate3d(${x}px, ${y0 - 8}px, 0) translate(-50%, -100%)`;\n}\n\n/* ── the component ── */\n\nexport function Lasso({\n  children,\n  selected,\n  defaultSelected = NO_IDS,\n  onSelectedChange,\n  itemSelector = \"[data-lasso-id]\",\n  color,\n  label = () => \"selected\",\n  sound = false,\n  className = \"\",\n  style,\n  onPointerDown,\n  onKeyDown,\n  ...props\n}: LassoProps) {\n  const reduced = useReducedMotion();\n  const rootRef = React.useRef<HTMLDivElement>(null);\n  const canvasRef = React.useRef<HTMLCanvasElement>(null);\n  const chipRef = React.useRef<HTMLDivElement>(null);\n  const probes = React.useRef<(HTMLSpanElement | null)[]>([]);\n  const engineRef = React.useRef<Engine | null>(null);\n  const [own, setOwn] = React.useState<string[]>(defaultSelected);\n  const ids = selected ?? own;\n  const [announce, setAnnounce] = React.useState(\"\");\n\n  const engine = React.useCallback((): Engine => {\n    if (!engineRef.current) {\n      engineRef.current = {\n        root: null,\n        canvas: null,\n        chip: null,\n        width: 0,\n        height: 0,\n        dpr: 1,\n        items: [],\n        path: null,\n        bands: [],\n        caught: new Set(),\n        selected: new Set(),\n        badges: new Map(),\n        hold: null,\n        color: [48, 93, 222],\n        hi: [160, 185, 245],\n        dark: false,\n        frame: 0,\n        last: 0,\n        reduced: false,\n        sound: false,\n      };\n    }\n    return engineRef.current;\n  }, []);\n\n  const live = React.useRef({ onSelectedChange, controlled: selected !== undefined, itemSelector });\n  React.useLayoutEffect(() => {\n    live.current = { onSelectedChange, controlled: selected !== undefined, itemSelector };\n  });\n\n  const settle = React.useCallback(() => {\n    const e = engine();\n    if (e.sound && e.bands.length) playSound(\"tick\", 0.18);\n  }, [engine]);\n\n  const kick = React.useCallback(() => {\n    const e = engine();\n    if (e.frame || !e.canvas) return;\n    e.last = performance.now();\n    e.frame = requestAnimationFrame((t) => frame(e, t, settle));\n  }, [engine, settle]);\n\n  const commit = React.useCallback(\n    (next: Set<string>) => {\n      const list = [...next];\n      if (!live.current.controlled) setOwn(list);\n      live.current.onSelectedChange?.(list);\n      setAnnounce(list.length ? `${list.length} selected` : \"Selection cleared\");\n    },\n    [],\n  );\n\n  // Selection from the app (or a click on an item there): rings follow, and a band wraps the new set.\n  React.useEffect(() => {\n    const e = engine();\n    const next = new Set(ids);\n    const same = next.size === e.selected.size && [...next].every((id) => e.selected.has(id));\n    if (same) return;\n    e.selected = next;\n    if (!e.path) {\n      measure(e, live.current.itemSelector);\n      rebuild(e, performance.now());\n    }\n    kick();\n  }, [engine, ids, kick]);\n\n  React.useEffect(() => {\n    const e = engine();\n    e.reduced = reduced;\n    e.sound = sound;\n  }, [engine, reduced, sound]);\n\n  React.useLayoutEffect(() => {\n    const e = engine();\n    e.root = rootRef.current;\n    e.canvas = canvasRef.current;\n    e.chip = chipRef.current;\n    const root = rootRef.current;\n    if (!root) return;\n    const remeasure = () => {\n      measure(e, live.current.itemSelector);\n      // Taut bands re-wrap the selection where it now is.\n      if (e.selected.size && !e.path) {\n        e.bands = [];\n        rebuild(e, performance.now());\n      }\n      kick();\n    };\n    remeasure();\n    const observer = new ResizeObserver(remeasure);\n    observer.observe(root);\n    // Touch: once a hold has started a loop, the page mustn't scroll under the finger.\n    const block = (ev: TouchEvent) => {\n      if (e.path) ev.preventDefault();\n    };\n    root.addEventListener(\"touchmove\", block, { passive: false });\n    return () => {\n      observer.disconnect();\n      root.removeEventListener(\"touchmove\", block);\n      cancelAnimationFrame(e.frame);\n      e.frame = 0;\n    };\n  }, [engine, kick]);\n\n  // Theme colours, read again when the theme changes.\n  React.useEffect(() => {\n    const e = engine();\n    const read = () => {\n      const c = toRgb(probes.current[0] ? getComputedStyle(probes.current[0]).color : \"\", [48, 93, 222]);\n      const bg = toRgb(probes.current[1] ? getComputedStyle(probes.current[1]).color : \"\", [255, 255, 255]);\n      e.color = c;\n      e.hi = mix(c, [255, 255, 255], 0.55);\n      e.dark = lum(bg) < 0.5;\n      kick();\n    };\n    read();\n    const observer = new MutationObserver(read);\n    observer.observe(document.documentElement, { attributes: true, attributeFilter: [\"class\", \"style\", \"data-theme\"] });\n    const media = window.matchMedia(\"(prefers-color-scheme: dark)\");\n    media.addEventListener(\"change\", read);\n    return () => {\n      observer.disconnect();\n      media.removeEventListener(\"change\", read);\n    };\n  }, [engine, color, kick]);\n\n  /* ── the hand ── */\n\n  const gesture = React.useRef<{ id: number; x: number; y: number; started: boolean; add: boolean; timer: number } | null>(null);\n  const local = (ev: { clientX: number; clientY: number }) => {\n    const r = rootRef.current!.getBoundingClientRect();\n    return { x: ev.clientX - r.left, y: ev.clientY - r.top };\n  };\n\n  const begin = (x: number, y: number) => {\n    const e = engine();\n    const g = gesture.current;\n    if (!g) return;\n    g.started = true;\n    e.hold = null;\n    e.path = { x: [x], y: [y] };\n    e.caught = new Set();\n    if (!g.add) {\n      e.selected = new Set();\n      e.bands.forEach((b) => (b.dying = true));\n    }\n    rootRef.current?.setPointerCapture(g.id);\n    kick();\n  };\n\n  const handleDown = (ev: React.PointerEvent<HTMLDivElement>) => {\n    onPointerDown?.(ev);\n    if (ev.defaultPrevented || ev.button !== 0) return;\n    const target = ev.target as HTMLElement;\n    if (target.closest(itemSelector) || target.closest(\"button, a, input, textarea, select, [data-lasso-ignore]\")) return;\n    const e = engine();\n    measure(e, itemSelector);\n    const p = local(ev);\n    const insideBand = e.bands.some((b) => !b.dying && inside(b.x, b.y, N, p.x, p.y));\n    gesture.current = { id: ev.pointerId, x: p.x, y: p.y, started: false, add: ev.shiftKey || insideBand, timer: 0 };\n    if (ev.pointerType === \"touch\") {\n      // On touch a short hold starts the loop, so a plain swipe still scrolls the page.\n      e.hold = { x: p.x, y: p.y, t: performance.now() };\n      kick();\n      gesture.current.timer = window.setTimeout(() => begin(p.x, p.y), 280);\n    }\n  };\n\n  const handleMove = (ev: React.PointerEvent<HTMLDivElement>) => {\n    const g = gesture.current;\n    const e = engine();\n    if (!g || g.id !== ev.pointerId) return;\n    const p = local(ev);\n    if (!g.started) {\n      if (Math.hypot(p.x - g.x, p.y - g.y) < 5) return;\n      if (ev.pointerType === \"touch\") {\n        // Moved before the hold finished: it's a scroll.\n        window.clearTimeout(g.timer);\n        e.hold = null;\n        gesture.current = null;\n        return;\n      }\n      begin(g.x, g.y);\n    }\n    const path = e.path;\n    if (!path) return;\n    const lx = path.x[path.x.length - 1];\n    const ly = path.y[path.y.length - 1];\n    if (Math.hypot(p.x - lx, p.y - ly) < 3) return;\n    path.x.push(p.x);\n    path.y.push(p.y);\n    // Caught as you go: anything whose middle is inside the loop so far.\n    const caught = new Set<string>();\n    if (path.x.length > 2) for (const it of e.items) if (inside(path.x, path.y, path.x.length, it.x + it.w / 2, it.y + it.h / 2)) caught.add(it.id);\n    if (e.sound && caught.size > e.caught.size) playSound(\"pop\", 0.15);\n    e.caught = caught;\n    kick();\n  };\n\n  const handleUp = (ev: React.PointerEvent<HTMLDivElement>) => {\n    const g = gesture.current;\n    const e = engine();\n    if (!g || g.id !== ev.pointerId) return;\n    window.clearTimeout(g.timer);\n    gesture.current = null;\n    e.hold = null;\n    const path = e.path;\n    e.path = null;\n    if (!g.started || !path) {\n      // A plain click on empty space lets the selection go.\n      if (ev.type === \"pointerup\" && e.selected.size) letGo();\n      kick();\n      return;\n    }\n    const caughtNow = e.caught;\n    const next = g.add ? new Set([...e.selected, ...caughtNow]) : new Set(caughtNow);\n    e.caught = new Set();\n    let area = 0;\n    for (let i = 0, j = path.x.length - 1; i < path.x.length; j = i++) area += (path.x[j] + path.x[i]) * (path.y[j] - path.y[i]);\n    if (Math.abs(area) / 2 < 400 || next.size === 0) {\n      e.selected = next;\n      rebuild(e, ev.timeStamp);\n      commit(next);\n      kick();\n      return;\n    }\n    e.selected = next;\n    rebuild(e, ev.timeStamp, { xs: path.x, ys: path.y, ids: caughtNow });\n    commit(next);\n    kick();\n  };\n\n  const letGo = () => {\n    const e = engine();\n    e.selected = new Set();\n    e.bands.forEach((b) => {\n      b.dying = true;\n      if (e.reduced) b.alpha = 0;\n    });\n    if (e.sound) playSound(\"tick\", 0.2);\n    commit(new Set());\n    kick();\n  };\n\n  const handleKey = (ev: React.KeyboardEvent<HTMLDivElement>) => {\n    onKeyDown?.(ev);\n    if (ev.key === \"Escape\" && engine().selected.size) {\n      ev.stopPropagation();\n      letGo();\n    }\n  };\n\n  // Selected items carry an attribute your styles can use.\n  React.useEffect(() => {\n    const root = rootRef.current;\n    if (!root) return;\n    const set = new Set(ids);\n    root.querySelectorAll<HTMLElement>(itemSelector).forEach((el) => {\n      if (set.has(el.dataset.lassoId ?? \"\")) el.setAttribute(\"data-lasso-selected\", \"\");\n      else el.removeAttribute(\"data-lasso-selected\");\n    });\n  }, [ids, itemSelector, children]);\n\n  const count = ids.length;\n  return (\n    <div\n      ref={rootRef}\n      className={`relative select-none ${className}`}\n      style={style}\n      onPointerDown={handleDown}\n      onPointerMove={handleMove}\n      onPointerUp={handleUp}\n      onPointerCancel={handleUp}\n      onKeyDown={handleKey}\n      {...props}\n    >\n      <span ref={(el) => void (probes.current[0] = el)} hidden style={{ color: color ?? \"var(--primary)\" }} />\n      <span ref={(el) => void (probes.current[1] = el)} hidden className=\"text-background\" />\n      {children}\n      <canvas\n        ref={canvasRef}\n        aria-hidden\n        className=\"pointer-events-none absolute z-10\"\n        style={{ left: -OVER, top: -OVER, width: `calc(100% + ${OVER * 2}px)`, height: `calc(100% + ${OVER * 2}px)` }}\n      />\n      <div\n        ref={chipRef}\n        className=\"absolute left-0 top-0 z-20 flex h-8 items-center gap-1 rounded-full bg-foreground pl-3 pr-1 text-[12.5px] font-medium text-background\"\n        style={{ opacity: 0, pointerEvents: \"none\", transition: `opacity 220ms ${EASE}`, willChange: \"transform\" }}\n        data-lasso-ignore\n      >\n        <span className=\"tabular-nums\">\n          <NumberRoll value={count} />\n        </span>\n        <span>{label(count)}</span>\n        <button\n          type=\"button\"\n          aria-label=\"Clear selection\"\n          onClick={letGo}\n          className={`ml-1 grid size-6 cursor-pointer place-items-center rounded-full hover:bg-[color-mix(in_oklab,var(--background)_20%,var(--foreground))] ${INTERACTION_PRESS} ${INTERACTION_FOCUS}`}\n        >\n          <X className=\"size-3.5\" aria-hidden />\n        </button>\n      </div>\n      <span className=\"sr-only\" role=\"status\" aria-live=\"polite\">\n        {announce}\n      </span>\n    </div>\n  );\n}\n\n/** Reduced motion: run the band to rest at once. */\nfunction settleNow(e: Engine, b: Band) {\n  for (let k = 0; k < 600 && b.still < 30; k++) stepBand(e, b, solidFor(e, b));\n  b.px = Float32Array.from(b.x);\n  b.py = Float32Array.from(b.y);\n}\n"},{"path":"registry/ui-interaction-motion.ts","type":"registry:component","content":"// Hairline UI · lasso · 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"},{"path":"registry/ui-sounds.ts","type":"registry:component","content":"// Hairline UI · lasso · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n/* ─────────────────────────────────────────────────────────\n * UI SOUNDS: small interface sounds, made in code\n *\n * No files and nothing to license: every sound is built from a\n * tone or a burst of noise with the Web Audio API the moment it\n * plays. They're short and quiet, made to sit under an interface,\n * and components only play them when you pass `sound`.\n *\n *   fold     paper creasing: two short crisp bursts\n *   unfold   paper opening: a soft rising sweep\n *   drop     something small landing: a low, soft knock\n *   tick     a light click\n *   pop      a quick bright blip\n *   success  two soft rising notes\n *   error    two low falling notes\n *\n * Browsers only start audio after the visitor has pressed\n * something on the page, so a sound before that stays silent.\n * ───────────────────────────────────────────────────────── */\n\nexport type UiSound = \"fold\" | \"unfold\" | \"drop\" | \"tick\" | \"pop\" | \"success\" | \"error\";\n\nlet context: AudioContext | null = null;\nlet noise: AudioBuffer | null = null;\n\nfunction audio() {\n  if (typeof window === \"undefined\") return null;\n  if (!context) {\n    const Ctx = window.AudioContext ?? (window as unknown as { webkitAudioContext?: typeof AudioContext }).webkitAudioContext;\n    if (!Ctx) return null;\n    context = new Ctx();\n  }\n  if (context.state === \"suspended\") void context.resume().catch(() => {});\n  return context;\n}\n\nfunction noiseBuffer(ctx: AudioContext) {\n  if (noise && noise.sampleRate === ctx.sampleRate) return noise;\n  noise = ctx.createBuffer(1, Math.floor(ctx.sampleRate * 0.5), ctx.sampleRate);\n  const data = noise.getChannelData(0);\n  for (let i = 0; i < data.length; i++) data[i] = Math.random() * 2 - 1;\n  return noise;\n}\n\n/** A burst of filtered noise. */\nfunction burst(ctx: AudioContext, out: AudioNode, at: number, length: number, { type = \"bandpass\", from = 2000, to = from, q = 0.9, level = 0.5 }: { type?: BiquadFilterType; from?: number; to?: number; q?: number; level?: number }) {\n  const src = ctx.createBufferSource();\n  src.buffer = noiseBuffer(ctx);\n  const filter = ctx.createBiquadFilter();\n  filter.type = type;\n  filter.Q.value = q;\n  filter.frequency.setValueAtTime(from, at);\n  filter.frequency.exponentialRampToValueAtTime(Math.max(40, to), at + length);\n  const gain = ctx.createGain();\n  gain.gain.setValueAtTime(0.0001, at);\n  gain.gain.exponentialRampToValueAtTime(level, at + Math.min(0.012, length / 3));\n  gain.gain.exponentialRampToValueAtTime(0.0001, at + length);\n  src.connect(filter).connect(gain).connect(out);\n  src.start(at, Math.random() * 0.3, length + 0.02);\n}\n\n/** A tone that glides from one pitch to another. */\nfunction tone(ctx: AudioContext, out: AudioNode, at: number, length: number, { type = \"sine\", from, to = from, level = 0.4 }: { type?: OscillatorType; from: number; to?: number; level?: number }) {\n  const osc = ctx.createOscillator();\n  osc.type = type;\n  osc.frequency.setValueAtTime(from, at);\n  osc.frequency.exponentialRampToValueAtTime(Math.max(20, to), at + length);\n  const gain = ctx.createGain();\n  gain.gain.setValueAtTime(0.0001, at);\n  gain.gain.exponentialRampToValueAtTime(level, at + 0.006);\n  gain.gain.exponentialRampToValueAtTime(0.0001, at + length);\n  osc.connect(gain).connect(out);\n  osc.start(at);\n  osc.stop(at + length + 0.02);\n}\n\n/** Plays one sound. `volume` is 0 to 1; the default sits quietly under an interface. */\nexport function playSound(name: UiSound, volume = 0.5) {\n  const ctx = audio();\n  if (!ctx) return;\n  const out = ctx.createGain();\n  out.gain.value = Math.max(0, Math.min(1, volume)) * 0.5;\n  out.connect(ctx.destination);\n  const t = ctx.currentTime + 0.005;\n  switch (name) {\n    case \"fold\":\n      burst(ctx, out, t, 0.05, { type: \"highpass\", from: 2600, q: 0.7, level: 0.45 });\n      burst(ctx, out, t + 0.07, 0.07, { type: \"bandpass\", from: 3200, to: 1800, q: 1.2, level: 0.35 });\n      break;\n    case \"unfold\":\n      burst(ctx, out, t, 0.16, { type: \"bandpass\", from: 900, to: 2800, q: 0.8, level: 0.3 });\n      break;\n    case \"drop\":\n      tone(ctx, out, t, 0.12, { from: 180, to: 70, level: 0.55 });\n      burst(ctx, out, t, 0.03, { type: \"lowpass\", from: 1200, q: 0.5, level: 0.2 });\n      break;\n    case \"tick\":\n      tone(ctx, out, t, 0.025, { type: \"triangle\", from: 1900, to: 1500, level: 0.25 });\n      break;\n    case \"pop\":\n      tone(ctx, out, t, 0.06, { from: 620, to: 980, level: 0.3 });\n      break;\n    case \"success\":\n      tone(ctx, out, t, 0.11, { from: 660, level: 0.22 });\n      tone(ctx, out, t + 0.09, 0.16, { from: 990, level: 0.22 });\n      break;\n    case \"error\":\n      tone(ctx, out, t, 0.12, { type: \"triangle\", from: 330, level: 0.25 });\n      tone(ctx, out, t + 0.1, 0.18, { type: \"triangle\", from: 247, level: 0.25 });\n      break;\n  }\n  window.setTimeout(() => out.disconnect(), 600);\n}\n"}],"css":{},"docs":"Docs and live preview: https://hairlineui.com/ui/lasso. MIT licensed: https://hairlineui.com/license#components","meta":{"license":"MIT"}}