Interruptor liquid glass
Interruptor al estilo iOS 26: pastilla de vidrio que se ensancha mientras se mantiene presionada.
Prueba el material con el puntero, al pulsar y con el teclado.
Código completo
Es exactamente el archivo que se descarga. Cópialo a tu proyecto y úsalo.
"use client";
import { createElement, useCallback, useEffect, useId, useLayoutEffect, useRef, useState, useSyncExternalStore, type CSSProperties, type PointerEvent, type ReactNode } from "react";
/** Interruptor liquid glass al estilo iOS 26: la perilla es una lente de cristal transparente que refracta el color del riel y se ensancha mientras se mantiene presionada. React + TypeScript, sin dependencias. */
export type InterruptorLiquidGlassProps = {
checked?: boolean;
defaultChecked?: boolean;
onChange?: (checked: boolean) => void;
label?: string;
disabled?: boolean;
/** Dark para fondos oscuros o con color; light para fondos claros. */
scheme?: "dark" | "light";
variant?: "regular" | "clear";
className?: string;
style?: CSSProperties;
};
const CSS = `
.gcilq-root { box-sizing: border-box; display: inline-flex; align-items: center; gap: 14px; max-width: 100%; font: 500 16px/1.2 -apple-system, "SF Pro Display", ui-sans-serif, system-ui, sans-serif; color: var(--gcilq-fg, #fff); text-shadow: 0 1px 2px rgba(10, 10, 50, .3); }
.gcilq-root[data-s="light"] { --gcilq-fg: #14193d; text-shadow: none; }
.gcilq-root *, .gcilq-root *::before, .gcilq-root *::after { box-sizing: border-box; }
.gcilq-root button { font: inherit; -webkit-tap-highlight-color: transparent; }
.gcilq-root :focus-visible { outline: 2px solid #fff; outline-offset: 4px; border-radius: 999px; }
.gcilq-root[data-s="light"] :focus-visible { outline-color: #14193d; }
@property --gcilq-a { syntax: "<angle>"; inherits: true; initial-value: 135deg; }
@property --gcilq-p { syntax: "<angle>"; inherits: true; initial-value: 0deg; }
@property --gcilq-sx { syntax: "<percentage>"; inherits: true; initial-value: 24%; }
@property --gcilq-sy { syntax: "<percentage>"; inherits: true; initial-value: 8%; }
@property --gcilq-hi { syntax: "<number>"; inherits: true; initial-value: .78; }
@property --gcilq-tc { syntax: "<color>"; inherits: true; initial-value: transparent; }
@property --gcilq-te { syntax: "<color>"; inherits: true; initial-value: transparent; }
.gcilq-g, .gcilq-gf {
--gcilq-a: 135deg; --gcilq-p: 0deg; --gcilq-sx: 24%; --gcilq-sy: 8%;
--gcilq-bl: var(--gcilq-blur, 2.6px); --gcilq-tc: rgba(255,255,255,.025); --gcilq-te: rgba(255,255,255,.12);
--gcilq-sh: rgba(12,16,24,.16); --gcilq-hi: .78; --gcilq-ink: 12,16,24; --gcilq-ins: 3px;
--gcilq-contact: .14; --gcilq-ambient: .2;
position: relative; isolation: isolate; border: 0; color: var(--gcilq-fg, #fff);
background: radial-gradient(115% 120% at 50% 40%, var(--gcilq-tc) 42%, var(--gcilq-te) 100%), linear-gradient(var(--gcilq-sh),var(--gcilq-sh));
-webkit-backdrop-filter: blur(var(--gcilq-bl)) saturate(1.08) brightness(1.02);
backdrop-filter: blur(var(--gcilq-bl)) saturate(1.08) brightness(1.02);
box-shadow: inset .5px 1px 1px rgba(255,255,255,.42), inset -.5px -1px 1.5px rgba(255,255,255,.16), inset 2px 3px 7px -5px rgba(255,255,255,.45), inset -2px -4px 8px -5px rgba(var(--gcilq-ink),.26), 0 1px 2px rgba(var(--gcilq-ink),var(--gcilq-contact)), 0 12px 28px -10px rgba(var(--gcilq-ink),var(--gcilq-ambient));
transition: --gcilq-a 280ms cubic-bezier(.16,1,.3,1), --gcilq-p 320ms cubic-bezier(.22,1.08,.36,1), --gcilq-sx 240ms cubic-bezier(.16,1,.3,1), --gcilq-sy 240ms cubic-bezier(.16,1,.3,1), --gcilq-hi 180ms ease-out, --gcilq-tc 180ms ease-out, --gcilq-te 180ms ease-out, box-shadow 240ms ease-out, transform 360ms cubic-bezier(.22,1.08,.36,1);
}
.gcilq-g[data-v="clear"], .gcilq-gf[data-v="clear"] { --gcilq-bl: var(--gcilq-clear-blur,.45px); --gcilq-tc: rgba(255,255,255,.008); --gcilq-te: rgba(255,255,255,.065); --gcilq-sh: rgba(12,16,24,.07); }
.gcilq-root[data-s="light"] :is(.gcilq-g,.gcilq-gf), .gcilq-g[data-s="light"], .gcilq-gf[data-s="light"] { --gcilq-tc: rgba(255,255,255,.06); --gcilq-te: rgba(255,255,255,.18); --gcilq-sh: rgba(255,255,255,.025); --gcilq-ink: 24,30,38; --gcilq-fg: #17202b; --gcilq-contact: .09; --gcilq-ambient: .13; }
.gcilq-root[data-s="light"] :is(.gcilq-g,.gcilq-gf)[data-v="clear"], .gcilq-g[data-s="light"][data-v="clear"], .gcilq-gf[data-s="light"][data-v="clear"] { --gcilq-tc: rgba(255,255,255,.015); --gcilq-te: rgba(255,255,255,.085); }
/* Nested controls share their parent's optical plane; never blur glass twice. */
.gcilq-gf { -webkit-backdrop-filter: none; backdrop-filter: none; --gcilq-tc: rgba(255,255,255,.04); --gcilq-te: rgba(255,255,255,.12); --gcilq-sh: transparent; }
.gcilq-g[data-r="1"] { backdrop-filter: blur(var(--gcilq-bl)) var(--gcilq-f) saturate(1.08) brightness(1.02); }
.gcilq-g[data-t="solid"], .gcilq-gf[data-t="solid"] { --gcilq-tc: rgba(255,255,255,.19); --gcilq-te: rgba(255,255,255,.32); --gcilq-sh: rgba(12,16,24,.2); font-weight: 650; }
.gcilq-g[data-t="solid"][data-s="light"], .gcilq-gf[data-t="solid"][data-s="light"] { --gcilq-sh: rgba(255,255,255,.08); }
.gcilq-g::before, .gcilq-gf::before { content: ""; position: absolute; inset: 0; z-index: 3; padding: .8px; border-radius: inherit; pointer-events: none; opacity: var(--gcilq-hi);
background: conic-gradient(from calc(var(--gcilq-a) + var(--gcilq-p)), rgba(255,255,255,.04), rgba(255,255,255,.06) 12%, rgba(255,255,255,.88) 21%, rgba(255,255,255,.16) 28%, rgba(255,255,255,.025) 42%, rgba(255,255,255,.04) 60%, rgba(255,255,255,.62) 72%, rgba(255,255,255,.13) 79%, rgba(255,255,255,.04));
-webkit-mask: linear-gradient(#000 0 0) content-box, linear-gradient(#000 0 0); -webkit-mask-composite: xor;
mask: linear-gradient(#000 0 0) content-box, linear-gradient(#000 0 0); mask-composite: exclude;
}
.gcilq-g::after, .gcilq-gf::after { content: ""; position: absolute; inset: var(--gcilq-ins); z-index: -1; border-radius: max(0px,calc(var(--gcilq-r,24px) - var(--gcilq-ins))); pointer-events: none; opacity: .55; transition: opacity 180ms ease-out;
background: radial-gradient(38% 24% at var(--gcilq-sx) var(--gcilq-sy), rgba(255,255,255,.22), transparent 75%), radial-gradient(30% 18% at 84% 98%, rgba(255,255,255,.085), transparent 75%);
box-shadow: inset .5px 1px 1px rgba(255,255,255,.15), inset -.5px -1px 2px rgba(var(--gcilq-ink),.12);
}
.gcilq-root[data-s="light"] :is(.gcilq-g,.gcilq-gf)::before, .gcilq-g[data-s="light"]::before, .gcilq-gf[data-s="light"]::before { background: conic-gradient(from calc(var(--gcilq-a) + var(--gcilq-p)), rgba(var(--gcilq-ink),.08), rgba(255,255,255,.3) 12%, #fff 21%, rgba(255,255,255,.25) 28%, rgba(var(--gcilq-ink),.13) 45%, rgba(var(--gcilq-ink),.03) 60%, rgba(255,255,255,.95) 72%, rgba(255,255,255,.3) 79%, rgba(var(--gcilq-ink),.08)); }
.gcilq-g[data-e="2"] { --gcilq-contact: .17; --gcilq-ambient: .25; box-shadow: inset .5px 1px 1px rgba(255,255,255,.5), inset -.5px -1px 2px rgba(255,255,255,.2), inset 2px 3px 8px -5px rgba(255,255,255,.45), inset -2px -5px 10px -6px rgba(var(--gcilq-ink),.24), 0 2px 4px rgba(var(--gcilq-ink),var(--gcilq-contact)), 0 24px 52px -18px rgba(var(--gcilq-ink),var(--gcilq-ambient)); }
.gcilq-g[data-i], .gcilq-gf[data-i] { cursor: pointer; touch-action: manipulation; }
.gcilq-g:focus-visible, .gcilq-gf:focus-visible { outline: 2px solid var(--gcilq-fg,#fff); outline-offset: 4px; }
@media (hover: hover) and (pointer: fine) {
.gcilq-g[data-i]:hover:not(:disabled), .gcilq-gf[data-i]:hover:not(:disabled) { --gcilq-hi: .98; }
.gcilq-g[data-i]:hover:not(:disabled)::after, .gcilq-gf[data-i]:hover:not(:disabled)::after { opacity: .85; }
.gcilq-g[data-t="solid"][data-i]:hover:not(:disabled), .gcilq-gf[data-t="solid"][data-i]:hover:not(:disabled) { --gcilq-tc: rgba(255,255,255,.25); }
}
.gcilq-g[data-i]:active:not(:disabled), .gcilq-gf[data-i]:active:not(:disabled) { --gcilq-p: 14deg; --gcilq-hi: 1; transform: scale(.985,.97); transition-duration: 80ms; }
.gcilq-g[data-i]:active:not(:disabled)::after, .gcilq-gf[data-i]:active:not(:disabled)::after { opacity: .95; }
.gcilq-g:disabled, .gcilq-gf:disabled { cursor: not-allowed; }
.gcilq-svg { position: absolute; width: 0; height: 0; overflow: hidden; pointer-events: none; }
@supports not ((backdrop-filter: blur(1px)) or (-webkit-backdrop-filter: blur(1px))) {
.gcilq-g { background: rgba(30,36,46,.9); }
.gcilq-root[data-s="light"] .gcilq-g, .gcilq-g[data-s="light"] { background: rgba(245,247,250,.94); }
}
@media (prefers-reduced-transparency: reduce) { .gcilq-g, .gcilq-gf { background: #26303d; color: #fff; -webkit-backdrop-filter: none; backdrop-filter: none; } .gcilq-root[data-s="light"] :is(.gcilq-g,.gcilq-gf), .gcilq-g[data-s="light"], .gcilq-gf[data-s="light"] { background: #f2f5f8; color: #17202b; } }
@media (prefers-reduced-motion: reduce) {
.gcilq-root *, .gcilq-root *::before, .gcilq-root *::after { animation: none !important; transition-duration: .01ms !important; }
.gcilq-g[data-i]:active:not(:disabled), .gcilq-gf[data-i]:active:not(:disabled) { transform: none; }
}
@media (forced-colors: active) { .gcilq-g, .gcilq-gf { border: 1px solid CanvasText; background: Canvas; color: CanvasText; -webkit-backdrop-filter: none; backdrop-filter: none; } .gcilq-g::before, .gcilq-g::after, .gcilq-gf::before, .gcilq-gf::after { display: none; } }
/* Contact and directional travel deform the lens without changing the track. */
.gcilq-sw { position: relative; flex: none; width: 66px; height: 44px; padding: 0; border-radius: 999px; cursor: pointer; touch-action: manipulation; -webkit-tap-highlight-color: transparent; }
.gcilq-root .gcilq-sw[aria-checked="true"][data-v] { --gcilq-tc: var(--gcilq-on,rgba(52,199,89,.5)); --gcilq-te: rgba(80,218,119,.64); }
.gcilq-sw .gcilq-thumb[data-v] { --gcilq-tc: rgba(255,255,255,.045); --gcilq-te: rgba(255,255,255,.24); --gcilq-hi: .94; --gcilq-sh: rgba(12,16,24,.025); position: absolute; top: 4px; left: 4px; width: 38px; height: 36px; border-radius: 999px; translate: 0 0; transform-origin: 50% 50%; pointer-events: none;
transition: translate 400ms cubic-bezier(1,0,.4,1), transform 80ms ease-out, --gcilq-p 280ms ease-out, --gcilq-te 180ms ease-out; }
.gcilq-sw[aria-checked="true"] .gcilq-thumb[data-v] { translate: 20px 0; }
@media (hover: hover) and (pointer: fine) { .gcilq-sw:hover:not(:disabled) .gcilq-thumb[data-v] { --gcilq-te: rgba(255,255,255,.3); } }
.gcilq-sw:active:not(:disabled) .gcilq-thumb[data-v] { --gcilq-p: 14deg; transform: scale(1.05,.97); }
.gcilq-sw:disabled { opacity: .5; cursor: not-allowed; }
@media (prefers-reduced-motion: reduce) { .gcilq-sw:active:not(:disabled) .gcilq-thumb[data-v] { transform: none; } }
@media (forced-colors: active) { .gcilq-sw[aria-checked="true"] { background: Highlight; } }
`;
/** Pulso de forma independiente del viaje: retoma la escala visible si se interrumpe. */
function useGlassStretch(node: HTMLElement | null, position: number, peak = 1.1) {
const previous = useRef<{ node: HTMLElement; position: number } | null>(null);
const pulse = useRef<Animation | null>(null);
useLayoutEffect(() => {
if (!node) return;
const preference = window.matchMedia("(prefers-reduced-motion: reduce)");
const stop = () => { if (preference.matches) pulse.current?.cancel(); };
preference.addEventListener("change", stop);
return () => {
preference.removeEventListener("change", stop);
pulse.current?.cancel();
pulse.current = null;
previous.current = null;
};
}, [node]);
useLayoutEffect(() => {
if (!node) return;
const from = previous.current;
previous.current = { node, position };
if (!from || from.node !== node || from.position === position) return;
const visibleScale = getComputedStyle(node).scale;
pulse.current?.cancel();
if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;
const origin = position > from.position ? "left center" : "right center";
pulse.current = node.animate(
[{ scale: visibleScale === "none" ? "1 1" : visibleScale, transformOrigin: origin }, { scale: `${peak} 1`, transformOrigin: origin, offset: .5 }, { scale: "1 1", transformOrigin: origin }],
{ duration: 440, easing: "ease" },
);
}, [node, position, peak]);
}
/* Motor de vidrio líquido: mapa de desplazamiento por borde (refracción) + dispersión leve, calculado a la medida de cada pieza. */
const noop = () => () => {};
const canRefract = () => typeof window !== "undefined" && typeof window.CSS !== "undefined" && window.CSS.supports("backdrop-filter", "url(#a)") && /Chrome\//.test(navigator.userAgent);
const bend = (t: number) => {
const u = 1 - t;
const th = Math.atan(Math.pow(Math.max(1 - u * u * u * u, 1e-6), -0.75) * u * u * u * 0.9);
return Math.sin(th - Math.asin(Math.sin(th) / 1.5));
};
const PEAK = bend(0.02);
/** Mapa R/G de desplazamiento: 0 en el centro, máximo en el borde (perfil de cristal convexo y ley de Snell, n = 1.5). */
const mapCache = new Map<string, string>();
function glassMap(w: number, h: number, r: number, bezel: number): string {
const key = [w, h, r, bezel].join(":");
const cached = mapCache.get(key);
if (cached) return cached;
const k = Math.min(1, Math.sqrt(90000 / (w * h)));
const cw = Math.max(2, Math.round(w * k));
const ch = Math.max(2, Math.round(h * k));
const canvas = document.createElement("canvas");
canvas.width = cw;
canvas.height = ch;
const ctx = canvas.getContext("2d");
if (!ctx) return "";
const img = ctx.createImageData(cw, ch);
const hx = w / 2;
const hy = h / 2;
for (let j = 0; j < ch; j++) {
for (let i = 0; i < cw; i++) {
const px = (i + 0.5) * w / cw - hx;
const py = (j + 0.5) * h / ch - hy;
const qx = Math.abs(px) - (hx - r);
const qy = Math.abs(py) - (hy - r);
let nx = 0;
let ny = 0;
let d: number;
if (qx > 0 && qy > 0) {
const l = Math.hypot(qx, qy);
d = r - l;
nx = qx / l;
ny = qy / l;
} else if (qx > qy) {
d = hx - Math.abs(px);
nx = 1;
} else {
d = hy - Math.abs(py);
ny = 1;
}
const t = d / bezel;
const m = t >= 1 ? 0 : Math.min(1, bend(Math.max(t, 0.02)) / PEAK);
const o = (j * cw + i) * 4;
img.data[o] = 128 - (Math.sign(px) || 1) * nx * m * 127;
img.data[o + 1] = 128 - (Math.sign(py) || 1) * ny * m * 127;
img.data[o + 2] = 128;
img.data[o + 3] = 255;
}
}
ctx.putImageData(img, 0, 0);
const map = canvas.toDataURL();
if (mapCache.size >= 24) mapCache.delete(mapCache.keys().next().value!);
mapCache.set(key, map);
return map;
}
type SurfaceProps = {
as?: string;
/** Radio de las esquinas en px; por defecto el que resuelve el CSS. */
radius?: number;
/** Ancho de la franja que refracta, en px. */
bezel?: number;
/** Desplazamiento máximo del fondo en el borde, en px. */
depth?: number;
variant?: "regular" | "clear";
/** Solid: mayor contraste para la acción principal, conservando transparencia. */
tone?: "solid";
scheme?: "dark" | "light";
elevated?: boolean;
flat?: boolean;
interactive?: boolean;
elRef?: (node: HTMLElement | null) => void;
className?: string;
style?: CSSProperties;
children?: ReactNode;
onPointerMove?: (event: PointerEvent<HTMLElement>) => void;
onPointerLeave?: (event: PointerEvent<HTMLElement>) => void;
[prop: string]: unknown;
};
/** Superficie de vidrio: refracta el fondo en Chromium (SVG + backdrop-filter) y cae a vidrio con desenfoque en el resto; el borde óptico, el volumen y las sombras no dependen del filtro. */
function Surface({ as = "div", radius, bezel, depth, variant = "regular", tone, scheme = "dark", elevated, flat, interactive, elRef, className = "", style, children, onPointerMove, onPointerLeave, ...rest }: SurfaceProps) {
const id = `gcilq-f-${useId().replace(/[^a-zA-Z0-9]/g, "")}`;
const refract = useSyncExternalStore(noop, canRefract, () => false) && !flat;
const [node, setNode] = useState<HTMLElement | null>(null);
const [lens, setLens] = useState<{ w: number; h: number; r: number; depth: number; map: string } | null>(null);
const bind = useCallback(
(el: HTMLElement | null) => {
setNode(el);
elRef?.(el);
},
[elRef],
);
useEffect(() => {
if (!node || !refract) return;
let lw = 0;
let lh = 0;
let frame = 0;
const measure = () => {
const w = node.offsetWidth;
const h = node.offsetHeight;
if (!w || !h || (w === lw && h === lh)) return;
lw = w;
lh = h;
const corner = getComputedStyle(node).borderTopLeftRadius;
const resolved = corner.endsWith("%") ? parseFloat(corner) / 100 * Math.min(w, h) : parseFloat(corner) || 0;
const r = Math.min(radius ?? resolved, w / 2, h / 2);
const bz = Math.max(6, Math.min(bezel ?? Math.min(w, h) * 0.24, Math.min(w, h) / 2, 48));
const map = glassMap(w, h, r, bz);
setLens(map ? { w, h, r, depth: (depth ?? Math.round(bz * .85)) * (variant === "clear" ? 1 : .85), map } : null);
};
const observer = new ResizeObserver(() => {
cancelAnimationFrame(frame);
frame = requestAnimationFrame(measure);
});
observer.observe(node);
return () => { observer.disconnect(); cancelAnimationFrame(frame); };
}, [node, refract, radius, bezel, depth, variant]);
const live = refract && lens;
const move = (event: PointerEvent<HTMLElement>) => {
if (event.pointerType !== "touch" && !event.currentTarget.matches(":disabled") && !window.matchMedia("(prefers-reduced-motion: reduce)").matches) {
const box = event.currentTarget.getBoundingClientRect();
const x = Math.max(0, Math.min(1, (event.clientX - box.left) / box.width));
const y = Math.max(0, Math.min(1, (event.clientY - box.top) / box.height));
event.currentTarget.style.setProperty("--gcilq-a", `${135 + (x - 0.5) * 40 - (y - 0.5) * 18}deg`);
event.currentTarget.style.setProperty("--gcilq-sx", `${18 + x * 64}%`);
event.currentTarget.style.setProperty("--gcilq-sy", `${3 + y * 12}%`);
}
onPointerMove?.(event);
};
const leave = (event: PointerEvent<HTMLElement>) => {
for (const name of ["a", "sx", "sy"]) event.currentTarget.style.removeProperty(`--gcilq-${name}`);
onPointerLeave?.(event);
};
return createElement(
as,
{
...rest,
ref: bind,
className: `gcilq-${flat ? "gf" : "g"} ${className}`,
"data-v": variant,
"data-s": scheme,
"data-t": tone,
"data-r": live ? "1" : undefined,
"data-e": elevated ? "2" : undefined,
"data-i": interactive ? "1" : undefined,
style: { ...style, "--gcilq-r": live ? `${lens.r}px` : radius !== undefined ? `${radius}px` : undefined, "--gcilq-f": live ? `url(#${id})` : undefined } as CSSProperties,
onPointerMove: move,
onPointerLeave: leave,
},
live ? (
<svg className="gcilq-svg" aria-hidden="true" focusable="false">
<filter id={id} filterUnits="userSpaceOnUse" x={-lens.depth} y={-lens.depth} width={lens.w + lens.depth * 2} height={lens.h + lens.depth * 2} colorInterpolationFilters="sRGB">
<feImage href={lens.map} x={0} y={0} width={lens.w} height={lens.h} preserveAspectRatio="none" result="m" />
<feDisplacementMap in="SourceGraphic" in2="m" scale={lens.depth * 1.012} xChannelSelector="R" yChannelSelector="G" result="dr" />
<feColorMatrix in="dr" type="matrix" values="1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1" result="cr" />
<feDisplacementMap in="SourceGraphic" in2="m" scale={lens.depth} xChannelSelector="R" yChannelSelector="G" result="dg" />
<feColorMatrix in="dg" type="matrix" values="0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1" result="cg" />
<feDisplacementMap in="SourceGraphic" in2="m" scale={lens.depth * .988} xChannelSelector="R" yChannelSelector="G" result="db" />
<feColorMatrix in="db" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1" result="cb" />
<feBlend in="cr" in2="cg" mode="screen" result="rg" />
<feBlend in="rg" in2="cb" mode="screen" />
</filter>
</svg>
) : null,
children,
);
}
export function InterruptorLiquidGlass({ checked, defaultChecked = true, onChange, label = "Wi-Fi", disabled, variant = "regular", scheme = "dark", className = "", style }: InterruptorLiquidGlassProps) {
const [inner, setInner] = useState(defaultChecked);
const on = checked ?? inner;
const [indicator, setIndicator] = useState<HTMLElement | null>(null);
useGlassStretch(indicator, on ? 20 : 0);
return (
<span className={`gcilq-root ${className}`} style={style} data-s={scheme}>
<style>{CSS}</style>
<Surface as="button"
className="gcilq-sw" flat variant={variant} scheme={scheme}
type="button"
role="switch"
aria-checked={on}
aria-label={label}
disabled={disabled}
onClick={() => {
setInner(!on);
onChange?.(!on);
}}
>
<Surface as="span" className="gcilq-thumb" elRef={setIndicator} variant="clear" scheme={scheme} radius={18} bezel={15} depth={17} />
</Surface>
<span aria-hidden="true">{label}</span>
</span>
);
}
Úsalo en tu proyecto
Instálalo con la CLI de shadcn.
npx shadcn@latest add https://www.gassierconsulting.com/r/interruptor-liquid-glassEjemplo de uso de Interruptor liquid glass
Después de copiar interruptor-liquid-glass.tsx a tu proyecto, impórtalo y colócalo donde lo necesites.
import { InterruptorLiquidGlass } from "./interruptor-liquid-glass";
export default function Ejemplo() {
return <InterruptorLiquidGlass scheme="dark" label="Ejemplo" checked />;
}Propiedades de InterruptorLiquidGlass
InterruptorLiquidGlass acepta 9 propiedades: todas son opcionales y tienen un valor por defecto, así que funciona sin configurar nada.
| Propiedad | Tipo | Descripción |
|---|---|---|
checked? | boolean | Opcional. |
defaultChecked? | boolean | Opcional. |
onChange? | (checked: boolean) => void | Opcional. |
label? | string | Opcional. |
disabled? | boolean | Opcional. |
scheme? | "dark" | "light" | Dark para fondos oscuros o con color; light para fondos claros. |
variant? | "regular" | "clear" | Opcional. |
className? | string | Opcional. |
style? | CSSProperties | Opcional. |
Variantes disponibles
scheme:dark,lightvariant:regular,clear
Personaliza Interruptor liquid glass con variables CSS
Define estas variables en el contenedor o en tu hoja de estilos para cambiar los colores sin tocar el componente. Si no las defines, se usa el valor por defecto.
| Variable | Valor por defecto |
|---|---|
--gcilq-fg | #fff |
--gcilq-blur | 2.6px |
--gcilq-clear-blur | .45px |
--gcilq-r | 24px |
--gcilq-on | rgba(52,199,89,.5) |
Accesibilidad y rendimiento
El archivo tiene 339 líneas (21 KB) y no necesita @keyframes. Esto es lo que hace Interruptor liquid glass por quien lo usa:
- Detecta prefers-reduced-motion y baja o quita el movimiento cuando la persona lo pide.
- Muestra un anillo de foco visible al navegar con teclado (:focus-visible).
- Declara roles ARIA para lectores de pantalla: switch.
- Reacciona al puntero con eventos pointer (ratón, lápiz y táctil).
- Anima con requestAnimationFrame, sincronizado con el refresco de pantalla.
- Usa backdrop-filter para el efecto de vidrio; en navegadores sin soporte el panel se ve sin desenfoque.
- Lee preferencias del navegador con useSyncExternalStore, sin parpadeos en la hidratación.
- Usa @property de CSS para animar valores que normalmente no se interpolan.
- Es un componente de cliente de Next.js: incluye la directiva "use client".