wisspop.

Mini-library for modals, dropdowns, and selects with origin-anchored animations. The panel doesn't pop out of nowhere; it grows out of the element that triggered it and morphs back upon closing.

TRY IT LIVE

Introduction

Standard modals fade in or scale up from the center of the viewport. While functional, it breaks visual continuity: the user clicks a button on one side of the screen and a dialog appears somewhere else without spatial relation.

wisspop maintains spatial continuity. The panel starts with the exact position, size, and border-radius of the button that opened it, growing smoothly into its final form. Upon closing, it reverses the transition. The eye seamlessly follows the object without losing context.

Installation

Install wisspop using your preferred package manager:

bash
pnpm add wisspop # o npm install wisspop / yarn add wisspop

Basic Usage & Components

Comprehensive catalog of wisspop live demos showing origin-anchored morphing, flying text, FLIP transitions, and gestures.

1. Anchored to a button

The panel grows out of the button and docks at any of the 6 placement combinations.

2. From a circular button

The trigger's border radius is computed dynamically. The '+' icon flies into data-wisspop-title.

3. Expand in place

placement: 'origin' centers the panel on the trigger button without moving towards viewport center.

4. Drawers (Side and top/bottom)

drawer-left, drawer-right, drawer-top, and drawer-bottom dock the panel seamlessly to screen edges.

5. Flying text (PillModal)

The trigger label flies across the screen, smoothly interpolating size and position onto data-wisspop-title.

6. Flying element formats

Scales font-size for text, and width/height for icons and images.

7. Gesture dismissal (Swipe to Close)

swipeToClose: true allows dismissing the panel by dragging it in any direction.

8. FlipModal — Shared elements

Individual elements with data-flip-id travel from trigger to modal with GSAP Flip.

Gato Viajero

Travelling Cat

Click to expand detail

9. DropdownPanel — Elastic menu

Elastic dropdown with enterDropdownAnimation and leaveDropdownAnimation.

10. Reactive height & view switcher (Auth Demo)

Demonstrates resync() on height changes and changeView() when switching between signup and login.

11. Backdrop overlay (Blur & Opacity)

Customize the background overlay: toggle built-in presets (overlayBlur & overlayDark) or provide utility classes via overlayClass.

Métodos de la API

La instancia devuelta por createModal() o expuesta por los wrappers contiene los siguientes métodos de control:

Método Firma Descripción
open (originRef, label?, options?) Inicia la animación de apertura despegando desde el origen medido.
close () Inicia la animación de cierre retornando a la posición actual del origen.
changeView (mutateFn) Aplica el cambio de vista y ajusta el alto con un fade-through corto sin cerrar el panel.
resync () Recalcula la geometría del contenido y ajusta suavemente la altura del panel abierto.
destroy () Limpia observers y elimina los elementos del DOM.

Options & Placement

Configure placement (top, bottom, left, right, origin, center, drawer-left), alignment, gap, scroll locking, and callbacks.

Opción Valores Por defecto Descripción
placement top | bottom | left | right | origin | center | drawer-left | drawer-right | drawer-top | drawer-bottom 'bottom' Posición respecto al origen. origin crece en el lugar; drawer-* fija a bordes.
align start | center | end 'center' Alineación sobre el eje cruzado al punto de anclaje.
gap number (px) 8 Distancia en px hacia el elemento disparador.
margin number (px) 16 Margen mínimo de seguridad a los bordes de la ventana.
swipeToClose boolean false Permite descartar el panel arrastrándolo con la mano o mouse.
overlay boolean true Renders a background backdrop overlay behind the open modal.
overlayBlur boolean false Applies standard native backdrop-filter: blur(6px) without custom CSS.
overlayDark boolean false Applies standard soft dark tint background (rgba(0, 0, 0, 0.25)).
overlayClass string "" Custom CSS or Tailwind classes to customize opacity, color, and blur (e.g. 'bg-black/60 backdrop-blur-md').
overlayDuration number undefined Custom duration in seconds for the overlay transition (inherits duration by default).
closeOnEscape boolean true Closes modal on Escape key press.
lockScroll boolean true Locks body scroll with scrollbar gutter compensation.
fullscreenOnMobile boolean true Expands modal to 100% full screen on viewports < 640px.

Overlay Customization (Opacity, Background & Blur)

WissPop's background overlay is fully customizable. You can adjust the backgroundColor opacity and backdrop-blur intensity through 3 flexible approaches:

Option 1

Via Utility Classes (overlayClass / Tailwind CSS) — Recommended

Pass custom or Tailwind classes directly into overlayClass to configure exact background opacity (e.g. `bg-black/50`, `bg-slate-900/80`) and blur intensity (`backdrop-blur-sm`, `backdrop-blur-md`, `backdrop-blur-xl`):

