{"$schema":"https://ui.shadcn.com/schema/registry-item.json","author":"Eduardo Calvo <edu@smoothui.dev>","css":{},"dependencies":["motion"],"description":"A photo sticker with a physical peel, optional tearing and procedural sounds.","devDependencies":[],"files":[{"content":"\"use client\";\n\nimport { useReducedMotion } from \"motion/react\";\nimport {\n  type ReactNode,\n  type PointerEvent as ReactPointerEvent,\n  type RefObject,\n  useEffect,\n  useRef,\n  useState,\n} from \"react\";\nimport { useMaterialAudio } from \"./material-audio\";\nimport { createPeelSounds, type Rasp } from \"./peel-sounds\";\n\nexport { type MaterialOutput, useMaterialAudio } from \"./material-audio\";\nexport { createPeelSounds, grain, noiseFor, type Rasp } from \"./peel-sounds\";\n\nimport { cn } from \"@/lib/utils\";\n\ntype Vec = [number, number];\n\n/** Drag this far (px) before a press counts as a peel, not a tap. */\nconst TAP_SLOP = 5;\n/** Room around the card so the part still stuck keeps its own shadow. */\nconst ROOM = 48;\n/** Light from the top left, slightly in front (x right, y down, z out). */\nconst LIGHT: [number, number, number] = (() => {\n  const l: [number, number, number] = [-0.35, -0.55, 1];\n  const n = Math.hypot(...l);\n  return [l[0] / n, l[1] / n, l[2] / n];\n})();\n/** Below this the flap is not drawn. */\nconst FLAT = 0.002;\n/** How high (px) a sticker floats while it is held. */\nconst LIFT = 26;\n/** Pointer speed (px/s) that tears a paper sticker instead of peeling it. */\nconst TEAR_SPEED = 2400;\n\nconst dot = (a: Vec, b: Vec) => a[0] * b[0] + a[1] * b[1];\nconst clamp = (v: number, lo: number, hi: number) =>\n  Math.min(hi, Math.max(lo, v));\nconst smooth = (from: number, to: number, dt: number, rate: number) =>\n  from + (to - from) * (1 - Math.exp(-dt * rate));\nconst smoothstep = (a: number, b: number, v: number) => {\n  const t = clamp((v - a) / (b - a), 0, 1);\n  return t * t * (3 - 2 * t);\n};\nconst rotate = ([x, y]: Vec, a: number): Vec => [\n  x * Math.cos(a) - y * Math.sin(a),\n  x * Math.sin(a) + y * Math.cos(a),\n];\n\n/** Clips a polygon to the convex half-plane where keep(p) >= 0. */\nconst clip = (points: Vec[], keep: (p: Vec) => number): Vec[] => {\n  const out: Vec[] = [];\n  for (let i = 0; i < points.length; i++) {\n    const a = points[i];\n    const b = points[(i + 1) % points.length];\n    const da = keep(a);\n    const db = keep(b);\n    if (da >= 0) {\n      out.push(a);\n    }\n    if (da >= 0 !== db >= 0) {\n      const t = da / (da - db);\n      out.push([a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t]);\n    }\n  }\n  return out;\n};\n\nconst rect = (x0: number, y0: number, x1: number, y1: number): Vec[] => [\n  [x0, y0],\n  [x1, y0],\n  [x1, y1],\n  [x0, y1],\n];\n\nconst area = (points: Vec[]) => {\n  let sum = 0;\n  for (let i = 0; i < points.length; i++) {\n    const [x0, y0] = points[i];\n    const [x1, y1] = points[(i + 1) % points.length];\n    sum += x0 * y1 - x1 * y0;\n  }\n  return Math.abs(sum) / 2;\n};\n\nconst polygon = (points: Vec[]) =>\n  points.length < 3\n    ? \"polygon(0 0, 0 0, 0 0)\"\n    : `polygon(${points.map(([x, y]) => `${x.toFixed(1)}px ${y.toFixed(1)}px`).join(\", \")})`;\n\n/**\n * A linear gradient along `n` over a w x h box, with stops given in px from\n * the line dot(p, n) = fold. CSS measures gradient angles clockwise from\n * \"to top\", so the direction (nx, ny) is atan2(nx, -ny).\n */\nconst along = (\n  w: number,\n  h: number,\n  n: Vec,\n  fold: number,\n  stops: [string, number][]\n) => {\n  const angle = (Math.atan2(n[0], -n[1]) * 180) / Math.PI;\n  const length = Math.abs(w * n[0]) + Math.abs(h * n[1]) || 1;\n  const at = (fold - dot([w / 2, h / 2], n)) / length + 0.5;\n  const list = stops\n    .map(([color, px]) => `${color} ${((at + px / length) * 100).toFixed(3)}%`)\n    .join(\", \");\n  return `linear-gradient(${angle.toFixed(3)}deg, ${list})`;\n};\n\n/** Sum of the rotations of the element and its ancestors, in radians. */\nexport const totalRotation = (element: HTMLElement): number => {\n  let angle = 0;\n  let node: HTMLElement | null = element;\n  for (let depth = 0; node && depth < 6; depth++) {\n    const style = getComputedStyle(node);\n    if (style.rotate && style.rotate !== \"none\") {\n      const value = Number.parseFloat(style.rotate);\n      angle += style.rotate.endsWith(\"rad\") ? value : (value * Math.PI) / 180;\n    }\n    if (style.transform && style.transform !== \"none\") {\n      const m = new DOMMatrix(style.transform);\n      angle += Math.atan2(m.b, m.a);\n    }\n    node = node.parentElement;\n  }\n  return angle;\n};\n\n/** Pointer position in an element's own unrotated, unscaled frame. */\nexport const toFrame = (\n  element: HTMLElement,\n  clientX: number,\n  clientY: number\n): Vec => {\n  const r = element.getBoundingClientRect();\n  const w = element.offsetWidth;\n  const h = element.offsetHeight;\n  const a = totalRotation(element);\n  const cos = Math.cos(a);\n  const sin = Math.sin(a);\n  const scale = r.width / (w * Math.abs(cos) + h * Math.abs(sin)) || 1;\n  const dx = (clientX - (r.left + r.width / 2)) / scale;\n  const dy = (clientY - (r.top + r.height / 2)) / scale;\n  return [dx * cos + dy * sin + w / 2, -dx * sin + dy * cos + h / 2];\n};\n\n/** Keeps a grabbable portion inside the caller's visible play area. */\nexport function getCanvasOffsetLimits(\n  anchor: HTMLElement,\n  bounds: HTMLElement | null | undefined,\n  centre: Vec,\n  margin: number\n): (x: number, y: number) => Vec {\n  if (!bounds) {\n    return (x, y) => [x, y];\n  }\n  const box = bounds.getBoundingClientRect();\n  const [left, top] = toFrame(anchor, box.left, box.top);\n  const [right, bottom] = toFrame(anchor, box.right, box.bottom);\n  const paddingX = Math.min(margin, (right - left) / 2);\n  const paddingY = Math.min(margin, (bottom - top) / 2);\n  return (x, y) => [\n    clamp(x, left + paddingX - centre[0], right - paddingX - centre[0]),\n    clamp(y, top + paddingY - centre[1], bottom - paddingY - centre[1]),\n  ];\n}\n\n/**\n * Replaces the straight edge a half-plane clip left on the fold line with a\n * shared ragged path, so both halves of a tear fit each other.\n */\nconst tearEdge = (\n  poly: Vec[],\n  n: Vec,\n  fold: number,\n  path: { from: Vec; points: Vec[]; to: Vec } | null\n) => {\n  const onLine = (p: Vec) => Math.abs(dot(p, n) - fold) < 0.01;\n  for (let i = 0; i < poly.length; i++) {\n    const a = poly[i];\n    const b = poly[(i + 1) % poly.length];\n    if (!(onLine(a) && onLine(b))) {\n      continue;\n    }\n    let points: Vec[];\n    let shared = path;\n    if (shared) {\n      const forward =\n        Math.hypot(a[0] - shared.from[0], a[1] - shared.from[1]) < 0.5;\n      points = forward ? shared.points : [...shared.points].reverse();\n    } else {\n      const length = Math.hypot(b[0] - a[0], b[1] - a[1]);\n      const count = Math.max(2, Math.floor(length / 6));\n      let drift = 0;\n      points = [];\n      for (let k = 1; k < count; k++) {\n        drift = clamp(drift + (Math.random() - 0.5) * 2.6, -3.2, 3.2);\n        const t = k / count;\n        const fibre = Math.random() < 0.18 ? (Math.random() - 0.5) * 3 : 0;\n        points.push([\n          a[0] + (b[0] - a[0]) * t + n[0] * (drift + fibre),\n          a[1] + (b[1] - a[1]) * t + n[1] * (drift + fibre),\n        ]);\n      }\n      shared = { from: a, points, to: b };\n    }\n    return {\n      path: shared,\n      poly: [...poly.slice(0, i + 1), ...points, ...poly.slice(i + 1)],\n    };\n  }\n  return { path, poly };\n};\n\ntype Mode = \"idle\" | \"peel\" | \"held\" | \"drop\" | \"settle\";\n\ninterface Sim {\n  angle: number;\n  /** Direction from the fold toward the lifted side, unit length. */\n  dir: Vec;\n  fold: number;\n  grab: Vec;\n  lift: number;\n  liftVel: number;\n  mode: Mode;\n  omega: number;\n  rot: number;\n  scale: number;\n  shift: Vec;\n  vel: number;\n}\n\n/** What a torn-off piece inherits so it carries on in the hand. */\ninterface Handoff {\n  angle: number;\n  dir: Vec;\n  fold: number;\n  grab: Vec;\n  pointer: Vec;\n  rot: number;\n  shift: Vec;\n}\n\ninterface Parts {\n  backShade: HTMLDivElement;\n  crease: HTMLDivElement;\n  flap: HTMLDivElement;\n  flapBack: HTMLDivElement;\n  flapFront: HTMLDivElement;\n  front: HTMLDivElement;\n  root: HTMLButtonElement;\n  shade: HTMLDivElement;\n  shadowFlap: HTMLDivElement;\n  shadowFlapShape: HTMLDivElement;\n  shadowKeep: HTMLDivElement;\n  shadowKeepShape: HTMLDivElement;\n}\n\ninterface PieceProps {\n  anchorRef: RefObject<HTMLDivElement | null>;\n  back: ReactNode;\n  backClassName?: string;\n  boundsRef?: RefObject<HTMLElement | null>;\n  children: ReactNode;\n  first: boolean;\n  hold?: Handoff;\n  label: string;\n  onMove: () => void;\n  onTear: (keep: Vec[], torn: Vec[], hold: Handoff) => void;\n  shape: Vec[] | null;\n  sounds: ReturnType<typeof createPeelSounds>;\n  tearable: boolean;\n}\n\n/**\n * One piece of a sticker on the page. It can be peeled (a 3D flap turning\n * around a straight fold, cut with a soft one-pixel mask, lit by its angle,\n * casting a blurred shadow), pulled clean off and carried, dropped anywhere\n * with a bounce, torn in two when a paper sticker is yanked, and turned over\n * with a tap to read its back.\n *\n * Peel: pulling the grabbed point a distance d lifts a lip first and then\n * folds over: depth L = max(lip, d / 2) and cos(angle) = 1 - d / L, so the\n * grabbed point stays under the pointer. Once the fold passes the far edge,\n * the sticker is off: it unfolds on a spring while the grabbed point keeps\n * following the pointer, floats on a shadow and swings with the drag. On\n * release it falls back onto the page and stays there.\n */\nfunction StickerPiece({\n  anchorRef,\n  back,\n  backClassName,\n  boundsRef,\n  children,\n  first,\n  hold,\n  label,\n  onMove,\n  onTear,\n  shape,\n  sounds,\n  tearable,\n}: PieceProps) {\n  const reduce = useReducedMotion();\n  const [flipped, setFlipped] = useState(false);\n  const refs = {\n    backShade: useRef<HTMLDivElement>(null),\n    crease: useRef<HTMLDivElement>(null),\n    flap: useRef<HTMLDivElement>(null),\n    flapBack: useRef<HTMLDivElement>(null),\n    flapFront: useRef<HTMLDivElement>(null),\n    front: useRef<HTMLDivElement>(null),\n    root: useRef<HTMLButtonElement>(null),\n    shade: useRef<HTMLDivElement>(null),\n    shadowFlap: useRef<HTMLDivElement>(null),\n    shadowFlapShape: useRef<HTMLDivElement>(null),\n    shadowKeep: useRef<HTMLDivElement>(null),\n    shadowKeepShape: useRef<HTMLDivElement>(null),\n  };\n  const sim = useRef<Sim>({\n    angle: 0,\n    dir: [Math.SQRT1_2, Math.SQRT1_2],\n    fold: 0,\n    grab: [0, 0],\n    lift: 0,\n    liftVel: 0,\n    mode: \"idle\",\n    omega: 0,\n    rot: 0,\n    scale: 1,\n    shift: [0, 0],\n    vel: 0,\n  });\n  /** The pointer, in the anchor's frame, with a smoothed velocity. */\n  const pointer = useRef({ at: [0, 0] as Vec, t: 0, vel: [0, 0] as Vec });\n  const press = useRef<{ moved: boolean; start: Vec } | null>(null);\n  const rasp = useRef<Rasp | null>(null);\n  const peeled = useRef(false);\n  const frame = useRef(0);\n  const last = useRef(0);\n  const shapeRef = useRef(shape);\n  shapeRef.current = shape;\n  const latest = useRef({ onMove, onTear, tearable });\n  latest.current = { onMove, onTear, tearable };\n  const listeners = useRef<(() => void) | null>(null);\n\n  const size = () => {\n    const root = refs.root.current;\n    return root ? { h: root.offsetHeight, w: root.offsetWidth } : null;\n  };\n\n  const outline = (w: number, h: number) =>\n    shapeRef.current ?? rect(0, 0, w, h);\n\n  const parts = (): Parts | null => {\n    const found = Object.fromEntries(\n      Object.entries(refs).map(([key, ref]) => [key, ref.current])\n    );\n    return Object.values(found).every(Boolean)\n      ? (found as unknown as Parts)\n      : null;\n  };\n\n  const toAnchor = (clientX: number, clientY: number): Vec | null => {\n    const anchor = anchorRef.current;\n    return anchor ? toFrame(anchor, clientX, clientY) : null;\n  };\n\n  /** Anchor point to the piece's own frame, undoing its move and swing. */\n  const toLocal = (p: Vec): Vec | null => {\n    const box = size();\n    if (!box) {\n      return null;\n    }\n    const s = sim.current;\n    const c: Vec = [box.w / 2, box.h / 2];\n    const back_ = rotate(\n      [p[0] - c[0] - s.shift[0], p[1] - c[1] - s.shift[1]],\n      -s.rot\n    );\n    return [c[0] + back_[0] / s.scale, c[1] + back_[1] / s.scale];\n  };\n\n  /** Where a point of the sticker lies on the page plane, with the fold. */\n  const project = (s: Sim, q: Vec): Vec => {\n    const a = dot(q, s.dir) - s.fold;\n    if (a <= 0 || s.angle < FLAT) {\n      return q;\n    }\n    const shift = s.fold + a * Math.cos(s.angle) - dot(q, s.dir);\n    return [q[0] + s.dir[0] * shift, q[1] + s.dir[1] * shift];\n  };\n\n  const draw = () => {\n    const box = size();\n    const p = parts();\n    if (!(box && p)) {\n      return;\n    }\n    const s = sim.current;\n    const { w, h } = box;\n    const S = outline(w, h);\n    const torn = shapeRef.current !== null;\n    const n = s.dir;\n    const { fold, angle, lift } = s;\n    const cos = Math.cos(angle);\n    const sin = Math.sin(angle);\n    const lifted = angle >= FLAT;\n\n    p.root.style.transform =\n      s.shift[0] || s.shift[1] || s.rot || s.scale !== 1\n        ? `translate(${s.shift[0].toFixed(2)}px, ${s.shift[1].toFixed(2)}px) rotate(${s.rot.toFixed(5)}rad) scale(${s.scale.toFixed(4)})`\n        : \"\";\n\n    // The part still flat: clipped to the stuck side of the fold, and to\n    // the torn outline when this is a piece.\n    const base = torn ? S : rect(-ROOM, -ROOM, w + ROOM, h + ROOM);\n    const keep = lifted ? clip(base, (q) => fold + 0.5 - dot(q, n)) : base;\n    p.front.style.clipPath = lifted || torn ? polygon(keep) : \"\";\n\n    // Lifted shadow of the flat part, while the sticker floats.\n    if (lift > 0.4) {\n      const flatPart = lifted ? clip(S, (q) => fold - dot(q, n)) : S;\n      p.shadowKeepShape.style.clipPath = polygon(\n        flatPart.map(\n          (q): Vec => [\n            q[0] - LIGHT[0] * lift * 0.6,\n            q[1] - LIGHT[1] * lift * 0.6,\n          ]\n        )\n      );\n      p.shadowKeep.style.filter = `blur(${(2 + lift * 0.3).toFixed(1)}px)`;\n      p.shadowKeep.style.opacity = (0.32 / (1 + lift / 50)).toFixed(3);\n      p.shadowKeep.style.visibility = \"visible\";\n    } else {\n      p.shadowKeep.style.visibility = \"hidden\";\n    }\n\n    if (!lifted) {\n      p.flap.style.visibility = \"hidden\";\n      p.shadowFlap.style.visibility = \"hidden\";\n      return;\n    }\n\n    // The flap turns around the fold line, toward the viewer.\n    p.flap.style.transformOrigin = `${(n[0] * fold).toFixed(2)}px ${(n[1] * fold).toFixed(2)}px`;\n    p.flap.style.transform = `rotate3d(${(-n[1]).toFixed(5)}, ${n[0].toFixed(5)}, 0, ${(-angle).toFixed(5)}rad)`;\n    p.flap.style.visibility = \"visible\";\n\n    // Each face keeps the lifted side, with a soft one-pixel edge. The back\n    // face is mirrored left to right, so its mask and outline are too.\n    const nb: Vec = [-n[0], n[1]];\n    const foldB = fold - w * n[0];\n    const mask = along(w, h, n, fold, [\n      [\"transparent\", -0.5],\n      [\"#000\", 0.5],\n    ]);\n    const maskB = along(w, h, nb, foldB, [\n      [\"transparent\", -0.5],\n      [\"#000\", 0.5],\n    ]);\n    p.flapFront.style.maskImage = mask;\n    p.flapFront.style.webkitMaskImage = mask;\n    p.flapBack.style.maskImage = maskB;\n    p.flapBack.style.webkitMaskImage = maskB;\n    p.flapFront.style.clipPath = torn ? polygon(S) : \"\";\n    p.flapBack.style.clipPath = torn\n      ? polygon(S.map(([x, y]): Vec => [w - x, y]))\n      : \"\";\n\n    // Light on each face from its turned normal (-n sin, cos).\n    const lit = (side: 1 | -1) =>\n      clamp(\n        (side *\n          (-n[0] * sin * LIGHT[0] - n[1] * sin * LIGHT[1] + cos * LIGHT[2])) /\n          LIGHT[2],\n        0,\n        1\n      );\n    p.shade.style.opacity = (0.5 - 0.5 * lit(1)).toFixed(3);\n    p.backShade.style.opacity = (0.16 - 0.16 * lit(-1)).toFixed(3);\n\n    const reach = Math.max(0, Math.max(...S.map((q) => dot(q, n))) - fold);\n    p.crease.style.backgroundImage = along(w, h, nb, foldB, [\n      [\"rgb(0 0 0 / 0.22)\", 0],\n      [\"rgb(0 0 0 / 0.06)\", 4],\n      [\"rgb(0 0 0 / 0)\", 12],\n      [\"rgb(0 0 0 / 0)\", Math.max(13, reach * 0.7)],\n      [\"rgb(0 0 0 / 0.06)\", Math.max(14, reach)],\n    ]);\n\n    // Cast shadow of the flap: its footprint pushed away from the light by\n    // its height, blurrier and fainter the higher it is.\n    const cast = clip(S, (q) => dot(q, n) - fold).map((q): Vec => {\n      const a = dot(q, n) - fold;\n      const slide = fold + a * cos - dot(q, n);\n      const height = a * sin + lift;\n      return [\n        q[0] + n[0] * slide - LIGHT[0] * height * 0.5,\n        q[1] + n[1] * slide - LIGHT[1] * height * 0.5,\n      ];\n    });\n    p.shadowFlapShape.style.clipPath = polygon(cast);\n    const rise = reach * Math.max(0, sin) * 0.5 + lift;\n    p.shadowFlap.style.filter = `blur(${(2.5 + rise * 0.15).toFixed(1)}px)`;\n    p.shadowFlap.style.opacity = (\n      (0.3 * smoothstep(0.04, 0.5, angle)) /\n      (1 + rise / 120)\n    ).toFixed(3);\n    p.shadowFlap.style.visibility = \"visible\";\n  };\n\n  const stopRasp = () => {\n    rasp.current?.stop();\n    rasp.current = null;\n  };\n\n  /** Off the page: the rest of the sticker comes with the pointer. */\n  const detach = (s: Sim, box: { h: number; w: number }) => {\n    const S = outline(box.w, box.h);\n    s.fold = Math.min(...S.map((q) => dot(q, s.dir))) - 0.5;\n    s.mode = \"held\";\n    s.vel = 0;\n    stopRasp();\n    sounds.playPop();\n    sounds.playWhoosh(0.7);\n  };\n\n  /** A fast yank on paper splits it along the fold with a ragged edge. */\n  const tear = (s: Sim, box: { h: number; w: number }) => {\n    const S = outline(box.w, box.h);\n    const n = s.dir;\n    const keep = clip(S, (q) => s.fold - dot(q, n));\n    const torn = clip(S, (q) => dot(q, n) - s.fold);\n    const whole = area(S);\n    if (area(keep) < whole * 0.15 || area(torn) < whole * 0.15) {\n      return false;\n    }\n    const first_ = tearEdge(keep, n, s.fold, null);\n    const second = tearEdge(torn, n, s.fold, first_.path);\n    const length = first_.path\n      ? Math.hypot(\n          first_.path.to[0] - first_.path.from[0],\n          first_.path.to[1] - first_.path.from[1]\n        )\n      : 200;\n    stopRasp();\n    sounds.playTear(length);\n    const handoff: Handoff = {\n      angle: s.angle,\n      dir: n,\n      fold: s.fold,\n      grab: s.grab,\n      pointer: pointer.current.at,\n      rot: s.rot,\n      shift: s.shift,\n    };\n    s.angle = 0;\n    s.mode = \"idle\";\n    press.current = null;\n    peeled.current = true;\n    listeners.current?.();\n    latest.current.onTear(first_.poly, second.poly, handoff);\n    return true;\n  };\n\n  const stepPeel = (s: Sim, dt: number, box: { h: number; w: number }) => {\n    const local = toLocal(pointer.current.at);\n    if (!local) {\n      return;\n    }\n    const dx = s.grab[0] - local[0];\n    const dy = s.grab[1] - local[1];\n    const d = Math.hypot(dx, dy);\n    const prevFold = s.fold;\n    const prevAngle = s.angle;\n    if (d < 0.5) {\n      s.angle = smooth(s.angle, 0, dt, 24);\n      return;\n    }\n    const k = 1 - Math.exp(-dt * 28);\n    const nx = s.dir[0] + (dx / d - s.dir[0]) * k;\n    const ny = s.dir[1] + (dy / d - s.dir[1]) * k;\n    const len = Math.hypot(nx, ny) || 1;\n    s.dir = [nx / len, ny / len];\n    const lip = clamp(Math.min(box.w, box.h) * 0.22, 20, 64);\n    const pulled = Math.max(0, dot(s.grab, s.dir) - dot(local, s.dir));\n    const depth = Math.max(lip, pulled / 2);\n    const wantAngle = Math.acos(clamp(1 - pulled / depth, -1, 1));\n    const wantFold = dot(s.grab, s.dir) - depth;\n    s.fold = s.angle < FLAT * 2 ? wantFold : smooth(s.fold, wantFold, dt, 24);\n    s.angle = reduce ? wantAngle : smooth(s.angle, wantAngle, dt, 24);\n\n    const speed = Math.hypot(...pointer.current.vel);\n    if (\n      latest.current.tearable &&\n      speed > TEAR_SPEED &&\n      s.angle > 1.1 &&\n      tear(s, box)\n    ) {\n      return;\n    }\n    const S = outline(box.w, box.h);\n    if (s.fold <= Math.min(...S.map((q) => dot(q, s.dir))) + 0.5) {\n      detach(s, box);\n      return;\n    }\n    rasp.current?.update(\n      (Math.abs(s.fold - prevFold) + Math.abs(s.angle - prevAngle) * 40) / dt\n    );\n  };\n\n  /** In the hand: unfold, float, keep the grabbed point under the pointer. */\n  const stepHeld = (s: Sim, dt: number, box: { h: number; w: number }) => {\n    const k = 170;\n    s.vel += (-k * s.angle - 2 * Math.sqrt(k) * 0.85 * s.vel) * dt;\n    s.angle = Math.max(0, s.angle + s.vel * dt);\n    if (reduce) {\n      s.angle = 0;\n    }\n    s.lift = reduce ? LIFT : smooth(s.lift, LIFT, dt, 14);\n    s.scale = 1 + s.lift / 520;\n    const c: Vec = [box.w / 2, box.h / 2];\n    const q = project(s, s.grab);\n    const arm = rotate(\n      [(q[0] - c[0]) * s.scale, (q[1] - c[1]) * s.scale],\n      s.rot\n    );\n    const reach = Math.hypot(...arm);\n    if (!reduce && reach > 4) {\n      const [vx, vy] = pointer.current.vel;\n      const torque = (arm[0] * vy - arm[1] * vx) / reach;\n      s.omega += torque * 0.012 * Math.min(reach / 110, 1) * dt;\n    }\n    // A weak pull back toward upright, so a sticker swings but never ends\n    // up hanging upside down.\n    s.omega += -s.rot * 5 * dt;\n    s.omega *= Math.exp(-4.5 * dt);\n    s.rot += s.omega * dt;\n    const placed = rotate(\n      [(q[0] - c[0]) * s.scale, (q[1] - c[1]) * s.scale],\n      s.rot\n    );\n    const { at } = pointer.current;\n    s.shift = [at[0] - c[0] - placed[0], at[1] - c[1] - placed[1]];\n  };\n\n  /** Let go in the air: unfold the rest, fall, tap the page, settle. */\n  const stepDrop = (s: Sim, dt: number): boolean => {\n    if (reduce) {\n      s.angle = 0;\n      s.lift = 0;\n      s.scale = 1;\n      s.omega = 0;\n      return false;\n    }\n    const k = 170;\n    s.vel += (-k * s.angle - 2 * Math.sqrt(k) * 0.85 * s.vel) * dt;\n    s.angle = Math.max(0, s.angle + s.vel * dt);\n    const steps = 4;\n    const h = dt / steps;\n    for (let i = 0; i < steps; i++) {\n      s.liftVel += (-260 * s.lift - 2 * Math.sqrt(260) * 0.55 * s.liftVel) * h;\n      s.lift += s.liftVel * h;\n      if (s.lift < 0) {\n        s.lift = 0;\n        const impact = -s.liftVel;\n        if (impact > 20) {\n          sounds.playStick(clamp(impact / 260, 0.2, 1.1));\n        }\n        s.liftVel = impact * 0.25 < 18 ? 0 : impact * 0.25;\n      }\n    }\n    s.scale = 1 + s.lift / 520;\n    s.omega += -s.rot * 4 * dt;\n    s.omega *= Math.exp(-9 * dt);\n    s.rot += s.omega * dt;\n    return !(\n      s.lift < 0.05 &&\n      Math.abs(s.liftVel) < 0.5 &&\n      s.angle < 0.004 &&\n      Math.abs(s.omega) < 0.002\n    );\n  };\n\n  /** Damped spring back to the page, in substeps; taps and bounces at 0. */\n  const stepSettle = (s: Sim, dt: number): boolean => {\n    if (reduce) {\n      s.angle = 0;\n      s.vel = 0;\n      return false;\n    }\n    const stiffness = 210;\n    const damping = 2 * Math.sqrt(stiffness) * 0.38;\n    const steps = 4;\n    const h = dt / steps;\n    for (let i = 0; i < steps; i++) {\n      s.vel += (-stiffness * s.angle - damping * s.vel) * h;\n      s.angle += s.vel * h;\n      if (s.angle < 0) {\n        s.angle = 0;\n        const impact = -s.vel;\n        if (impact > 0.6) {\n          sounds.playStick(clamp(impact / 9, 0.15, 1.1));\n        }\n        s.vel = impact * 0.28 < 0.5 ? 0 : impact * 0.28;\n      }\n    }\n    return !(Math.abs(s.vel) < 0.03 && s.angle < 0.004);\n  };\n\n  /** Advances one frame; false once the sticker is at rest. */\n  const step = (s: Sim, dt: number, box: { h: number; w: number }) => {\n    switch (s.mode) {\n      case \"peel\":\n        stepPeel(s, dt, box);\n        return true;\n      case \"held\":\n        stepHeld(s, dt, box);\n        return true;\n      case \"drop\":\n        if (stepDrop(s, dt)) {\n          return true;\n        }\n        Object.assign(s, {\n          angle: 0,\n          lift: 0,\n          liftVel: 0,\n          mode: \"idle\",\n          omega: 0,\n          scale: 1,\n          vel: 0,\n        });\n        latest.current.onMove();\n        return false;\n      case \"settle\":\n        if (stepSettle(s, dt)) {\n          return true;\n        }\n        Object.assign(s, { angle: 0, mode: \"idle\", vel: 0 });\n        return false;\n      default:\n        return false;\n    }\n  };\n\n  const tick = (now: number) => {\n    const dt = Math.min(0.05, (now - (last.current || now)) / 1000) || 1 / 60;\n    last.current = now;\n    const box = size();\n    const running = box ? step(sim.current, dt, box) : false;\n    draw();\n    frame.current = running ? requestAnimationFrame(tick) : 0;\n  };\n\n  const run = () => {\n    if (!frame.current) {\n      last.current = 0;\n      frame.current = requestAnimationFrame(tick);\n    }\n  };\n\n  const release = () => {\n    const s = sim.current;\n    stopRasp();\n    if (s.mode === \"held\") {\n      const anchor = anchorRef.current;\n      const box = size();\n      if (anchor && box && boundsRef?.current) {\n        const outlinePoints = outline(box.w, box.h);\n        const xs = outlinePoints.map(([x]) => x);\n        const ys = outlinePoints.map(([, y]) => y);\n        const centre: Vec = [\n          (Math.min(...xs) + Math.max(...xs)) / 2,\n          (Math.min(...ys) + Math.max(...ys)) / 2,\n        ];\n        s.shift = getCanvasOffsetLimits(\n          anchor,\n          boundsRef.current,\n          centre,\n          24\n        )(...s.shift);\n      }\n      s.mode = \"drop\";\n      s.liftVel = 0;\n      sounds.playWhoosh(0.4, 0.16);\n    } else if (s.mode === \"peel\") {\n      s.vel = 0;\n      s.mode = \"settle\";\n    }\n    run();\n  };\n\n  const track = (event: PointerEvent) => {\n    const at = toAnchor(event.clientX, event.clientY);\n    if (!at) {\n      return;\n    }\n    const p = pointer.current;\n    const now = performance.now();\n    const dt = Math.max(1, now - p.t) / 1000;\n    const k = 1 - Math.exp(-dt * 30);\n    p.vel = [\n      p.vel[0] + ((at[0] - p.at[0]) / dt - p.vel[0]) * k,\n      p.vel[1] + ((at[1] - p.at[1]) / dt - p.vel[1]) * k,\n    ];\n    p.at = at;\n    p.t = now;\n  };\n\n  /** Window listeners for the life of one press, so a torn piece inherits it. */\n  const listen = () => {\n    listeners.current?.();\n    const move = (event: PointerEvent) => {\n      // A release we never heard about (outside the window): let go now.\n      if (event.buttons === 0) {\n        up();\n        return;\n      }\n      track(event);\n      const s = sim.current;\n      const pr = press.current;\n      if (pr && !pr.moved && s.mode !== \"held\") {\n        const local = toLocal(pointer.current.at);\n        if (\n          !local ||\n          Math.hypot(local[0] - pr.start[0], local[1] - pr.start[1]) < TAP_SLOP\n        ) {\n          return;\n        }\n        pr.moved = true;\n        s.angle = 0;\n        s.grab = pr.start;\n        s.mode = \"peel\";\n        sounds.playPeelStart();\n        rasp.current = sounds.startRasp();\n      }\n      run();\n    };\n    const up = () => {\n      const pr = press.current;\n      press.current = null;\n      stop();\n      if (!pr || pr.moved || sim.current.mode === \"held\") {\n        peeled.current = true;\n        release();\n      }\n    };\n    const stop = () => {\n      window.removeEventListener(\"pointermove\", move);\n      window.removeEventListener(\"pointerup\", up);\n      window.removeEventListener(\"pointercancel\", up);\n      window.removeEventListener(\"blur\", up);\n      listeners.current = null;\n    };\n    window.addEventListener(\"pointermove\", move);\n    window.addEventListener(\"pointerup\", up);\n    window.addEventListener(\"pointercancel\", up);\n    window.addEventListener(\"blur\", up);\n    listeners.current = stop;\n  };\n\n  // A torn-off piece starts life in the hand, carrying on the same press.\n  // biome-ignore lint/correctness/useExhaustiveDependencies: runs once on mount with the handoff it was born with\n  useEffect(() => {\n    if (hold) {\n      const s = sim.current;\n      Object.assign(s, {\n        angle: hold.angle,\n        dir: hold.dir,\n        fold: hold.fold,\n        grab: hold.grab,\n        rot: hold.rot,\n        shift: hold.shift,\n      });\n      pointer.current = { at: hold.pointer, t: performance.now(), vel: [0, 0] };\n      press.current = { moved: true, start: hold.grab };\n      // Already all on the lifted side of the tear: it is off the page.\n      s.mode = \"held\";\n      s.vel = 0;\n      listen();\n      run();\n    }\n    return () => {\n      cancelAnimationFrame(frame.current);\n      frame.current = 0;\n      listeners.current?.();\n      stopRasp();\n    };\n  }, []);\n\n  // A tear changes this piece's outline: redraw it with the new edge.\n  // biome-ignore lint/correctness/useExhaustiveDependencies: redraw only when the outline changes\n  useEffect(() => {\n    draw();\n  }, [shape]);\n\n  const flip = () => {\n    sounds.playFlip();\n    setFlipped((value) => !value);\n  };\n\n  const onPointerDown = (event: ReactPointerEvent<HTMLButtonElement>) => {\n    if (event.button !== 0 || flipped) {\n      return;\n    }\n    const at = toAnchor(event.clientX, event.clientY);\n    const local = at && toLocal(at);\n    const box = size();\n    if (!(at && local && box)) {\n      return;\n    }\n    pointer.current = { at, t: performance.now(), vel: [0, 0] };\n    press.current = { moved: false, start: local };\n    // Capture keeps the moves and the release coming even outside the\n    // window; the window listeners below still hear them as they bubble.\n    event.currentTarget.setPointerCapture(event.pointerId);\n    listen();\n  };\n\n  /** A tap, Enter or Space turns the sticker over; a peel's release does not. */\n  const onClick = () => {\n    if (peeled.current) {\n      peeled.current = false;\n      return;\n    }\n    flip();\n  };\n\n  const backFace = (\n    <div\n      className={cn(\n        \"size-full overflow-hidden bg-[#f4f1ea] dark:bg-[#e2ded5]\",\n        backClassName\n      )}\n    >\n      {back}\n    </div>\n  );\n\n  return (\n    <button\n      aria-pressed={flipped}\n      className={cn(\n        \"perspective-[1400px] pointer-events-auto block w-full cursor-grab touch-none select-none text-left focus-visible:outline-2 focus-visible:outline-brand focus-visible:outline-offset-4 active:cursor-grabbing\",\n        first ? \"relative\" : \"absolute inset-0\"\n      )}\n      onClick={onClick}\n      onPointerDown={onPointerDown}\n      ref={refs.root}\n      type=\"button\"\n    >\n      <span className=\"sr-only\">{label}</span>\n\n      {/* Shadow under the sticker while it floats in the hand. */}\n      <div\n        aria-hidden=\"true\"\n        className=\"pointer-events-none invisible absolute inset-0\"\n        ref={refs.shadowKeep}\n      >\n        <div className=\"size-full bg-black\" ref={refs.shadowKeepShape} />\n      </div>\n\n      <div\n        className={cn(\n          \"transform-3d relative\",\n          !reduce &&\n            \"transition-transform duration-500 ease-[cubic-bezier(0.32,0.72,0,1)]\"\n        )}\n        style={{ transform: flipped ? \"rotateY(180deg)\" : undefined }}\n      >\n        <div className=\"backface-hidden\" ref={refs.front}>\n          {children}\n        </div>\n        <div\n          aria-hidden={!flipped}\n          className=\"backface-hidden absolute inset-0 rotate-y-180 drop-shadow-[0_6px_10px_rgb(0_0_0/0.2)]\"\n          style={{\n            clipPath: shape\n              ? polygon(\n                  shape.map(\n                    ([x, y]): Vec => [\n                      (refs.root.current?.offsetWidth ?? 0) - x,\n                      y,\n                    ]\n                  )\n                )\n              : undefined,\n          }}\n        >\n          {backFace}\n        </div>\n      </div>\n\n      {/* Shadow the lifted flap casts on the page. */}\n      <div\n        aria-hidden=\"true\"\n        className=\"pointer-events-none invisible absolute inset-0\"\n        ref={refs.shadowFlap}\n      >\n        <div className=\"size-full bg-black\" ref={refs.shadowFlapShape} />\n      </div>\n\n      {/* The lifted flap: a 3D card with the sticker and its backing. */}\n      <div\n        aria-hidden=\"true\"\n        className=\"transform-3d pointer-events-none invisible absolute inset-0 will-change-transform\"\n        ref={refs.flap}\n      >\n        <div\n          className=\"backface-hidden absolute inset-0 [mask-repeat:no-repeat]\"\n          ref={refs.flapFront}\n        >\n          {children}\n          <div\n            className=\"absolute inset-0 bg-black opacity-0\"\n            ref={refs.shade}\n          />\n        </div>\n        <div\n          className=\"backface-hidden absolute inset-0 rotate-y-180 [mask-repeat:no-repeat]\"\n          ref={refs.flapBack}\n        >\n          {backFace}\n          <div\n            className=\"absolute inset-0 bg-black opacity-0\"\n            ref={refs.backShade}\n          />\n          <div className=\"absolute inset-0\" ref={refs.crease} />\n        </div>\n      </div>\n    </button>\n  );\n}\n\ninterface Piece {\n  hold?: Handoff;\n  id: number;\n  shape: Vec[] | null;\n}\n\n/**\n * A photo sticker: one piece to start with, two once a paper one is torn.\n * Every piece can be peeled, carried, dropped and turned over on its own.\n */\nexport interface PeelableStickerProps {\n  back: ReactNode;\n  backClassName?: string;\n  /** Optional play area; released pieces remain reachable inside it. */\n  boundsRef?: RefObject<HTMLElement | null>;\n  children: ReactNode;\n  label: string;\n  onChange?: () => void;\n  sound?: boolean;\n  tearable?: boolean;\n}\n\nexport default function PeelableSticker({\n  back,\n  backClassName,\n  boundsRef,\n  children,\n  label,\n  onChange,\n  sound = false,\n  tearable = false,\n}: PeelableStickerProps) {\n  const sounds = createPeelSounds(useMaterialAudio(sound));\n  const anchorRef = useRef<HTMLDivElement>(null);\n  const [pieces, setPieces] = useState<Piece[]>([{ id: 0, shape: null }]);\n  const torn = pieces.length > 1;\n  const changed = () => onChange?.();\n\n  return (\n    <div className=\"relative\" ref={anchorRef}>\n      {pieces.map((piece, index) => (\n        <StickerPiece\n          anchorRef={anchorRef}\n          back={back}\n          backClassName={backClassName}\n          boundsRef={boundsRef}\n          first={index === 0}\n          hold={piece.hold}\n          key={piece.id}\n          label={label}\n          onMove={changed}\n          onTear={(keep, tornShape, hold) => {\n            setPieces((current) => [\n              ...current.map((p) =>\n                p.id === piece.id ? { ...p, shape: keep } : p\n              ),\n              { hold, id: current.length, shape: tornShape },\n            ]);\n            changed();\n          }}\n          shape={piece.shape}\n          sounds={sounds}\n          tearable={tearable && !torn}\n        >\n          {children}\n        </StickerPiece>\n      ))}\n    </div>\n  );\n}\n","path":"index.tsx","target":"components/smoothui/peelable-sticker/index.tsx","type":"registry:ui"},{"content":"\"use client\";\n\nimport { useCallback, useEffect, useRef } from \"react\";\n\ninterface Output {\n  context: AudioContext;\n  master: GainNode;\n}\nexport type MaterialOutput = () => Output | null;\n\nexport function useMaterialAudio(enabled: boolean): MaterialOutput {\n  const live = useRef<Output | null>(null);\n  const enabledRef = useRef(enabled);\n  enabledRef.current = enabled;\n\n  useEffect(() => {\n    if (live.current) {\n      live.current.master.gain.value = enabled ? 0.28 : 0;\n    }\n  }, [enabled]);\n  useEffect(\n    () => () => {\n      const output = live.current;\n      live.current = null;\n      if (output && output.context.state !== \"closed\") {\n        output.context.close().catch(() => undefined);\n      }\n    },\n    []\n  );\n\n  return useCallback(() => {\n    if (!enabledRef.current || typeof AudioContext === \"undefined\") {\n      return null;\n    }\n    try {\n      if (!live.current) {\n        const context = new AudioContext();\n        const master = context.createGain();\n        master.gain.value = 0.28;\n        master.connect(context.destination);\n        live.current = { context, master };\n      }\n      if (live.current.context.state === \"suspended\") {\n        live.current.context.resume().catch(() => undefined);\n      }\n      return live.current;\n    } catch {\n      return null;\n    }\n  }, []);\n}\n","path":"material-audio.ts","target":"components/smoothui/peelable-sticker/material-audio.ts","type":"registry:ui"},{"content":"/**\n * Sticker sounds, synthesised from white noise so they need no files and\n * never sound the same twice: a crackle when the glue lets go, a dry rasp\n * that follows the drag speed while peeling, and a soft thump when the\n * sticker lands back on the page. They go through the site's sound engine,\n * so the sound switch mutes them too.\n */\n\nimport type { MaterialOutput } from \"./material-audio\";\n\ntype Output = NonNullable<ReturnType<MaterialOutput>>;\n\nlet noise: AudioBuffer | null = null;\n\nexport const noiseFor = (context: AudioContext): AudioBuffer => {\n  if (noise?.sampleRate === context.sampleRate) {\n    return noise;\n  }\n  const length = context.sampleRate * 2;\n  const buffer = context.createBuffer(1, length, context.sampleRate);\n  const data = buffer.getChannelData(0);\n  for (let i = 0; i < length; i++) {\n    data[i] = Math.random() * 2 - 1;\n  }\n  noise = buffer;\n  return buffer;\n};\n\nconst clamp = (value: number, min: number, max: number) =>\n  Math.min(max, Math.max(min, value));\n\n/** One short filtered noise grain with a fast attack and exponential tail. */\nexport const grain = (\n  { context, master }: Output,\n  {\n    at,\n    duration,\n    frequency,\n    gain,\n    q,\n    type = \"bandpass\",\n  }: {\n    at: number;\n    duration: number;\n    frequency: number;\n    gain: number;\n    q: number;\n    type?: BiquadFilterType;\n  }\n) => {\n  const source = context.createBufferSource();\n  source.buffer = noiseFor(context);\n  const filter = context.createBiquadFilter();\n  filter.type = type;\n  filter.frequency.value = frequency;\n  filter.Q.value = q;\n  const amp = context.createGain();\n  amp.gain.setValueAtTime(0, at);\n  amp.gain.linearRampToValueAtTime(gain, at + 0.0005);\n  amp.gain.exponentialRampToValueAtTime(0.0001, at + duration);\n  source.connect(filter).connect(amp).connect(master);\n  source.start(at, Math.random() * 1.8, duration + 0.01);\n};\n\nexport interface Rasp {\n  stop: () => void;\n  update: (speed: number) => void;\n}\n\nexport function createPeelSounds(synthOutput: MaterialOutput) {\n  /** The glue letting go: a few tiny clicks a few milliseconds apart. */\n  const playPeelStart = () => {\n    const out = synthOutput();\n    if (!out) {\n      return;\n    }\n    const now = out.context.currentTime;\n    const count = 3 + Math.floor(Math.random() * 4);\n    for (let i = 0; i < count; i++) {\n      grain(out, {\n        at: now + i * (0.003 + Math.random() * 0.007),\n        duration: 0.008 + Math.random() * 0.012,\n        frequency: 2400 * (0.6 + Math.random() * 0.9),\n        gain: 0.2 + Math.random() * 0.3,\n        q: 1.3,\n      });\n    }\n  };\n\n  /**\n   * The paper rasp while peeling: looped noise through a band-pass whose\n   * level and pitch follow the drag speed (px per second). Silent at rest.\n   */\n  const startRasp = (): Rasp | null => {\n    const out = synthOutput();\n    if (!out) {\n      return null;\n    }\n    const { context, master } = out;\n    const source = context.createBufferSource();\n    source.buffer = noiseFor(context);\n    source.loop = true;\n    const filter = context.createBiquadFilter();\n    filter.type = \"bandpass\";\n    filter.Q.value = 0.9;\n    filter.frequency.value = 1100;\n    const amp = context.createGain();\n    amp.gain.value = 0;\n    source.connect(filter).connect(amp).connect(master);\n    source.start();\n\n    return {\n      stop: () => {\n        const now = context.currentTime;\n        amp.gain.setTargetAtTime(0, now, 0.03);\n        source.stop(now + 0.2);\n      },\n      update: (speed) => {\n        const now = context.currentTime;\n        filter.frequency.setTargetAtTime(\n          1300 * (0.8 + clamp(speed / 1500, 0, 0.6)),\n          now,\n          0.02\n        );\n        amp.gain.setTargetAtTime(clamp(speed / 900, 0, 1) * 0.3, now, 0.025);\n      },\n    };\n  };\n\n  /** Landing back on the page: a dull low thump with a little paper slap. */\n  const playStick = (strength = 1) => {\n    const out = synthOutput();\n    if (!out) {\n      return;\n    }\n    const { context, master } = out;\n    const at = context.currentTime + 0.001;\n    const level = clamp(strength, 0.2, 1.2);\n    grain(out, {\n      at,\n      duration: 0.018,\n      frequency: 3400,\n      gain: 0.4 * level,\n      q: 0.7,\n      type: \"lowpass\",\n    });\n    const thump = context.createOscillator();\n    thump.frequency.setValueAtTime(150, at);\n    thump.frequency.exponentialRampToValueAtTime(90, at + 0.03);\n    const amp = context.createGain();\n    amp.gain.setValueAtTime(0, at);\n    amp.gain.linearRampToValueAtTime(0.45 * level, at + 0.002);\n    amp.gain.exponentialRampToValueAtTime(0.0001, at + 0.08);\n    thump.connect(amp).connect(master);\n    thump.start(at);\n    thump.stop(at + 0.12);\n  };\n\n  /** Flipping the photo over in the hand: a short soft swish. */\n  const playFlip = () => {\n    const out = synthOutput();\n    if (!out) {\n      return;\n    }\n    const now = out.context.currentTime + 0.001;\n    grain(out, {\n      at: now,\n      duration: 0.09,\n      frequency: 1400,\n      gain: 0.22,\n      q: 0.7,\n      type: \"lowpass\",\n    });\n    grain(out, {\n      at: now + 0.01,\n      duration: 0.05,\n      frequency: 3600,\n      gain: 0.06,\n      q: 1.1,\n    });\n  };\n\n  /** The last bit of glue letting go as the sticker comes off the page. */\n  const playPop = () => {\n    const out = synthOutput();\n    if (!out) {\n      return;\n    }\n    const now = out.context.currentTime;\n    for (let i = 0; i < 6; i++) {\n      grain(out, {\n        at: now + i * (0.002 + Math.random() * 0.005),\n        duration: 0.006 + Math.random() * 0.01,\n        frequency: 2600 * (0.6 + Math.random() * 0.9),\n        gain: 0.25 + Math.random() * 0.3,\n        q: 1.3,\n      });\n    }\n    grain(out, {\n      at: now + 0.004,\n      duration: 0.03,\n      frequency: 1800,\n      gain: 0.5,\n      q: 1.4,\n    });\n  };\n\n  /** Air moving as the sticker is lifted away: a short band-pass sweep. */\n  const playWhoosh = (level = 0.7, duration = 0.22) => {\n    const out = synthOutput();\n    if (!out) {\n      return;\n    }\n    const { context, master } = out;\n    const now = context.currentTime;\n    const source = context.createBufferSource();\n    source.buffer = noiseFor(context);\n    const filter = context.createBiquadFilter();\n    filter.type = \"bandpass\";\n    filter.Q.value = 0.8;\n    filter.frequency.setValueAtTime(500, now);\n    filter.frequency.exponentialRampToValueAtTime(1800, now + duration * 0.5);\n    filter.frequency.exponentialRampToValueAtTime(700, now + duration);\n    const amp = context.createGain();\n    amp.gain.setValueAtTime(0, now);\n    amp.gain.linearRampToValueAtTime(0.09 * level, now + duration * 0.35);\n    amp.gain.exponentialRampToValueAtTime(0.0001, now + duration);\n    source.connect(filter).connect(amp).connect(master);\n    source.start(now, Math.random(), duration + 0.02);\n  };\n\n  /** Paper tearing: a dense run of fibre clicks over a low ripping body. */\n  const playTear = (length: number) => {\n    const out = synthOutput();\n    if (!out) {\n      return;\n    }\n    const now = out.context.currentTime;\n    const duration = clamp(length / 700, 0.07, 0.3);\n    const count = Math.round(duration * 240);\n    for (let i = 0; i < count; i++) {\n      const t = i / count;\n      grain(out, {\n        at: now + duration * t + Math.random() * 0.003,\n        duration: 0.004 + Math.random() * 0.01,\n        frequency: 2400 * (0.35 + Math.random() * 0.9),\n        gain: (0.3 + Math.random() * 0.6) * 0.5 * (1 - t * 0.45),\n        q: 0.8 + Math.random() * 1.6,\n      });\n    }\n    grain(out, {\n      at: now,\n      duration: duration * 1.1,\n      frequency: 1100,\n      gain: 0.16,\n      q: 0.6,\n    });\n  };\n\n  return {\n    playFlip,\n    playPeelStart,\n    playPop,\n    playStick,\n    playTear,\n    playWhoosh,\n    startRasp,\n  };\n}\n","path":"peel-sounds.ts","target":"components/smoothui/peelable-sticker/peel-sounds.ts","type":"registry:ui"}],"name":"peelable-sticker","registryDependencies":["https://smoothui.dev/r/tokens.json"],"title":"Peelable Sticker","type":"registry:ui"}