Communitygithub.com

ComeOnOliver/skillshub

Este documento captura lecciones aprendidas al solucionar problemas de navegación por teclado cuando componentes flotantes (Select, DropdownMenu, Popover) tienen animaciones CSS de apertura/cierre.

¿Qué es skillshub?

Este skill documenta una técnica esencial para desarrolladores que trabajan con componentes flotantes animados (como Select, DropdownMenu y Popover) en bibliotecas UI como SummitUI, aplicable también a frameworks como Tailwind CSS y Svelte (bits-ui). El problema principal surge cuando los elementos animados comienzan con `opacity: 0` (por ejemplo, mediante `animate-in fade-in-0` de Tailwind), lo que provoca que el navegador rechace la llamada `element.focus()` porque el elemento es invisible inicialmente. Como resultado, la navegación por teclado (flechas, Escape) no funciona al abrir el componente con teclado, y los eventos se capturan incorrectamente en el botón desencadenante. La solución implementa un mecanismo de reintento para el enfoque: primero usa `requestAnimationFrame` para esperar la aplicación de CSS, luego verifica si `document.activeElement` coincide con el elemento deseado, y reintenta hasta 5 veces con intervalos de 20ms (máximo 100ms de espera). Esto permite que la animación progrese más allá del estado invisible sin agregar una latencia notable. El skill incluye ejemplos de código JavaScript, clases CSS para pruebas, y casos de prueba para cada componente. Es ideal para equipos que desarrollan componentes UI accesibles y responsivos, especialmente en entornos donde las animaciones CSS son comunes.

Compatible con~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/ComeOnOliver/skillshub/tree/HEAD/skills/aiskillstore/marketplace/andrehogberg/animated-focus

Preguntar en tu IA favorita

Abre un nuevo chat con esta habilidad de agente ya precargada.

Documentación

Gestión de Enfoque con Animaciones CSS

Este documento captura lecciones aprendidas al solucionar problemas de navegación por teclado cuando componentes flotantes (Select, DropdownMenu, Popover) tienen animaciones CSS de apertura/cierre.

El Problema

Cuando los elementos de contenido flotante tienen animaciones CSS que comienzan con opacity: 0 (como animate-in fade-in-0 de Tailwind), el navegador puede rechazar las llamadas element.focus() porque el elemento es invisible.

Síntomas

  • El componente se abre correctamente con clics del ratón
  • La navegación por teclado (flechas, Escape) no funciona después de abrir con teclado
  • Funciona correctamente en demos sin clases de animación
  • No funciona en demos con clases de animación

Causa Raíz

  1. Las animaciones CSS como fade-in-0 inician el elemento con opacity: 0
  2. Cuando se llama a focus() inmediatamente después del renderizado, el elemento aún es invisible
  3. El navegador rechaza el enfoque en elementos invisibles
  4. El enfoque permanece en el botón desencadenante en lugar de moverse al contenido
  5. Los eventos de teclado van al desencadenante (que no hace nada cuando está abierto) en lugar del contenido

Evidencia de la Depuración en Consola

// Después de abrir el select, los eventos de teclado van al desencadenante, no al contenido:
Document keydown: ArrowDown Target: <button role="combobox" ...>

// El elemento activo es el desencadenante, no el contenido:
Active: BUTTON summit-select-...-trigger

La Solución

Implementar un mecanismo de reintento para el enfoque que permita que la animación progrese más allá de opacity: 0 antes de rendirse.

Implementación en JavaScript

// src/SummitUI/Scripts/floating.js

/**
 * Enfoca un elemento con mecanismo de reintento para elementos animados.
 * Los elementos con animaciones CSS que comienzan con opacity:0 pueden rechazar el enfoque inicialmente.
 * Esto reintenta el enfoque hasta 5 veces con retrasos de 20ms para permitir que la animación
 * progrese más allá del estado invisible.
 * @param {HTMLElement} element - Elemento a enfocar
 */
export function focusElement(element) {
    if (!element) return;
    
    function tryFocus(attempts) {
        element.focus();
        // Si el enfoque no tuvo éxito y quedan intentos, reintentar
        if (document.activeElement !== element && attempts > 0) {
            setTimeout(() => tryFocus(attempts - 1), 20);
        }
    }
    
    // Primer intento después de un frame para dejar que CSS se aplique
    requestAnimationFrame(() => tryFocus(5));
}

