Moonlight Header
A header cluster (notifications, a night-mode switch and a profile menu) that falls into moonlight together. Click it, or drag and throw the knob: it is a spring-driven body that glides into the moon's socket, which eclipses it into a thin glowing rim around a solid little moon, and at night the rim waxes and wanes as your cursor moves over it. Night spreads out of the moon across the page; the bell, name, separators and menu all turn over with it, and a Three.js beam of moonlight pours out of the moon down the page with dust drifting through it, leaning after your cursor while the dust parts around it. The bell rings on hover and the profile menu opens with a smooth staggered reveal.
Tweak
LIVELIVEHeader
Photo avatar (off: initials)
Unread notifications
Light
Beam and dust across the page
Page (demo only)
Size
Usage
Follows your tweaks.
import { MoonlightHeader } from "@/components/inreact/moonlight-header";
// sets <html data-theme="light|dark"> the moment the switch is flipped
export function TopBar() {
return (
<header className="flex justify-end px-6 py-4">
<MoonlightHeader
applyToDocument
name="Alex Morgan"
avatarSrc="/me.jpg"
unread={3}
menu={[{ label: "Profile", href: "/me" }, { label: "Settings", href: "/settings" }, { label: "Sign out", onSelect: signOut }]}
/>
</header>
);
}
// only the switch, with its beam:
// import { MoonlightSwitch } from "@/components/inreact/moonlight-header";
/* in your CSS (ease the page into the night):
:root { background: var(--bg); transition: background-color .35s ease; }
:root[data-theme="light"] { --bg: #f0f0fc; }
:root[data-theme="dark"] { --bg: #22253b; } */Install with the CLI
npx shadcn@latest add https://inreact.vercel.app/r/moonlight-header.jsonOr copy the source
Install the dependencies, then save this as components/inreact/moonlight-header.tsx.
npm install gsap three"use client";
import { gsap } from "gsap";
import * as THREE from "three";
import { useCallback, useEffect, useLayoutEffect, useRef, useState, type CSSProperties, type KeyboardEvent, type MutableRefObject, type PointerEvent as ReactPointerEvent } from "react";
/**
* Moonlight Header: a header cluster (notifications, a night-mode switch and a
* profile menu) that falls into moonlight together.
*
* By day the switch is a soft pill with a white knob and an outlined moon.
* Switch it on and the knob glides into the moon's socket, which eclipses it
* into a thin glowing rim wrapped around a solid little moon, a single moon.
* Every piece turns over with it, and a beam of moonlight (Three.js) falls
* across the page with dust drifting through it; the beam leans after your
* cursor and the dust parts around it.
*
* <MoonlightHeader name="Alex Morgan" applyToDocument />
* // or just the switch, with its beam:
* <MoonlightSwitch value={theme} onValueChange={setTheme} />
*
* The switch is a real switch (role="switch"); the menu is a menu with arrow
* keys and Escape. Reduced motion: instant flips, a still beam, no dust.
*/
export type Theme = "light" | "dark";
const reduced = () => typeof window !== "undefined" && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
function rgb(hex: string): [number, number, number] {
const h = hex.replace("#", "");
const n = parseInt(h.length === 3 ? h.replace(/./g, "$&$&") : h.slice(0, 6), 16);
return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
}
const rgba = (hex: string, a: number) => `rgba(${rgb(hex).join(", ")}, ${a})`;
// shared palette for the two themes
const INK = { light: "#2a2c3e", dark: "#e9ebff" };
const ICON = { light: "#4a4d63", dark: "#c9cdf0" };
const LINE = { light: "rgba(28,30,70,.10)", dark: "rgba(200,205,255,.13)" };
// colours turn over as the night (spreading out of the moon) reaches them, and back as it withdraws
const fade = (theme: Theme, props: string) =>
props
.split(",")
.map((x) => `${x.trim()} .4s ease ${theme === "dark" ? ".22s" : ".42s"}`)
.join(", ");
/* ------------------------------------------------------------------------ */
/* Moonbeam: a cone of moonlight with drifting dust, drawn with Three.js */
/* ------------------------------------------------------------------------ */
const BEAM_VERT = /* glsl */ `
varying vec2 vUv;
void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }
`;
const BEAM_FRAG = /* glsl */ `
precision highp float;
uniform vec2 uSize; // canvas size, css px
uniform vec2 uApex; // the moon, css px, y up
uniform float uAngle; // radians from straight down, positive leans left
uniform float uOn;
uniform float uReach; // how far the light has poured, css px
uniform float uTime;
uniform float uUnit; // switch height, css px
uniform vec3 uColor;
varying vec2 vUv;
float hash(vec2 p) { return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453); }
float noise(vec2 p) {
vec2 i = floor(p), f = fract(p);
vec2 u = f * f * (3.0 - 2.0 * f);
return mix(mix(hash(i), hash(i + vec2(1, 0)), u.x), mix(hash(i + vec2(0, 1)), hash(i + vec2(1, 1)), u.x), u.y);
}
void main() {
vec2 p = vUv * uSize;
vec2 d = p - uApex;
vec2 dir = vec2(-sin(uAngle), -cos(uAngle));
vec2 nrm = vec2(-dir.y, dir.x);
float along = dot(d, dir);
float across = dot(d, nrm);
// a soft cone that leaves the moon about a knob wide
float halfW = uUnit * 0.42 + max(along, 0.0) * 0.36;
float t = abs(across) / halfW;
float cone = exp(-t * t * 2.4);
float start = smoothstep(-uUnit * 0.2, uUnit * 0.9, along);
float fall = exp(-max(along, 0.0) / (uUnit * 5.5));
// faint shafts drifting slowly through it
float ang = across / halfW;
float shafts = 0.78 + 0.44 * noise(vec2(ang * 3.2, along / (uUnit * 6.0) - uTime * 0.05));
// the moon's own halo
float halo = exp(-length(d) / (uUnit * 0.9)) * 0.35;
// fade to nothing well before every edge of the canvas, so it never shows a border
vec2 e = min(vUv, 1.0 - vUv);
float edge = smoothstep(0.0, 0.12, e.x) * smoothstep(0.0, 0.12, e.y);
halo *= 1.0 - smoothstep(uUnit * 1.4, uUnit * 2.6, length(d));
float reach = 1.0 - smoothstep(uReach - uUnit * 3.0, uReach, along);
float I = (cone * start * fall * shafts * 0.78 * reach + halo) * uOn * edge;
vec3 col = max(uColor * I + (hash(p + uTime) - 0.5) / 255.0 * smoothstep(0.0, 0.02, I), 0.0); // dithered only where lit: no banding, no visible canvas edge
gl_FragColor = vec4(col, clamp(max(col.r, max(col.g, col.b)), 0.0, 1.0));
}
`;
const DUST_VERT = /* glsl */ `
attribute float aGlow;
attribute float aSize;
uniform float uDpr;
varying float vGlow;
void main() {
vGlow = aGlow;
gl_PointSize = aSize * uDpr;
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
`;
const DUST_FRAG = /* glsl */ `
precision highp float;
uniform vec3 uColor;
varying float vGlow;
void main() {
float r = length(gl_PointCoord - 0.5) * 2.0;
float a = smoothstep(1.0, 0.2, r) * vGlow;
vec3 c = mix(uColor, vec3(1.0), 0.6) * a;
gl_FragColor = vec4(c, a);
}
`;
const DUST = 70;
interface BeamHandle {
setOn: (on: boolean) => void;
}
function Moonbeam({ unit, apex, moonlight, handle }: { unit: number; apex: { x: number; y: number }; moonlight: string; handle: MutableRefObject<BeamHandle | null> }) {
const hostRef = useRef<HTMLSpanElement>(null);
const CW = Math.round(unit * 13);
const CH = Math.round(unit * 14);
// the apex sits near the canvas' upper right; the beam falls down-left
const left = apex.x - CW * 0.74;
const top = apex.y - CH * 0.22;
const ax = CW * 0.74;
const ay = CH - CH * 0.22; // y up
useEffect(() => {
const host = hostRef.current;
if (!host) return;
const still = reduced();
// a fresh canvas per mount, so a remount never reuses a lost context
const canvas = document.createElement("canvas");
canvas.style.cssText = "position:absolute;inset:0;width:100%;height:100%;";
host.appendChild(canvas);
let renderer: THREE.WebGLRenderer;
try {
renderer = new THREE.WebGLRenderer({ canvas, alpha: true, premultipliedAlpha: true, antialias: false, powerPreference: "high-performance" });
} catch {
canvas.remove();
return;
}
const dpr = Math.min(window.devicePixelRatio || 1, 2);
renderer.setPixelRatio(dpr);
renderer.setSize(CW, CH, false);
renderer.setClearColor(0x000000, 0);
const scene = new THREE.Scene();
const camera = new THREE.OrthographicCamera(0, CW, CH, 0, -1, 1);
const [r, g, b] = rgb(moonlight).map((v) => v / 255);
const color = new THREE.Color(r, g, b);
const beamMat = new THREE.ShaderMaterial({
vertexShader: BEAM_VERT,
fragmentShader: BEAM_FRAG,
transparent: true,
depthTest: false,
blending: THREE.CustomBlending,
blendSrc: THREE.OneFactor,
blendDst: THREE.OneMinusSrcAlphaFactor,
uniforms: {
uSize: { value: new THREE.Vector2(CW, CH) },
uApex: { value: new THREE.Vector2(ax, ay) },
uAngle: { value: (24 * Math.PI) / 180 },
uOn: { value: 0 },
uReach: { value: 0 },
uTime: { value: 0 },
uUnit: { value: unit },
uColor: { value: color },
},
});
const quad = new THREE.Mesh(new THREE.PlaneGeometry(CW, CH), beamMat);
quad.position.set(CW / 2, CH / 2, 0);
scene.add(quad);
// dust drifting in the moonlight
const pos = new Float32Array(DUST * 3);
const vel = new Float32Array(DUST * 2);
const glow = new Float32Array(DUST);
const size = new Float32Array(DUST);
const seed = new Float32Array(DUST);
const u = beamMat.uniforms;
const inCone = (x: number, y: number) => {
const a = u.uAngle.value as number;
const dx = x - ax, dy = y - ay;
const dirx = -Math.sin(a), diry = -Math.cos(a);
const along = dx * dirx + dy * diry;
const across = dx * -diry + dy * dirx;
const hw = unit * 0.42 + Math.max(along, 0) * 0.36;
const t = Math.abs(across) / hw;
const s = Math.min(1, Math.max(0, (along - unit * 0.6) / (unit * 1.2)));
const reach = 1 - Math.min(1, Math.max(0, (along - ((u.uReach.value as number) - unit * 3)) / (unit * 3)));
return Math.exp(-t * t * 2.4) * s * Math.exp(-Math.max(along, 0) / (unit * 6)) * reach;
};
const spawn = (i: number, burst: boolean) => {
const a = u.uAngle.value as number;
const along = burst ? unit * (0.6 + Math.random() * 0.8) : unit * (0.8 + Math.random() * 7);
const across = (Math.random() - 0.5) * 1.4 * (unit * 0.42 + along * 0.36);
const dirx = -Math.sin(a), diry = -Math.cos(a);
pos[i * 3] = ax + dirx * along - diry * across;
pos[i * 3 + 1] = ay + diry * along + dirx * across;
vel[i * 2] = burst ? dirx * (20 + Math.random() * 40) + (Math.random() - 0.5) * 30 : 0;
vel[i * 2 + 1] = burst ? diry * (20 + Math.random() * 40) + (Math.random() - 0.5) * 30 : 0;
size[i] = 1.4 + Math.random() * 1.8;
seed[i] = Math.random() * 100;
};
for (let i = 0; i < DUST; i++) spawn(i, false);
const geo = new THREE.BufferGeometry();
geo.setAttribute("position", new THREE.BufferAttribute(pos, 3));
geo.setAttribute("aGlow", new THREE.BufferAttribute(glow, 1));
geo.setAttribute("aSize", new THREE.BufferAttribute(size, 1));
const dustMat = new THREE.ShaderMaterial({
vertexShader: DUST_VERT,
fragmentShader: DUST_FRAG,
transparent: true,
depthTest: false,
blending: THREE.CustomBlending,
blendSrc: THREE.OneFactor,
blendDst: THREE.OneFactor,
uniforms: { uDpr: { value: dpr }, uColor: { value: color } },
});
const dust = new THREE.Points(geo, dustMat);
if (!still) scene.add(dust);
// compile the shaders now, not on the first night switch (that compile would stall a frame)
renderer.compile(scene, camera);
// the cursor, in canvas space (y up)
const mouse = { x: -1e4, y: -1e4 };
const angle = { v: 24 };
const lean = gsap.quickTo(angle, "v", { duration: 1.2, ease: "power3.out" });
const onMove = (e: PointerEvent) => {
const rc = host.getBoundingClientRect();
mouse.x = e.clientX - rc.left;
mouse.y = CH - (e.clientY - rc.top);
if (still) return;
const dx = (mouse.x - ax) / (unit * 10);
lean(24 - Math.max(-1, Math.min(1, dx)) * 7);
};
window.addEventListener("pointermove", onMove, { passive: true });
let visible = true;
const io = new IntersectionObserver(([e]) => (visible = e.isIntersecting));
io.observe(host);
const t0 = performance.now();
let last = t0;
let cleared = false;
const tick = () => {
const now = performance.now();
const dt = Math.min(0.05, (now - last) / 1000);
last = now;
if (!visible) return;
const on = u.uOn.value as number;
// off: clear once and idle. The canvas stays composited (never hidden), so switching on
// doesn't have to build a new layer in the middle of the transition
if (on < 0.002) {
if (!cleared) {
renderer.clear();
cleared = true;
}
return;
}
cleared = false;
const time = (now - t0) / 1000;
u.uTime.value = time;
u.uAngle.value = (angle.v * Math.PI) / 180;
if (!still) {
const R = unit * 1.6;
for (let i = 0; i < DUST; i++) {
let x = pos[i * 3], y = pos[i * 3 + 1];
let vx = vel[i * 2], vy = vel[i * 2 + 1];
// a slow drift, like dust settling through still air
const s = seed[i];
vx += (Math.sin(time * 0.31 + s) * 6 - vx * 1.4) * dt;
vy += (Math.cos(time * 0.27 + s * 1.7) * 5 - 3 - vy * 1.4) * dt;
// parting around the cursor
const mx = x - mouse.x, my = y - mouse.y;
const md = Math.hypot(mx, my);
if (md < R && md > 0.01) {
const f = (1 - md / R) ** 2 * 900;
vx += (mx / md) * f * dt;
vy += (my / md) * f * dt;
}
x += vx * dt;
y += vy * dt;
pos[i * 3] = x;
pos[i * 3 + 1] = y;
vel[i * 2] = vx;
vel[i * 2 + 1] = vy;
const c = inCone(x, y);
glow[i] = c * on * (0.55 + 0.45 * Math.sin(time * (0.8 + (s % 1.3)) + s)) ;
if (c < 0.01 && on > 0.9) spawn(i, false);
}
geo.attributes.position.needsUpdate = true;
geo.attributes.aGlow.needsUpdate = true;
geo.attributes.aSize.needsUpdate = true;
}
renderer.render(scene, camera);
};
gsap.ticker.add(tick);
handle.current = {
setOn(on) {
if (still) {
u.uOn.value = on ? 1 : 0;
return;
}
if (on) {
for (let i = 0; i < DUST; i += 5) spawn(i, true); // dust lifts off the moon as it lights
// the light pours out of the moon and runs down the page
gsap.fromTo(u.uReach, { value: (u.uOn.value as number) > 0.5 ? (u.uReach.value as number) : 0 }, { value: CH * 1.3, duration: 1.5, ease: "power2.out", delay: 0.32, overwrite: true });
gsap.to(u.uOn, { value: 1, duration: 0.6, ease: "power2.out", delay: 0.28, overwrite: true }); // once the night has reached it
} else {
// and draws back up into it
gsap.to(u.uReach, { value: 0, duration: 0.55, ease: "power3.in", overwrite: true });
gsap.to(u.uOn, { value: 0, duration: 0.35, ease: "power2.in", delay: 0.25, overwrite: true });
}
},
};
return () => {
handle.current = null;
gsap.ticker.remove(tick);
gsap.killTweensOf(u.uOn);
gsap.killTweensOf(u.uReach);
window.removeEventListener("pointermove", onMove);
io.disconnect();
geo.dispose();
dustMat.dispose();
beamMat.dispose();
quad.geometry.dispose();
renderer.dispose();
canvas.remove();
};
}, [CW, CH, ax, ay, unit, moonlight, handle]);
return <span ref={hostRef} aria-hidden="true" className="pointer-events-none absolute block" style={{ left, top, width: CW, height: CH, zIndex: 0 }} />; // premultiplied light, composited normally: a blend mode here would force everything beneath to re-raster every frame
}
/* ------------------------------------------------------------------------ */
/* The switch */
/* ------------------------------------------------------------------------ */
export type MoonOrigin = { x: number; y: number };
export interface MoonlightSwitchProps {
value?: Theme;
defaultValue?: Theme;
/** Called the moment it is switched, with the moon's position on screen (spread the night from it). */
onValueChange?: (theme: Theme, origin: MoonOrigin) => void;
/** Set data-theme and color-scheme on <html>; where the browser can, the new theme spreads out from the moon. */
applyToDocument?: boolean;
/** Colour of the moonlight (the moon's rim, the beam and the dust). */
moonlight?: string;
/** Cast a beam of moonlight across the page at night. */
beam?: boolean;
/** Height in px. */
size?: number;
className?: string;
"aria-label"?: string;
}
let vtStyled = false;
// flip <html>, spreading the new theme out of the moon with a view transition where supported
function applyTheme(next: Theme, o: MoonOrigin) {
const root = document.documentElement;
const flip = () => {
root.dataset.theme = next;
root.style.colorScheme = next;
};
const doc = document as Document & { startViewTransition?: (cb: () => void) => { ready: Promise<void> } };
if (!doc.startViewTransition || reduced()) return flip();
if (!vtStyled) {
vtStyled = true;
const st = document.createElement("style");
st.textContent = "::view-transition-old(root),::view-transition-new(root){animation:none;mix-blend-mode:normal}";
document.head.appendChild(st);
}
const r = Math.hypot(Math.max(o.x, innerWidth - o.x), Math.max(o.y, innerHeight - o.y));
doc
.startViewTransition(flip)
.ready.then(() => {
root.animate({ clipPath: [`circle(0px at ${o.x}px ${o.y}px)`, `circle(${r}px at ${o.x}px ${o.y}px)`] }, { duration: 1000, easing: "cubic-bezier(.65,0,.35,1)", pseudoElement: "::view-transition-new(root)" });
})
.catch(() => {});
}
function useTheme(value: Theme | undefined, defaultValue: Theme, onValueChange: ((t: Theme, o: MoonOrigin) => void) | undefined, applyToDocument: boolean) {
const [inner, setInner] = useState<Theme>(defaultValue);
const theme = value ?? inner;
const set = useCallback(
(next: Theme, origin: MoonOrigin) => {
if (applyToDocument && typeof document !== "undefined") applyTheme(next, origin);
if (value === undefined) setInner(next);
onValueChange?.(next, origin);
},
[applyToDocument, onValueChange, value],
);
return [theme, set] as const;
}
export function MoonlightSwitch({ value, defaultValue = "light", onValueChange, applyToDocument = false, moonlight = "#9aa6ff", beam = true, size = 44, className, "aria-label": ariaLabel = "Night mode" }: MoonlightSwitchProps) {
const [theme, setTheme] = useTheme(value, defaultValue, onValueChange, applyToDocument);
const night = theme === "dark";
const beamRef = useRef<BeamHandle | null>(null);
const rootRef = useRef<HTMLButtonElement>(null);
const q = useRef<Record<string, HTMLElement | SVGElement | null>>({});
const set = (k: string) => (el: HTMLElement | SVGElement | null) => {
q.current[k] = el;
};
const tl = useRef<gsap.core.Timeline | null>(null);
const nightRef = useRef(night);
nightRef.current = night;
const h = size;
const W = Math.round(h * 1.92);
const k = Math.round(h * 0.8); // knob
const pad = (h - k) / 2;
// the knob travels all the way to the other end, over the little moon, and becomes the moon itself
const endX = W - pad - k / 2;
const sx = endX; // where the moon rests (and the day icon sits)
const sy = h / 2;
const rs = k * 0.47; // the shadow that turns the disc into a crescent
const travel = endX - (pad + k / 2);
const m = Math.round(k * 0.5); // room around the knob so its shadow and glow aren't masked away
const iconSize = Math.round(k * 0.6);
// the knob is a real body: a spring pulls it to its side, a drag moves it directly
const phys = useRef({ x: night ? travel : 0, v: 0, target: night ? travel : 0, drag: false });
const lean = useRef<{ x: (v: number) => void; y: (v: number) => void } | null>(null);
// everything else (the sky, the glow, the stars) follows how far across the knob is
useLayoutEffect(() => {
const $ = q.current;
const t = gsap.timeline({ paused: true, defaults: { ease: "none" } });
t.to($.trackNight!, { opacity: 1, duration: 0.5 }, 0.05)
.to($.track!, { boxShadow: `inset 0 1px 2px rgba(0,0,0,.30), inset 0 2px 6px rgba(0,0,0,.22), inset 0 0 0 1px ${rgba(moonlight, 0.16)}, 0 1px 0 rgba(255,255,255,0)`, duration: 0.5 }, 0.05)
.to($.dayDisc!, { opacity: 0, duration: 0.4 }, 0.3)
.to($.glow!, { filter: `drop-shadow(0 0 ${Math.max(1, h * 0.04)}px rgba(240,243,255,.95)) drop-shadow(0 0 ${h * 0.22}px ${rgba(moonlight, 0.85)})`, duration: 0.45 }, 0.4)
.to($.icon!, { opacity: 0, scale: 0.55, duration: 0.3 }, 0.42)
.to(gsap.utils.toArray<HTMLElement>(rootRef.current!.querySelectorAll("[data-star]")), { opacity: 1, scale: 1, duration: 0.25, stagger: 0.05 }, 0.55);
tl.current = t;
const p = phys.current;
p.x = p.target = nightRef.current ? travel : 0;
p.v = 0;
t.progress(nightRef.current ? 1 : 0);
return () => {
t.kill();
};
}, [travel, h, moonlight]);
// the frame loop: spring, stretch, scrub the look, and shade the knob into a crescent
useEffect(() => {
const $ = q.current;
const still = reduced();
lean.current = {
x: gsap.quickTo($.knobInner!, "x", { duration: 0.7, ease: "power3.out" }),
y: gsap.quickTo($.knobInner!, "y", { duration: 0.7, ease: "power3.out" }),
};
let lastP = -1;
// last written values: only touch the DOM when something actually changed
const last = { x: Infinity, st: Infinity, ex: "", ey: "" }; // Infinity, not NaN: NaN never compares as changed
const step = (_t: number, dms: number) => {
const p = phys.current;
const dt = Math.min(0.032, dms / 1000);
if (!p.drag) {
if (still) {
p.x = p.target;
p.v = 0;
} else if (p.x !== p.target || p.v !== 0) {
// slightly under-damped: it glides, sinks a hair past its rest, and settles (~0.5s)
const acc = 200 * (p.target - p.x) - 19 * p.v;
p.v += acc * dt;
p.x += p.v * dt;
// it can't leave the track: it bumps softly off the day end, and off the night end
if (p.x < -pad * 0.8) {
p.x = -pad * 0.8;
p.v = Math.abs(p.v) * 0.35;
}
if (p.x > travel + pad * 0.8) {
p.x = travel + pad * 0.8;
p.v = -Math.abs(p.v) * 0.35;
}
if (Math.abs(p.target - p.x) < 0.02 && Math.abs(p.v) < 0.5) {
p.x = p.target;
p.v = 0;
}
}
}
if (Math.abs(p.x - last.x) > 0.01) {
last.x = p.x;
gsap.set($.knob!, { x: p.x });
}
// speed stretches it a little along its path
const st = still ? 0 : Math.min(Math.abs(p.v) / (travel * 22), 0.06);
if (Math.abs(st - last.st) > 0.0005) {
last.st = st;
gsap.set($.knobBody!, { scaleX: 1 + st, scaleY: 1 - st * 0.5 });
}
const prog = gsap.utils.clamp(0, 1, p.x / travel);
if (prog !== lastP) {
tl.current?.progress(prog);
lastP = prog;
}
const el = $.eclipse as HTMLElement | null;
if (el) {
// a moon phase on the knob itself: the shadow sweeps in from the upper right as it crosses,
// and the cursor nudges it, so the crescent waxes and wanes
const ph = gsap.utils.clamp(0, 1, (prog - 0.3) / 0.7);
const e = ph * ph * (3 - 2 * ph);
const ix = gsap.getProperty($.knobInner!, "x") as number, iy = gsap.getProperty($.knobInner!, "y") as number;
const ex = `${(k * (1.15 - 0.83 * e) + ix * 3.2).toFixed(2)}px`, ey = `${(-k * (0.55 - 0.37 * e) + iy * 2.4).toFixed(2)}px`;
if (ex !== last.ex) el.style.setProperty("--ex", (last.ex = ex));
if (ey !== last.ey) el.style.setProperty("--ey", (last.ey = ey));
}
};
gsap.ticker.add(step);
return () => {
gsap.ticker.remove(step);
lean.current = null;
};
}, [pad, k, h, sx, sy, travel]);
// a theme from outside (or a click) sets where the knob is heading
useEffect(() => {
phys.current.target = night ? travel : 0;
beamRef.current?.setOn(night);
}, [night, travel]);
// the beam mounts after the switch; give it the current state
useEffect(() => {
const id = requestAnimationFrame(() => beamRef.current?.setOn(nightRef.current));
return () => cancelAnimationFrame(id);
}, [beam, h, moonlight]);
// stars twinkle
useEffect(() => {
if (reduced()) return;
const ctx = gsap.context(() => {
rootRef.current!.querySelectorAll("[data-twinkle]").forEach((s, i) => {
gsap.to(s, { opacity: 0.2, duration: 1.1 + i * 0.37, ease: "sine.inOut", yoyo: true, repeat: -1, delay: i * 0.4 });
});
});
return () => ctx.revert();
}, []);
const origin = (): MoonOrigin => {
const r = rootRef.current!.getBoundingClientRect();
return { x: r.left + sx, y: r.top + sy };
};
const commit = (next: Theme) => {
phys.current.target = next === "dark" ? travel : 0;
setTheme(next, origin());
};
const press = (down: boolean) => {
if (reduced()) return;
gsap.to(q.current.knobInner!, down ? { scale: 0.93, duration: 0.18, ease: "power2.out", overwrite: "auto" } : { scale: 1, duration: 0.7, ease: "elastic.out(1, 0.45)", overwrite: "auto" });
};
// dragging: rubber-bands past the ends, and the throw decides the side
const drag = useRef<{ id: number; x0: number; k0: number; moved: boolean; lx: number; lt: number; v: number } | null>(null);
const rubber = (o: number, lim: number) => lim * (1 - Math.exp(-o / lim));
const onDown = (e: ReactPointerEvent<HTMLButtonElement>) => {
if (e.button !== 0) return;
e.currentTarget.setPointerCapture(e.pointerId);
drag.current = { id: e.pointerId, x0: e.clientX, k0: phys.current.x, moved: false, lx: e.clientX, lt: performance.now(), v: 0 };
press(true);
};
const onMove = (e: ReactPointerEvent<HTMLButtonElement>) => {
// the knob drifts after the cursor: at night the moon's rim waxes and wanes as you move
const r = e.currentTarget.getBoundingClientRect();
const nx = gsap.utils.clamp(-1, 1, (e.clientX - (r.left + pad + k / 2 + phys.current.x)) / k);
const ny = gsap.utils.clamp(-1, 1, (e.clientY - (r.top + h / 2)) / (h * 0.7));
if (!reduced() && !drag.current?.moved) {
lean.current?.x(nx * h * 0.04);
lean.current?.y(ny * h * 0.03);
}
const d = drag.current;
if (!d || d.id !== e.pointerId) return;
const dx = e.clientX - d.x0;
if (!d.moved && Math.abs(dx) < 4) return;
if (!d.moved) {
d.moved = true;
lean.current?.x(0);
lean.current?.y(0);
}
const now = performance.now();
d.v = d.v * 0.5 + (((e.clientX - d.lx) / Math.max(1, now - d.lt)) * 1000) * 0.5;
d.lx = e.clientX;
d.lt = now;
let x = d.k0 + dx;
// the track holds it: a hair of give at the day end, a little more into the socket
if (x < 0) x = -rubber(-x, pad * 0.8);
if (x > travel) x = travel + rubber(x - travel, k * 0.12);
const p = phys.current;
p.drag = true;
p.v = d.v;
p.x = x;
};
const onUp = (e: ReactPointerEvent<HTMLButtonElement>, cancel = false) => {
const d = drag.current;
if (!d || d.id !== e.pointerId) return;
drag.current = null;
phys.current.drag = false;
press(false);
if (cancel) return void (phys.current.target = nightRef.current ? travel : 0);
if (!d.moved) return commit(nightRef.current ? "light" : "dark");
const next: Theme = phys.current.x + d.v * 0.12 > travel / 2 ? "dark" : "light";
if ((next === "dark") !== nightRef.current) commit(next);
else phys.current.target = nightRef.current ? travel : 0;
};
const eclipseMask = `radial-gradient(circle at calc(50% + var(--ex)) calc(50% + var(--ey)), transparent ${(rs - 0.6).toFixed(2)}px, #000 ${(rs + 0.6).toFixed(2)}px)`;
return (
<button
ref={rootRef}
type="button"
role="switch"
aria-checked={night}
aria-label={ariaLabel}
// pointers are handled below; this is the keyboard (Space / Enter)
onClick={(e) => e.detail === 0 && commit(night ? "light" : "dark")}
onPointerDown={onDown}
onPointerMove={onMove}
onPointerUp={(e) => onUp(e)}
onPointerCancel={(e) => onUp(e, true)}
onPointerLeave={() => {
lean.current?.x(0);
lean.current?.y(0);
}}
className={["relative inline-block shrink-0 cursor-pointer touch-none select-none rounded-full outline-none [-webkit-tap-highlight-color:transparent] focus-visible:ring-1 focus-visible:ring-current/40 focus-visible:ring-offset-4 focus-visible:ring-offset-transparent", className].filter(Boolean).join(" ")}
style={{ width: W, height: h, color: night ? INK.dark : INK.light }}
>
{beam && <Moonbeam unit={h} apex={{ x: sx, y: sy }} moonlight={moonlight} handle={beamRef} />}
{/* the track: a soft inset pill by day, a deep night sky lit by the moon */}
<span
ref={set("track")}
aria-hidden="true"
className="absolute inset-0 overflow-hidden rounded-full"
style={{ zIndex: 1, background: "linear-gradient(90deg, #eeeff9, #d9dbee)", boxShadow: "inset 0 1px 2px rgba(28,30,70,.10), inset 0 2px 6px rgba(28,30,70,.06), inset 0 0 0 1px rgba(28,30,70,.04), 0 1px 0 rgba(255,255,255,.9)" }}
>
<span
ref={set("trackNight")}
className="absolute inset-0 rounded-full opacity-0"
style={{ background: `radial-gradient(circle at ${((sx - k * 0.1) / W) * 100}% 70%, ${rgba(moonlight, 0.62)} 0%, ${rgba(moonlight, 0.24)} 34%, ${rgba(moonlight, 0)} 62%), radial-gradient(120% 70% at 55% 115%, ${rgba(moonlight, 0.28)}, ${rgba(moonlight, 0)} 70%), linear-gradient(180deg, #191c32, #272c4a)` }}
/>
</span>
{/* the little moon in its socket: outlined by day, solid at night */}
<span ref={set("icon")} aria-hidden="true" className="absolute" style={{ zIndex: 2, width: iconSize, height: iconSize, left: sx - iconSize / 2, top: sy - iconSize / 2, filter: `drop-shadow(0 0 0px ${rgba(moonlight, 0)})` }}>
<svg viewBox="0 0 24 24" width="100%" height="100%" style={{ overflow: "visible" }}>
<path ref={set("iconPath")} d="M20.2 14.4A8.4 8.4 0 0 1 9.6 3.8a8.4 8.4 0 1 0 10.6 10.6Z" fill="#eef0ff" fillOpacity={0} stroke={ICON.light} strokeOpacity={1} strokeWidth={1.7} strokeLinejoin="round" />
</svg>
</span>
{/* the knob: a white disc by day; at the far end a shadow sweeps over it and it becomes the glowing crescent moon */}
<span ref={set("knob")} aria-hidden="true" className="absolute" style={{ zIndex: 3, left: pad, top: pad, width: k, height: k }}>
<span ref={set("knobInner")} className="absolute inset-0">
<span ref={set("knobBody")} className="absolute inset-0">
<span ref={set("glow")} className="absolute" style={{ inset: -m, filter: `drop-shadow(0 0 0px rgba(240,243,255,0)) drop-shadow(0 0 0px ${rgba(moonlight, 0)})` }}>
<span ref={set("eclipse")} className="absolute inset-0" style={{ "--ex": "999px", "--ey": "0px", WebkitMaskImage: eclipseMask, maskImage: eclipseMask } as CSSProperties}>
<span className="absolute rounded-full" style={{ inset: m, background: "radial-gradient(circle at 30% 70%, #ffffff, #eef0ff 55%, #dfe3ff)" }} />
<span
ref={set("dayDisc")}
className="absolute rounded-full"
style={{
inset: m,
background: "radial-gradient(circle at 36% 30%, #ffffff 0%, #f6f6fb 45%, #e8e9f3 100%)",
boxShadow: "0 1px 1px rgba(28,30,70,.06), 0 2px 4px rgba(28,30,70,.06), 0 4px 8px rgba(28,30,70,.06), 0 8px 16px rgba(28,30,70,.05), inset 0 -1px 1px rgba(28,30,70,.05), inset 0 1px 0 #fff",
}}
/>
</span>
</span>
</span>
</span>
</span>
{/* stars */}
{[
{ x: 0.95, y: -0.12 },
{ x: 0.4, y: -0.22 },
{ x: 0.55, y: 1.2 },
{ x: 0.9, y: 1.14 },
{ x: 1.1, y: 0.5 },
].map((s, i) => (
<span key={i} data-star aria-hidden="true" className="pointer-events-none absolute opacity-0" style={{ zIndex: 2, left: Math.round(s.x * W - 1), top: Math.round(s.y * h - 1), width: 2, height: 2, transform: "scale(0.3)" }}>
<span data-twinkle className="absolute inset-0 rounded-full bg-white" />
</span>
))}
</button>
);
}
/* ------------------------------------------------------------------------ */
/* The header cluster: notifications | switch | profile menu */
/* ------------------------------------------------------------------------ */
export interface MoonlightHeaderMenuItem {
label: string;
href?: string;
onSelect?: () => void;
}
export interface MoonlightHeaderProps extends Omit<MoonlightSwitchProps, "className" | "aria-label"> {
/** The signed-in person's name. */
name?: string;
/** Avatar image; initials are drawn when it's missing. */
avatarSrc?: string;
/** Unread notifications (a dot on the bell when above 0). */
unread?: number;
onNotificationsClick?: () => void;
/** Profile menu entries. */
menu?: MoonlightHeaderMenuItem[];
className?: string;
}
function Bell({ unread, unit, theme, onClick }: { unread: number; unit: number; theme: Theme; onClick?: () => void }) {
const bell = useRef<SVGGElement>(null);
const clapper = useRef<SVGCircleElement>(null);
const dot = useRef<HTMLSpanElement>(null);
const ring = () => {
if (reduced()) return;
gsap.timeline({ overwrite: true })
.to(bell.current, { rotation: 16, duration: 0.12, ease: "power2.out", svgOrigin: "12 3" })
.to(bell.current, { rotation: -12, duration: 0.16, ease: "sine.inOut", svgOrigin: "12 3" })
.to(bell.current, { rotation: 8, duration: 0.16, ease: "sine.inOut", svgOrigin: "12 3" })
.to(bell.current, { rotation: 0, duration: 0.7, ease: "elastic.out(1, 0.35)", svgOrigin: "12 3" });
gsap.timeline({ overwrite: true })
.to(clapper.current, { x: -1.6, duration: 0.14, ease: "power2.out" })
.to(clapper.current, { x: 1.4, duration: 0.18, ease: "sine.inOut" })
.to(clapper.current, { x: 0, duration: 0.7, ease: "elastic.out(1, 0.35)" });
};
useEffect(() => {
if (!dot.current) return;
if (reduced()) return void gsap.set(dot.current, { scale: unread > 0 ? 1 : 0 });
gsap.to(dot.current, { scale: unread > 0 ? 1 : 0, duration: unread > 0 ? 0.6 : 0.25, ease: unread > 0 ? "elastic.out(1, 0.45)" : "power2.in" });
}, [unread]);
const s = Math.round(unit * 0.5);
return (
<button
type="button"
aria-label={unread > 0 ? `Notifications, ${unread} unread` : "Notifications"}
onPointerEnter={ring}
onFocus={ring}
onClick={onClick}
className="relative grid shrink-0 place-items-center rounded-full outline-none [-webkit-tap-highlight-color:transparent] focus-visible:ring-1 focus-visible:ring-current/40"
style={{ width: unit * 0.9, height: unit * 0.9, color: ICON[theme], transition: fade(theme, "color") }}
>
<svg viewBox="0 0 24 24" width={s} height={s} fill="none" stroke="currentColor" strokeWidth={1.6} strokeLinecap="round" strokeLinejoin="round" aria-hidden="true" style={{ overflow: "visible" }}>
<g ref={bell}>
<path d="M6 16.5V11a6 6 0 0 1 12 0v5.5l1.5 1.5h-15L6 16.5Z" />
<path d="M12 3v2" />
</g>
<circle ref={clapper} cx="12" cy="20.6" r="1.4" fill="currentColor" stroke="none" />
</svg>
<span ref={dot} aria-hidden="true" className="absolute rounded-full" style={{ width: unit * 0.16, height: unit * 0.16, top: unit * 0.18, right: unit * 0.2, background: "#6d7cff", boxShadow: `0 0 0 2px ${theme === "dark" ? "#22253b" : "#f0f0fc"}`, transform: "scale(0)", transition: fade(theme, "box-shadow") }} />
</button>
);
}
function initialsOf(name: string) {
return name
.split(/\s+/)
.filter(Boolean)
.slice(0, 2)
.map((w) => w[0]!.toUpperCase())
.join("");
}
function Profile({ name, avatarSrc, unit, theme, menu, moonlight }: { name: string; avatarSrc?: string; unit: number; theme: Theme; menu: MoonlightHeaderMenuItem[]; moonlight: string }) {
const [open, setOpen] = useState(false);
const wrap = useRef<HTMLDivElement>(null);
const panel = useRef<HTMLDivElement>(null);
const chev = useRef<SVGSVGElement>(null);
const items = useRef<(HTMLElement | null)[]>([]);
const hl = useRef<HTMLSpanElement>(null);
const shown = useRef(false);
const viaKeys = useRef(false);
const night = theme === "dark";
// one highlight that glides between items, like a native menu
const glideTo = (el: HTMLElement | null) => {
const h = hl.current;
if (!h || !el) return;
const r = reduced();
const to = { y: el.offsetTop, height: el.offsetHeight };
if (!shown.current) {
shown.current = true;
gsap.set(h, { ...to, scaleX: 0.97 });
gsap.to(h, { opacity: 1, scaleX: 1, duration: r ? 0 : 0.22, ease: "power2.out", overwrite: "auto" });
} else {
gsap.to(h, { ...to, opacity: 1, scaleX: 1, duration: r ? 0 : 0.42, ease: "expo.out", overwrite: "auto" });
}
};
const fadeHighlight = () => {
if (!hl.current || !shown.current) return;
shown.current = false;
gsap.to(hl.current, { opacity: 0, scaleX: 0.97, duration: reduced() ? 0 : 0.25, ease: "power2.out", overwrite: "auto" });
};
useEffect(() => {
const p = panel.current;
if (!p) return;
const r = reduced();
gsap.to(chev.current, { rotation: open ? 180 : 0, duration: r ? 0 : 0.45, ease: "power3.inOut" });
if (open) {
gsap.set(p, { display: "block" });
gsap.fromTo(p, { opacity: 0, y: -8, scale: 0.96 }, { opacity: 1, y: 0, scale: 1, duration: r ? 0 : 0.45, ease: "expo.out", overwrite: true });
gsap.fromTo(items.current.filter(Boolean), { opacity: 0, y: 5 }, { opacity: 1, y: 0, duration: r ? 0 : 0.4, ease: "expo.out", stagger: r ? 0 : 0.04, delay: r ? 0 : 0.04 });
shown.current = false;
if (hl.current) gsap.set(hl.current, { opacity: 0 });
// from the keyboard the first item takes focus; from a pointer, nothing is highlighted until you move
if (viaKeys.current) items.current[0]?.focus({ preventScroll: true });
else p.focus({ preventScroll: true });
} else {
gsap.to(p, { opacity: 0, y: -4, scale: 0.98, duration: r ? 0 : 0.2, ease: "power2.in", overwrite: true, onComplete: () => void gsap.set(p, { display: "none" }) });
}
}, [open]);
useEffect(() => {
if (!open) return;
const away = (e: PointerEvent) => !wrap.current?.contains(e.target as Node) && setOpen(false);
document.addEventListener("pointerdown", away);
return () => document.removeEventListener("pointerdown", away);
}, [open]);
const onKey = (e: KeyboardEvent) => {
if (e.key === "Escape") return setOpen(false);
if (!open) return;
const list = items.current.filter(Boolean) as HTMLElement[];
const i = list.indexOf(document.activeElement as HTMLElement);
if (e.key === "ArrowDown") {
e.preventDefault();
list[i < 0 ? 0 : (i + 1) % list.length]?.focus();
}
if (e.key === "ArrowUp") {
e.preventDefault();
list[i < 0 ? list.length - 1 : (i - 1 + list.length) % list.length]?.focus();
}
};
const av = Math.round(unit * 0.8);
return (
<div ref={wrap} className="relative" onKeyDown={onKey}>
<button
type="button"
aria-haspopup="menu"
aria-expanded={open}
onClick={(e) => {
viaKeys.current = e.detail === 0;
setOpen((o) => !o);
}}
className="group flex items-center rounded-full outline-none [-webkit-tap-highlight-color:transparent] focus-visible:ring-1 focus-visible:ring-current/40"
style={{ gap: unit * 0.24, padding: `${unit * 0.06}px ${unit * 0.12}px ${unit * 0.06}px ${unit * 0.06}px`, color: INK[theme], transition: fade(theme, "color") }}
>
<span className="relative grid shrink-0 place-items-center overflow-hidden rounded-full font-medium text-white" style={{ width: av, height: av, fontSize: av * 0.36, background: `linear-gradient(145deg, #2d3158, ${rgba(moonlight, 1)})`, boxShadow: `inset 0 0 0 1px rgba(255,255,255,.12)` }}>
{avatarSrc ? <img src={avatarSrc} alt="" className="absolute inset-0 h-full w-full object-cover" /> : initialsOf(name)}
</span>
<span className="whitespace-nowrap font-medium" style={{ fontSize: Math.round(unit * 0.34), letterSpacing: "-0.005em" }}>
{name}
</span>
<svg ref={chev} viewBox="0 0 24 24" width={unit * 0.36} height={unit * 0.36} fill="none" stroke="currentColor" strokeWidth={1.8} strokeLinecap="round" strokeLinejoin="round" aria-hidden="true" style={{ color: ICON[theme], transition: fade(theme, "color") }}>
<path d="m6 9 6 6 6-6" />
</svg>
</button>
<div
ref={panel}
role="menu"
aria-label={`${name} menu`}
tabIndex={-1}
onPointerLeave={fadeHighlight}
className="absolute right-0 z-20 hidden origin-top-right rounded-2xl p-1.5 outline-none"
style={{
top: `calc(100% + ${unit * 0.3}px)`,
minWidth: unit * 4.6,
background: night ? "#262a44" : "#ffffff",
boxShadow: night
? `inset 0 0 0 1px ${rgba(moonlight, 0.16)}, 0 2px 4px rgba(0,0,0,.12), 0 8px 16px rgba(0,0,0,.14), 0 16px 32px rgba(0,0,0,.14)`
: "inset 0 0 0 1px rgba(28,30,70,.06), 0 1px 2px rgba(28,30,70,.05), 0 4px 8px rgba(28,30,70,.05), 0 12px 24px rgba(28,30,70,.06)",
transition: fade(theme, "background-color, box-shadow"),
}}
>
{/* the highlight, gliding under the item you're on */}
<span ref={hl} aria-hidden="true" className="pointer-events-none absolute inset-x-1.5 top-0 rounded-xl opacity-0" style={{ background: night ? "rgba(255,255,255,.07)" : "rgba(28,30,70,.055)", transition: fade(theme, "background-color") }} />
{menu.map((it, i) => {
const cls = "relative block w-full rounded-xl px-3 py-2 text-left outline-none";
const style: CSSProperties = { fontSize: Math.round(unit * 0.31), color: INK[theme] };
const ref = (el: HTMLElement | null) => {
items.current[i] = el;
};
const pick = () => {
it.onSelect?.();
setOpen(false);
};
return it.href ? (
<a key={it.label} ref={ref} role="menuitem" tabIndex={-1} href={it.href} onClick={pick} onPointerEnter={(e) => glideTo(e.currentTarget)} onFocus={(e) => glideTo(e.currentTarget)} className={cls} style={style}>
{it.label}
</a>
) : (
<button key={it.label} ref={ref} role="menuitem" tabIndex={-1} type="button" onClick={pick} onPointerEnter={(e) => glideTo(e.currentTarget)} onFocus={(e) => glideTo(e.currentTarget)} className={cls} style={style}>
{it.label}
</button>
);
})}
</div>
</div>
);
}
export function MoonlightHeader({
value,
defaultValue = "light",
onValueChange,
applyToDocument = false,
moonlight = "#9aa6ff",
beam = true,
size = 44,
name = "Alex Morgan",
avatarSrc,
unread = 0,
onNotificationsClick,
menu = [{ label: "Profile" }, { label: "Settings" }, { label: "Sign out" }],
className,
}: MoonlightHeaderProps) {
const [theme, setTheme] = useTheme(value, defaultValue, onValueChange, applyToDocument);
const u = size;
const sep = <span aria-hidden="true" className="shrink-0 self-stretch" style={{ width: 1, background: LINE[theme], transition: fade(theme, "background-color") }} />;
return (
<div className={["relative inline-flex flex-col", className].filter(Boolean).join(" ")}>
<div className="relative flex items-center" style={{ gap: u * 0.5, height: u * 1.45, paddingInline: u * 0.1 }}>
<Bell unread={unread} unit={u} theme={theme} onClick={onNotificationsClick} />
{sep}
<MoonlightSwitch value={theme} onValueChange={setTheme} moonlight={moonlight} beam={beam} size={u} />
{sep}
<Profile name={name} avatarSrc={avatarSrc} unit={u} theme={theme} menu={menu} moonlight={moonlight} />
</div>
{/* the hairline under the header */}
<span aria-hidden="true" className="relative block" style={{ height: 1, marginTop: u * 0.12, background: LINE[theme], transition: fade(theme, "background-color") }} />
</div>
);
}
export default MoonlightHeader;
One prompt, any AI agent
Paste into Claude Code, Codex, Cursor or Windsurf. It carries your tweaks and the full source, so the agent installs it exactly.
Props
13 propsvalue"light" | "dark"Controlled theme.defaultValue"light" | "dark"Initial theme when uncontrolled.default "light"default "light"onValueChange(theme, origin) => voidCalled the moment it is switched, with the moon's screen position (spread the new theme from it).applyToDocumentbooleanSet data-theme and color-scheme on <html>; where supported, the new theme spreads out of the moon (View Transitions).default falsedefault falsenamestringThe signed-in person's name.default "Alex Morgan"default "Alex Morgan"avatarSrcstringAvatar image; initials are drawn when it's missing.unreadnumberUnread notifications; a dot springs onto the bell above 0.default 0default 0onNotificationsClick() => voidBell click handler.menu{ label; href?; onSelect? }[]Profile menu entries.default Profile, Settings, Sign outdefault Profile, Settings, Sign outmoonlightstringColour of the moon's rim, the beam and the dust.default "#9aa6ff"default "#9aa6ff"beambooleanCast the beam of moonlight across the page at night (it overflows, so don't clip its parents).default truedefault truesizenumberScale: the switch height in px; everything sizes from it.default 44default 44classNamestringExtra classes.