Ir al contenido
Evaluar mi proyecto
Componentes · Modales y capasDisponible

Diálogo liquid glass

Diálogo de cristal líquido que nace del propio botón y refracta el fondo en su borde, con formulario validado.

Material
Fondo

Únete a la lista

Te avisaremos en cuanto abramos el acceso anticipado.

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.

capa-dialogo-vidrio.tsx378 líneas
Descargar
"use client";

import { createElement, useCallback, useEffect, useId, useRef, useState, useSyncExternalStore, type CSSProperties, type PointerEvent, type ReactNode } from "react";

/** Diálogo modal liquid glass: el panel nace del propio botón (la geometría se expande sin saltos), refracta el fondo en su borde y usa <dialog> nativo con formulario de dos campos. React + TypeScript, sin dependencias. */
export type CapaDialogoVidrioProps = {
  trigger?: string;
  title?: string;
  description?: string;
  onSubmit?: (data: { name: string; email: string }) => void;
  variant?: "regular" | "clear";
  scheme?: "dark" | "light";
  className?: string;
  style?: CSSProperties;
};

const CSS = `
.gccdv-root { box-sizing: border-box; display: inline-block; font: 500 15px/1.5 -apple-system, "SF Pro Display", ui-sans-serif, system-ui, sans-serif; color: #fff; }
.gccdv-root *, .gccdv-root *::before, .gccdv-root *::after { box-sizing: border-box; }
.gccdv-root button, .gccdv-root input { font: inherit; }
.gccdv-root :focus-visible { outline: 2px solid #fff; outline-offset: 3px; }
.gccdv-root[data-s="light"] { color: #17202b; text-shadow: none; }
@property --gccdv-a { syntax: "<angle>"; inherits: true; initial-value: 135deg; }
@property --gccdv-p { syntax: "<angle>"; inherits: true; initial-value: 0deg; }
@property --gccdv-sx { syntax: "<percentage>"; inherits: true; initial-value: 24%; }
@property --gccdv-sy { syntax: "<percentage>"; inherits: true; initial-value: 8%; }
@property --gccdv-hi { syntax: "<number>"; inherits: true; initial-value: .78; }
@property --gccdv-tc { syntax: "<color>"; inherits: true; initial-value: transparent; }
@property --gccdv-te { syntax: "<color>"; inherits: true; initial-value: transparent; }
.gccdv-g, .gccdv-gf {
  --gccdv-a: 135deg; --gccdv-p: 0deg; --gccdv-sx: 24%; --gccdv-sy: 8%;
  --gccdv-bl: var(--gccdv-blur, 2.6px); --gccdv-tc: rgba(255,255,255,.025); --gccdv-te: rgba(255,255,255,.12);
  --gccdv-sh: rgba(12,16,24,.16); --gccdv-hi: .78; --gccdv-ink: 12,16,24; --gccdv-ins: 3px;
  --gccdv-contact: .14; --gccdv-ambient: .2;
  position: relative; isolation: isolate; border: 0; color: var(--gccdv-fg, #fff);
  background: radial-gradient(115% 120% at 50% 40%, var(--gccdv-tc) 42%, var(--gccdv-te) 100%), linear-gradient(var(--gccdv-sh),var(--gccdv-sh));
  -webkit-backdrop-filter: blur(var(--gccdv-bl)) saturate(1.08) brightness(1.02);
  backdrop-filter: blur(var(--gccdv-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(--gccdv-ink),.26), 0 1px 2px rgba(var(--gccdv-ink),var(--gccdv-contact)), 0 12px 28px -10px rgba(var(--gccdv-ink),var(--gccdv-ambient));
  transition: --gccdv-a 280ms cubic-bezier(.16,1,.3,1), --gccdv-p 320ms cubic-bezier(.22,1.08,.36,1), --gccdv-sx 240ms cubic-bezier(.16,1,.3,1), --gccdv-sy 240ms cubic-bezier(.16,1,.3,1), --gccdv-hi 180ms ease-out, --gccdv-tc 180ms ease-out, --gccdv-te 180ms ease-out, box-shadow 240ms ease-out, transform 360ms cubic-bezier(.22,1.08,.36,1);
}
.gccdv-g[data-v="clear"], .gccdv-gf[data-v="clear"] { --gccdv-bl: var(--gccdv-clear-blur,.45px); --gccdv-tc: rgba(255,255,255,.008); --gccdv-te: rgba(255,255,255,.065); --gccdv-sh: rgba(12,16,24,.07); }
.gccdv-root[data-s="light"] :is(.gccdv-g,.gccdv-gf), .gccdv-g[data-s="light"], .gccdv-gf[data-s="light"] { --gccdv-tc: rgba(255,255,255,.06); --gccdv-te: rgba(255,255,255,.18); --gccdv-sh: rgba(255,255,255,.025); --gccdv-ink: 24,30,38; --gccdv-fg: #17202b; --gccdv-contact: .09; --gccdv-ambient: .13; }
.gccdv-root[data-s="light"] :is(.gccdv-g,.gccdv-gf)[data-v="clear"], .gccdv-g[data-s="light"][data-v="clear"], .gccdv-gf[data-s="light"][data-v="clear"] { --gccdv-tc: rgba(255,255,255,.015); --gccdv-te: rgba(255,255,255,.085); }
/* Nested controls share their parent's optical plane; never blur glass twice. */
.gccdv-gf { -webkit-backdrop-filter: none; backdrop-filter: none; --gccdv-tc: rgba(255,255,255,.04); --gccdv-te: rgba(255,255,255,.12); --gccdv-sh: transparent; }
.gccdv-g[data-r="1"] { backdrop-filter: blur(var(--gccdv-bl)) var(--gccdv-f) saturate(1.08) brightness(1.02); }
.gccdv-g[data-t="solid"], .gccdv-gf[data-t="solid"] { --gccdv-tc: rgba(255,255,255,.19); --gccdv-te: rgba(255,255,255,.32); --gccdv-sh: rgba(12,16,24,.2); font-weight: 650; }
.gccdv-g[data-t="solid"][data-s="light"], .gccdv-gf[data-t="solid"][data-s="light"] { --gccdv-sh: rgba(255,255,255,.08); }
.gccdv-g::before, .gccdv-gf::before { content: ""; position: absolute; inset: 0; z-index: 3; padding: .8px; border-radius: inherit; pointer-events: none; opacity: var(--gccdv-hi);
  background: conic-gradient(from calc(var(--gccdv-a) + var(--gccdv-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;
}
.gccdv-g::after, .gccdv-gf::after { content: ""; position: absolute; inset: var(--gccdv-ins); z-index: -1; border-radius: max(0px,calc(var(--gccdv-r,24px) - var(--gccdv-ins))); pointer-events: none; opacity: .55; transition: opacity 180ms ease-out;
  background: radial-gradient(38% 24% at var(--gccdv-sx) var(--gccdv-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(--gccdv-ink),.12);
}
.gccdv-root[data-s="light"] :is(.gccdv-g,.gccdv-gf)::before, .gccdv-g[data-s="light"]::before, .gccdv-gf[data-s="light"]::before { background: conic-gradient(from calc(var(--gccdv-a) + var(--gccdv-p)), rgba(var(--gccdv-ink),.08), rgba(255,255,255,.3) 12%, #fff 21%, rgba(255,255,255,.25) 28%, rgba(var(--gccdv-ink),.13) 45%, rgba(var(--gccdv-ink),.03) 60%, rgba(255,255,255,.95) 72%, rgba(255,255,255,.3) 79%, rgba(var(--gccdv-ink),.08)); }
.gccdv-g[data-e="2"] { --gccdv-contact: .17; --gccdv-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(--gccdv-ink),.24), 0 2px 4px rgba(var(--gccdv-ink),var(--gccdv-contact)), 0 24px 52px -18px rgba(var(--gccdv-ink),var(--gccdv-ambient)); }
.gccdv-g[data-i], .gccdv-gf[data-i] { cursor: pointer; touch-action: manipulation; }
.gccdv-g:focus-visible, .gccdv-gf:focus-visible { outline: 2px solid var(--gccdv-fg,#fff); outline-offset: 4px; }
@media (hover: hover) and (pointer: fine) {
  .gccdv-g[data-i]:hover:not(:disabled), .gccdv-gf[data-i]:hover:not(:disabled) { --gccdv-hi: .98; }
  .gccdv-g[data-i]:hover:not(:disabled)::after, .gccdv-gf[data-i]:hover:not(:disabled)::after { opacity: .85; }
  .gccdv-g[data-t="solid"][data-i]:hover:not(:disabled), .gccdv-gf[data-t="solid"][data-i]:hover:not(:disabled) { --gccdv-tc: rgba(255,255,255,.25); }
}
.gccdv-g[data-i]:active:not(:disabled), .gccdv-gf[data-i]:active:not(:disabled) { --gccdv-p: 14deg; --gccdv-hi: 1; transform: scale(.985,.97); transition-duration: 80ms; }
.gccdv-g[data-i]:active:not(:disabled)::after, .gccdv-gf[data-i]:active:not(:disabled)::after { opacity: .95; }
.gccdv-g:disabled, .gccdv-gf:disabled { cursor: not-allowed; }
.gccdv-svg { position: absolute; width: 0; height: 0; overflow: hidden; pointer-events: none; }
@supports not ((backdrop-filter: blur(1px)) or (-webkit-backdrop-filter: blur(1px))) {
  .gccdv-g { background: rgba(30,36,46,.9); }
  .gccdv-root[data-s="light"] .gccdv-g, .gccdv-g[data-s="light"] { background: rgba(245,247,250,.94); }
}
@media (prefers-reduced-transparency: reduce) { .gccdv-g, .gccdv-gf { background: #26303d; color: #fff; -webkit-backdrop-filter: none; backdrop-filter: none; } .gccdv-root[data-s="light"] :is(.gccdv-g,.gccdv-gf), .gccdv-g[data-s="light"], .gccdv-gf[data-s="light"] { background: #f2f5f8; color: #17202b; } }
@media (prefers-reduced-motion: reduce) {
  .gccdv-root *, .gccdv-root *::before, .gccdv-root *::after { animation: none !important; transition-duration: .01ms !important; }
  .gccdv-g[data-i]:active:not(:disabled), .gccdv-gf[data-i]:active:not(:disabled) { transform: none; }
}
@media (forced-colors: active) { .gccdv-g, .gccdv-gf { border: 1px solid CanvasText; background: Canvas; color: CanvasText; -webkit-backdrop-filter: none; backdrop-filter: none; } .gccdv-g::before, .gccdv-g::after, .gccdv-gf::before, .gccdv-gf::after { display: none; } }

.gccdv-open { min-height: 52px; padding: 0 28px; border-radius: 999px; font-weight: 600; text-shadow: 0 1px 2px rgba(10, 10, 60, .3); }
.gccdv-dlg { position: fixed; margin: auto; inset: 0; width: min(420px, calc(100vw - 32px)); height: fit-content; max-height: calc(100dvh - 32px); overflow: auto; padding: 28px; border-radius: 32px; text-shadow: 0 1px 3px rgba(10, 10, 70, .3); }
.gccdv-dlg:not([open]) { display: none; }
.gccdv-dlg::backdrop { background: rgba(12,16,24,.22); animation: gccdv-fade .4s ease-out; }
.gccdv-root .gccdv-title { color: inherit; margin: 0 0 6px; font-size: 24px; font-weight: 700; letter-spacing: -.03em; }
.gccdv-root .gccdv-desc { color: inherit; margin: 0 0 18px; opacity: .92; }
.gccdv-f { display: grid; gap: 10px; margin-bottom: 20px; }
.gccdv-in { width: 100%; height: 50px; padding: 0 18px; border: 0; border-radius: 18px; background: rgba(255, 255, 255, .1); color: inherit; box-shadow: inset 0 2px 5px rgba(8, 6, 40, .26), inset 0 -1px 0 rgba(255, 255, 255, .28), inset 0 0 0 1px rgba(255, 255, 255, .1); text-shadow: none; transition: background .25s, box-shadow .25s; }
.gccdv-in::placeholder { color: color-mix(in srgb,currentColor 78%,transparent); }
.gccdv-in:focus-visible { outline: 0; background: rgba(255, 255, 255, .17); box-shadow: inset 0 2px 5px rgba(8, 6, 40, .22), inset 0 -1px 0 rgba(255, 255, 255, .4), 0 0 0 2px rgba(255, 255, 255, .8); }
.gccdv-root[data-s="light"] .gccdv-in:focus-visible { box-shadow: inset 0 2px 5px rgba(12,16,24,.1), 0 0 0 2px #17202b; }
.gccdv-foot { display: flex; gap: 10px; }
.gccdv-b { flex: 1; min-height: 50px; border-radius: 999px; font-weight: 600; }
@keyframes gccdv-fade { from { opacity: 0; } }`;

