Liquid Toolbar
A borderless pill of Apple-style liquid glass holding a row of icon actions, rendered for real on the GPU. What is behind it is frosted through the flat face and bent hardest in the wide rounded bevel, with a faint colour fringe, so the edge reads by refraction alone: no outline, no shadow. Soft highlights follow your cursor round the bevel. A clear lens glides to what you point at on a soft spring, and when you press it lifts into a magnifying drop you can slide along the bar while the bar dips, swells and settles. Fully keyboard accessible.

Tweak
LIVELIVEStage
Behind the glass
Glass
Optics
Tool picker
Keep the lens on the last pressed action
Usage
Follows your tweaks.
import { LiquidToolbar } from "@/components/inreact/liquid-toolbar";
export function CanvasTools({ onTool }: { onTool: (id: string) => void }) {
return (
<LiquidToolbar
aria-label="Canvas tools"
items={[
{ id: "add", label: "Add", icon: "plus" },
{ id: "ellipse", label: "Ellipse", icon: "circle" },
{ id: "rect", label: "Rectangle", icon: "square" },
]}
defaultValue="add"
onValueChange={onTool}
/>
);
}Install with the CLI
npx shadcn@latest add https://inreact.vercel.app/r/liquid-toolbar.jsonOr copy the source
Install the dependencies, then save this as components/inreact/liquid-toolbar.tsx.
npm install gsap"use client";
import { gsap } from "gsap";
import { useCallback, useEffect, useRef, useState, type KeyboardEvent, type PointerEvent as ReactPointerEvent, type ReactNode, type RefObject } from "react";
/**
* Liquid Toolbar: a borderless pill of Apple-style liquid glass holding a row of icon actions.
*
* The glass is rendered for real on the GPU. It is a slab with a flat face and a
* wide rounded bevel: whatever is behind it is frosted through the face, and
* bent hardest in the bevel, where the light splits into a faint colour fringe,
* so the edge reads by refraction alone (no outline, no shadow). Soft
* highlights sit in the bevel on the side facing your cursor, and swing round
* as you move.
*
* A clear lens rests under the chosen action. It glides to whatever you point
* at on a soft spring (stretching with its speed, overshooting a touch and
* settling), and when you press it lifts into a magnifying drop you can slide
* along the bar; let go and it snaps to the nearest action. The whole bar dips,
* swells and settles as you press, leans a little when it is moved, and grows
* in when it first appears. Icons answer presses (the plus turns, the circle
* pops, the square softens its corners).
*
* const photo = useRef<HTMLImageElement>(null);
* <img ref={photo} src="/hero.jpg" className="absolute inset-0 size-full object-cover" />
* <LiquidToolbar backdrop={photo} aria-label="Canvas tools" onValueChange={setTool} />
*
* Without a backdrop it still works over any page: the browser frosts what is
* behind (backdrop-filter) and the GPU adds the bevel light. Keyboard: arrows,
* Home and End move between actions; Enter or Space presses. Reduced motion:
* no springs. WebGL2; without it, a static frosted pill.
*/
export type LiquidToolbarIcon = "plus" | "circle" | "square" | ReactNode;
export interface LiquidToolbarItem {
id: string;
/** Accessible name (also the tooltip). */
label: string;
/** A built-in icon ("plus", "circle", "square") or your own SVG. */
icon: LiquidToolbarIcon;
/** Called when this action is pressed. */
onSelect?: () => void;
}
export interface LiquidToolbarProps {
items?: LiquidToolbarItem[];
/** The image, video or canvas behind the toolbar, refracted through the glass. */
backdrop?: RefObject<HTMLImageElement | HTMLVideoElement | HTMLCanvasElement | null>;
/** Controlled selected id (null for none). */
value?: string | null;
/** Initially selected id when uncontrolled. */
defaultValue?: string | null;
/** Called with the pressed action's id. */
onValueChange?: (id: string) => void;
/** Keep the lens on the last pressed action (a tool picker). Off: plain actions. */
selectable?: boolean;
/** Height of the pill in px. */
size?: number;
/** Colour of the glass tint. */
tint?: string;
/** Strength of the tint, 0 clear to 1 solid. */
frost?: number;
/** Colour of the icons. */
iconColor?: string;
/** Strength of the refraction in the bevel. */
refraction?: number;
/** Colour fringing in the bevel, 0 to 1. */
dispersion?: number;
/** Frosting of what is seen through the glass, px. */
blur?: number;
/** Width of the rounded bevel, 0.2 to 1 (share of the half height). */
bevel?: number;
className?: string;
"aria-label"?: string;
}
const DEFAULT_ITEMS: LiquidToolbarItem[] = [
{ id: "add", label: "Add", icon: "plus" },
{ id: "ellipse", label: "Ellipse", icon: "circle" },
{ id: "rect", label: "Rectangle", icon: "square" },
];
const reduced = () => typeof window !== "undefined" && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
const clamp = (a: number, b: number, v: number) => Math.max(a, Math.min(b, v));
function hex(c: string): [number, number, number] {
let h = c.replace("#", "");
if (h.length === 3) h = h.replace(/./g, (x) => x + x);
const n = parseInt(h, 16) || 0;
return [((n >> 16) & 255) / 255, ((n >> 8) & 255) / 255, (n & 255) / 255];
}
const VERT = `#version 300 es
in vec2 aQ;
void main() { gl_Position = vec4(aQ, 0.0, 1.0); }`;
const FRAG = `#version 300 es
precision highp float;
uniform vec2 uRes, uTexSize;
uniform float uDpr, uLight, uRefr, uDisp, uBlur, uFrost, uHasTex, uLensA, uLensP, uBevel, uAlpha;
uniform vec4 uPill; // centre x, y, half width, half height (css px, canvas space)
uniform vec4 uLens; // centre x, y, half width, half height
uniform vec4 uBack; // where the backdrop is drawn: x, y, w, h (css px, canvas space)
uniform vec3 uTint;
uniform sampler2D uTex;
out vec4 o;
float sdCap(vec2 p, vec4 c) {
vec2 q = abs(p - c.xy);
float r = c.w;
return length(vec2(max(q.x - (c.z - r), 0.0), q.y)) - r;
}
float smin(float a, float b, float k) { float h = clamp(0.5 + 0.5 * (b - a) / k, 0.0, 1.0); return mix(b, a, h) - k * h * (1.0 - h); }
// the silhouette: the bar, with the lifted lens swelling out of it while pressed
float sdf(vec2 p) {
float d = sdCap(p, uPill);
if (uLensP > 0.001) d = smin(d, sdCap(p, uLens), 6.0 * uLensP + 0.01);
return d;
}
// a slab: flat face, wide rounded bevel (a soft quarter-round, so the light spreads instead of drawing a line)
float bevelH(float d, float bev) {
float t = clamp(-d / bev, 0.0, 1.0);
return bev * (1.0 - pow(1.0 - t, 2.4)) * 0.55;
}
float height(vec2 p) {
float h = bevelH(sdf(p), uPill.w * uBevel);
// the lens is a thicker drop of glass of its own
float dl = sdCap(p, uLens);
h += bevelH(dl, uLens.w * 0.9) * uLensA * (0.55 + 0.6 * uLensP);
return h;
}
vec3 tex(vec2 css, float lod) {
vec2 uv = (css - uBack.xy) / uBack.zw;
return textureLod(uTex, clamp(uv, vec2(0.001), vec2(0.999)), lod).rgb;
}
// frosted read: a pre-blurred mip level, smoothed by a ring of taps
vec3 frosted(vec2 c, float r) {
float lod = log2(max(1.0, r * 0.6 * uTexSize.x / uBack.z));
vec3 s = tex(c, lod) * 0.25;
for (int i = 0; i < 6; i++) {
float a = float(i) * 1.0472 + 0.3;
s += tex(c + vec2(cos(a), sin(a)) * r * 0.75, lod) * 0.125;
}
return s;
}
void main() {
vec2 frag = vec2(gl_FragCoord.x, uRes.y - gl_FragCoord.y) / uDpr;
float d = sdf(frag);
float aa = 0.75 / uDpr;
float alpha = (1.0 - smoothstep(-aa, aa, d)) * uAlpha;
if (alpha < 0.002) { o = vec4(0.0); return; }
float e = 1.0;
float hx = height(frag + vec2(e, 0.0)) - height(frag - vec2(e, 0.0));
float hy = height(frag + vec2(0.0, e)) - height(frag - vec2(0.0, e));
vec3 n = normalize(vec3(-vec2(hx, hy) / (2.0 * e), 1.0));
float edge = 1.0 - n.z; // 0 on the flat face, rising through the bevel
// Snell refraction through the bevel, each colour with its own index: the rim bends hardest and splits a little
vec3 I = vec3(0.0, 0.0, -1.0);
float K = uPill.w * 1.6 * uRefr;
vec2 dR = -refract(I, n, 1.0 / (1.5 - 0.035 * uDisp)).xy;
vec2 dG = -refract(I, n, 1.0 / 1.5).xy;
vec2 dB = -refract(I, n, 1.0 / (1.5 + 0.035 * uDisp)).xy;
// the lifted lens magnifies what is under it
vec2 lc = uLens.xy;
float inLens = (1.0 - smoothstep(-2.0, 2.0, sdCap(frag, uLens))) * uLensA;
vec2 mag = (frag - lc) * (0.22 * uLensP + 0.06) * inLens;
vec3 body;
float br = max(uBlur, 0.0) * (1.0 - 0.75 * inLens * uLensP);
if (uHasTex > 0.5) {
body.r = frosted(frag - mag + dR * K, br).r;
body.g = frosted(frag - mag + dG * K, br).g;
body.b = frosted(frag - mag + dB * K, br).b;
} else {
body = uTint;
}
vec3 col = body;
if (uHasTex > 0.5) {
col = mix(col, uTint, uFrost);
col = mix(col, vec3(1.0), 0.05); // the milky veil of frosted glass
col *= 1.0 + 0.1 * inLens; // the lens is a touch clearer and brighter
}
// the bevel lifts a little light from its surroundings (never darker, so no outline)
float band = smoothstep(0.0, 0.18, edge);
col = mix(col, col * 1.18 + 0.03, band * 0.55);
// soft highlights in the bevel on the side facing the light, a fainter one opposite
vec2 Ld = vec2(cos(uLight), sin(uLight));
vec2 nd = normalize(n.xy + 1e-5);
float facing = dot(nd, Ld);
float w = smoothstep(0.02, 0.5, edge) * smoothstep(0.0, 1.2, -d); // fades out at the very rim: a glow in the bevel, not a line
col += w * (0.55 * pow(max(facing, 0.0), 2.5) + 0.2 * pow(max(-facing, 0.0), 3.0));
// a broad sheen across the face, brightest toward the light
vec2 rel = (frag - uPill.xy) / uPill.zw;
col += 0.045 * smoothstep(-1.0, 1.0, dot(rel, Ld)) * (1.0 - band);
float bodyA = uHasTex > 0.5 ? 1.0 : clamp(uFrost * 0.7 + band * 0.25 + w * 0.5, 0.0, 1.0);
float a = alpha * bodyA;
o = vec4(col * a, a);
}`;
function BuiltInIcon({ kind }: { kind: "plus" | "circle" | "square" }) {
const common = { width: "100%", height: "100%", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: 2.1, "aria-hidden": true } as const;
if (kind === "plus")
return (
<svg {...common} strokeLinecap="round" data-icon="plus">
<path d="M12 3.5v17M3.5 12h17" />
</svg>
);
if (kind === "circle")
return (
<svg {...common} data-icon="circle">
<circle cx="12" cy="12" r="8.6" />
</svg>
);
return (
<svg {...common} data-icon="square">
<rect x="3.6" y="3.6" width="16.8" height="16.8" rx="4.6" />
</svg>
);
}
const isBuiltIn = (i: LiquidToolbarIcon): i is "plus" | "circle" | "square" => i === "plus" || i === "circle" || i === "square";
export function LiquidToolbar({
items = DEFAULT_ITEMS,
backdrop,
value,
defaultValue = null,
onValueChange,
selectable = true,
size = 76,
tint = "#141416",
frost = 0.2,
iconColor = "#ffffff",
refraction = 1,
dispersion = 0.6,
blur = 10,
bevel = 0.75,
className,
"aria-label": ariaLabel = "Toolbar",
}: LiquidToolbarProps) {
const rootRef = useRef<HTMLDivElement>(null);
const btnRefs = useRef<(HTMLButtonElement | null)[]>([]);
const iconRefs = useRef<(HTMLSpanElement | null)[]>([]);
const [inner, setInner] = useState(defaultValue);
const selected = value !== undefined ? value : inner;
const [focusIdx, setFocusIdx] = useState(() => Math.max(0, items.findIndex((i) => i.id === selected)));
const [gpu, setGpu] = useState(true);
const [hasTex, setHasTex] = useState(false);
const pad = Math.round(size * 0.13);
const btn = size - pad * 2;
const gap = Math.round(size * 0.06);
const M = Math.round(size * 0.35); // room around the pill for the press swell
const props = useRef({ tint, frost, refraction, dispersion, blur, bevel });
props.current = { tint, frost, refraction, dispersion, blur, bevel };
// what the render loop reads; written by pointer handlers and React state
const sim = useRef({
wake: () => {},
lensTarget: null as number | null,
drag: null as number | null, // pointer x while the lens is being slid
down: (_on: boolean) => {},
});
const hoverIdx = useRef<number | null>(null);
const keyboard = useRef(false);
const centerOf = useCallback(
(i: number) => {
const b = btnRefs.current[i];
return b ? b.offsetLeft + b.offsetWidth / 2 : pad + btn / 2 + i * (btn + gap);
},
[btn, gap, pad],
);
// where the lens should rest: the hovered action, else the keyboard-focused one, else the selected one
const retarget = useCallback(() => {
const selIdx = selectable ? items.findIndex((i) => i.id === selected) : -1;
const idx = hoverIdx.current ?? (keyboard.current ? focusIdx : selIdx >= 0 ? selIdx : null);
sim.current.lensTarget = idx === null || idx < 0 ? null : centerOf(idx);
sim.current.wake();
}, [centerOf, focusIdx, items, selectable, selected]);
useEffect(() => {
retarget();
}, [retarget]);
// ---- the renderer and the springs ----
useEffect(() => {
const root = rootRef.current;
if (!root) return;
// a fresh canvas per mount: a context released on unmount must never be reused
const canvas = document.createElement("canvas");
canvas.setAttribute("aria-hidden", "true");
canvas.className = "pointer-events-none absolute";
canvas.style.left = `${-M}px`;
canvas.style.top = `${-M}px`;
root.insertBefore(canvas, root.firstChild);
const gl = canvas.getContext("webgl2", { alpha: true, premultipliedAlpha: true, antialias: false });
if (!gl) {
canvas.remove();
setGpu(false);
return;
}
const compile = (type: number, src: string) => {
const sh = gl.createShader(type)!;
gl.shaderSource(sh, src);
gl.compileShader(sh);
if (!gl.getShaderParameter(sh, gl.COMPILE_STATUS)) console.error(gl.getShaderInfoLog(sh));
return sh;
};
const prog = gl.createProgram()!;
const vs = compile(gl.VERTEX_SHADER, VERT), fs = compile(gl.FRAGMENT_SHADER, FRAG);
gl.attachShader(prog, vs);
gl.attachShader(prog, fs);
gl.bindAttribLocation(prog, 0, "aQ");
gl.linkProgram(prog);
gl.useProgram(prog);
const U = Object.fromEntries(
["uRes", "uTexSize", "uDpr", "uLight", "uRefr", "uDisp", "uBlur", "uFrost", "uHasTex", "uLensA", "uLensP", "uBevel", "uAlpha", "uPill", "uLens", "uBack", "uTint", "uTex"].map((k) => [k, gl.getUniformLocation(prog, k)]),
) as Record<string, WebGLUniformLocation | null>;
const vao = gl.createVertexArray();
gl.bindVertexArray(vao);
const vbo = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, vbo);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 3, -1, -1, 3]), gl.STATIC_DRAW);
gl.enableVertexAttribArray(0);
gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0);
const texture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array([0, 0, 0, 255]));
gl.uniform1i(U.uTex, 0);
let texW = 1, texH = 1;
const still = reduced();
// ---- state (css px in canvas space) ----
let W = 1, H = 1, dpr = 1;
const lens = { x: 0, v: 0, a: 0, ready: false, p: 0, pv: 0, pt: 0 };
// the whole bar: scale springs (press dip and swell, entrance) and a lean when moved
const body = { sx: still ? 1 : 0.55, sy: still ? 1 : 0.55, vx: 0, vy: 0, tx: 1, ty: 1, ox: 0, oy: 0, ovx: 0, ovy: 0, alpha: still ? 1 : 0 };
if (!still) gsap.to(body, { alpha: 1, duration: 0.35, ease: "power2.out", delay: 0.05 });
const ptr = { x: -1e4, y: -1e4, in: false };
const light = { a: -2.2 };
const lightTo = gsap.quickTo(light, "a", { duration: 0.6, ease: "power3.out" });
let texSrc: HTMLImageElement | HTMLVideoElement | HTMLCanvasElement | null = null;
let texReady = false;
let lastRect = { x: 0, y: 0 };
let lastBack = "";
let awake = 3;
const resize = () => {
W = root.offsetWidth;
H = root.offsetHeight;
dpr = Math.min(window.devicePixelRatio || 1, 2);
canvas.style.width = `${W + 2 * M}px`;
canvas.style.height = `${H + 2 * M}px`;
canvas.width = Math.round((W + 2 * M) * dpr);
canvas.height = Math.round((H + 2 * M) * dpr);
};
resize();
const ro = new ResizeObserver(() => {
resize();
awake = 3;
});
ro.observe(root);
const upload = (el: HTMLImageElement | HTMLVideoElement | HTMLCanvasElement) => {
try {
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, el);
gl.generateMipmap(gl.TEXTURE_2D);
texW = el instanceof HTMLImageElement ? el.naturalWidth : el instanceof HTMLVideoElement ? el.videoWidth : el.width;
texH = el instanceof HTMLImageElement ? el.naturalHeight : el instanceof HTMLVideoElement ? el.videoHeight : el.height;
texReady = texW > 0;
return true;
} catch {
return false;
}
};
const loadTex = () => {
const el = backdrop?.current ?? null;
texSrc = el;
texReady = false;
if (!el) return void setHasTex(false);
const go = () => {
setHasTex(upload(el));
awake = 3;
};
if (el instanceof HTMLImageElement) {
if (el.complete && el.naturalWidth) go();
el.addEventListener("load", go);
return () => el.removeEventListener("load", go);
}
go();
};
let unTex = loadTex();
// the backdrop element can change (a different photo): watch its src
const mo = new MutationObserver(() => {
unTex?.();
unTex = loadTex();
});
if (backdrop?.current) mo.observe(backdrop.current, { attributes: true, attributeFilter: ["src"] });
// ---- input ----
const onMove = (e: PointerEvent) => {
const r = root.getBoundingClientRect();
ptr.x = e.clientX - r.left + M;
ptr.y = e.clientY - r.top + M;
ptr.in = true;
const cx = M + W / 2, cy = M + H / 2;
// the light swings round to face the cursor
let a = Math.atan2(ptr.y - cy, (ptr.x - cx) * 0.45);
while (a - light.a > Math.PI) a -= Math.PI * 2;
while (a - light.a < -Math.PI) a += Math.PI * 2;
if (!still) lightTo(a);
awake = 3;
};
window.addEventListener("pointermove", onMove, { passive: true });
sim.current.wake = () => {
awake = 3;
};
let dipTimer = 0;
sim.current.down = (on: boolean) => {
awake = 3;
if (still) return;
window.clearTimeout(dipTimer);
if (on) {
// anticipation: a small dip, then the bar swells and the lens lifts into a drop
body.tx = 0.975;
body.ty = 0.96;
dipTimer = window.setTimeout(() => {
body.tx = 1.035;
body.ty = 1.05;
awake = 3;
}, 70);
lens.pt = 1;
} else {
body.tx = 1;
body.ty = 1;
lens.pt = 0;
}
};
// ---- the loop: springs advance; the GPU only draws while something is changing ----
let raf = 0;
let prev = performance.now();
let visible = true;
const io = new IntersectionObserver(([en]) => {
visible = en.isIntersecting;
prev = performance.now();
awake = 3;
});
io.observe(root);
const spring = (x: number, v: number, t: number, k: number, c: number, dt: number) => {
for (let i = 0; i < 2; i++) (v += (k * (t - x) - c * v) * (dt / 2)), (x += v * (dt / 2));
return [x, v];
};
const frame = () => {
raf = requestAnimationFrame(frame);
const now = performance.now();
const dt = Math.min(1 / 30, (now - prev) / 1000);
prev = now;
if (!visible) return;
const P = props.current;
// the bar moved on the page (dragged, scrolled): it leans against the motion, well damped
const r = root.getBoundingClientRect();
const mvx = (r.left - lastRect.x) / Math.max(dt, 1e-3), mvy = (r.top - lastRect.y) / Math.max(dt, 1e-3);
const moved = Math.abs(r.left - lastRect.x) > 0.01 || Math.abs(r.top - lastRect.y) > 0.01;
lastRect = { x: r.left, y: r.top };
if (moved && !still) {
body.ovx += clamp(-3000, 3000, -mvx) * 0.012;
body.ovy += clamp(-3000, 3000, -mvy) * 0.012;
}
let back = "";
if (texSrc && texReady) {
const b = texSrc.getBoundingClientRect();
back = `${b.left - r.left}|${b.top - r.top}|${b.width}|${b.height}`;
}
if (moved || back !== lastBack) awake = 3;
lastBack = back;
// lens: follows the target (or your finger while sliding) on a slightly underdamped spring
const lt = sim.current.drag ?? sim.current.lensTarget;
if (lt !== null) {
if (!lens.ready || lens.a < 0.02) {
lens.x = lt + M;
lens.v = 0;
lens.ready = true;
}
if (still) (lens.x = lt + M), (lens.v = 0);
else [lens.x, lens.v] = spring(lens.x, lens.v, lt + M, sim.current.drag !== null ? 700 : 340, sim.current.drag !== null ? 44 : 24, dt);
}
lens.a += ((lt !== null ? 1 : 0) - lens.a) * (1 - Math.exp(-dt * (still ? 1e3 : 12)));
if (still) lens.p = lens.pt;
else [lens.p, lens.pv] = spring(lens.p, lens.pv, lens.pt, 260, 20, dt);
// body: scale and lean springs (overshoot a touch, then settle)
if (still) (body.sx = body.tx), (body.sy = body.ty);
else {
[body.sx, body.vx] = spring(body.sx, body.vx, body.tx, 230, 17, dt);
[body.sy, body.vy] = spring(body.sy, body.vy, body.ty, 230, 15, dt);
body.ovx += (-160 * body.ox - 17 * body.ovx) * dt;
body.ovy += (-160 * body.oy - 17 * body.ovy) * dt;
body.ox = clamp(-8, 8, body.ox + body.ovx * dt);
body.oy = clamp(-6, 6, body.oy + body.ovy * dt);
}
// icons lean toward the cursor; the one under the lifted lens is magnified
const cy = M + H / 2;
iconRefs.current.forEach((el, i) => {
if (!el) return;
const c = centerOf(i) + M;
const dx = ptr.x - c, dy = ptr.y - cy;
const near = ptr.in && Math.hypot(dx, dy) < btn * 0.9;
const under = Math.max(0, 1 - Math.abs(lens.x - c) / (btn * 0.8)) * lens.a;
const s = 1 + 0.2 * lens.p * under;
el.style.transform = `translate(${near && !still ? (dx * 0.1).toFixed(2) : 0}px, ${near && !still ? (dy * 0.1).toFixed(2) : 0}px) scale(${s.toFixed(3)})`;
});
const energy = Math.abs(lens.v) + Math.abs(lens.pv) * 40 + (Math.abs(body.vx) + Math.abs(body.vy)) * 40 + Math.abs(body.ovx) + Math.abs(body.ovy) + Math.abs(body.ox) + Math.abs(body.oy) + Math.abs(body.sx - body.tx) * 100 + Math.abs(lens.p - lens.pt) * 100;
const video = texSrc instanceof HTMLVideoElement || texSrc instanceof HTMLCanvasElement;
if (energy > 0.04 || Math.abs((lt !== null ? 1 : 0) - lens.a) > 0.002 || video || body.alpha < 1 || gsap.isTweening(light)) awake = 3;
if (awake <= 0) return;
awake--;
// ---- draw ----
if (video && texSrc) upload(texSrc);
if (texSrc && texReady) {
// where the backdrop is drawn, honouring object-fit
const b = texSrc.getBoundingClientRect();
let dw = b.width, dh = b.height, ox = b.left, oy = b.top;
const fit = getComputedStyle(texSrc).objectFit;
if (texW && texH && (fit === "cover" || fit === "contain")) {
const s = fit === "cover" ? Math.max(b.width / texW, b.height / texH) : Math.min(b.width / texW, b.height / texH);
dw = texW * s;
dh = texH * s;
ox = b.left + (b.width - dw) / 2;
oy = b.top + (b.height - dh) / 2;
}
gl.uniform4f(U.uBack, ox - (r.left - M), oy - (r.top - M), dw, dh);
gl.uniform2f(U.uTexSize, texW, texH);
}
const cx = M + W / 2;
gl.viewport(0, 0, canvas.width, canvas.height);
gl.clearColor(0, 0, 0, 0);
gl.clear(gl.COLOR_BUFFER_BIT);
gl.uniform2f(U.uRes, canvas.width, canvas.height);
gl.uniform1f(U.uDpr, dpr);
gl.uniform1f(U.uLight, light.a);
gl.uniform1f(U.uRefr, Math.max(0, P.refraction));
gl.uniform1f(U.uDisp, clamp(0, 1, P.dispersion));
gl.uniform1f(U.uBlur, Math.max(0, P.blur));
gl.uniform1f(U.uFrost, clamp(0, 1, P.frost));
gl.uniform1f(U.uBevel, clamp(0.2, 1, P.bevel));
gl.uniform1f(U.uAlpha, body.alpha);
gl.uniform1f(U.uHasTex, texSrc && texReady ? 1 : 0);
gl.uniform3fv(U.uTint, hex(P.tint));
// a lean stretches the bar a touch along the motion
const lean = Math.min(0.05, Math.hypot(body.ox, body.oy) / 160);
gl.uniform4f(U.uPill, cx + body.ox, cy + body.oy, (W / 2) * body.sx * (1 + lean), (H / 2) * body.sy * (1 - lean * 0.6));
const sp = Math.min(Math.abs(lens.v) / 1600, 0.4);
const lp = Math.max(0, lens.p);
const lh = (btn / 2) * (1 + 0.32 * lp) * (1 - sp * 0.22);
gl.uniform4f(U.uLens, lens.x + body.ox, cy + body.oy, Math.max(lh, (btn / 2) * (1 + sp) * (1 + 0.32 * lp)), lh);
gl.uniform1f(U.uLensA, lens.a);
gl.uniform1f(U.uLensP, clamp(0, 1.2, lp));
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.drawArrays(gl.TRIANGLES, 0, 3);
};
raf = requestAnimationFrame(frame);
return () => {
cancelAnimationFrame(raf);
window.clearTimeout(dipTimer);
sim.current.wake = () => {};
sim.current.down = () => {};
unTex?.();
mo.disconnect();
ro.disconnect();
io.disconnect();
window.removeEventListener("pointermove", onMove);
gsap.killTweensOf([light, body]);
gl.deleteTexture(texture);
gl.deleteProgram(prog);
gl.deleteShader(vs);
gl.deleteShader(fs);
gl.deleteBuffer(vbo);
gl.deleteVertexArray(vao);
gl.getExtension("WEBGL_lose_context")?.loseContext();
canvas.remove();
};
}, [backdrop, btn, centerOf, M]);
// icons grow in one after another on mount
useEffect(() => {
if (reduced()) return;
const els = iconRefs.current.filter(Boolean).map((el) => el!.firstElementChild);
gsap.fromTo(els, { scale: 0.3, opacity: 0 }, { scale: 1, opacity: 1, duration: 0.6, ease: "back.out(2.6)", stagger: 0.06, delay: 0.15 });
}, []);
const animateIcon = (i: number) => {
const svg = btnRefs.current[i]?.querySelector("svg");
if (!svg || reduced()) return;
const kind = svg.getAttribute("data-icon");
if (kind === "plus") gsap.fromTo(svg, { rotate: 0 }, { rotate: 90, duration: 0.55, ease: "back.out(2.2)", clearProps: "rotate" });
else if (kind === "circle") gsap.fromTo(svg, { scale: 0.7 }, { scale: 1, duration: 0.65, ease: "elastic.out(1, 0.42)" });
else if (kind === "square") {
const rect = svg.querySelector("rect");
if (rect) gsap.fromTo(rect, { attr: { rx: 8.4 } }, { attr: { rx: 4.6 }, duration: 0.65, ease: "elastic.out(1, 0.45)" });
gsap.fromTo(svg, { scale: 0.84 }, { scale: 1, duration: 0.55, ease: "back.out(2)" });
} else gsap.fromTo(svg, { scale: 0.8 }, { scale: 1, duration: 0.5, ease: "back.out(2)" });
};
const press = (i: number) => {
const it = items[i];
if (!it) return;
if (selectable && value === undefined) setInner(it.id);
onValueChange?.(it.id);
it.onSelect?.();
animateIcon(i);
};
// press and slide: the lens lifts under your finger, follows it along the bar, and snaps to the nearest action
const pressing = useRef<{ id: number; x0: number; moved: boolean } | null>(null);
const lastPointerPress = useRef(0);
const localX = (e: ReactPointerEvent) => e.clientX - (rootRef.current?.getBoundingClientRect().left ?? 0);
const nearest = (x: number) => {
let best = 0, bd = Infinity;
items.forEach((_, i) => {
const d = Math.abs(centerOf(i) - x);
if (d < bd) (bd = d), (best = i);
});
return best;
};
const onPointerDown = (e: ReactPointerEvent<HTMLDivElement>) => {
if (e.button !== 0 || !(e.target as HTMLElement).closest("button")) return;
pressing.current = { id: e.pointerId, x0: e.clientX, moved: false };
try {
e.currentTarget.setPointerCapture(e.pointerId);
} catch {}
keyboard.current = false;
sim.current.drag = clamp(centerOf(0), centerOf(items.length - 1), localX(e));
sim.current.down(true);
};
const onPointerMove = (e: ReactPointerEvent<HTMLDivElement>) => {
const p = pressing.current;
if (!p || p.id !== e.pointerId) return;
if (Math.abs(e.clientX - p.x0) > 4) p.moved = true;
sim.current.drag = clamp(centerOf(0), centerOf(items.length - 1), localX(e));
hoverIdx.current = nearest(localX(e));
sim.current.wake();
};
const onPointerUp = (e: ReactPointerEvent<HTMLDivElement>) => {
const p = pressing.current;
if (!p || p.id !== e.pointerId) return;
pressing.current = null;
const i = nearest(localX(e));
sim.current.drag = null;
sim.current.down(false);
if (e.type === "pointerup") {
lastPointerPress.current = performance.now();
hoverIdx.current = i;
press(i);
}
retarget();
};
const onKeyDown = (e: KeyboardEvent<HTMLDivElement>) => {
const n = items.length;
let next = focusIdx;
if (e.key === "ArrowRight" || e.key === "ArrowDown") next = (focusIdx + 1) % n;
else if (e.key === "ArrowLeft" || e.key === "ArrowUp") next = (focusIdx - 1 + n) % n;
else if (e.key === "Home") next = 0;
else if (e.key === "End") next = n - 1;
else return;
e.preventDefault();
keyboard.current = true;
setFocusIdx(next);
btnRefs.current[next]?.focus();
};
const radius = size / 2;
// without a backdrop to refract, the page behind is frosted by the browser and the GPU adds the bevel light
const cssFrost = !gpu || !hasTex;
return (
<div
ref={rootRef}
role="toolbar"
aria-label={ariaLabel}
aria-orientation="horizontal"
onKeyDown={onKeyDown}
onPointerDown={onPointerDown}
onPointerMove={onPointerMove}
onPointerUp={onPointerUp}
onPointerCancel={onPointerUp}
onPointerLeave={() => {
if (pressing.current) return;
hoverIdx.current = null;
retarget();
}}
className={["relative inline-flex touch-none items-center select-none", className].filter(Boolean).join(" ")}
style={{ height: size, padding: pad, gap, borderRadius: radius }}
>
{cssFrost && (
<div
aria-hidden="true"
className="pointer-events-none absolute inset-0"
style={{
borderRadius: radius,
backdropFilter: `blur(${blur + 12}px) saturate(1.6)`,
WebkitBackdropFilter: `blur(${blur + 12}px) saturate(1.6)`,
background: gpu ? undefined : `rgba(${hex(tint).map((v) => Math.round(v * 255)).join(",")}, ${frost})`,
}}
/>
)}
{items.map((it, i) => {
const on = selectable && selected === it.id;
return (
<button
key={it.id}
ref={(el) => {
btnRefs.current[i] = el;
}}
type="button"
aria-label={it.label}
title={it.label}
aria-pressed={selectable ? on : undefined}
tabIndex={i === focusIdx ? 0 : -1}
onPointerEnter={() => {
if (pressing.current) return;
keyboard.current = false;
hoverIdx.current = i;
retarget();
}}
onFocus={() => setFocusIdx(i)}
onBlur={(e) => {
if (rootRef.current?.contains(e.relatedTarget as Node | null)) return;
keyboard.current = false;
retarget();
}}
onKeyUp={(e) => {
if (e.key === "Tab") {
keyboard.current = true;
retarget();
}
}}
onClick={() => {
// pointer presses are handled on release (so the lens can be slid); keys and assistive tech land here
if (performance.now() - lastPointerPress.current < 400) return;
press(i);
}}
className="relative z-10 grid shrink-0 cursor-pointer place-items-center rounded-full border-0 bg-transparent p-0 outline-none focus-visible:shadow-[inset_0_0_0_1.5px_rgba(255,255,255,0.7)]"
style={{ width: btn, height: btn, color: iconColor }}
>
<span
ref={(el) => {
iconRefs.current[i] = el;
}}
className="grid place-items-center will-change-transform"
style={{ width: btn * 0.6, height: btn * 0.6 }}
>
<span className="grid size-full place-items-center">{isBuiltIn(it.icon) ? <BuiltInIcon kind={it.icon} /> : it.icon}</span>
</span>
</button>
);
})}
</div>
);
}
export default LiquidToolbar;
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
16 propsitemsLiquidToolbarItem[]The actions: { id, label, icon, onSelect? }. icon is "plus", "circle", "square" or your own SVG.default Add, Ellipse, Rectangledefault Add, Ellipse, RectanglebackdropRefObject<HTMLImageElement | HTMLVideoElement | HTMLCanvasElement>The image, video or canvas behind the toolbar, refracted through the glass. Without it, the page behind is frosted.valuestring | nullControlled selected id.defaultValuestring | nullInitially selected id when uncontrolled.default nulldefault nullonValueChange(id: string) => voidCalled with the pressed action's id.selectablebooleanKeep the lens on the last pressed action (a tool picker). Off: plain actions.default truedefault truesizenumberHeight of the pill, px.default 76default 76tintstringColour of the glass tint.default "#141416"default "#141416"frostnumberStrength of the tint, 0 clear to 1 solid.default 0.2default 0.2iconColorstringColour of the icons.default "#ffffff"default "#ffffff"refractionnumberStrength of the refraction.default 1default 1dispersionnumberColour fringing in the bevel, 0 to 1.default 0.6default 0.6blurnumberFrosting of what is seen through the glass, px.default 10default 10bevelnumberWidth of the rounded bevel, 0.2 to 1 (share of the half height).default 0.75default 0.75aria-labelstringAccessible name of the toolbar.default "Toolbar"default "Toolbar"classNamestringExtra classes on the toolbar.