Communitygithub.com

Fokusverwaltung mit CSS-Animationen

Dieses Dokument beschreibt Lösungen für Tastaturnavigationsprobleme bei schwebenden Komponenten (Select, DropdownMenu, Popover) mit CSS-Öffnungs-/Schließanimationen.

Was ist Fokusverwaltung mit CSS-Animationen?

Dieses Skill dokumentiert eine Lösung für ein häufiges Problem bei der Barrierefreiheit: Wenn schwebende UI-Komponenten wie Select, DropdownMenu oder Popover mit CSS-Animationen geöffnet werden, die bei `opacity: 0` beginnen (z.B. Tailwinds `animate-in fade-in-0`), kann der Browser `element.focus()`-Aufrufe ablehnen, da das Element unsichtbar ist. Dies führt dazu, dass die Tastaturnavigation nach dem Öffnen nicht funktioniert – z.B. reagieren Pfeiltasten oder Escape nicht. Die Kernlösung ist ein Wiederholungsmechanismus für `focus()`: Nach einem `requestAnimationFrame` wird das Element bis zu 5 Mal im Abstand von 20 ms fokussiert, bis die Animation den unsichtbaren Zustand verlassen hat. Der Ansatz ist plattformunabhängig und wurde für Blazor-basierte Komponenten (Select, DropdownMenu, Popover) in einem SummitUI-Projekt implementiert. Er umfasst auch Playwright-Tests für animierte Varianten und CSS-Keyframe-Animationen zur Reproduktion. Der Mechanismus ist ressourcenschonend, funktioniert mit beliebigen Animationsdauern und erfordert keine Änderungen an der CSS-Authoring-Praxis.

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

In Ihrer bevorzugten KI fragen

Öffnet einen neuen Chat, in dem dieser Agent-Skill bereits geladen ist.

Dokumentation

Was macht Fokusverwaltung mit CSS-Animationen?

Dieses Dokument beschreibt Lösungen für Tastaturnavigationsprobleme bei schwebenden Komponenten (Select, DropdownMenu, Popover) mit CSS-Öffnungs-/Schließanimationen.

Das Problem

Wenn schwebende Inhaltselemente CSS-Animationen haben, die bei opacity: 0 beginnen (wie Tailwinds animate-in fade-in-0), kann der Browser element.focus()-Aufrufe ablehnen, weil das Element unsichtbar ist.

Symptome

  • Die Komponente öffnet sich korrekt mit Mausklicks
  • Die Tastaturnavigation (Pfeiltasten, Escape) funktioniert nicht nach dem Öffnen mit der Tastatur
  • Funktioniert einwandfrei in Demos ohne Animationsklassen
  • Fehlerhaft in Demos mit Animationsklassen

Grundursache

  1. CSS-Animationen wie fade-in-0 starten das Element bei opacity: 0
  2. Wenn focus() unmittelbar nach dem Rendern aufgerufen wird, ist das Element noch unsichtbar
  3. Der Browser lehnt den Fokus auf unsichtbare Elemente ab
  4. Der Fokus bleibt auf dem Auslöser-Button statt auf dem Inhalt
  5. Tastaturereignisse gehen an den Auslöser (der im geöffneten Zustand nichts tut) statt an den Inhalt

Nachweis durch Konsolen-Debugging

// Nach dem Öffnen von Select gehen Tastaturereignisse an den Auslöser, nicht an den Inhalt:
Document keydown: ArrowDown Target: <button role="combobox" ...>

// Aktives Element ist der Auslöser, nicht der Inhalt:
Active: BUTTON summit-select-...-trigger

Die Lösung

Implementieren Sie einen Wiederholungsmechanismus für den Fokus, der es der Animation ermöglicht, über opacity: 0 hinaus fortzuschreiten, bevor aufgegeben wird.

JavaScript-Implementierung

// src/SummitUI/Scripts/floating.js

