feat(ui): app-wide keyboard shortcuts with TUI keybind import

This commit is contained in:
Chris Scott committed 2026-10-08 10:47:52 -04:00
1 parent b18e4f13b3
commit b06de60f6b
38 files changed
+2467 -440

No files matched your search

@@ -54,7 +54,6 @@ export function AgentQuickSelect({
const buttonContent = (
<button
data-toggle-mode
style={styleVars as React.CSSProperties}
className="px-2 md:px-3.5 py-1 h-[36px] rounded-lg text-sm font-medium border min-w-[56px] max-w-[80px] md:max-w-[100px] flex-shrink-0 flex items-center justify-center transition-all duration-200 active:scale-95 hover:scale-105 shadow-md text-[var(--agent-color)] bg-[var(--agent-bg)] border-[var(--agent-border)] hover:bg-[var(--agent-bg-hover)] hover:border-[var(--agent-border-hover)] shadow-[var(--agent-shadow)] hover:shadow-[var(--agent-shadow-hover)]"
>
@@ -422,6 +422,30 @@ describe('PromptInput command submission', () => {
expect(screen.getByTestId('model-quick-select')).toHaveAttribute('data-open', 'true')
})
it('resets bash mode through the imperative clearPrompt', async () => {
const queryClient = createTestQueryClient()
queryClient.setQueryData(['opencode', 'session', 'test-session', '/test'], sessionInfo())
const ref = createRef<PromptInputHandle>()
render(
<QueryClientProvider client={queryClient}>
<PromptInput {...defaultProps} ref={ref} />
</QueryClientProvider>
)
const input = await screen.findByPlaceholderText('Send a message...')
fireEvent.change(input, { target: { value: '!' } })
expect(input).toHaveValue('!')
expect(screen.getByTestId('composer-mode-badge')).toHaveTextContent('BASH')
act(() => {
ref.current?.clearPrompt()
})
expect(input).toHaveValue('')
expect(screen.queryByTestId('composer-mode-badge')).not.toBeInTheDocument()
})
it('keeps attachments and clears only the text when a built-in command is submitted', async () => {
const { container } = renderComponent()
+34 -29
View File
@@ -110,6 +110,8 @@ export interface PromptInputHandle {
clearPrompt: () => void
triggerFileUpload: () => void
openModelPicker: () => void
cycleAgent: () => void
cycleVariant: () => void
}
interface PromptInputProps {
@@ -243,29 +245,6 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
fileInputRef.current?.click()
}, [])
useImperativeHandle(ref, () => ({
setPromptValue: (value: string) => {
setPrompt(value)
textareaRef.current?.focus()
},
clearPrompt: () => {
setPrompt('')
setAttachedFiles(new Map())
revokeBlobUrls(imageAttachments)
setImageAttachments([])
resetVoiceGestureState()
if (isRecording) {
abortRecording()
} else {
clearSTT()
}
textareaRef.current?.focus()
},
triggerFileUpload: openFilePicker,
openModelPicker: () => {
setIsModelPickerOpen(true)
}
}), [imageAttachments, clearSTT, isRecording, abortRecording, resetVoiceGestureState, openFilePicker])
const sessionAgent = useSessionAgent(sessionID, directory)
const currentMode = localMode ?? sessionAgent.agent
const setStoredAgent = useSessionAgentStore((s) => s.setAgent)
@@ -1090,16 +1069,13 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read)
textareaRef.current?.blur()
}
handleSubmit()
} else if (e.key === 'Escape') {
} else if (e.key === 'Escape' && !isSessionActive) {
closeSuggestions()
setPrompt('')
revokeBlobUrls(imageAttachments)
setImageAttachments([])
resetVoiceGestureState()
clearSTT()
} else if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 't') {
e.preventDefault()
handleCycleVariant()
}
}
@@ -1125,13 +1101,13 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read)
updateSuggestionTriggers(value, e.target.selectionStart)
}
const closeSuggestions = () => {
const closeSuggestions = useCallback(() => {
setShowSuggestions(false)
setSuggestionQuery('')
setShowMentionSuggestions(false)
setMentionQuery('')
setMentionRange(null)
}
}, [])
const updateSuggestionTriggers = (value: string, cursorPosition: number) => {
const mentionTrigger = detectMentionTrigger(value, cursorPosition)
@@ -1290,6 +1266,34 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read)
handleAgentChange(next)
}, [agents, currentMode, handleAgentChange])
useImperativeHandle(ref, () => ({
setPromptValue: (value: string) => {
setPrompt(value)
textareaRef.current?.focus()
},
clearPrompt: () => {
setPrompt('')
setAttachedFiles(new Map())
revokeBlobUrls(imageAttachments)
setImageAttachments([])
closeSuggestions()
setIsBashMode(false)
resetVoiceGestureState()
if (isRecording) {
abortRecording()
} else {
clearSTT()
}
textareaRef.current?.focus()
},
triggerFileUpload: openFilePicker,
openModelPicker: () => {
setIsModelPickerOpen(true)
},
cycleAgent: handleCycleAgent,
cycleVariant: handleCycleVariant,
}), [imageAttachments, clearSTT, isRecording, abortRecording, resetVoiceGestureState, closeSuggestions, openFilePicker, handleCycleAgent, handleCycleVariant])
const commandActionsWithPrompt = useMemo<CommandActions>(
() => ({
...commandActions,
@@ -1466,6 +1470,7 @@ return (
)}
<textarea
ref={textareaRef}
data-prompt-input
value={prompt}
onChange={handleInput}
onFocus={handlePromptFocus}
@@ -1,5 +1,5 @@
import { describe, it, expect, vi, beforeAll, beforeEach } from 'vitest'
import { render, screen, within } from '@testing-library/react'
import { describe, it, expect, vi, beforeAll, beforeEach, afterEach } from 'vitest'
import { fireEvent, render, screen, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { ModelQuickSelect } from './ModelQuickSelect'
import { buildModelSections } from '@/lib/modelSections'
@@ -144,6 +144,17 @@ async function openSelector(user: ReturnType<typeof userEvent.setup>) {
return screen.findByRole('dialog', { name: 'Select model' })
}
function focusDetachedTextarea() {
const textarea = document.createElement('textarea')
document.body.appendChild(textarea)
textarea.focus()
return textarea
}
afterEach(() => {
document.querySelectorAll('textarea').forEach((element) => element.remove())
})
beforeAll(() => {
Object.defineProperty(HTMLElement.prototype, 'clientHeight', {
configurable: true,
@@ -371,3 +382,75 @@ describe('ModelQuickSelect more models', () => {
expect(setModel).toHaveBeenCalledWith(selection('anthropic', 'claude-sonnet-4'))
})
})
describe('ModelQuickSelect keyboard navigation', () => {
it('moves the active quick row with ArrowDown and selects it with Enter', () => {
const { setModel } = setModelSelection({ model: selection('opencode-go', 'go-1') })
render(<ModelQuickSelect open />)
const textarea = focusDetachedTextarea()
expect(fireEvent.keyDown(textarea, { key: 'ArrowDown' })).toBe(false)
expect(fireEvent.keyDown(textarea, { key: 'Enter' })).toBe(false)
expect(setModel).toHaveBeenCalledWith(selection('opencode', 'zen-1'))
})
it('clamps at the first quick row and jumps to the last with End', () => {
const { setModel } = setModelSelection({ model: selection('opencode-go', 'go-1') })
render(<ModelQuickSelect open />)
const dialog = screen.getByRole('dialog', { name: 'Select model' })
fireEvent.keyDown(dialog, { key: 'ArrowUp' })
fireEvent.keyDown(dialog, { key: 'Enter' })
expect(setModel).toHaveBeenLastCalledWith(selection('opencode-go', 'go-1'))
setModel.mockClear()
fireEvent.keyDown(dialog, { key: 'End' })
fireEvent.keyDown(dialog, { key: 'Enter' })
expect(setModel).toHaveBeenCalledWith(selection('anthropic', 'claude-sonnet-4'))
})
it('navigates the search results with the arrow keys and Enter', 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...')
await user.type(searchInput, '5')
await screen.findAllByText('Claude Opus 5.5')
expect(fireEvent.keyDown(searchInput, { key: 'ArrowDown' })).toBe(false)
expect(fireEvent.keyDown(searchInput, { key: 'Enter' })).toBe(false)
expect(setModel).toHaveBeenCalledWith(selection('openai', 'gpt-5'))
})
it('does not select a model when Enter is pressed on a row button', () => {
const { setModel } = setModelSelection({ favorite: [selection('anthropic', 'claude-sonnet-4')] })
render(<ModelQuickSelect open />)
const star = screen.getByRole('button', { name: /favorites/ })
star.focus()
fireEvent.keyDown(star, { key: 'Enter' })
expect(setModel).not.toHaveBeenCalled()
})
it('does not intercept arrow keys when the sheet is closed', () => {
render(<ModelQuickSelect />)
const textarea = focusDetachedTextarea()
expect(fireEvent.keyDown(textarea, { key: 'ArrowDown' })).toBe(true)
})
})
@@ -48,12 +48,13 @@ interface ProviderListItem {
interface VirtualizedListProps<T> {
items: T[]
itemHeight: number
renderItem: (item: T) => React.ReactNode
renderItem: (item: T, index: number) => React.ReactNode
getKey: (item: T) => string
emptyLabel: string
className?: string
resetKey?: string
overscan?: number
activeIndex?: number
}
const MODEL_OPTION_ROW_HEIGHT = 60
@@ -76,6 +77,7 @@ function VirtualizedList<T>({
className,
resetKey,
overscan = VIRTUAL_LIST_OVERSCAN,
activeIndex,
}: VirtualizedListProps<T>) {
const scrollRef = useRef<HTMLDivElement>(null)
const [scrollTop, setScrollTop] = useState(0)
@@ -104,6 +106,21 @@ function VirtualizedList<T>({
setScrollTop(0)
}, [resetKey])
useEffect(() => {
if (activeIndex === undefined) return
const element = scrollRef.current
if (!element) return
const rowTop = activeIndex * itemHeight
const rowBottom = rowTop + itemHeight
if (rowTop < element.scrollTop) {
element.scrollTop = rowTop
} else if (rowBottom > element.scrollTop + element.clientHeight) {
element.scrollTop = rowBottom - element.clientHeight
}
setScrollTop(element.scrollTop)
}, [activeIndex, itemHeight])
const visibleRange = useMemo(() => {
if (items.length === 0 || viewportHeight === 0) {
return { start: 0, end: 0 }
@@ -141,7 +158,7 @@ function VirtualizedList<T>({
height: itemHeight,
}}
>
{renderItem(item)}
{renderItem(item, visibleRange.start + index)}
</div>
))}
</div>
@@ -164,6 +181,8 @@ export function ModelQuickSelect({
const [searchQuery, setSearchQuery] = useState('')
const deferredSearchQuery = useDeferredValue(searchQuery)
const [selectedProviderId, setSelectedProviderId] = useState<string | null>(null)
const [activeIndex, setActiveIndex] = useState(0)
const quickListRef = useRef<HTMLDivElement>(null)
const { model, modelString, info, recentModels, favoriteModels, setModel, toggleFavorite, removeRecentModel } = useModelSelection(directory, session)
const { availableVariants, currentVariant, setVariant, clearVariant, hasVariants } = useVariants(directory, session)
@@ -265,12 +284,100 @@ export function ModelQuickSelect({
const browseModels = selectedProviderId ? selectedProviderModels : browseData?.allModels ?? EMPTY_MODELS
const handleModelSelect = (providerID: string, modelID: string) => {
const navigableItems = useMemo((): ModelListItem[] => {
if (showAllModels) {
return isSearching ? searchResults : browseModels
}
return quickSections.flatMap((section) => section.models)
}, [showAllModels, isSearching, searchResults, browseModels, quickSections])
const quickSectionOffsets = useMemo(() => {
const offsets = new Map<string, number>()
let running = 0
for (const section of quickSections) {
offsets.set(section.title, running)
running += section.models.length
}
return offsets
}, [quickSections])
const activeResetKey = `${isOpen}|${showAllModels}|${isSearching ? deferredSearchQuery : ''}|${selectedProviderId ?? ''}`
const navigableItemsRef = useRef(navigableItems)
navigableItemsRef.current = navigableItems
const modelStringRef = useRef(modelString)
modelStringRef.current = modelString
useEffect(() => {
const selectedIndex = navigableItemsRef.current.findIndex((item) => item.key === modelStringRef.current)
setActiveIndex(selectedIndex >= 0 ? selectedIndex : 0)
}, [activeResetKey])
useEffect(() => {
setActiveIndex((current) => {
if (navigableItems.length === 0) return 0
return Math.min(current, navigableItems.length - 1)
})
}, [navigableItems.length])
useEffect(() => {
if (showAllModels) return
const container = quickListRef.current
if (!container) return
const element = container.querySelector<HTMLElement>(`[data-model-index="${activeIndex}"]`)
if (element && typeof element.scrollIntoView === 'function') {
element.scrollIntoView({ block: 'nearest' })
}
}, [activeIndex, showAllModels])
const handleModelSelect = useCallback((providerID: string, modelID: string) => {
setModel({ providerID, modelID })
setShowAllModels(false)
setSearchQuery('')
setSelectedProviderId(null)
}
}, [setModel])
useEffect(() => {
if (!isOpen) return
const handleKeyDown = (event: KeyboardEvent) => {
if (event.ctrlKey || event.metaKey || event.altKey) 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')
if (event.key === 'Enter') {
if (target instanceof HTMLElement && target.closest('button')) return
const item = navigableItems[activeIndex]
if (!item) return
event.preventDefault()
event.stopPropagation()
handleModelSelect(item.providerID, item.modelID)
return
}
let nextIndex: number | null = null
if (event.key === 'ArrowDown') {
nextIndex = Math.min(activeIndex + 1, navigableItems.length - 1)
} else if (event.key === 'ArrowUp') {
nextIndex = Math.max(activeIndex - 1, 0)
} else if (event.key === 'Home' && !isTextInput) {
nextIndex = 0
} else if (event.key === 'End' && !isTextInput) {
nextIndex = navigableItems.length - 1
}
if (nextIndex === null || navigableItems.length === 0) return
event.preventDefault()
event.stopPropagation()
setActiveIndex(nextIndex)
}
document.addEventListener('keydown', handleKeyDown, true)
return () => document.removeEventListener('keydown', handleKeyDown, true)
}, [isOpen, activeIndex, navigableItems, handleModelSelect])
const handleOpenChange = (nextOpen: boolean) => {
if (open === undefined) {
@@ -301,15 +408,19 @@ export function ModelQuickSelect({
const getPrimaryLabel = (item: ModelListItem) => item.displayName || item.modelID
const renderModelOption = (item: ModelListItem) => {
const renderModelOption = (item: ModelListItem, index: number) => {
const isSelected = modelString === item.key
const isFavorite = favoriteKeySet.has(item.key)
const isRecent = recentKeySet.has(item.key)
const isActive = index === activeIndex
return (
<div
key={item.key}
className={`group flex w-full items-center gap-2 rounded-xl py-2 text-left transition-colors hover:bg-accent ${isSelected ? 'bg-highlight/10' : ''}`}
data-model-index={index}
data-active={isActive ? 'true' : undefined}
onMouseMove={() => setActiveIndex(index)}
className={`group flex w-full items-center gap-2 rounded-xl py-2 text-left transition-colors hover:bg-accent ${isSelected ? 'bg-highlight/10' : ''} ${isActive ? 'bg-accent ring-1 ring-border' : ''}`}
>
<button
type="button"
@@ -521,11 +632,12 @@ export function ModelQuickSelect({
<VirtualizedList
items={searchResults}
itemHeight={MODEL_OPTION_ROW_HEIGHT}
renderItem={(item) => renderModelOption(item)}
renderItem={(item, index) => renderModelOption(item, index)}
getKey={(item) => item.key}
emptyLabel="No models found"
className="px-4 pb-4 pt-2"
resetKey={`${selectedProviderId ?? 'all'}:${deferredSearchQuery}`}
activeIndex={activeIndex}
/>
</div>
) : (
@@ -544,11 +656,12 @@ export function ModelQuickSelect({
<VirtualizedList
items={browseModels}
itemHeight={MODEL_OPTION_ROW_HEIGHT}
renderItem={(item) => renderModelOption(item)}
renderItem={(item, index) => renderModelOption(item, index)}
getKey={(item) => item.key}
emptyLabel="No models found"
className="px-4 pb-4 pt-2"
resetKey={selectedProviderId ?? 'all'}
activeIndex={activeIndex}
/>
</div>
@@ -558,7 +671,7 @@ export function ModelQuickSelect({
<VirtualizedList
items={selectedProviderModels}
itemHeight={MODEL_OPTION_ROW_HEIGHT}
renderItem={(item) => renderModelOption(item)}
renderItem={(item, index) => renderModelOption(item, index)}
getKey={(item) => item.key}
emptyLabel="No models found"
className="px-4 pb-4"
@@ -580,7 +693,7 @@ export function ModelQuickSelect({
)
) : (
<div className="flex min-h-0 flex-1 flex-col overflow-hidden pb-safe pt-0">
<div className="min-h-0 flex-1 space-y-4 overflow-y-auto px-4 pb-3">
<div ref={quickListRef} className="min-h-0 flex-1 space-y-4 overflow-y-auto px-4 pb-3">
{quickSections.map(section => (
<section key={section.title}>
<h3 className="mb-1.5 flex items-center gap-1.5 text-xs font-medium text-muted-foreground">
@@ -588,7 +701,7 @@ export function ModelQuickSelect({
{section.title}
</h3>
<div className="space-y-1">
{section.models.map(item => renderModelOption(item))}
{section.models.map((item, index) => renderModelOption(item, (quickSectionOffsets.get(section.title) ?? 0) + index))}
</div>
</section>
))}
@@ -1,8 +1,9 @@
import { describe, expect, it, vi } from 'vitest'
import { describe, expect, it, vi, afterEach } from 'vitest'
import { render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import type { ReactNode } from 'react'
import { MemoryRouter, useLocation } from 'react-router-dom'
import { stubMatchMedia } from '@/test/test-utils'
import { ToolSidePanel } from './ToolSidePanel'
import { useToolPanel } from '@/hooks/useToolPanel'
@@ -43,6 +44,7 @@ function Harness({ docked }: { docked: boolean }) {
const panel = useToolPanel(docked)
return (
<>
<textarea data-prompt-input aria-label="prompt" />
{docked ? (
<ToolSidePanel
panel={panel}
@@ -83,6 +85,10 @@ function HomeHarness() {
)
}
afterEach(() => {
Reflect.deleteProperty(window, 'matchMedia')
})
describe('ToolSidePanel', () => {
it('shows the tool name in a tooltip when hovering a rail icon', async () => {
const user = userEvent.setup()
@@ -229,4 +235,19 @@ describe('ToolSidePanel', () => {
await waitFor(() => expect(search().get('dialog')).toBe('sourceControl'))
expect(search().has('panel')).toBe(false)
})
it('moves focus to the chat prompt when the docked panel closes on desktop', async () => {
stubMatchMedia(true)
const user = userEvent.setup()
renderAt('')
await user.click(screen.getByRole('button', { name: 'Files' }))
const closeButton = await screen.findByRole('button', { name: 'Close panel' })
closeButton.focus()
await user.click(closeButton)
await waitFor(() => expect(search().has('panel')).toBe(false))
expect(screen.getByLabelText('prompt')).toHaveFocus()
})
})
@@ -1,3 +1,4 @@
import { useEffect, useRef } from 'react'
import { X } from 'lucide-react'
import { useLocation } from 'react-router-dom'
import { FileBrowser } from '@/components/file-browser/FileBrowser'
@@ -19,6 +20,7 @@ import { buildToolItems, type MoreDrawerItem } from '@/components/navigation/mor
import { isPanelTool, type ToolPanelState, type PanelTool } from '@/hooks/useToolPanel'
import { useOpenNavItem } from '@/hooks/useOpenNavItem'
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'
import { restoreOverlayFocus } from '@/lib/overlayFocus'
import { cn } from '@/lib/utils'
interface ToolSidePanelProps {
@@ -90,6 +92,19 @@ export function ToolSidePanel({
const { activeTool, toggleTool, closePanel } = panel
const location = useLocation()
const openNavItem = useOpenNavItem()
const railRef = useRef<HTMLElement>(null)
const previousActiveToolRef = useRef(activeTool)
useEffect(() => {
const previousTool = previousActiveToolRef.current
previousActiveToolRef.current = activeTool
if (previousTool === null || activeTool !== null) return
const active = document.activeElement
if (active === null || active === document.body || railRef.current?.contains(active)) {
restoreOverlayFocus(null)
}
}, [activeTool])
const panelTools: Array<{ item: MoreDrawerItem; tool: PanelTool }> = []
const actionItems: MoreDrawerItem[] = []
for (const item of buildToolItems(location.pathname)) {
@@ -182,7 +197,7 @@ export function ToolSidePanel({
) : null}
<TooltipProvider>
<nav aria-label="Tools" className="flex w-11 shrink-0 flex-col items-center gap-1 overflow-y-auto border-l border-border bg-background py-2">
<nav ref={railRef} aria-label="Tools" className="flex w-11 shrink-0 flex-col items-center gap-1 overflow-y-auto border-l border-border bg-background py-2">
{panelTools.map(({ item, tool }) => (
<RailButton key={item.key} item={item} active={tool === activeTool} onClick={() => toggleTool(tool)} />
))}
@@ -1,9 +1,22 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, fireEvent, within } from '@testing-library/react'
import { render, screen, fireEvent, within, waitFor } from '@testing-library/react'
import { KeyboardShortcuts } from './KeyboardShortcuts'
import { DEFAULT_KEYBOARD_SHORTCUTS } from '@/api/types/settings'
import { DEFAULT_DIRECT_SHORTCUTS, DEFAULT_KEYBOARD_SHORTCUTS, DEFAULT_LEADER_KEY } from '@/api/types/settings'
const { updateSettings } = vi.hoisted(() => ({ updateSettings: vi.fn() }))
const { updateSettings, parseTuiKeybindConfig, applyTuiKeybindImport, showToast } = vi.hoisted(() => ({
updateSettings: vi.fn(),
parseTuiKeybindConfig: vi.fn(),
applyTuiKeybindImport: vi.fn(),
showToast: {
success: vi.fn(),
error: vi.fn(),
info: vi.fn(),
warning: vi.fn(),
loading: vi.fn(),
promise: vi.fn(),
dismiss: vi.fn(),
},
}))
vi.mock('@/hooks/useMobile', () => ({ useMobile: () => false }))
vi.mock('@/hooks/useSettings', () => ({
@@ -13,6 +26,20 @@ vi.mock('@/hooks/useSettings', () => ({
updateSettings,
}),
}))
vi.mock('@/lib/tuiKeybindImport', () => ({ parseTuiKeybindConfig, applyTuiKeybindImport }))
vi.mock('@/lib/toast', () => ({ showToast }))
const getFileInput = (container: HTMLElement) => {
const input = container.querySelector('input[type="file"]')
if (!input) throw new Error('file input not found')
return input as HTMLInputElement
}
const makeFile = (content: string, name: string) => {
const file = new File([content], name)
Object.defineProperty(file, 'text', { value: () => Promise.resolve(content) })
return file
}
describe('KeyboardShortcuts layout', () => {
beforeEach(() => vi.clearAllMocks())
@@ -36,17 +63,118 @@ describe('KeyboardShortcuts layout', () => {
expect(screen.getByPlaceholderText('Press keys...')).toBe(input)
expect(input).toHaveFocus()
fireEvent.keyDown(input, { key: 'k', ctrlKey: true })
expect(updateSettings).toHaveBeenCalledWith({ keyboardShortcuts: expect.objectContaining({ customAction: 'Ctrl+K' }) })
expect(updateSettings).toHaveBeenCalledWith({
keyboardShortcuts: expect.objectContaining({ customAction: 'Ctrl+K' }),
directShortcuts: [...DEFAULT_DIRECT_SHORTCUTS, 'customAction'],
})
expect(screen.queryByPlaceholderText('Press keys...')).not.toBeInTheDocument()
})
it('records the leader key followed by a key as a leader shortcut', () => {
render(<KeyboardShortcuts />)
fireEvent.click(screen.getByRole('button', { name: /Ctrl\+T/ }))
const input = screen.getByPlaceholderText('Press keys...')
fireEvent.keyDown(input, { key: 'o', ctrlKey: true })
expect(updateSettings).not.toHaveBeenCalled()
expect(input).toHaveValue(`${DEFAULT_LEADER_KEY} → `)
fireEvent.keyDown(input, { key: 'v' })
expect(updateSettings).toHaveBeenCalledWith({
keyboardShortcuts: expect.objectContaining({ variantCycle: 'V' }),
directShortcuts: DEFAULT_DIRECT_SHORTCUTS.filter((action) => action !== 'variantCycle'),
})
})
it('preserves direct-toggle and clear actions in a grouped row', () => {
render(<KeyboardShortcuts />)
const row = screen.getByText('custom Action').parentElement!.parentElement!
fireEvent.click(within(row).getByRole('button', { name: 'Requires leader key (click to make direct)' }))
expect(updateSettings).toHaveBeenCalledWith({ directShortcuts: ['submit', 'abort', 'customAction'] })
expect(updateSettings).toHaveBeenCalledWith({ directShortcuts: [...DEFAULT_DIRECT_SHORTCUTS, 'customAction'] })
fireEvent.click(within(row).getByTitle('Clear shortcut'))
expect(updateSettings).toHaveBeenCalledWith({ keyboardShortcuts: expect.objectContaining({ customAction: '' }) })
expect(within(row).getByRole('button', { name: 'Not set' })).toBeInTheDocument()
})
})
describe('KeyboardShortcuts TUI import', () => {
beforeEach(() => vi.clearAllMocks())
it('parses the selected file and applies the imported shortcuts once', async () => {
const imported = {
leaderKey: 'Ctrl+Space',
shortcuts: { submit: 'S' },
leaderActions: [],
directActions: [],
skipped: [],
}
parseTuiKeybindConfig.mockReturnValue(imported)
applyTuiKeybindImport.mockReturnValue({
keyboardShortcuts: { submit: 'S' },
directShortcuts: DEFAULT_DIRECT_SHORTCUTS,
leaderKey: 'Ctrl+Space',
cleared: [],
})
const { container } = render(<KeyboardShortcuts />)
fireEvent.change(getFileInput(container), {
target: { files: [makeFile('{"keybinds":{}}', 'cli.json')] },
})
await waitFor(() => expect(updateSettings).toHaveBeenCalledTimes(1))
expect(parseTuiKeybindConfig).toHaveBeenCalledWith('{"keybinds":{}}')
expect(applyTuiKeybindImport).toHaveBeenCalledWith(imported, {
keyboardShortcuts: expect.objectContaining({ customAction: 'Alt+J' }),
directShortcuts: DEFAULT_DIRECT_SHORTCUTS,
})
expect(updateSettings).toHaveBeenCalledWith({
keyboardShortcuts: { submit: 'S' },
directShortcuts: DEFAULT_DIRECT_SHORTCUTS,
leaderKey: 'Ctrl+Space',
})
expect(showToast.success).toHaveBeenCalledWith('Imported 2 shortcuts from cli.json', undefined)
})
it('shows an error and leaves settings untouched when parsing fails', async () => {
parseTuiKeybindConfig.mockImplementation(() => {
throw new Error('Invalid JSONC')
})
const { container } = render(<KeyboardShortcuts />)
fireEvent.change(getFileInput(container), {
target: { files: [makeFile('not jsonc', 'cli.json')] },
})
await waitFor(() =>
expect(showToast.error).toHaveBeenCalledWith('Could not import shortcuts', { description: 'Invalid JSONC' }),
)
expect(updateSettings).not.toHaveBeenCalled()
expect(applyTuiKeybindImport).not.toHaveBeenCalled()
})
it('lists skipped entries in the success toast description', async () => {
const skipped = ['a', 'b', 'c', 'd', 'e', 'f'].map((name) => ({ name, reason: 'unsupported' }))
parseTuiKeybindConfig.mockReturnValue({
shortcuts: { submit: 'S' },
leaderActions: [],
directActions: [],
skipped,
})
applyTuiKeybindImport.mockReturnValue({
keyboardShortcuts: { submit: 'S' },
directShortcuts: DEFAULT_DIRECT_SHORTCUTS,
cleared: ['toggleMode'],
})
const { container } = render(<KeyboardShortcuts />)
fireEvent.change(getFileInput(container), {
target: { files: [makeFile('{}', 'tui.json')] },
})
await waitFor(() => expect(showToast.success).toHaveBeenCalled())
expect(showToast.success).toHaveBeenCalledWith('Imported 1 shortcut from tui.json', {
description:
'Unbound to avoid conflicts: toggle mode. Skipped: a (unsupported), b (unsupported), c (unsupported), d (unsupported), e (unsupported) and 1 more',
})
})
})
@@ -2,19 +2,14 @@ import { useState, useEffect, useMemo, useRef, useCallback } from 'react'
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 { applyTuiKeybindImport, parseTuiKeybindConfig } from '@/lib/tuiKeybindImport'
import { showToast } from '@/lib/toast'
const isMac = navigator.platform.toUpperCase().indexOf('MAC') >= 0
const CMD_KEY = isMac ? 'Cmd' : 'Ctrl'
const normalizeShortcut = (shortcut: string): string => {
return shortcut.replace(/Cmd/g, CMD_KEY)
}
const DEFAULT_DIRECT_SHORTCUTS = ['submit', 'abort']
const CONVERSATION_ACTIONS = ['submit', 'abort', 'toggleMode', 'undo', 'redo', 'compact', 'fork', 'selectModel', 'variantCycle']
const NAVIGATION_ACTIONS = ['settings', 'sessions', 'newSession', 'closeSession', 'toggleSidebar']
const CONVERSATION_ACTIONS = ['submit', 'abort', 'clearPrompt', 'toggleMode', 'undo', 'redo', 'compact', 'fork', 'timeline', 'exportSession', 'selectModel', 'variantCycle']
const NAVIGATION_ACTIONS = ['settings', 'sessions', 'newSession', 'closeSession', 'toggleSidebar', 'toggleTerminal', 'toggleSourceControl']
const formatShortcutLabel = (action: string): string => {
return action.replace(/([A-Z])/g, ' $1').trim()
@@ -25,6 +20,15 @@ interface ShortcutGroup {
actions: string[]
}
const MAX_SKIPPED_IN_TOAST = 5
const buildSkippedDescription = (skipped: Array<{ name: string; reason: string }>): string | undefined => {
if (skipped.length === 0) return undefined
const shown = skipped.slice(0, MAX_SKIPPED_IN_TOAST).map((entry) => `${entry.name} (${entry.reason})`).join(', ')
const remaining = skipped.length - MAX_SKIPPED_IN_TOAST
return remaining > 0 ? `${shown} and ${remaining} more` : shown
}
const buildShortcutGroups = (shortcuts: Record<string, string>): ShortcutGroup[] => {
const knownActions = new Set([...CONVERSATION_ACTIONS, ...NAVIGATION_ACTIONS])
const unknownActions = Object.keys(shortcuts).filter((action) => !knownActions.has(action))
@@ -128,9 +132,9 @@ export function KeyboardShortcuts() {
const [currentKeys, setCurrentKeys] = useState<string>('')
const leaderKey = tempLeaderKey ?? preferences?.leaderKey ?? DEFAULT_LEADER_KEY
const directShortcuts = preferences?.directShortcuts ?? DEFAULT_DIRECT_SHORTCUTS
const directShortcuts = resolveDirectShortcuts(preferences?.directShortcuts, preferences?.keyboardShortcuts)
const shortcuts = useMemo(() => ({
const shortcuts = useMemo<Record<string, string>>(() => ({
...DEFAULT_KEYBOARD_SHORTCUTS,
...preferences?.keyboardShortcuts,
...tempShortcuts
@@ -141,9 +145,17 @@ export function KeyboardShortcuts() {
const shortcutsRef = useRef(shortcuts)
shortcutsRef.current = shortcuts
const leaderKeyRef = useRef(leaderKey)
leaderKeyRef.current = leaderKey
const directShortcutsRef = useRef(directShortcuts)
directShortcutsRef.current = directShortcuts
const updateSettingsRef = useRef(updateSettings)
updateSettingsRef.current = updateSettings
const fileInputRef = useRef<HTMLInputElement>(null)
const startRecording = (action: string) => {
setRecordingKey(action)
setRecordingLeader(false)
@@ -172,64 +184,55 @@ export function KeyboardShortcuts() {
useEffect(() => {
if (!recordingKey && !recordingLeader) return
let leaderPressed = false
const leaderPrefix = () => (leaderPressed ? `${normalizeShortcut(leaderKeyRef.current)} → ` : '')
const handleKeyDown = (e: KeyboardEvent) => {
e.preventDefault()
e.stopPropagation()
const keys = []
if (e.ctrlKey) keys.push('Ctrl')
if (e.metaKey) keys.push('Cmd')
if (e.altKey) keys.push('Alt')
if (e.shiftKey) keys.push('Shift')
const mainKey = e.key
if (!['Control', 'Meta', 'Alt', 'Shift'].includes(mainKey)) {
let displayKey = mainKey
if (mainKey === ' ') displayKey = 'Space'
else if (mainKey === 'ArrowUp') displayKey = 'Up'
else if (mainKey === 'ArrowDown') displayKey = 'Down'
else if (mainKey === 'ArrowLeft') displayKey = 'Left'
else if (mainKey === 'ArrowRight') displayKey = 'Right'
else if (mainKey === 'Enter') displayKey = 'Return'
else if (mainKey === 'Escape') displayKey = 'Esc'
else if (mainKey === 'Tab') displayKey = 'Tab'
else if (mainKey === 'Backspace') displayKey = 'Backspace'
else if (mainKey === 'Delete') displayKey = 'Delete'
else if (mainKey.length === 1) displayKey = mainKey.toUpperCase()
keys.push(displayKey)
if (keys.length > 0) {
const shortcut = keys.join('+')
if (recordingLeader) {
setTempLeaderKey(shortcut)
setRecordingLeader(false)
setCurrentKeys('')
updateSettingsRef.current({ leaderKey: shortcut })
} else if (recordingKey) {
setTempShortcuts(prev => ({ ...prev, [recordingKey]: shortcut }))
setRecordingKey(null)
setCurrentKeys('')
updateSettingsRef.current({
keyboardShortcuts: { ...shortcutsRef.current, [recordingKey]: shortcut }
})
}
}
} else {
setCurrentKeys(keys.join('+'))
const shortcut = formatShortcutEvent(e)
if (!shortcut) {
setCurrentKeys(leaderPrefix() + formatEventModifiers(e))
return
}
if (recordingLeader) {
setTempLeaderKey(shortcut)
setRecordingLeader(false)
setCurrentKeys('')
updateSettingsRef.current({ leaderKey: shortcut })
return
}
if (!recordingKey) return
if (!leaderPressed && shortcut === normalizeShortcut(leaderKeyRef.current)) {
leaderPressed = true
setCurrentKeys(leaderPrefix())
return
}
const otherDirectShortcuts = directShortcutsRef.current.filter((action) => action !== recordingKey)
setTempShortcuts(prev => ({ ...prev, [recordingKey]: shortcut }))
setRecordingKey(null)
setCurrentKeys('')
updateSettingsRef.current({
keyboardShortcuts: { ...shortcutsRef.current, [recordingKey]: shortcut },
directShortcuts: leaderPressed ? otherDirectShortcuts : [...otherDirectShortcuts, recordingKey],
})
}
const handleKeyUp = (e: KeyboardEvent) => {
if (['Control', 'Meta', 'Alt', 'Shift'].includes(e.key)) {
setCurrentKeys('')
if (isModifierOnlyEvent(e)) {
setCurrentKeys(leaderPrefix())
}
}
document.addEventListener('keydown', handleKeyDown)
document.addEventListener('keydown', handleKeyDown, true)
document.addEventListener('keyup', handleKeyUp)
return () => {
document.removeEventListener('keydown', handleKeyDown)
document.removeEventListener('keydown', handleKeyDown, true)
document.removeEventListener('keyup', handleKeyUp)
}
}, [recordingKey, recordingLeader])
@@ -257,6 +260,54 @@ export function KeyboardShortcuts() {
updateSettings({ directShortcuts: newDirectShortcuts })
}
const importFromTui = async (event: React.ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0]
event.target.value = ''
if (!file) return
try {
const imported = parseTuiKeybindConfig(await file.text())
stopRecording()
const applied = applyTuiKeybindImport(imported, {
keyboardShortcuts: shortcutsRef.current,
directShortcuts: directShortcutsRef.current,
})
const importedCount = Object.keys(imported.shortcuts).length + (applied.leaderKey ? 1 : 0)
const skippedDescription = buildSkippedDescription(imported.skipped)
if (importedCount === 0) {
showToast.info(
`No matching shortcuts found in ${file.name}`,
skippedDescription ? { description: skippedDescription } : undefined,
)
return
}
updateSettingsRef.current({
keyboardShortcuts: applied.keyboardShortcuts,
directShortcuts: applied.directShortcuts,
...(applied.leaderKey ? { leaderKey: applied.leaderKey } : {}),
})
setTempShortcuts(applied.keyboardShortcuts)
if (applied.leaderKey !== undefined) {
setTempLeaderKey(applied.leaderKey)
}
const description = [
applied.cleared.length > 0 ? `Unbound to avoid conflicts: ${applied.cleared.map((action) => formatShortcutLabel(action).toLowerCase()).join(', ')}` : undefined,
skippedDescription ? `Skipped: ${skippedDescription}` : undefined,
].filter(Boolean).join('. ')
showToast.success(
`Imported ${importedCount} shortcut${importedCount === 1 ? '' : 's'} from ${file.name}`,
description ? { description } : undefined,
)
} catch (error) {
showToast.error('Could not import shortcuts', {
description: error instanceof Error ? error.message : 'Unknown error',
})
}
}
if (isMobile) {
return (
<div className="bg-card border border-border rounded-lg p-6">
@@ -270,7 +321,25 @@ export function KeyboardShortcuts() {
return (
<div className="bg-card border border-border rounded-lg p-6">
<h2 className="text-lg font-semibold text-foreground mb-6">Keyboard Shortcuts</h2>
<div className="mb-6 flex flex-wrap items-start justify-between gap-3">
<h2 className="text-lg font-semibold text-foreground">Keyboard Shortcuts</h2>
<div className="flex flex-col items-end gap-1">
<Button variant="outline" size="sm" onClick={() => fileInputRef.current?.click()}>
Import from OpenCode TUI
</Button>
<input
ref={fileInputRef}
type="file"
accept=".json,.jsonc,application/json"
className="hidden"
onChange={importFromTui}
/>
<p className="text-xs text-muted-foreground text-right">
Select your OpenCode cli.json (or legacy tui.json), usually in ~/.config/opencode.
</p>
</div>
</div>
<div className="flex flex-wrap items-center justify-between gap-2 py-3 border-b border-border">
<div className="flex min-w-0 flex-wrap items-baseline gap-x-2">
@@ -316,7 +385,7 @@ export function KeyboardShortcuts() {
</div>
<p className="mt-6 text-sm text-muted-foreground">
Click on any shortcut to record a new key combination. Click on the status text below each action to toggle whether it requires the leader key.
Click on any shortcut to record a new key combination. Press the leader key first to record a leader shortcut, or press a combination directly to record a direct one. Click on the status text below each action to toggle whether it requires the leader key.
</p>
</div>
)
@@ -1,5 +1,6 @@
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { stubMatchMedia } from '@/test/test-utils'
import { BottomSheet, BottomSheetHeader, BottomSheetContent } from './bottom-sheet'
import { useSwipeDismiss } from '@/hooks/useMobile'
@@ -11,6 +12,21 @@ vi.mock('@/hooks/useMobile', () => ({
})),
}))
function renderSheet(isOpen: boolean) {
return render(
<>
<textarea data-prompt-input aria-label="prompt" />
<BottomSheet isOpen={isOpen} onClose={() => {}} ariaLabel="Test sheet">
<button type="button">inside</button>
</BottomSheet>
</>,
)
}
afterEach(() => {
Reflect.deleteProperty(window, 'matchMedia')
})
describe('BottomSheet', () => {
beforeEach(() => {
vi.clearAllMocks()
@@ -132,6 +148,58 @@ describe('BottomSheet', () => {
expect(mockBind).toHaveBeenCalled()
})
it('moves focus to the chat prompt on desktop when it closes', () => {
stubMatchMedia(true)
const { rerender } = renderSheet(false)
rerender(
<>
<textarea data-prompt-input aria-label="prompt" />
<BottomSheet isOpen onClose={() => {}} ariaLabel="Test sheet">
<button type="button">inside</button>
</BottomSheet>
</>,
)
screen.getByRole('button', { name: 'inside' }).focus()
rerender(
<>
<textarea data-prompt-input aria-label="prompt" />
<BottomSheet isOpen={false} onClose={() => {}} ariaLabel="Test sheet">
<button type="button">inside</button>
</BottomSheet>
</>,
)
expect(screen.getByLabelText('prompt')).toHaveFocus()
})
it('does not refocus the chat prompt on touch when it closes', () => {
stubMatchMedia(false)
const { rerender } = renderSheet(false)
rerender(
<>
<textarea data-prompt-input aria-label="prompt" />
<BottomSheet isOpen onClose={() => {}} ariaLabel="Test sheet">
<button type="button">inside</button>
</BottomSheet>
</>,
)
screen.getByRole('button', { name: 'inside' }).focus()
rerender(
<>
<textarea data-prompt-input aria-label="prompt" />
<BottomSheet isOpen={false} onClose={() => {}} ariaLabel="Test sheet">
<button type="button">inside</button>
</BottomSheet>
</>,
)
expect(screen.getByLabelText('prompt')).not.toHaveFocus()
})
})
describe('BottomSheetHeader', () => {
@@ -3,6 +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'
export interface BottomSheetProps {
isOpen: boolean
@@ -23,6 +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)
const { bind, swipeStyles } = useSwipeDismiss(onClose, {
enabled: isOpen,
@@ -42,6 +45,15 @@ 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) {
@@ -86,6 +98,7 @@ export function BottomSheet({
role="dialog"
aria-modal="true"
aria-label={ariaLabel}
data-state={isOpen ? 'open' : 'closed'}
style={swipeStyles}
>
<div className="w-full flex justify-center pt-3 pb-2">
@@ -441,6 +441,22 @@ function ReturnFocusHost({ onCloseAutoFocus }: { onCloseAutoFocus?: (event: Even
)
}
function PromptReturnFocusHost() {
const [open, setOpen] = useState(false)
return (
<>
<textarea data-prompt-input aria-label="chat prompt" />
<button type="button" onClick={() => setOpen(true)}>open prompt dialog</button>
<Dialog open={open} onOpenChange={setOpen}>
<DialogContent>
<DialogTitle>Prompt Focus Dialog</DialogTitle>
<input aria-label="prompt dialog input" autoFocus />
</DialogContent>
</Dialog>
</>
)
}
async function openAndEscape(returnTarget: HTMLElement) {
returnTarget.focus()
fireEvent.click(screen.getByText('open'))
@@ -495,6 +511,22 @@ describe('Dialog return focus', () => {
expect(prompt).not.toHaveFocus()
})
it('moves focus to the chat prompt when the dialog closes on desktop', async () => {
stubMatchMedia(true)
render(<PromptReturnFocusHost />)
const opener = screen.getByText('open prompt dialog')
opener.focus()
fireEvent.click(opener)
const input = await screen.findByLabelText('prompt dialog input')
await waitFor(() => expect(input).toHaveFocus())
fireEvent.keyDown(input, { key: 'Escape' })
await waitFor(() => expect(screen.queryByLabelText('prompt dialog input')).not.toBeInTheDocument())
await act(() => new Promise((resolve) => setTimeout(resolve, 0)))
expect(screen.getByLabelText('chat prompt')).toHaveFocus()
})
})
function stubVisualViewport(height: number) {
+5 -16
View File
@@ -5,23 +5,11 @@ import { X } from "lucide-react"
import { cn } from "@/lib/utils"
import { useSwipeBack } from '@/hooks/useMobile'
import { useVisualViewport } from '@/hooks/useVisualViewport'
import { FINE_POINTER_MEDIA_QUERY } from '@/hooks/useMediaQuery'
import { getFocusedElement, restoreOverlayFocus } from '@/lib/overlayFocus'
const DialogOpenContext = React.createContext<boolean>(true)
const DialogReturnFocusContext = React.createContext<HTMLElement | null>(null)
function getFocusedElement(): HTMLElement | null {
return typeof document !== 'undefined' && document.activeElement instanceof HTMLElement
? document.activeElement
: null
}
function canRestoreFocus(element: HTMLElement): boolean {
if (!element.isConnected || element === document.body) return false
if (!element.matches('input, textarea, [contenteditable="true"]')) return true
return typeof window.matchMedia === 'function' && window.matchMedia(FINE_POINTER_MEDIA_QUERY).matches
}
function Dialog({ open, ...props }: React.ComponentProps<typeof DialogPrimitive.Root>) {
const [openState, setOpenState] = React.useState(() => ({
open,
@@ -83,9 +71,10 @@ const DialogContent = React.forwardRef<
const returnFocus = React.useContext(DialogReturnFocusContext)
const handleCloseAutoFocus = (event: Event) => {
onCloseAutoFocus?.(event)
if (event.defaultPrevented || !returnFocus || !canRestoreFocus(returnFocus)) return
event.preventDefault()
returnFocus.focus()
if (event.defaultPrevented) return
if (restoreOverlayFocus(returnFocus, event.currentTarget as Element | null)) {
event.preventDefault()
}
}
const handleEscapeKeyDown = (event: KeyboardEvent) => {
onEscapeKeyDown?.(event)
@@ -1,7 +1,23 @@
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
import { describe, it, expect, vi } from 'vitest'
import { describe, it, expect, vi, afterEach } from 'vitest'
import { stubMatchMedia } from '@/test/test-utils'
import { SideDrawer, SideDrawerHeader, SideDrawerContent } from './side-drawer'
function renderDrawer(isOpen: boolean) {
return render(
<>
<textarea data-prompt-input aria-label="prompt" />
<SideDrawer isOpen={isOpen} onClose={() => {}} ariaLabel="Test drawer">
<button type="button">inside</button>
</SideDrawer>
</>,
)
}
afterEach(() => {
Reflect.deleteProperty(window, 'matchMedia')
})
describe('SideDrawer', () => {
it('renders when isOpen is true', () => {
render(
@@ -79,6 +95,32 @@ describe('SideDrawer', () => {
expect(closeInner).toHaveBeenCalledTimes(1)
expect(closeOuter).not.toHaveBeenCalled()
})
it('moves focus to the chat prompt on desktop when it closes', () => {
stubMatchMedia(true)
const { rerender } = renderDrawer(false)
rerender(
<>
<textarea data-prompt-input aria-label="prompt" />
<SideDrawer isOpen onClose={() => {}} ariaLabel="Test drawer">
<button type="button">inside</button>
</SideDrawer>
</>,
)
screen.getByRole('button', { name: 'inside' }).focus()
rerender(
<>
<textarea data-prompt-input aria-label="prompt" />
<SideDrawer isOpen={false} onClose={() => {}} ariaLabel="Test drawer">
<button type="button">inside</button>
</SideDrawer>
</>,
)
expect(screen.getByLabelText('prompt')).toHaveFocus()
})
})
describe('SideDrawerHeader', () => {
@@ -2,6 +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'
const openDrawerStack: symbol[] = []
@@ -25,6 +26,9 @@ export function SideDrawer({
ariaLabel,
}: SideDrawerProps) {
const [shouldRender, setShouldRender] = useState(false)
const panelRef = useRef<HTMLDivElement>(null)
const returnFocusRef = useRef<HTMLElement | null>(null)
const wasOpenRef = useRef(isOpen)
useEffect(() => {
if (isOpen) {
@@ -35,6 +39,15 @@ 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
@@ -81,6 +94,7 @@ export function SideDrawer({
aria-hidden="true"
/>
<div
ref={panelRef}
className={cn(
'fixed top-0 bottom-0 bg-background border-l border-border pt-safe flex flex-col z-50',
side === 'right' ? 'right-0' : 'left-0',
@@ -90,6 +104,7 @@ export function SideDrawer({
role="dialog"
aria-modal="true"
aria-label={ariaLabel}
data-state={isOpen ? 'open' : 'closed'}
>
{children}
</div>