mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 12:54:20 +01:00
feat(shortcuts): rework shortcut bindings, focus restore, and input guards
Resolve effective bindings from stored prefs plus defaults with leader/direct collision handling and default leader Ctrl+X; let direct actions pass through in terminals and suppress abort while an overlay is open. Add half-page scroll disengage, verified overlay focus restore, and consolidate prompt reset.
This commit is contained in:
1 parent
7e8443f54f
commit
994a8b82e8
33 files changed
+784
-195
No files matched your search
@@ -446,6 +446,23 @@ describe('PromptInput command submission', () => {
|
||||
expect(screen.queryByTestId('composer-mode-badge')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('clears attachments and exits bash mode on Escape while idle', async () => {
|
||||
const { container } = renderComponent()
|
||||
|
||||
const input = await screen.findByPlaceholderText('Send a message...')
|
||||
fireEvent.change(input, { target: { value: '!' } })
|
||||
expect(screen.getByTestId('composer-mode-badge')).toHaveTextContent('BASH')
|
||||
|
||||
await attachImage(container)
|
||||
expect(screen.getByText('pic.png')).toBeInTheDocument()
|
||||
|
||||
fireEvent.keyDown(input, { key: 'Escape' })
|
||||
|
||||
expect(input).toHaveValue('')
|
||||
expect(screen.queryByTestId('composer-mode-badge')).not.toBeInTheDocument()
|
||||
expect(screen.queryByText('pic.png')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('keeps attachments and clears only the text when a built-in command is submitted', async () => {
|
||||
const { container } = renderComponent()
|
||||
|
||||
|
||||
@@ -988,8 +988,7 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read)
|
||||
const handleKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {
|
||||
if (isBashMode && e.key === 'Escape') {
|
||||
e.preventDefault()
|
||||
setIsBashMode(false)
|
||||
setPrompt('')
|
||||
resetPrompt()
|
||||
return
|
||||
}
|
||||
|
||||
@@ -1070,12 +1069,7 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read)
|
||||
}
|
||||
handleSubmit()
|
||||
} else if (e.key === 'Escape' && !isSessionActive) {
|
||||
closeSuggestions()
|
||||
setPrompt('')
|
||||
revokeBlobUrls(imageAttachments)
|
||||
setImageAttachments([])
|
||||
resetVoiceGestureState()
|
||||
clearSTT()
|
||||
resetPrompt()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1109,6 +1103,21 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read)
|
||||
setMentionRange(null)
|
||||
}, [])
|
||||
|
||||
const resetPrompt = useCallback(() => {
|
||||
setPrompt('')
|
||||
setAttachedFiles(new Map())
|
||||
revokeBlobUrls(imageAttachments)
|
||||
setImageAttachments([])
|
||||
closeSuggestions()
|
||||
setIsBashMode(false)
|
||||
resetVoiceGestureState()
|
||||
if (isRecording) {
|
||||
abortRecording()
|
||||
} else {
|
||||
clearSTT()
|
||||
}
|
||||
}, [imageAttachments, clearSTT, isRecording, abortRecording, resetVoiceGestureState, closeSuggestions])
|
||||
|
||||
const updateSuggestionTriggers = (value: string, cursorPosition: number) => {
|
||||
const mentionTrigger = detectMentionTrigger(value, cursorPosition)
|
||||
|
||||
@@ -1272,18 +1281,7 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read)
|
||||
textareaRef.current?.focus()
|
||||
},
|
||||
clearPrompt: () => {
|
||||
setPrompt('')
|
||||
setAttachedFiles(new Map())
|
||||
revokeBlobUrls(imageAttachments)
|
||||
setImageAttachments([])
|
||||
closeSuggestions()
|
||||
setIsBashMode(false)
|
||||
resetVoiceGestureState()
|
||||
if (isRecording) {
|
||||
abortRecording()
|
||||
} else {
|
||||
clearSTT()
|
||||
}
|
||||
resetPrompt()
|
||||
textareaRef.current?.focus()
|
||||
},
|
||||
triggerFileUpload: openFilePicker,
|
||||
@@ -1292,7 +1290,7 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read)
|
||||
},
|
||||
cycleAgent: handleCycleAgent,
|
||||
cycleVariant: handleCycleVariant,
|
||||
}), [imageAttachments, clearSTT, isRecording, abortRecording, resetVoiceGestureState, closeSuggestions, openFilePicker, handleCycleAgent, handleCycleVariant])
|
||||
}), [resetPrompt, openFilePicker, handleCycleAgent, handleCycleVariant])
|
||||
|
||||
const commandActionsWithPrompt = useMemo<CommandActions>(
|
||||
() => ({
|
||||
|
||||
@@ -9,8 +9,17 @@ import type { Provider } from '@/api/providers'
|
||||
const mocks = vi.hoisted(() => ({
|
||||
useModelSelection: vi.fn(),
|
||||
useModelSections: vi.fn(),
|
||||
deferredSearchValue: { current: null as string | null },
|
||||
}))
|
||||
|
||||
vi.mock('react', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('react')>()
|
||||
return {
|
||||
...actual,
|
||||
useDeferredValue: (value: string) => mocks.deferredSearchValue.current ?? value,
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('@/hooks/useModelSelection', () => ({
|
||||
useModelSelection: mocks.useModelSelection,
|
||||
}))
|
||||
@@ -151,8 +160,23 @@ function focusDetachedTextarea() {
|
||||
return textarea
|
||||
}
|
||||
|
||||
const originalInnerWidth = window.innerWidth
|
||||
|
||||
function setViewportWidth(width: number) {
|
||||
Object.defineProperty(window, 'innerWidth', { configurable: true, writable: true, value: width })
|
||||
}
|
||||
|
||||
function mobileModelList() {
|
||||
const lists = Array.from(document.querySelectorAll<HTMLElement>('.overflow-y-auto.px-4.pb-4'))
|
||||
const list = lists.find((element) => !element.classList.contains('pt-2'))
|
||||
if (!list) throw new Error('No mobile model list found')
|
||||
return list
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
document.querySelectorAll('textarea').forEach((element) => element.remove())
|
||||
setViewportWidth(originalInnerWidth)
|
||||
mocks.deferredSearchValue.current = null
|
||||
})
|
||||
|
||||
beforeAll(() => {
|
||||
@@ -453,4 +477,89 @@ describe('ModelQuickSelect keyboard navigation', () => {
|
||||
|
||||
expect(fireEvent.keyDown(textarea, { key: 'ArrowDown' })).toBe(true)
|
||||
})
|
||||
|
||||
it('ignores keyboard navigation when the mobile provider list hides the models', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { setModel } = setModelSelection()
|
||||
setViewportWidth(500)
|
||||
|
||||
render(<ModelQuickSelect open />)
|
||||
await user.click(screen.getByRole('button', { name: /More models/ }))
|
||||
|
||||
const textarea = focusDetachedTextarea()
|
||||
|
||||
expect(fireEvent.keyDown(textarea, { key: 'ArrowDown' })).toBe(true)
|
||||
expect(fireEvent.keyDown(textarea, { key: 'Enter' })).toBe(true)
|
||||
|
||||
expect(setModel).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('navigates the provider models that are visible on mobile', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { setModel } = setModelSelection()
|
||||
setViewportWidth(500)
|
||||
|
||||
render(<ModelQuickSelect open />)
|
||||
await user.click(screen.getByRole('button', { name: /More models/ }))
|
||||
await user.click(screen.getAllByRole('button', { name: /Anthropic 2 models/ })[0])
|
||||
|
||||
const textarea = focusDetachedTextarea()
|
||||
|
||||
expect(fireEvent.keyDown(textarea, { key: 'ArrowDown' })).toBe(false)
|
||||
expect(fireEvent.keyDown(textarea, { key: 'Enter' })).toBe(false)
|
||||
|
||||
expect(setModel).toHaveBeenCalledWith(selection('anthropic', 'claude-opus-5-5-fast'))
|
||||
})
|
||||
|
||||
it('ignores keydown events while an IME composition is active', () => {
|
||||
const { setModel } = setModelSelection({ model: selection('opencode-go', 'go-1') })
|
||||
|
||||
render(<ModelQuickSelect open />)
|
||||
|
||||
const textarea = focusDetachedTextarea()
|
||||
|
||||
expect(fireEvent.keyDown(textarea, { key: 'ArrowDown', isComposing: true })).toBe(true)
|
||||
expect(fireEvent.keyDown(textarea, { key: 'Enter', isComposing: true })).toBe(true)
|
||||
|
||||
expect(setModel).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('does not select while the deferred search query is still catching up', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { setModel } = setModelSelection()
|
||||
|
||||
render(<ModelQuickSelect open />)
|
||||
await user.click(screen.getByRole('button', { name: /More models/ }))
|
||||
|
||||
const searchInput = screen.getByPlaceholderText('Search models...')
|
||||
mocks.deferredSearchValue.current = ''
|
||||
await user.type(searchInput, '5')
|
||||
|
||||
expect(fireEvent.keyDown(searchInput, { key: 'Enter' })).toBe(false)
|
||||
|
||||
expect(setModel).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('scrolls the mobile provider model list to follow the active row', async () => {
|
||||
const user = userEvent.setup()
|
||||
const clientHeight = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'clientHeight')
|
||||
Object.defineProperty(HTMLElement.prototype, 'clientHeight', { configurable: true, get: () => 60 })
|
||||
setViewportWidth(500)
|
||||
|
||||
try {
|
||||
render(<ModelQuickSelect open />)
|
||||
await user.click(screen.getByRole('button', { name: /More models/ }))
|
||||
await user.click(screen.getAllByRole('button', { name: /Anthropic 2 models/ })[0])
|
||||
|
||||
const list = mobileModelList()
|
||||
expect(list.scrollTop).toBe(0)
|
||||
|
||||
const textarea = focusDetachedTextarea()
|
||||
fireEvent.keyDown(textarea, { key: 'ArrowDown' })
|
||||
|
||||
expect(list.scrollTop).toBe(60)
|
||||
} finally {
|
||||
Object.defineProperty(HTMLElement.prototype, 'clientHeight', clientHeight!)
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useCallback, useDeferredValue, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'
|
||||
import { Check, ChevronDown, ChevronLeft, ChevronRight, Search, Star, Trash2, X, type LucideIcon } from 'lucide-react'
|
||||
import { useModelSelection, type ModelSelectionSession } from '@/hooks/useModelSelection'
|
||||
import { useMobile } from '@/hooks/useMobile'
|
||||
import { useModelSections } from '@/hooks/useModelSections'
|
||||
import { useVariants } from '@/hooks/useVariants'
|
||||
import { modelSelectionRef, type Model } from '@/api/providers'
|
||||
@@ -14,6 +15,7 @@ import {
|
||||
} from '@/components/ui/dropdown-menu'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { buildModelSections, filterModelSections, type ModelOption } from '@/lib/modelSections'
|
||||
import { isTextEntryElement } from '@/lib/domTargets'
|
||||
|
||||
interface ModelQuickSelectProps {
|
||||
directory?: string
|
||||
@@ -183,6 +185,7 @@ export function ModelQuickSelect({
|
||||
const [selectedProviderId, setSelectedProviderId] = useState<string | null>(null)
|
||||
const [activeIndex, setActiveIndex] = useState(0)
|
||||
const quickListRef = useRef<HTMLDivElement>(null)
|
||||
const isMobile = useMobile()
|
||||
const { model, modelString, info, recentModels, favoriteModels, setModel, toggleFavorite, removeRecentModel } = useModelSelection(directory, session)
|
||||
const { availableVariants, currentVariant, setVariant, clearVariant, hasVariants } = useVariants(directory, session)
|
||||
|
||||
@@ -286,10 +289,12 @@ export function ModelQuickSelect({
|
||||
|
||||
const navigableItems = useMemo((): ModelListItem[] => {
|
||||
if (showAllModels) {
|
||||
return isSearching ? searchResults : browseModels
|
||||
if (isSearching) return searchResults
|
||||
if (isMobile && !selectedProviderId) return EMPTY_MODELS
|
||||
return browseModels
|
||||
}
|
||||
return quickSections.flatMap((section) => section.models)
|
||||
}, [showAllModels, isSearching, searchResults, browseModels, quickSections])
|
||||
}, [showAllModels, isSearching, isMobile, selectedProviderId, searchResults, browseModels, quickSections])
|
||||
|
||||
const quickSectionOffsets = useMemo(() => {
|
||||
const offsets = new Map<string, number>()
|
||||
@@ -306,6 +311,10 @@ export function ModelQuickSelect({
|
||||
navigableItemsRef.current = navigableItems
|
||||
const modelStringRef = useRef(modelString)
|
||||
modelStringRef.current = modelString
|
||||
const searchQueryRef = useRef(searchQuery)
|
||||
searchQueryRef.current = searchQuery
|
||||
const deferredSearchQueryRef = useRef(deferredSearchQuery)
|
||||
deferredSearchQueryRef.current = deferredSearchQuery
|
||||
|
||||
useEffect(() => {
|
||||
const selectedIndex = navigableItemsRef.current.findIndex((item) => item.key === modelStringRef.current)
|
||||
@@ -341,15 +350,20 @@ export function ModelQuickSelect({
|
||||
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.ctrlKey || event.metaKey || event.altKey) return
|
||||
if (event.isComposing) return
|
||||
|
||||
const target = event.target
|
||||
if (target instanceof HTMLElement && target.closest('[role="menu"]')) return
|
||||
|
||||
const isTextInput =
|
||||
target instanceof HTMLElement && (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA')
|
||||
const isTextInput = target instanceof Element && isTextEntryElement(target)
|
||||
|
||||
if (event.key === 'Enter') {
|
||||
if (target instanceof HTMLElement && target.closest('button')) return
|
||||
if (searchQueryRef.current !== deferredSearchQueryRef.current) {
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
return
|
||||
}
|
||||
const item = navigableItems[activeIndex]
|
||||
if (!item) return
|
||||
event.preventDefault()
|
||||
@@ -676,6 +690,7 @@ export function ModelQuickSelect({
|
||||
emptyLabel="No models found"
|
||||
className="px-4 pb-4"
|
||||
resetKey={selectedProviderId}
|
||||
activeIndex={activeIndex}
|
||||
/>
|
||||
) : (
|
||||
<div className="h-full overflow-y-auto px-4 pb-4">
|
||||
|
||||
@@ -16,7 +16,7 @@ import { RepoActionsContent } from '@/components/repo/RepoActionsDialog'
|
||||
import { RepoSkillsContent } from '@/components/repo/RepoSkillsDialog'
|
||||
import { RepoSchedulesContent } from '@/components/schedules/RepoSchedulesContent'
|
||||
import type { SkillFileInfo } from '@opencode-manager/shared'
|
||||
import { buildToolItems, type MoreDrawerItem } from '@/components/navigation/moreDrawerItems'
|
||||
import { buildToolItems, toolKeyOf, type MoreDrawerItem } from '@/components/navigation/moreDrawerItems'
|
||||
import { isPanelTool, type ToolPanelState, type PanelTool } from '@/hooks/useToolPanel'
|
||||
import { useOpenNavItem } from '@/hooks/useOpenNavItem'
|
||||
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'
|
||||
@@ -108,7 +108,7 @@ export function ToolSidePanel({
|
||||
const panelTools: Array<{ item: MoreDrawerItem; tool: PanelTool }> = []
|
||||
const actionItems: MoreDrawerItem[] = []
|
||||
for (const item of buildToolItems(location.pathname)) {
|
||||
const tool = item.panelTool ?? item.dialog ?? null
|
||||
const tool = toolKeyOf(item)
|
||||
if (isPanelTool(tool)) panelTools.push({ item, tool })
|
||||
else actionItems.push(item)
|
||||
}
|
||||
|
||||
@@ -60,6 +60,11 @@ export function buildToolItems(pathname: string): MoreDrawerItem[] {
|
||||
return buildNavModel(pathname).items.filter((item) => !NON_TOOL_ITEM_KEYS.has(item.key))
|
||||
}
|
||||
|
||||
/** The `?panel=`/`?dialog=` tool identifier an item targets, preferring its panel tool. */
|
||||
export function toolKeyOf(item: MoreDrawerItem): string | null {
|
||||
return item.panelTool ?? item.dialog ?? null
|
||||
}
|
||||
|
||||
function buildRouteNavModel(pathname: string): NavModel {
|
||||
const baseItems = getBaseItems()
|
||||
|
||||
|
||||
@@ -1,9 +1,24 @@
|
||||
import { render, screen, waitFor, within } from '@testing-library/react'
|
||||
import { render as renderRaw, screen, waitFor, within } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import type { ReactElement } from 'react'
|
||||
import type { FormInfo } from '@opencode-manager/shared/opencode'
|
||||
import { KeyboardShortcutsProvider, useShortcutActions } from '@/contexts/KeyboardShortcutsContext'
|
||||
import { FormPrompt } from './FormPrompt'
|
||||
|
||||
vi.mock('@/hooks/useSettings', () => ({
|
||||
useSettings: () => ({ preferences: undefined }),
|
||||
}))
|
||||
|
||||
function render(ui: ReactElement) {
|
||||
return renderRaw(ui, { wrapper: KeyboardShortcutsProvider })
|
||||
}
|
||||
|
||||
function AbortLayer({ onAbort }: { onAbort: () => void }) {
|
||||
useShortcutActions({ abort: onAbort })
|
||||
return null
|
||||
}
|
||||
|
||||
const selectForm: FormInfo = {
|
||||
id: 'form-1',
|
||||
sessionID: 'session-1',
|
||||
@@ -612,4 +627,22 @@ describe('FormPrompt', () => {
|
||||
expect(screen.queryByRole('link', { name: /Approve access/ })).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
describe('keyboard shortcuts', () => {
|
||||
it('minimizes once on Escape while expanded without triggering a registered session abort', async () => {
|
||||
const sessionAbort = vi.fn()
|
||||
const onMinimize = vi.fn()
|
||||
render(
|
||||
<>
|
||||
<AbortLayer onAbort={sessionAbort} />
|
||||
<FormPrompt form={selectForm} onReply={vi.fn()} onCancel={vi.fn()} onMinimize={onMinimize} />
|
||||
</>
|
||||
)
|
||||
|
||||
await userEvent.keyboard('{Escape}')
|
||||
|
||||
expect(onMinimize).toHaveBeenCalledTimes(1)
|
||||
expect(sessionAbort).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -7,6 +7,7 @@ import type { FormAnswer, FormField, FormInfo } from '@opencode-manager/shared/o
|
||||
import { buildAnswer, hasMissingAnswers, visibleFields } from '@/lib/formFields'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { showToast } from '@/lib/toast'
|
||||
import { useShortcutActions } from '@/contexts/KeyboardShortcutsContext'
|
||||
|
||||
type AnswerableFormField = Exclude<FormField, { type: 'external' }>
|
||||
|
||||
@@ -136,6 +137,10 @@ export function FormPrompt({ form, onReply, onCancel, onMinimize }: FormPromptPr
|
||||
onMinimize?.()
|
||||
}
|
||||
|
||||
useShortcutActions({
|
||||
abort: !isMinimized && !expandedCustom ? handleMinimize : undefined,
|
||||
})
|
||||
|
||||
const handleSubmit = async () => {
|
||||
if (!canSubmit) return
|
||||
setIsSubmitting(true)
|
||||
@@ -161,6 +166,7 @@ export function FormPrompt({ form, onReply, onCancel, onMinimize }: FormPromptPr
|
||||
|
||||
useEffect(() => {
|
||||
const handleKeyDown = (e: KeyboardEvent) => {
|
||||
if (e.defaultPrevented) return
|
||||
if (e.key === 'Escape' && !isMinimized && !expandedCustom) {
|
||||
setIsMinimized(true)
|
||||
onMinimize?.()
|
||||
|
||||
@@ -75,7 +75,7 @@ describe('KeyboardShortcuts layout', () => {
|
||||
fireEvent.click(screen.getByRole('button', { name: /Ctrl\+T/ }))
|
||||
const input = screen.getByPlaceholderText('Press keys...')
|
||||
|
||||
fireEvent.keyDown(input, { key: 'o', ctrlKey: true })
|
||||
fireEvent.keyDown(input, { key: 'x', ctrlKey: true })
|
||||
expect(updateSettings).not.toHaveBeenCalled()
|
||||
expect(input).toHaveValue(`${DEFAULT_LEADER_KEY} → `)
|
||||
|
||||
|
||||
@@ -3,8 +3,7 @@ import { useSettings } from '@/hooks/useSettings'
|
||||
import { useMobile } from '@/hooks/useMobile'
|
||||
import { Loader2, X } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { DEFAULT_KEYBOARD_SHORTCUTS, DEFAULT_LEADER_KEY } from '@/api/types/settings'
|
||||
import { formatEventModifiers, formatShortcutEvent, isModifierOnlyEvent, normalizeShortcut, resolveDirectShortcuts } from '@/lib/keyboardShortcuts'
|
||||
import { formatEventModifiers, formatShortcutEvent, isModifierOnlyEvent, normalizeShortcut, resolveShortcutBindings } from '@/lib/keyboardShortcuts'
|
||||
import { applyTuiKeybindImport, parseTuiKeybindConfig } from '@/lib/tuiKeybindImport'
|
||||
import { showToast } from '@/lib/toast'
|
||||
|
||||
@@ -131,14 +130,14 @@ export function KeyboardShortcuts() {
|
||||
const [tempLeaderKey, setTempLeaderKey] = useState<string | null>(null)
|
||||
const [currentKeys, setCurrentKeys] = useState<string>('')
|
||||
|
||||
const leaderKey = tempLeaderKey ?? preferences?.leaderKey ?? DEFAULT_LEADER_KEY
|
||||
const directShortcuts = resolveDirectShortcuts(preferences?.directShortcuts, preferences?.keyboardShortcuts)
|
||||
const bindings = useMemo(() => resolveShortcutBindings(preferences), [preferences])
|
||||
const leaderKey = tempLeaderKey ?? bindings.leaderKey
|
||||
const directShortcuts = bindings.directShortcuts
|
||||
|
||||
const shortcuts = useMemo<Record<string, string>>(() => ({
|
||||
...DEFAULT_KEYBOARD_SHORTCUTS,
|
||||
...preferences?.keyboardShortcuts,
|
||||
...bindings.shortcuts,
|
||||
...tempShortcuts
|
||||
}), [preferences?.keyboardShortcuts, tempShortcuts])
|
||||
}), [bindings.shortcuts, tempShortcuts])
|
||||
|
||||
const shortcutGroups = useMemo(() => buildShortcutGroups(shortcuts), [shortcuts])
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
|
||||
import { useState } from 'react'
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { stubMatchMedia } from '@/test/test-utils'
|
||||
import { BottomSheet, BottomSheetHeader, BottomSheetContent } from './bottom-sheet'
|
||||
@@ -23,6 +24,18 @@ function renderSheet(isOpen: boolean) {
|
||||
)
|
||||
}
|
||||
|
||||
function AutoFocusSheetHost() {
|
||||
const [open, setOpen] = useState(false)
|
||||
return (
|
||||
<>
|
||||
<button type="button" onClick={() => setOpen(true)}>open sheet</button>
|
||||
<BottomSheet isOpen={open} onClose={() => setOpen(false)} ariaLabel="Auto focus sheet">
|
||||
<input aria-label="sheet input" autoFocus />
|
||||
</BottomSheet>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
Reflect.deleteProperty(window, 'matchMedia')
|
||||
})
|
||||
@@ -200,6 +213,49 @@ describe('BottomSheet', () => {
|
||||
|
||||
expect(screen.getByLabelText('prompt')).not.toHaveFocus()
|
||||
})
|
||||
|
||||
it('restores focus to the opener when an autoFocus child takes focus on open', async () => {
|
||||
stubMatchMedia(true)
|
||||
render(<AutoFocusSheetHost />)
|
||||
const opener = screen.getByRole('button', { name: 'open sheet' })
|
||||
opener.focus()
|
||||
|
||||
fireEvent.click(opener)
|
||||
expect(screen.getByLabelText('sheet input')).toHaveFocus()
|
||||
|
||||
fireEvent.keyDown(document, { key: 'Escape' })
|
||||
|
||||
await waitFor(() => expect(opener).toHaveFocus())
|
||||
})
|
||||
|
||||
it('captures the opener when mounted already open and restores it on close', () => {
|
||||
stubMatchMedia(true)
|
||||
const { rerender } = render(
|
||||
<button type="button">opener</button>,
|
||||
)
|
||||
const opener = screen.getByRole('button', { name: 'opener' })
|
||||
opener.focus()
|
||||
|
||||
rerender(
|
||||
<>
|
||||
<button type="button">opener</button>
|
||||
<BottomSheet isOpen onClose={() => {}} ariaLabel="Mounted open sheet">
|
||||
<button type="button">inside</button>
|
||||
</BottomSheet>
|
||||
</>,
|
||||
)
|
||||
|
||||
rerender(
|
||||
<>
|
||||
<button type="button">opener</button>
|
||||
<BottomSheet isOpen={false} onClose={() => {}} ariaLabel="Mounted open sheet">
|
||||
<button type="button">inside</button>
|
||||
</BottomSheet>
|
||||
</>,
|
||||
)
|
||||
|
||||
expect(opener).toHaveFocus()
|
||||
})
|
||||
})
|
||||
|
||||
describe('BottomSheetHeader', () => {
|
||||
|
||||
@@ -3,7 +3,7 @@ import { createPortal } from 'react-dom'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { MODAL_TRANSITION_MS } from '@/lib/utils'
|
||||
import { useSwipeDismiss } from '@/hooks/useMobile'
|
||||
import { getFocusedElement, restoreOverlayFocus } from '@/lib/overlayFocus'
|
||||
import { useRestoreFocusOnClose } from '@/hooks/useRestoreFocusOnClose'
|
||||
|
||||
export interface BottomSheetProps {
|
||||
isOpen: boolean
|
||||
@@ -24,8 +24,8 @@ export function BottomSheet({
|
||||
}: BottomSheetProps) {
|
||||
const [shouldRender, setShouldRender] = useState(false)
|
||||
const panelRef = useRef<HTMLDivElement>(null)
|
||||
const returnFocusRef = useRef<HTMLElement | null>(null)
|
||||
const wasOpenRef = useRef(isOpen)
|
||||
|
||||
useRestoreFocusOnClose(isOpen, panelRef)
|
||||
|
||||
const { bind, swipeStyles } = useSwipeDismiss(onClose, {
|
||||
enabled: isOpen,
|
||||
@@ -45,15 +45,6 @@ export function BottomSheet({
|
||||
}
|
||||
}, [isOpen])
|
||||
|
||||
useEffect(() => {
|
||||
if (isOpen) {
|
||||
returnFocusRef.current = getFocusedElement()
|
||||
} else if (wasOpenRef.current) {
|
||||
restoreOverlayFocus(returnFocusRef.current, panelRef.current)
|
||||
}
|
||||
wasOpenRef.current = isOpen
|
||||
}, [isOpen])
|
||||
|
||||
useEffect(() => {
|
||||
const handleEscape = (e: KeyboardEvent) => {
|
||||
if (e.key === 'Escape' && isOpen) {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
|
||||
import { useState } from 'react'
|
||||
import { describe, it, expect, vi, afterEach } from 'vitest'
|
||||
import { stubMatchMedia } from '@/test/test-utils'
|
||||
import { SideDrawer, SideDrawerHeader, SideDrawerContent } from './side-drawer'
|
||||
@@ -14,6 +15,18 @@ function renderDrawer(isOpen: boolean) {
|
||||
)
|
||||
}
|
||||
|
||||
function AutoFocusDrawerHost() {
|
||||
const [open, setOpen] = useState(false)
|
||||
return (
|
||||
<>
|
||||
<button type="button" onClick={() => setOpen(true)}>open drawer</button>
|
||||
<SideDrawer isOpen={open} onClose={() => setOpen(false)} ariaLabel="Auto focus drawer">
|
||||
<input aria-label="drawer input" autoFocus />
|
||||
</SideDrawer>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
Reflect.deleteProperty(window, 'matchMedia')
|
||||
})
|
||||
@@ -121,6 +134,20 @@ describe('SideDrawer', () => {
|
||||
|
||||
expect(screen.getByLabelText('prompt')).toHaveFocus()
|
||||
})
|
||||
|
||||
it('restores focus to the opener when an autoFocus child takes focus on open', async () => {
|
||||
stubMatchMedia(true)
|
||||
render(<AutoFocusDrawerHost />)
|
||||
const opener = screen.getByRole('button', { name: 'open drawer' })
|
||||
opener.focus()
|
||||
|
||||
fireEvent.click(opener)
|
||||
expect(screen.getByLabelText('drawer input')).toHaveFocus()
|
||||
|
||||
fireEvent.keyDown(document, { key: 'Escape' })
|
||||
|
||||
await waitFor(() => expect(opener).toHaveFocus())
|
||||
})
|
||||
})
|
||||
|
||||
describe('SideDrawerHeader', () => {
|
||||
|
||||
@@ -2,7 +2,7 @@ import { useEffect, useRef, useState } from 'react'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { MODAL_TRANSITION_MS } from '@/lib/utils'
|
||||
import { X } from 'lucide-react'
|
||||
import { getFocusedElement, restoreOverlayFocus } from '@/lib/overlayFocus'
|
||||
import { useRestoreFocusOnClose } from '@/hooks/useRestoreFocusOnClose'
|
||||
|
||||
const openDrawerStack: symbol[] = []
|
||||
|
||||
@@ -27,8 +27,8 @@ export function SideDrawer({
|
||||
}: SideDrawerProps) {
|
||||
const [shouldRender, setShouldRender] = useState(false)
|
||||
const panelRef = useRef<HTMLDivElement>(null)
|
||||
const returnFocusRef = useRef<HTMLElement | null>(null)
|
||||
const wasOpenRef = useRef(isOpen)
|
||||
|
||||
useRestoreFocusOnClose(isOpen, panelRef)
|
||||
|
||||
useEffect(() => {
|
||||
if (isOpen) {
|
||||
@@ -39,15 +39,6 @@ export function SideDrawer({
|
||||
}
|
||||
}, [isOpen])
|
||||
|
||||
useEffect(() => {
|
||||
if (isOpen) {
|
||||
returnFocusRef.current = getFocusedElement()
|
||||
} else if (wasOpenRef.current) {
|
||||
restoreOverlayFocus(returnFocusRef.current, panelRef.current)
|
||||
}
|
||||
wasOpenRef.current = isOpen
|
||||
}, [isOpen])
|
||||
|
||||
const onCloseRef = useRef(onClose)
|
||||
useEffect(() => {
|
||||
onCloseRef.current = onClose
|
||||
|
||||
Reference in new issue
Block a user