Communitygithub.com

ComeOnOliver/skillshub

CSSアニメーション(opacity: 0からのフェードイン)を伴う浮動コンポーネント(Select、DropdownMenu、Popover)におけるキーボードナビゲーションの問題を修正した学習内容をまとめています。

skillshub とは?

このスキルは、CSSアニメーション(特にTailwindの`fade-in-0`など`opacity: 0`から始まるアニメーション)を使用している浮動コンポーネント(Select、DropdownMenu、Popover)において、キーボードナビゲーションが機能しなくなる問題の根本原因と解決策を文書化しています。問題の原因は、レンダリング直後に要素が不可視であるためにブラウザが`focus()`呼び出しを拒否し、キーボードイベントがトリガーボタンに留まることにあります。このスキルでは、`requestAnimationFrame`と20ms間隔のリトライ(最大5回)を組み合わせて、アニメーションが進行して要素がフォーカス可能になるのを待つシンプルなリトライ機構を提案しています。このパターンは`floating.js`内の`focusElement`および`focusElementById`関数に実装され、Select、DropdownMenu、Popoverの各コンポーネントで適用されています。また、アニメーションありのテストケース(開く、矢印キー操作、選択/実行、Escape閉じる)とPlaywrightテストも追加されています。

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

お気に入りのAIに質問する

このエージェントスキルを事前に読み込んだ状態で新しいチャットを開きます。

ドキュメント

CSSアニメーションにおけるフォーカス管理

このドキュメントは、浮動コンポーネント(Select、DropdownMenu、Popover)にCSSの開閉アニメーションがある場合のキーボードナビゲーションの問題を修正した学習内容をまとめたものです。

問題

浮動コンテンツ要素にopacity: 0から始まるCSSアニメーション(Tailwindのanimate-in fade-in-0など)があると、ブラウザが要素を不可視と判断し、element.focus()の呼び出しを拒否する場合があります。

症状

  • マウスクリックではコンポーネントが正しく開く
  • キーボードで開いた後、キーボードナビゲーション(矢印キー、Escape)が機能しない
  • アニメーションクラスがないデモでは正常に動作する
  • アニメーションクラスがあるデモでは動作しない

根本原因

  1. fade-in-0のようなCSSアニメーションは要素をopacity: 0から開始する
  2. レンダリング直後にfocus()が呼び出されると、要素はまだ不可視状態
  3. ブラウザは不可視要素へのフォーカスを拒否する
  4. フォーカスがトリガーボタンに留まり、コンテンツに移動しない
  5. キーボードイベントが(開いている状態では何もしない)トリガーに送られ、コンテンツには届かない

コンソールデバッグによる証拠

// セレクトを開いた後、キーボードイベントはコンテンツではなくトリガーに送られる:
Document keydown: ArrowDown Target: <button role="combobox" ...>

// アクティブ要素はコンテンツではなくトリガー:
Active: BUTTON summit-select-...-trigger

解決策

フォーカスが失敗した場合に、アニメーションがopacity: 0の状態を過ぎて進行するのを待つリトライ機構を実装します。

JavaScript実装

// src/SummitUI/Scripts/floating.js

/**
 * アニメーション要素向けのリトライ機構付きフォーカス関数。
 * opacity:0から始まるCSSアニメーション要素は、初期状態でフォーカスを拒否する場合がある。
 * 20ms間隔で最大5回リトライし、アニメーションが不可視状態を過ぎるのを待つ。
 * @param {HTMLElement} element - フォーカスする要素
 */
export function focusElement(element) {
    if (!element) return;
    
    function tryFocus(attempts) {
        element.focus();
        // フォーカスが成功せず、リトライ回数が残っている場合、再試行
        if (document.activeElement !== element && attempts > 0) {
            setTimeout(() => tryFocus(attempts - 1), 20);
        }
    }
    
    // CSSが適用されるよう、1フレーム後に最初の試行
    requestAnimationFrame(() => tryFocus(5));
}

重要なポイント

  1. 最初にrequestAnimationFrameを使用 - CSSが適用されてからフォーカスを試行することを保証
  2. document.activeElementを確認 - フォーカスが実際に成功したか検証
  3. 遅延付きでリトライ - 20ms間隔でアニメーションの進行を許可
  4. リトライ回数を制限 - 5回のリトライ = 最大100msの待機、一般的なアニメーションに十分
  5. すべてのフォーカス関数に適用 - focusElement(element)とfocusElementById(id)の両方にこのパターンが必要

更新された関数

  • floating.js:focusElement(element) - SelectContentで使用
  • floating.js:focusElementById(elementId) - DropdownMenuContentで使用

テスト

「アニメーションあり」セクションをテストデモページに追加し、対応するPlaywrightテストも追加しました。

テスト用CSSアニメーションクラス

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

テストケース

各コンポーネント(Select、DropdownMenu、Popover)に対して:

テスト検証内容
Animated*_ShouldOpen_OnEnterKeyアニメーションありでキーボード(Enter)で開くこと
Animated*_ShouldNavigate_WithArrowKeysアニメーションありで開いた後に矢印キーが動作すること
Animated*_ShouldSelect/Activate_OnEnterKeyアニメーションありで開いた後に項目を選択/実行できること
Animated*_ShouldClose_OnEscapeEscapeキーで閉じるアニメーションがトリガーされること

アニメーションテストの実行

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

関連ファイル

ファイル目的
src/SummitUI/Scripts/floating.jsfocusElementとfocusElementById関数を含む
src/SummitUI/Components/Select/SelectContent.cs開く際にFocusElementAsyncを呼び出す
src/SummitUI/Components/DropdownMenu/DropdownMenuContent.csメニュー項目に対してFocusElementByIdAsyncを呼び出す
src/SummitUI/Components/Popover/PopoverContent.csポップオーバーコンテンツのフォーカスを管理

検討した代替アプローチ

  1. より長い初期遅延 - 最初のフォーカス試行前に50~100msの遅延を入れる方法。ただし、顕著なラグが生じる。
  2. アニメーション開始前にフォーカス - レンダリング順序の変更が必要で複雑。
  3. フォーカス中にアニメーションを無効化 - 視覚的な不具合が生じる。
  4. CSSのvisibilityをopacityの代わりに使用 - アニメーションの記述方法を変更する必要がある。

リトライ機構を選択した理由:

  • あらゆるアニメーション時間に対応
  • CSSの記述方法を変更する必要がない
  • パフォーマンスへの影響が最小限
  • フォーカスが最終的に成功しなくても、グレースフルに失敗する

関連パターン

このパターンは、Svelteコンポーネントにおけるbits-uiのアニメーションプレゼンス処理と似ています。重要な洞察は、DOM操作(フォーカスなど)はCSSアニメーションがフォーカス可能な状態に達するのを待つ必要がある可能性があるということです。

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

関連スキル