Vanilla JS (javascript)
import { createModal } from 'wisspop/vanilla';

const modal = createModal({
  overlay: true,
  // 60% opacidad negra + desenfoque medio
  overlayClass: 'bg-black/60 backdrop-blur-md',
  content: '<div class="p-6">Contenido...</div>'
});
Vue 3 (vue)
<template>
  <WissPopMorph
    v-model="isOpen"
    :origin-ref="btnRef"
    overlayClass="bg-black/60 backdrop-blur-md"
  >
    <div class="p-6">Contenido...</div>
  </WissPopMorph>
</template>
Option 2

Via CSS Custom Properties (--wisspop-overlay-*)

WissPop supports standard CSS custom properties. You can override them globally in `:root` or locally inside a custom CSS selector:

styles.css (css)
/* Configuración global para toda tu aplicación */
:root {
  /* Color y nivel de opacidad (ej. 40%, 50%, 75%) */
  --wisspop-overlay-bg: rgba(0, 0, 0, 0.55);

  /* Intensidad del desenfoque (ej. blur(4px), blur(12px), blur(20px)) */
  --wisspop-overlay-blur: blur(10px);
}

/* O para un modal específico */
.overlay-vidrio-intenso {
  --wisspop-overlay-bg: rgba(15, 23, 42, 0.8);
  --wisspop-overlay-blur: blur(20px);
}
Option 3

Built-in Preset Flags (overlayBlur & overlayDark)

If you don't use Tailwind or custom CSS, enable instant preset styles with boolean flags:

  • overlayBlur: true → Applies standard 6px blur (`backdrop-filter: blur(6px)`).
  • overlayDark: true → Applies standard soft dark tint (`rgba(0, 0, 0, 0.25)`).
  • overlayBlur: true, overlayDark: true → Seamlessly combines both blur and dark tint.
Vanilla JS Presets (javascript)
createModal({
  overlay: true,
  overlayBlur: true, // Desenfoque nativo 6px
  overlayDark: true, // Fondo oscuro suave
  content: '<div class="p-6">Panel con blur nativo</div>'
});
Vue 3 Presets (vue)
<WissPopMorph
  v-model="isOpen"
  :origin-ref="btnRef"
  :overlay="true"
  :overlay-blur="true"
  :overlay-dark="true"
>
  <div class="p-6">Panel con blur nativo</div>
</WissPopMorph>

Framework Support

Zero-dependency core (Pure JS + GSAP) with native adapter for Vue 3 and agnostic API for Vanilla JS.

Vue 3 (Wrapper Nativo)

vue
<script setup>
import { ref } from 'vue';
import { WissPopMorph } from 'wisspop/vue';

const open = ref(false);
const btnRef = ref(null);
</script>

<template>
  <button ref="btnRef" @click="open = true">Abrir</button>
  <WissPopMorph v-model="open" :origin-ref="btnRef" placement="bottom" modalClass="panel">
    <template #default="{ close }">
      <p>Contenido Vue...</p>
      <button @click="close">Cerrar</button>
    </template>
  </WissPopMorph>
</template>

Vanilla JS / Agnóstico

javascript
import { createModal } from 'wisspop/vanilla';

const modal = createModal({
  content: '<p>Contenido...</p>',
  placement: 'bottom',
  modalClass: 'panel',
  closeButton: true,
});

document.querySelector('#btn').addEventListener('click', (e) => {
  modal.open(e.currentTarget);
});

Astro

via vanilla

Astro doesn't need a reactive wrapper. Use the vanilla API directly in a <script> tag inside your .astro component.

astro
---
// MiModal.astro
---
<button id="mi-btn">Abrir modal</button>

<script>
  import { createModal } from 'wisspop/vanilla';

  const modal = createModal({
    content: '<div class="p-6"><h2 data-wisspop-title>Hola Astro</h2><p>Contenido del modal</p></div>',
    placement: 'bottom',
    modalClass: 'panel',
    closeButton: true,
  });

  document.getElementById('mi-btn')
    ?.addEventListener('click', (e) => modal.open(e.currentTarget));
</script>

React

via vanilla

React doesn't have a native wrapper yet. Use the vanilla API with useRef and useEffect to integrate wisspop.

React (javascript)
import { useRef, useEffect } from 'react';
import { createModal } from 'wisspop/vanilla';

export default function MiModal() {
  const btnRef = useRef(null);
  const modalRef = useRef(null);

  useEffect(() => {
    modalRef.current = createModal({
      content: '<div class="p-6"><h2 data-wisspop-title>Hola React</h2><p>Contenido</p></div>',
      placement: 'bottom',
      modalClass: 'panel',
      closeButton: true,
    });
    return () => modalRef.current?.destroy?.();
  }, []);

  return (
    <button ref={btnRef} onClick={() => modalRef.current?.open(btnRef.current)}>
      Abrir modal
    </button>
  );
}

