Communitygithub.com

ComeOnOliver/skillshub

記錄修復浮動元件 (Select、DropdownMenu、Popover) 在 CSS 開合動畫下鍵盤導航問題的解決方案與學習心得。

skillshub 是什麼?

這份文件詳細說明當浮動內容元件(如 Select、DropdownMenu、Popover)使用 CSS 開合動畫時,如何修復鍵盤導航失效的問題。問題根源在於 CSS 動畫從 `opacity: 0` 開始時,瀏覽器會拒絕對不可見元素呼叫 `focus()`,導致鍵盤事件(方向鍵、Escape)仍然作用於觸發按鈕而非浮動內容。解決方案是實作一個重試機制,利用 `requestAnimationFrame` 確保 CSS 已套用,並在最多 5 次、每次延遲 20ms 的嘗試中檢查 `document.activeElement` 是否成功聚焦,從而讓動畫順利越過 `opacity: 0` 狀態。此技能支援在任何使用浮動元件的 Web 框架中應用,並已在原始專案的測試頁面與 Playwright 測試中被驗證有效,是最小侵入性且相容於各種動畫持續時間的解決方案。

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

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

CSS 動畫下的焦點管理

本文件記錄修復浮動元件(Select、DropdownMenu、Popover)在 CSS 開合動畫下鍵盤導航問題的學習心得。

問題

當浮動內容元素使用從 opacity: 0 起始的 CSS 動畫(例如 Tailwind 的 animate-in fade-in-0),瀏覽器可能會因為元素不可見而拒絕 element.focus() 的呼叫。

症狀

  • 使用滑鼠點擊時元件正常開啟
  • 使用鍵盤開啟後,鍵盤導航(方向鍵、Escape)失效
  • 在沒有動畫類別的示範頁面上正常運作
  • 在有動畫類別的示範頁面上失效

根本原因

  1. CSS 動畫(如 fade-in-0)讓元素從 opacity: 0 開始
  2. 在渲染後立即呼叫 focus() 時,元素仍處於不可見狀態
  3. 瀏覽器拒絕將焦點放在不可見元素上
  4. 焦點停留在觸發按鈕,而非移至內容
  5. 鍵盤事件進入觸發按鈕(開啟時無作用),而非內容

主控台除錯證據

// 開啟 Select 後,鍵盤事件進入觸發按鈕,而非內容:
Document keydown: ArrowDown Target: <button role="combobox" ...>

// 活動元素是觸發按鈕,而非內容:
Active: BUTTON summit-select-...-trigger

解決方案

實作一個針對動畫元素的焦點重試機制,讓動畫在放棄前有機會越過 opacity: 0 狀態。

JavaScript 實作

// src/SummitUI/Scripts/floating.js

/**
 * 使用重試機制聚焦於元素,適用於動畫元素。
 * 起始於 opacity:0 的 CSS 動畫元素可能會拒絕初始焦點。
 * 本函數最多重試 5 次,每次延遲 20ms,讓動畫
 * 能夠越過不可見狀態。
 * @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 有時間套用
    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在動畫存在時以鍵盤開啟
Animated*_ShouldNavigate_WithArrowKeys在動畫開啟後方向鍵可運作
Animated*_ShouldSelect/Activate_OnEnterKey在動畫開啟後可選擇/啟動項目
Animated*_ShouldClose_OnEscapeEscape 可觸發關閉動畫

執行動畫測試

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

涉及檔案

檔案用途
src/SummitUI/Scripts/floating.js包含 focusElement 和 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 撰寫方式
  • 效能影響極小
  • 若聚焦始終不成功,可優雅地失敗

相關模式

此模式類似於 bits-ui 在 Svelte 元件中處理動畫存在(animated presence)的方式。關鍵洞察在於 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

相關技能