compose-focus-navigation — скилл для Claude Code
Скилл помогает писать и проверять навигацию фокуса в Jetpack Compose для TV, клавиатуры и D-pad. Пригодится для начального и восстановленного фокуса.
npx skills add chrisbanes/skills --skill compose-focus-navigation -a claude-codeЧто делает compose-focus-navigation
Скилл разбирает фокус как состояние интерфейса: предлагает использовать уже фокусируемые компоненты, а для особых случаев добавлять FocusRequester, focusProperties, onFocusChanged или focusable(). Начальный и восстановленный фокус он связывает с LaunchedEffect, а для lazy-контента учитывает момент композиции элемента и стабильный идентификатор.
Отдельно задаются исключения пространственного поиска: переходы вверх и вниз, прыжки и ловушки фокуса. Обработчики клавиш должны поглощать только нужное событие, а проверки используют пользовательский ввод через performKeyInput и assertIsFocused(). При обновлении данных скилл советует сохранять фокус по идентификатору и выбирать детерминированный запасной вариант. Если проект не использует Jetpack Compose, эти рекомендации неприменимы.
Какие задачи решает
- настроить начальный фокус после загрузки экрана
- восстановить фокус на элементе после обновления данных
- задать исключения для навигации через D-pad
- обработать особое нажатие клавиши
- проверить фокус через пользовательский ввод
Примеры запросов агенту
- Проверь экран Jetpack Compose для TV: начальный фокус должен запрашиваться после появления элемента, а не из тела composable.
- Настрой переходы фокуса между header и первым рядом через
focusProperties, оставив стандартный пространственный поиск для остальных элементов. - Напиши тест, который нажимает
Key.DirectionDownчерезperformKeyInputи проверяетassertIsFocused()на кнопкеplay-button.
Как установить compose-focus-navigation
1Через Skills CLI (Vercel)
npx skills add chrisbanes/skills --skill compose-focus-navigation -a claude-code2Вручную: положить файлы
~/.claude/skills/compose-focus-navigation/SKILL.mdПапка скилла целиком; для одного проекта — .claude/skills/compose-focus-navigation/
1Через Skills CLI (Vercel)
npx skills add chrisbanes/skills --skill compose-focus-navigation -a codex2Вручную: положить файлы
.agents/skills/compose-focus-navigation/SKILL.mdДля всех проектов — ~/.agents/skills/
1Через Skills CLI (Vercel)
npx skills add chrisbanes/skills --skill compose-focus-navigation -a cursor2Вручную: положить файлы
.cursor/skills/compose-focus-navigation/SKILL.mdCursor читает и .agents/skills/, и .claude/skills/
1GitHub CLI
gh skill install chrisbanes/skills compose-focus-navigation2Вручную: положить файлы
.github/skills/compose-focus-navigation/SKILL.md1Через Skills CLI (Vercel)
npx skills add chrisbanes/skills --skill compose-focus-navigation -a gemini-cli2Командой платформы
gemini skills install https://github.com/chrisbanes/skills --path skills/compose-focus-navigationВручную: положить файлы
.devin/skills/compose-focus-navigation/SKILL.mdСтарый путь .windsurf/skills/ тоже читается
Через Skills CLI (Vercel)
npx skills add chrisbanes/skills --skill compose-focus-navigation -a opencodeClaude.ai
Упакуйте папку в zip и загрузите в Settings → Capabilities → Skills
По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов
Из того же набора17
Похожие
Рядом в теме «Фронтенд и UI»
Всё по теме «Фронтенд и UI» →Вопросы о compose-focus-navigation
Как установить compose-focus-navigation в Claude Code?
Выполните npx skills add chrisbanes/skills --skill compose-focus-navigation -a claude-code, затем повторите эту команду: npx skills add chrisbanes/skills --skill compose-focus-navigation -a claude-code. Файл скилла находится по пути ~/.claude/skills/compose-focus-navigation/SKILL.md.
Что делает compose-focus-navigation?
Скилл помогает проектировать и проверять фокус в Jetpack Compose: начальный и восстановленный фокус, D-pad-навигацию, обработку клавиш, особые переходы и тесты через пользовательский ввод.
С какими платформами работает compose-focus-navigation?
Скилл доступен для Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI и OpenCode.
Исходный текст
SKILL.md · Apache-2.0
---
name: compose-focus-navigation
description: Use when writing or reviewing Jetpack Compose UI for TV, keyboard, desktop, accessibility focus, D-pad navigation, FocusRequester, focusProperties, key events, or initial focus behavior.
---
# Compose: focus navigation
## Core principle
Focus is stateful UI behavior: make targets and exceptional edges explicit, then drive and verify it through the user's keyboard, D-pad, or remote input.
## Procedure
1. Start with components that already participate in focus. Add a hook only for a requested behavior:
| Need | Add |
|---|---|
| Normal button/text field/clickable focus | Nothing extra; use the focusable component |
| Programmatic initial/restored focus | `FocusRequester` + `Modifier.focusRequester(...)` |
| Visual or state reaction to focus changes | `Modifier.onFocusChanged { ... }` |
| Custom interactive surface that is not already focusable | `Modifier.focusable()` plus role/semantics as appropriate |
2. Request initial or restored focus from `LaunchedEffect`, keyed to the condition that makes the target present. For lazy content, keep requesters by stable item id and request only after the item is composed. Inside `AnimatedContent`, use the content lambda's target consistently for rendered identity, tags, requester ownership, and the effect key; captured outer state gives outgoing and incoming content the same identity.
In a review, a finding about `requestFocus()` running in the composable body
is incomplete until it names the event or keyed effect that should issue
the request after its target is available.
3. Keep default spatial search unless a concrete edge, jump, or trap is wrong. Encode only those exceptions with `focusProperties`.
4. Handle keys only for behavior that is not normal click or traversal. Consume exactly the handled event; throttle rapid D-pad work at its expensive owner, not across the screen.
5. Restore by semantic identity after refresh: retain the focused id when it exists, otherwise choose a deterministic fallback.
6. Test with one concrete key/D-pad interaction and focused semantics. When the behavior under review is user-triggered, do not substitute direct state mutation or leave the input conditional. Use screenshots only for the focus appearance.
7. Finish when all intentional targets and exceptional edges are encoded, loading/refresh behavior has a stable focus policy, and tests use the same input model as users.
For example, request and observe focus only when both behaviors are required:
```kotlin
val requester = remember { FocusRequester() }
Button(
onClick = onClick,
modifier = Modifier
.focusRequester(requester)
.onFocusChanged { state -> isFocused = state.isFocused },
) {
Text("Play")
}
```
Call focus requests from an effect, not the composable body:
```kotlin
val initialFocus = remember { FocusRequester() }
LaunchedEffect(initialFocus) {
initialFocus.requestFocus()
}
```
If the target appears after loading, key the request to the condition:
```kotlin
LaunchedEffect(items.isNotEmpty()) {
if (items.isNotEmpty()) {
firstItemRequester.requestFocus()
}
}
```
Use `focusProperties` only when default spatial search is wrong:
```kotlin
Modifier.focusProperties {
up = headerRequester
down = firstRowRequester
left = FocusRequester.Cancel
}
```
Too many hard-coded links create stale focus graphs. For special key behavior, consume only the handled event:
```kotlin
Modifier.onPreviewKeyEvent { event ->
if (event.type == KeyEventType.KeyUp && event.key == Key.Back) {
onBack()
true
} else {
false
}
}
```
Test focus through user input:
```kotlin
composeTestRule.onNodeWithTag("screen").performKeyInput {
pressKey(Key.DirectionDown)
}
composeTestRule.onNodeWithTag("play-button").assertIsFocused()
```
Broader test-shape choices are in [Compose UI testing patterns](../compose-ui-testing-patterns/SKILL.md).
© chrisbanes · Apache-2.0 · chrisbanes/skills