Loading…
← All components

Navigation · Navigation

Glass Navbar

A real glass navbar refracting a glowing indicator that slides to the active item.

<GlassmorphismNavbar3D />Live

Customize

Accent#8b5cf6

Installation

Use it in your project

Or skip the copy-paste

One command: writes the file and installs the dependencies.

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

components/GlassmorphismNavbar3D.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, type ThreeEvent } from "@react-three/fiber";
16import { Environment, Lightformer, MeshTransmissionMaterial } 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/** Inline widget: fills its positioned parent and receives pointer events. */
166const FILL_STYLE: CSSProperties = { position: "absolute", top: 0, left: 0, width: "100%", height: "100%" };
167
168/** Cursor overlay: covers the viewport, above everything, never intercepts the page's events. */
169const OVERLAY_STYLE: CSSProperties = {
170 position: "fixed",
171 top: 0,
172 left: 0,
173 width: "100%",
174 height: "100%",
175 pointerEvents: "none",
176 zIndex: 9999,
177};
178
179/** Visually hidden but reachable by keyboard and screen readers. */
180const SR_ONLY: CSSProperties = {
181 position: "absolute",
182 width: 1,
183 height: 1,
184 padding: 0,
185 margin: -1,
186 overflow: "hidden",
187 clip: "rect(0, 0, 0, 0)",
188 whiteSpace: "nowrap",
189 border: 0,
190};
191
192interface UICanvasProps extends Omit<CanvasProps, "children" | "style" | "gl">, Pick<PerformanceProps, "pauseWhenOffscreen" | "lowPowerMode"> {
193 children: ReactNode;
194 /** Full-viewport, click-through overlay (cursors) instead of an inline widget. */
195 overlay?: boolean;
196}
197
198/**
199 * Ready-to-use <Canvas>: pauses its render loop while scrolled out of view (pauseWhenOffscreen), pixel
200 * ratio 1 in lowPowerMode; R3F disposes the renderer and its WebGL context on unmount.
201 */
202function UICanvas({ children, overlay = false, dpr = [1, 2], pauseWhenOffscreen = DEFAULT_3D_PROPS.pauseWhenOffscreen, lowPowerMode = DEFAULT_3D_PROPS.lowPowerMode, ...canvasProps }: UICanvasProps) {
203 const containerRef = useRef<HTMLDivElement>(null);
204 // In view at first: the first frame is always drawn before the loop can be paused
205 const [inView, setInView] = useState(true);
206 useEffect(() => {
207 const el = containerRef.current;
208 if (!el || !pauseWhenOffscreen) return undefined;
209 const observer = new IntersectionObserver(([entry]) => setInView(entry.isIntersecting));
210 observer.observe(el);
211 return () => observer.disconnect();
212 }, [pauseWhenOffscreen]);
213 return (
214 <div ref={containerRef} style={overlay ? OVERLAY_STYLE : FILL_STYLE} aria-hidden="true">
215 <Canvas
216 dpr={lowPowerMode ? 1 : dpr}
217 frameloop={inView || !pauseWhenOffscreen ? "always" : "never"}
218 gl={{ antialias: true, alpha: true, powerPreference: "high-performance" }}
219 style={overlay ? { pointerEvents: "none" } : undefined}
220 {...canvasProps}
221 >
222 {children}
223 </Canvas>
224 </div>
225 );
226}
227
228/**
229 * Perspective camera placed so that 1 world unit = 1 CSS pixel on the z = 0 plane: widgets are laid
230 * out in pixels like the rest of the page, and still get real depth (presses, tilts, shadows).
231 */
232function PixelPerspective({ fov = 30 }: { fov?: number }) {
233 const camera = useThree((state) => state.camera) as THREE.PerspectiveCamera;
234 const size = useThree((state) => state.size);
235 useLayoutEffect(() => {
236 camera.fov = fov;
237 camera.near = 1;
238 camera.far = 20000;
239 camera.position.set(0, 0, size.height / 2 / Math.tan(THREE.MathUtils.degToRad(fov / 2)));
240 camera.lookAt(0, 0, 0);
241 camera.updateProjectionMatrix();
242 }, [camera, size, fov]);
243 return null;
244}
245
246function pageFontFamily() {
247 if (typeof document === "undefined") return "sans-serif";
248 return getComputedStyle(document.body).fontFamily || "sans-serif";
249}
250
251let measureContext: CanvasRenderingContext2D | null = null;
252
253/** Width of a label in CSS pixels, in the page's font. */
254function measureLabel(text: string, fontSize: number, fontWeight = 600) {
255 if (typeof document === "undefined") return text.length * fontSize * 0.6;
256 measureContext ??= document.createElement("canvas").getContext("2d");
257 if (!measureContext) return text.length * fontSize * 0.6;
258 measureContext.font = `${fontWeight} ${fontSize}px ${pageFontFamily()}`;
259 return measureContext.measureText(text).width;
260}
261
262interface LabelOptions {
263 text: string;
264 /** Second, smaller line under the text. */
265 subtext?: string;
266 /** Glyph drawn before the text (emoji, arrow, symbol…). */
267 icon?: string;
268 width: number;
269 height: number;
270 color: string;
271 /** Face color; transparent when omitted. */
272 background?: string;
273 fontSize?: number;
274 fontWeight?: number;
275 /** Wrap the text over several lines within the width (minus padding). */
276 wrap?: boolean;
277 align?: "center" | "left";
278 /** Horizontal padding, in CSS pixels (used by wrapping and left alignment). Default 0. */
279 padding?: number;
280 /** Line height, as a multiple of the font size. Default 1.35. */
281 lineHeight?: number;
282}
283
284function wrapLines(ctx: CanvasRenderingContext2D, text: string, maxWidth: number) {
285 const lines: string[] = [];
286 let line = "";
287 for (const word of text.split(/\s+/)) {
288 const candidate = line ? `${line} ${word}` : word;
289 if (line && ctx.measureText(candidate).width > maxWidth) {
290 lines.push(line);
291 line = word;
292 } else {
293 line = candidate;
294 }
295 }
296 if (line) lines.push(line);
297 return lines;
298}
299
300function drawLabel(canvas: HTMLCanvasElement, o: LabelOptions) {
301 // Drawn at 2× (or the screen's ratio) so the text stays crisp once mapped on its plane
302 const scale = Math.min(Math.max(window.devicePixelRatio || 1, 2), 3);
303 canvas.width = Math.max(2, Math.ceil(o.width * scale));
304 canvas.height = Math.max(2, Math.ceil(o.height * scale));
305 const ctx = canvas.getContext("2d");
306 if (!ctx) return;
307 ctx.setTransform(scale, 0, 0, scale, 0, 0);
308 ctx.clearRect(0, 0, o.width, o.height);
309 if (o.background) {
310 ctx.fillStyle = o.background;
311 ctx.fillRect(0, 0, o.width, o.height);
312 }
313
314 const family = pageFontFamily();
315 const size = o.fontSize ?? 15;
316 const weight = o.fontWeight ?? 600;
317 ctx.fillStyle = o.color;
318 ctx.textBaseline = "middle";
319 ctx.textAlign = "center";
320
321 const padding = o.padding ?? 0;
322 const left = o.align === "left";
323 ctx.textAlign = left ? "left" : "center";
324 const x = left ? padding : o.width / 2;
325
326 let text = o.text;
327 if (o.icon) text = `${o.icon} ${text}`;
328 ctx.font = `${weight} ${size}px ${family}`;
329
330 if (o.wrap) {
331 const step = size * (o.lineHeight ?? 1.35);
332 const lines = wrapLines(ctx, text, o.width - padding * 2);
333 // Only as many lines as fit; the last one kept ends with an ellipsis
334 const maxLines = Math.max(1, Math.floor(o.height / step));
335 if (lines.length > maxLines) {
336 lines.length = maxLines;
337 let last = lines[maxLines - 1];
338 while (last && ctx.measureText(`${last}…`).width > o.width - padding * 2) last = last.slice(0, -1);
339 lines[maxLines - 1] = `${last.trimEnd()}…`;
340 }
341 const top = o.height / 2 - ((lines.length - 1) * step) / 2;
342 lines.forEach((line, i) => ctx.fillText(line, x, top + i * step));
343 return;
344 }
345
346 const mainY = o.subtext ? o.height * 0.4 : o.height / 2;
347 ctx.fillText(text, x, mainY);
348
349 if (o.subtext) {
350 ctx.globalAlpha = 0.7;
351 ctx.font = `500 ${Math.round(size * 0.72)}px ${family}`;
352 ctx.fillText(o.subtext, x, o.height * 0.7);
353 ctx.globalAlpha = 1;
354 }
355}
356
357/**
358 * Text drawn into a CanvasTexture, in the page's own font: no font file to download (unlike drei's
359 * <Text>). Redrawn once web fonts finish loading; disposed on unmount.
360 */
361function useLabelTexture(options: LabelOptions) {
362 const key = JSON.stringify(options);
363 const [fontsVersion, setFontsVersion] = useState(0);
364 useEffect(() => {
365 let alive = true;
366 document.fonts?.ready.then(() => {
367 if (alive) setFontsVersion((v) => v + 1);
368 });
369 return () => {
370 alive = false;
371 };
372 }, []);
373
374 const texture = useMemo(() => {
375 const t = new THREE.CanvasTexture(document.createElement("canvas"));
376 t.colorSpace = THREE.SRGBColorSpace;
377 t.anisotropy = 4;
378 return t;
379 }, []);
380
381 useLayoutEffect(() => {
382 drawLabel(texture.image as HTMLCanvasElement, JSON.parse(key) as LabelOptions);
383 texture.needsUpdate = true;
384 }, [texture, key, fontsVersion]);
385
386 useEffect(() => () => texture.dispose(), [texture]);
387 return texture;
388}
389
390/** Rounded-rectangle outline centered on the origin (radius clamped to a pill). */
391function roundedRectShape(width: number, height: number, radius: number) {
392 const r = Math.min(radius, width / 2, height / 2);
393 const x = -width / 2;
394 const y = -height / 2;
395 const shape = new THREE.Shape();
396 shape.moveTo(x + r, y);
397 shape.lineTo(x + width - r, y);
398 shape.quadraticCurveTo(x + width, y, x + width, y + r);
399 shape.lineTo(x + width, y + height - r);
400 shape.quadraticCurveTo(x + width, y + height, x + width - r, y + height);
401 shape.lineTo(x + r, y + height);
402 shape.quadraticCurveTo(x, y + height, x, y + height - r);
403 shape.lineTo(x, y + r);
404 shape.quadraticCurveTo(x, y, x + r, y);
405 return shape;
406}
407
408/** Bevelled, extruded rounded rectangle, centered on the origin (front face at +depth/2 + bevel). */
409function createBevelledSlab(width: number, height: number, radius: number, depth: number, bevel: number) {
410 const geometry = new THREE.ExtrudeGeometry(roundedRectShape(width - bevel * 2, height - bevel * 2, Math.max(0, radius - bevel)), {
411 depth,
412 bevelEnabled: true,
413 bevelThickness: bevel,
414 bevelSize: bevel,
415 bevelSegments: 6,
416 curveSegments: 24,
417 });
418 geometry.translate(0, 0, -depth / 2);
419 return geometry;
420}
421
422interface Spring {
423 value: number;
424 velocity: number;
425}
426
427/** Damped spring step: overshoots a little, then settles. */
428function stepSpring(spring: Spring, target: number, stiffness: number, damping: number, dt: number) {
429 spring.velocity += (target - spring.value) * stiffness * dt;
430 spring.velocity *= Math.exp(-damping * dt);
431 spring.value += spring.velocity * dt;
432 return spring.value;
433}
434
435export interface GlassNavItem {
436 id: string;
437 label: string;
438}
439
440export interface GlassNavbarProps extends Pick<MaterialProps, "emissiveColor" | "transmission">, Pick<PerformanceProps, "pauseWhenOffscreen" | "lowPowerMode"> {
441 items: GlassNavItem[];
442 activeId: string;
443 onSelect: (id: string) => void;
444 /** Color of the glowing indicator behind the glass. */
445 emissiveColor?: string;
446 /** @deprecated Use `emissiveColor`. */
447 accentColor?: string;
448 /** 0–1. Default 1. */
449 transmission?: number;
450}
451
452const BAR_HEIGHT = 58;
453const BAR_DEPTH = 14;
454const BEVEL = 7;
455const BAR_PAD = 8;
456const ITEM_PAD = 22;
457const FONT_SIZE = 14;
458const FRONT_Z = BAR_DEPTH / 2 + BEVEL + 1; // labels sit just in front of the glass, crisp and unrefracted
459const PILL_RADIUS = (BAR_HEIGHT - 20) / 2;
460
461interface NavLabelProps {
462 label: string;
463 index: number;
464 width: number;
465 x: number;
466 active: boolean;
467 hovered: RefObject<number>;
468 geometry: THREE.PlaneGeometry;
469}
470
471function NavLabel({ label, index, width, x, active, hovered, geometry }: NavLabelProps) {
472 const texture = useLabelTexture({ text: label, width, height: BAR_HEIGHT, color: "#ffffff", fontSize: FONT_SIZE, fontWeight: 600 });
473 const material = useMemo(() => new THREE.MeshBasicMaterial({ transparent: true, depthWrite: false, toneMapped: false }), []);
474 useEffect(() => {
475 material.map = texture;
476 material.needsUpdate = true;
477 }, [material, texture]);
478 useEffect(() => () => material.dispose(), [material]);
479 useFrame((_, delta) => {
480 material.opacity = THREE.MathUtils.damp(material.opacity, active ? 1 : hovered.current === index ? 0.85 : 0.55, 10, delta);
481 });
482 return <mesh geometry={geometry} material={material} position={[x, 0, FRONT_Z]} scale={[width, BAR_HEIGHT, 1]} />;
483}
484
485/**
486 * The glass renders the scene into its own buffer to refract it. The labels sit in front of the glass:
487 * caught in that buffer they would show up doubled through it. They are hidden by a frame callback
488 * registered before the glass's (this component is placed before it) and shown again by one registered
489 * after it (placed after the labels).
490 */
491function SetVisible({ target, visible }: { target: RefObject<THREE.Object3D | null>; visible: boolean }) {
492 useFrame(() => {
493 if (target.current) target.current.visible = visible;
494 });
495 return null;
496}
497
498/** The navbar's 3D content, for an existing R3F scene (1 world unit = 1 CSS pixel, see PixelPerspective). */
499export const GlassNavbarScene = memo(function GlassNavbarScene({
500 items,
501 activeId,
502 onSelect,
503 emissiveColor,
504 accentColor = emissiveColor ?? "#8b5cf6",
505 transmission = 1,
506}: GlassNavbarProps) {
507 const gl = useThree((state) => state.gl);
508 const hovered = useRef(-1);
509 const labelsRef = useRef<THREE.Group>(null);
510 const glassBackground = useMemo(() => new THREE.Color("#0b0b10"), []);
511 const pill = useRef({ x: { value: 0, velocity: 0 } as Spring, length: { value: 0, velocity: 0 } as Spring, started: false });
512 const pillGroup = useRef<THREE.Group>(null);
513 const leftCap = useRef<THREE.Mesh>(null);
514 const rightCap = useRef<THREE.Mesh>(null);
515 const body = useRef<THREE.Mesh>(null);
516 const glow = useRef<THREE.Mesh>(null);
517
518 // Layout in pixels: each item is as wide as its label plus padding
519 const labelsKey = items.map((item) => item.label).join("\n");
520 const layout = useMemo(() => {
521 const widths = labelsKey.split("\n").map((label) => Math.ceil(measureLabel(label, FONT_SIZE, 600)) + ITEM_PAD * 2);
522 const total = widths.reduce((sum, w) => sum + w, 0) + BAR_PAD * 2;
523 let cursor = -total / 2 + BAR_PAD;
524 const centers = widths.map((w) => {
525 const c = cursor + w / 2;
526 cursor += w;
527 return c;
528 });
529 return { widths, centers, total };
530 }, [labelsKey]);
531
532 const barGeometry = useMemo(() => createBevelledSlab(layout.total, BAR_HEIGHT, BAR_HEIGHT / 2, BAR_DEPTH, BEVEL), [layout.total]);
533 const planeGeometry = useMemo(() => new THREE.PlaneGeometry(1, 1), []);
534 const capGeometry = useMemo(() => new THREE.SphereGeometry(PILL_RADIUS, 32, 16), []);
535 const bodyGeometry = useMemo(() => {
536 // Unit-length cylinder along X: scaled in length only, so the pill never distorts its round ends
537 const g = new THREE.CylinderGeometry(PILL_RADIUS, PILL_RADIUS, 1, 32, 1, true);
538 g.rotateZ(Math.PI / 2);
539 return g;
540 }, []);
541 const pillMaterial = useMemo(() => new THREE.MeshStandardMaterial({ roughness: 0.3, metalness: 0.1, emissiveIntensity: 2.2, toneMapped: false }), []);
542 const glowMaterial = useMemo(
543 () =>
544 new THREE.ShaderMaterial({
545 uniforms: { uColor: { value: new THREE.Color() }, uSize: { value: new THREE.Vector2(1, 1) } },
546 vertexShader: /* glsl */ `
547 varying vec2 vUv;
548 void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }
549 `,
550 fragmentShader: /* glsl */ `
551 uniform vec3 uColor;
552 uniform vec2 uSize;
553 varying vec2 vUv;
554 void main() {
555 // Soft halo around the pill: distance to a rounded rectangle, faded out
556 vec2 p = (vUv - 0.5) * uSize;
557 vec2 b = uSize * 0.5 - vec2(30.0);
558 float r = ${PILL_RADIUS.toFixed(1)};
559 vec2 q = abs(p) - (b - r);
560 float d = length(max(q, 0.0)) + min(max(q.x, q.y), 0.0) - r;
561 float glow = exp(-max(d, 0.0) / 14.0) * 0.9;
562 gl_FragColor = vec4(uColor * glow, glow);
563 #include <colorspace_fragment>
564 }
565 `,
566 transparent: true,
567 depthWrite: false,
568 blending: THREE.AdditiveBlending,
569 }),
570 []
571 );
572 const hitMaterial = useMemo(() => new THREE.MeshBasicMaterial({ transparent: true, opacity: 0, depthWrite: false }), []);
573
574 useEffect(() => {
575 pillMaterial.color.set(accentColor);
576 pillMaterial.emissive.set(accentColor);
577 (glowMaterial.uniforms.uColor.value as THREE.Color).set(accentColor);
578 }, [pillMaterial, glowMaterial, accentColor]);
579 useEffect(() => () => barGeometry.dispose(), [barGeometry]);
580 useEffect(
581 () => () => {
582 planeGeometry.dispose();
583 capGeometry.dispose();
584 bodyGeometry.dispose();
585 pillMaterial.dispose();
586 glowMaterial.dispose();
587 hitMaterial.dispose();
588 },
589 [planeGeometry, capGeometry, bodyGeometry, pillMaterial, glowMaterial, hitMaterial]
590 );
591
592 const activeIndex = Math.max(0, items.findIndex((item) => item.id === activeId));
593
594 useFrame((_, delta) => {
595 const dt = Math.min(delta, 1 / 30);
596 const s = pill.current;
597 const targetX = layout.centers[activeIndex] ?? 0;
598 const targetLength = Math.max(0, (layout.widths[activeIndex] ?? 0) - 10 - PILL_RADIUS * 2);
599 if (!s.started) {
600 s.x.value = targetX;
601 s.length.value = targetLength;
602 s.started = true;
603 }
604 // Hovering another tab draws the indicator a little towards it
605 const h = hovered.current;
606 const lean = h >= 0 && h !== activeIndex ? (layout.centers[h] - targetX) * 0.14 : 0;
607 stepSpring(s.x, targetX + lean, 170, 15, dt);
608 stepSpring(s.length, targetLength, 170, 15, dt);
609
610 // Liquid feel: the pill stretches with its speed and thins a little
611 const stretch = Math.min(Math.abs(s.x.velocity) * 0.06, 40);
612 const length = Math.max(0, s.length.value + stretch);
613 const squash = 1 - Math.min(stretch / 160, 0.18);
614 if (pillGroup.current) {
615 pillGroup.current.position.x = s.x.value;
616 pillGroup.current.scale.set(1, squash, squash);
617 }
618 leftCap.current?.position.set(-length / 2, 0, 0);
619 rightCap.current?.position.set(length / 2, 0, 0);
620 body.current?.scale.set(length || 0.0001, 1, 1);
621 if (glow.current) {
622 const w = length + PILL_RADIUS * 2 + 60;
623 const hgt = PILL_RADIUS * 2 + 60;
624 glow.current.scale.set(w, hgt, 1);
625 (glowMaterial.uniforms.uSize.value as THREE.Vector2).set(w, hgt);
626 }
627 });
628
629 return (
630 <group>
631 {/* Indicator behind the glass: a 3D pill (two caps + a cylinder) and its halo */}
632 <group ref={pillGroup} position={[0, 0, -BAR_DEPTH]}>
633 <mesh ref={glow} geometry={planeGeometry} material={glowMaterial} position={[0, 0, -PILL_RADIUS]} />
634 <mesh ref={leftCap} geometry={capGeometry} material={pillMaterial} />
635 <mesh ref={body} geometry={bodyGeometry} material={pillMaterial} />
636 <mesh ref={rightCap} geometry={capGeometry} material={pillMaterial} />
637 </group>
638
639 <SetVisible target={labelsRef} visible={false} />
640 {/* Frosted glass bar: refracts and blurs the indicator moving behind it */}
641 <mesh geometry={barGeometry}>
642 <MeshTransmissionMaterial
643 transmission={transmission}
644 thickness={30}
645 roughness={0.18}
646 ior={1.3}
647 chromaticAberration={0.06}
648 anisotropicBlur={0.2}
649 distortion={0.12}
650 distortionScale={0.3}
651 temporalDistortion={0.05}
652 samples={6}
653 resolution={512}
654 backside={false}
655 background={glassBackground}
656 />
657 </mesh>
658
659 <group ref={labelsRef}>
660 {items.map((item, i) => (
661 <NavLabel
662 key={item.id}
663 label={item.label}
664 index={i}
665 width={layout.widths[i]}
666 x={layout.centers[i]}
667 active={i === activeIndex}
668 hovered={hovered}
669 geometry={planeGeometry}
670 />
671 ))}
672 </group>
673 <SetVisible target={labelsRef} visible />
674
675 {/* Hit areas: R3F pointer events per tab */}
676 {items.map((item, i) => (
677 <mesh
678 key={`hit-${item.id}`}
679 geometry={planeGeometry}
680 material={hitMaterial}
681 position={[layout.centers[i], 0, FRONT_Z + 1]}
682 scale={[layout.widths[i], BAR_HEIGHT, 1]}
683 onPointerOver={(e: ThreeEvent<PointerEvent>) => {
684 e.stopPropagation();
685 hovered.current = i;
686 gl.domElement.style.cursor = "pointer";
687 }}
688 onPointerOut={() => {
689 if (hovered.current === i) hovered.current = -1;
690 gl.domElement.style.cursor = "";
691 }}
692 onClick={(e: ThreeEvent<MouseEvent>) => {
693 e.stopPropagation();
694 onSelect(item.id);
695 }}
696 />
697 ))}
698 </group>
699 );
700});
701
702/** Self-contained navbar: fills its positioned parent (give it a height ≥ 90px) and centers the bar. */
703function GlassmorphismNavbar3D(props: GlassNavbarProps) {
704 return (
705 <>
706 <UICanvas pauseWhenOffscreen={props.pauseWhenOffscreen} lowPowerMode={props.lowPowerMode}>
707 <PixelPerspective />
708 <Environment resolution={128} frames={1}>
709 <Lightformer form="rect" intensity={3} position={[0, 5, 3]} rotation-x={Math.PI / 2} scale={[12, 2, 1]} />
710 <Lightformer form="rect" intensity={1.5} position={[-6, 0, 3]} rotation-y={Math.PI / 2} scale={[2, 6, 1]} />
711 <Lightformer form="rect" intensity={1.5} position={[6, 0, 3]} rotation-y={-Math.PI / 2} scale={[2, 6, 1]} />
712 </Environment>
713 <GlassNavbarScene {...props} />
714 </UICanvas>
715 {/* Real buttons for keyboard and screen-reader users (the canvas is aria-hidden) */}
716 <nav aria-label="Main" style={SR_ONLY}>
717 {props.items.map((item) => (
718 <button key={item.id} type="button" aria-current={item.id === props.activeId ? "page" : undefined} onClick={() => props.onSelect(item.id)}>
719 {item.label}
720 </button>
721 ))}
722 </nav>
723 </>
724 );
725}
726
727export default memo(GlassmorphismNavbar3D);
03

Drop it in a page

Updated live with the settings above.

app/page.tsx
1"use client";
2
3import { useState } from "react";
4import GlassmorphismNavbar3D from "@/components/GlassmorphismNavbar3D";
5
6export default function Section() {
7 const [activeId, setActiveId] = useState("home");
8
9 return (
10 // The component fills this box: give it a position and a height
11 <div style={{ position: "relative", width: "100%", height: "120px" }}>
12 <GlassmorphismNavbar3D
13 items={[
14 { id: "home", label: "Home" },
15 { id: "work", label: "Work" },
16 { id: "about", label: "About" },
17 { id: "contact", label: "Contact" },
18 ]}
19 transmission={1}
20 emissiveColor="#8b5cf6"
21 activeId={activeId}
22 onSelect={setActiveId}
23 />
24 </div>
25 );
26}
Next componentPrism Navbar→