← All components Next component3D Key Button→
Navigation · Navigation
Prism Navbar
Menu items as prisms that turn a quarter on hover to reveal a sublabel and an icon.
<PrismNavbar3D />Live
Hover an item to turn it
Customize
Hidden face#7c3aed
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-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/PrismNavbar3D.tsx and paste it in.
components/PrismNavbar3D.tsx
1"use client";23import {4 memo,5 useEffect,6 useLayoutEffect,7 useMemo,8 useRef,9 useState,10 type CSSProperties,11 type ReactNode,12} from "react";13import * as THREE from "three";14import { RoundedBoxGeometry } from "three/examples/jsm/geometries/RoundedBoxGeometry.js";15import { Canvas, useFrame, useThree, type CanvasProps, type ThreeEvent } from "@react-three/fiber";16import { Environment, Lightformer } from "@react-three/drei";1718/**19 * The shared props API of DeepUI's individual 3D components (not the full-page templates, which keep20 * their own tailored scenes).21 *22 * The props are grouped by concern. A component extends ONLY the groups it really applies, so its23 * 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 are29 * inlined into each component's single-file bundle (lib/bundle-source.mjs), only what it uses.30 */3132/** 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";3435/** 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}4647/** 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}5859/** 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}7273/** 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}9091/** 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}102103/** 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}112113/** 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}122123/** Every group at once. Components extend only the groups they apply (see the top of this file). */124interface Base3DComponentProps125 extends CursorProps,126 TiltProps,127 Text3DProps,128 MaterialProps,129 MotionProps,130 EnvironmentProps,131 PerformanceProps {}132133type Defaults = Required<Omit<Base3DComponentProps, "text" | "fontUrl" | "particleCount" | "cameraFov">>;134135/** 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};164165/** Inline widget: fills its positioned parent and receives pointer events. */166const FILL_STYLE: CSSProperties = { position: "absolute", top: 0, left: 0, width: "100%", height: "100%" };167168/** 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};178179/** 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};191192interface 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}197198/**199 * Ready-to-use <Canvas>: pauses its render loop while scrolled out of view (pauseWhenOffscreen), pixel200 * 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 paused205 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 <Canvas216 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}227228/**229 * Perspective camera placed so that 1 world unit = 1 CSS pixel on the z = 0 plane: widgets are laid230 * 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}245246function pageFontFamily() {247 if (typeof document === "undefined") return "sans-serif";248 return getComputedStyle(document.body).fontFamily || "sans-serif";249}250251let measureContext: CanvasRenderingContext2D | null = null;252253/** 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}261262interface 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}283284function 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}299300function drawLabel(canvas: HTMLCanvasElement, o: LabelOptions) {301 // Drawn at 2× (or the screen's ratio) so the text stays crisp once mapped on its plane302 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 }313314 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";320321 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;325326 let text = o.text;327 if (o.icon) text = `${o.icon} ${text}`;328 ctx.font = `${weight} ${size}px ${family}`;329330 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 ellipsis334 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 }345346 const mainY = o.subtext ? o.height * 0.4 : o.height / 2;347 ctx.fillText(text, x, mainY);348349 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}356357/**358 * Text drawn into a CanvasTexture, in the page's own font: no font file to download (unlike drei's359 * <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 }, []);373374 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 }, []);380381 useLayoutEffect(() => {382 drawLabel(texture.image as HTMLCanvasElement, JSON.parse(key) as LabelOptions);383 texture.needsUpdate = true;384 }, [texture, key, fontsVersion]);385386 useEffect(() => () => texture.dispose(), [texture]);387 return texture;388}389390interface Spring {391 value: number;392 velocity: number;393}394395/** Damped spring step: overshoots a little, then settles. */396function stepSpring(spring: Spring, target: number, stiffness: number, damping: number, dt: number) {397 spring.velocity += (target - spring.value) * stiffness * dt;398 spring.velocity *= Math.exp(-damping * dt);399 spring.value += spring.velocity * dt;400 return spring.value;401}402403export interface PrismNavItem {404 label: string;405 /** Shown on the hidden face, revealed on hover. */406 sublabel?: string;407 /** Glyph shown on the hidden face (emoji, arrow, symbol…). */408 icon?: string;409}410411export interface PrismNavbarProps extends Pick<MaterialProps, "primaryColor">, Pick<PerformanceProps, "pauseWhenOffscreen" | "lowPowerMode"> {412 items: PrismNavItem[];413 /** Color of the hidden face. */414 primaryColor?: string;415 /** @deprecated Use `primaryColor`. */416 prismColor?: string;417 /** Speed of the 90° turn. Default 1. */418 rotationSpeed?: number;419 /** Called with the item's index on click (or Enter on the accessible buttons). */420 onSelect?: (index: number) => void;421}422423const HEIGHT = 48; // square cross-section: a 90° turn shows a full face424const GAP = 10;425const FONT_SIZE = 14;426const ITEM_PAD = 26;427const FACE_COLOR = "#141418";428429interface PrismProps {430 item: PrismNavItem;431 width: number;432 x: number;433 prismColor: string;434 rotationSpeed: number;435 sideMaterial: THREE.MeshStandardMaterial;436 onSelect?: () => void;437}438439/** One menu item: a box whose front shows the label and whose bottom face turns up on hover. */440const Prism = memo(function Prism({ item, width, x, prismColor, rotationSpeed, sideMaterial, onSelect }: PrismProps) {441 const groupRef = useRef<THREE.Group>(null);442 const gl = useThree((state) => state.gl);443 const hovered = useRef(false);444 const turn = useRef<Spring>({ value: 0, velocity: 0 });445 const lift = useRef(0);446447 const frontTexture = useLabelTexture({ text: item.label, width, height: HEIGHT, color: "#ffffff", background: FACE_COLOR, fontSize: FONT_SIZE });448 const hiddenTexture = useLabelTexture({449 text: item.sublabel ?? item.label,450 icon: item.icon,451 width,452 height: HEIGHT,453 color: "#ffffff",454 background: prismColor,455 fontSize: FONT_SIZE,456 });457458 const geometry = useMemo(() => new RoundedBoxGeometry(width, HEIGHT, HEIGHT, 3, 5), [width]);459 const frontMaterial = useMemo(() => new THREE.MeshStandardMaterial({ roughness: 0.45, metalness: 0.15 }), []);460 const hiddenMaterial = useMemo(() => new THREE.MeshStandardMaterial({ roughness: 0.35, metalness: 0.2 }), []);461 useEffect(() => {462 frontMaterial.map = frontTexture;463 frontMaterial.needsUpdate = true;464 }, [frontMaterial, frontTexture]);465 useEffect(() => {466 hiddenMaterial.map = hiddenTexture;467 hiddenMaterial.needsUpdate = true;468 }, [hiddenMaterial, hiddenTexture]);469 useEffect(() => () => geometry.dispose(), [geometry]);470 useEffect(471 () => () => {472 frontMaterial.dispose();473 hiddenMaterial.dispose();474 },475 [frontMaterial, hiddenMaterial]476 );477478 // Box face order: +x, -x, +y, -y, +z (front), -z479 const materials = useMemo(480 () => [sideMaterial, sideMaterial, sideMaterial, hiddenMaterial, frontMaterial, sideMaterial],481 [sideMaterial, hiddenMaterial, frontMaterial]482 );483484 useFrame((_, delta) => {485 const group = groupRef.current;486 if (!group) return;487 const dt = Math.min(delta, 1 / 30);488 // Damped spring: a short overshoot at the end of the turn489 stepSpring(turn.current, hovered.current ? -Math.PI / 2 : 0, 150 * rotationSpeed * rotationSpeed, 13 * rotationSpeed, dt);490 group.rotation.x = turn.current.value;491 lift.current = THREE.MathUtils.damp(lift.current, hovered.current ? 1 : 0, 10, dt);492 group.position.z = lift.current * 12;493 });494495 return (496 <group position={[x, 0, 0]}>497 <group ref={groupRef}>498 <mesh499 geometry={geometry}500 material={materials}501 onPointerOver={(e: ThreeEvent<PointerEvent>) => {502 e.stopPropagation();503 hovered.current = true;504 gl.domElement.style.cursor = "pointer";505 }}506 onPointerOut={() => {507 hovered.current = false;508 gl.domElement.style.cursor = "";509 }}510 onClick={(e: ThreeEvent<MouseEvent>) => {511 e.stopPropagation();512 onSelect?.();513 }}514 />515 </group>516 </group>517 );518});519520/** The navbar's 3D content, for an existing R3F scene (1 world unit = 1 CSS pixel, see PixelPerspective). */521export const PrismNavbarScene = memo(function PrismNavbarScene({ items, primaryColor, prismColor = primaryColor ?? "#7c3aed", rotationSpeed = 1, onSelect }: PrismNavbarProps) {522 const sideMaterial = useMemo(() => new THREE.MeshStandardMaterial({ color: "#1d1d23", metalness: 0.7, roughness: 0.3 }), []);523 useEffect(() => () => sideMaterial.dispose(), [sideMaterial]);524525 const labelsKey = items.map((item) => item.label + "\t" + (item.sublabel ?? "") + "\t" + (item.icon ?? "")).join("\n");526 const layout = useMemo(() => {527 const widths = items.map((item) => {528 const main = measureLabel(item.label, FONT_SIZE, 600);529 const hidden = measureLabel(`${item.icon ? `${item.icon} ` : ""}${item.sublabel ?? item.label}`, FONT_SIZE, 600);530 return Math.ceil(Math.max(main, hidden)) + ITEM_PAD * 2;531 });532 const total = widths.reduce((sum, w) => sum + w, 0) + GAP * (widths.length - 1);533 let cursor = -total / 2;534 const centers = widths.map((w) => {535 const c = cursor + w / 2;536 cursor += w + GAP;537 return c;538 });539 return { widths, centers };540 }, [labelsKey]);541542 return (543 <group>544 {items.map((item, i) => (545 <Prism546 key={`${i}-${item.label}`}547 item={item}548 width={layout.widths[i]}549 x={layout.centers[i]}550 prismColor={prismColor}551 rotationSpeed={rotationSpeed}552 sideMaterial={sideMaterial}553 onSelect={onSelect ? () => onSelect(i) : undefined}554 />555 ))}556 </group>557 );558});559560/** Self-contained navbar: fills its positioned parent (give it a height ≥ 90px) and centers the row. */561function PrismNavbar3D(props: PrismNavbarProps) {562 return (563 <>564 <UICanvas pauseWhenOffscreen={props.pauseWhenOffscreen} lowPowerMode={props.lowPowerMode}>565 <PixelPerspective />566 <ambientLight intensity={0.6} />567 <directionalLight position={[200, 400, 600]} intensity={2} />568 {/* Light panels for the metal edges: no HDR file to download */}569 <Environment resolution={128} frames={1}>570 <Lightformer form="rect" intensity={2.5} position={[0, 5, 3]} rotation-x={Math.PI / 2} scale={[12, 2, 1]} />571 <Lightformer form="rect" intensity={1.2} position={[-6, 0, 3]} rotation-y={Math.PI / 2} scale={[2, 6, 1]} />572 </Environment>573 <PrismNavbarScene {...props} />574 </UICanvas>575 {/* Real buttons for keyboard and screen-reader users (the canvas is aria-hidden) */}576 <nav aria-label="Main" style={SR_ONLY}>577 {props.items.map((item, i) => (578 <button key={`${i}-${item.label}`} type="button" onClick={() => props.onSelect?.(i)}>579 {item.label}580 {item.sublabel ? ` — ${item.sublabel}` : ""}581 </button>582 ))}583 </nav>584 </>585 );586}587588export default memo(PrismNavbar3D);
03
Drop it in a page
Updated live with the settings above.
app/page.tsx
1import PrismNavbar3D from "@/components/PrismNavbar3D";23export default function Section() {4 return (5 // The component fills this box: give it a position and a height6 <div style={{ position: "relative", width: "100%", height: "100vh" }}>7 <PrismNavbar3D8 items={[9 { label: "Product", sublabel: "Features", icon: "◆" },10 { label: "Pricing", sublabel: "From $9", icon: "€" },11 { label: "Docs", sublabel: "Read →", icon: "✦" },12 ]}13 rotationSpeed={1}14 primaryColor="#7c3aed"15 />16 </div>17 );18}