TypeScript

Types included

WissPop ships with built-in TypeScript declarations (.d.ts) for Vanilla, Vue 3, and Core. No need to install extra @types packages.

TypeScript (typescript)
import { createModal, createFlipModal, setDefaults } from 'wisspop/vanilla';

// Todas las opciones, métodos y estados cuentan con autocompletado y tipado estricto
const modal = createModal({
  content: '<div class="p-6"><h2>Modal Tipado</h2></div>',
  placement: 'center',
  duration: 0.6,
  overlay: true,
  overlayBlur: true,
  swipeToClose: true,
});

const trigger = document.querySelector<HTMLButtonElement>('#mi-boton');
trigger?.addEventListener('click', () => {
  modal.open(trigger);
});
Guía Técnica

Guía de Buenas Prácticas y Errores Comunes

Patrones recomendados, advertencias técnicas y soluciones aprendidas para integrar WissPop con la máxima fluidez visual.

Tipos de Modales y Cuándo Usar Cada Uno

Componente Tipo de Animación Cuándo Usarlo Elementos y Reglas
WissPopMorph La caja física nace del botón y se expande/transforma hacia su destino (placement="origin" o anclado). Dropdowns, menús contextuales, drawers laterales, mini-modales de confirmación o aviso. NO usa texto volador. La caja hace todo el morph físico.
WissPopPill La caja se expande y el texto o icono del botón vuela e interpola su escala hacia el título. Modales de formularios principales, login/auth, calculadoras donde la etiqueta del botón se convierte en el título. Requiere [data-wisspop-title] en el modal y opcionalmente data-wisspop-label en el botón.
WissPopFlip Transición FLIP completa de múltiples elementos compartidos (imágenes, títulos, badges) entre tarjeta y vista de detalle. Galerías de productos, cards interactivas que se expanden a pantalla completa. Requiere atributos data-flip-id="id-unico" coincidentes en el trigger y en el modal.

Errores Comunes y Cómo Evitarlos

Crear un Doble Contenedor en WissPopMorph

El Problema: Wisspop anima directamente su propio elemento contenedor .wisspop-box (modifica con GSAP width, height, borderRadius, top y left). Si dentro del slot colocas otro <div> con fondo, borde, redondeo y sombra, habrá dos cajas compitiendo y se producirá un salto o retraso visual ("efecto pop").

La Solución: Pasa los estilos del contenedor directamente a la propiedad modalClass.

Incorrecto (Doble caja con saltos) (astro)
<WissPopMorph id="mi-modal" placement="origin">
  <!-- Doble contenedor: compite con .wisspop-box -->
  <div class="bg-white rounded-2xl border border-slate-900 shadow-xl p-5">
    <h3>Contenido</h3>
  </div>
</WissPopMorph>
Correcto (Estilos en modalClass) (astro)
<WissPopMorph 
  id="mi-modal" 
  placement="origin" 
  modalClass="bg-white dark:bg-zinc-900 rounded-2xl border border-zinc-200 dark:border-zinc-800 shadow-xl"
  closeButton={true}
  swipeToClose={true}
>
  <!-- Contenido interno limpio con ancho responsivo -->
  <div class="p-5" style="width: min(24rem, calc(100vw - 2rem));">
    <h3 class="font-bold text-base">Contenido</h3>
  </div>
</WissPopMorph>

Mezclar flyingTextClass o data-wisspop-title en WissPopMorph

El Problema: flyingTextClass y data-wisspop-title son exclusivos del sistema de texto viajero de WissPopPill. Si los usas en un WissPopMorph, Wisspop ocultará temporalmente el título (visibility: hidden) esperando una animación de vuelo que nunca ocurrirá.

La Solución: En WissPopMorph, usa encabezados HTML normales <h3> sin data-wisspop-title. Para títulos con texto viajero, utiliza <WissPopPill>.

Incorrecto en WissPopMorph (astro)
<!-- Ocultará el título esperando un vuelo que no ocurrirá -->
<WissPopMorph id="mi-modal" modalClass="panel">
  <div class="p-5" style="width: min(24rem, calc(100vw - 2rem));">
    <h3 data-wisspop-title>Título Oculto</h3>
  </div>
</WissPopMorph>
Correcto en WissPopMorph (astro)
<!-- Encabezado normal sin atributos de vuelo -->
<WissPopMorph id="mi-modal" modalClass="panel">
  <div class="p-5" style="width: min(24rem, calc(100vw - 2rem));">
    <h3 class="font-bold text-lg">Título Visible</h3>
  </div>
