{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "confetti",
  "title": "Confetti",
  "description": "Hand-written canvas 2D confetti with flipping paper physics, fired over the page from an element or inside a contained canvas via ref, and a no-op under reduced motion.",
  "dependencies": [],
  "registryDependencies": [
    "https://goodui.dev/r/sounds.json"
  ],
  "files": [
    {
      "path": "registry/components/feedback/confetti.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\nimport { cn } from \"@/lib/utils\"\nimport type { SoundName } from \"@/lib/goodui-sounds\"\n\nexport type ConfettiShape = \"square\" | \"circle\" | \"strip\"\n\nexport type ConfettiOptions = {\n  /** Launch point in viewport px (clientX/clientY). Defaults to the element's center, then the canvas center. */\n  origin?: { x: number; y: number }\n  /** Burst from the center of this element. */\n  element?: Element | null\n  /** Pieces per burst. */\n  particleCount?: number\n  /** Launch direction in degrees. 90 is straight up, 0 is right, 180 is left. */\n  angle?: number\n  /** Cone width in degrees. */\n  spread?: number\n  /** Launch speed in px per frame. */\n  startVelocity?: number\n  /** 1 is normal gravity, 0 floats. */\n  gravity?: number\n  /** Speed kept per frame, 0 to 1. Lower stops sooner. */\n  decay?: number\n  /** Sideways wind in px per frame. */\n  drift?: number\n  /** Lifetime in frames at 60fps. */\n  ticks?: number\n  /** Particle size multiplier. */\n  scalar?: number\n  /** Any CSS colors; each piece picks one at random. */\n  colors?: string[]\n  /** Shapes to pick from at random; repeat one to make it more common. */\n  shapes?: ConfettiShape[]\n  /**\n   * Confetti is for rare moments. With a key, the burst fires once per page load and later calls with that key do\n   * nothing, e.g. fireConfetti({ once: \"first-booking\" }).\n   */\n  once?: string\n  /** Plays \"celebrate\" with the burst when the visitor has sounds on (lib/goodui-sounds); pass a sound name to pick another. Off by default. */\n  sound?: boolean | SoundName\n}\n\n// Optional UI sound: the sound module is loaded only when `sound` is on, so silent apps pay nothing.\nfunction cue(sound: boolean | SoundName | undefined) {\n  if (!sound) return\n  void import(\"@/lib/goodui-sounds\").then((m) => m.play(sound === true ? \"celebrate\" : sound))\n}\n\nconst fired = new Set<string>()\n\nfunction firstTime(key: string | undefined) {\n  if (key === undefined) return true\n  if (fired.has(key)) return false\n  fired.add(key)\n  return true\n}\n\nconst DEFAULT_COLORS: [string, ...string[]] = [\"#f43f5e\", \"#f59e0b\", \"#10b981\", \"#0ea5e9\", \"#8b5cf6\", \"#ec4899\", \"#facc15\"]\n\ntype Particle = {\n  x: number\n  y: number\n  angle: number\n  velocity: number\n  gravity: number\n  decay: number\n  drift: number\n  wobble: number\n  wobbleSpeed: number\n  rotation: number\n  rotationSpeed: number\n  flip: number\n  flipSpeed: number\n  tick: number\n  ticks: number\n  color: string\n  shape: ConfettiShape\n  w: number\n  h: number\n}\n\nfunction makeParticles(o: ConfettiOptions, origin: { x: number; y: number }): Particle[] {\n  const {\n    particleCount = 90,\n    angle = 90,\n    spread = 70,\n    startVelocity = 38,\n    gravity = 1,\n    decay = 0.91,\n    drift = 0,\n    ticks = 220,\n    scalar = 1,\n    colors = DEFAULT_COLORS,\n    shapes = [\"square\", \"square\", \"strip\", \"circle\"],\n  } = o\n  const rad = (angle * Math.PI) / 180\n  const cone = (spread * Math.PI) / 180\n  return Array.from({ length: Math.max(0, Math.round(particleCount)) }, () => {\n    const shape = shapes[Math.floor(Math.random() * shapes.length)] ?? \"square\"\n    const size = (6 + Math.random() * 4) * scalar\n    return {\n      x: origin.x,\n      y: origin.y,\n      angle: -rad + (Math.random() - 0.5) * cone,\n      velocity: startVelocity * (0.5 + Math.random() * 0.7),\n      gravity: gravity * 3 * (0.85 + Math.random() * 0.3),\n      decay: decay + (Math.random() - 0.5) * 0.02,\n      drift,\n      wobble: Math.random() * 10,\n      wobbleSpeed: 0.05 + Math.random() * 0.06,\n      rotation: Math.random() * Math.PI * 2,\n      rotationSpeed: (Math.random() - 0.5) * 0.3,\n      flip: Math.random() * Math.PI,\n      flipSpeed: 0.08 + Math.random() * 0.12,\n      tick: 0,\n      ticks: ticks * (0.8 + Math.random() * 0.4),\n      color: colors[Math.floor(Math.random() * colors.length)] ?? DEFAULT_COLORS[0],\n      shape,\n      w: shape === \"strip\" ? size * 0.45 : size,\n      h: shape === \"strip\" ? size * 1.8 : shape === \"circle\" ? size : size * 0.65,\n    }\n  })\n}\n\n/** Canvas 2D particle loop. It runs only while particles are alive and stops while the tab is hidden or off-screen. */\nclass ConfettiEngine {\n  private particles: Particle[] = []\n  private raf = 0\n  private last = 0\n  private ctx: CanvasRenderingContext2D | null\n  private width = 0\n  private height = 0\n  private hiddenDoc = false\n  private offscreen = false\n\n  private canvas: HTMLCanvasElement\n  private onIdle?: () => void\n\n  constructor(canvas: HTMLCanvasElement, onIdle?: () => void) {\n    this.canvas = canvas\n    this.onIdle = onIdle\n    this.ctx = canvas.getContext(\"2d\")\n    this.hiddenDoc = document.hidden\n    document.addEventListener(\"visibilitychange\", this.onVisibility)\n    window.addEventListener(\"resize\", this.resize)\n  }\n\n  private onVisibility = () => {\n    this.hiddenDoc = document.hidden\n    this.sync()\n  }\n\n  setOffscreen(value: boolean) {\n    this.offscreen = value\n    this.sync()\n  }\n\n  private sync() {\n    if (this.hiddenDoc || this.offscreen) this.stop()\n    else this.start()\n  }\n\n  resize = () => {\n    const rect = this.canvas.getBoundingClientRect()\n    const dpr = Math.min(window.devicePixelRatio || 1, 2)\n    this.width = rect.width\n    this.height = rect.height\n    this.canvas.width = Math.max(1, Math.round(rect.width * dpr))\n    this.canvas.height = Math.max(1, Math.round(rect.height * dpr))\n    this.ctx?.setTransform(dpr, 0, 0, dpr, 0, 0)\n  }\n\n  add(particles: Particle[]) {\n    if (!this.ctx) return\n    if (this.particles.length === 0) this.resize()\n    this.particles.push(...particles)\n    this.start()\n  }\n\n  private start() {\n    if (this.raf || this.hiddenDoc || this.offscreen || this.particles.length === 0) return\n    this.last = performance.now()\n    this.raf = requestAnimationFrame(this.frame)\n  }\n\n  private stop() {\n    if (this.raf) cancelAnimationFrame(this.raf)\n    this.raf = 0\n  }\n\n  private frame = (now: number) => {\n    this.raf = 0\n    const ctx = this.ctx\n    if (!ctx) return\n    // Frame-rate independent: 1 = one 60fps frame. Capped so a long stall does not teleport particles.\n    const dt = Math.min((now - this.last) / (1000 / 60), 3)\n    this.last = now\n    ctx.clearRect(0, 0, this.width, this.height)\n\n    const alive: Particle[] = []\n    for (const p of this.particles) {\n      p.x += Math.cos(p.angle) * p.velocity * dt + p.drift * dt\n      p.y += Math.sin(p.angle) * p.velocity * dt + p.gravity * dt\n      p.velocity *= Math.pow(p.decay, dt)\n      p.wobble += p.wobbleSpeed * dt\n      p.rotation += p.rotationSpeed * dt\n      p.flip += p.flipSpeed * dt\n      p.tick += dt\n      if (p.tick >= p.ticks || p.y > this.height + 40) continue\n      alive.push(p)\n\n      const progress = p.tick / p.ticks\n      ctx.globalAlpha = progress < 0.65 ? 1 : Math.max(0, 1 - (progress - 0.65) / 0.35)\n      ctx.fillStyle = p.color\n      ctx.save()\n      ctx.translate(p.x + Math.cos(p.wobble) * 2.5, p.y)\n      ctx.rotate(p.rotation)\n      // Scaling one axis by cos() makes the paper look like it flips in 3D.\n      const face = Math.cos(p.flip)\n      ctx.scale(1, face)\n      const paint = () => {\n        if (p.shape === \"circle\") {\n          ctx.beginPath()\n          ctx.arc(0, 0, p.w / 2, 0, Math.PI * 2)\n          ctx.fill()\n        } else {\n          ctx.fillRect(-p.w / 2, -p.h / 2, p.w, p.h)\n        }\n      }\n      paint()\n      // Paper catches the light: the back is darker, and the front glints as it turns to face you.\n      ctx.fillStyle = face < 0 ? \"rgb(0 0 0/.22)\" : `rgb(255 255 255/${(face * face * 0.28).toFixed(3)})`\n      paint()\n      ctx.restore()\n    }\n    ctx.globalAlpha = 1\n    this.particles = alive\n\n    if (alive.length) this.raf = requestAnimationFrame(this.frame)\n    else {\n      ctx.clearRect(0, 0, this.width, this.height)\n      this.onIdle?.()\n    }\n  }\n\n  clear() {\n    this.stop()\n    this.particles = []\n    this.ctx?.clearRect(0, 0, this.width, this.height)\n  }\n\n  destroy() {\n    this.clear()\n    document.removeEventListener(\"visibilitychange\", this.onVisibility)\n    window.removeEventListener(\"resize\", this.resize)\n  }\n}\n\nfunction prefersReducedMotion() {\n  return typeof window !== \"undefined\" && window.matchMedia?.(\"(prefers-reduced-motion: reduce)\").matches\n}\n\nfunction centerOf(el: Element) {\n  const r = el.getBoundingClientRect()\n  return { x: r.left + r.width / 2, y: r.top + r.height / 2 }\n}\n\n/* ------------------------------------------------------ full-page burst */\n\nlet pageEngine: ConfettiEngine | null = null\nlet pageCanvas: HTMLCanvasElement | null = null\n\n/**\n * Fire confetti over the whole page from an element or a point. Does nothing when the user prefers reduced motion.\n * The canvas is created on demand and removed when the last particle is gone.\n */\nexport function fireConfetti(options: ConfettiOptions = {}) {\n  if (typeof window === \"undefined\" || !firstTime(options.once)) return\n  cue(options.sound)\n  if (prefersReducedMotion()) return\n  if (!pageEngine || !pageCanvas) {\n    const canvas = document.createElement(\"canvas\")\n    canvas.setAttribute(\"aria-hidden\", \"true\")\n    canvas.style.cssText = \"position:fixed;inset:0;width:100%;height:100%;pointer-events:none;z-index:2147483000\"\n    document.body.appendChild(canvas)\n    pageCanvas = canvas\n    pageEngine = new ConfettiEngine(canvas, () => {\n      pageEngine?.destroy()\n      pageCanvas?.remove()\n      pageEngine = null\n      pageCanvas = null\n    })\n  }\n  const origin = options.origin ?? (options.element ? centerOf(options.element) : { x: window.innerWidth / 2, y: window.innerHeight / 2 })\n  pageEngine.add(makeParticles(options, origin))\n}\n\n/* ------------------------------------------------------ contained canvas */\n\nexport type ConfettiHandle = {\n  /** Burst inside this canvas. `origin` is still in viewport px. */\n  fire: (options?: ConfettiOptions) => void\n  clear: () => void\n}\n\nexport type ConfettiProps = Omit<React.ComponentProps<\"canvas\">, \"ref\" | \"children\"> & {\n  /** Receives { fire(options), clear() } to burst inside this canvas. */\n  ref?: React.Ref<ConfettiHandle>\n  /** Default `sound` for fire(): \"celebrate\" (true) or a sound name, when the visitor has sounds on. Off by default. */\n  sound?: boolean | SoundName\n}\n\n/**\n * A canvas that fills its positioned parent. Call `ref.current.fire()` to burst inside it, clipped to the parent.\n * Reduced motion turns `fire` into a no-op.\n */\nexport function Confetti({ ref, sound, className, ...props }: ConfettiProps) {\n  const canvasRef = React.useRef<HTMLCanvasElement>(null)\n  const engineRef = React.useRef<ConfettiEngine | null>(null)\n\n  React.useEffect(() => {\n    const canvas = canvasRef.current\n    if (!canvas) return\n    const engine = new ConfettiEngine(canvas)\n    engineRef.current = engine\n    const ro = new ResizeObserver(() => engine.resize())\n    ro.observe(canvas)\n    const io = new IntersectionObserver(([entry]) => entry && engine.setOffscreen(!entry.isIntersecting))\n    io.observe(canvas)\n    return () => {\n      ro.disconnect()\n      io.disconnect()\n      engine.destroy()\n      engineRef.current = null\n    }\n  }, [])\n\n  React.useImperativeHandle(\n    ref,\n    () => ({\n      fire(options = {}) {\n        if (!firstTime(options.once)) return\n        cue(options.sound ?? sound)\n        const canvas = canvasRef.current\n        const engine = engineRef.current\n        if (!canvas || !engine || prefersReducedMotion()) return\n        const rect = canvas.getBoundingClientRect()\n        const point = options.origin ?? (options.element ? centerOf(options.element) : { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 })\n        engine.add(makeParticles(options, { x: point.x - rect.left, y: point.y - rect.top }))\n      },\n      clear() {\n        engineRef.current?.clear()\n      },\n    }),\n    [sound],\n  )\n\n  return <canvas ref={canvasRef} aria-hidden=\"true\" className={cn(\"pointer-events-none absolute inset-0 size-full\", className)} {...props} />\n}\n",
      "type": "registry:component",
      "target": "components/goodui/confetti.tsx"
    }
  ],
  "categories": [
    "components",
    "feedback"
  ],
  "type": "registry:component"
}