/**
 * Fokussiert ein Element mit Wiederholungsmechanismus für animierte Elemente.
 * Elemente mit CSS-Animationen, die bei opacity:0 beginnen, können anfänglich focus() ablehnen.
 * Dies wiederholt den Fokus bis zu 5 Mal mit 20ms Verzögerung, um der Animation
 * zu ermöglichen, den unsichtbaren Zustand zu verlassen.
 * @param {HTMLElement} element - Zu fokussierendes Element
 */
export function focusElement(element) {
    if (!element) return;
    
    function tryFocus(attempts) {
        element.focus();
        // Wenn der Fokus nicht erfolgreich war und noch Versuche übrig sind, wiederholen
        if (document.activeElement !== element && attempts > 0) {
            setTimeout(() => tryFocus(attempts - 1), 20);
        }
    }
    
    // Erster Versuch nach einem Frame, damit CSS angewendet werden kann
    requestAnimationFrame(() => tryFocus(5));
}

Kernpunkte

  1. requestAnimationFrame zuerst verwenden – Stellt sicher, dass CSS angewendet wurde, bevor der Fokus versucht wird
  2. document.activeElement prüfen – Überprüfen, ob der Fokus tatsächlich erfolgreich war
  3. Mit Verzögerungen wiederholen – 20ms-Intervalle ermöglichen das Fortschreiten der Animation
  4. Begrenzte Versuche – 5 Wiederholungen = 100ms maximale Wartezeit, ausreichend für typische Animationen
  5. Auf alle Fokusfunktionen anwenden – Sowohl focusElement(element) als auch focusElementById(id) benötigen dieses Muster

Aktualisierte Funktionen

  • floating.js:focusElement(element) – Wird von SelectContent verwendet
  • floating.js:focusElementById(elementId) – Wird von DropdownMenuContent verwendet

Testen

"Mit Animationen"-Abschnitte zu Test-Demo-Seiten und entsprechende Playwright-Tests hinzugefügt.

CSS-Animationsklassen für Tests

/* 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;
}

Testfälle

Für jede Komponente (Select, DropdownMenu, Popover):

TestWas wird geprüft
Animated*_ShouldOpen_OnEnterKeyÖffnen mit Tastatur bei vorhandenen Animationen
Animated*_ShouldNavigate_WithArrowKeysPfeiltasten funktionieren nach animiertem Öffnen
Animated*_ShouldSelect/Activate_OnEnterKeyAuswahl/Aktivierung nach animiertem Öffnen möglich
Animated*_ShouldClose_OnEscapeEscape löst Schließanimation aus

Animationstests ausführen

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

Beteiligte Dateien

DateiZweck
src/SummitUI/Scripts/floating.jsEnthält die Funktionen focusElement und focusElementById
src/SummitUI/Components/Select/SelectContent.csRuft FocusElementAsync beim Öffnen auf
src/SummitUI/Components/DropdownMenu/DropdownMenuContent.csRuft FocusElementByIdAsync für Menüeinträge auf
src/SummitUI/Components/Popover/PopoverContent.csVerwaltet den Fokus für Popover-Inhalte

Alternativansätze

  1. Längere anfängliche Verzögerung – Könnte 50-100ms Verzögerung vor dem ersten Fokusversuch verwenden, fügt jedoch spürbare Verzögerung hinzu
  2. Fokus vor Animationsstart – Würde Änderungen an der Render-Reihenfolge erfordern, komplex
  3. Animation während Fokus deaktivieren – Würde einen visuellen Fehler verursachen
  4. CSS visibility statt opacity – Würde Änderungen an der Art und Weise erfordern, wie Animationen erstellt werden

Der Wiederholungsmechanismus wurde gewählt, weil er:

  • Mit jeder Animationsdauer funktioniert
  • Keine Änderungen an der CSS-Erstellung erfordert
  • Minimale Auswirkungen auf die Leistung hat
  • Sich bei fehlgeschlagenem Fokus ordentlich verhält

Verwandte Muster

Dieses Muster ähnelt der Handhabung von animierter Präsenz in bits-ui für Svelte-Komponenten. Die zentrale Erkenntnis ist, dass DOM-Operationen (wie Fokus) möglicherweise darauf warten müssen, dass CSS-Animationen einen fokussierbaren Zustand erreichen.

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

Verwandte Skills