Loading…
← All components

Navigation · Hologram

Holo Burger Menu

A discreet holographic badge in a corner: its 3D hamburger turns into a cross and the links cascade out as floating cards.

Portfolio

Quiet pages, loud work.

Open the menu in the top corner.

<DiscreteHoloBurgerNavbar3D />Live

Customize

Corner
Hologram#22d3ee

Installation

Use it in your project

Or skip the copy-paste

One command: writes the file and installs the dependencies.

$ npx deepui-cli add holo-burger-navbar
01

Install

The 3D packages this component is built on.

$ npm install three @react-three/fiber && npm install -D @types/three
02

Add the component

One self-contained file: create components/DiscreteHoloBurgerNavbar3D.tsx and paste it in.

components/DiscreteHoloBurgerNavbar3D.tsx
1"use client";
2
3import {
4 memo,
5 useCallback,
6 useEffect,
7 useLayoutEffect,
8 useMemo,
9 useRef,
10 useState,
11 type CSSProperties,
12 type ReactNode,
13 type RefObject,
14} from "react";
15import * as THREE from "three";
16import { Canvas, useFrame, useThree, type CanvasProps } from "@react-three/fiber";
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
402function usePrefersReducedMotion() {
403 const [reduced, setReduced] = useState(false);
404 useEffect(() => {
405 const query = window.matchMedia("(prefers-reduced-motion: reduce)");
406 const sync = () => setReduced(query.matches);
407 sync();
408 query.addEventListener("change", sync);
409 return () => query.removeEventListener("change", sync);
410 }, []);
411 return reduced;
412}
413
414/** Resets the default button look, keeps a visible focus ring for keyboard users. */
415const BUTTON_RESET: CSSProperties = {
416 appearance: "none",
417 background: "transparent",
418 border: 0,
419 margin: 0,
420 padding: 0,
421 font: "inherit",
422 color: "inherit",
423 cursor: "pointer",
424 WebkitTapHighlightColor: "transparent",
425};
426
427export interface DiscreteHoloBurgerProps extends Pick<PerformanceProps, "pauseWhenOffscreen" | "lowPowerMode"> {
428 items: { id: string; label: string; href?: string }[];
429 onSelect?: (id: string) => void;
430 /** Color of the hologram. Default "#22d3ee". */
431 badgeColor?: string;
432 /** Corner of the screen. Default "top-right". */
433 menuPosition?: "top-right" | "top-left";
434 /** Pinned to the viewport (default) or to the positioned parent (false). */
435 fixed?: boolean;
436}
437
438const BADGE = 56;
439const CARD_W = 260;
440const CARD_H = 52;
441const GAP = 12;
442const MARGIN = 20;
443const INSET = 10; // space between the edges of the menu area and the badge / cards
444
445// Hologram: scanlines running up, a fresnel rim, a flicker that crackles while hovered
446const holoVertex = /* glsl */ `
447varying vec3 vNormal;
448varying vec3 vView;
449varying vec2 vScreen;
450void main() {
451 vec4 mv = modelViewMatrix * vec4(position, 1.0);
452 vNormal = normalize(normalMatrix * normal);
453 vView = normalize(-mv.xyz);
454 vec4 clip = projectionMatrix * mv;
455 vScreen = clip.xy / clip.w;
456 gl_Position = clip;
457}
458`;
459const holoFragment = /* glsl */ `
460uniform vec3 uColor;
461uniform float uTime;
462uniform float uHover;
463uniform float uOpacity;
464varying vec3 vNormal;
465varying vec3 vView;
466varying vec2 vScreen;
467float hash(float n) { return fract(sin(n) * 43758.5453); }
468void main() {
469 float rim = pow(1.0 - abs(dot(normalize(vNormal), normalize(vView))), 2.0);
470 float scan = 0.5 + 0.5 * sin(vScreen.y * 260.0 - uTime * 6.0);
471 float band = smoothstep(0.0, 0.08, fract(vScreen.y * 1.5 - uTime * 0.35)) * smoothstep(0.2, 0.08, fract(vScreen.y * 1.5 - uTime * 0.35));
472 float crackle = uHover * step(0.86, hash(floor(uTime * 24.0) + floor(vScreen.y * 40.0)));
473 vec3 color = uColor * (0.16 + scan * 0.14 + rim * 1.1 + band * 0.6 + crackle * 0.8);
474 float alpha = (0.55 + rim * 0.45) * uOpacity;
475 gl_FragColor = vec4(color, alpha);
476 #include <colorspace_fragment>
477}
478`;
479
480function createHoloMaterial() {
481 return new THREE.ShaderMaterial({
482 uniforms: { uColor: { value: new THREE.Color() }, uTime: { value: 0 }, uHover: { value: 0 }, uOpacity: { value: 1 } },
483 vertexShader: holoVertex,
484 fragmentShader: holoFragment,
485 transparent: true,
486 depthWrite: false,
487 toneMapped: false,
488 });
489}
490
491interface Layout {
492 width: number;
493 height: number;
494 /** +1 when the menu hangs from the right corner. */
495 side: number;
496}
497
498interface CardProps {
499 label: string;
500 index: number;
501 layout: Layout;
502 open: RefObject<boolean>;
503 hovered: RefObject<number>;
504 color: string;
505 geometry: THREE.BufferGeometry;
506 reducedMotion: boolean;
507}
508
509const Card = memo(function Card({ label, index, layout, open, hovered, color, geometry, reducedMotion }: CardProps) {
510 const group = useRef<THREE.Group>(null);
511 const material = useMemo(() => createHoloMaterial(), []);
512 const texture = useLabelTexture({ text: label, width: CARD_W - 24, height: CARD_H, color: "#ffffff", fontSize: 15, fontWeight: 600, align: "left", padding: 8 });
513 const labelMat = useMemo(() => new THREE.MeshBasicMaterial({ transparent: true, depthWrite: false, toneMapped: false }), []);
514 const plane = useMemo(() => new THREE.PlaneGeometry(CARD_W - 24, CARD_H), []);
515 useEffect(() => {
516 labelMat.map = texture;
517 labelMat.needsUpdate = true;
518 }, [labelMat, texture]);
519 useEffect(() => {
520 (material.uniforms.uColor.value as THREE.Color).set(color);
521 }, [material, color]);
522 useEffect(
523 () => () => {
524 material.dispose();
525 labelMat.dispose();
526 plane.dispose();
527 },
528 [material, labelMat, plane]
529 );
530 const t = useRef<Spring>({ value: 0, velocity: 0 });
531 const delay = useRef(0);
532
533 useFrame((state, delta) => {
534 const dt = Math.min(delta, 1 / 30);
535 const g = group.current;
536 if (!g) return;
537 // Staggered: each card leaves the badge a little after the previous one (and returns first)
538 const isOpen = open.current ?? false;
539 delay.current = isOpen ? delay.current + dt : 0;
540 const target = isOpen && delay.current > index * 0.05 ? 1 : 0;
541 stepSpring(t.current, target, 150, 13, dt);
542 const p = Math.max(0, t.current.value);
543 const badgeX = layout.side * (layout.width / 2 - INSET - BADGE / 2);
544 const badgeY = layout.height / 2 - INSET - BADGE / 2;
545 const x = layout.side * (layout.width / 2 - INSET - CARD_W / 2);
546 const y = layout.height / 2 - INSET - BADGE - GAP - CARD_H / 2 - index * (CARD_H + GAP);
547 const hover = hovered.current === index ? 1 : 0;
548 const bob = reducedMotion ? 0 : Math.sin(state.clock.elapsedTime * 1.6 + index) * 2;
549 g.position.set(badgeX + (x - badgeX) * p + hover * -layout.side * 6, badgeY + (y - badgeY) * p + bob * p, (1 - p) * -260 + hover * 12);
550 g.rotation.set((1 - p) * -0.9, (1 - p) * layout.side * 0.6, 0);
551 g.scale.setScalar(0.25 + 0.75 * Math.min(1, p));
552 g.visible = p > 0.01;
553 material.uniforms.uTime.value = state.clock.elapsedTime;
554 material.uniforms.uHover.value = THREE.MathUtils.damp(material.uniforms.uHover.value, hover, 10, dt);
555 material.uniforms.uOpacity.value = Math.min(1, p);
556 labelMat.opacity = Math.min(1, p * 1.4);
557 });
558
559 return (
560 <group ref={group} visible={false}>
561 <mesh geometry={geometry} material={material} />
562 <mesh geometry={plane} material={labelMat} position={[0, 0, 10]} />
563 </group>
564 );
565});
566
567interface BadgeProps {
568 layout: Layout;
569 open: RefObject<boolean>;
570 hoveredBadge: RefObject<boolean>;
571 color: string;
572}
573
574/** The holographic badge and its 3D hamburger, which morphs into a cross when the menu is open. */
575const Badge = memo(function Badge({ layout, open, hoveredBadge, color }: BadgeProps) {
576 const group = useRef<THREE.Group>(null);
577 const bars = useRef<(THREE.Mesh | null)[]>([]);
578 const geometry = useMemo(() => createBevelledSlab(BADGE, BADGE, 16, 14, 5), []);
579 const barGeometry = useMemo(() => new THREE.BoxGeometry(22, 2.6, 2.6), []);
580 const material = useMemo(() => createHoloMaterial(), []);
581 const barMaterial = useMemo(() => new THREE.MeshBasicMaterial({ color: "#ffffff", toneMapped: false }), []);
582 const morph = useRef<Spring>({ value: 0, velocity: 0 });
583 useEffect(() => {
584 (material.uniforms.uColor.value as THREE.Color).set(color);
585 }, [material, color]);
586 useEffect(
587 () => () => {
588 geometry.dispose();
589 barGeometry.dispose();
590 material.dispose();
591 barMaterial.dispose();
592 },
593 [geometry, barGeometry, material, barMaterial]
594 );
595
596 useFrame((state, delta) => {
597 const dt = Math.min(delta, 1 / 30);
598 const m = stepSpring(morph.current, open.current ? 1 : 0, 220, 16, dt);
599 const hover = hoveredBadge.current ? 1 : 0;
600 material.uniforms.uTime.value = state.clock.elapsedTime;
601 material.uniforms.uHover.value = THREE.MathUtils.damp(material.uniforms.uHover.value, hover, 10, dt);
602 const g = group.current;
603 if (g) {
604 g.position.set(layout.side * (layout.width / 2 - INSET - BADGE / 2), layout.height / 2 - INSET - BADGE / 2, hover * 6);
605 g.rotation.y = THREE.MathUtils.damp(g.rotation.y, hover * 0.25 * -layout.side, 6, dt);
606 }
607 // ☰ → ✕ : top and bottom bars meet in the middle and turn ±45°, the middle one shrinks away
608 const [top, middle, bottom] = bars.current;
609 if (top && middle && bottom) {
610 top.position.y = 7 * (1 - m);
611 bottom.position.y = -7 * (1 - m);
612 top.rotation.z = (Math.PI / 4) * m;
613 bottom.rotation.z = (-Math.PI / 4) * m;
614 middle.scale.x = Math.max(0.001, 1 - m);
615 }
616 });
617
618 return (
619 <group ref={group}>
620 <mesh geometry={geometry} material={material} />
621 {[0, 1, 2].map((i) => (
622 <mesh
623 key={i}
624 ref={(el) => {
625 bars.current[i] = el;
626 }}
627 geometry={barGeometry}
628 material={barMaterial}
629 position={[0, 7 - i * 7, 14]}
630 />
631 ))}
632 </group>
633 );
634});
635
636/**
637 * Discreet holographic menu: a compact badge floating in a corner of the screen. Hovered, its
638 * hologram crackles with scanlines; clicked, its hamburger turns into a volumetric cross and the
639 * links cascade out of it as floating holographic cards. Escape, a click outside or a choice closes
640 * it. The badge and the links are real buttons / links (focus, keyboard, screen readers).
641 */
642function DiscreteHoloBurgerNavbar3D({ items, onSelect, badgeColor = "#22d3ee", menuPosition = "top-right", fixed = true, pauseWhenOffscreen, lowPowerMode }: DiscreteHoloBurgerProps) {
643 const reducedMotion = usePrefersReducedMotion();
644 const root = useRef<HTMLDivElement>(null);
645 const firstLink = useRef<HTMLElement | null>(null);
646 const [isOpen, setIsOpen] = useState(false);
647 const open = useRef(false);
648 const hovered = useRef(-1);
649 const hoveredBadge = useRef(false);
650 const side = menuPosition === "top-left" ? -1 : 1;
651 const layout = useMemo<Layout>(() => ({ width: CARD_W + INSET * 2, height: INSET * 2 + BADGE + GAP + items.length * (CARD_H + GAP), side }), [items.length, side]);
652 const cardGeometry = useMemo(() => createBevelledSlab(CARD_W, CARD_H, 14, 8, 4), []);
653 useEffect(() => () => cardGeometry.dispose(), [cardGeometry]);
654
655 const setOpen = useCallback((value: boolean) => {
656 open.current = value;
657 setIsOpen(value);
658 }, []);
659
660 useEffect(() => {
661 if (!isOpen) return undefined;
662 firstLink.current?.focus({ preventScroll: true });
663 const key = (event: KeyboardEvent) => {
664 if (event.key === "Escape") setOpen(false);
665 };
666 const outside = (event: PointerEvent) => {
667 if (!root.current?.contains(event.target as Node)) setOpen(false);
668 };
669 window.addEventListener("keydown", key);
670 window.addEventListener("pointerdown", outside);
671 return () => {
672 window.removeEventListener("keydown", key);
673 window.removeEventListener("pointerdown", outside);
674 };
675 }, [isOpen, setOpen]);
676
677 const anchor: CSSProperties = {
678 position: fixed ? "fixed" : "absolute",
679 top: MARGIN,
680 [side > 0 ? "right" : "left"]: MARGIN,
681 width: layout.width,
682 height: layout.height,
683 maxWidth: `calc(100% - ${MARGIN}px)`,
684 zIndex: 50,
685 pointerEvents: "none",
686 };
687 const linkStyle = (i: number): CSSProperties => ({
688 ...BUTTON_RESET,
689 position: "absolute",
690 top: INSET + BADGE + GAP + i * (CARD_H + GAP),
691 [side > 0 ? "right" : "left"]: INSET,
692 width: CARD_W,
693 height: CARD_H,
694 borderRadius: 14,
695 color: "transparent", // drawn on the holographic card
696 textDecoration: "none",
697 pointerEvents: isOpen ? "auto" : "none",
698 });
699
700 return (
701 <div ref={root} style={anchor}>
702 <style>{`.holo-nav-link:focus-visible,.holo-nav-badge:focus-visible{outline:2px solid ${badgeColor};outline-offset:3px}`}</style>
703 <NavCanvas pauseWhenOffscreen={pauseWhenOffscreen} lowPowerMode={lowPowerMode}>
704 <Badge layout={layout} open={open} hoveredBadge={hoveredBadge} color={badgeColor} />
705 {items.map((item, i) => (
706 <Card key={item.id} label={item.label} index={i} layout={layout} open={open} hovered={hovered} color={badgeColor} geometry={cardGeometry} reducedMotion={reducedMotion} />
707 ))}
708 </NavCanvas>
709 <button
710 type="button"
711 className="holo-nav-badge"
712 aria-expanded={isOpen}
713 aria-label={isOpen ? "Close menu" : "Open menu"}
714 onClick={() => setOpen(!isOpen)}
715 onPointerEnter={() => (hoveredBadge.current = true)}
716 onPointerLeave={() => (hoveredBadge.current = false)}
717 style={{ ...BUTTON_RESET, position: "absolute", top: INSET, [side > 0 ? "right" : "left"]: INSET, width: BADGE, height: BADGE, borderRadius: 16, pointerEvents: "auto" }}
718 />
719 <nav aria-label="Main" hidden={!isOpen} style={{ ...FILL, pointerEvents: "none" }}>
720 {items.map((item, i) => {
721 const common = {
722 className: "holo-nav-link",
723 onPointerEnter: () => (hovered.current = i),
724 onPointerLeave: () => {
725 if (hovered.current === i) hovered.current = -1;
726 },
727 onFocus: () => (hovered.current = i),
728 onBlur: () => (hovered.current = -1),
729 style: linkStyle(i),
730 };
731 const choose = () => {
732 onSelect?.(item.id);
733 setOpen(false);
734 };
735 return item.href ? (
736 <a
737 key={item.id}
738 href={item.href}
739 ref={(el) => {
740 if (i === 0) firstLink.current = el;
741 }}
742 onClick={choose}
743 {...common}
744 >
745 {item.label}
746 </a>
747 ) : (
748 <button
749 key={item.id}
750 type="button"
751 ref={(el) => {
752 if (i === 0) firstLink.current = el;
753 }}
754 onClick={choose}
755 {...common}
756 >
757 {item.label}
758 </button>
759 );
760 })}
761 </nav>
762 </div>
763 );
764}
765
766export default memo(DiscreteHoloBurgerNavbar3D);
03

Drop it in a page

Updated live with the settings above.

app/page.tsx
1import DiscreteHoloBurgerNavbar3D from "@/components/DiscreteHoloBurgerNavbar3D";
2
3export default function Section() {
4 return (
5 // The component fills this box: give it a position and a height
6 <div style={{ position: "relative", width: "100%", height: "100vh" }}>
7 <DiscreteHoloBurgerNavbar3D
8 items={[
9 { id: "home", label: "Home" },
10 { id: "projects", label: "Projects" },
11 { id: "about", label: "About" },
12 { id: "contact", label: "Contact" },
13 ]}
14 menuPosition="top-right"
15 badgeColor="#22d3ee"
16 onSelect={(id) => console.log(id)}
17 />
18 </div>
19 );
20}
Next componentSnake Roadmap→