Loading…
← All components

Sections · Storytelling

Chaos to Harmony

An about section where a dark cloud of particles gathers into a golden sculpture as the story's chapters unfold.

Installation

Use it in your project

Or skip the copy-paste

One command: writes the file and installs the dependencies.

$ npx deepui-cli add chaos-harmony-story
01

Install

The 3D packages this component is built on.

$ npm install three @react-three/fiber gsap && npm install -D @types/three
02

Add the component

One self-contained file: create components/ChaosToHarmonyStorytelling3D.tsx and paste it in.

components/ChaosToHarmonyStorytelling3D.tsx
1"use client";
2
3import {
4 memo,
5 useEffect,
6 useMemo,
7 useRef,
8 useState,
9 type CSSProperties,
10 type ReactNode,
11 type RefObject,
12} from "react";
13import * as THREE from "three";
14import { Canvas, useFrame, type CanvasProps } from "@react-three/fiber";
15import gsap from "gsap";
16import { ScrollTrigger } from "gsap/ScrollTrigger";
17
18/**
19 * The shared props API of DeepUI's individual 3D components (not the full-page templates, which keep
20 * their own tailored scenes).
21 *
22 * The props are grouped by concern. A component extends ONLY the groups it really applies, so its
23 * 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 are
29 * inlined into each component's single-file bundle (lib/bundle-source.mjs), only what it uses.
30 */
31
32/** 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";
34
35/** 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}
46
47/** 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}
58
59/** 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}
72
73/** 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}
90
91/** 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}
102
103/** 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}
112
113/** 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}
122
123/** Every group at once. Components extend only the groups they apply (see the top of this file). */
124interface Base3DComponentProps
125 extends CursorProps,
126 TiltProps,
127 Text3DProps,
128 MaterialProps,
129 MotionProps,
130 EnvironmentProps,
131 PerformanceProps {}
132
133type Defaults = Required<Omit<Base3DComponentProps, "text" | "fontUrl" | "particleCount" | "cameraFov">>;
134
135/** 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};
164
165/** Fills the positioned parent. */
166const FILL: CSSProperties = { position: "absolute", top: 0, left: 0, width: "100%", height: "100%" };
167
168interface PinnedScrollOptions {
169 /** Scroll distance of the pin, in screen heights. Default 3. */
170 length?: number;
171 /** Disable the pin (the progress then runs while the section crosses the screen). */
172 pin?: boolean;
173}
174
175/**
176 * Pins the section with GSAP ScrollTrigger (`pin: true`, scrubbed) for `length` screens of scroll and
177 * returns a ref to the progress, 0 → 1. Read it in useFrame: scrolling never re-renders React. The
178 * trigger is killed on unmount. Works with Lenis or any smooth scroll that updates ScrollTrigger.
179 */
180function usePinnedProgress(section: RefObject<HTMLElement | null>, { length = 3, pin = true }: PinnedScrollOptions = {}) {
181 const progress = useRef(0);
182 useEffect(() => {
183 const el = section.current;
184 if (!el) return undefined;
185 gsap.registerPlugin(ScrollTrigger);
186 const trigger = ScrollTrigger.create({
187 trigger: el,
188 start: pin ? "top top" : "top bottom",
189 end: () => (pin ? `+=${window.innerHeight * length}` : "bottom top"),
190 pin,
191 scrub: 1,
192 invalidateOnRefresh: true,
193 onUpdate: (self) => {
194 progress.current = self.progress;
195 },
196 });
197 return () => trigger.kill();
198 }, [section, length, pin]);
199 return progress;
200}
201
202interface SectionCanvasProps extends Omit<CanvasProps, "children" | "style" | "gl" | "frameloop">, Pick<PerformanceProps, "pauseWhenOffscreen" | "lowPowerMode"> {
203 children: ReactNode;
204 /** Pointer events for the 3D (raycasting). The canvas is click-through otherwise. */
205 interactive?: boolean;
206 /** Hidden from screen readers (default). Turn off when real HTML lives inside the canvas (drei <Html>). */
207 decorative?: boolean;
208}
209
210/** Touch screens (phones, tablets): far less GPU memory than a desktop, the tab is killed when it runs out. */
211function isTouchDevice() {
212 return typeof window !== "undefined" && window.matchMedia("(pointer: coarse)").matches;
213}
214
215/**
216 * Canvas filling its positioned parent: alpha, render loop paused while it is scrolled out of view.
217 *
218 * Memory, for pages that stack many of these (the templates have up to 9): the canvas only exists while
219 * its section is within a screen of the viewport. Further away it is unmounted, and R3F disposes the
220 * renderer and releases its WebGL context; it comes back, rebuilt, before it scrolls into view. On touch
221 * screens the pixel ratio is capped at 1.5 and antialiasing is off: on an iPhone (ratio 3) a full-screen
222 * canvas with MSAA takes hundreds of MB, and a few of them make Safari kill the tab ("a problem
223 * repeatedly occurred").
224 */
225function SectionCanvas({ children, interactive = false, decorative = true, dpr, pauseWhenOffscreen = DEFAULT_3D_PROPS.pauseWhenOffscreen, lowPowerMode = DEFAULT_3D_PROPS.lowPowerMode, ...canvasProps }: SectionCanvasProps) {
226 const ref = useRef<HTMLDivElement>(null);
227 const [inView, setInView] = useState(true);
228 const [near, setNear] = useState(false);
229 const [touch] = useState(isTouchDevice);
230 useEffect(() => {
231 const el = ref.current;
232 if (!el) return undefined;
233 const visible = new IntersectionObserver(([entry]) => setInView(entry.isIntersecting));
234 // One screen of margin above and below: built before it shows, released once well past
235 const nearby = new IntersectionObserver(([entry]) => setNear(entry.isIntersecting), { rootMargin: "100% 0px" });
236 visible.observe(el);
237 nearby.observe(el);
238 return () => {
239 visible.disconnect();
240 nearby.disconnect();
241 };
242 }, []);
243 const maxDpr = lowPowerMode ? 1 : touch ? 1.5 : 2;
244 const range: [number, number] = Array.isArray(dpr) ? [dpr[0], Math.min(dpr[1], maxDpr)] : [1, Math.min(typeof dpr === "number" ? dpr : 2, maxDpr)];
245 return (
246 <div ref={ref} aria-hidden={decorative ? "true" : undefined} style={{ ...FILL, pointerEvents: interactive ? "auto" : "none" }}>
247 {near && (
248 <Canvas
249 dpr={range}
250 frameloop={inView || !pauseWhenOffscreen ? "always" : "never"}
251 gl={{ antialias: !touch, alpha: true, powerPreference: "high-performance" }}
252 style={{ pointerEvents: interactive ? "auto" : "none", touchAction: "pan-y" }}
253 {...canvasProps}
254 >
255 {children}
256 </Canvas>
257 )}
258 </div>
259 );
260}
261
262/** True under 768px: scenes recompose (camera farther, layouts in columns). */
263function useIsMobile() {
264 const [mobile, setMobile] = useState(false);
265 useEffect(() => {
266 const query = window.matchMedia("(max-width: 767px)");
267 const sync = () => setMobile(query.matches);
268 sync();
269 query.addEventListener("change", sync);
270 return () => query.removeEventListener("change", sync);
271 }, []);
272 return mobile;
273}
274
275/** Smoothstep window: 0 outside [a, b], ramps up, holds, ramps down over `fade` at both ends. */
276function windowed(t: number, a: number, b: number, fade = 0.06) {
277 return THREE.MathUtils.smoothstep(t, a - fade, a) * (1 - THREE.MathUtils.smoothstep(t, b, b + fade));
278}
279
280// Shared by the storytelling sections: chapter shapes and sample content.
281
282interface StoryChapter {
283 title: string;
284 text: string;
285}
286
287const DEFAULT_CHAPTERS: StoryChapter[] = [
288 { title: "It started as noise", text: "A garage, a thousand ideas and no direction. Every prototype pulled a different way." },
289 { title: "Then came a shape", text: "We kept what people loved and dropped the rest. The product found its form." },
290 { title: "Now it moves as one", text: "Forty people, one vision: tools that make the web feel alive." },
291];
292
293export type { StoryChapter };
294
295export interface ChaosToHarmonyProps extends Pick<MotionProps, "particleCount">, Pick<PerformanceProps, "pauseWhenOffscreen" | "lowPowerMode"> {
296 chapters?: StoryChapter[];
297 /** Color of the particles at the start (chaos). Default "#8a8aa3". */
298 chaosColor?: string;
299 /** Color of the sculpture they settle into (harmony). Default "#fbbf24". */
300 harmonyColor?: string;
301 /** Number of particles. Default 9000 (halved on phones). */
302 particleCount?: number;
303 /** Scroll length of the pinned section, in screen heights. Default 3. */
304 scrollLength?: number;
305}
306
307const vertexShader = /* glsl */ `
308attribute vec3 aChaos;
309attribute float aSeed;
310uniform float uProgress;
311uniform float uTime;
312uniform float uPixel;
313varying float vT;
314varying float vSeed;
315void main() {
316 // Every particle leaves the chaos at its own moment, so the sculpture assembles as a wave
317 float t = smoothstep(aSeed * 0.45, aSeed * 0.45 + 0.55, uProgress);
318 vec3 drift = vec3(sin(uTime * 0.6 + aSeed * 40.0), cos(uTime * 0.5 + aSeed * 31.0), sin(uTime * 0.4 + aSeed * 17.0)) * 0.35;
319 vec3 p = mix(aChaos + drift, position, t);
320 // A spiral on the way from one state to the other
321 float s = sin(t * 3.14159);
322 p.xz = mat2(cos(s * 1.6), -sin(s * 1.6), sin(s * 1.6), cos(s * 1.6)) * p.xz;
323 vec4 mv = modelViewMatrix * vec4(p, 1.0);
324 gl_PointSize = uPixel * (1.2 + t * 1.6) * (8.0 / -mv.z);
325 gl_Position = projectionMatrix * mv;
326 vT = t;
327 vSeed = aSeed;
328}
329`;
330const fragmentShader = /* glsl */ `
331uniform vec3 uChaos;
332uniform vec3 uHarmony;
333varying float vT;
334varying float vSeed;
335void main() {
336 float d = length(gl_PointCoord - 0.5);
337 if (d > 0.5) discard;
338 float core = smoothstep(0.5, 0.0, d);
339 vec3 color = mix(uChaos * 0.75, uHarmony * (1.1 + vSeed * 0.6), vT);
340 float alpha = core * mix(0.7, 0.95, vT);
341 gl_FragColor = vec4(color * (0.6 + core * 0.8), alpha);
342 #include <colorspace_fragment>
343}
344`;
345
346/** Points spread over the surface of a torus knot: the harmonious sculpture. */
347function sculpturePoints(count: number) {
348 const knot = new THREE.TorusKnotGeometry(1.6, 0.42, 320, 24, 2, 3);
349 const pos = knot.attributes.position;
350 const out = new Float32Array(count * 3);
351 for (let i = 0; i < count; i++) {
352 const k = Math.floor(Math.random() * pos.count);
353 out[i * 3] = pos.getX(k);
354 out[i * 3 + 1] = pos.getY(k);
355 out[i * 3 + 2] = pos.getZ(k);
356 }
357 knot.dispose();
358 return out;
359}
360
361interface SceneProps {
362 count: number;
363 chaosColor: string;
364 harmonyColor: string;
365 progress: RefObject<number>;
366}
367
368const Particles = memo(function Particles({ count, chaosColor, harmonyColor, progress }: SceneProps) {
369 const points = useRef<THREE.Points>(null);
370 const geometry = useMemo(() => {
371 const g = new THREE.BufferGeometry();
372 g.setAttribute("position", new THREE.BufferAttribute(sculpturePoints(count), 3));
373 const chaos = new Float32Array(count * 3);
374 const seed = new Float32Array(count);
375 for (let i = 0; i < count; i++) {
376 // A wide, uneven cloud
377 const r = 3 + Math.random() ** 0.5 * 7;
378 const a = Math.random() * Math.PI * 2;
379 const b = Math.acos(Math.random() * 2 - 1);
380 chaos.set([Math.sin(b) * Math.cos(a) * r * 1.4, Math.cos(b) * r * 0.7, Math.sin(b) * Math.sin(a) * r], i * 3);
381 seed[i] = Math.random();
382 }
383 g.setAttribute("aChaos", new THREE.BufferAttribute(chaos, 3));
384 g.setAttribute("aSeed", new THREE.BufferAttribute(seed, 1));
385 return g;
386 }, [count]);
387 const material = useMemo(
388 () =>
389 new THREE.ShaderMaterial({
390 uniforms: {
391 uProgress: { value: 0 },
392 uTime: { value: 0 },
393 uPixel: { value: 1 },
394 uChaos: { value: new THREE.Color() },
395 uHarmony: { value: new THREE.Color() },
396 },
397 vertexShader,
398 fragmentShader,
399 transparent: true,
400 depthWrite: false,
401 blending: THREE.AdditiveBlending,
402 }),
403 []
404 );
405 useEffect(() => {
406 (material.uniforms.uChaos.value as THREE.Color).set(chaosColor);
407 (material.uniforms.uHarmony.value as THREE.Color).set(harmonyColor);
408 }, [material, chaosColor, harmonyColor]);
409 useEffect(() => () => geometry.dispose(), [geometry]);
410 useEffect(() => () => material.dispose(), [material]);
411 const smooth = useRef(0);
412
413 useFrame((state, delta) => {
414 const dt = Math.min(delta, 1 / 30);
415 smooth.current = THREE.MathUtils.damp(smooth.current, progress.current ?? 0, 4, dt);
416 const u = material.uniforms;
417 u.uProgress.value = smooth.current;
418 u.uTime.value = state.clock.elapsedTime;
419 u.uPixel.value = state.gl.getPixelRatio() * 2.2;
420 if (points.current) points.current.rotation.y += dt * (0.05 + smooth.current * 0.2);
421 });
422
423 return <points ref={points} geometry={geometry} material={material} />;
424});
425
426/**
427 * Pinned "about" section: as the visitor scrolls, a dark, scattered cloud of particles (the early
428 * chaos) gathers into a glowing, harmonious sculpture (the company today), while the chapters of the
429 * story follow one another beside it.
430 */
431function ChaosToHarmonyStorytelling3D({
432 chapters = DEFAULT_CHAPTERS,
433 chaosColor = "#8a8aa3",
434 harmonyColor = "#fbbf24",
435 particleCount = 9000,
436 scrollLength = 3,
437 pauseWhenOffscreen,
438 lowPowerMode,
439}: ChaosToHarmonyProps) {
440 const section = useRef<HTMLElement>(null);
441 const panels = useRef<(HTMLElement | null)[]>([]);
442 const progress = usePinnedProgress(section, { length: scrollLength });
443 const mobile = useIsMobile();
444 const count = mobile ? Math.round(particleCount / 2) : particleCount;
445
446 // Each chapter holds one slice of the scroll
447 useEffect(() => {
448 let id = 0;
449 const tick = () => {
450 const p = progress.current ?? 0;
451 const n = chapters.length;
452 panels.current.forEach((el, i) => {
453 if (!el) return;
454 const o = windowed(p, i / n, (i + 1) / n - 0.02, 0.06);
455 el.style.opacity = String(i === 0 && p < 0.02 ? 1 : i === n - 1 && p > 0.98 ? 1 : o);
456 el.style.transform = `translateY(${((1 - o) * 24).toFixed(1)}px)`;
457 });
458 id = requestAnimationFrame(tick);
459 };
460 id = requestAnimationFrame(tick);
461 return () => cancelAnimationFrame(id);
462 }, [progress, chapters.length]);
463
464 return (
465 <div>
466 <section ref={section} className="relative h-svh w-full overflow-hidden bg-[#050507] text-white" aria-label="Our story">
467 <SectionCanvas pauseWhenOffscreen={pauseWhenOffscreen} lowPowerMode={lowPowerMode} camera={{ position: [mobile ? 0 : 3.4, mobile ? -1.5 : 0, mobile ? 14 : 10], fov: 45 }}>
468 <Particles count={count} chaosColor={chaosColor} harmonyColor={harmonyColor} progress={progress} />
469 </SectionCanvas>
470 <div className="pointer-events-none absolute inset-x-[6%] bottom-12 md:inset-x-auto md:top-1/2 md:right-[8%] md:bottom-auto md:w-[min(420px,38vw)] md:-translate-y-1/2">
471 {chapters.map((c, i) => (
472 <article
473 key={i}
474 ref={(el) => {
475 panels.current[i] = el;
476 }}
477 className={i === 0 ? "relative" : "absolute inset-0"}
478 style={{ opacity: i === 0 ? 1 : 0 }}
479 >
480 <p className="font-mono text-xs uppercase tracking-[0.25em] text-white/45">
481 Chapter {String(i + 1).padStart(2, "0")}
482 </p>
483 <h2 className="mt-3 text-3xl font-bold leading-[0.95] tracking-tighter sm:text-5xl">{c.title}</h2>
484 <p className="mt-4 text-base leading-relaxed text-white/65">{c.text}</p>
485 </article>
486 ))}
487 </div>
488 </section>
489 </div>
490 );
491}
492
493export default memo(ChaosToHarmonyStorytelling3D);
03

Drop it in a page

It fills the box you put it in.

app/page.tsx
1import ChaosToHarmonyStorytelling3D from "@/components/ChaosToHarmonyStorytelling3D";
2
3export default function Page() {
4 return (
5 <main>
6 {/* …your other sections */}
7 {/* A full-width section: it brings its own height (and its pinned scroll) */}
8 <ChaosToHarmonyStorytelling3D />
9 {/* …the rest of the page */}
10 </main>
11 );
12}
Next componentScattered Review Cloud→