Ir al contenido
Evaluar mi proyecto
Componentes · NavegaciónDisponible

Barra flotante liquid glass

Pastilla de vidrio que sigue al puntero o al enlace activo, ajustándose a su ancho con un resorte.

Material
Fondo

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.

nav-flotante.tsx354 líneas
Descargar
"use client";

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

/** Barra de navegación flotante en liquid glass: la barra es una pieza de cristal que refracta el fondo, y una pastilla de vidrio sigue al puntero o al enlace activo ajustándose a su ancho y estirándose hacia el destino. Teclado y foco incluidos. React + TypeScript, sin dependencias. */
export type NavFlotanteProps = {
  brand?: string;
  links?: { label: string; href?: string }[];
  cta?: string;
  variant?: "regular" | "clear";
  /** Dark para fondos oscuros o con color; light para fondos claros. */
  scheme?: "dark" | "light";
  className?: string;
  style?: CSSProperties;
};

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

.gcnfl-bar { display: flex; align-items: center; gap: 4px; max-width: 100%; padding: 6px; border-radius: 999px; text-shadow: 0 1px 2px rgba(10, 10, 60, .28); }
.gcnfl-root[data-s="light"] .gcnfl-bar { text-shadow: none; }
.gcnfl-brand { padding: 0 16px 0 14px; font-weight: 800; letter-spacing: -.02em; font-size: 15px; }
.gcnfl-links { position: relative; display: flex; gap: 2px; margin: 0; padding: 0; list-style: none; }
.gcnfl-links li { display: contents; }
.gcnfl-links .gcnfl-ind { position: absolute; top: 0; bottom: 0; left: 0; z-index: 0; width: 0; border-radius: 999px; pointer-events: none; --gcnfl-tc: rgba(255,255,255,.08); --gcnfl-te: rgba(255,255,255,.2); transition: translate 400ms cubic-bezier(1,0,.4,1), width 400ms cubic-bezier(1,0,.4,1), opacity .2s; }
.gcnfl-link { position: relative; z-index: 1; display: flex; align-items: center; min-height: 44px; padding: 12px 18px; border-radius: 999px; color: inherit; text-decoration: none; }
.gcnfl-cta { min-height: 44px; display: inline-flex; align-items: center; margin-left: 6px; padding: 12px 20px; border-radius: 999px; text-decoration: none; }
@container (max-width: 560px) { .gcnfl-brand { display: none; } .gcnfl-link { padding: 10px 4px; font-size: 11.5px; } .gcnfl-cta { margin-left: 2px; padding: 10px 8px; font-size: 11.5px; } .gcnfl-bar { padding: 5px; gap: 2px; } .gcnfl-links { gap: 0; } }
@media (prefers-reduced-motion: reduce) { .gcnfl-ind { transition-duration: .01ms; } }
.gcnfl-link { transition: opacity 140ms ease-out; touch-action: manipulation; } .gcnfl-link:active { opacity: .72; }`;

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

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

export function NavFlotante({ brand = "Nube", links = DEFAULT_LINKS, cta = "Empezar", variant = "regular", scheme = "dark", className = "", style }: NavFlotanteProps) {
  const [list, setList] = useState<HTMLUListElement | null>(null);
  const [active, setActive] = useState(0);
  const [hover, setHover] = useState<number | null>(null);
  const [rect, setRect] = useState({ x: 0, w: 0 });
  const target = hover ?? active;
  const [indicator, setIndicator] = useState<HTMLElement | null>(null);
  useGlassStretch(indicator, rect.x, target === 0 || target === links.length - 1 ? 1.1 : 1.2);

  useEffect(() => {
    if (!list) return;
    const place = () => {
      const el = list.querySelectorAll("a")[target] as HTMLElement | undefined;
      setRect(el ? { x: el.offsetLeft, w: el.offsetWidth } : { x: 0, w: 0 });
    };
    place();
    const observer = new ResizeObserver(place);
    observer.observe(list);
    list.querySelectorAll("a").forEach((link) => observer.observe(link));
    return () => observer.disconnect();
  }, [list, target, links.length]);

  return (
    <nav className={`gcnfl-root ${className}`} style={style} aria-label="Principal" data-s={scheme}>
      <style>{CSS}</style>
      <Surface className="gcnfl-bar" variant={variant} scheme={scheme} elevated bezel={22} depth={24}>
        <span className="gcnfl-brand">{brand}</span>
        <ul className="gcnfl-links" ref={setList} onPointerLeave={() => setHover(null)}>
          <Surface as="span" flat variant="clear" scheme={scheme} className="gcnfl-ind" elRef={setIndicator} aria-hidden="true" style={{ translate: `${rect.x}px 0`, width: rect.w, opacity: rect.w ? 1 : 0 }} />
          {links.map((link, index) => (
            <li key={link.label}>
              <a className="gcnfl-link" href={link.href ?? "#"} aria-current={active === index ? "page" : undefined} onPointerEnter={(event) => { if (event.pointerType !== "touch") setHover(index); }} onFocus={() => setHover(index)} onBlur={() => setHover(null)} onClick={(event) => { if (!link.href) event.preventDefault(); setActive(index); }}>
                {link.label}
              </a>
            </li>
          ))}
        </ul>
        <Surface as="a" className="gcnfl-cta" href="#" tone="solid" scheme={scheme} flat interactive onClick={(event: { preventDefault: () => void }) => event.preventDefault()}>
          {cta}
        </Surface>
      </Surface>
    </nav>
  );
}

Úsalo en tu proyecto

Instálalo con la CLI de shadcn.

terminal.sh1 líneas
npx shadcn@latest add https://www.gassierconsulting.com/r/nav-flotante

Ejemplo de uso de Barra flotante liquid glass

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

ejemplo.tsx5 líneas
import { NavFlotante } from "./nav-flotante";

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

Propiedades de NavFlotante

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

PropiedadTipoDescripción
brand?stringOpcional.
links?{ label: string; href?: string }[]Opcional.
cta?stringOpcional.
variant?"regular" | "clear"Opcional.
scheme?"dark" | "light"Dark para fondos oscuros o con color; light para fondos claros.
className?stringOpcional.
style?CSSPropertiesOpcional.

Variantes disponibles

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

Personaliza Barra flotante 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
--gcnfl-fg#fff
--gcnfl-blur2.6px
--gcnfl-clear-blur.45px
--gcnfl-r24px

Accesibilidad y rendimiento

El archivo tiene 354 líneas (22 KB) y no necesita @keyframes. Esto es lo que hace Barra flotante 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-*.
  • 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".
Licencia
MIT
Dependencias
React >=18
Compatibilidad
React 18 y 19 · Next.js (componente de cliente)