← All components Next componentLiquid Neon→
Widgets · Gamification
Reward Modal
An accessible confirmation modal whose 3D gift box springs open in a burst of confetti.
<InteractiveModal3D />Live
Controlled: isOpen + onClose
Customize
Box#7c3aed
Ribbon & confetti#facc15
Installation
Use it in your project
Or skip the copy-paste
One command: writes the file and installs the dependencies.
$ npx deepui-cli add reward-modal
01
Install
The 3D packages this component is built on.
$ npm install three @react-three/fiber @react-three/drei && npm install -D @types/three
02
Add the component
One self-contained file: create components/InteractiveModal3D.tsx and paste it in.
components/InteractiveModal3D.tsx
1"use client";23import {4 memo,5 useEffect,6 useId,7 useMemo,8 useRef,9 useState,10 type CSSProperties,11 type DependencyList,12 type ReactNode,13} from "react";14import * as THREE from "three";15import { Canvas, useFrame, useThree, type CanvasProps } from "@react-three/fiber";16import { Environment, Lightformer, RoundedBox } from "@react-three/drei";1718/**19 * The shared props API of DeepUI's individual 3D components (not the full-page templates, which keep20 * their own tailored scenes).21 *22 * The props are grouped by concern. A component extends ONLY the groups it really applies, so its23 * type never advertises a knob that does nothing (a card has no particles, a background has no tilt):24 *25 * interface MyCardProps extends CursorProps, TiltProps, MaterialProps, PerformanceProps { … }26 *27 * `Base3DComponentProps` is every group at once, for tooling that handles any component. Same name,28 * same unit and same meaning everywhere; the default values live in DEFAULT_3D_PROPS. These files are29 * inlined into each component's single-file bundle (lib/bundle-source.mjs), only what it uses.30 */3132/** Which rotation axes follow the pointer. "x-only": the object nods (up / down); "y-only": it turns (left / right). */33export type TiltAxis = "both" | "x-only" | "y-only" | "none";3435/** 1. Cursor: how the pointer pulls, pushes and drags the object. */36interface CursorProps {37 /** Reach of the pointer's influence, in the component's own space: CSS pixels for pixel-laid-out widgets, world units for 3D scenes (each component says which). Default 220 (px). */38 cursorRadius?: number;39 /** Positive pulls things towards the pointer, negative pushes them away (repulsion, shockwave). Default 1. */40 cursorForce?: number;41 /** How far the object slides towards the pointer, 0 (stays put) to 1 (follows closely). Default 0. */42 magneticStrength?: number;43 /** Share of the remaining distance the motion closes each frame (at 60 fps), 0.01 (heavy, slow) to 1 (instant). Default 0.1. */44 cursorDamping?: number;45}4647/** 2. Tilt and parallax: the object leans towards the pointer, its layers slide against each other. */48interface TiltProps {49 /** Largest lean towards the pointer, in degrees. Default 15. */50 maxTiltAngle?: number;51 /** Axes that follow the pointer. Default "both". */52 tiltAxis?: TiltAxis;53 /** Lean away from the pointer instead of towards it. Default false. */54 invertTilt?: boolean;55 /** How far apart the depth layers slide when the object tilts, 0 (flat) to 2. Default 1. */56 parallaxOffset?: number;57}5859/** 3. Text and 3D typography, for components that draw a label. */60interface Text3DProps {61 /** The label drawn by the component. */62 text?: string;63 /** Scale of the lettering. Default 1. */64 fontSize?: number;65 /** Extrusion depth of 3D letters. Default 0.2. */66 textDepth?: number;67 /** Bevelled, light-catching edges on 3D letters. Default true. */68 bevelEnabled?: boolean;69 /** Custom font: a .woff / .ttf (flat text) or a typeface .json (extruded text). */70 fontUrl?: string;71}7273/** 4. Rendering, materials and glow. */74interface MaterialProps {75 /** Main color of the object. Default "#6366f1". */76 primaryColor?: string;77 /** Color of the glow. Default "#00f0ff". */78 emissiveColor?: string;79 /** Strength of the glow, 0 (none) to 3. Default 1. */80 emissiveIntensity?: number;81 /** 0 (mirror, glass) to 1 (matte). Default 0.3. */82 roughness?: number;83 /** 0 (plastic, organic) to 1 (metal). Default 0.5. */84 metalness?: number;85 /** 0 (opaque) to 1 (clear glass): see-through, refracting surfaces. Default 0. */86 transmission?: number;87 /** Technical wireframe rendering. Default false. */88 wireframe?: boolean;89}9091/** 5. Particles, idle motion and shader animation. */92interface MotionProps {93 /** Number of instanced elements. Default depends on the component. */94 particleCount?: number;95 /** Spin on its own, in radians per second (negative: the other way; 0.5 ≈ one turn in 12 s). Default 0. */96 autoRotateSpeed?: number;97 /** Pulses or ripples per second. Default 1. */98 pulseRate?: number;99 /** Amplitude of the noise deformation, 0 (none) to 2. Default 1. */100 displacementScale?: number;101}102103/** 6. Environment and camera. */104interface EnvironmentProps {105 /** Camera field of view, in degrees. Default depends on the component. */106 cameraFov?: number;107 /** Color of the depth fog. Default "#0a0a0a". */108 fogColor?: string;109 /** Thickness of the fog, 0 (none) to 0.2. Default 0. */110 fogDensity?: number;111}112113/** 7. Performance and accessibility. */114interface PerformanceProps {115 /** Lighter rendering for weak devices: pixel ratio 1, fewer instances, smaller environment maps. Default false. */116 lowPowerMode?: boolean;117 /** Under the OS "reduce motion" setting, stop idle spin, pulses and deformation (pointer feedback stays). Default true. */118 respectReducedMotion?: boolean;119 /** Stop the render loop while the component is scrolled out of view. Default true. */120 pauseWhenOffscreen?: boolean;121}122123/** Every group at once. Components extend only the groups they apply (see the top of this file). */124interface Base3DComponentProps125 extends CursorProps,126 TiltProps,127 Text3DProps,128 MaterialProps,129 MotionProps,130 EnvironmentProps,131 PerformanceProps {}132133type Defaults = Required<Omit<Base3DComponentProps, "text" | "fontUrl" | "particleCount" | "cameraFov">>;134135/** The values a prop takes when it is left out. A component may override one, and then documents it. */136const DEFAULT_3D_PROPS: Defaults = {137 cursorRadius: 220,138 cursorForce: 1,139 magneticStrength: 0,140 cursorDamping: 0.1,141 maxTiltAngle: 15,142 tiltAxis: "both",143 invertTilt: false,144 parallaxOffset: 1,145 fontSize: 1,146 textDepth: 0.2,147 bevelEnabled: true,148 primaryColor: "#6366f1",149 emissiveColor: "#00f0ff",150 emissiveIntensity: 1,151 roughness: 0.3,152 metalness: 0.5,153 transmission: 0,154 wireframe: false,155 autoRotateSpeed: 0,156 pulseRate: 1,157 displacementScale: 1,158 fogColor: "#0a0a0a",159 fogDensity: 0,160 lowPowerMode: false,161 respectReducedMotion: true,162 pauseWhenOffscreen: true,163};164165/** Fills the positioned parent. The objects receive pointer events (orbit, hover, click). */166const FILL_STYLE: CSSProperties = { position: "absolute", top: 0, left: 0, width: "100%", height: "100%" };167168interface ObjectCanvasProps extends Omit<CanvasProps, "children" | "style" | "frameloop" | "gl">, Pick<PerformanceProps, "pauseWhenOffscreen" | "lowPowerMode"> {169 children: ReactNode;170 /** CSS touch-action of the canvas: "pan-y" keeps vertical page scrolling on touch screens. */171 touchAction?: CSSProperties["touchAction"];172}173174/**175 * Ready-to-use <Canvas> shared by every object: fills its positioned parent, pauses its render loop176 * while scrolled out of view, caps the pixel ratio; R3F disposes the renderer on unmount.177 */178function ObjectCanvas({ children, touchAction = "pan-y", dpr = [1, 2], shadows, pauseWhenOffscreen = DEFAULT_3D_PROPS.pauseWhenOffscreen, lowPowerMode = DEFAULT_3D_PROPS.lowPowerMode, ...canvasProps }: ObjectCanvasProps) {179 const containerRef = useRef<HTMLDivElement>(null);180 const [inView, setInView] = useState(true);181182 useEffect(() => {183 const el = containerRef.current;184 if (!el) return undefined;185 const observer = new IntersectionObserver(([entry]) => setInView(entry.isIntersecting));186 observer.observe(el);187 return () => observer.disconnect();188 }, []);189190 return (191 <div ref={containerRef} style={FILL_STYLE}>192 <Canvas193 dpr={lowPowerMode ? 1 : dpr}194 frameloop={inView || !pauseWhenOffscreen ? "always" : "never"}195 gl={{ antialias: true, alpha: true, powerPreference: "high-performance" }}196 style={{ touchAction }}197 // `shadows` alone asks R3F for PCFSoftShadowMap, which recent three.js versions removed (with a warning)198 shadows={shadows === true ? "percentage" : shadows}199 {...canvasProps}200 >201 {children}202 </Canvas>203 </div>204 );205}206207/** Studio reflections from light panels: no HDR file to download. */208function StudioEnvironment({ intensity = 1, warm = false }: { intensity?: number; warm?: boolean }) {209 return (210 <Environment resolution={256} frames={1}>211 <Lightformer form="rect" intensity={3 * intensity} position={[0, 5, 2]} rotation-x={Math.PI / 2} scale={[10, 3, 1]} />212 <Lightformer213 form="rect"214 intensity={2 * intensity}215 position={[-5, 1, 2]}216 rotation-y={Math.PI / 2}217 scale={[2, 6, 1]}218 color={warm ? "#ffe2c4" : "#ffffff"}219 />220 <Lightformer221 form="rect"222 intensity={1.5 * intensity}223 position={[5, 0, -2]}224 rotation-y={-Math.PI / 2}225 scale={[2, 6, 1]}226 color={warm ? "#c4dcff" : "#ffffff"}227 />228 <Lightformer form="ring" intensity={2 * intensity} position={[2, 3, 5]} scale={2} />229 </Environment>230 );231}232233type Disposable = { dispose: () => void };234235type DisposableTree = Disposable | Disposable[] | { [key: string]: DisposableTree };236237function disposeTree(value: DisposableTree) {238 if (Array.isArray(value)) value.forEach(disposeTree);239 else if (typeof (value as Disposable).dispose === "function") (value as Disposable).dispose();240 else Object.values(value as Record<string, DisposableTree>).forEach(disposeTree);241}242243/**244 * useMemo for GPU resources: the geometries/materials/textures it returns (alone, in an array or245 * in a nested object) are disposed when the deps change and on unmount.246 */247function useDisposable<T extends DisposableTree>(factory: () => T, deps: DependencyList): T {248 const value = useMemo(factory, deps);249 useEffect(() => () => disposeTree(value), [value]);250 return value;251}252253export interface InteractiveModalProps extends Pick<MaterialProps, "primaryColor" | "emissiveColor">, Pick<PerformanceProps, "pauseWhenOffscreen" | "lowPowerMode"> {254 isOpen: boolean;255 onClose: () => void;256 title: string;257 /** Text under the title. */258 description?: string;259 /** Label of the closing button. Default "Awesome!". */260 actionLabel?: string;261 primaryColor?: string;262 /** @deprecated Use `primaryColor`. */263 boxColor?: string;264 emissiveColor?: string;265 /** @deprecated Use `emissiveColor`. */266 particleColor?: string;267 /**268 * Render inside the nearest positioned parent instead of over the whole page (e.g. in a preview).269 * Default false.270 */271 contained?: boolean;272}273274const EXIT_MS = 260;275const CONFETTI = 180;276277/* -------------------------------------------------------------------------- */278/* Gift box */279/* -------------------------------------------------------------------------- */280281interface Confetto {282 position: THREE.Vector3;283 velocity: THREE.Vector3;284 rotation: THREE.Euler;285 spin: THREE.Vector3;286 size: number;287}288289function GiftBox({ boxColor, particleColor }: { boxColor: string; particleColor: string }) {290 const res = useDisposable(291 () => ({292 box: new THREE.MeshPhysicalMaterial({ roughness: 0.35, clearcoat: 1, clearcoatRoughness: 0.15 }),293 ribbon: new THREE.MeshPhysicalMaterial({ roughness: 0.25, metalness: 0.6, clearcoat: 1 }),294 glow: new THREE.MeshBasicMaterial({ toneMapped: false, transparent: true, opacity: 0 }),295 confetti: new THREE.MeshStandardMaterial({ roughness: 0.5, metalness: 0.3, side: THREE.DoubleSide }),296 confettoGeometry: new THREE.PlaneGeometry(0.09, 0.14),297 ribbonV: new THREE.BoxGeometry(0.16, 1.02, 1.42),298 ribbonH: new THREE.BoxGeometry(1.42, 1.02, 0.16),299 lidRibbonV: new THREE.BoxGeometry(0.16, 0.3, 1.52),300 lidRibbonH: new THREE.BoxGeometry(1.52, 0.3, 0.16),301 bow: new THREE.TorusGeometry(0.16, 0.05, 10, 24),302 inner: new THREE.PlaneGeometry(1.3, 1.3),303 }),304 []305 );306307 useEffect(() => {308 res.box.color.set(boxColor);309 res.ribbon.color.set(particleColor);310 res.glow.color.set(particleColor).multiplyScalar(1.6);311 }, [res, boxColor, particleColor]);312313 const root = useRef<THREE.Group>(null);314 const lid = useRef<THREE.Group>(null);315 const light = useRef<THREE.PointLight>(null);316 const anim = useRef({ t: 0, scale: 0.4, scaleV: 0, lid: 0, lidV: 0, burst: false });317 const dummy = useMemo(() => new THREE.Object3D(), []);318319 // Confetti colours: the particle colour, the box colour and white320 const confetti = useRef<THREE.InstancedMesh>(null);321 const particles = useMemo<Confetto[]>(322 () =>323 Array.from({ length: CONFETTI }, () => ({324 position: new THREE.Vector3(0, -10, 0),325 velocity: new THREE.Vector3(),326 rotation: new THREE.Euler(),327 spin: new THREE.Vector3(),328 size: 0.7 + Math.random() * 0.8,329 })),330 []331 );332 useEffect(() => {333 const mesh = confetti.current;334 if (!mesh) return;335 const palette = [new THREE.Color(particleColor), new THREE.Color(boxColor), new THREE.Color("#ffffff")];336 for (let i = 0; i < CONFETTI; i++) mesh.setColorAt(i, palette[i % 3]);337 if (mesh.instanceColor) mesh.instanceColor.needsUpdate = true;338 // Hidden (zero scale) until the burst339 if (!anim.current.burst) {340 const hidden = new THREE.Matrix4().makeScale(0, 0, 0);341 for (let i = 0; i < CONFETTI; i++) mesh.setMatrixAt(i, hidden);342 mesh.instanceMatrix.needsUpdate = true;343 }344 }, [particleColor, boxColor]);345346347 useFrame((_, delta) => {348 const dt = Math.min(delta, 1 / 30);349 const a = anim.current;350 a.t += dt;351352 // Pop in on a spring, then a short shake before it opens353 a.scaleV += ((1 - a.scale) * 120 - a.scaleV * 11) * dt;354 a.scale += a.scaleV * dt;355 const shaking = a.t > 0.35 && a.t < 0.75;356 if (root.current) {357 root.current.scale.setScalar(a.scale);358 root.current.rotation.z = shaking ? Math.sin(a.t * 60) * 0.06 : root.current.rotation.z * 0.85;359 root.current.rotation.y = -0.5 + Math.sin(a.t * 0.6) * 0.15;360 }361362 // Lid: an underdamped spring towards open, so it bounces on its hinge363 const target = a.t > 0.75 ? -2.1 : 0;364 a.lidV += ((target - a.lid) * 90 - a.lidV * 7) * dt;365 a.lid += a.lidV * dt;366 if (lid.current) lid.current.rotation.x = a.lid;367 const open = THREE.MathUtils.clamp(-a.lid / 2.1, 0, 1);368 res.glow.opacity = open * 0.9;369 if (light.current) light.current.intensity = open * 6;370371 // Confetti burst out of the box when the lid flies open372 if (!a.burst && a.t > 0.8) {373 a.burst = true;374 particles.forEach((p) => {375 p.position.set((Math.random() - 0.5) * 0.8, 0.5, (Math.random() - 0.5) * 0.8);376 const angle = Math.random() * Math.PI * 2;377 const spread = 0.8 + Math.random() * 1.8;378 p.velocity.set(Math.cos(angle) * spread, 2.6 + Math.random() * 2, Math.sin(angle) * spread);379 p.spin.set(Math.random() * 12 - 6, Math.random() * 12 - 6, Math.random() * 12 - 6);380 });381 }382 const mesh = confetti.current;383 if (mesh && a.burst) {384 particles.forEach((p, i) => {385 // Gravity, air drag and a little flutter386 p.velocity.y -= 6.5 * dt;387 p.velocity.multiplyScalar(1 - 1.1 * dt);388 p.position.addScaledVector(p.velocity, dt);389 p.position.x += Math.sin(a.t * 6 + i) * 0.004;390 p.rotation.x += p.spin.x * dt;391 p.rotation.y += p.spin.y * dt;392 p.rotation.z += p.spin.z * dt;393 const life = THREE.MathUtils.clamp(1 - (a.t - 0.8) / 3.2, 0, 1);394 dummy.position.copy(p.position);395 dummy.rotation.copy(p.rotation);396 dummy.scale.setScalar(p.size * life);397 dummy.updateMatrix();398 mesh.setMatrixAt(i, dummy.matrix);399 });400 mesh.instanceMatrix.needsUpdate = true;401 }402 });403404 return (405 <>406 <group ref={root} position={[0, -0.55, 0]}>407 <RoundedBox args={[1.4, 1, 1.4]} radius={0.06} smoothness={3} position={[0, 0, 0]} material={res.box} castShadow />408 <mesh geometry={res.ribbonV} material={res.ribbon} />409 <mesh geometry={res.ribbonH} material={res.ribbon} />410 {/* Light from inside the box once it is open */}411 <mesh geometry={res.inner} material={res.glow} position={[0, 0.51, 0]} rotation={[-Math.PI / 2, 0, 0]} />412 <pointLight ref={light} position={[0, 0.9, 0]} distance={4} decay={1.5} intensity={0} color={particleColor} />413 {/* Lid, hinged on its back edge */}414 <group ref={lid} position={[0, 0.5, -0.76]}>415 <group position={[0, 0.15, 0.76]}>416 <RoundedBox args={[1.52, 0.3, 1.52]} radius={0.06} smoothness={3} material={res.box} castShadow />417 <mesh geometry={res.lidRibbonV} material={res.ribbon} />418 <mesh geometry={res.lidRibbonH} material={res.ribbon} />419 <mesh geometry={res.bow} material={res.ribbon} position={[-0.15, 0.22, 0]} rotation={[0, 0, 0.6]} />420 <mesh geometry={res.bow} material={res.ribbon} position={[0.15, 0.22, 0]} rotation={[0, 0, -0.6]} />421 </group>422 </group>423 </group>424 <instancedMesh ref={confetti} args={[res.confettoGeometry, res.confetti, CONFETTI]} frustumCulled={false} />425 </>426 );427}428429function LookAt({ y }: { y: number }) {430 const camera = useThree((s) => s.camera);431 useEffect(() => camera.lookAt(0, y, 0), [camera, y]);432 return null;433}434435/* -------------------------------------------------------------------------- */436/* Dialog */437/* -------------------------------------------------------------------------- */438439const BUTTON: CSSProperties = {440 marginTop: 18,441 width: "100%",442 padding: "12px 18px",443 borderRadius: 999,444 border: 0,445 background: "white",446 color: "black",447 font: "700 14px/1 system-ui, sans-serif",448 cursor: "pointer",449};450451/**452 * Reward / confirmation modal with a 3D gift box that pops in, shakes, and bursts open with453 * confetti. Controlled: render it with `isOpen`, close it with `onClose` (button, Escape or a click454 * on the backdrop). It animates out before unmounting.455 */456function InteractiveModal3D({457 isOpen,458 onClose,459 title,460 description,461 actionLabel = "Awesome!",462 primaryColor,463 boxColor = primaryColor ?? "#7c3aed",464 emissiveColor,465 particleColor = emissiveColor ?? "#facc15",466 contained = false,467 pauseWhenOffscreen,468 lowPowerMode,469}: InteractiveModalProps) {470 const [mounted, setMounted] = useState(isOpen);471 const [visible, setVisible] = useState(false);472 const titleId = useId();473 const button = useRef<HTMLButtonElement>(null);474 const opener = useRef<Element | null>(null);475476 // Mount, then fade in on the next frame; on close, fade out and unmount after the transition477 useEffect(() => {478 if (isOpen) {479 opener.current = document.activeElement;480 setMounted(true);481 const id = requestAnimationFrame(() => setVisible(true));482 return () => cancelAnimationFrame(id);483 }484 setVisible(false);485 const id = window.setTimeout(() => setMounted(false), EXIT_MS);486 return () => window.clearTimeout(id);487 }, [isOpen]);488489 // Focus the action button while open; give focus back to whatever opened the modal490 useEffect(() => {491 if (!visible) return undefined;492 button.current?.focus();493 return () => {494 if (opener.current instanceof HTMLElement) opener.current.focus();495 };496 }, [visible]);497498 useEffect(() => {499 if (!isOpen) return undefined;500 const onKey = (e: KeyboardEvent) => e.key === "Escape" && onClose();501 window.addEventListener("keydown", onKey);502 return () => window.removeEventListener("keydown", onKey);503 }, [isOpen, onClose]);504505 if (!mounted) return null;506507 return (508 <div509 style={{510 position: contained ? "absolute" : "fixed",511 inset: 0,512 zIndex: 1000,513 display: "flex",514 alignItems: "center",515 justifyContent: "center",516 padding: 16,517 background: "rgba(5,5,10,0.6)",518 backdropFilter: "blur(8px)",519 opacity: visible ? 1 : 0,520 transition: `opacity ${EXIT_MS}ms ease`,521 }}522 onClick={(e) => e.target === e.currentTarget && onClose()}523 >524 <div525 role="dialog"526 aria-modal="true"527 aria-labelledby={titleId}528 style={{529 width: "min(380px, 100%)",530 borderRadius: 24,531 overflow: "hidden",532 background: "linear-gradient(180deg, #17171f 0%, #0b0b10 100%)",533 border: "1px solid rgba(255,255,255,0.12)",534 boxShadow: "0 40px 80px -30px rgba(0,0,0,0.8)",535 color: "white",536 transform: visible ? "translateY(0) scale(1)" : "translateY(16px) scale(0.94)",537 transition: `transform ${EXIT_MS + 120}ms cubic-bezier(0.34, 1.56, 0.64, 1)`,538 }}539 >540 <div style={{ position: "relative", height: 240 }}>541 <ObjectCanvas pauseWhenOffscreen={pauseWhenOffscreen} lowPowerMode={lowPowerMode} shadows camera={{ position: [0, 1.6, 4.4], fov: 38 }}>542 <ambientLight intensity={0.6} />543 <directionalLight position={[3, 5, 4]} intensity={1.6} castShadow />544 <StudioEnvironment intensity={0.8} />545 <LookAt y={0.1} />546 <GiftBox boxColor={boxColor} particleColor={particleColor} />547 </ObjectCanvas>548 </div>549 <div style={{ padding: "4px 24px 24px", textAlign: "center", font: "500 14px/1.5 system-ui, sans-serif" }}>550 <h2 id={titleId} style={{ margin: 0, font: "700 22px/1.2 system-ui, sans-serif" }}>551 {title}552 </h2>553 {description ? <p style={{ margin: "8px 0 0", opacity: 0.65 }}>{description}</p> : null}554 <button ref={button} type="button" onClick={onClose} style={BUTTON}>555 {actionLabel}556 </button>557 </div>558 </div>559 </div>560 );561}562563export default memo(InteractiveModal3D);
03
Drop it in a page
Updated live with the settings above.
app/page.tsx
1import InteractiveModal3D from "@/components/InteractiveModal3D";23export default function Section() {4 return (5 // The component fills this box: give it a position and a height6 <div style={{ position: "relative", width: "100%", height: "100vh" }}>7 <InteractiveModal3D8 title="Reward unlocked!"9 description="You completed your first project. Here is a month of Pro, on us."10 primaryColor="#7c3aed"11 emissiveColor="#facc15"12 />13 </div>14 );15}