Components59 / 118
Glass Orb Toggle
A dark / light switch with a clear glass orb, larger than its pill, resting over one end. Through the glass you see the pill magnified and bent toward the rim, with a curved studio reflection under its crown and a bright fresnel edge. Switch it and the orb glides across on a spring, squashing a little along its path; the glowing moon inside turns into the sun, the labels trade places and the pill lights up. Drag it, throw it, and it leans after your cursor.
Glass shaderGlass shaderThree.jsThree.jsSpring physicsSpring physicsDraggableDraggableTheme switchTheme switchGSAPGSAP
Click or drag the orbMove near it: the glass leans
Tweak
LIVELIVELabels
Size
72px
Usage
Follows your tweaks.
usage.tsx
import { GlassOrbToggle } from "@/components/inreact/glass-orb-toggle";
// sets <html data-theme="dark|light"> when it switches
export function Header() {
return <GlassOrbToggle applyToDocument size={72} />;
}Install with the CLI
TS + Tailwind
npx shadcn@latest add https://inreact.vercel.app/r/glass-orb-toggle.jsonOr copy the source
Install the dependencies, then save this as components/inreact/glass-orb-toggle.tsx.
terminal
npm install gsap threecomponents/inreact/glass-orb-toggle.tsx
"use client";
import { gsap } from "gsap";
import * as THREE from "three";
import { useCallback, useEffect, useRef, useState, type PointerEvent as ReactPointerEvent } from "react";
/**
* Glass Orb Toggle: a dark / light switch with a drop of liquid glass gliding across it.
*
* A borderless lens of liquid glass, larger than its pill, rests over one end.
* Like Apple's Liquid Glass it has a flat top and a rounded bevel: what's under
* it warps hardest at the edge and splits into colour there, and soft
* highlights sit in the bevel facing the light, which follows your cursor.
* Switch it and the orb glides across on a spring, squashing a little along
* its path; the glowing moon inside turns into the sun, the labels trade
* places and the pill lights up. Drag it and throw it; it leans after your
* cursor and gives under a press.
*
* <GlassOrbToggle applyToDocument />
* <GlassOrbToggle value={theme} onValueChange={setTheme} />
*
* A real switch (role="switch"): Space / Enter toggle it.
* Reduced motion: it moves without the spring and squash.
*/
export type Theme = "dark" | "light";
export interface GlassOrbToggleProps {
value?: Theme;
defaultValue?: Theme;
onValueChange?: (theme: Theme) => void;
/** Set data-theme and color-scheme on <html> when it switches. */
applyToDocument?: boolean;
/** Labels: shown on the side the orb isn't on. */
labels?: { dark: string; light: string };
/** Orb diameter in px; the pill is sized from it. */
size?: number;
className?: string;
"aria-label"?: string;
}
const reduced = () => typeof window !== "undefined" && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
const smooth = (a: number, b: number, x: number) => {
const t = Math.min(1, Math.max(0, (x - a) / (b - a)));
return t * t * (3 - 2 * t);
};
const mix = (a: number, b: number, t: number) => a + (b - a) * t;
const VERT = /* glsl */ `
varying vec2 vUv;
void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }
`;
// Liquid glass, the way Apple builds it: no outline at all. A flat-topped lens with a rounded
// squircle bevel; light refracts through the bevel by Snell's law (IOR ~1.5), so the content
// behind warps hardest at the edge and splits into colour there, while the centre stays clear.
// Soft speculars sit in the bevel facing the light (and faintly opposite it).
const FRAG = /* glsl */ `
precision highp float;
uniform sampler2D uTex;
uniform vec2 uSize; // canvas, css px
uniform vec2 uC; // lens centre, css px, y up
uniform float uR; // radius, css px
uniform vec2 uSq; // squash
uniform vec2 uLightDir; // where the light comes from (y up)
uniform float uLight; // 0 dark .. 1 light
uniform float uPx; // one device pixel, css px
uniform float uMag; // magnification across the lens (<1 magnifies)
uniform float uDisp; // dispersion strength
varying vec2 vUv;
const float BEVEL = 0.46; // bevel width, fraction of the radius
const float DEPTH = 0.62; // glass thickness, in radii
vec4 tex(vec2 p) { return texture2D(uTex, clamp(p / uSize, 0.0, 1.0)); }
void main() {
vec2 p = vUv * uSize;
vec4 base = tex(p);
vec2 d = (p - uC) / (uR * uSq);
float L = length(d);
float aa = uPx * 1.1 / uR;
float inside = 1.0 - smoothstep(1.0 - aa, 1.0, L);
if (inside <= 0.0) { gl_FragColor = base; return; }
vec2 dir = L > 1e-4 ? d / L : vec2(0.0);
// squircle bevel: height climbs from the rim and flattens on top
float t = clamp((1.0 - L) / BEVEL, 0.0, 1.0);
float w = 1.0 - t;
float f = pow(max(1.0 - pow(w, 4.0), 0.0), 0.25);
float fp = pow(max(1.0 - pow(w, 4.0), 1e-4), -0.75) * pow(w, 3.0);
float slope = min(fp * DEPTH / BEVEL, 4.2);
vec3 n = normalize(vec3(dir * slope, 1.0));
float k = (DEPTH * f + 0.35) * uR; // path to the scene behind, px
// Snell, one IOR per channel
vec3 I = vec3(0.0, 0.0, -1.0);
// the colour split lives inside the bevel and fades out before the silhouette, so the edge never reads as a line
float disp = uDisp * smoothstep(0.0, 0.16, 1.0 - L);
vec3 rr = refract(I, n, 1.0 / (1.50 - 0.045 * disp));
vec3 rg = refract(I, n, 1.0 / 1.50);
vec3 rb = refract(I, n, 1.0 / (1.50 + 0.055 * disp));
vec2 lens = (p - uC) * uMag;
vec4 sr = tex(uC + lens + rr.xy / max(-rr.z, 0.12) * k * uSq);
vec4 sg = tex(uC + lens + rg.xy / max(-rg.z, 0.12) * k * uSq);
vec4 sb = tex(uC + lens + rb.xy / max(-rb.z, 0.12) * k * uSq);
vec4 g = vec4(sr.r, sg.g, sb.b, max(sg.a, max(sr.a, sb.a)));
// the glass body: barely there
float bevel = 1.0 - n.z;
vec3 tint = mix(vec3(0.86, 0.89, 0.96), vec3(1.0), uLight);
float bodyA = mix(0.05, 0.08, uLight);
g.rgb = g.rgb * (1.0 - bodyA * 0.5) + tint * bodyA;
g.a = g.a + (1.0 - g.a) * bodyA;
// speculars in the bevel, soft at the very rim so nothing reads as a line
vec2 ld = normalize(uLightDir);
float facing = dot(dir, ld);
float inBevel = smoothstep(0.02, 0.5, bevel) * smoothstep(0.02, 0.14, 1.0 - L);
float sp = pow(max(facing, 0.0), 2.6) * inBevel * mix(0.5, 0.62, uLight)
+ pow(max(-facing, 0.0), 3.5) * inBevel * 0.2;
// a broad sheen across the lit side of the top
vec2 sd = d - ld * 0.42;
float sheen = exp(-dot(sd, sd) * 5.0) * mix(0.045, 0.07, uLight);
float lit = sp + sheen;
g.rgb += vec3(lit);
g.a = clamp(g.a + lit, 0.0, 1.0);
float h = fract(sin(dot(p, vec2(12.9898, 78.233))) * 43758.5453);
g.rgb += (h - 0.5) / 255.0;
gl_FragColor = mix(base, g, inside);
}
`;
export function GlassOrbToggle({
value,
defaultValue = "dark",
onValueChange,
applyToDocument = false,
labels = { dark: "Dark", light: "Light" },
size = 64,
className,
"aria-label": ariaLabel = "Light mode",
}: GlassOrbToggleProps) {
const [inner, setInner] = useState<Theme>(defaultValue);
const theme = value ?? inner;
const light = theme === "light";
const lightRef = useRef(light);
lightRef.current = light;
const hostRef = useRef<HTMLSpanElement>(null);
const rootRef = useRef<HTMLButtonElement>(null);
// geometry, css px
const D = size;
const th = Math.round(D * 0.56); // pill height
const W = Math.round(D * 1.45); // pill width
const inset = D * 0.18; // orb centre from the pill's end
const travel = W - inset * 2;
const mx = Math.round(D * 0.46);
const my = Math.round(D * 0.32);
const CW = W + mx * 2;
const CH = D + my * 2;
const phys = useRef({ x: light ? travel : 0, v: 0, target: light ? travel : 0, drag: false });
const lean = useRef({ x: 0, y: 0, s: 1 });
const lamp = useRef({ x: -0.6, y: 0.8 }); // the light, which drifts toward the cursor
const jelly = useRef({ s: 0, v: 0 }); // squash, on its own spring
const labelsRef = useRef(labels);
labelsRef.current = labels;
const repaint = useRef(0);
const setTheme = useCallback(
(next: Theme) => {
if (applyToDocument && typeof document !== "undefined") {
document.documentElement.dataset.theme = next;
document.documentElement.style.colorScheme = next;
}
if (value === undefined) setInner(next);
onValueChange?.(next);
},
[applyToDocument, onValueChange, value],
);
useEffect(() => {
phys.current.target = light ? travel : 0;
}, [light, travel]);
// the renderer: a 2D layer (pill, labels, icon) seen through a glass shader
useEffect(() => {
const host = hostRef.current;
if (!host) return;
const still = reduced();
const pr = Math.min(3, Math.min(window.devicePixelRatio || 1, 2) * 1.5); // supersampled
const layer = document.createElement("canvas");
layer.width = Math.round(CW * pr);
layer.height = Math.round(CH * pr);
const ctx = layer.getContext("2d")!;
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 });
} catch {
canvas.remove();
return;
}
renderer.setPixelRatio(pr);
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 texture = new THREE.CanvasTexture(layer);
texture.premultiplyAlpha = true;
texture.minFilter = THREE.LinearFilter;
texture.magFilter = THREE.LinearFilter;
texture.generateMipmaps = false;
const mat = new THREE.ShaderMaterial({
vertexShader: VERT,
fragmentShader: FRAG,
transparent: true,
depthTest: false,
blending: THREE.NoBlending,
uniforms: {
uTex: { value: texture },
uSize: { value: new THREE.Vector2(CW, CH) },
uC: { value: new THREE.Vector2(0, 0) },
uR: { value: D / 2 },
uSq: { value: new THREE.Vector2(1, 1) },
uLightDir: { value: new THREE.Vector2(-0.6, 0.8) },
uMag: { value: 0.9 },
uDisp: { value: 1 },
uLight: { value: 0 },
uPx: { value: 1 / pr },
},
});
const quad = new THREE.Mesh(new THREE.PlaneGeometry(CW, CH), mat);
quad.position.set(CW / 2, CH / 2, 0);
scene.add(quad);
const u = mat.uniforms;
const font = `500 ${Math.round(th * 0.3)}px Inter, ui-sans-serif, -apple-system, "Segoe UI", system-ui, sans-serif`;
const pillX = mx, pillY = my + (D - th) / 2;
// the crescent is cut on its own small canvas, so its glow isn't clipped with it
const moonCanvas = document.createElement("canvas");
const mctx = moonCanvas.getContext("2d")!;
const moon = (cx: number, cy: number, r: number, a: number, sc: number) => {
if (a <= 0.001) return;
const S = Math.ceil(r * 2.4 * pr);
if (moonCanvas.width !== S) {
moonCanvas.width = moonCanvas.height = S;
mctx.setTransform(1, 0, 0, 1, 0, 0);
mctx.clearRect(0, 0, S, S);
mctx.translate(S / 2, S / 2);
mctx.scale(pr, pr);
mctx.fillStyle = "#ffffff";
mctx.beginPath();
mctx.arc(0, 0, r, 0, Math.PI * 2);
mctx.fill();
mctx.globalCompositeOperation = "destination-out";
mctx.beginPath();
mctx.arc(r * 0.55, -r * 0.45, r * 0.82, 0, Math.PI * 2);
mctx.fill();
mctx.globalCompositeOperation = "source-over";
}
ctx.save();
ctx.globalAlpha = a;
ctx.translate(cx, cy);
ctx.rotate(-0.35 * (1 - sc));
ctx.scale(sc, sc);
ctx.shadowColor = "rgba(255,255,255,0.7)";
ctx.shadowBlur = r * 1.2 * pr;
const w = S / pr;
ctx.drawImage(moonCanvas, -w / 2, -w / 2, w, w);
ctx.restore();
};
const sun = (cx: number, cy: number, r: number, a: number, s: number) => {
if (a <= 0.001) return;
ctx.save();
ctx.globalAlpha = a;
ctx.translate(cx, cy);
ctx.rotate(-(1 - s) * 1.2);
ctx.shadowColor = "rgba(255,255,255,0.6)";
ctx.shadowBlur = r * 1.1 * pr;
ctx.fillStyle = "#ffffff";
ctx.beginPath();
ctx.arc(0, 0, r * 0.5 * (0.6 + 0.4 * s), 0, Math.PI * 2);
ctx.fill();
ctx.strokeStyle = "#ffffff";
ctx.lineCap = "round";
ctx.lineWidth = r * 0.17;
for (let i = 0; i < 8; i++) {
const ang = (i / 8) * Math.PI * 2;
const r0 = r * 0.74, r1 = r * (0.74 + 0.3 * s);
ctx.beginPath();
ctx.moveTo(Math.cos(ang) * r0, Math.sin(ang) * r0);
ctx.lineTo(Math.cos(ang) * r1, Math.sin(ang) * r1);
ctx.stroke();
}
ctx.restore();
};
// draw the flat scene the orb sits on
const paint = (prog: number, ox: number, oy: number) => {
ctx.setTransform(pr, 0, 0, pr, 0, 0);
ctx.clearRect(0, 0, CW, CH);
const lt = smooth(0.25, 0.85, prog);
// the pill, lit from inside in the light state
const g = ctx.createLinearGradient(0, pillY, 0, pillY + th);
const top = Math.round(mix(26, 132, lt)), bot = Math.round(mix(18, 92, lt));
g.addColorStop(0, `rgb(${top},${top},${top + 1})`);
g.addColorStop(1, `rgb(${bot},${bot},${bot + 1})`);
ctx.save();
ctx.shadowColor = `rgba(255,255,255,${0.32 * lt})`;
ctx.shadowBlur = th * 0.55 * pr;
ctx.fillStyle = g;
ctx.beginPath();
ctx.roundRect(pillX, pillY, W, th, th / 2);
ctx.fill();
ctx.restore();
// labels: the option the orb isn't on
ctx.font = font;
ctx.textBaseline = "middle";
ctx.textAlign = "center";
ctx.fillStyle = "#ffffff";
const cy = pillY + th / 2 + 0.5;
const lA = 1 - smooth(0.05, 0.55, prog), dA = smooth(0.45, 0.95, prog);
if (lA > 0) {
ctx.globalAlpha = lA * 0.95;
ctx.fillText(labelsRef.current.light, pillX + W - D * 0.385, cy);
}
if (dA > 0) {
ctx.globalAlpha = dA * 0.95;
ctx.fillText(labelsRef.current.dark, pillX + D * 0.385, cy);
}
ctx.globalAlpha = 1;
// the icon rides in the orb
const s = smooth(0.32, 0.72, prog);
const ir = D * 0.115; // the glass magnifies it about 1.4x
moon(ox, oy, ir, 1 - s, 1 - 0.35 * s);
sun(ox, oy, ir * 1.05, s, s);
texture.needsUpdate = true;
};
let lastKey = "";
let visible = true;
const io = new IntersectionObserver(([e]) => (visible = e.isIntersecting));
io.observe(host);
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) {
// under-damped a touch: it glides, runs a hair past its rest and settles
const acc = 170 * (p.target - p.x) - 19 * p.v;
p.v += acc * dt;
p.x += p.v * dt;
if (Math.abs(p.target - p.x) < 0.02 && Math.abs(p.v) < 0.4) {
p.x = p.target;
p.v = 0;
}
}
}
if (!visible) return;
const prog = Math.min(1, Math.max(0, p.x / travel));
// squash with speed, on its own damped spring, so it settles with one soft give
const j = jelly.current;
if (still) j.s = 0;
else {
const goal = Math.min(Math.abs(p.v) / (D * 12), 0.085);
const ja = 280 * (goal - j.s) - 20 * j.v;
j.v += ja * dt;
j.s += j.v * dt;
if (Math.abs(goal - j.s) < 1e-4 && Math.abs(j.v) < 1e-3) {
j.s = goal;
j.v = 0;
}
}
const sq = j.s;
const sc = lean.current.s;
const ox = mx + inset + p.x + lean.current.x;
const oy = my + D / 2 + lean.current.y;
const key = `${repaint.current}|${ox.toFixed(2)}|${oy.toFixed(2)}|${sq.toFixed(4)}|${sc.toFixed(4)}|${prog.toFixed(4)}|${lamp.current.x.toFixed(3)}|${lamp.current.y.toFixed(3)}`;
if (key === lastKey) return;
lastKey = key;
paint(prog, ox, oy);
u.uC.value.set(ox, CH - oy);
u.uR.value = (D / 2) * sc;
u.uSq.value.set(0.97 - sq, 1.02 + sq * 0.55);
u.uLightDir.value.set(lamp.current.x, lamp.current.y);
u.uLight.value = smooth(0.25, 0.85, prog);
// lifted, it magnifies more; moving, the colour splits a little wider
u.uMag.value = 0.8 - (sc - 1) * 0.9;
u.uDisp.value = 1 + Math.min(Math.abs(p.v) / (D * 5), 1.2);
renderer.render(scene, camera);
};
gsap.ticker.add(step);
// the light drifts toward the cursor, wherever it is on the page
const lx = gsap.quickTo(lamp.current, "x", { duration: 1.1, ease: "power3.out" });
const ly = gsap.quickTo(lamp.current, "y", { duration: 1.1, ease: "power3.out" });
const onWin = (e: PointerEvent) => {
if (still) return;
const rc = host.getBoundingClientRect();
const cx = rc.left + mx + inset + phys.current.x, cy = rc.top + my + D / 2;
const dx = e.clientX - cx, dy = cy - e.clientY;
const len = Math.hypot(dx, dy) || 1;
// mostly from above, swung toward the cursor
lx((dx / len) * 0.75);
ly(Math.max(0.35, dy / len) * 0.9 + 0.1);
};
window.addEventListener("pointermove", onWin, { passive: true });
// fonts may arrive late; repaint once they do
document.fonts?.ready.then(() => void repaint.current++);
return () => {
gsap.ticker.remove(step);
window.removeEventListener("pointermove", onWin);
io.disconnect();
texture.dispose();
mat.dispose();
quad.geometry.dispose();
renderer.dispose();
canvas.remove();
};
}, [CW, CH, D, W, th, mx, my, inset, travel]);
// labels can change without a rebuild
useEffect(() => {
repaint.current++;
}, [labels.dark, labels.light]);
const press = (down: boolean) => {
if (reduced()) return;
// like Apple's switches: touched, the glass lifts and swells; let go, it settles back
gsap.to(lean.current, down ? { s: 1.1, duration: 0.32, ease: "power3.out", overwrite: "auto" } : { s: 1, duration: 0.75, ease: "elastic.out(1, 0.55)", overwrite: "auto" });
};
const leanTo = (x: number, y: number) => {
if (reduced()) return;
gsap.to(lean.current, { x, y, duration: 0.7, ease: "power3.out", overwrite: "auto" });
};
const commit = (next: Theme) => {
phys.current.target = next === "light" ? travel : 0;
setTheme(next);
};
// drag and throw
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>) => {
const r = e.currentTarget.getBoundingClientRect();
const d = drag.current;
if (!d?.moved) {
// the orb leans after the cursor
const cx = r.left + inset + phys.current.x, cy = r.top + D / 2;
leanTo(gsap.utils.clamp(-1, 1, (e.clientX - cx) / D) * D * 0.06, gsap.utils.clamp(-1, 1, (e.clientY - cy) / D) * D * 0.04);
}
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;
leanTo(0, 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;
if (x < 0) x = -rubber(-x, D * 0.08);
if (x > travel) x = travel + rubber(x - travel, D * 0.08);
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 = lightRef.current ? travel : 0);
if (!d.moved) return commit(lightRef.current ? "dark" : "light");
const next: Theme = phys.current.x + d.v * 0.12 > travel / 2 ? "light" : "dark";
if ((next === "light") !== lightRef.current) commit(next);
else phys.current.target = lightRef.current ? travel : 0;
};
return (
<button
ref={rootRef}
type="button"
role="switch"
aria-checked={light}
aria-label={ariaLabel}
onClick={(e) => e.detail === 0 && commit(light ? "dark" : "light")}
onPointerDown={onDown}
onPointerMove={onMove}
onPointerUp={(e) => onUp(e)}
onPointerCancel={(e) => onUp(e, true)}
onPointerLeave={() => leanTo(0, 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-white/40 focus-visible:ring-offset-4 focus-visible:ring-offset-transparent", className].filter(Boolean).join(" ")}
style={{ width: W, height: D }}
>
<span ref={hostRef} aria-hidden="true" className="pointer-events-none absolute block" style={{ left: -mx, top: -my, width: CW, height: CH }} />
<span className="sr-only">{light ? labels.light : labels.dark}</span>
</button>
);
}
export default GlassOrbToggle;
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
8 propsvalue"dark" | "light"Controlled theme.defaultValue"dark" | "light"Initial theme when uncontrolled.default "dark"default "dark"onValueChange(theme) => voidCalled the moment it is switched.applyToDocumentbooleanSet data-theme and color-scheme on <html> when it switches.default falsedefault falselabels{ dark: string; light: string }Shown on the side the orb isn't on.default Dark / Lightdefault Dark / LightsizenumberOrb diameter in px; the pill is sized from it.default 64default 64aria-labelstringAccessible name.default "Light mode"default "Light mode"classNamestringExtra classes.