/* 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 = `gccdv-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("--gccdv-a", `${135 + (x - 0.5) * 40 - (y - 0.5) * 18}deg`);
      event.currentTarget.style.setProperty("--gccdv-sx", `${18 + x * 64}%`);
      event.currentTarget.style.setProperty("--gccdv-sy", `${3 + y * 12}%`);
    }
    onPointerMove?.(event);
  };
  const leave = (event: PointerEvent<HTMLElement>) => {
    for (const name of ["a", "sx", "sy"]) event.currentTarget.style.removeProperty(`--gccdv-${name}`);
    onPointerLeave?.(event);
  };

  return createElement(
    as,
    {
      ...rest,
      ref: bind,
      className: `gccdv-${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, "--gccdv-r": live ? `${lens.r}px` : radius !== undefined ? `${radius}px` : undefined, "--gccdv-f": live ? `url(#${id})` : undefined } as CSSProperties,
      onPointerMove: move,
      onPointerLeave: leave,
    },
    live ? (
      <svg className="gccdv-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,
  );
}

const SPRING = "cubic-bezier(.22, 1.04, .36, 1)";
const still = () => window.matchMedia("(prefers-reduced-motion: reduce)").matches;

export function CapaDialogoVidrio({ trigger = "Unirme a la lista", title = "Únete a la lista", description = "Te avisaremos en cuanto abramos el acceso anticipado.", onSubmit, variant = "regular", scheme = "dark", className = "", style }: CapaDialogoVidrioProps) {
  const id = useId();
  const [dlg, setDlg] = useState<HTMLElement | null>(null);
  const origin = useRef<DOMRect | null>(null);
  const closing = useRef<Animation | null>(null);
  const box = dlg as HTMLDialogElement | null;

  /** Transformación que lleva el panel a la forma y posición del botón. */
  function fromOrigin() {
    const from = origin.current;
    if (!box || !from) return null;
    const to = box.getBoundingClientRect();
    const sx = Math.min(1, from.width / to.width);
    const sy = Math.min(1, from.height / to.height);
    const dx = from.left + from.width / 2 - (to.left + to.width / 2);
    const dy = from.top + from.height / 2 - (to.top + to.height / 2);
    return { transform: `translate(${dx}px, ${dy}px) scale(${sx}, ${sy})`, borderRadius: `${from.height / 2 / sx}px / ${from.height / 2 / sy}px` };
  }

  function open(event: PointerEvent<HTMLElement> | { currentTarget: HTMLElement }) {
    if (!box || box.open) return;
    origin.current = event.currentTarget.getBoundingClientRect();
    box.showModal();
    if (still()) return;
    const start = fromOrigin();
    if (!start) return;
    box.animate([{ ...start, opacity: .55 }, { transform: "none", borderRadius: "32px / 32px", opacity: 1 }], { duration: 460, easing: SPRING });
    box.animate([{ boxShadow: "0 2px 6px rgba(12,16,24,.08)" }, { boxShadow: getComputedStyle(box).boxShadow }], { duration: 380, easing: "ease-out" });
    box.querySelector("form")?.animate([{ opacity: 0, transform: "translateY(5px)" }, { opacity: 1, transform: "none" }], { duration: 240, delay: 100, easing: "cubic-bezier(.16, 1, .3, 1)", fill: "backwards" });
  }

  function close() {
    if (!box || !box.open || closing.current) return;
    const end = still() ? null : fromOrigin();
    if (!end) {
      box.close();
      return;
    }
    // Capture the current pose before cancelling: Escape during expansion stays continuous.
    const current = getComputedStyle(box);
    const start = { transform: current.transform, borderRadius: current.borderRadius, opacity: current.opacity };
    for (const animation of box.getAnimations({ subtree: true })) animation.cancel();
    const leave = box.animate([start, { ...end, opacity: 0 }], { duration: 240, easing: "cubic-bezier(.4,0,.6,1)", fill: "forwards" });
    closing.current = leave;
    const finish = () => { box.close(); leave.cancel(); closing.current = null; };
    leave.finished.then(finish, finish);
  }

  return (
    <div className={`gccdv-root ${className}`} style={style} data-s={scheme}>
      <style>{CSS}</style>
      <Surface as="button" className="gccdv-open" type="button" variant={variant} interactive bezel={20} depth={22} onClick={open}>
        {trigger}
      </Surface>
      <Surface
        as="dialog"
        elRef={setDlg}
        className="gccdv-dlg"
        aria-labelledby={`${id}-t`}
        variant={variant}
        elevated
        radius={32}
        bezel={30}
        depth={30}
        onCancel={(event: { preventDefault: () => void }) => {
          event.preventDefault();
          close();
        }}
        onClick={(event: { target: unknown; clientX: number; clientY: number }) => {
          if (event.target !== dlg || !box) return;
          const rect = box.getBoundingClientRect();
          if (event.clientX < rect.left || event.clientX > rect.right || event.clientY < rect.top || event.clientY > rect.bottom) close();
        }}
      >
        <form
          onSubmit={(event) => {
            event.preventDefault();
            const data = new FormData(event.currentTarget);
            onSubmit?.({ name: String(data.get("name") ?? ""), email: String(data.get("email") ?? "") });
            close();
          }}
        >
          <h2 className="gccdv-title" id={`${id}-t`}>{title}</h2>
          <p className="gccdv-desc">{description}</p>
          <div className="gccdv-f">
            <input className="gccdv-in" name="name" aria-label="Nombre" placeholder="Tu nombre" required />
            <input className="gccdv-in" name="email" type="email" aria-label="Correo" placeholder="tu@correo.com" required />
          </div>
          <div className="gccdv-foot">
            <Surface as="button" flat interactive className="gccdv-b" type="button" onClick={close}>Ahora no</Surface>
            <Surface as="button" flat interactive tone="solid" className="gccdv-b" type="submit">Apuntarme</Surface>
          </div>
        </form>
      </Surface>
    </div>
  );
}

