Communitygithub.com

ComeOnOliver/skillshub

CSS 애니메이션이 있는 플로팅 컴포넌트(Select, DropdownMenu, Popover)의 키보드 탐색 문제를 수정한 학습 내용을 문서화합니다.

skillshub란 무엇인가요?

이 스킬은 CSS 오픈/클로즈 애니메이션(예: Tailwind의 `fade-in-0`)이 있는 플로팅 UI 컴포넌트에서 키보드 포커스가 제대로 작동하지 않는 문제를 해결하는 방법을 설명합니다. 문제의 근본 원인은 애니메이션이 `opacity: 0`으로 시작할 때 브라우저가 보이지 않는 요소에 `focus()`를 거부하기 때문입니다. 이로 인해 키보드 이벤트가 콘텐츠가 아닌 트리거 버튼에 전달되어 탐색이 실패합니다. 해결책으로 `requestAnimationFrame`과 20ms 간격의 재시도 메커니즘(최대 5회)을 구현하여 애니메이션이 진행되어 요소가 보이는 상태가 될 때까지 포커스를 지연시킵니다. 이 패턴은 JavaScript `focusElement` 및 `focusElementById` 함수에 적용되며, Select, DropdownMenu, Popover 컴포넌트에서 사용됩니다. 또한 애니메이션 테스트를 위한 CSS 키프레임과 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. 키보드 이벤트가 콘텐츠 대신 트리거로 전달됨(트리거는 열려 있을 때 아무 동작도 하지 않음)

콘솔 디버깅 증거

// Select를 연 후, 키보드 이벤트가 콘텐츠가 아닌 트리거로 전달됨:
Document keydown: ArrowDown Target: <button role="combobox" ...>

// 활성 요소는 트리거이며, 콘텐츠가 아님:
Active: BUTTON summit-select-...-trigger

해결책

애니메이션이 opacity: 0 상태를 지나 진행될 수 있도록 포커스 재시도 메커니즘을 구현합니다.

JavaScript 구현

// src/SummitUI/Scripts/floating.js

/**
 * 애니메이션 요소를 위한 재시도 메커니즘으로 요소에 포커스를 설정합니다.
 * opacity:0으로 시작하는 CSS 애니메이션이 있는 요소는 초기에 focus()를 거부할 수 있습니다.
 * 애니메이션이 보이지 않는 상태를 지나 진행될 수 있도록 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가 적용될 수 있도록 한 프레임 후 첫 번째 시도
    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.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. opacity 대신 CSS visibility 사용 - 애니메이션 작성 방식을 변경해야 함

재시도 메커니즘을 선택한 이유:

  • 모든 애니메이션 지속 시간과 호환됨
  • 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

관련 스킬