Puntos Clave

  1. Usar requestAnimationFrame primero - Asegura que CSS se haya aplicado antes de intentar el enfoque
  2. Verificar document.activeElement - Comprueba si el enfoque realmente tuvo éxito
  3. Reintentar con retrasos - Intervalos de 20ms permiten que la animación progrese
  4. Intentos limitados - 5 reintentos = 100ms de espera máxima, suficiente para animaciones típicas
  5. Aplicar a todas las funciones de enfoque - Tanto focusElement(element) como focusElementById(id) necesitan este patrón

Funciones Actualizadas

  • floating.js:focusElement(element) - Usado por SelectContent
  • floating.js:focusElementById(elementId) - Usado por DropdownMenuContent

Pruebas

Se agregaron secciones "Con Animaciones" a las páginas demo de prueba y las correspondientes pruebas de Playwright.

Clases CSS de Animación para Pruebas

/* tests/SummitUI.Tests.Manual/SummitUI.Tests.Manual/wwwroot/app.css */

@keyframes fadeInZoomIn {
    from {
        opacity: 0;
        transform: scale(0.95);
    }
    to {
        opacity: 1;
        transform: scale(1);
    }
}

@keyframes fadeOutZoomOut {
    from {
        opacity: 1;
        transform: scale(1);
    }
    to {
        opacity: 0;
        transform: scale(0.95);
    }
}

.animated-content[data-state="open"] {
    animation: fadeInZoomIn 150ms ease-out forwards;
}

.animated-content[data-state="closed"] {
    animation: fadeOutZoomOut 150ms ease-in forwards;
}

Casos de Prueba

Para cada componente (Select, DropdownMenu, Popover):

PruebaQué Verifica
Animated*_ShouldOpen_OnEnterKeySe abre con teclado cuando hay animaciones presentes
Animated*_ShouldNavigate_WithArrowKeysLas flechas funcionan después de apertura animada
Animated*_ShouldSelect/Activate_OnEnterKeyPuede seleccionar/activar un elemento después de apertura animada
Animated*_ShouldClose_OnEscapeEscape activa la animación de cierre

Ejecutar Pruebas de Animación

dotnet run --project tests/SummitUI.Tests.Playwright -- --treenode-filter '/*/*/*/Animated*'

Archivos Involucrados

ArchivoPropósito
src/SummitUI/Scripts/floating.jsContiene las funciones focusElement y focusElementById
src/SummitUI/Components/Select/SelectContent.csLlama a FocusElementAsync al abrir
src/SummitUI/Components/DropdownMenu/DropdownMenuContent.csLlama a FocusElementByIdAsync para elementos del menú
src/SummitUI/Components/Popover/PopoverContent.csGestiona el enfoque para el contenido del popover

Enfoques Alternativos Considerados

  1. Retraso inicial más largo - Podría usar 50-100ms de retraso antes del primer intento de enfoque, pero añade una latencia notable
  2. Enfocar antes de que comience la animación - Requeriría cambios en el orden de renderizado, complejo
  3. Desactivar animación durante el enfoque - Causaría un destello visual
  4. Usar visibility en lugar de opacity en CSS - Requeriría cambios en cómo se crean las animaciones

Se eligió el mecanismo de reintento porque:

  • Funciona con cualquier duración de animación
  • No requiere cambios en la creación de CSS
  • Tiene un impacto mínimo en el rendimiento
  • Fallas de manera elegante si el enfoque nunca tiene éxito

Patrones Relacionados

Este patrón es similar a cómo bits-ui maneja la presencia animada en componentes Svelte. La idea clave es que las operaciones del DOM (como el enfoque) pueden necesitar esperar a que las animaciones CSS alcancen un estado enfocable.

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

ComeOnOliver/skillshub

Create stunning, animation-rich HTML presentations from scratch or by converting PowerPoint files. Use when the user wants to build a presentation, convert a PPT/PPTX to web, or create slides for a talk/pitch. Helps non-designers discover their aesthetic through visual exploration rather than abstract choices.

ComeOnOliver/skillshub

Next.js 16+ 和 Turbopack — 增量打包、文件系统缓存、开发速度,以及何时使用 Turbopack 与 webpack。

