UI Library for Design Engineers. Animated components and effects you can copy and paste into your apps. Free. Open Source.
fix: refactor confetti animation for better API (#126)
Dillion Verma0e9af9880107
diff --git a/components/user-avatar.tsx b/components/user-avatar.tsxdeleted file mode 100644index 79a64d8a..00000000--- a/components/user-avatar.tsx+++ /dev/null@@ -1,24 +0,0 @@-import { User } from "@prisma/client";-import { AvatarProps } from "@radix-ui/react-avatar";--import { Icons } from "@/components/icons";-import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";--interface UserAvatarProps extends AvatarProps {- user: Pick<User, "image" | "name">;-}--export function UserAvatar({ user, ...props }: UserAvatarProps) {- return (- <Avatar {...props}>- {user.image ? (- <AvatarImage alt="Picture" src={user.image} />- ) : (- <AvatarFallback>- <span className="sr-only">{user.name}</span>- <Icons.user className="h-4 w-4" />- </AvatarFallback>- )}- </Avatar>- );-}diff --git a/content/docs/components/confetti.mdx b/content/docs/components/confetti.mdxindex e2e0193a..6678500a 100644--- a/content/docs/components/confetti.mdx+++ b/content/docs/components/confetti.mdx@@ -1,12 +1,12 @@---title: Confettidate: 2024-05-26-description: How to add confetti effects to your project+description: Confetti animations are best used to delight your users when something special happensauthor: Bankkrollpublished: true----<ComponentPreview name="confetti-basic-cannon" />+<ComponentPreview name="confetti-hover" /><Steps>@@ -30,6 +30,10 @@ components/magicui/confetti.tsx## Examples+### Basic++<ComponentPreview name="confetti-basic-cannon" />+### Random Direction<ComponentPreview name="confetti-random-direction" />@@ -54,29 +58,37 @@ components/magicui/confetti.tsx<ComponentPreview name="confetti-emoji" />-## Props-| Prop | Type | Description | Default |-| ------------------------- | ------------------------- | ------------------------------------------------ | ----------------------------------------------------------------------- |-| particleCount | Integer | The number of confetti particles to launch | 50 |-| angle | Number | The angle in degrees at which to launch confetti | 90 |-| spread | Number | The spread in degrees of the confetti | 45 |-| startVelocity | Number | The initial velocity of the confetti | 45 |-| decay | Number | The rate at which confetti slows down | 0.9 |-| gravity | Number | The gravity applied to confetti particles | 1 |-| drift | Number | The horizontal drift applied to particles | 0 |-| flat | Boolean | Whether confetti particles are flat | false |-| ticks | Number | The number of frames confetti lasts | 200 |-| origin | Object | The origin point of the confetti | `{ x: 0.5, y: 0.5 }` |-| colors | Array of Strings | Array of color strings in HEX format | ['#26ccff', '#a25afd', '#ff5e7e', '#88ff5a', '#fcff42', '#ffa62d', '#ff36ff'] |-| shapes | Array of Strings | Array of shapes for the confetti | ['square', 'circle'] |-| zIndex | Integer | The z-index of the confetti | 100 |-| disableForReducedMotion | Boolean | Disables confetti for users who prefer no motion | false |-| useWorker | Boolean | Use Web Worker for better performance | true |-| resize | Boolean | Whether to resize the canvas | true |-| canvas | HTMLCanvasElement or null | Custom canvas element to draw confetti | null |-| scalar | Number | Scaling factor for confetti size | 1 |+### Confetti++| Prop | Type | Description | Default |+| ----------------------- | ------------------------- | ------------------------------------------------ | ----------------------------------------------------------------------------- |+| particleCount | Integer | The number of confetti particles to launch | 50 |+| angle | Number | The angle in degrees at which to launch confetti | 90 |+| spread | Number | The spread in degrees of the confetti | 45 |+| startVelocity | Number | The initial velocity of the confetti | 45 |+| decay | Number | The rate at which confetti slows down | 0.9 |+| gravity | Number | The gravity applied to confetti particles | 1 |+| drift | Number | The horizontal drift applied to particles | 0 |+| flat | Boolean | Whether confetti particles are flat | false |+| ticks | Number | The number of frames confetti lasts | 200 |+| origin | Object | The origin point of the confetti | `{ x: 0.5, y: 0.5 }` |+| colors | Array of Strings | Array of color strings in HEX format | ['#26ccff', '#a25afd', '#ff5e7e', '#88ff5a', '#fcff42', '#ffa62d', '#ff36ff'] |+| shapes | Array of Strings | Array of shapes for the confetti | ['square', 'circle'] |+| zIndex | Integer | The z-index of the confetti | 100 |+| disableForReducedMotion | Boolean | Disables confetti for users who prefer no motion | false |+| useWorker | Boolean | Use Web Worker for better performance | true |+| resize | Boolean | Whether to resize the canvas | true |+| canvas | HTMLCanvasElement or null | Custom canvas element to draw confetti | null |+| scalar | Number | Scaling factor for confetti size | 1 |++### ConfettiButton++| Prop | Type | Description | Default |+| -------- | --------------- | ------------------------------------ | ------- |+| options | Object | Options for the confetti | {} |+| children | React.ReactNode | Children to render inside the button | null |## Creditsdiff --git a/registry/components/example/confetti-basic-cannon.tsx b/registry/components/example/confetti-basic-cannon.tsxindex 915696aa..aeb0f87c 100644--- a/registry/components/example/confetti-basic-cannon.tsx+++ b/registry/components/example/confetti-basic-cannon.tsx@@ -1,14 +1,9 @@-import { Button } from "@/components/ui/button";-import { Confetti } from "@/registry/components/magicui/confetti";--export default function ConfettiBasicCannon() {- const handleClick = () => {- Confetti({}); // Use default settings for basic confetti- };+import { ConfettiButton } from "@/registry/components/magicui/confetti";+export default function ConfettiButtonDemo() {return (- <div className="relative justify-center">- <Button onClick={handleClick}>Trigger Basic Cannon</Button>+ <div className="relative">+ <ConfettiButton>Confetti π</ConfettiButton></div>);}diff --git a/registry/components/example/confetti-custom-shapes.tsx b/registry/components/example/confetti-custom-shapes.tsxindex 369557c5..b65201b7 100644--- a/registry/components/example/confetti-custom-shapes.tsx+++ b/registry/components/example/confetti-custom-shapes.tsx@@ -1,24 +1,20 @@import { Button } from "@/components/ui/button";-import { Confetti } from "@/registry/components/magicui/confetti";+import confetti from "canvas-confetti";export default function ConfettiCustomShapes() {const handleClick = () => {const scalar = 2;- const triangle = Confetti.shapeFromPath({+ const triangle = confetti.shapeFromPath({path: "M0 10 L5 0 L10 10z",- scalar,});- const square = Confetti.shapeFromPath({+ const square = confetti.shapeFromPath({path: "M0 0 L10 0 L10 10 L0 10 Z",- scalar,});- const coin = Confetti.shapeFromPath({+ const coin = confetti.shapeFromPath({path: "M5 0 A5 5 0 1 0 5 10 A5 5 0 1 0 5 0 Z",- scalar,});- const tree = Confetti.shapeFromPath({+ const tree = confetti.shapeFromPath({path: "M5 0 L10 10 L0 10 Z",- scalar,});const defaults = {@@ -32,18 +28,17 @@ export default function ConfettiCustomShapes() {};const shoot = () => {- Confetti({+ confetti({...defaults,particleCount: 30,});- Confetti({+ confetti({...defaults,particleCount: 5,- flat: true,});- Confetti({+ confetti({...defaults,particleCount: 15,scalar: scalar / 2,diff --git a/registry/components/example/confetti-emoji.tsx b/registry/components/example/confetti-emoji.tsxindex 36afd5f1..23145c5d 100644--- a/registry/components/example/confetti-emoji.tsx+++ b/registry/components/example/confetti-emoji.tsx@@ -1,10 +1,10 @@import { Button } from "@/components/ui/button";-import { Confetti } from "@/registry/components/magicui/confetti";+import confetti from "canvas-confetti";export default function ConfettiEmoji() {const handleClick = () => {const scalar = 2;- const unicorn = Confetti.shapeFromText({ text: "π¦", scalar });+ const unicorn = confetti.shapeFromText({ text: "π¦", scalar });const defaults = {spread: 360,@@ -17,18 +17,17 @@ export default function ConfettiEmoji() {};const shoot = () => {- Confetti({+ confetti({...defaults,particleCount: 30,});- Confetti({+ confetti({...defaults,particleCount: 5,- flat: true,});- Confetti({+ confetti({...defaults,particleCount: 15,scalar: scalar / 2,diff --git a/registry/components/example/confetti-fireworks.tsx b/registry/components/example/confetti-fireworks.tsxindex 99101869..86de29a9 100644--- a/registry/components/example/confetti-fireworks.tsx+++ b/registry/components/example/confetti-fireworks.tsx@@ -1,5 +1,5 @@import { Button } from "@/components/ui/button";-import { Confetti } from "@/registry/components/magicui/confetti";+import confetti from "canvas-confetti";export default function ConfettiFireworks() {const handleClick = () => {@@ -18,12 +18,12 @@ export default function ConfettiFireworks() {}const particleCount = 50 * (timeLeft / duration);- Confetti({+ confetti({...defaults,particleCount,origin: { x: randomInRange(0.1, 0.3), y: Math.random() - 0.2 },});- Confetti({+ confetti({...defaults,particleCount,origin: { x: randomInRange(0.7, 0.9), y: Math.random() - 0.2 },@@ -32,7 +32,7 @@ export default function ConfettiFireworks() {};return (- <div className="relative justify-center">+ <div className="relative"><Button onClick={handleClick}>Trigger Fireworks</Button></div>);diff --git a/registry/components/example/confetti-hover.tsx b/registry/components/example/confetti-hover.tsxnew file mode 100644index 00000000..3250abca--- /dev/null+++ b/registry/components/example/confetti-hover.tsx@@ -0,0 +1,25 @@+"use client";++import type { ConfettiRef } from "@/registry/components/magicui/confetti";+import Confetti from "@/registry/components/magicui/confetti";+import { useRef } from "react";++export default function ConfettiBasicCannon() {+ const confettiRef = useRef<ConfettiRef>(null);++ return (+ <div className="relative flex h-[500px] w-full max-w-[32rem] flex-col items-center justify-center overflow-hidden rounded-lg border bg-background md:shadow-xl">+ <span className="pointer-events-none whitespace-pre-wrap bg-gradient-to-b from-black to-gray-300/80 bg-clip-text text-center text-8xl font-semibold leading-none text-transparent dark:from-white dark:to-slate-900/10">+ Confetti+ </span>++ <Confetti+ ref={confettiRef}+ className="absolute left-0 top-0 z-0 h-full w-full"+ onMouseEnter={() => {+ confettiRef.current?.fire({});+ }}+ />+ </div>+ );+}diff --git a/registry/components/example/confetti-random-direction.tsx b/registry/components/example/confetti-random-direction.tsxindex 9bb73285..c473e233 100644--- a/registry/components/example/confetti-random-direction.tsx+++ b/registry/components/example/confetti-random-direction.tsx@@ -1,16 +1,17 @@-import { Button } from "@/components/ui/button";-import { Confetti } from "@/registry/components/magicui/confetti";--export default function ConfettiRandomDirection() {- const handleClick = () => {- Confetti({- angle: Math.random() * 360,- });- };+import { ConfettiButton } from "@/registry/components/magicui/confetti";+export default function ConfettiButtonDemo() {return (- <div className="relative justify-center">- <Button onClick={handleClick}>Trigger Random Direction</Button>+ <div className="relative">+ <ConfettiButton+ options={{+ get angle() {+ return Math.random() * 360;+ },+ }}+ >+ Random Confetti π+ </ConfettiButton></div>);}diff --git a/registry/components/example/confetti-side-cannons.tsx b/registry/components/example/confetti-side-cannons.tsxindex 332e8a37..f6a4e746 100644--- a/registry/components/example/confetti-side-cannons.tsx+++ b/registry/components/example/confetti-side-cannons.tsx@@ -1,5 +1,5 @@import { Button } from "@/components/ui/button";-import { Confetti } from "@/registry/components/magicui/confetti";+import confetti from "canvas-confetti";export default function ConfettiSideCannons() {const handleClick = () => {@@ -9,7 +9,7 @@ export default function ConfettiSideCannons() {const frame = () => {if (Date.now() > end) return;- Confetti({+ confetti({particleCount: 2,angle: 60,spread: 55,@@ -17,7 +17,7 @@ export default function ConfettiSideCannons() {origin: { x: 0, y: 0.5 },colors: colors,});- Confetti({+ confetti({particleCount: 2,angle: 120,spread: 55,@@ -33,7 +33,7 @@ export default function ConfettiSideCannons() {};return (- <div className="relative justify-center">+ <div className="relative"><Button onClick={handleClick}>Trigger Side Cannons</Button></div>);diff --git a/registry/components/example/confetti-stars.tsx b/registry/components/example/confetti-stars.tsxindex f5bef070..9c62e350 100644--- a/registry/components/example/confetti-stars.tsx+++ b/registry/components/example/confetti-stars.tsx@@ -1,5 +1,5 @@import { Button } from "@/components/ui/button";-import { Confetti } from "@/registry/components/magicui/confetti";+import confetti from "canvas-confetti";export default function ConfettiStars() {const handleClick = () => {@@ -13,14 +13,14 @@ export default function ConfettiStars() {};const shoot = () => {- Confetti({+ confetti({...defaults,particleCount: 40,scalar: 1.2,shapes: ["star"],});- Confetti({+ confetti({...defaults,particleCount: 10,scalar: 0.75,@@ -34,7 +34,7 @@ export default function ConfettiStars() {};return (- <div className="relative justify-center">+ <div className="relative"><Button onClick={handleClick}>Trigger Stars</Button></div>);diff --git a/registry/components/magicui/confetti-button.tsx b/registry/components/magicui/confetti-button.tsxnew file mode 100644index 00000000..32b12c81--- /dev/null+++ b/registry/components/magicui/confetti-button.tsx@@ -0,0 +1,41 @@+"use client";++import { Button, ButtonProps } from "@/components/ui/button";+import confetti from "canvas-confetti";+import React from "react";++import type {+ GlobalOptions as ConfettiGlobalOptions,+ Options as ConfettiOptions,+} from "canvas-confetti";++interface ConfettiButtonProps extends ButtonProps {+ options?: ConfettiOptions &+ ConfettiGlobalOptions & { canvas?: HTMLCanvasElement };+ children?: React.ReactNode;+}++export default function ConfettiButton({+ options,+ children,+ ...props+}: ConfettiButtonProps) {+ const handleClick = (event: React.MouseEvent<HTMLButtonElement>) => {+ const rect = event.currentTarget.getBoundingClientRect();+ const x = rect.left + rect.width / 2;+ const y = rect.top + rect.height / 2;+ confetti({+ ...options,+ origin: {+ x: x / window.innerWidth,+ y: y / window.innerHeight,+ },+ });+ };++ return (+ <Button onClick={handleClick} {...props}>+ {children}+ </Button>+ );+}diff --git a/registry/components/magicui/confetti.tsx b/registry/components/magicui/confetti.tsxindex 4b06b4b6..2f59dd9c 100644--- a/registry/components/magicui/confetti.tsx+++ b/registry/components/magicui/confetti.tsx@@ -1,52 +1,126 @@+import { Button, ButtonProps } from "@/components/ui/button";import confetti from "canvas-confetti";+import type { ReactNode } from "react";+import React, {+ createContext,+ forwardRef,+ useCallback,+ useEffect,+ useImperativeHandle,+ useMemo,+ useRef,+} from "react";-interface ConfettiOptions extends confetti.Options {- particleCount?: number;- angle?: number;- spread?: number;- startVelocity?: number;- decay?: number;- gravity?: number;- drift?: number;- flat?: boolean;- ticks?: number;- origin?: { x: number; y: number };- colors?: string[];- shapes?: confetti.Shape[];- zIndex?: number;- disableForReducedMotion?: boolean;- useWorker?: boolean;- resize?: boolean;- canvas?: HTMLCanvasElement | null;- scalar?: number;-}+import type {+ GlobalOptions as ConfettiGlobalOptions,+ Options as ConfettiOptions,+} from "canvas-confetti";-const Confetti = (options: ConfettiOptions) => {- if (- options.disableForReducedMotion &&- window.matchMedia("(prefers-reduced-motion)").matches- ) {- return;- }-- const confettiInstance = options.canvas- ? confetti.create(options.canvas, {- resize: options.resize ?? true,- useWorker: options.useWorker ?? true,- })- : confetti;-- confettiInstance({- ...options,- });-};+import type { CreateTypes as ConfettiInstance } from "canvas-confetti";-Confetti.shapeFromPath = (options: { path: string; [key: string]: any }) => {- return confetti.shapeFromPath({ ...options });+type Api = {+ fire: (options?: ConfettiOptions) => void;};-Confetti.shapeFromText = (options: { text: string; [key: string]: any }) => {- return confetti.shapeFromText({ ...options });+type Props = React.ComponentPropsWithRef<"canvas"> & {+ options?: ConfettiOptions;+ globalOptions?: ConfettiGlobalOptions;+ manualstart?: boolean;+ children?: ReactNode;};-export { Confetti };+export type ConfettiRef = Api | null;++const ConfettiContext = createContext<Api>({} as Api);++const Confetti = forwardRef<ConfettiRef, Props>((props, ref) => {+ const {+ options,+ globalOptions = { resize: true, useWorker: true },+ manualstart = false,+ children,+ ...rest+ } = props;+ const instanceRef = useRef<ConfettiInstance | null>(null); // confetti instance++ const canvasRef = useCallback(+ // https://react.dev/reference/react-dom/components/common#ref-callback+ // https://reactjs.org/docs/refs-and-the-dom.html#callback-refs+ (node: HTMLCanvasElement) => {+ if (node !== null) {+ // <canvas> is mounted => create the confetti instance+ if (instanceRef.current) return; // if not already created+ instanceRef.current = confetti.create(node, {+ ...globalOptions,+ resize: true,+ });+ } else {+ // <canvas> is unmounted => reset and destroy instanceRef+ if (instanceRef.current) {+ instanceRef.current.reset();+ instanceRef.current = null;+ }+ }+ },+ [globalOptions],+ );++ // `fire` is a function that calls the instance() with `opts` merged with `options`+ const fire = useCallback(+ (opts = {}) => instanceRef.current?.({ ...options, ...opts }),+ [options],+ );++ const api = useMemo(+ () => ({+ fire,+ }),+ [fire],+ );++ useImperativeHandle(ref, () => api, [api]);++ useEffect(() => {+ if (!manualstart) {+ fire();+ }+ }, [manualstart, fire]);++ return (+ <ConfettiContext.Provider value={api}>+ <canvas ref={canvasRef} {...rest} />+ {children}+ </ConfettiContext.Provider>+ );+});++interface ConfettiButtonProps extends ButtonProps {+ options?: ConfettiOptions &+ ConfettiGlobalOptions & { canvas?: HTMLCanvasElement };+ children?: React.ReactNode;+}++function ConfettiButton({ options, children, ...props }: ConfettiButtonProps) {+ const handleClick = (event: React.MouseEvent<HTMLButtonElement>) => {+ const rect = event.currentTarget.getBoundingClientRect();+ const x = rect.left + rect.width / 2;+ const y = rect.top + rect.height / 2;+ confetti({+ ...options,+ origin: {+ x: x / window.innerWidth,+ y: y / window.innerHeight,+ },+ });+ };++ return (+ <Button onClick={handleClick} {...props}>+ {children}+ </Button>+ );+}++export { Confetti, ConfettiButton };++export default Confetti;diff --git a/registry/index.tsx b/registry/index.tsxindex 75fda37b..4e99bd9f 100644--- a/registry/index.tsx+++ b/registry/index.tsx@@ -848,6 +848,14 @@ const example: Registry = {() => import("@/registry/components/example/shine-border-demo-2"),),},+ "confetti-hover": {+ name: "confetti-hover",+ type: "components:example",+ files: ["registry/components/example/confetti-hover.tsx"],+ component: React.lazy(+ () => import("@/registry/components/example/confetti-hover"),+ ),+ },"confetti-basic-cannon": {name: "confetti-basic-cannon",type: "components:example",