</WissPopMorph>

No Definir Ancho en el Contenido Interno

El Problema: Para que GSAP mida con precisión la geometría final de la caja antes de animar el despegue, el cuerpo del panel debe tener un ancho medible.

La Solución: Establece un ancho explícito o responsivo en el div interior (ej. style="width: min(24rem, calc(100vw - 2rem));" o clases Tailwind equivalentes como w-80 max-w-[calc(100vw-2rem)]).

Incorrecto (Sin ancho medible) (astro)
<WissPopMorph id="mi-modal" modalClass="panel">
  <!-- Sin ancho: GSAP no puede calcular la geometría exacta -->
  <div class="p-5">
    <h3>Contenido sin ancho</h3>
  </div>
</WissPopMorph>
Correcto (Ancho responsivo) (astro)
<WissPopMorph id="mi-modal" modalClass="panel">
  <!-- Ancho explícito y responsivo para medición fluida -->
  <div class="p-5" style="width: min(24rem, calc(100vw - 2rem));">
    <h3>Contenido</h3>
  </div>
</WissPopMorph>

Modales Anidados o Disparadores Dinámicos Dentro de <template>

El Problema: En Astro, los slots se emiten dentro de etiquetas <template data-wisspop="...">. Si un botón que abre un submodal se encuentra dentro del template de otro modal que aún no se ha abierto, document.querySelectorAll() no lo encontrará en la carga inicial.

La Solución: El runtime cliente de wisspop/astro incluye delegación global automática de eventos para [data-wisspop-trigger], montando bajo demanda cualquier submodal anidado o disparador dinámico.

Delegación Automática para Submodales (astro)
<!-- Disparador dentro de otro modal o generado dinámicamente -->
<button data-wisspop-trigger="sub-modal-confirmacion" class="demo-btn">
  Abrir Confirmación
</button>

<!-- El runtime monta el template bajo demanda al hacer clic -->
<WissPopMorph id="sub-modal-confirmacion" placement="center" modalClass="panel">
  <div class="p-5" style="width: min(20rem, calc(100vw - 2rem));">
    <h4 class="font-bold mb-3">¿Deseas confirmar la acción?</h4>
    <button data-wisspop-close class="demo-btn w-full">Aceptar</button>
  </div>
</WissPopMorph>

Destellos de Color Inesperados al Abrir/Cerrar (Interpolación de backgroundColor)

El Problema: WissPop lee automáticamente el color de fondo computado del botón disparador (getComputedStyle(ref).backgroundColor) y lo interpola con GSAP hacia el color del modal al abrir, y de vuelta al color del botón al cerrar. Si el botón tiene un color muy saturado o semitransparente (ej. bg-amber-500/10), toda la caja del modal se teñirá de ese tono mientras se encoge.

La Solución: Mantén el fondo del botón disparador en un tono armónico o neutro respecto al modal (ej. bg-white, bg-zinc-100 o tonos arena), y aplica los colores de acento/alerta en iconos, bordes o badges internos.

Destello amarillo al encogerse (html)
<!-- El modal completo se teñirá de amarillo al cerrar -->
<button class="bg-amber-500/10 border border-amber-500" data-wisspop-trigger="mi-modal">
  Aviso Importante
</button>
Transición limpia y armónica (html)
<!-- Fondo neutro; color de acento en el icono -->
<button class="bg-zinc-100 dark:bg-zinc-800 border border-zinc-300 dark:border-zinc-700 flex items-center gap-2 p-2 rounded-xl" data-wisspop-trigger="mi-modal">
  <span class="bg-amber-100 dark:bg-amber-950 text-amber-600 p-1 rounded-lg">!</span>
  <span>Aviso Importante</span>
</button>

Configuración de Proyecto y View Transitions

Para asegurar que Astro y Vite procesen correctamente los módulos de WissPop en SSR y durante las transiciones de página de <ClientRouter />:

js
// astro.config.mjs
import { defineConfig } from 'astro/config';
import tailwindcss from '@tailwindcss/vite';

export default defineConfig({
  vite: {
    plugins: [tailwindcss()],
    ssr: {
      noExternal: ['wisspop']
    }
  },
});

docs.accesibilidad

Includes automatic focus trap, Escape key listener, focus restoration, body scroll locking, reduced motion support, and ARIA roles.

  • Focus Trap: El foco del teclado queda confinado dentro del modal abierto.
  • Tecla Escape: Cierra el panel automáticamente de forma nativa.
  • Foco de Retorno: Al cerrar el panel, el foco vuelve automáticamente al elemento disparador.
  • Reduced Motion: Si el sistema tiene activado prefers-reduced-motion, se salta la animación hacia la geometría final.
Copied AI Prompt to clipboard!