ComeOnOliver/skillshub

SwiftUI architecture patterns, state management with @Observable, view composition, navigation, performance optimization, and modern iOS/macOS UI best practices.

ComeOnOliver/skillshub

See, Understand, Act on video and audio. See- ingest from local files, URLs, RTSP/live feeds, or live record desktop; return realtime context and playable stream links. Understand- extract frames, build visual/semantic/temporal indexes, and search moments with timestamps and auto-clips. Act- transcode and normalize (codec, fps, resolution, aspect ratio), perform timeline edits (subtitles, text/image overlays, branding, audio overlays, dubbing, translation), generate media assets (image, audio, video), and create real time alerts for events from live streams or desktop capture.

ComeOnOliver/skillshub

AI-assisted video editing workflows for cutting, structuring, and augmenting real footage. Covers the full pipeline from raw capture through FFmpeg, Remotion, ElevenLabs, fal.ai, and final polish in Descript or CapCut. Use when the user wants to edit video, cut footage, create vlogs, or build video content.

ComeOnOliver/skillshub

Next.js 15 애플리케이션을 위한 프론트엔드 개발 가이드라인. React 19, TypeScript, Shadcn/ui, Tailwind CSS를 사용한 모던 패턴. Server Components, Client Components, App Router, 파일 구조, Shadcn/ui 컴포넌트, 성능 최적화, TypeScript 모범 사례 포함. 컴포넌트, 페이지, 기능 생성, 데이터 페칭, 스타일링, 라우팅, 프론트엔드 코드 작업 시 사용.

ComeOnOliver/skillshub

Provides Tamagui patterns for config v4, compiler optimization, styled context, and cross-platform styling. Must use when working with Tamagui projects (tamagui.config.ts, @tamagui imports).

ComeOnOliver/skillshub

Create distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.

ComeOnOliver/skillshub

Create high-converting, visually distinctive landing pages. Use when building marketing pages, product launches, SaaS homepages, or any single-page conversion-focused website. Guides section-by-section composition with anti-AI-slop principles.

ComeOnOliver/skillshub

Auto-loaded context for Portfolio Buddy 2 development. Use for ANY task involving: React 19 development, TypeScript, portfolio analysis features, metrics calculations, trading strategy comparison, or working with the Portfolio Buddy 2 codebase. Contains tech stack, known issues, and architectural constraints.

ComeOnOliver/skillshub

Next.js development tooling via MCP. Inspect routes, components, build info, and debug Next.js apps. Use when working on Next.js applications, debugging routing, or inspecting app structure. NOT for general React or non-Next.js projects.

ComeOnOliver/skillshub

Implement UI using Shadcn MCP (atoms/theme) and 21st.dev MCP (complex sections). Use when adding buttons, layouts, or generating landing pages.

ComeOnOliver/skillshub

A conceptual skill for building an API client in Next.js that handles JWT tokens

ComeOnOliver/skillshub

Best practices and patterns for Next.js App Router, Server Actions, and Routing in this project.

ComeOnOliver/skillshub

The Design System, Theme, and UX rules for the Physical AI Hub.

ComeOnOliver/skillshub

Comprehensive frontend development skill for building modern, performant web applications using ReactJS, NextJS, TypeScript, Tailwind CSS. Includes component scaffolding, performance optimization, bundle analysis, and UI best practices. Use when developing frontend features, optimizing performance, implementing UI/UX designs, managing state, or reviewing frontend code.

ComeOnOliver/skillshub

Build Next.js 16 applications with correct patterns and distinctive design. Use when creating pages, layouts, dynamic routes, upgrading from Next.js 15, or implementing proxy.ts. Covers breaking changes (async params/searchParams, Turbopack, cacheComponents) and frontend aesthetics. NOT when building non-React or backend-only applications.

ComeOnOliver/skillshub

Comprehensive Framer Motion animation library for React. Covers motion components, variants, gestures, page transitions, and scroll animations. Use when adding animations to React/Next.js applications.

ComeOnOliver/skillshub

Next.js 16+ uses App Router with Server Components by default. Client Components are only used when interactivity is needed (hooks, event handlers, browser APIs).

ComeOnOliver/skillshub

Build interfaces that resonate, not just render. This skill enforces bold, intentional

Skills relacionados