Loading…
← All components

Navigation · Prism

Studio Prism Navbar

Every link is a quartz prism that flips over on hover to reveal a second face; a click ripples a wave through its neighbors.

<StudioPrismNavbar3D />Live

Customize

Quartz#1f1b2e
Hidden face#c084fc

Installation

Use it in your project

Or skip the copy-paste

One command: writes the file and installs the dependencies.

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

components/StudioPrismNavbar3D.tsx
1"use client";
2
3import {
4 memo,
5 useEffect,
6 useLayoutEffect,
7 useMemo,
8 useRef,
9 useState,
10 type CSSProperties,
11 type ReactNode,
12 type RefObject,
13} from "react";
14import * as THREE from "three";
15import { Canvas, useFrame, useThree, type CanvasProps } from "@react-three/fiber";
16import { Environment, Lightformer } from "@react-three/drei";
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/**
166 * Perspective camera placed so that 1 world unit = 1 CSS pixel on the z = 0 plane: widgets are laid
167 * out in pixels like the rest of the page, and still get real depth (presses, tilts, shadows).
168 */
169function PixelPerspective({ fov = 30 }: { fov?: number }) {
170 const camera = useThree((state) => state.camera) as THREE.PerspectiveCamera;
171 const size = useThree((state) => state.size);
172 useLayoutEffect(() => {
173 camera.fov = fov;
174 camera.near = 1;
175 camera.far = 20000;
176 camera.position.set(0, 0, size.height / 2 / Math.tan(THREE.MathUtils.degToRad(fov / 2)));
177 camera.lookAt(0, 0, 0);
178 camera.updateProjectionMatrix();
179 }, [camera, size, fov]);
180 return null;
181}
182
183function pageFontFamily() {
184 if (typeof document === "undefined") return "sans-serif";
185 return getComputedStyle(document.body).fontFamily || "sans-serif";
186}
187
188interface LabelOptions {
189 text: string;
190 /** Second, smaller line under the text. */
191 subtext?: string;
192 /** Glyph drawn before the text (emoji, arrow, symbol…). */
193 icon?: string;
194 width: number;
195 height: number;
196 color: string;
197 /** Face color; transparent when omitted. */
198 background?: string;
199 fontSize?: number;
200 fontWeight?: number;
201 /** Wrap the text over several lines within the width (minus padding). */
202 wrap?: boolean;
203 align?: "center" | "left";
204 /** Horizontal padding, in CSS pixels (used by wrapping and left alignment). Default 0. */
205 padding?: number;
206 /** Line height, as a multiple of the font size. Default 1.35. */
207 lineHeight?: number;
208}
209
210function wrapLines(ctx: CanvasRenderingContext2D, text: string, maxWidth: number) {
211 const lines: string[] = [];
212 let line = "";
213 for (const word of text.split(/\s+/)) {
214 const candidate = line ? `${line} ${word}` : word;
215 if (line && ctx.measureText(candidate).width > maxWidth) {
216 lines.push(line);
217 line = word;
218 } else {
219 line = candidate;
220 }
221 }
222 if (line) lines.push(line);
223 return lines;
224}
225
226function drawLabel(canvas: HTMLCanvasElement, o: LabelOptions) {
227 // Drawn at 2× (or the screen's ratio) so the text stays crisp once mapped on its plane
228 const scale = Math.min(Math.max(window.devicePixelRatio || 1, 2), 3);
229 canvas.width = Math.max(2, Math.ceil(o.width * scale));
230 canvas.height = Math.max(2, Math.ceil(o.height * scale));
231 const ctx = canvas.getContext("2d");
232 if (!ctx) return;
233 ctx.setTransform(scale, 0, 0, scale, 0, 0);
234 ctx.clearRect(0, 0, o.width, o.height);
235 if (o.background) {
236 ctx.fillStyle = o.background;
237 ctx.fillRect(0, 0, o.width, o.height);
238 }
239
240 const family = pageFontFamily();
241 const size = o.fontSize ?? 15;
242 const weight = o.fontWeight ?? 600;
243 ctx.fillStyle = o.color;
244 ctx.textBaseline = "middle";
245 ctx.textAlign = "center";
246
247 const padding = o.padding ?? 0;
248 const left = o.align === "left";
249 ctx.textAlign = left ? "left" : "center";
250 const x = left ? padding : o.width / 2;
251
252 let text = o.text;
253 if (o.icon) text = `${o.icon} ${text}`;
254 ctx.font = `${weight} ${size}px ${family}`;
255
256 if (o.wrap) {
257 const step = size * (o.lineHeight ?? 1.35);
258 const lines = wrapLines(ctx, text, o.width - padding * 2);
259 // Only as many lines as fit; the last one kept ends with an ellipsis
260 const maxLines = Math.max(1, Math.floor(o.height / step));
261 if (lines.length > maxLines) {
262 lines.length = maxLines;
263 let last = lines[maxLines - 1];
264 while (last && ctx.measureText(`${last}…`).width > o.width - padding * 2) last = last.slice(0, -1);
265 lines[maxLines - 1] = `${last.trimEnd()}…`;
266 }
267 const top = o.height / 2 - ((lines.length - 1) * step) / 2;
268 lines.forEach((line, i) => ctx.fillText(line, x, top + i * step));
269 return;
270 }
271
272 const mainY = o.subtext ? o.height * 0.4 : o.height / 2;
273 ctx.fillText(text, x, mainY);
274
275 if (o.subtext) {
276 ctx.globalAlpha = 0.7;
277 ctx.font = `500 ${Math.round(size * 0.72)}px ${family}`;
278 ctx.fillText(o.subtext, x, o.height * 0.7);
279 ctx.globalAlpha = 1;
280 }
281}
282
283/**
284 * Text drawn into a CanvasTexture, in the page's own font: no font file to download (unlike drei's
285 * <Text>). Redrawn once web fonts finish loading; disposed on unmount.
286 */
287function useLabelTexture(options: LabelOptions) {
288 const key = JSON.stringify(options);
289 const [fontsVersion, setFontsVersion] = useState(0);
290 useEffect(() => {
291 let alive = true;
292 document.fonts?.ready.then(() => {
293 if (alive) setFontsVersion((v) => v + 1);
294 });
295 return () => {
296 alive = false;
297 };
298 }, []);
299
300 const texture = useMemo(() => {
301 const t = new THREE.CanvasTexture(document.createElement("canvas"));
302 t.colorSpace = THREE.SRGBColorSpace;
303 t.anisotropy = 4;
304 return t;
305 }, []);
306
307 useLayoutEffect(() => {
308 drawLabel(texture.image as HTMLCanvasElement, JSON.parse(key) as LabelOptions);
309 texture.needsUpdate = true;
310 }, [texture, key, fontsVersion]);
311
312 useEffect(() => () => texture.dispose(), [texture]);
313 return texture;
314}
315
316/** Rounded-rectangle outline centered on the origin (radius clamped to a pill). */
317function roundedRectShape(width: number, height: number, radius: number) {
318 const r = Math.min(radius, width / 2, height / 2);
319 const x = -width / 2;
320 const y = -height / 2;
321 const shape = new THREE.Shape();
322 shape.moveTo(x + r, y);
323 shape.lineTo(x + width - r, y);
324 shape.quadraticCurveTo(x + width, y, x + width, y + r);
325 shape.lineTo(x + width, y + height - r);
326 shape.quadraticCurveTo(x + width, y + height, x + width - r, y + height);
327 shape.lineTo(x + r, y + height);
328 shape.quadraticCurveTo(x, y + height, x, y + height - r);
329 shape.lineTo(x, y + r);
330 shape.quadraticCurveTo(x, y, x + r, y);
331 return shape;
332}
333
334/** Bevelled, extruded rounded rectangle, centered on the origin (front face at +depth/2 + bevel). */
335function createBevelledSlab(width: number, height: number, radius: number, depth: number, bevel: number) {
336 const geometry = new THREE.ExtrudeGeometry(roundedRectShape(width - bevel * 2, height - bevel * 2, Math.max(0, radius - bevel)), {
337 depth,
338 bevelEnabled: true,
339 bevelThickness: bevel,
340 bevelSize: bevel,
341 bevelSegments: 6,
342 curveSegments: 24,
343 });
344 geometry.translate(0, 0, -depth / 2);
345 return geometry;
346}
347
348interface Spring {
349 value: number;
350 velocity: number;
351}
352
353/** Damped spring step: overshoots a little, then settles. */
354function stepSpring(spring: Spring, target: number, stiffness: number, damping: number, dt: number) {
355 spring.velocity += (target - spring.value) * stiffness * dt;
356 spring.velocity *= Math.exp(-damping * dt);
357 spring.value += spring.velocity * dt;
358 return spring.value;
359}
360
361/** Fills the positioned parent. */
362const FILL: CSSProperties = { position: "absolute", top: 0, left: 0, width: "100%", height: "100%" };
363
364/** Camera field of view used with PixelPerspective (1 world unit = 1 CSS pixel on z = 0). */
365const NAV_FOV = 30;
366
367interface NavCanvasProps extends Omit<CanvasProps, "children" | "style" | "gl" | "frameloop">, Pick<PerformanceProps, "pauseWhenOffscreen" | "lowPowerMode"> {
368 children: ReactNode;
369}
370
371/**
372 * Click-through canvas for the navbars: the 3D draws the material (glass, metal, prisms…) while real
373 * HTML buttons on top carry the labels, the clicks, the keyboard focus and the screen reader. Pauses
374 * while scrolled out of view; R3F disposes the renderer and its WebGL context on unmount.
375 */
376function NavCanvas({ children, dpr, pauseWhenOffscreen = DEFAULT_3D_PROPS.pauseWhenOffscreen, lowPowerMode = DEFAULT_3D_PROPS.lowPowerMode, ...canvasProps }: NavCanvasProps) {
377 const ref = useRef<HTMLDivElement>(null);
378 const [inView, setInView] = useState(true);
379 useEffect(() => {
380 const el = ref.current;
381 if (!el) return undefined;
382 const observer = new IntersectionObserver(([entry]) => setInView(entry.isIntersecting));
383 observer.observe(el);
384 return () => observer.disconnect();
385 }, []);
386 return (
387 <div ref={ref} aria-hidden="true" style={{ ...FILL, pointerEvents: "none" }}>
388 <Canvas
389 dpr={lowPowerMode ? 1 : dpr ?? [1, typeof window === "undefined" ? 2 : Math.min(window.devicePixelRatio || 1, 2)]}
390 frameloop={inView || !pauseWhenOffscreen ? "always" : "never"}
391 gl={{ antialias: true, alpha: true, powerPreference: "high-performance" }}
392 style={{ pointerEvents: "none" }}
393 {...canvasProps}
394 >
395 <PixelPerspective fov={NAV_FOV} />
396 {children}
397 </Canvas>
398 </div>
399 );
400}
401
402/** Size of an element in CSS pixels, kept in sync with a ResizeObserver. */
403function useElementSize(ref: RefObject<HTMLElement | null>) {
404 const [size, setSize] = useState({ width: 0, height: 0 });
405 useLayoutEffect(() => {
406 const el = ref.current;
407 if (!el) return undefined;
408 const sync = () => setSize({ width: el.clientWidth, height: el.clientHeight });
409 sync();
410 const observer = new ResizeObserver(sync);
411 observer.observe(el);
412 return () => observer.disconnect();
413 }, [ref]);
414 return size;
415}
416
417interface ItemBox {
418 /** Center of the item, relative to the center of the container (y up, like the 3D). */
419 x: number;
420 y: number;
421 width: number;
422 height: number;
423}
424
425/**
426 * Boxes of the HTML items, relative to the container's center: the 3D scene (1 unit = 1 px, origin at
427 * the center) draws exactly under them. Measured again when the container or the items resize.
428 */
429function useItemBoxes(container: RefObject<HTMLElement | null>, items: RefObject<(HTMLElement | null)[]>, key: unknown) {
430 const [boxes, setBoxes] = useState<ItemBox[]>([]);
431 useLayoutEffect(() => {
432 const root = container.current;
433 if (!root) return undefined;
434 const measure = () => {
435 const r = root.getBoundingClientRect();
436 const cx = r.left + r.width / 2;
437 const cy = r.top + r.height / 2;
438 setBoxes(
439 (items.current ?? []).map((el) => {
440 if (!el) return { x: 0, y: 0, width: 0, height: 0 };
441 // offset* ignore the CSS tilt applied to the layer: the boxes stay flat
442 const box = { left: el.offsetLeft, top: el.offsetTop, width: el.offsetWidth, height: el.offsetHeight };
443 let parent = el.offsetParent as HTMLElement | null;
444 while (parent && parent !== root && root.contains(parent)) {
445 box.left += parent.offsetLeft;
446 box.top += parent.offsetTop;
447 parent = parent.offsetParent as HTMLElement | null;
448 }
449 return { x: r.left + box.left + box.width / 2 - cx, y: cy - (r.top + box.top + box.height / 2), width: box.width, height: box.height };
450 })
451 );
452 };
453 measure();
454 const observer = new ResizeObserver(measure);
455 observer.observe(root);
456 (items.current ?? []).forEach((el) => el && observer.observe(el));
457 document.fonts?.ready.then(measure);
458 return () => observer.disconnect();
459 }, [container, items, key]);
460 return boxes;
461}
462
463function usePrefersReducedMotion() {
464 const [reduced, setReduced] = useState(false);
465 useEffect(() => {
466 const query = window.matchMedia("(prefers-reduced-motion: reduce)");
467 const sync = () => setReduced(query.matches);
468 sync();
469 query.addEventListener("change", sync);
470 return () => query.removeEventListener("change", sync);
471 }, []);
472 return reduced;
473}
474
475/** Resets the default button look, keeps a visible focus ring for keyboard users. */
476const BUTTON_RESET: CSSProperties = {
477 appearance: "none",
478 background: "transparent",
479 border: 0,
480 margin: 0,
481 padding: 0,
482 font: "inherit",
483 color: "inherit",
484 cursor: "pointer",
485 WebkitTapHighlightColor: "transparent",
486};
487
488/** CSS for the focus ring of the HTML items (scoped by a class name). */
489const focusRing = (className: string, color: string) =>
490 `.${className}:focus-visible{outline:2px solid ${color};outline-offset:3px;border-radius:999px}`;
491
492export interface StudioPrismNavbarProps extends Pick<MaterialProps, "primaryColor">, Pick<PerformanceProps, "pauseWhenOffscreen" | "lowPowerMode"> {
493 items: { id: string; label: string; sublabel?: string }[];
494 activeId: string;
495 onSelect: (id: string) => void;
496 /** Tint of the quartz prisms. Default "#1f1b2e". */
497 primaryColor?: string;
498 /** @deprecated Use `primaryColor`. */
499 prismColor?: string;
500 /** Color of the face revealed on hover, and of the active marker. Default "#c084fc". */
501 hoverColor?: string;
502}
503
504const H = 52; // square cross-section: half a turn shows the opposite face
505const BEVEL = 6;
506const FONT = 14;
507
508interface Wave {
509 at: number; // time it reaches this prism
510 strength: number;
511}
512
513interface PrismProps {
514 box: ItemBox;
515 label: string;
516 sublabel: string;
517 index: number;
518 active: boolean;
519 hovered: RefObject<number>;
520 waves: RefObject<Wave[][]>;
521 material: THREE.MeshPhysicalMaterial;
522 hoverColor: string;
523 reducedMotion: boolean;
524}
525
526const Prism = memo(function Prism({ box, label, sublabel, index, active, hovered, waves, material, hoverColor, reducedMotion }: PrismProps) {
527 const group = useRef<THREE.Group>(null);
528 const marker = useRef<THREE.Mesh>(null);
529 const turn = useRef<Spring>({ value: 0, velocity: 0 });
530 const lift = useRef<Spring>({ value: 0, velocity: 0 });
531 const width = box.width;
532
533 const geometry = useMemo(() => createBevelledSlab(width, H, 10, H - BEVEL * 2, BEVEL), [width]);
534 const plane = useMemo(() => new THREE.PlaneGeometry(width - 8, H - 8), [width]);
535 useEffect(() => () => geometry.dispose(), [geometry]);
536 useEffect(() => () => plane.dispose(), [plane]);
537
538 // Front: the label on the quartz. Back: the sublabel on the accent color.
539 const front = useLabelTexture({ text: label, width: width - 8, height: H - 8, color: "#ffffff", fontSize: FONT, fontWeight: 600 });
540 const back = useLabelTexture({ text: sublabel, width: width - 8, height: H - 8, color: "#0b0b10", background: hoverColor, fontSize: FONT - 1, fontWeight: 700 });
541 const frontMat = useMemo(() => new THREE.MeshBasicMaterial({ transparent: true, toneMapped: false }), []);
542 const backMat = useMemo(() => new THREE.MeshBasicMaterial({ toneMapped: false }), []);
543 useEffect(() => {
544 frontMat.map = front;
545 backMat.map = back;
546 frontMat.needsUpdate = backMat.needsUpdate = true;
547 }, [frontMat, backMat, front, back]);
548 useEffect(
549 () => () => {
550 frontMat.dispose();
551 backMat.dispose();
552 },
553 [frontMat, backMat]
554 );
555
556 useFrame((state, delta) => {
557 const dt = Math.min(delta, 1 / 30);
558 const time = state.clock.elapsedTime;
559 const g = group.current;
560 if (!g) return;
561 // Click waves: a kick of spin and depth when the wave reaches this prism
562 const queue = waves.current?.[index];
563 if (queue) {
564 for (let i = queue.length - 1; i >= 0; i--) {
565 if (time >= queue[i].at) {
566 turn.current.velocity += queue[i].strength * (reducedMotion ? 0.2 : 6);
567 lift.current.velocity += queue[i].strength * 160;
568 queue.splice(i, 1);
569 }
570 }
571 }
572 const flipped = hovered.current === index;
573 stepSpring(turn.current, flipped ? Math.PI : 0, 90, 9, dt);
574 stepSpring(lift.current, active ? 10 : flipped ? 6 : 0, 140, 12, dt);
575 g.rotation.x = turn.current.value;
576 g.position.set(box.x, box.y, lift.current.value);
577 if (marker.current) {
578 marker.current.position.set(box.x, box.y - H / 2 - 8, 0);
579 const m = marker.current.material as THREE.MeshBasicMaterial;
580 m.opacity = THREE.MathUtils.damp(m.opacity, active ? 1 : 0, 8, dt);
581 }
582 });
583
584 return (
585 <>
586 <group ref={group}>
587 <mesh geometry={geometry} material={material} />
588 <mesh geometry={plane} material={frontMat} position={[0, 0, H / 2 + 0.6]} />
589 {/* Back face, upside down so it reads upright once the prism has turned over */}
590 <mesh geometry={plane} material={backMat} position={[0, 0, -H / 2 - 0.6]} rotation={[Math.PI, 0, 0]} />
591 </group>
592 <mesh ref={marker} scale={[Math.max(12, width * 0.35), 3, 1]}>
593 <planeGeometry />
594 <meshBasicMaterial color={hoverColor} transparent opacity={0} toneMapped={false} />
595 </mesh>
596 </>
597 );
598});
599
600/**
601 * Creative-studio navbar: every link is a bevelled quartz prism. Hover (or focus) one and it flips
602 * over with inertia to reveal its second face — the sublabel on an accent color; click and a wave of
603 * light and motion ripples through the neighboring prisms. The active link floats forward over a glowing
604 * marker. Labels are drawn on the faces; real buttons over them handle clicks, focus and screen readers.
605 */
606function StudioPrismNavbar3D({ items, activeId, onSelect, primaryColor, prismColor = primaryColor ?? "#1f1b2e", hoverColor = "#c084fc", pauseWhenOffscreen, lowPowerMode }: StudioPrismNavbarProps) {
607 const reducedMotion = usePrefersReducedMotion();
608 const root = useRef<HTMLDivElement>(null);
609 const itemRefs = useRef<(HTMLButtonElement | null)[]>([]);
610 const hovered = useRef(-1);
611 const waves = useRef<Wave[][]>([]);
612 const clock = useRef<THREE.Clock | null>(null);
613 const size = useElementSize(root);
614 const labelsKey = items.map((i) => `${i.label}|${i.sublabel ?? ""}`).join("\n");
615 const boxes = useItemBoxes(root, itemRefs, `${labelsKey}|${size.width}`);
616 const activeIndex = items.findIndex((i) => i.id === activeId);
617
618 const material = useMemo(
619 () => new THREE.MeshPhysicalMaterial({ roughness: 0.12, metalness: 0.15, clearcoat: 1, clearcoatRoughness: 0.05, envMapIntensity: 1.5, sheen: 0.4 }),
620 []
621 );
622 useEffect(() => {
623 material.color.set(prismColor);
624 material.sheenColor.set(hoverColor);
625 }, [material, prismColor, hoverColor]);
626 useEffect(() => () => material.dispose(), [material]);
627
628 // A click sends a wave outward: each prism gets its kick later the farther it is
629 const ripple = (from: number) => {
630 const now = clock.current?.elapsedTime ?? 0;
631 waves.current = items.map((_, j) => {
632 const d = Math.abs(j - from);
633 const queue = waves.current[j] ?? [];
634 return d === 0 ? queue : [...queue, { at: now + d * 0.09, strength: 0.9 / d }];
635 });
636 };
637
638 return (
639 <div ref={root} style={FILL}>
640 <style>{focusRing("prism-nav-item", hoverColor)}</style>
641 <NavCanvas pauseWhenOffscreen={pauseWhenOffscreen} lowPowerMode={lowPowerMode}>
642 <ClockRef target={clock} />
643 <ambientLight intensity={0.5} />
644 <directionalLight position={[200, 300, 400]} intensity={1.6} />
645 <Environment resolution={128}>
646 <Lightformer form="rect" intensity={2.5} position={[0, 4, 4]} rotation-x={Math.PI / 2} scale={[12, 2, 1]} />
647 <Lightformer form="rect" intensity={1.5} position={[-6, 0, 2]} rotation-y={Math.PI / 2} scale={[2, 6, 1]} color={hoverColor} />
648 <Lightformer form="rect" intensity={1} position={[6, -2, 2]} rotation-y={-Math.PI / 2} scale={[2, 6, 1]} />
649 </Environment>
650 {boxes.map((box, i) =>
651 items[i] && box.width > 0 ? (
652 <Prism
653 key={items[i].id}
654 box={box}
655 label={items[i].label}
656 sublabel={items[i].sublabel ?? items[i].label}
657 index={i}
658 active={i === activeIndex}
659 hovered={hovered}
660 waves={waves}
661 material={material}
662 hoverColor={hoverColor}
663 reducedMotion={reducedMotion}
664 />
665 ) : null
666 )}
667 </NavCanvas>
668 {/* Real buttons, laid out like the prisms: the 3D is drawn exactly under them */}
669 <nav aria-label="Main" style={{ ...FILL, display: "flex", alignItems: "center", justifyContent: "center", flexWrap: "wrap", gap: 10, padding: "0 12px" }}>
670 {items.map((item, i) => (
671 <button
672 key={item.id}
673 ref={(el) => {
674 itemRefs.current[i] = el;
675 }}
676 type="button"
677 className="prism-nav-item"
678 aria-current={i === activeIndex ? "page" : undefined}
679 aria-label={item.sublabel ? `${item.label} — ${item.sublabel}` : item.label}
680 onClick={() => {
681 onSelect(item.id);
682 ripple(i);
683 }}
684 onPointerEnter={() => (hovered.current = i)}
685 onPointerLeave={() => {
686 if (hovered.current === i) hovered.current = -1;
687 }}
688 onFocus={() => (hovered.current = i)}
689 onBlur={() => (hovered.current = -1)}
690 style={{
691 ...BUTTON_RESET,
692 height: H,
693 padding: "0 24px",
694 fontSize: FONT,
695 fontWeight: 600,
696 whiteSpace: "nowrap",
697 color: "transparent", // the label is drawn on the prism; the text keeps the width
698 }}
699 >
700 {(item.sublabel?.length ?? 0) > item.label.length ? item.sublabel : item.label}
701 </button>
702 ))}
703 </nav>
704 </div>
705 );
706}
707
708/** Exposes the R3F clock to the HTML handlers (click waves are timed on it). */
709function ClockRef({ target }: { target: RefObject<THREE.Clock | null> }) {
710 useFrame((state) => {
711 target.current = state.clock;
712 });
713 return null;
714}
715
716export default memo(StudioPrismNavbar3D);
03

Drop it in a page

Updated live with the settings above.

app/page.tsx
1"use client";
2
3import { useState } from "react";
4import StudioPrismNavbar3D from "@/components/StudioPrismNavbar3D";
5
6export default function Section() {
7 const [activeId, setActiveId] = useState("work");
8
9 return (
10 // The component fills this box: give it a position and a height
11 <div style={{ position: "relative", width: "100%", height: "140px" }}>
12 <StudioPrismNavbar3D
13 items={[
14 { id: "work", label: "Work", sublabel: "12 cases" },
15 { id: "studio", label: "Studio", sublabel: "Paris" },
16 { id: "lab", label: "Lab", sublabel: "R&D" },
17 { id: "contact", label: "Contact", sublabel: "Say hi" },
18 ]}
19 primaryColor="#1f1b2e"
20 hoverColor="#c084fc"
21 activeId={activeId}
22 onSelect={setActiveId}
23 />
24 </div>
25 );
26}
Next componentHolo Burger Menu→