Communitygithub.com

ComeOnOliver/skillshub

本技能记录了修复浮动组件(Select、DropdownMenu、Popover)在带有 CSS 开闭动画时键盘导航失效问题的解决方案。

skillshub 是什么?

本技能针对浮动组件(如 Select、DropdownMenu、Popover)在应用 CSS 开闭动画时出现的键盘导航失效问题,提供了一套经过验证的修复方案。核心问题在于,当元素通过 CSS 动画从 `opacity: 0` 开始渲染时,浏览器会拒绝立即调用 `focus()`,导致焦点仍停留在触发按钮上,从而使键盘事件无法正确传递到内容区域。技能文档详细分析了此问题的根本原因、控制台调试证据,并给出了一个基于重试机制的解决方案:利用 `requestAnimationFrame` 确保 CSS 已应用,然后以 20ms 为间隔最多重试 5 次 `focus()` 调用,直到焦点成功转移。该方案涵盖了 JavaScript 实现、需更新的函数列表、测试用例(包括 Playwright 测试)以及动画 CSS 类定义。它适用于任何前端框架中使用 CSS 动画的浮动 UI 组件,尤其对使用 Tailwind 等工具库并开启了 `animate-in fade-in-0` 类名的项目具有直接指导意义。

兼容平台~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 开闭动画时,修复键盘导航问题所积累的经验。

问题

当浮动内容元素的 CSS 动画从 opacity: 0 开始(例如 Tailwind 的 animate-in fade-in-0),浏览器可能会拒绝 element.focus() 调用,因为元素此时不可见。

症状

  • 使用鼠标点击可以正常打开组件
  • 使用键盘打开组件后,键盘导航(方向键、Escape)失效
  • 没有动画类别的演示中工作正常
  • 有动画类别的演示中出现故障

根本原因

  1. 诸如 fade-in-0 的 CSS 动画使元素从 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

/**
 * 为动画元素实现带重试机制的焦点设置。
 * CSS 动画从 opacity:0 开始的元素最初可能拒绝焦点设置。
 * 此函数最多重试 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 组件中处理动画存在性的方式。关键洞察在于,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

相关技能