Úsalo en tu proyecto

Instálalo con la CLI de shadcn.

terminal.sh1 líneas
npx shadcn@latest add https://www.gassierconsulting.com/r/capa-dialogo-vidrio

Ejemplo de uso de Diálogo liquid glass

Después de copiar capa-dialogo-vidrio.tsx a tu proyecto, impórtalo y colócalo donde lo necesites.

ejemplo.tsx5 líneas
import { CapaDialogoVidrio } from "./capa-dialogo-vidrio";

export default function Ejemplo() {
  return <CapaDialogoVidrio variant="regular" trigger="Ejemplo" />;
}

Propiedades de CapaDialogoVidrio

CapaDialogoVidrio acepta 8 propiedades: todas son opcionales y tienen un valor por defecto, así que funciona sin configurar nada.

PropiedadTipoDescripción
trigger?stringOpcional.
title?stringOpcional.
description?stringOpcional.
onSubmit?(data: { name: string; email: string }) => voidOpcional.
variant?"regular" | "clear"Opcional.
scheme?"dark" | "light"Opcional.
className?stringOpcional.
style?CSSPropertiesOpcional.

Variantes disponibles

  • variant: regular, clear
  • scheme: dark, light

Personaliza Diálogo 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.

VariableValor por defecto
--gccdv-blur2.6px
--gccdv-fg#fff
--gccdv-clear-blur.45px
--gccdv-r24px

Accesibilidad y rendimiento

El archivo tiene 378 líneas (23 KB) y define 1 animación con @keyframes. Esto es lo que hace Diálogo 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).
  • Expone su estado a tecnologías de apoyo con atributos aria-*.
  • Usa el elemento <dialog> nativo, con foco y cierre con Escape gestionados por el navegador.
  • 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.
  • Calcula tonos con color-mix(), así que un solo color base alcanza.
  • Es un componente de cliente de Next.js: incluye la directiva "use client".
Licencia
MIT
Dependencias
React >=18
Compatibilidad
React 18 y 19 · Next.js (componente de cliente)

Acerca del producto

Diálogo de cristal líquido que nace del propio botón, refracta el fondo en su borde y trae un formulario de dos campos validado.