Loading…
← All components

Navigation · Glass

SaaS Premium Navbar

A floating frosted-glass bar with chromatic edges and a liquid-metal capsule that springs under the active tab, tilting with the pointer.

<SaaSPremiumNavbar3D />Live

Customize

Indicator#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 saas-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/SaaSPremiumNavbar3D.tsx and paste it in.

components/SaaSPremiumNavbar3D.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, 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/**
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
183/** Rounded-rectangle outline centered on the origin (radius clamped to a pill). */
184function roundedRectShape(width: number, height: number, radius: number) {
185 const r = Math.min(radius, width / 2, height / 2);
186 const x = -width / 2;
187 const y = -height / 2;
188 const shape = new THREE.Shape();
189 shape.moveTo(x + r, y);
190 shape.lineTo(x + width - r, y);
191 shape.quadraticCurveTo(x + width, y, x + width, y + r);
192 shape.lineTo(x + width, y + height - r);
193 shape.quadraticCurveTo(x + width, y + height, x + width - r, y + height);
194 shape.lineTo(x + r, y + height);
195 shape.quadraticCurveTo(x, y + height, x, y + height - r);
196 shape.lineTo(x, y + r);
197 shape.quadraticCurveTo(x, y, x + r, y);
198 return shape;
199}
200
201/** Bevelled, extruded rounded rectangle, centered on the origin (front face at +depth/2 + bevel). */
202function createBevelledSlab(width: number, height: number, radius: number, depth: number, bevel: number) {
203 const geometry = new THREE.ExtrudeGeometry(roundedRectShape(width - bevel * 2, height - bevel * 2, Math.max(0, radius - bevel)), {
204 depth,
205 bevelEnabled: true,
206 bevelThickness: bevel,
207 bevelSize: bevel,
208 bevelSegments: 6,
209 curveSegments: 24,
210 });
211 geometry.translate(0, 0, -depth / 2);
212 return geometry;
213}
214
215interface Spring {
216 value: number;
217 velocity: number;
218}
219
220/** Damped spring step: overshoots a little, then settles. */
221function stepSpring(spring: Spring, target: number, stiffness: number, damping: number, dt: number) {
222 spring.velocity += (target - spring.value) * stiffness * dt;
223 spring.velocity *= Math.exp(-damping * dt);
224 spring.value += spring.velocity * dt;
225 return spring.value;
226}
227
228/** Fills the positioned parent. */
229const FILL: CSSProperties = { position: "absolute", top: 0, left: 0, width: "100%", height: "100%" };
230
231/** Camera field of view used with PixelPerspective (1 world unit = 1 CSS pixel on z = 0). */
232const NAV_FOV = 30;
233
234/** Distance of that camera, for a canvas `height` px tall: also the CSS perspective matching it. */
235const cameraDistance = (height: number) => height / 2 / Math.tan(THREE.MathUtils.degToRad(NAV_FOV / 2));
236
237interface NavCanvasProps extends Omit<CanvasProps, "children" | "style" | "gl" | "frameloop">, Pick<PerformanceProps, "pauseWhenOffscreen" | "lowPowerMode"> {
238 children: ReactNode;
239}
240
241/**
242 * Click-through canvas for the navbars: the 3D draws the material (glass, metal, prisms…) while real
243 * HTML buttons on top carry the labels, the clicks, the keyboard focus and the screen reader. Pauses
244 * while scrolled out of view; R3F disposes the renderer and its WebGL context on unmount.
245 */
246function NavCanvas({ children, dpr, pauseWhenOffscreen = DEFAULT_3D_PROPS.pauseWhenOffscreen, lowPowerMode = DEFAULT_3D_PROPS.lowPowerMode, ...canvasProps }: NavCanvasProps) {
247 const ref = useRef<HTMLDivElement>(null);
248 const [inView, setInView] = useState(true);
249 useEffect(() => {
250 const el = ref.current;
251 if (!el) return undefined;
252 const observer = new IntersectionObserver(([entry]) => setInView(entry.isIntersecting));
253 observer.observe(el);
254 return () => observer.disconnect();
255 }, []);
256 return (
257 <div ref={ref} aria-hidden="true" style={{ ...FILL, pointerEvents: "none" }}>
258 <Canvas
259 dpr={lowPowerMode ? 1 : dpr ?? [1, typeof window === "undefined" ? 2 : Math.min(window.devicePixelRatio || 1, 2)]}
260 frameloop={inView || !pauseWhenOffscreen ? "always" : "never"}
261 gl={{ antialias: true, alpha: true, powerPreference: "high-performance" }}
262 style={{ pointerEvents: "none" }}
263 {...canvasProps}
264 >
265 <PixelPerspective fov={NAV_FOV} />
266 {children}
267 </Canvas>
268 </div>
269 );
270}
271
272/** Size of an element in CSS pixels, kept in sync with a ResizeObserver. */
273function useElementSize(ref: RefObject<HTMLElement | null>) {
274 const [size, setSize] = useState({ width: 0, height: 0 });
275 useLayoutEffect(() => {
276 const el = ref.current;
277 if (!el) return undefined;
278 const sync = () => setSize({ width: el.clientWidth, height: el.clientHeight });
279 sync();
280 const observer = new ResizeObserver(sync);
281 observer.observe(el);
282 return () => observer.disconnect();
283 }, [ref]);
284 return size;
285}
286
287interface ItemBox {
288 /** Center of the item, relative to the center of the container (y up, like the 3D). */
289 x: number;
290 y: number;
291 width: number;
292 height: number;
293}
294
295/**
296 * Boxes of the HTML items, relative to the container's center: the 3D scene (1 unit = 1 px, origin at
297 * the center) draws exactly under them. Measured again when the container or the items resize.
298 */
299function useItemBoxes(container: RefObject<HTMLElement | null>, items: RefObject<(HTMLElement | null)[]>, key: unknown) {
300 const [boxes, setBoxes] = useState<ItemBox[]>([]);
301 useLayoutEffect(() => {
302 const root = container.current;
303 if (!root) return undefined;
304 const measure = () => {
305 const r = root.getBoundingClientRect();
306 const cx = r.left + r.width / 2;
307 const cy = r.top + r.height / 2;
308 setBoxes(
309 (items.current ?? []).map((el) => {
310 if (!el) return { x: 0, y: 0, width: 0, height: 0 };
311 // offset* ignore the CSS tilt applied to the layer: the boxes stay flat
312 const box = { left: el.offsetLeft, top: el.offsetTop, width: el.offsetWidth, height: el.offsetHeight };
313 let parent = el.offsetParent as HTMLElement | null;
314 while (parent && parent !== root && root.contains(parent)) {
315 box.left += parent.offsetLeft;
316 box.top += parent.offsetTop;
317 parent = parent.offsetParent as HTMLElement | null;
318 }
319 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 };
320 })
321 );
322 };
323 measure();
324 const observer = new ResizeObserver(measure);
325 observer.observe(root);
326 (items.current ?? []).forEach((el) => el && observer.observe(el));
327 document.fonts?.ready.then(measure);
328 return () => observer.disconnect();
329 }, [container, items, key]);
330 return boxes;
331}
332
333/** Pointer position relative to an element, in -1..1 (y up), and whether it is near it. */
334interface NavPointer {
335 x: number;
336 y: number;
337 near: boolean;
338}
339
340/** Tracks the pointer against an element through window listeners (no React re-render). */
341function useNavPointer(target: RefObject<HTMLElement | null>, reach = 220) {
342 const pointer = useRef<NavPointer>({ x: 0, y: 0, near: false });
343 useEffect(() => {
344 const move = (event: PointerEvent) => {
345 const el = target.current;
346 if (!el || event.pointerType === "touch") return;
347 const r = el.getBoundingClientRect();
348 const p = pointer.current;
349 p.x = THREE.MathUtils.clamp(((event.clientX - r.left) / r.width) * 2 - 1, -1.5, 1.5);
350 p.y = THREE.MathUtils.clamp(-(((event.clientY - r.top) / r.height) * 2 - 1), -1.5, 1.5);
351 p.near =
352 event.clientX > r.left - reach && event.clientX < r.right + reach && event.clientY > r.top - reach && event.clientY < r.bottom + reach;
353 };
354 const leave = () => {
355 pointer.current.near = false;
356 };
357 window.addEventListener("pointermove", move, { passive: true });
358 document.documentElement.addEventListener("pointerleave", leave);
359 return () => {
360 window.removeEventListener("pointermove", move);
361 document.documentElement.removeEventListener("pointerleave", leave);
362 };
363 }, [target, reach]);
364 return pointer;
365}
366
367function usePrefersReducedMotion() {
368 const [reduced, setReduced] = useState(false);
369 useEffect(() => {
370 const query = window.matchMedia("(prefers-reduced-motion: reduce)");
371 const sync = () => setReduced(query.matches);
372 sync();
373 query.addEventListener("change", sync);
374 return () => query.removeEventListener("change", sync);
375 }, []);
376 return reduced;
377}
378
379/** Resets the default button look, keeps a visible focus ring for keyboard users. */
380const BUTTON_RESET: CSSProperties = {
381 appearance: "none",
382 background: "transparent",
383 border: 0,
384 margin: 0,
385 padding: 0,
386 font: "inherit",
387 color: "inherit",
388 cursor: "pointer",
389 WebkitTapHighlightColor: "transparent",
390};
391
392/** CSS for the focus ring of the HTML items (scoped by a class name). */
393const focusRing = (className: string, color: string) =>
394 `.${className}:focus-visible{outline:2px solid ${color};outline-offset:3px;border-radius:999px}`;
395
396export interface SaaSPremiumNavbarProps extends Pick<MaterialProps, "emissiveColor" | "roughness" | "transmission">, Pick<PerformanceProps, "pauseWhenOffscreen" | "lowPowerMode"> {
397 items: { id: string; label: string }[];
398 activeId: string;
399 onSelect: (id: string) => void;
400 /** Color of the liquid-metal indicator under the active tab. Default "#8b5cf6". */
401 emissiveColor?: string;
402 /** @deprecated Use `emissiveColor`. */
403 accentColor?: string;
404 /** Frosting of the glass, 0 = clear. Default 0.2. */
405 roughness?: number;
406 /** @deprecated Use `roughness`. */
407 glassRoughness?: number;
408 /** 0 = opaque, 1 = fully see-through glass. Default 1. */
409 transmission?: number;
410}
411
412const BAR_HEIGHT = 60;
413const BAR_PAD = 8;
414const DEPTH = 14;
415const BEVEL = 7;
416const PILL_HEIGHT = 40;
417const MAX_TILT = THREE.MathUtils.degToRad(6);
418
419interface SceneProps {
420 boxes: ItemBox[];
421 activeIndex: number;
422 hovered: RefObject<number>;
423 pointer: RefObject<NavPointer>;
424 tilt: RefObject<{ x: number; y: number }>;
425 accentColor: string;
426 glassRoughness: number;
427 transmission: number;
428 reducedMotion: boolean;
429}
430
431/** The 3D under the labels: a frosted glass bar and a liquid-metal capsule sliding behind it. */
432const Bar = memo(function Bar({ boxes, activeIndex, hovered, pointer, tilt, accentColor, glassRoughness, transmission, reducedMotion }: SceneProps) {
433 const group = useRef<THREE.Group>(null);
434 const pill = useRef<THREE.Group>(null);
435 const body = useRef<THREE.Mesh>(null);
436 const capL = useRef<THREE.Mesh>(null);
437 const capR = useRef<THREE.Mesh>(null);
438 const lights = useRef<THREE.Group>(null);
439 const spring = useRef({ x: { value: 0, velocity: 0 } as Spring, w: { value: 0, velocity: 0 } as Spring, started: false });
440
441 const width = boxes.length ? boxes[boxes.length - 1].x + boxes[boxes.length - 1].width / 2 - (boxes[0].x - boxes[0].width / 2) + BAR_PAD * 2 : 0;
442 const center = boxes.length ? (boxes[boxes.length - 1].x + boxes[boxes.length - 1].width / 2 + boxes[0].x - boxes[0].width / 2) / 2 : 0;
443
444 const slab = useMemo(() => (width > BAR_HEIGHT ? createBevelledSlab(width, BAR_HEIGHT, BAR_HEIGHT / 2, DEPTH, BEVEL) : null), [width]);
445 useEffect(() => () => slab?.dispose(), [slab]);
446 const r = PILL_HEIGHT / 2;
447 const cap = useMemo(() => new THREE.SphereGeometry(r, 32, 16), [r]);
448 const tube = useMemo(() => {
449 const g = new THREE.CylinderGeometry(r, r, 1, 32, 1, true);
450 g.rotateZ(Math.PI / 2);
451 return g;
452 }, [r]);
453 const metal = useMemo(() => new THREE.MeshStandardMaterial({ metalness: 1, roughness: 0.16, envMapIntensity: 1.6 }), []);
454 // Soft halo around the capsule: distance to a rounded rectangle, faded out (no hard edges)
455 const glow = useMemo(
456 () =>
457 new THREE.ShaderMaterial({
458 uniforms: { uColor: { value: new THREE.Color() }, uSize: { value: new THREE.Vector2(1, 1) } },
459 vertexShader: /* glsl */ `
460 varying vec2 vUv;
461 void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }
462 `,
463 fragmentShader: /* glsl */ `
464 uniform vec3 uColor;
465 uniform vec2 uSize;
466 varying vec2 vUv;
467 void main() {
468 vec2 p = (vUv - 0.5) * uSize;
469 vec2 b = uSize * 0.5 - vec2(26.0);
470 float r = ${(PILL_HEIGHT / 2).toFixed(1)};
471 vec2 q = abs(p) - (b - r);
472 float d = length(max(q, 0.0)) + min(max(q.x, q.y), 0.0) - r;
473 float g = exp(-max(d, 0.0) / 11.0) * 0.75;
474 gl_FragColor = vec4(uColor * g, g);
475 #include <colorspace_fragment>
476 }
477 `,
478 transparent: true,
479 depthWrite: false,
480 blending: THREE.AdditiveBlending,
481 }),
482 []
483 );
484 const glowPlane = useMemo(() => new THREE.PlaneGeometry(1, 1), []);
485 const background = useMemo(() => new THREE.Color("#121219"), []);
486 useEffect(() => {
487 metal.color.set(accentColor).lerp(new THREE.Color("#ffffff"), 0.25);
488 metal.emissive.set(accentColor);
489 metal.emissiveIntensity = 0.35;
490 (glow.uniforms.uColor.value as THREE.Color).set(accentColor);
491 }, [metal, glow, accentColor]);
492 useEffect(
493 () => () => {
494 cap.dispose();
495 tube.dispose();
496 metal.dispose();
497 glow.dispose();
498 glowPlane.dispose();
499 },
500 [cap, tube, metal, glow, glowPlane]
501 );
502
503 useFrame((_, delta) => {
504 const dt = Math.min(delta, 1 / 30);
505 const box = boxes[activeIndex];
506 if (!box) return;
507 const s = spring.current;
508 const h = hovered.current ?? -1;
509 // Hovering another tab draws the capsule a little toward it
510 const lean = h >= 0 && h !== activeIndex && boxes[h] ? (boxes[h].x - box.x) * 0.16 : 0;
511 const targetW = Math.max(0, box.width - 8 - r * 2);
512 if (!s.started) {
513 s.x.value = box.x;
514 s.w.value = targetW;
515 s.started = true;
516 }
517 stepSpring(s.x, box.x + lean, 180, 14, dt);
518 stepSpring(s.w, targetW, 180, 14, dt);
519 // Liquid: it stretches with its speed and thins out
520 const stretch = Math.min(Math.abs(s.x.velocity) * 0.05, 40);
521 const len = Math.max(0, s.w.value + stretch);
522 const squash = 1 - Math.min(stretch / 170, 0.2);
523 pill.current?.position.set(s.x.value, box.y, -DEPTH / 2 - 4);
524 pill.current?.scale.set(1, squash, squash);
525 capL.current?.position.set(-len / 2, 0, 0);
526 capR.current?.position.set(len / 2, 0, 0);
527 body.current?.scale.set(Math.max(len, 0.001), 1, 1);
528 const glowMesh = pill.current?.children[0] as THREE.Mesh | undefined;
529 if (glowMesh) {
530 glowMesh.scale.set(len + r * 2 + 52, PILL_HEIGHT + 52, 1);
531 (glow.uniforms.uSize.value as THREE.Vector2).set(len + r * 2 + 52, PILL_HEIGHT + 52);
532 }
533
534 // Subtle tilt toward the pointer; the HTML labels get the same rotation (see the component)
535 const p = pointer.current;
536 const tx = p?.near && !reducedMotion ? -p.y * MAX_TILT : 0;
537 const ty = p?.near && !reducedMotion ? p.x * MAX_TILT : 0;
538 const t = tilt.current;
539 if (t && group.current) {
540 t.x = THREE.MathUtils.damp(t.x, tx, 5, dt);
541 t.y = THREE.MathUtils.damp(t.y, ty, 5, dt);
542 group.current.rotation.set(t.x, t.y, 0);
543 }
544 // Micro reflections slide across the glass with the pointer
545 if (lights.current && p) lights.current.position.x = THREE.MathUtils.damp(lights.current.position.x, p.near ? p.x * 4 : 0, 3, dt);
546 });
547
548 return (
549 <>
550 <Environment resolution={128}>
551 <group ref={lights}>
552 <Lightformer form="rect" intensity={3} position={[0, 4, 3]} rotation-x={Math.PI / 2} scale={[10, 1.5, 1]} />
553 <Lightformer form="rect" intensity={1.4} position={[-6, 0, 3]} rotation-y={Math.PI / 2} scale={[2, 6, 1]} color={accentColor} />
554 <Lightformer form="rect" intensity={1.4} position={[6, 0, 3]} rotation-y={-Math.PI / 2} scale={[2, 6, 1]} />
555 </group>
556 </Environment>
557 <group ref={group} position={[center, 0, 0]}>
558 <group position={[-center, 0, 0]}>
559 <group ref={pill}>
560 <mesh geometry={glowPlane} material={glow} position={[0, 0, -r]} />
561 <mesh ref={capL} geometry={cap} material={metal} />
562 <mesh ref={body} geometry={tube} material={metal} />
563 <mesh ref={capR} geometry={cap} material={metal} />
564 </group>
565 {slab && (
566 <mesh geometry={slab} position={[center, boxes[0]?.y ?? 0, 0]}>
567 <MeshTransmissionMaterial
568 transmission={transmission}
569 thickness={28}
570 roughness={glassRoughness}
571 ior={1.32}
572 chromaticAberration={0.08}
573 anisotropicBlur={0.2}
574 distortion={0.1}
575 distortionScale={0.3}
576 temporalDistortion={reducedMotion ? 0 : 0.04}
577 samples={6}
578 resolution={512}
579 background={background}
580 />
581 </mesh>
582 )}
583 </group>
584 </group>
585 </>
586 );
587});
588
589/**
590 * Ultra-premium floating navbar (Stripe / Linear style): a frosted glass bar with chromatic edges, a
591 * liquid-metal capsule that springs under the active tab (and leans toward the hovered one), and a
592 * subtle 3D tilt following the pointer. Labels are real buttons over the 3D: crisp, focusable and
593 * read by screen readers. Fills its positioned parent and centers the bar (give it ≥ 90px of height).
594 */
595function SaaSPremiumNavbar3D({ items, activeId, onSelect, emissiveColor, accentColor = emissiveColor ?? "#8b5cf6", roughness, glassRoughness = roughness ?? 0.2, transmission = 1, pauseWhenOffscreen, lowPowerMode }: SaaSPremiumNavbarProps) {
596 const reducedMotion = usePrefersReducedMotion();
597 const root = useRef<HTMLDivElement>(null);
598 const layer = useRef<HTMLDivElement>(null);
599 const bar = useRef<HTMLDivElement>(null);
600 const itemRefs = useRef<(HTMLButtonElement | null)[]>([]);
601 const hovered = useRef(-1);
602 const tilt = useRef({ x: 0, y: 0 });
603 const [hoverIndex, setHoverIndex] = useState(-1);
604 const size = useElementSize(root);
605 const labelsKey = items.map((i) => i.label).join("\n");
606 const boxes = useItemBoxes(root, itemRefs, `${labelsKey}|${size.width}`);
607 const pointer = useNavPointer(bar);
608 const activeIndex = Math.max(0, items.findIndex((i) => i.id === activeId));
609
610 // The HTML layer follows the 3D tilt (same perspective as the camera), so labels stay on the glass
611 useEffect(() => {
612 let id = 0;
613 const tick = () => {
614 const t = tilt.current;
615 if (layer.current) layer.current.style.transform = `rotateX(${-t.x}rad) rotateY(${t.y}rad)`;
616 id = requestAnimationFrame(tick);
617 };
618 id = requestAnimationFrame(tick);
619 return () => cancelAnimationFrame(id);
620 }, []);
621
622 return (
623 <div ref={root} style={{ ...FILL, perspective: size.height ? `${cameraDistance(size.height)}px` : undefined }}>
624 <style>{focusRing("saas-nav-item", accentColor)}</style>
625 <NavCanvas pauseWhenOffscreen={pauseWhenOffscreen} lowPowerMode={lowPowerMode}>
626 <Bar
627 boxes={boxes}
628 activeIndex={activeIndex}
629 hovered={hovered}
630 pointer={pointer}
631 tilt={tilt}
632 accentColor={accentColor}
633 glassRoughness={glassRoughness}
634 transmission={transmission}
635 reducedMotion={reducedMotion}
636 />
637 </NavCanvas>
638 <div ref={layer} style={{ ...FILL, display: "flex", alignItems: "center", justifyContent: "center", transformStyle: "preserve-3d", willChange: "transform" }}>
639 <nav aria-label="Main">
640 <div ref={bar} style={{ display: "flex", alignItems: "center", gap: 0, padding: `0 ${BAR_PAD}px`, height: BAR_HEIGHT }}>
641 {items.map((item, i) => (
642 <button
643 key={item.id}
644 ref={(el) => {
645 itemRefs.current[i] = el;
646 }}
647 type="button"
648 className="saas-nav-item"
649 aria-current={i === activeIndex ? "page" : undefined}
650 onClick={() => onSelect(item.id)}
651 onPointerEnter={() => {
652 hovered.current = i;
653 setHoverIndex(i);
654 }}
655 onPointerLeave={() => {
656 if (hovered.current === i) hovered.current = -1;
657 setHoverIndex(-1);
658 }}
659 onFocus={() => (hovered.current = i)}
660 onBlur={() => (hovered.current = -1)}
661 style={{
662 ...BUTTON_RESET,
663 minHeight: 44,
664 padding: "0 clamp(12px, 2.4vw, 22px)",
665 fontSize: 14,
666 fontWeight: 600,
667 letterSpacing: "-0.01em",
668 whiteSpace: "nowrap",
669 color: "#fff",
670 opacity: i === activeIndex ? 1 : hoverIndex === i ? 0.9 : 0.62,
671 textShadow: "0 1px 10px rgba(0,0,0,0.45)",
672 transition: "opacity 0.2s",
673 }}
674 >
675 {item.label}
676 </button>
677 ))}
678 </div>
679 </nav>
680 </div>
681 </div>
682 );
683}
684
685export default memo(SaaSPremiumNavbar3D);
03

Drop it in a page

Updated live with the settings above.

app/page.tsx
1"use client";
2
3import { useState } from "react";
4import SaaSPremiumNavbar3D from "@/components/SaaSPremiumNavbar3D";
5
6export default function Section() {
7 const [activeId, setActiveId] = useState("product");
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 <SaaSPremiumNavbar3D
13 items={[
14 { id: "product", label: "Product" },
15 { id: "pricing", label: "Pricing" },
16 { id: "docs", label: "Docs" },
17 { id: "changelog", label: "Changelog" },
18 ]}
19 roughness={0.2}
20 transmission={1}
21 emissiveColor="#8b5cf6"
22 activeId={activeId}
23 onSelect={setActiveId}
24 />
25 </div>
26 );
27}
Next componentStudio Prism Navbar→