Loading…
← All components

Gallery · Prism

Prism Accordion

A row of image prisms that turn to their next face on click, two to four faces each.

<PrismAccordionGallery />Live

Customize

Installation

Use it in your project

Or skip the copy-paste

One command: writes the file and installs the dependencies.

$ npx deepui-cli add prism-accordion
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/PrismAccordionGallery.tsx and paste it in.

components/PrismAccordionGallery.tsx
1"use client";
2
3import {
4 Component,
5 memo,
6 Suspense,
7 useCallback,
8 useEffect,
9 useLayoutEffect,
10 useMemo,
11 useRef,
12 useState,
13 type CSSProperties,
14 type ReactNode,
15 type Ref,
16} from "react";
17import * as THREE from "three";
18import {
19 Canvas,
20 useFrame,
21 useThree,
22 type CanvasProps,
23 type ThreeElements,
24 type ThreeEvent,
25} from "@react-three/fiber";
26import { ContactShadows, Environment, Lightformer, useTexture } from "@react-three/drei";
27
28/**
29 * The shared props API of DeepUI's individual 3D components (not the full-page templates, which keep
30 * their own tailored scenes).
31 *
32 * The props are grouped by concern. A component extends ONLY the groups it really applies, so its
33 * type never advertises a knob that does nothing (a card has no particles, a background has no tilt):
34 *
35 * interface MyCardProps extends CursorProps, TiltProps, MaterialProps, PerformanceProps { … }
36 *
37 * `Base3DComponentProps` is every group at once, for tooling that handles any component. Same name,
38 * same unit and same meaning everywhere; the default values live in DEFAULT_3D_PROPS. These files are
39 * inlined into each component's single-file bundle (lib/bundle-source.mjs), only what it uses.
40 */
41
42/** Which rotation axes follow the pointer. "x-only": the object nods (up / down); "y-only": it turns (left / right). */
43export type TiltAxis = "both" | "x-only" | "y-only" | "none";
44
45/** 1. Cursor: how the pointer pulls, pushes and drags the object. */
46interface CursorProps {
47 /** 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). */
48 cursorRadius?: number;
49 /** Positive pulls things towards the pointer, negative pushes them away (repulsion, shockwave). Default 1. */
50 cursorForce?: number;
51 /** How far the object slides towards the pointer, 0 (stays put) to 1 (follows closely). Default 0. */
52 magneticStrength?: number;
53 /** Share of the remaining distance the motion closes each frame (at 60 fps), 0.01 (heavy, slow) to 1 (instant). Default 0.1. */
54 cursorDamping?: number;
55}
56
57/** 2. Tilt and parallax: the object leans towards the pointer, its layers slide against each other. */
58interface TiltProps {
59 /** Largest lean towards the pointer, in degrees. Default 15. */
60 maxTiltAngle?: number;
61 /** Axes that follow the pointer. Default "both". */
62 tiltAxis?: TiltAxis;
63 /** Lean away from the pointer instead of towards it. Default false. */
64 invertTilt?: boolean;
65 /** How far apart the depth layers slide when the object tilts, 0 (flat) to 2. Default 1. */
66 parallaxOffset?: number;
67}
68
69/** 3. Text and 3D typography, for components that draw a label. */
70interface Text3DProps {
71 /** The label drawn by the component. */
72 text?: string;
73 /** Scale of the lettering. Default 1. */
74 fontSize?: number;
75 /** Extrusion depth of 3D letters. Default 0.2. */
76 textDepth?: number;
77 /** Bevelled, light-catching edges on 3D letters. Default true. */
78 bevelEnabled?: boolean;
79 /** Custom font: a .woff / .ttf (flat text) or a typeface .json (extruded text). */
80 fontUrl?: string;
81}
82
83/** 4. Rendering, materials and glow. */
84interface MaterialProps {
85 /** Main color of the object. Default "#6366f1". */
86 primaryColor?: string;
87 /** Color of the glow. Default "#00f0ff". */
88 emissiveColor?: string;
89 /** Strength of the glow, 0 (none) to 3. Default 1. */
90 emissiveIntensity?: number;
91 /** 0 (mirror, glass) to 1 (matte). Default 0.3. */
92 roughness?: number;
93 /** 0 (plastic, organic) to 1 (metal). Default 0.5. */
94 metalness?: number;
95 /** 0 (opaque) to 1 (clear glass): see-through, refracting surfaces. Default 0. */
96 transmission?: number;
97 /** Technical wireframe rendering. Default false. */
98 wireframe?: boolean;
99}
100
101/** 5. Particles, idle motion and shader animation. */
102interface MotionProps {
103 /** Number of instanced elements. Default depends on the component. */
104 particleCount?: number;
105 /** Spin on its own, in radians per second (negative: the other way; 0.5 ≈ one turn in 12 s). Default 0. */
106 autoRotateSpeed?: number;
107 /** Pulses or ripples per second. Default 1. */
108 pulseRate?: number;
109 /** Amplitude of the noise deformation, 0 (none) to 2. Default 1. */
110 displacementScale?: number;
111}
112
113/** 6. Environment and camera. */
114interface EnvironmentProps {
115 /** Camera field of view, in degrees. Default depends on the component. */
116 cameraFov?: number;
117 /** Color of the depth fog. Default "#0a0a0a". */
118 fogColor?: string;
119 /** Thickness of the fog, 0 (none) to 0.2. Default 0. */
120 fogDensity?: number;
121}
122
123/** 7. Performance and accessibility. */
124interface PerformanceProps {
125 /** Lighter rendering for weak devices: pixel ratio 1, fewer instances, smaller environment maps. Default false. */
126 lowPowerMode?: boolean;
127 /** Under the OS "reduce motion" setting, stop idle spin, pulses and deformation (pointer feedback stays). Default true. */
128 respectReducedMotion?: boolean;
129 /** Stop the render loop while the component is scrolled out of view. Default true. */
130 pauseWhenOffscreen?: boolean;
131}
132
133/** Every group at once. Components extend only the groups they apply (see the top of this file). */
134interface Base3DComponentProps
135 extends CursorProps,
136 TiltProps,
137 Text3DProps,
138 MaterialProps,
139 MotionProps,
140 EnvironmentProps,
141 PerformanceProps {}
142
143type Defaults = Required<Omit<Base3DComponentProps, "text" | "fontUrl" | "particleCount" | "cameraFov">>;
144
145/** The values a prop takes when it is left out. A component may override one, and then documents it. */
146const DEFAULT_3D_PROPS: Defaults = {
147 cursorRadius: 220,
148 cursorForce: 1,
149 magneticStrength: 0,
150 cursorDamping: 0.1,
151 maxTiltAngle: 15,
152 tiltAxis: "both",
153 invertTilt: false,
154 parallaxOffset: 1,
155 fontSize: 1,
156 textDepth: 0.2,
157 bevelEnabled: true,
158 primaryColor: "#6366f1",
159 emissiveColor: "#00f0ff",
160 emissiveIntensity: 1,
161 roughness: 0.3,
162 metalness: 0.5,
163 transmission: 0,
164 wireframe: false,
165 autoRotateSpeed: 0,
166 pulseRate: 1,
167 displacementScale: 1,
168 fogColor: "#0a0a0a",
169 fogDensity: 0,
170 lowPowerMode: false,
171 respectReducedMotion: true,
172 pauseWhenOffscreen: true,
173};
174
175/** Fills the positioned parent. Unlike the backgrounds, galleries receive pointer events. */
176const GALLERY_STYLE: CSSProperties = {
177 position: "absolute",
178 top: 0,
179 left: 0,
180 width: "100%",
181 height: "100%",
182};
183
184interface GalleryCanvasProps extends Omit<CanvasProps, "children" | "style" | "frameloop" | "gl">, Pick<PerformanceProps, "pauseWhenOffscreen" | "lowPowerMode"> {
185 children: ReactNode;
186 /**
187 * The gallery uses the wheel: Lenis (site-wide smooth scroll) is told to leave wheel events
188 * over the canvas alone, so the gallery's own handler decides whether the page scrolls.
189 */
190 captureWheel?: boolean;
191 /** CSS touch-action of the canvas: "pan-y" keeps vertical page scrolling on touch screens. */
192 touchAction?: CSSProperties["touchAction"];
193}
194
195/**
196 * Ready-to-use <Canvas> shared by every gallery: the render loop pauses while the gallery is
197 * scrolled out of view, and R3F disposes the renderer and its WebGL context on unmount.
198 */
199function GalleryCanvas({ children, captureWheel = false, touchAction = "pan-y", dpr = [1, 2], pauseWhenOffscreen = DEFAULT_3D_PROPS.pauseWhenOffscreen, lowPowerMode = DEFAULT_3D_PROPS.lowPowerMode, ...canvasProps }: GalleryCanvasProps) {
200 const containerRef = useRef<HTMLDivElement>(null);
201 const [inView, setInView] = useState(true);
202
203 useEffect(() => {
204 const el = containerRef.current;
205 if (!el) return undefined;
206 const observer = new IntersectionObserver(([entry]) => setInView(entry.isIntersecting));
207 observer.observe(el);
208 return () => observer.disconnect();
209 }, []);
210
211 return (
212 <div ref={containerRef} style={GALLERY_STYLE} {...(captureWheel ? { "data-lenis-prevent": "" } : {})}>
213 <Canvas
214 dpr={lowPowerMode ? 1 : dpr}
215 frameloop={inView || !pauseWhenOffscreen ? "always" : "never"}
216 gl={{ antialias: true, alpha: true, powerPreference: "high-performance" }}
217 style={{ touchAction }}
218 {...canvasProps}
219 >
220 {children}
221 </Canvas>
222 </div>
223 );
224}
225
226/**
227 * Collects the textures loaded by a gallery's cards and disposes them (plus drei's loader cache
228 * entries) when the gallery unmounts or its image list changes.
229 */
230function useGalleryTextures(urls: string[]) {
231 const textures = useRef(new Set<THREE.Texture>());
232 const key = urls.join("\n");
233 const onTexture = useCallback((texture: THREE.Texture) => {
234 textures.current.add(texture);
235 }, []);
236
237 useEffect(() => {
238 const loaded = textures.current;
239 return () => {
240 loaded.forEach((texture) => texture.dispose());
241 loaded.clear();
242 const list = key ? key.split("\n") : [];
243 if (list.length) useTexture.clear(list);
244 };
245 }, [key]);
246
247 return onTexture;
248}
249
250const cardVertexShader = /* glsl */ `
251uniform float uCurve; // 1 / radius: bends the card around the Y axis, convex side out (0 = flat)
252
253varying vec2 vUv;
254varying float vFacing;
255
256void main() {
257 vUv = uv;
258 vec3 p = position;
259 vec3 n = vec3(0.0, 0.0, 1.0);
260 if (uCurve > 0.0001) {
261 float a = p.x * uCurve;
262 p.x = sin(a) / uCurve;
263 p.z = (cos(a) - 1.0) / uCurve;
264 n = vec3(sin(a), 0.0, cos(a));
265 }
266 vec4 mvPosition = modelViewMatrix * vec4(p, 1.0);
267 vFacing = abs(dot(normalize(normalMatrix * n), normalize(-mvPosition.xyz)));
268 gl_Position = projectionMatrix * mvPosition;
269}
270`;
271
272const cardFragmentShader = /* glsl */ `
273uniform sampler2D uMap;
274uniform float uHasMap; // 1 once the texture is loaded
275uniform float uReveal; // 0 → 1 fade from the placeholder to the image
276uniform float uImageAspect;
277uniform vec2 uSize; // card size in world units
278uniform float uRadius; // corner radius in world units
279uniform float uZoom; // > 1 crops into the image (headroom for parallax)
280uniform vec2 uOffset; // image shift inside the card (parallax), in UV units
281uniform float uBlur; // motion blur length, in UV units
282uniform vec2 uBlurDir;
283uniform float uOpacity;
284uniform float uDim; // 0 = full brightness, 1 = black
285uniform float uHover; // 0 → 1 highlight
286uniform float uShade; // how much faces turned away from the camera darken
287uniform float uTime;
288uniform vec3 uTint; // placeholder color
289
290varying vec2 vUv;
291varying float vFacing;
292
293// "object-fit: cover": the image fills the card without stretching
294vec2 coverUv(vec2 uv) {
295 float planeAspect = uSize.x / uSize.y;
296 vec2 scale = planeAspect > uImageAspect ? vec2(1.0, uImageAspect / planeAspect) : vec2(planeAspect / uImageAspect, 1.0);
297 return (uv - 0.5) * scale / uZoom + 0.5 + uOffset;
298}
299
300float roundedMask(vec2 uv) {
301 vec2 p = (uv - 0.5) * uSize;
302 vec2 q = abs(p) - (uSize * 0.5 - uRadius);
303 float d = length(max(q, 0.0)) + min(max(q.x, q.y), 0.0) - uRadius;
304 float aa = fwidth(d);
305 return 1.0 - smoothstep(-aa, aa, d);
306}
307
308void main() {
309 vec2 uv = vUv;
310 // Seen from behind (a ring's far side), the image would be mirrored: flip it back
311 if (!gl_FrontFacing) uv.x = 1.0 - uv.x;
312
313 float mask = roundedMask(vUv);
314 float alpha = mask * uOpacity;
315 if (alpha < 0.005) discard;
316
317 // Placeholder: dark tint with a sweeping shimmer while the texture loads
318 float shimmer = pow(max(0.0, sin((vUv.x - vUv.y * 0.5) * 3.0 - uTime * 2.5)), 12.0);
319 vec3 color = uTint + shimmer * 0.06;
320
321 if (uHasMap > 0.5) {
322 vec2 imageUv = coverUv(uv);
323 vec3 image;
324 if (uBlur > 0.0005) {
325 // Motion blur: 7 taps along the direction of travel
326 image = vec3(0.0);
327 for (int i = 0; i < 7; i++) {
328 float t = (float(i) / 6.0 - 0.5) * uBlur;
329 image += texture2D(uMap, imageUv + uBlurDir * t).rgb;
330 }
331 image /= 7.0;
332 } else {
333 image = texture2D(uMap, imageUv).rgb;
334 }
335 color = mix(color, image, uReveal);
336 }
337
338 color *= mix(1.0, 0.35 + 0.65 * vFacing, uShade);
339 color *= 1.0 - uDim;
340 color += uHover * 0.07;
341 gl_FragColor = vec4(color, alpha);
342 #include <colorspace_fragment>
343}
344`;
345
346interface CardUniforms {
347 uMap: THREE.IUniform<THREE.Texture | null>;
348 uHasMap: THREE.IUniform<number>;
349 uReveal: THREE.IUniform<number>;
350 uImageAspect: THREE.IUniform<number>;
351 uSize: THREE.IUniform<THREE.Vector2>;
352 uRadius: THREE.IUniform<number>;
353 uCurve: THREE.IUniform<number>;
354 uZoom: THREE.IUniform<number>;
355 uOffset: THREE.IUniform<THREE.Vector2>;
356 uBlur: THREE.IUniform<number>;
357 uBlurDir: THREE.IUniform<THREE.Vector2>;
358 uOpacity: THREE.IUniform<number>;
359 uDim: THREE.IUniform<number>;
360 uHover: THREE.IUniform<number>;
361 uShade: THREE.IUniform<number>;
362 uTime: THREE.IUniform<number>;
363 uTint: THREE.IUniform<THREE.Color>;
364}
365
366function createCardMaterial() {
367 const uniforms: CardUniforms = {
368 uMap: { value: null },
369 uHasMap: { value: 0 },
370 uReveal: { value: 0 },
371 uImageAspect: { value: 1 },
372 uSize: { value: new THREE.Vector2(1, 1) },
373 uRadius: { value: 0.06 },
374 uCurve: { value: 0 },
375 uZoom: { value: 1 },
376 uOffset: { value: new THREE.Vector2() },
377 uBlur: { value: 0 },
378 uBlurDir: { value: new THREE.Vector2(0, 1) },
379 uOpacity: { value: 1 },
380 uDim: { value: 0 },
381 uHover: { value: 0 },
382 uShade: { value: 0 },
383 uTime: { value: 0 },
384 uTint: { value: new THREE.Color() },
385 };
386 return new THREE.ShaderMaterial({
387 uniforms: uniforms as unknown as Record<string, THREE.IUniform>,
388 vertexShader: cardVertexShader,
389 fragmentShader: cardFragmentShader,
390 transparent: true,
391 side: THREE.DoubleSide,
392 });
393}
394
395/** Typed access to a card's uniforms from its mesh (galleries animate them in useFrame). */
396function cardUniforms(mesh: THREE.Mesh) {
397 return (mesh.material as THREE.ShaderMaterial).uniforms as unknown as CardUniforms;
398}
399
400/** Plane sized in world units; enough columns to bend smoothly when the card is curved. */
401function createCardGeometry(width: number, height: number, segments = 1) {
402 return new THREE.PlaneGeometry(width, height, segments, 1);
403}
404
405function TextureBinder({ url, material, onTexture }: { url: string; material: THREE.ShaderMaterial; onTexture?: (texture: THREE.Texture) => void }) {
406 const texture = useTexture(url); // suspends until loaded; drei caches it per URL
407 useLayoutEffect(() => {
408 if (texture.colorSpace !== THREE.SRGBColorSpace) {
409 texture.colorSpace = THREE.SRGBColorSpace;
410 texture.needsUpdate = true;
411 }
412 texture.anisotropy = 4;
413 const image = texture.image as { width?: number; height?: number } | undefined;
414 const u = material.uniforms as unknown as CardUniforms;
415 if (u.uMap.value !== texture) u.uReveal.value = 0; // fade in each new image
416 u.uMap.value = texture;
417 u.uImageAspect.value = image?.width && image?.height ? image.width / image.height : 1;
418 u.uHasMap.value = 1;
419 onTexture?.(texture);
420 }, [texture, material, onTexture]);
421 return null;
422}
423
424/** A failed image keeps its placeholder instead of breaking the whole gallery. */
425class TextureErrorBoundary extends Component<{ children: ReactNode }, { failed: boolean }> {
426 state = { failed: false };
427 static getDerivedStateFromError() {
428 return { failed: true };
429 }
430 render() {
431 return this.state.failed ? null : this.props.children;
432 }
433}
434
435interface ImageCardProps extends Omit<ThreeElements["mesh"], "geometry" | "material" | "ref"> {
436 url: string;
437 width: number;
438 height: number;
439 /** Shared plane from createCardGeometry(width, height, segments). */
440 geometry: THREE.BufferGeometry;
441 radius?: number;
442 /** 1 / radius of the surface the card is bent on (0 = flat). */
443 curve?: number;
444 /** 0–1: darken the card as it turns away from the camera. */
445 shade?: number;
446 zoom?: number;
447 placeholderColor?: string;
448 onTexture?: (texture: THREE.Texture) => void;
449 ref?: Ref<THREE.Mesh>;
450}
451
452/**
453 * Image card: rounded corners, cover-fit image, placeholder shimmer while loading, fade-in once
454 * loaded, placeholder kept if the image fails. Its material is created once and disposed on unmount.
455 */
456const ImageCard = memo(function ImageCard({
457 url,
458 width,
459 height,
460 geometry,
461 radius = 0.06,
462 curve = 0,
463 shade = 0,
464 zoom = 1,
465 placeholderColor = "#151517",
466 onTexture,
467 ref,
468 ...meshProps
469}: ImageCardProps) {
470 const material = useMemo(() => createCardMaterial(), []);
471 const u = material.uniforms as unknown as CardUniforms;
472
473 useEffect(() => {
474 u.uSize.value.set(width, height);
475 u.uRadius.value = Math.min(radius, width / 2, height / 2);
476 u.uCurve.value = curve;
477 u.uShade.value = shade;
478 u.uZoom.value = zoom;
479 u.uTint.value.set(placeholderColor);
480 }, [u, width, height, radius, curve, shade, zoom, placeholderColor]);
481
482 useEffect(() => () => material.dispose(), [material]);
483
484 useFrame((state, delta) => {
485 if (u.uHasMap.value > 0.5) {
486 if (u.uReveal.value < 0.999) u.uReveal.value = THREE.MathUtils.damp(u.uReveal.value, 1, 5, delta);
487 } else {
488 u.uTime.value = state.clock.elapsedTime;
489 }
490 });
491
492 return (
493 // The shader bends the card: the plane's own bounds are not reliable for frustum culling
494 <mesh ref={ref} geometry={geometry} material={material} frustumCulled={false} {...meshProps}>
495 <TextureErrorBoundary key={url}>
496 <Suspense fallback={null}>
497 <TextureBinder url={url} material={material} onTexture={onTexture} />
498 </Suspense>
499 </TextureErrorBoundary>
500 </mesh>
501 );
502});
503
504export interface PrismItem {
505 front: string;
506 back: string;
507 left?: string;
508 right?: string;
509}
510
511export interface PrismAccordionProps extends Pick<PerformanceProps, "pauseWhenOffscreen" | "lowPowerMode"> {
512 /** One prism per item. Its faces, in turning order: front, right, back, left (the defined ones). */
513 items: PrismItem[];
514 /** Gap between prisms, in world units. Default 0.5. */
515 spacing?: number;
516 /** Speed of the turn to the next face. Default 1. */
517 rotationSpeed?: number;
518}
519
520const FACE_WIDTH = 1.9;
521const FACE_HEIGHT = 2.5;
522const FLOOR_Y = -FACE_HEIGHT / 2 - 0.26; // just under the prisms
523const EDGE_RADIUS = 0.028;
524
525interface PrismShared {
526 faceGeometry: THREE.BufferGeometry;
527 edgeGeometry: THREE.BufferGeometry;
528 metal: THREE.MeshStandardMaterial;
529 glass: THREE.MeshPhysicalMaterial;
530 onTexture: (texture: THREE.Texture) => void;
531}
532
533interface PrismProps {
534 faces: string[];
535 x: number;
536 rotationSpeed: number;
537 shared: PrismShared;
538}
539
540/** Polygon of the prism's corners, in the XZ plane (for the caps). */
541function prismCorners(sides: number, width: number) {
542 const step = (2 * Math.PI) / sides;
543 const circumradius = width / (2 * Math.sin(step / 2));
544 return Array.from({ length: sides }, (_, k) => {
545 const a = (k + 0.5) * step;
546 return new THREE.Vector2(Math.sin(a) * circumradius, Math.cos(a) * circumradius);
547 });
548}
549
550const Prism = memo(function Prism({ faces, x, rotationSpeed, shared }: PrismProps) {
551 const groupRef = useRef<THREE.Group>(null);
552 const faceRefs = useRef<(THREE.Mesh | null)[]>([]);
553 const hovered = useRef(false);
554 const spin = useRef({ angle: 0, target: 0, velocity: 0, tiltX: 0, tiltY: 0, pointerX: 0, pointerY: 0 });
555 const sides = faces.length;
556 const step = (2 * Math.PI) / sides;
557 // Two faces: a card, back to back. Three or more: a real prism, faces at the apothem.
558 const apothem = sides === 2 ? 0.012 : FACE_WIDTH / (2 * Math.tan(Math.PI / sides));
559
560 // Caps (top and bottom) and corner positions for the metal edges
561 const corners = useMemo(() => (sides > 2 ? prismCorners(sides, FACE_WIDTH) : [new THREE.Vector2(-FACE_WIDTH / 2, 0), new THREE.Vector2(FACE_WIDTH / 2, 0)]), [sides]);
562 const capGeometry = useMemo(() => {
563 if (sides <= 2) return null;
564 const g = new THREE.ShapeGeometry(new THREE.Shape(corners.map((c) => new THREE.Vector2(c.x, -c.y))));
565 g.rotateX(-Math.PI / 2);
566 return g;
567 }, [corners, sides]);
568 useEffect(() => () => capGeometry?.dispose(), [capGeometry]);
569
570 useFrame((_, delta) => {
571 const group = groupRef.current;
572 if (!group) return;
573 const dt = Math.min(delta, 1 / 30);
574 const s = spin.current;
575
576 // Damped spring towards the target face: a short, physical overshoot at the end of each turn
577 const stiffness = 70 * rotationSpeed * rotationSpeed;
578 const damping = 10 * rotationSpeed;
579 s.velocity += (s.target - s.angle) * stiffness * dt;
580 s.velocity *= Math.exp(-damping * dt);
581 s.angle += s.velocity * dt;
582
583 // Hover: the prism leans towards the pointer and lifts a little
584 const k = 1 - Math.exp(-8 * dt);
585 s.tiltX += ((hovered.current ? -s.pointerY * 0.18 : 0) - s.tiltX) * k;
586 s.tiltY += ((hovered.current ? s.pointerX * 0.25 : 0) - s.tiltY) * k;
587 group.rotation.set(s.tiltX, s.angle + s.tiltY, 0);
588 group.position.y = THREE.MathUtils.damp(group.position.y, hovered.current ? 0.12 : 0, 8, dt);
589
590 faceRefs.current.forEach((mesh) => {
591 if (!mesh) return;
592 const u = cardUniforms(mesh);
593 u.uHover.value = THREE.MathUtils.damp(u.uHover.value, hovered.current ? 1 : 0, 8, dt);
594 });
595 });
596
597 return (
598 <group position={[x, 0, 0]}>
599 <group
600 ref={groupRef}
601 onPointerOver={(e: ThreeEvent<PointerEvent>) => {
602 e.stopPropagation();
603 hovered.current = true;
604 document.body.style.cursor = "pointer";
605 }}
606 onPointerOut={() => {
607 hovered.current = false;
608 document.body.style.cursor = "";
609 }}
610 onPointerMove={(e: ThreeEvent<PointerEvent>) => {
611 // Pointer position relative to the prism, -1..1
612 spin.current.pointerX = THREE.MathUtils.clamp((e.point.x - x) / (FACE_WIDTH / 2), -1, 1);
613 spin.current.pointerY = THREE.MathUtils.clamp(e.point.y / (FACE_HEIGHT / 2), -1, 1);
614 }}
615 onClick={(e: ThreeEvent<MouseEvent>) => {
616 e.stopPropagation();
617 // Next face (shift-click: previous)
618 spin.current.target -= e.nativeEvent.shiftKey ? -step : step;
619 }}
620 >
621 {faces.map((url, k) => (
622 <group key={k} rotation={[0, k * step, 0]}>
623 <ImageCard
624 ref={(mesh) => {
625 faceRefs.current[k] = mesh;
626 }}
627 url={url}
628 width={FACE_WIDTH}
629 height={FACE_HEIGHT}
630 geometry={shared.faceGeometry}
631 radius={0.015}
632 shade={0.85}
633 position={[0, 0, apothem]}
634 onTexture={shared.onTexture}
635 />
636 </group>
637 ))}
638 {/* Polished metal on every vertical edge: it catches the studio lights as the prism turns */}
639 {corners.map((c, k) => (
640 <mesh key={k} geometry={shared.edgeGeometry} material={shared.metal} position={[c.x, 0, sides > 2 ? c.y : 0]} />
641 ))}
642 {capGeometry ? (
643 <>
644 <mesh geometry={capGeometry} material={shared.glass} position={[0, FACE_HEIGHT / 2, 0]} />
645 <mesh geometry={capGeometry} material={shared.glass} position={[0, -FACE_HEIGHT / 2, 0]} rotation={[Math.PI, 0, 0]} />
646 </>
647 ) : null}
648 </group>
649 </group>
650 );
651});
652
653// Pool of light on the floor: on a dark page the contact shadows need something lit to fall on
654const floorVertexShader = /* glsl */ `
655varying vec2 vUv;
656void main() {
657 vUv = uv;
658 gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
659}
660`;
661const floorFragmentShader = /* glsl */ `
662uniform vec3 uColor;
663uniform float uAspect;
664varying vec2 vUv;
665void main() {
666 float d = length((vUv - 0.5) * vec2(uAspect, 1.0));
667 float alpha = 1.0 - smoothstep(0.05, 0.5, d);
668 gl_FragColor = vec4(uColor, alpha * 0.9);
669 #include <colorspace_fragment>
670}
671`;
672
673function Floor({ width }: { width: number }) {
674 const depth = 9;
675 const geometry = useMemo(() => new THREE.PlaneGeometry(width, depth), [width]);
676 const material = useMemo(
677 () =>
678 new THREE.ShaderMaterial({
679 uniforms: { uColor: { value: new THREE.Color("#2a2a31") }, uAspect: { value: 1 } },
680 vertexShader: floorVertexShader,
681 fragmentShader: floorFragmentShader,
682 transparent: true,
683 depthWrite: false,
684 }),
685 []
686 );
687 useEffect(() => {
688 material.uniforms.uAspect.value = width / depth;
689 }, [material, width]);
690 useEffect(() => () => geometry.dispose(), [geometry]);
691 useEffect(() => () => material.dispose(), [material]);
692 return <mesh geometry={geometry} material={material} rotation={[-Math.PI / 2, 0, 0]} position={[0, FLOOR_Y - 0.01, 0]} />;
693}
694
695/** Keeps the whole row in frame, whatever the container's proportions (portrait included). */
696function CameraFit({ width }: { width: number }) {
697 const camera = useThree((state) => state.camera) as THREE.PerspectiveCamera;
698 const size = useThree((state) => state.size);
699 useEffect(() => {
700 const aspect = size.width / Math.max(1, size.height);
701 const halfFov = THREE.MathUtils.degToRad(camera.fov / 2);
702 // Distance at which the row's width (plus margins) fits horizontally, and the faces vertically
703 const fitWidth = (width / 2 + 0.6) / (Math.tan(halfFov) * aspect);
704 const fitHeight = (FACE_HEIGHT / 2 + 1.2) / Math.tan(halfFov);
705 const distance = Math.max(fitWidth, fitHeight);
706 camera.position.set(0, distance * 0.18, distance);
707 camera.lookAt(0, -0.35, 0);
708 }, [camera, size, width]);
709 return null;
710}
711
712const Row = memo(function Row({ items, spacing, rotationSpeed }: Required<Omit<PrismAccordionProps, "pauseWhenOffscreen" | "lowPowerMode">>) {
713 const urls = useMemo(() => items.flatMap((item) => [item.front, item.right, item.back, item.left].filter((u): u is string => !!u)), [items]);
714 const onTexture = useGalleryTextures(urls);
715
716 const faceGeometry = useMemo(() => createCardGeometry(FACE_WIDTH, FACE_HEIGHT), []);
717 const edgeGeometry = useMemo(() => new THREE.CylinderGeometry(EDGE_RADIUS, EDGE_RADIUS, FACE_HEIGHT, 12), []);
718 const metal = useMemo(() => new THREE.MeshStandardMaterial({ color: "#d4d4d8", metalness: 1, roughness: 0.18 }), []);
719 const glass = useMemo(
720 () => new THREE.MeshPhysicalMaterial({ color: "#0b0b0d", metalness: 0.6, roughness: 0.15, clearcoat: 1, clearcoatRoughness: 0.05, side: THREE.DoubleSide }),
721 []
722 );
723 useEffect(
724 () => () => {
725 faceGeometry.dispose();
726 edgeGeometry.dispose();
727 metal.dispose();
728 glass.dispose();
729 },
730 [faceGeometry, edgeGeometry, metal, glass]
731 );
732 const shared = useMemo(() => ({ faceGeometry, edgeGeometry, metal, glass, onTexture }), [faceGeometry, edgeGeometry, metal, glass, onTexture]);
733
734 // Faces in turning order; an item always keeps at least front and back
735 const prisms = useMemo(() => items.map((item) => [item.front, item.right, item.back, item.left].filter((u): u is string => !!u)), [items]);
736 const pitch = FACE_WIDTH * 1.35 + spacing;
737
738 return (
739 <>
740 {prisms.map((faces, i) => (
741 <Prism key={i} faces={faces} x={(i - (prisms.length - 1) / 2) * pitch} rotationSpeed={rotationSpeed} shared={shared} />
742 ))}
743 </>
744 );
745});
746
747function PrismAccordionGallery({ items, spacing = 0.5, rotationSpeed = 1, pauseWhenOffscreen, lowPowerMode }: PrismAccordionProps) {
748 // Frame the whole row
749 const width = items.length * (FACE_WIDTH * 1.35 + spacing);
750 return (
751 <GalleryCanvas pauseWhenOffscreen={pauseWhenOffscreen} lowPowerMode={lowPowerMode} camera={{ position: [0, 1.4, 10], fov: 40 }}>
752 <CameraFit width={width} />
753 <ambientLight intensity={0.4} />
754 <directionalLight position={[4, 6, 5]} intensity={2} />
755 {/* Studio light panels for the metal edges and glass caps: no HDR file to download */}
756 <Environment resolution={256} frames={1}>
757 <Lightformer form="rect" intensity={3} position={[0, 5, 2]} rotation-x={Math.PI / 2} scale={[12, 3, 1]} />
758 <Lightformer form="rect" intensity={2} position={[-6, 1, 3]} rotation-y={Math.PI / 2} scale={[1, 6, 1]} />
759 <Lightformer form="rect" intensity={2} position={[6, 1, 3]} rotation-y={-Math.PI / 2} scale={[1, 6, 1]} />
760 </Environment>
761 <Row items={items} spacing={spacing} rotationSpeed={rotationSpeed} />
762 {/* Live contact shadows: they follow every turn and tilt */}
763 <Floor width={width + 8} />
764 <ContactShadows position={[0, FLOOR_Y, 0]} opacity={0.85} scale={width + 6} blur={2.2} far={3.5} resolution={512} color="#000000" />
765 </GalleryCanvas>
766 );
767}
768
769export default memo(PrismAccordionGallery);
03

Drop it in a page

Updated live with the settings above.

app/page.tsx
1import PrismAccordionGallery from "@/components/PrismAccordionGallery";
2
3export default function Section() {
4 return (
5 // The component fills this box: give it a position and a height
6 <div style={{ position: "relative", width: "100%", height: "100vh" }}>
7 <PrismAccordionGallery
8 items={[
9 { front: "/3d1.jpg", back: "/3d2.jpg" },
10 { front: "/cowboy.jpg", right: "/girl.jpg", back: "/haine.jpg" },
11 {
12 front: "/heart.jpg",
13 right: "/piastri.jpg",
14 back: "/touching.jpg",
15 left: "/blackhole.jpg",
16 },
17 {
18 front: "/3d3.jpg",
19 right: "/3d4.jpg",
20 back: "/scroll-expand-bg.jpg",
21 left: "/girl.jpg",
22 },
23 ]}
24 spacing={0.5}
25 rotationSpeed={1}
26 />
27 </div>
28 );
29}
Next componentChrome Blob Cursor→