Ir al contenido
Evaluar mi proyecto
Componentes · Modales y capasDisponible

Popover anclado para compartir

Panel con flecha anclado a su botón: Escape, clic fuera o salir con Tab lo cierran y el foco vuelve; copia el enlace.

Código completo

Es exactamente el archivo que se descarga. Cópialo a tu proyecto y úsalo.

capa-popover.tsx80 líneas
Descargar
"use client";

import { useEffect, useId, useRef, useState, type CSSProperties } from "react";

/** Popover anclado a su botón con flecha, para compartir un enlace: cierra con Escape, clic fuera o Tab fuera, devuelve el foco y confirma la copia. Minimalista. React + TypeScript, sin dependencias. */
export type CapaPopoverProps = {
  trigger?: string;
  url?: string;
  className?: string;
  style?: CSSProperties;
};

const CSS = `
.gccpp-root { box-sizing: border-box; position: relative; display: inline-block; font: 500 14px/1.45 ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif; color: #18181b; }
.gccpp-root *, .gccpp-root *::before, .gccpp-root *::after { box-sizing: border-box; }
.gccpp-root button, .gccpp-root input { font: inherit; }
.gccpp-root :focus-visible { outline: 2px solid #2563eb; outline-offset: 2px; }
@media (prefers-reduced-motion: reduce) { .gccpp-pop { animation: none !important; } }
.gccpp-btn { display: inline-flex; align-items: center; gap: 8px; min-height: 44px; padding: 0 16px; border: 1px solid #d4d4d8; border-radius: 10px; background: #fff; color: inherit; font-weight: 600; cursor: pointer; transition: background .15s; }
.gccpp-btn:hover, .gccpp-btn[aria-expanded="true"] { background: #f4f4f5; }
.gccpp-pop { position: absolute; z-index: 10; top: calc(100% + 12px); left: 0; width: 320px; max-width: calc(100vw - 32px); padding: 16px; border: 1px solid #e4e4e7; border-radius: 14px; background: #fff; box-shadow: 0 20px 40px -14px rgba(0, 0, 0, .3); transform-origin: 24px -12px; animation: gccpp-in .2s cubic-bezier(.16, 1, .3, 1); }
.gccpp-pop::before { content: ""; position: absolute; top: -7px; left: 22px; width: 12px; height: 12px; border-top: 1px solid #e4e4e7; border-left: 1px solid #e4e4e7; background: #fff; transform: rotate(45deg); }
.gccpp-title { margin: 0 0 4px; font-size: 15px; font-weight: 700; }
.gccpp-sub { margin: 0 0 12px; color: #71717a; font-size: 13px; }
.gccpp-row { display: flex; gap: 8px; }
.gccpp-in { flex: 1; min-width: 0; height: 40px; padding: 0 10px; border: 1px solid #d4d4d8; border-radius: 8px; background: #fafafa; color: #3f3f46; font-size: 13px; }
.gccpp-copy { min-height: 40px; padding: 0 14px; border: 0; border-radius: 8px; background: #18181b; color: #fff; font-weight: 600; cursor: pointer; transition: background .15s; }
.gccpp-copy:hover { background: #3f3f46; }
.gccpp-copy[data-done="true"] { background: #16a34a; }
@keyframes gccpp-in { from { opacity: 0; transform: translateY(-6px) scale(.96); } }`;

export function CapaPopover({ trigger = "Compartir", url = "https://ejemplo.com/propuesta/8f3k2", className = "", style }: CapaPopoverProps) {
  const id = useId();
  const [open, setOpen] = useState(false);
  const [done, setDone] = useState(false);
  const root = useRef<HTMLDivElement>(null);
  const btn = useRef<HTMLButtonElement>(null);
  const input = useRef<HTMLInputElement>(null);

  useEffect(() => {
    if (!open) return;
    input.current?.select();
    const away = (event: PointerEvent) => { if (!root.current?.contains(event.target as Node)) setOpen(false); };
    const esc = (event: KeyboardEvent) => { if (event.key === "Escape") { setOpen(false); btn.current?.focus(); } };
    const focusOut = (event: FocusEvent) => { if (event.relatedTarget && !root.current?.contains(event.relatedTarget as Node)) setOpen(false); };
    document.addEventListener("pointerdown", away);
    document.addEventListener("keydown", esc);
    root.current?.addEventListener("focusout", focusOut);
    const node = root.current;
    return () => { document.removeEventListener("pointerdown", away); document.removeEventListener("keydown", esc); node?.removeEventListener("focusout", focusOut); };
  }, [open]);

  async function copy() {
    try { await navigator.clipboard.writeText(url); } catch { input.current?.select(); document.execCommand?.("copy"); }
    setDone(true);
    window.setTimeout(() => setDone(false), 1800);
  }

  return (
    <div ref={root} className={`gccpp-root ${className}`} style={style}>
      <style>{CSS}</style>
      <button ref={btn} className="gccpp-btn" type="button" aria-expanded={open} aria-haspopup="dialog" aria-controls={`${id}-p`} onClick={() => setOpen((value) => !value)}>
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M8.600 13.500l6.800 4M15.400 6.500l-6.800 4M18 8a3 3 0 1 0 0-6 3 3 0 0 0 0 6zM6 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6zM18 22a3 3 0 1 0 0-6 3 3 0 0 0 0 6z" /></svg>
        {trigger}
      </button>
      {open ? (
        <div id={`${id}-p`} className="gccpp-pop" role="dialog" aria-label="Compartir enlace">
          <h3 className="gccpp-title">Compartir propuesta</h3>
          <p className="gccpp-sub">Cualquiera con el enlace puede verla.</p>
          <div className="gccpp-row">
            <input ref={input} className="gccpp-in" readOnly value={url} aria-label="Enlace" />
            <button className="gccpp-copy" type="button" data-done={done} onClick={copy}>{done ? "Copiado" : "Copiar"}</button>
          </div>
          <span role="status" style={{ position: "absolute", width: 1, height: 1, overflow: "hidden", clip: "rect(0 0 0 0)" }}>{done ? "Enlace copiado" : ""}</span>
        </div>
      ) : null}
    </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-popover

Ejemplo de uso de Popover anclado para compartir

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

ejemplo.tsx5 líneas
import { CapaPopover } from "./capa-popover";

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

Propiedades de CapaPopover

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

PropiedadTipoDescripción
trigger?stringOpcional.
url?stringOpcional.
className?stringOpcional.
style?CSSPropertiesOpcional.

Accesibilidad y rendimiento

El archivo tiene 80 líneas (5 KB) y define 1 animación con @keyframes. Esto es lo que hace Popover anclado para compartir 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: dialog, status.
  • Responde al teclado, no solo al ratón.
  • 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)