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

+25 -15
View File
@@ -24,6 +24,7 @@ import { useMobileTabBar } from '@/hooks/useMobileTabBar'
import { TTSProvider } from './contexts/TTSContext'
import { ThemeProvider, useThemeMode } from './contexts/ThemeContext'
import { AuthProvider } from './contexts/AuthContext'
import { KeyboardShortcutsProvider } from './contexts/KeyboardShortcutsContext'
import { EventProvider, usePermissions, useEventContext } from '@/contexts/EventContext'
import { SwipeNavigationProvider, useSwipeNavigation } from '@/contexts/SwipeNavigationContext'
import { PermissionRequestDialog } from './components/session/PermissionRequestDialog'
@@ -34,6 +35,7 @@ import { onNotificationClick } from '@/lib/serviceWorker'
import { useAuth } from '@/hooks/useAuth'
import { useOpenCodeFailureToast } from '@/hooks/useOpenCodeFailureToast'
import { useOpenCodeServerActions } from '@/hooks/useOpenCodeServerActions'
import { useGlobalShortcutActions } from '@/hooks/useGlobalShortcutActions'
import { RestartServerDialog } from '@/components/settings/RestartServerDialog'
const queryClient = new QueryClient({
@@ -116,6 +118,11 @@ function PermissionDialogWrapper() {
)
}
function GlobalShortcuts() {
useGlobalShortcutActions()
return null
}
function AppShell() {
const navigate = useNavigate()
const location = useLocation()
@@ -188,21 +195,24 @@ function AppShell() {
<ThemeProvider>
<AuthProvider>
<EventProvider>
<div ref={rootRef} className="flex h-dvh w-full min-w-0">
<DesktopSidebar />
<main className="flex-1 min-w-0 min-h-0 flex flex-col">
<Outlet />
</main>
</div>
<MobileTabBar />
<MobileSheetHost />
<PermissionDialogWrapper />
<SSHHostKeyDialogWrapper />
<SettingsDialog />
<HealthMonitor />
<VersionNotifier />
<PwaUpdatePrompt />
<ThemedToaster />
<KeyboardShortcutsProvider>
<GlobalShortcuts />
<div ref={rootRef} className="flex h-dvh w-full min-w-0">
<DesktopSidebar />
<main className="flex-1 min-w-0 min-h-0 flex flex-col">
<Outlet />
</main>
</div>
<MobileTabBar />
<MobileSheetHost />
<PermissionDialogWrapper />
<SSHHostKeyDialogWrapper />
<SettingsDialog />
<HealthMonitor />
<VersionNotifier />
<PwaUpdatePrompt />
<ThemedToaster />
</KeyboardShortcutsProvider>
</EventProvider>
</AuthProvider>
</ThemeProvider>
+3 -2
View File
@@ -4,6 +4,7 @@ import {
DEFAULT_KEYBOARD_SHORTCUTS,
DEFAULT_USER_PREFERENCES,
DEFAULT_LEADER_KEY,
DEFAULT_DIRECT_SHORTCUTS,
BLOCKED_SERVER_ENV_KEYS,
selectPreferredOpenCodeConfigSourceName,
type TTSConfig,
@@ -27,8 +28,8 @@ import type { NotificationPreferences } from '@opencode-manager/shared/types'
import { saveFile } from '@/lib/download'
export type { TTSConfig, STTConfig, OpenCodeConfigFile, OpenCodeConfigSourceFile, OpenCodeConfigSourceName, UpdateOpenCodeConfigRequest, ModelConfig, ProviderConfig, SandboxPreferences, NotificationPreferences, SkillFileInfo, CreateSkillRequest, UpdateSkillRequest, SkillScope, InstallSkillFromGithubRequest, InstallSkillResponse }
export type { UserPreferences, UpdateSettingsRequest, CustomCommand, GitCredential, GitIdentity, GitIdentityProfile } from '@opencode-manager/shared'
export { DEFAULT_TTS_CONFIG, DEFAULT_STT_CONFIG, DEFAULT_KEYBOARD_SHORTCUTS, DEFAULT_USER_PREFERENCES, DEFAULT_LEADER_KEY, BLOCKED_SERVER_ENV_KEYS }
export type { UserPreferences, UpdateSettingsRequest, CustomCommand, GitCredential, GitIdentity, GitIdentityProfile, KeyboardShortcutAction } from '@opencode-manager/shared'
export { DEFAULT_TTS_CONFIG, DEFAULT_STT_CONFIG, DEFAULT_KEYBOARD_SHORTCUTS, DEFAULT_USER_PREFERENCES, DEFAULT_LEADER_KEY, DEFAULT_DIRECT_SHORTCUTS, BLOCKED_SERVER_ENV_KEYS }
export { isOpenCodeConfigSourceName } from '@opencode-manager/shared'
export function getOpenCodeConfigSources(config: OpenCodeConfigFile): OpenCodeConfigSourceFile[] {
@@ -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>
@@ -0,0 +1,302 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { act, render, renderHook, screen } from '@testing-library/react'
import type { ReactNode } from 'react'
import { KeyboardShortcutsProvider, useShortcutActions, type ShortcutActions } from './KeyboardShortcutsContext'
const { preferences } = vi.hoisted(() => ({
preferences: {
leaderKey: 'Ctrl+O',
keyboardShortcuts: { submit: 'Ctrl+Enter', abort: 'Escape', newSession: 'N' } as Record<string, string>,
directShortcuts: ['submit', 'abort'],
},
}))
vi.mock('@/hooks/useSettings', () => ({
useSettings: () => ({ preferences }),
}))
function pressKey(target: Element, init: KeyboardEventInit) {
const event = new KeyboardEvent('keydown', { bubbles: true, cancelable: true, ...init })
act(() => {
target.dispatchEvent(event)
})
return event
}
function mountElement<K extends keyof HTMLElementTagNameMap>(tag: K, attributes: Record<string, string> = {}) {
const element = document.createElement(tag)
for (const [name, value] of Object.entries(attributes)) element.setAttribute(name, value)
return document.body.appendChild(element)
}
function ActionLayer({ actions, scope = 'page' }: { actions: ShortcutActions; scope?: 'global' | 'page' }) {
useShortcutActions(actions, scope)
return null
}
function ConditionalLayer({ show, actions }: { show: boolean; actions: ShortcutActions }) {
if (!show) return null
return <ActionLayer actions={actions} />
}
function renderProvider(children: ReactNode) {
return render(<KeyboardShortcutsProvider>{children}</KeyboardShortcutsProvider>)
}
describe('KeyboardShortcutsProvider', () => {
afterEach(() => {
document.body.innerHTML = ''
})
it('matches stored Enter and Escape bindings against Return and Esc key events', () => {
const submit = vi.fn()
const abort = vi.fn()
renderProvider(<ActionLayer actions={{ submit, abort }} />)
const prompt = mountElement('textarea', { 'data-prompt-input': '' })
pressKey(prompt, { key: 'Enter', ctrlKey: true })
pressKey(document.body, { key: 'Escape' })
expect(submit).toHaveBeenCalledTimes(1)
expect(abort).toHaveBeenCalledTimes(1)
})
it('activates the leader from the prompt and runs the follow-up action without typing it', () => {
const newSession = vi.fn()
renderProvider(<ActionLayer actions={{ newSession }} />)
const prompt = mountElement('textarea', { 'data-prompt-input': '' })
expect(pressKey(prompt, { key: 'o', ctrlKey: true }).defaultPrevented).toBe(true)
const followUp = pressKey(prompt, { key: 'n' })
expect(newSession).toHaveBeenCalledTimes(1)
expect(followUp.defaultPrevented).toBe(true)
})
it('applies new default actions as direct shortcuts for users with legacy stored preferences', () => {
const toggleTerminal = vi.fn()
renderProvider(<ActionLayer actions={{ toggleTerminal }} />)
const input = mountElement('textarea')
pressKey(input, { key: '`', ctrlKey: true })
expect(toggleTerminal).toHaveBeenCalledTimes(1)
})
it('leaves submit to the focused input and only interrupts from the prompt', () => {
const submit = vi.fn()
const abort = vi.fn()
renderProvider(<ActionLayer actions={{ submit, abort }} />)
const otherInput = mountElement('input')
const prompt = mountElement('textarea', { 'data-prompt-input': '' })
pressKey(otherInput, { key: 'Enter', ctrlKey: true })
pressKey(otherInput, { key: 'Escape' })
expect(submit).not.toHaveBeenCalled()
expect(abort).not.toHaveBeenCalled()
pressKey(prompt, { key: 'Escape' })
expect(abort).toHaveBeenCalledTimes(1)
})
it('submits from the prompt on plain Enter when submit is bound to Enter, leaving Enter alone elsewhere', () => {
const original = preferences.keyboardShortcuts
preferences.keyboardShortcuts = { ...original, submit: 'Return' }
try {
const submit = vi.fn()
renderProvider(<ActionLayer actions={{ submit }} />)
const prompt = mountElement('textarea', { 'data-prompt-input': '' })
const button = mountElement('button')
expect(pressKey(prompt, { key: 'Enter' }).defaultPrevented).toBe(true)
expect(submit).toHaveBeenCalledTimes(1)
expect(pressKey(prompt, { key: 'Enter', shiftKey: true }).defaultPrevented).toBe(false)
expect(pressKey(prompt, { key: 'Enter', isComposing: true }).defaultPrevented).toBe(false)
expect(pressKey(button, { key: 'Enter' }).defaultPrevented).toBe(false)
expect(pressKey(document.body, { key: 'Enter' }).defaultPrevented).toBe(false)
expect(submit).toHaveBeenCalledTimes(1)
} finally {
preferences.keyboardShortcuts = original
}
})
it('cycles the agent with a direct Tab only from the prompt, keeping Tab for focus elsewhere', () => {
const original = { keyboardShortcuts: preferences.keyboardShortcuts, directShortcuts: preferences.directShortcuts }
preferences.keyboardShortcuts = { ...original.keyboardShortcuts, toggleMode: 'Tab' }
preferences.directShortcuts = ['submit', 'abort', 'toggleMode']
try {
const toggleMode = vi.fn()
renderProvider(<ActionLayer actions={{ toggleMode }} />)
const prompt = mountElement('textarea', { 'data-prompt-input': '' })
const button = mountElement('button')
const otherInput = mountElement('input')
expect(pressKey(button, { key: 'Tab' }).defaultPrevented).toBe(false)
expect(pressKey(document.body, { key: 'Tab' }).defaultPrevented).toBe(false)
expect(pressKey(otherInput, { key: 'Tab' }).defaultPrevented).toBe(false)
expect(toggleMode).not.toHaveBeenCalled()
expect(pressKey(prompt, { key: 'Tab' }).defaultPrevented).toBe(true)
expect(toggleMode).toHaveBeenCalledTimes(1)
} finally {
preferences.keyboardShortcuts = original.keyboardShortcuts
preferences.directShortcuts = original.directShortcuts
}
})
it('never runs a prompt-only shortcut on a key that types a character', () => {
const original = { keyboardShortcuts: preferences.keyboardShortcuts, directShortcuts: preferences.directShortcuts }
preferences.keyboardShortcuts = { ...original.keyboardShortcuts, toggleMode: 'T' }
preferences.directShortcuts = ['submit', 'abort', 'toggleMode']
try {
const toggleMode = vi.fn()
renderProvider(<ActionLayer actions={{ toggleMode }} />)
const prompt = mountElement('textarea', { 'data-prompt-input': '' })
expect(pressKey(prompt, { key: 't' }).defaultPrevented).toBe(false)
expect(toggleMode).not.toHaveBeenCalled()
} finally {
preferences.keyboardShortcuts = original.keyboardShortcuts
preferences.directShortcuts = original.directShortcuts
}
})
it('clears the prompt with a direct Ctrl+C only from the prompt', () => {
const original = { keyboardShortcuts: preferences.keyboardShortcuts, directShortcuts: preferences.directShortcuts }
preferences.keyboardShortcuts = { ...original.keyboardShortcuts, clearPrompt: 'Ctrl+C' }
preferences.directShortcuts = ['submit', 'abort', 'clearPrompt']
try {
const clearPrompt = vi.fn()
renderProvider(<ActionLayer actions={{ clearPrompt }} />)
const prompt = mountElement('textarea', { 'data-prompt-input': '' })
const otherInput = mountElement('textarea')
const button = mountElement('button')
expect(pressKey(otherInput, { key: 'c', ctrlKey: true }).defaultPrevented).toBe(false)
expect(pressKey(button, { key: 'c', ctrlKey: true }).defaultPrevented).toBe(false)
expect(pressKey(document.body, { key: 'c', ctrlKey: true }).defaultPrevented).toBe(false)
expect(clearPrompt).not.toHaveBeenCalled()
expect(pressKey(prompt, { key: 'c', ctrlKey: true }).defaultPrevented).toBe(true)
expect(clearPrompt).toHaveBeenCalledTimes(1)
} finally {
preferences.keyboardShortcuts = original.keyboardShortcuts
preferences.directShortcuts = original.directShortcuts
}
})
it('runs leader and direct shortcuts from a terminal before it consumes the keys, passing other keys through', () => {
const newSession = vi.fn()
const toggleTerminal = vi.fn()
renderProvider(<ActionLayer actions={{ newSession, toggleTerminal }} />)
const terminal = mountElement('div', { 'data-terminal-id': 'pty-1' })
const terminalInput = terminal.appendChild(document.createElement('textarea'))
const shellInput = vi.fn()
terminalInput.addEventListener('keydown', (event) => {
shellInput(event.key)
event.preventDefault()
})
pressKey(terminalInput, { key: 'o', ctrlKey: true })
pressKey(terminalInput, { key: 'n' })
pressKey(terminalInput, { key: '`', ctrlKey: true })
pressKey(terminalInput, { key: 'l' })
expect(newSession).toHaveBeenCalledTimes(1)
expect(toggleTerminal).toHaveBeenCalledTimes(1)
expect(shellInput.mock.calls).toEqual([['l']])
})
it('ignores key events a component already handled', () => {
const abort = vi.fn()
renderProvider(<ActionLayer actions={{ abort }} />)
const element = mountElement('div')
element.addEventListener('keydown', (event) => event.preventDefault())
pressKey(element, { key: 'Escape' })
expect(abort).not.toHaveBeenCalled()
})
it('does not swallow a key whose action has no handler', () => {
renderProvider(<ActionLayer actions={{ abort: undefined }} />)
expect(pressKey(document.body, { key: 'Escape' }).defaultPrevented).toBe(false)
})
it('prefers a page layer over a global layer for the same action', () => {
const globalAbort = vi.fn()
const pageAbort = vi.fn()
renderProvider(
<>
<ActionLayer actions={{ abort: globalAbort }} scope="global" />
<ActionLayer actions={{ abort: pageAbort }} scope="page" />
</>
)
pressKey(document.body, { key: 'Escape' })
expect(pageAbort).toHaveBeenCalledTimes(1)
expect(globalAbort).not.toHaveBeenCalled()
})
it('falls through to the global handler when a page layer leaves the action undefined', () => {
const globalAbort = vi.fn()
renderProvider(
<>
<ActionLayer actions={{ abort: globalAbort }} scope="global" />
<ActionLayer actions={{ abort: undefined }} scope="page" />
</>
)
pressKey(document.body, { key: 'Escape' })
expect(globalAbort).toHaveBeenCalledTimes(1)
})
it('restores the global handler when a page layer unmounts', () => {
const globalAbort = vi.fn()
const pageAbort = vi.fn()
const view = renderProvider(
<>
<ActionLayer actions={{ abort: globalAbort }} scope="global" />
<ConditionalLayer show actions={{ abort: pageAbort }} />
</>
)
pressKey(document.body, { key: 'Escape' })
expect(pageAbort).toHaveBeenCalledTimes(1)
expect(globalAbort).not.toHaveBeenCalled()
view.rerender(
<KeyboardShortcutsProvider>
<ActionLayer actions={{ abort: globalAbort }} scope="global" />
<ConditionalLayer show={false} actions={{ abort: pageAbort }} />
</KeyboardShortcutsProvider>
)
pressKey(document.body, { key: 'Escape' })
expect(globalAbort).toHaveBeenCalledTimes(1)
})
it('shows the leader indicator after the leader key and hides it after the follow-up key', () => {
const newSession = vi.fn()
renderProvider(<ActionLayer actions={{ newSession }} />)
pressKey(document.body, { key: 'o', ctrlKey: true })
expect(screen.getByText('Waiting for shortcut key...')).toBeInTheDocument()
pressKey(document.body, { key: 'n' })
expect(screen.queryByText('Waiting for shortcut key...')).not.toBeInTheDocument()
expect(newSession).toHaveBeenCalledTimes(1)
})
it('throws when used outside the provider', () => {
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {})
expect(() => renderHook(() => useShortcutActions({ abort: vi.fn() }))).toThrow(
'useShortcutActions must be used within a KeyboardShortcutsProvider'
)
consoleError.mockRestore()
})
})
@@ -0,0 +1,177 @@
/* eslint-disable react-refresh/only-export-components */
import { createContext, useCallback, useContext, useEffect, useRef, useState, type ReactNode } from 'react'
import { useSettings } from '@/hooks/useSettings'
import type { KeyboardShortcutAction } from '@/api/types/settings'
import { findShortcutAction, formatShortcutEvent, hasCommandModifier, resolveShortcutBindings } from '@/lib/keyboardShortcuts'
const LEADER_TIMEOUT = 2000
export type ShortcutActions = Partial<Record<KeyboardShortcutAction, () => void>>
interface ShortcutLayer {
actionsRef: { current: ShortcutActions }
}
interface ShortcutRegistry {
global: ShortcutLayer[]
page: ShortcutLayer[]
}
const KeyboardShortcutsRegistryContext = createContext<ShortcutRegistry | null>(null)
function isTextInput(target: HTMLElement): boolean {
return target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable
}
const PROMPT_ONLY_DIRECT_ACTIONS: ReadonlySet<string> = new Set(['toggleMode', 'clearPrompt'])
function isPromptInput(target: HTMLElement): boolean {
return target.hasAttribute('data-prompt-input')
}
function typesCharacter(shortcut: string): boolean {
return !hasCommandModifier(shortcut) && /(^|\+).$/.test(shortcut)
}
/**
* Whether a direct shortcut may run for this focus target. Prompt-only actions (agent cycling, prompt clearing) run only
* from the prompt and never on a key that types a character. `submit` runs only from the prompt, so a submit bound to
* plain Enter sends the prompt without hijacking Enter on buttons or other fields; `abort` runs from the prompt or with
* no text field focused; other text inputs only accept modified shortcuts.
*/
function isDirectActionAllowed(action: string, shortcut: string, target: HTMLElement): boolean {
if (PROMPT_ONLY_DIRECT_ACTIONS.has(action)) return isPromptInput(target) && !typesCharacter(shortcut)
if (action === 'submit') return isPromptInput(target)
if (!isTextInput(target)) return true
if (action === 'abort') return isPromptInput(target)
return hasCommandModifier(shortcut)
}
function isTerminalTarget(target: EventTarget | null): boolean {
return target instanceof Element && target.closest('[data-terminal-id]') !== null
}
function findLayerHandler(layers: ShortcutLayer[], action: string): (() => void) | undefined {
for (let index = layers.length - 1; index >= 0; index -= 1) {
const handler = layers[index].actionsRef.current[action as KeyboardShortcutAction]
if (handler) return handler
}
return undefined
}
function findHandler(registry: ShortcutRegistry, action: string): (() => void) | undefined {
return findLayerHandler(registry.page, action) ?? findLayerHandler(registry.global, action)
}
export function KeyboardShortcutsProvider({ children }: { children: ReactNode }) {
const { preferences } = useSettings()
const [leaderActive, setLeaderActive] = useState(false)
const leaderActiveRef = useRef(false)
const leaderTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null)
const preferencesRef = useRef(preferences)
preferencesRef.current = preferences
const registryRef = useRef<ShortcutRegistry>({ global: [], page: [] })
const setLeader = useCallback((active: boolean) => {
if (leaderTimeoutRef.current) {
clearTimeout(leaderTimeoutRef.current)
leaderTimeoutRef.current = null
}
leaderActiveRef.current = active
setLeaderActive(active)
if (!active) return
leaderTimeoutRef.current = setTimeout(() => {
leaderTimeoutRef.current = null
leaderActiveRef.current = false
setLeaderActive(false)
}, LEADER_TIMEOUT)
}, [])
const runAction = useCallback((action: string | undefined, e: KeyboardEvent): boolean => {
if (!action) return false
const handler = findHandler(registryRef.current, action)
if (!handler) return false
e.preventDefault()
handler()
return true
}, [])
useEffect(() => {
const handleShortcut = (e: KeyboardEvent): boolean => {
if (e.defaultPrevented || e.isComposing) return false
const shortcut = formatShortcutEvent(e)
if (!shortcut) return false
const target = e.target as HTMLElement
if (target.closest?.('[data-file-editor="true"]')) return false
const bindings = resolveShortcutBindings(preferencesRef.current)
if (leaderActiveRef.current) {
setLeader(false)
return runAction(findShortcutAction(bindings, shortcut, false), e)
}
if (shortcut === bindings.leaderKey && (!isTextInput(target) || hasCommandModifier(shortcut))) {
e.preventDefault()
setLeader(true)
return true
}
const directAction = findShortcutAction(bindings, shortcut, true)
if (!directAction) return false
if (!isDirectActionAllowed(directAction, shortcut, target)) return false
return runAction(directAction, e)
}
const handleTerminalKeyDown = (e: KeyboardEvent) => {
if (!isTerminalTarget(e.target) || !handleShortcut(e)) return
e.stopPropagation()
}
const handleKeyDown = (e: KeyboardEvent) => {
if (isTerminalTarget(e.target)) return
handleShortcut(e)
}
document.addEventListener('keydown', handleTerminalKeyDown, true)
document.addEventListener('keydown', handleKeyDown)
return () => {
document.removeEventListener('keydown', handleTerminalKeyDown, true)
document.removeEventListener('keydown', handleKeyDown)
setLeader(false)
}
}, [runAction, setLeader])
return (
<KeyboardShortcutsRegistryContext.Provider value={registryRef.current}>
{children}
{leaderActive && (
<div className="fixed bottom-24 left-1/2 -translate-x-1/2 z-50 px-4 py-2 rounded-xl bg-primary/90 text-primary-foreground border border-primary shadow-lg backdrop-blur-md animate-pulse">
<span className="text-sm font-medium">Waiting for shortcut key...</span>
</div>
)}
</KeyboardShortcutsRegistryContext.Provider>
)
}
/**
* Registers a layer of shortcut handlers for the lifetime of the calling component. Page layers take precedence over global
* layers, and within a scope the newest layer wins; an action left `undefined` in a layer falls through to lower layers.
*/
export function useShortcutActions(actions: ShortcutActions, scope: 'global' | 'page' = 'page'): void {
const registry = useContext(KeyboardShortcutsRegistryContext)
if (!registry) throw new Error('useShortcutActions must be used within a KeyboardShortcutsProvider')
const layerRef = useRef<ShortcutLayer>({ actionsRef: { current: actions } })
layerRef.current.actionsRef.current = actions
useEffect(() => {
const layers = scope === 'global' ? registry.global : registry.page
const layer = layerRef.current
layers.push(layer)
return () => {
const index = layers.indexOf(layer)
if (index >= 0) layers.splice(index, 1)
}
}, [registry, scope])
}
@@ -0,0 +1,136 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { act, render, screen, waitFor } from '@testing-library/react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { MemoryRouter, useLocation } from 'react-router-dom'
import { KeyboardShortcutsProvider } from '@/contexts/KeyboardShortcutsContext'
import { useGlobalShortcutActions } from './useGlobalShortcutActions'
const mocks = vi.hoisted(() => ({
getRepo: vi.fn(),
createSession: vi.fn(),
useMobile: vi.fn(),
}))
vi.mock('@/hooks/useSettings', () => ({
useSettings: () => ({
preferences: { leaderKey: 'Ctrl+O', keyboardShortcuts: {}, directShortcuts: undefined },
}),
}))
vi.mock('@/hooks/useMobile', () => ({
useMobile: mocks.useMobile,
}))
vi.mock('@/api/repos', () => ({
getRepo: mocks.getRepo,
}))
vi.mock('@/api/opencode', () => ({
createSession: mocks.createSession,
}))
function Harness() {
useGlobalShortcutActions()
return null
}
function LocationDisplay() {
const location = useLocation()
return <div data-testid="location">{`${location.pathname}${location.search}`}</div>
}
function pressKey(init: KeyboardEventInit) {
const event = new KeyboardEvent('keydown', { bubbles: true, cancelable: true, ...init })
act(() => {
document.body.dispatchEvent(event)
})
return event
}
describe('useGlobalShortcutActions', () => {
let queryClient: QueryClient
beforeEach(() => {
vi.clearAllMocks()
queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
mocks.useMobile.mockReturnValue(false)
mocks.getRepo.mockResolvedValue({ id: 5, fullPath: '/repo/five' })
mocks.createSession.mockResolvedValue({ id: 'session-new' })
})
afterEach(() => {
queryClient.clear()
})
function renderHarness(initialEntry: string) {
render(
<QueryClientProvider client={queryClient}>
<KeyboardShortcutsProvider>
<MemoryRouter initialEntries={[initialEntry]}>
<Harness />
<LocationDisplay />
</MemoryRouter>
</KeyboardShortcutsProvider>
</QueryClientProvider>,
)
return {
location: () => screen.getByTestId('location').textContent,
}
}
it('opens the terminal dialog on the assistant host from the root route', async () => {
const { location } = renderHarness('/')
pressKey({ key: '`', ctrlKey: true })
await waitFor(() => expect(location()).toBe('/assistant?dialog=terminal'))
})
it('navigates to the nearest repo host from a repo sub-route without the tool', async () => {
const { location } = renderHarness('/repos/5/schedules')
pressKey({ key: '`', ctrlKey: true })
await waitFor(() => expect(location()).toBe('/repos/5?dialog=terminal'))
})
it('toggles the docked panel on and off when the route hosts the tool', async () => {
const { location } = renderHarness('/repos/5')
pressKey({ key: '`', ctrlKey: true })
await waitFor(() => expect(location()).toBe('/repos/5?panel=terminal'))
pressKey({ key: '`', ctrlKey: true })
await waitFor(() => expect(location()).toBe('/repos/5'))
})
it('toggles the dialog instead of the panel on mobile', async () => {
mocks.useMobile.mockReturnValue(true)
const { location } = renderHarness('/repos/5')
pressKey({ key: '`', ctrlKey: true })
await waitFor(() => expect(location()).toBe('/repos/5?dialog=terminal'))
})
it('creates a session in the repo directory and navigates to it from the leader shortcut', async () => {
queryClient.setQueryData(['repo', 5], { id: 5, fullPath: '/repo/five' })
const { location } = renderHarness('/repos/5')
pressKey({ key: 'o', ctrlKey: true })
pressKey({ key: 'n' })
await waitFor(() => expect(mocks.createSession).toHaveBeenCalledWith({ directory: '/repo/five' }))
await waitFor(() => expect(location()).toBe('/repos/5/sessions/session-new'))
})
it('does not swallow the follow-up key when the route has no new-session host', async () => {
renderHarness('/')
pressKey({ key: 'o', ctrlKey: true })
const followUp = pressKey({ key: 'n' })
expect(followUp.defaultPrevented).toBe(false)
expect(mocks.createSession).not.toHaveBeenCalled()
})
})
@@ -0,0 +1,66 @@
import { useCallback } from 'react'
import { useLocation, useNavigate } from 'react-router-dom'
import { useQuery } from '@tanstack/react-query'
import { ASSISTANT_REPO_ID } from '@opencode-manager/shared/utils'
import { getRepo } from '@/api/repos'
import { buildToolItems } from '@/components/navigation/moreDrawerItems'
import { useShortcutActions } from '@/contexts/KeyboardShortcutsContext'
import { dialogSearch } from '@/hooks/useDialogParam'
import { useCreateSession } from '@/hooks/useOpenCode'
import { useMobile } from '@/hooks/useMobile'
import { useSettingsDialog } from '@/hooks/useSettingsDialog'
import { useUrlParams } from '@/hooks/useUrlParams'
import { toggleToolDialogParams, toggleToolPanelParams, type PanelTool } from '@/hooks/useToolPanel'
import { getAssistantPath, getRepoPath, getSessionPath, isAssistantPath, parseRepoRoute } from '@/lib/navigation'
/**
* Registers the app-wide shortcut actions: the settings dialog, the route tool panels, and repo-scoped session
* creation. Page layers can override any of these by registering the same action name.
*/
export function useGlobalShortcutActions(): void {
const { pathname } = useLocation()
const navigate = useNavigate()
const { updateParams } = useUrlParams()
const { open: openSettings } = useSettingsDialog()
const isMobile = useMobile()
const repoId = isAssistantPath(pathname) ? ASSISTANT_REPO_ID : parseRepoRoute(pathname).repoId
const { data: repo } = useQuery({
queryKey: ['repo', repoId],
queryFn: () => getRepo(repoId as number),
enabled: repoId !== null,
})
const createSession = useCreateSession(repo?.fullPath, (session) => {
if (repoId === null) return
navigate(getSessionPath(repoId, session.id))
})
const hasFilesTool = buildToolItems(pathname).some((item) => (item.panelTool ?? item.dialog) === 'files')
const toggleRouteTool = useCallback((tool: PanelTool) => {
if (buildToolItems(pathname).some((item) => (item.panelTool ?? item.dialog) === tool)) {
updateParams((params) => {
if (isMobile) toggleToolDialogParams(params, tool)
else toggleToolPanelParams(params, tool)
}, 'push')
return
}
if (tool === 'files') return
const host = repoId !== null ? getRepoPath(repoId) : getAssistantPath()
navigate(`${host}${dialogSearch(tool)}`)
}, [pathname, isMobile, updateParams, navigate, repoId])
const newSession = repoId !== null && repo?.fullPath && !createSession.isPending
? () => createSession.mutate({})
: undefined
useShortcutActions({
settings: openSettings,
toggleTerminal: () => toggleRouteTool('terminal'),
toggleSourceControl: () => toggleRouteTool('sourceControl'),
toggleSidebar: hasFilesTool ? () => toggleRouteTool('files') : undefined,
newSession,
}, 'global')
}
@@ -1,34 +0,0 @@
import { describe, expect, it, vi } from 'vitest'
import { renderHook } from '@testing-library/react'
import { useKeyboardShortcuts } from './useKeyboardShortcuts'
vi.mock('./useSettings', () => ({
useSettings: () => ({
preferences: { keyboardShortcuts: { submit: 'Return' }, directShortcuts: ['submit'] },
}),
}))
describe('useKeyboardShortcuts', () => {
it('runs a direct shortcut from a text input', () => {
const submitPrompt = vi.fn()
renderHook(() => useKeyboardShortcuts({ submitPrompt }))
const textarea = document.body.appendChild(document.createElement('textarea'))
textarea.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true, cancelable: true }))
expect(submitPrompt).toHaveBeenCalledTimes(1)
textarea.remove()
})
it('ignores key events a component already handled', () => {
const submitPrompt = vi.fn()
renderHook(() => useKeyboardShortcuts({ submitPrompt }))
const textarea = document.body.appendChild(document.createElement('textarea'))
textarea.addEventListener('keydown', (event) => event.preventDefault())
textarea.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true, cancelable: true }))
expect(submitPrompt).not.toHaveBeenCalled()
textarea.remove()
})
})
-193
View File
@@ -1,193 +0,0 @@
import { useEffect, useCallback, useRef, useState } from 'react'
import { useSettings } from './useSettings'
import { DEFAULT_LEADER_KEY } from '@/api/types/settings'
const isMac = navigator.platform.toUpperCase().indexOf('MAC') >= 0
const normalizeShortcut = (shortcut: string): string => {
return shortcut.replace(/Cmd/g, isMac ? 'Cmd' : 'Ctrl')
}
const parseEventShortcut = (e: KeyboardEvent): string => {
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)
return keys.join('+')
}
return ''
}
const DEFAULT_DIRECT_SHORTCUTS = ['submit', 'abort']
const LEADER_TIMEOUT = 1500
interface ShortcutActions {
openModelDialog?: () => void
openSessions?: () => void
sessions?: () => void
newSession?: () => void
closeSession?: () => void
toggleSidebar?: () => void
submitPrompt?: () => void
interruptSession?: () => void
toggleMode?: () => void
undo?: () => void
redo?: () => void
compact?: () => void
fork?: () => void
openSettings?: () => void
}
export function useKeyboardShortcuts(actions: ShortcutActions = {}) {
const { preferences } = useSettings()
const [leaderActive, setLeaderActive] = useState(false)
const leaderTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null)
const preferencesRef = useRef(preferences)
preferencesRef.current = preferences
const actionsRef = useRef(actions)
actionsRef.current = actions
const clearLeaderTimeout = useCallback(() => {
if (leaderTimeoutRef.current) {
clearTimeout(leaderTimeoutRef.current)
leaderTimeoutRef.current = null
}
}, [])
const executeAction = useCallback((action: string, e: KeyboardEvent) => {
e.preventDefault()
const currentActions = actionsRef.current
switch (action) {
case 'selectModel':
currentActions.openModelDialog?.()
break
case 'sessions':
currentActions.openSessions?.()
break
case 'newSession':
currentActions.newSession?.()
break
case 'closeSession':
currentActions.closeSession?.()
break
case 'toggleSidebar':
currentActions.toggleSidebar?.()
break
case 'submit':
currentActions.submitPrompt?.()
break
case 'abort':
currentActions.interruptSession?.()
break
case 'toggleMode':
currentActions.toggleMode?.()
break
case 'undo':
currentActions.undo?.()
break
case 'redo':
currentActions.redo?.()
break
case 'compact':
currentActions.compact?.()
break
case 'fork':
currentActions.fork?.()
break
case 'settings':
currentActions.openSettings?.()
break
}
}, [])
const handleKeyDown = useCallback((e: KeyboardEvent) => {
if (e.defaultPrevented) return
const shortcut = parseEventShortcut(e)
if (!shortcut) return
const prefs = preferencesRef.current
const shortcuts = prefs?.keyboardShortcuts || {}
const leaderKey = normalizeShortcut(prefs?.leaderKey || DEFAULT_LEADER_KEY)
const directShortcuts = prefs?.directShortcuts ?? DEFAULT_DIRECT_SHORTCUTS
const activeFileEditor = document.querySelector('[data-file-editor="true"]')
if (activeFileEditor && document.activeElement === activeFileEditor) {
return
}
const target = e.target as HTMLElement
const isInInput = target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.contentEditable === 'true'
const isFileEditor = target.getAttribute('data-file-editor') === 'true'
if (isFileEditor) return
if (leaderActive) {
clearLeaderTimeout()
setLeaderActive(false)
const action = Object.entries(shortcuts).find(([actionName, keys]) => {
if (directShortcuts.includes(actionName)) return false
if (!keys) return false
return normalizeShortcut(keys) === shortcut
})?.[0]
if (action) {
executeAction(action, e)
}
return
}
if (shortcut === leaderKey && !isInInput) {
e.preventDefault()
setLeaderActive(true)
clearLeaderTimeout()
leaderTimeoutRef.current = setTimeout(() => {
setLeaderActive(false)
}, LEADER_TIMEOUT)
return
}
const directAction = Object.entries(shortcuts).find(([actionName, keys]) => {
if (!directShortcuts.includes(actionName)) return false
if (!keys) return false
return normalizeShortcut(keys) === shortcut
})?.[0]
if (directAction) {
if (isInInput && directAction !== 'submit' && directAction !== 'abort') {
return
}
executeAction(directAction, e)
}
}, [leaderActive, clearLeaderTimeout, executeAction])
useEffect(() => {
document.addEventListener('keydown', handleKeyDown)
return () => {
document.removeEventListener('keydown', handleKeyDown)
clearLeaderTimeout()
}
}, [handleKeyDown, clearLeaderTimeout])
return { leaderActive }
}
+84
View File
@@ -0,0 +1,84 @@
import { describe, expect, it } from 'vitest'
import { toggleToolDialogParams, toggleToolPanelParams } from './useToolPanel'
describe('toggleToolPanelParams', () => {
it('opens a tool, clears other tools owned params, and preserves unrelated params', () => {
const params = new URLSearchParams('previewPort=3000&previewPath=%2Fx&keep=1')
toggleToolPanelParams(params, 'terminal')
expect(params.get('panel')).toBe('terminal')
expect(params.has('previewPort')).toBe(false)
expect(params.has('previewPath')).toBe(false)
expect(params.get('keep')).toBe('1')
})
it('keeps the opened tool owned params', () => {
const params = new URLSearchParams('previewPort=3000&previewPath=%2Fx')
toggleToolPanelParams(params, 'preview')
expect(params.get('panel')).toBe('preview')
expect(params.get('previewPort')).toBe('3000')
expect(params.get('previewPath')).toBe('/x')
})
it('closes the active tool and clears every tool param', () => {
const params = new URLSearchParams('panel=terminal&terminal=%2Fbin%2Fsh&terminalDirectory=%2Fhome&previewPort=3000&keep=1')
toggleToolPanelParams(params, 'terminal')
expect(params.has('panel')).toBe(false)
expect(params.has('terminal')).toBe(false)
expect(params.has('terminalDirectory')).toBe(false)
expect(params.has('previewPort')).toBe(false)
expect(params.get('keep')).toBe('1')
})
it('switches from one tool to another and clears the previous owned params', () => {
const params = new URLSearchParams('panel=preview&previewPort=3000&previewPath=%2Fx')
toggleToolPanelParams(params, 'files')
expect(params.get('panel')).toBe('files')
expect(params.has('previewPort')).toBe(false)
expect(params.has('previewPath')).toBe(false)
})
})
describe('toggleToolDialogParams', () => {
it('opens a dialog, clears mobileTab and other tools owned params', () => {
const params = new URLSearchParams('mobileTab=more&previewPort=3000&previewPath=%2Fx&keep=1')
toggleToolDialogParams(params, 'terminal')
expect(params.get('dialog')).toBe('terminal')
expect(params.has('mobileTab')).toBe(false)
expect(params.has('previewPort')).toBe(false)
expect(params.has('previewPath')).toBe(false)
expect(params.get('keep')).toBe('1')
})
it('keeps the opened tool owned params', () => {
const params = new URLSearchParams('mobileTab=more&terminal=%2Fbin%2Fsh&terminalDirectory=%2Fhome&previewPort=3000')
toggleToolDialogParams(params, 'terminal')
expect(params.get('dialog')).toBe('terminal')
expect(params.get('terminal')).toBe('/bin/sh')
expect(params.get('terminalDirectory')).toBe('/home')
expect(params.has('previewPort')).toBe(false)
})
it('closes the active dialog and clears every tool param', () => {
const params = new URLSearchParams('dialog=terminal&terminal=%2Fbin%2Fsh&terminalDirectory=%2Fhome&previewPort=3000&keep=1')
toggleToolDialogParams(params, 'terminal')
expect(params.has('dialog')).toBe(false)
expect(params.has('terminal')).toBe(false)
expect(params.has('terminalDirectory')).toBe(false)
expect(params.has('previewPort')).toBe(false)
expect(params.get('keep')).toBe('1')
})
})
+22 -9
View File
@@ -26,6 +26,27 @@ function clearToolParams(params: URLSearchParams, keep?: PanelTool): void {
}
}
export function toggleToolPanelParams(params: URLSearchParams, tool: PanelTool): void {
if (params.get(PANEL_PARAM) === tool) {
params.delete(PANEL_PARAM)
clearToolParams(params)
return
}
params.set(PANEL_PARAM, tool)
clearToolParams(params, tool)
}
export function toggleToolDialogParams(params: URLSearchParams, tool: PanelTool): void {
if (params.get('dialog') === tool) {
params.delete('dialog')
clearToolParams(params)
return
}
params.set('dialog', tool)
params.delete('mobileTab')
clearToolParams(params, tool)
}
export interface ToolPanelState {
activeTool: PanelTool | null
toggleTool: (tool: PanelTool) => void
@@ -65,15 +86,7 @@ export function useToolPanel(docked: boolean): ToolPanelState {
}, [docked, dialogParam, panelParam, updateParams])
const toggleTool = useCallback((tool: PanelTool) => {
updateParams((params) => {
if (params.get(PANEL_PARAM) === tool) {
params.delete(PANEL_PARAM)
clearToolParams(params)
return
}
params.set(PANEL_PARAM, tool)
clearToolParams(params, tool)
}, 'push')
updateParams((params) => toggleToolPanelParams(params, tool), 'push')
}, [updateParams])
const closePanel = useCallback(() => {
@@ -0,0 +1,32 @@
import { describe, expect, it } from 'vitest'
import { DEFAULT_DIRECT_SHORTCUTS } from '@/api/types/settings'
import { formatShortcutEvent, normalizeShortcut, resolveDirectShortcuts } from './keyboardShortcuts'
describe('keyboardShortcuts', () => {
it('normalizes key aliases, modifier order and bare symbol keys', () => {
expect(normalizeShortcut('Ctrl+Enter')).toBe('Ctrl+Return')
expect(normalizeShortcut('Escape')).toBe('Esc')
expect(normalizeShortcut('Shift+Ctrl+z')).toBe('Ctrl+Shift+Z')
expect(normalizeShortcut('Ctrl++')).toBe('Ctrl++')
expect(normalizeShortcut('+')).toBe('+')
})
it('reads letters from the physical key when Alt rewrites the character', () => {
expect(formatShortcutEvent(new KeyboardEvent('keydown', { key: '†', code: 'KeyT', altKey: true }))).toBe('Alt+T')
expect(formatShortcutEvent(new KeyboardEvent('keydown', { key: 'Shift', shiftKey: true }))).toBeNull()
})
it('upgrades only the untouched legacy direct-shortcut list', () => {
expect(resolveDirectShortcuts(['abort', 'submit'])).toBe(DEFAULT_DIRECT_SHORTCUTS)
expect(resolveDirectShortcuts(['submit'])).toEqual(['submit'])
expect(resolveDirectShortcuts(undefined)).toBe(DEFAULT_DIRECT_SHORTCUTS)
})
it('adds default direct actions the stored shortcut map does not know about', () => {
expect(resolveDirectShortcuts(['submit'], { submit: 'Return' })).toEqual(DEFAULT_DIRECT_SHORTCUTS)
expect(resolveDirectShortcuts(['submit'], { submit: 'Return', abort: 'Escape' })).toEqual(
DEFAULT_DIRECT_SHORTCUTS.filter((action) => action !== 'abort'),
)
expect(resolveDirectShortcuts(['abort', 'submit'], { abort: 'Escape', submit: 'Return' })).toBe(DEFAULT_DIRECT_SHORTCUTS)
})
})
+113
View File
@@ -0,0 +1,113 @@
import { DEFAULT_DIRECT_SHORTCUTS, DEFAULT_KEYBOARD_SHORTCUTS, DEFAULT_LEADER_KEY } from '@/api/types/settings'
const isMac = typeof navigator !== 'undefined' && navigator.platform.toUpperCase().includes('MAC')
const CMD_KEY = isMac ? 'Cmd' : 'Ctrl'
const MODIFIER_ORDER = ['Ctrl', 'Cmd', 'Alt', 'Shift']
const MODIFIER_EVENT_KEYS = ['Control', 'Meta', 'Alt', 'Shift']
const KEY_ALIASES: Record<string, string> = {
' ': 'Space',
ArrowUp: 'Up',
ArrowDown: 'Down',
ArrowLeft: 'Left',
ArrowRight: 'Right',
Enter: 'Return',
Escape: 'Esc',
}
const LEGACY_DEFAULT_DIRECT_SHORTCUTS = ['submit', 'abort']
interface ShortcutPreferences {
leaderKey?: string
directShortcuts?: string[]
keyboardShortcuts?: Record<string, string>
}
export interface ShortcutBindings {
leaderKey: string
shortcuts: Record<string, string>
directShortcuts: string[]
}
function canonicalKey(key: string): string {
return KEY_ALIASES[key] ?? (key.length === 1 ? key.toUpperCase() : key)
}
function eventModifiers(e: KeyboardEvent): string[] {
return [e.ctrlKey && 'Ctrl', e.metaKey && 'Cmd', e.altKey && 'Alt', e.shiftKey && 'Shift'].filter((key): key is string => Boolean(key))
}
/**
* The main key of an event; with Alt held, letters and digits come from the physical key because macOS Option rewrites `key`.
*/
function eventMainKey(e: KeyboardEvent): string {
if (e.altKey && /^Key[A-Z]$/.test(e.code)) return e.code.slice(3)
if (e.altKey && /^Digit\d$/.test(e.code)) return e.code.slice(5)
return canonicalKey(e.key)
}
export function isModifierOnlyEvent(e: KeyboardEvent): boolean {
return MODIFIER_EVENT_KEYS.includes(e.key)
}
export function formatEventModifiers(e: KeyboardEvent): string {
return eventModifiers(e).join('+')
}
/**
* Formats a keydown event as a canonical shortcut string such as `Cmd+Shift+Z`, or null for a lone modifier key.
*/
export function formatShortcutEvent(e: KeyboardEvent): string | null {
if (isModifierOnlyEvent(e)) return null
return [...eventModifiers(e), eventMainKey(e)].join('+')
}
/**
* Canonicalizes a stored shortcut: `Cmd` becomes `Ctrl` off macOS, key aliases such as `Enter`/`Return` collapse, and modifiers are ordered.
*/
export function normalizeShortcut(shortcut: string): string {
if (!shortcut) return ''
const separator = shortcut.length < 2 ? -1 : shortcut.lastIndexOf('+', shortcut.length - 2)
const mainKey = canonicalKey(shortcut.slice(separator + 1))
const modifiers = separator < 0 ? [] : shortcut.slice(0, separator).split('+').map((modifier) => (modifier === 'Cmd' ? CMD_KEY : modifier))
const orderedModifiers = MODIFIER_ORDER.filter((modifier) => modifiers.includes(modifier))
return [...orderedModifiers, mainKey].join('+')
}
export function hasCommandModifier(shortcut: string): boolean {
return /(^|\+)(Ctrl|Cmd|Alt)\+./.test(shortcut)
}
/**
* The direct-shortcut list, upgrading the untouched legacy default and adding any default direct action that the stored
* shortcut map does not yet know about, so newly added direct defaults reach users who customized their list. When
* `storedShortcuts` is omitted the list is returned unchanged apart from the legacy upgrade.
*/
export function resolveDirectShortcuts(directShortcuts: string[] | undefined, storedShortcuts?: Record<string, string>): string[] {
if (!directShortcuts) return DEFAULT_DIRECT_SHORTCUTS
const isLegacyDefault = directShortcuts.length === LEGACY_DEFAULT_DIRECT_SHORTCUTS.length
&& LEGACY_DEFAULT_DIRECT_SHORTCUTS.every((action) => directShortcuts.includes(action))
const resolved = isLegacyDefault ? DEFAULT_DIRECT_SHORTCUTS : directShortcuts
if (!storedShortcuts) return resolved
const additions = DEFAULT_DIRECT_SHORTCUTS.filter(
(action) => !(action in storedShortcuts) && !resolved.includes(action),
)
return additions.length > 0 ? [...resolved, ...additions] : resolved
}
export function resolveShortcutBindings(preferences: ShortcutPreferences | undefined): ShortcutBindings {
return {
leaderKey: normalizeShortcut(preferences?.leaderKey || DEFAULT_LEADER_KEY),
shortcuts: { ...DEFAULT_KEYBOARD_SHORTCUTS, ...preferences?.keyboardShortcuts },
directShortcuts: resolveDirectShortcuts(preferences?.directShortcuts, preferences?.keyboardShortcuts),
}
}
export function findShortcutAction(bindings: ShortcutBindings, shortcut: string, direct: boolean): string | undefined {
return Object.entries(bindings.shortcuts).find(([action, keys]) => (
Boolean(keys) && bindings.directShortcuts.includes(action) === direct && normalizeShortcut(keys) === shortcut
))?.[0]
}
+110
View File
@@ -0,0 +1,110 @@
import { describe, it, expect, afterEach } from 'vitest'
import { stubMatchMedia } from '@/test/test-utils'
import { getFocusedElement, restoreOverlayFocus } from './overlayFocus'
function createElement<K extends keyof HTMLElementTagNameMap>(
tag: K,
attrs: Record<string, string> = {},
): HTMLElementTagNameMap[K] {
const element = document.createElement(tag)
for (const [name, value] of Object.entries(attrs)) element.setAttribute(name, value)
document.body.appendChild(element)
return element
}
afterEach(() => {
Reflect.deleteProperty(window, 'matchMedia')
document.body.innerHTML = ''
})
describe('getFocusedElement', () => {
it('returns the focused element', () => {
const button = createElement('button')
button.focus()
expect(getFocusedElement()).toBe(button)
})
})
describe('restoreOverlayFocus', () => {
it('focuses the chat prompt on desktop when focus was on a button', () => {
stubMatchMedia(true)
const prompt = createElement('textarea', { 'data-prompt-input': '' })
const button = createElement('button')
button.focus()
const moved = restoreOverlayFocus(button, null)
expect(moved).toBe(true)
expect(document.activeElement).toBe(prompt)
})
it('returns focus to a specific text field on desktop', () => {
stubMatchMedia(true)
const prompt = createElement('textarea', { 'data-prompt-input': '' })
const search = createElement('input')
const moved = restoreOverlayFocus(search, null)
expect(moved).toBe(true)
expect(document.activeElement).toBe(search)
expect(document.activeElement).not.toBe(prompt)
})
it('keeps focus inside another open overlay', () => {
stubMatchMedia(true)
const prompt = createElement('textarea', { 'data-prompt-input': '' })
const overlay = createElement('div', { role: 'dialog', 'data-state': 'open' })
const overlayInput = createElement('input')
overlay.appendChild(overlayInput)
const moved = restoreOverlayFocus(overlayInput, null)
expect(moved).toBe(true)
expect(document.activeElement).toBe(overlayInput)
expect(document.activeElement).not.toBe(prompt)
})
it('does not jump to the prompt behind another open overlay', () => {
stubMatchMedia(true)
const prompt = createElement('textarea', { 'data-prompt-input': '' })
createElement('div', { role: 'dialog', 'data-state': 'open' })
const button = createElement('button')
const moved = restoreOverlayFocus(button, null)
expect(moved).toBe(false)
expect(document.activeElement).not.toBe(prompt)
})
it('focuses a non-text return target on touch devices', () => {
stubMatchMedia(false)
const prompt = createElement('textarea', { 'data-prompt-input': '' })
const button = createElement('button')
const moved = restoreOverlayFocus(button, null)
expect(moved).toBe(true)
expect(document.activeElement).toBe(button)
expect(document.activeElement).not.toBe(prompt)
})
it('does not refocus a text field on touch devices', () => {
stubMatchMedia(false)
const comment = createElement('textarea')
const moved = restoreOverlayFocus(comment, null)
expect(moved).toBe(false)
expect(document.activeElement).not.toBe(comment)
})
it('falls back to the return target when no prompt exists', () => {
stubMatchMedia(true)
const button = createElement('button')
const moved = restoreOverlayFocus(button, null)
expect(moved).toBe(true)
expect(document.activeElement).toBe(button)
})
})
+100
View File
@@ -0,0 +1,100 @@
import { FINE_POINTER_MEDIA_QUERY } from '@/hooks/useMediaQuery'
const TEXT_FIELD_SELECTOR = 'input, textarea, [contenteditable="true"]'
const PROMPT_INPUT_SELECTOR = 'textarea[data-prompt-input]'
const OPEN_OVERLAY_SELECTOR = '[role="dialog"][data-state="open"], [role="alertdialog"][data-state="open"]'
/**
* Returns the element that currently owns focus, or null outside a DOM environment.
*/
export function getFocusedElement(): HTMLElement | null {
return typeof document !== 'undefined' && document.activeElement instanceof HTMLElement
? document.activeElement
: null
}
function isFinePointer(): boolean {
return (
typeof window !== 'undefined' &&
typeof window.matchMedia === 'function' &&
window.matchMedia(FINE_POINTER_MEDIA_QUERY).matches
)
}
function isTextField(element: Element): boolean {
return element.matches(TEXT_FIELD_SELECTOR)
}
function isDisabledTextField(element: HTMLElement): boolean {
return (element instanceof HTMLInputElement || element instanceof HTMLTextAreaElement) && element.disabled
}
function isInside(element: Element, container: Element | null): boolean {
return container !== null && container.contains(element)
}
function findOpenOverlays(closing: Element | null): Element[] {
if (typeof document === 'undefined') return []
return Array.from(document.querySelectorAll(OPEN_OVERLAY_SELECTOR)).filter(
(overlay) => overlay !== closing && !isInside(overlay, closing),
)
}
function findPromptInput(): HTMLTextAreaElement | null {
if (typeof document === 'undefined') return null
const prompt = document.querySelector<HTMLTextAreaElement>(PROMPT_INPUT_SELECTOR)
return prompt && prompt.isConnected && !prompt.disabled ? prompt : null
}
/**
* Moves focus after an overlay closes, preferring the chat prompt on desktop while leaving
* touch devices untouched so the on-screen keyboard stays closed.
*
* @returns true when focus was moved, so the caller can prevent its default handling.
*/
export function restoreOverlayFocus(returnFocus: HTMLElement | null, closing: Element | null = null): boolean {
if (typeof document === 'undefined') return false
const isDesktop = isFinePointer()
const openOverlays = findOpenOverlays(closing)
if (openOverlays.length > 0) {
if (!returnFocus?.isConnected) return false
if (!openOverlays.some((overlay) => overlay.contains(returnFocus))) return false
if (isTextField(returnFocus) && !isDesktop) return false
returnFocus.focus({ preventScroll: true })
return true
}
if (
isDesktop &&
returnFocus?.isConnected &&
isTextField(returnFocus) &&
!returnFocus.matches(PROMPT_INPUT_SELECTOR) &&
!isDisabledTextField(returnFocus) &&
!isInside(returnFocus, closing)
) {
returnFocus.focus({ preventScroll: true })
return true
}
if (isDesktop) {
const prompt = findPromptInput()
if (prompt) {
prompt.focus({ preventScroll: true })
return true
}
}
if (
returnFocus?.isConnected &&
returnFocus !== document.body &&
!isInside(returnFocus, closing) &&
!(isTextField(returnFocus) && !isDesktop)
) {
returnFocus.focus({ preventScroll: true })
return true
}
return false
}
+218
View File
@@ -0,0 +1,218 @@
import { describe, expect, it } from 'vitest'
import {
applyTuiKeybindImport,
parseTuiKeybindConfig,
type TuiKeybindImport,
} from './tuiKeybindImport'
const REAL_FILE = `{
"$schema": "https://opencode.ai/config.json",
"theme": "system",
"keybinds": {
"leader": "ctrl+o",
"terminal.toggle": "<leader>t",
"session.new": "ctrl+n,<leader>n",
"session.interrupt": "ctrl+s",
"session.compact": "<leader>c",
"model.list": "<leader>m",
"agent.cycle": "tab",
"session.undo": "<leader>u",
"session.redo": "none",
"session.tab.next": "ctrl+tab",
"app.exit": "ctrl+c,ctrl+d,<leader>q"
}
}`
describe('parseTuiKeybindConfig', () => {
it('converts the real cli.json keybinds excerpt', () => {
const result = parseTuiKeybindConfig(REAL_FILE)
expect(result.leaderKey).toBe('Ctrl+O')
expect(result.shortcuts).toEqual({
toggleTerminal: 'T',
newSession: 'N',
abort: 'Ctrl+S',
compact: 'C',
selectModel: 'M',
toggleMode: 'Tab',
undo: 'U',
redo: '',
})
expect(result.leaderActions).toEqual(['toggleTerminal', 'newSession', 'compact', 'selectModel', 'undo'])
expect(result.directActions).toEqual(['abort', 'toggleMode'])
expect(result.skipped).toEqual([])
})
it('parses JSONC with comments and trailing commas', () => {
const content = `{
// leader is ctrl+o
"keybinds": {
"leader": "ctrl+o",
"session.compact": "<leader>c", // compact
},
}`
const result = parseTuiKeybindConfig(content)
expect(result.leaderKey).toBe('Ctrl+O')
expect(result.shortcuts.compact).toBe('C')
expect(result.leaderActions).toEqual(['compact'])
})
it('reads legacy snake_case names', () => {
const content = `{
"keybinds": {
"session_new": "ctrl+n",
"messages_undo": "<leader>u",
"sidebar_toggle": "<leader>b",
"session_list": "<leader>l"
}
}`
const result = parseTuiKeybindConfig(content)
expect(result.shortcuts).toEqual({
newSession: 'Ctrl+N',
undo: 'U',
toggleSidebar: 'B',
sessions: 'L',
})
expect(result.leaderActions).toEqual(['undo', 'toggleSidebar', 'sessions'])
expect(result.directActions).toEqual(['newSession'])
})
it('prefers the dotted name over the legacy alias', () => {
const content = `{
"keybinds": {
"session_new": "ctrl+n",
"session.new": "<leader>n"
}
}`
const result = parseTuiKeybindConfig(content)
expect(result.shortcuts.newSession).toBe('N')
expect(result.leaderActions).toEqual(['newSession'])
expect(result.directActions).toEqual([])
})
it('converts KeyStroke, binding object and array values', () => {
const content = `{
"keybinds": {
"session.interrupt": { "name": "t", "ctrl": true },
"session.compact": { "key": "ctrl+k", "preventDefault": false },
"agent.cycle": ["ctrl+a", "<leader>z"],
"model.list": { "name": "pageup", "meta": true }
}
}`
const result = parseTuiKeybindConfig(content)
expect(result.shortcuts).toEqual({
abort: 'Ctrl+T',
compact: 'Ctrl+K',
toggleMode: 'Z',
selectModel: 'Alt+PageUp',
})
expect(result.leaderActions).toEqual(['toggleMode'])
expect(result.directActions).toEqual(['abort', 'compact', 'selectModel'])
})
it('converts <leader>pageup and ctrl++', () => {
const pageUp = parseTuiKeybindConfig('{ "keybinds": { "session.compact": "<leader>pageup" } }')
expect(pageUp.shortcuts.compact).toBe('PageUp')
expect(pageUp.leaderActions).toEqual(['compact'])
const ctrlPlus = parseTuiKeybindConfig('{ "keybinds": { "session.interrupt": "ctrl++" } }')
expect(ctrlPlus.shortcuts.abort).toBe('Ctrl++')
expect(ctrlPlus.directActions).toEqual(['abort'])
})
it('imports prompt.clear as a direct clearPrompt binding', () => {
const result = parseTuiKeybindConfig('{ "keybinds": { "prompt.clear": "ctrl+c" } }')
expect(result.shortcuts.clearPrompt).toBe('Ctrl+C')
expect(result.directActions).toEqual(['clearPrompt'])
expect(result.leaderActions).toEqual([])
})
it('imports the legacy input_clear alias as clearPrompt', () => {
const result = parseTuiKeybindConfig('{ "keybinds": { "input_clear": "ctrl+c" } }')
expect(result.shortcuts.clearPrompt).toBe('Ctrl+C')
expect(result.directActions).toEqual(['clearPrompt'])
})
it('records unconvertible bindings in skipped', () => {
const result = parseTuiKeybindConfig('{ "keybinds": { "session.undo": "gg" } }')
expect(result.shortcuts.undo).toBeUndefined()
expect(result.leaderActions).toEqual([])
expect(result.directActions).toEqual([])
expect(result.skipped).toEqual([{ name: 'session.undo', reason: 'unsupported key "gg"' }])
})
it('treats false and empty strings as disabled', () => {
const result = parseTuiKeybindConfig(`{
"keybinds": {
"session.fork": false,
"session.redo": ""
}
}`)
expect(result.shortcuts).toEqual({ fork: '', redo: '' })
expect(result.leaderActions).toEqual([])
expect(result.directActions).toEqual([])
expect(result.skipped).toEqual([])
})
it('ignores unknown keys silently', () => {
const result = parseTuiKeybindConfig('{ "keybinds": { "unknown.binding": "ctrl+x" } }')
expect(result.shortcuts).toEqual({})
expect(result.skipped).toEqual([])
})
it('throws when the file has no keybinds', () => {
expect(() => parseTuiKeybindConfig('{ "theme": "system" }')).toThrow('No keybinds found in this file')
expect(() => parseTuiKeybindConfig('[]')).toThrow('No keybinds found in this file')
expect(() => parseTuiKeybindConfig('{ "keybinds": [] }')).toThrow('No keybinds found in this file')
})
it('throws a SyntaxError for invalid JSONC', () => {
expect(() => parseTuiKeybindConfig('{ "keybinds": {')).toThrow(SyntaxError)
})
})
describe('applyTuiKeybindImport', () => {
it('merges shortcuts and updates the direct list', () => {
const imported: TuiKeybindImport = {
leaderKey: 'Ctrl+O',
shortcuts: { newSession: 'N', redo: '' },
leaderActions: ['newSession'],
directActions: ['abort'],
skipped: [],
}
const applied = applyTuiKeybindImport(imported, {
keyboardShortcuts: { abort: 'Escape', submit: 'Ctrl+Return', newSession: 'Ctrl+N' },
directShortcuts: ['submit', 'abort', 'newSession'],
})
expect(applied.keyboardShortcuts).toEqual({
abort: 'Escape',
submit: 'Ctrl+Return',
newSession: 'N',
redo: '',
})
expect(applied.directShortcuts).toEqual(['submit', 'abort'])
expect(applied.leaderKey).toBe('Ctrl+O')
})
it('adds new direct actions without duplicates and omits an undefined leader', () => {
const applied = applyTuiKeybindImport(
{ shortcuts: {}, leaderActions: [], directActions: ['compact', 'submit'], skipped: [] },
{ keyboardShortcuts: {}, directShortcuts: ['submit'] },
)
expect(applied.directShortcuts).toEqual(['submit', 'compact'])
expect(applied.leaderKey).toBeUndefined()
expect('leaderKey' in applied).toBe(false)
})
it('unbinds a current action that conflicts with an imported binding of the same kind', () => {
const applied = applyTuiKeybindImport(
{ shortcuts: { toggleTerminal: 'T', abort: 'Ctrl+S' }, leaderActions: ['toggleTerminal'], directActions: ['abort'], skipped: [] },
{
keyboardShortcuts: { toggleMode: 'T', toggleTerminal: 'Ctrl+`', variantCycle: 't', submit: 'Ctrl+S', abort: 'Escape' },
directShortcuts: ['submit', 'abort', 'variantCycle', 'toggleTerminal'],
},
)
expect(applied.cleared).toEqual(['toggleMode', 'submit'])
expect(applied.keyboardShortcuts).toMatchObject({ toggleMode: '', submit: '', variantCycle: 't', toggleTerminal: 'T', abort: 'Ctrl+S' })
expect(applied.directShortcuts).toEqual(['submit', 'abort', 'variantCycle'])
})
})
+285
View File
@@ -0,0 +1,285 @@
import type { KeyboardShortcutAction } from '@/api/types/settings'
import { parseJsonc } from '@/lib/jsonc'
import { normalizeShortcut } from '@/lib/keyboardShortcuts'
export interface TuiKeybindImport {
leaderKey?: string
shortcuts: Partial<Record<KeyboardShortcutAction, string>>
leaderActions: KeyboardShortcutAction[]
directActions: KeyboardShortcutAction[]
skipped: Array<{ name: string; reason: string }>
}
interface KeyStroke {
name: string
ctrl?: boolean
shift?: boolean
meta?: boolean
super?: boolean
hyper?: boolean
}
type Alternative = string | KeyStroke
type ResolvedBinding =
| { kind: 'disabled' }
| { kind: 'leader'; shortcut: string }
| { kind: 'direct'; shortcut: string }
| { kind: 'unconvertible'; reason: string }
type ConvertedAlternative = { shortcut: string; leader: boolean } | { reason: string }
const ACTION_BY_TUI_NAME = new Map<string, KeyboardShortcutAction>([
['session.interrupt', 'abort'],
['prompt.clear', 'clearPrompt'],
['agent.cycle', 'toggleMode'],
['variant.cycle', 'variantCycle'],
['session.undo', 'undo'],
['session.redo', 'redo'],
['session.compact', 'compact'],
['session.fork', 'fork'],
['opencode.settings', 'settings'],
['session.list', 'sessions'],
['session.new', 'newSession'],
['session.tab.close', 'closeSession'],
['session.sidebar.toggle', 'toggleSidebar'],
['model.list', 'selectModel'],
['terminal.toggle', 'toggleTerminal'],
['diff.open', 'toggleSourceControl'],
['session.timeline', 'timeline'],
['session.export', 'exportSession'],
])
const ACTION_BY_LEGACY_NAME = new Map<string, KeyboardShortcutAction>([
['session_interrupt', 'abort'],
['input_clear', 'clearPrompt'],
['agent_cycle', 'toggleMode'],
['variant_cycle', 'variantCycle'],
['messages_undo', 'undo'],
['messages_redo', 'redo'],
['session_compact', 'compact'],
['session_fork', 'fork'],
['session_list', 'sessions'],
['session_new', 'newSession'],
['session_tab_close', 'closeSession'],
['sidebar_toggle', 'toggleSidebar'],
['model_list', 'selectModel'],
['diff_open', 'toggleSourceControl'],
['session_timeline', 'timeline'],
['session_export', 'exportSession'],
])
const MODIFIER_LABELS = new Map<string, string | null>([
['ctrl', 'Ctrl'],
['shift', 'Shift'],
['meta', 'Alt'],
['alt', 'Alt'],
['option', 'Alt'],
['super', 'Cmd'],
['cmd', 'Cmd'],
['hyper', null],
])
const KEY_LABELS = new Map<string, string>([
['return', 'Return'],
['enter', 'Return'],
['escape', 'Esc'],
['esc', 'Esc'],
['space', 'Space'],
['tab', 'Tab'],
['up', 'Up'],
['down', 'Down'],
['left', 'Left'],
['right', 'Right'],
['pageup', 'PageUp'],
['pagedown', 'PageDown'],
['home', 'Home'],
['end', 'End'],
['delete', 'Delete'],
['backspace', 'Backspace'],
['insert', 'Insert'],
])
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value)
}
function isKeyStroke(value: unknown): value is KeyStroke {
return isRecord(value) && typeof value.name === 'string'
}
function convertKey(name: string): string | null {
const lower = name.toLowerCase()
const mapped = KEY_LABELS.get(lower)
if (mapped) return mapped
if (/^f([1-9]|1\d|2[0-4])$/.test(lower)) return `F${lower.slice(1)}`
if (name.length === 1) return name.toUpperCase()
return null
}
function splitToken(token: string): string[] {
const trailingPlus = token.endsWith('+')
const body = trailingPlus ? token.slice(0, -1) : token
const parts = body.split('+').filter((part) => part.length > 0)
return trailingPlus ? [...parts, '+'] : parts
}
function convertToken(token: string): ConvertedAlternative {
const lower = token.trim().toLowerCase()
if (!lower) return { reason: 'empty key' }
const leader = lower.startsWith('<leader>')
const body = leader ? lower.slice('<leader>'.length) : lower
if (!body) return { reason: 'missing key after <leader>' }
const parts = splitToken(body)
if (parts.length === 0) return { reason: `unsupported key "${token.trim()}"` }
const keyPart = parts[parts.length - 1]!
const key = convertKey(keyPart)
if (!key) return { reason: `unsupported key "${keyPart}"` }
const modifiers: string[] = []
for (const part of parts.slice(0, -1)) {
const label = MODIFIER_LABELS.get(part)
if (!label) return { reason: `unsupported modifier "${part}"` }
modifiers.push(label)
}
return { shortcut: normalizeShortcut([...modifiers, key].join('+')), leader }
}
function convertAlternative(alternative: Alternative): ConvertedAlternative {
if (typeof alternative === 'string') return convertToken(alternative)
const leader = alternative.name.startsWith('<leader>')
const name = leader ? alternative.name.slice('<leader>'.length) : alternative.name
if (!name) return { reason: 'missing key after <leader>' }
if (alternative.hyper) return { reason: 'unsupported modifier "hyper"' }
const key = convertKey(name)
if (!key) return { reason: `unsupported key "${name}"` }
const modifiers: string[] = []
if (alternative.ctrl) modifiers.push('Ctrl')
if (alternative.shift) modifiers.push('Shift')
if (alternative.meta) modifiers.push('Alt')
if (alternative.super) modifiers.push('Cmd')
return { shortcut: normalizeShortcut([...modifiers, key].join('+')), leader }
}
function collectAlternatives(value: unknown): Alternative[] {
if (typeof value === 'string') {
return value.split(',').map((part) => part.trim()).filter((part) => part.length > 0)
}
if (Array.isArray(value)) return value.flatMap(collectAlternatives)
if (isKeyStroke(value)) return [value]
if (isRecord(value) && 'key' in value) return collectAlternatives(value.key)
return []
}
function isMeaningfulAlternative(alternative: Alternative): boolean {
return typeof alternative !== 'string' || alternative.toLowerCase() !== 'none'
}
function resolveBinding(value: unknown, preferLeader: boolean): ResolvedBinding {
if (value === false) return { kind: 'disabled' }
if (typeof value === 'string' && (value.trim() === '' || value.trim().toLowerCase() === 'none')) {
return { kind: 'disabled' }
}
const alternatives = collectAlternatives(value).filter(isMeaningfulAlternative)
let reason: string | null = null
let leaderShortcut: string | null = null
let directShortcut: string | null = null
for (const alternative of alternatives) {
const result = convertAlternative(alternative)
if ('reason' in result) {
reason ??= result.reason
continue
}
if (result.leader) {
leaderShortcut ??= result.shortcut
continue
}
directShortcut ??= result.shortcut
}
if (preferLeader && leaderShortcut !== null) return { kind: 'leader', shortcut: leaderShortcut }
if (directShortcut !== null) return { kind: 'direct', shortcut: directShortcut }
return { kind: 'unconvertible', reason: reason ?? 'unsupported value' }
}
/**
* Converts an OpenCode TUI keybind config (cli.json, JSONC, or legacy tui.json) into this app's shortcut preferences.
*/
export function parseTuiKeybindConfig(content: string): TuiKeybindImport {
const root = parseJsonc<unknown>(content)
if (!isRecord(root) || !isRecord(root.keybinds)) {
throw new Error('No keybinds found in this file')
}
const keybinds = root.keybinds
const shortcuts: Partial<Record<KeyboardShortcutAction, string>> = {}
const leaderActions: KeyboardShortcutAction[] = []
const directActions: KeyboardShortcutAction[] = []
const skipped: Array<{ name: string; reason: string }> = []
let leaderKey: string | undefined
if ('leader' in keybinds) {
const resolved = resolveBinding(keybinds.leader, false)
if (resolved.kind === 'disabled') {
skipped.push({ name: 'leader', reason: 'leader key is disabled' })
} else if (resolved.kind === 'unconvertible') {
skipped.push({ name: 'leader', reason: resolved.reason })
} else {
leaderKey = resolved.shortcut
}
}
const byAction = new Map<KeyboardShortcutAction, { name: string; value: unknown; dotted: boolean }>()
for (const [name, value] of Object.entries(keybinds)) {
if (name === 'leader') continue
const action = ACTION_BY_TUI_NAME.get(name) ?? ACTION_BY_LEGACY_NAME.get(name)
if (!action) continue
const dotted = ACTION_BY_TUI_NAME.has(name)
const existing = byAction.get(action)
if (!existing || (dotted && !existing.dotted)) byAction.set(action, { name, value, dotted })
}
for (const [action, entry] of byAction) {
const resolved = resolveBinding(entry.value, true)
if (resolved.kind === 'disabled') {
shortcuts[action] = ''
continue
}
if (resolved.kind === 'unconvertible') {
skipped.push({ name: entry.name, reason: resolved.reason })
continue
}
shortcuts[action] = resolved.shortcut
if (resolved.kind === 'leader') leaderActions.push(action)
else directActions.push(action)
}
return { leaderKey, shortcuts, leaderActions, directActions, skipped }
}
/**
* Merges an imported TUI keybind result into the current shortcut preferences. The imported bindings win: an action the
* file does not set is unbound (and listed in `cleared`) when it has the same key and leader/direct kind as an imported one.
*/
export function applyTuiKeybindImport(
imported: TuiKeybindImport,
current: { keyboardShortcuts: Record<string, string>; directShortcuts: string[] },
): { keyboardShortcuts: Record<string, string>; directShortcuts: string[]; leaderKey?: string; cleared: string[] } {
const leaderSet = new Set<string>(imported.leaderActions)
const directShortcuts = [
...current.directShortcuts.filter((action) => !leaderSet.has(action)),
...imported.directActions.filter((action) => !current.directShortcuts.includes(action)),
]
const bindingKey = (action: string, keys: string) => `${directShortcuts.includes(action) ? 'direct' : 'leader'}:${normalizeShortcut(keys)}`
const importedBindings = new Set(
Object.entries(imported.shortcuts).filter(([, keys]) => Boolean(keys)).map(([action, keys]) => bindingKey(action, keys ?? '')),
)
const cleared = Object.entries(current.keyboardShortcuts)
.filter(([action, keys]) => !(action in imported.shortcuts) && Boolean(keys) && importedBindings.has(bindingKey(action, keys)))
.map(([action]) => action)
const keyboardShortcuts = {
...current.keyboardShortcuts,
...Object.fromEntries(cleared.map((action) => [action, ''])),
...imported.shortcuts,
}
return imported.leaderKey !== undefined
? { keyboardShortcuts, directShortcuts, leaderKey: imported.leaderKey, cleared }
: { keyboardShortcuts, directShortcuts, cleared }
}
+23 -38
View File
@@ -23,7 +23,7 @@ import { useSSE } from "@/hooks/useSSE";
import { useUIState } from "@/stores/uiStateStore";
import { useSettings } from "@/hooks/useSettings";
import { useModelSelection } from "@/hooks/useModelSelection";
import { useKeyboardShortcuts } from "@/hooks/useKeyboardShortcuts";
import { useShortcutActions } from "@/contexts/KeyboardShortcutsContext";
import { useSettingsDialog } from "@/hooks/useSettingsDialog";
import { useAutoScroll } from "@/hooks/useAutoScroll";
import { useMobile } from "@/hooks/useMobile";
@@ -455,34 +455,6 @@ export function SessionDetail() {
}
};
const { leaderActive } = useKeyboardShortcuts({
openModelDialog: handleOpenModelDialog,
openSessions: handleShowSessionsDialog,
openSettings,
newSession: handleNewSession,
closeSession: handleCloseSession,
compact: handleCompact,
undo: handleUndo,
redo: handleRedo,
fork: openForkPicker,
toggleSidebar: () => (docked ? sidePanel.toggleTool('files') : setFileBrowserOpen(!fileBrowserOpen)),
toggleMode: () => {
const modeButton = document.querySelector(
"[data-toggle-mode]",
) as HTMLButtonElement;
modeButton?.click();
},
submitPrompt: () => {
const submitButton = document.querySelector(
"[data-submit-prompt]",
) as HTMLButtonElement;
submitButton?.click();
},
interruptSession: handleInterruptSession,
});
const handleFileClick = useCallback((filePath: string) => {
setSelectedFilePath(getWorkspaceFilePath(filePath, {
directory: sessionDirectory,
@@ -611,14 +583,32 @@ export function SessionDetail() {
handleConnectProvider,
]);
const handleUndoMessage = useCallback((restoredPrompt: string) => {
promptInputRef.current?.setPromptValue(restoredPrompt)
}, []);
const handleClearPrompt = useCallback(() => {
promptInputRef.current?.clearPrompt()
}, []);
useShortcutActions({
selectModel: handleOpenModelDialog,
sessions: handleShowSessionsDialog,
newSession: handleNewSession,
closeSession: handleCloseSession,
compact: handleCompact,
undo: handleUndo,
redo: handleRedo,
fork: openForkPicker,
timeline: openTimelinePicker,
exportSession: handleExportSession,
toggleMode: () => promptInputRef.current?.cycleAgent(),
variantCycle: () => promptInputRef.current?.cycleVariant(),
submit: () => document.querySelector<HTMLButtonElement>("[data-submit-prompt]")?.click(),
abort: isSessionActive ? handleInterruptSession : undefined,
clearPrompt: handleClearPrompt,
});
const handleUndoMessage = useCallback((restoredPrompt: string) => {
promptInputRef.current?.setPromptValue(restoredPrompt)
}, []);
@@ -773,11 +763,6 @@ export function SessionDetail() {
</button>
)}
</div>
{leaderActive && (
<div className="absolute -top-12 left-1/2 -translate-x-1/2 z-50 px-4 py-2 rounded-xl bg-primary/90 text-primary-foreground border border-primary shadow-lg backdrop-blur-md animate-pulse">
<span className="text-sm font-medium">Waiting for shortcut key...</span>
</div>
)}
{minimizedForm && (
<MinimizedFormIndicator
form={minimizedForm}
@@ -17,7 +17,7 @@ const mocks = vi.hoisted(() => ({
useSettingsDialog: vi.fn(),
useMobile: vi.fn(),
useVisualViewport: vi.fn(),
useKeyboardShortcuts: vi.fn(),
useShortcutActions: vi.fn(),
useAutoScroll: vi.fn(),
useDialogParam: vi.fn(),
RepoSkillsDialog: vi.fn(() => null),
@@ -63,8 +63,8 @@ vi.mock('@/hooks/useVisualViewport', () => ({
useVisualViewport: vi.fn(() => ({ keyboardHeight: 0 })),
}))
vi.mock('@/hooks/useKeyboardShortcuts', () => ({
useKeyboardShortcuts: vi.fn(() => ({ leaderActive: false })),
vi.mock('@/contexts/KeyboardShortcutsContext', () => ({
useShortcutActions: mocks.useShortcutActions,
}))
vi.mock('@/hooks/useAutoScroll', () => ({
@@ -210,7 +210,6 @@ describe('SessionDetail assistant loading at repoId=0', () => {
mocks.useSettingsDialog.mockReturnValue({ open: vi.fn() })
mocks.useMobile.mockReturnValue(false)
mocks.useVisualViewport.mockReturnValue({ keyboardHeight: 0 })
mocks.useKeyboardShortcuts.mockReturnValue({ leaderActive: false })
mocks.useAutoScroll.mockReturnValue({ scrollToBottom: vi.fn() })
mocks.useDialogParam.mockReturnValue([false, vi.fn()])
})
@@ -126,8 +126,8 @@ vi.mock('@/hooks/useVisualViewport', () => ({
useVisualViewport: vi.fn(() => ({ keyboardHeight: 0 })),
}))
vi.mock('@/hooks/useKeyboardShortcuts', () => ({
useKeyboardShortcuts: vi.fn(() => ({ leaderActive: false })),
vi.mock('@/contexts/KeyboardShortcutsContext', () => ({
useShortcutActions: vi.fn(),
}))
vi.mock('@/hooks/useAutoScroll', () => ({
@@ -86,8 +86,8 @@ vi.mock('@/hooks/useVisualViewport', () => ({
useVisualViewport: vi.fn(() => ({ keyboardHeight: 0 })),
}))
vi.mock('@/hooks/useKeyboardShortcuts', () => ({
useKeyboardShortcuts: vi.fn(() => ({ leaderActive: false })),
vi.mock('@/contexts/KeyboardShortcutsContext', () => ({
useShortcutActions: vi.fn(),
}))
vi.mock('@/hooks/useAutoScroll', () => ({
@@ -17,7 +17,7 @@ const mocks = vi.hoisted(() => ({
useSettingsDialog: vi.fn(),
useMobile: vi.fn(),
useVisualViewport: vi.fn(),
useKeyboardShortcuts: vi.fn(),
useShortcutActions: vi.fn(),
useAutoScroll: vi.fn(),
useDialogParam: vi.fn(),
useSessionStatusForSession: vi.fn(),
@@ -65,8 +65,8 @@ vi.mock('@/hooks/useVisualViewport', () => ({
useVisualViewport: vi.fn(() => ({ keyboardHeight: 0 })),
}))
vi.mock('@/hooks/useKeyboardShortcuts', () => ({
useKeyboardShortcuts: vi.fn(() => ({ leaderActive: false })),
vi.mock('@/contexts/KeyboardShortcutsContext', () => ({
useShortcutActions: mocks.useShortcutActions,
}))
vi.mock('@/hooks/useAutoScroll', () => ({
@@ -185,7 +185,6 @@ describe('SessionDetail pending-actions polling gating', () => {
mocks.useSettingsDialog.mockReturnValue({ open: vi.fn() })
mocks.useMobile.mockReturnValue(false)
mocks.useVisualViewport.mockReturnValue({ keyboardHeight: 0 })
mocks.useKeyboardShortcuts.mockReturnValue({ leaderActive: false })
mocks.useAutoScroll.mockReturnValue({ scrollToBottom: vi.fn() })
mocks.useDialogParam.mockReturnValue([false, vi.fn()])
mocks.useSessionStatusForSession.mockReturnValue({ type: 'idle' })
@@ -18,7 +18,7 @@ const mocks = vi.hoisted(() => ({
useSettingsDialog: vi.fn(),
useMobile: vi.fn(),
useVisualViewport: vi.fn(),
useKeyboardShortcuts: vi.fn(),
useShortcutActions: vi.fn(),
useAutoScroll: vi.fn(),
useDialogParam: vi.fn(),
useSessionStatusForSession: vi.fn(),
@@ -81,8 +81,8 @@ vi.mock('@/hooks/useVisualViewport', () => ({
useVisualViewport: vi.fn(() => ({ keyboardHeight: 0 })),
}))
vi.mock('@/hooks/useKeyboardShortcuts', () => ({
useKeyboardShortcuts: vi.fn(() => ({ leaderActive: false })),
vi.mock('@/contexts/KeyboardShortcutsContext', () => ({
useShortcutActions: mocks.useShortcutActions,
}))
vi.mock('@/hooks/useAutoScroll', () => ({
@@ -273,7 +273,6 @@ describe('SessionDetail scroll floating button', () => {
mocks.useSSEHealth.mockReturnValue({ isHealthy: true })
mocks.useConfig.mockReturnValue({ data: undefined, isLoading: false })
mocks.useVisualViewport.mockReturnValue({ keyboardHeight: 0 })
mocks.useKeyboardShortcuts.mockReturnValue({ leaderActive: false })
mocks.useDialogParam.mockReturnValue([false, vi.fn()])
mocks.useSessionStatusForSession.mockReturnValue({ type: 'idle' })
mocks.PromptInput.mockImplementation(() => <div>MockedPromptInput</div>)
+13 -4
View File
@@ -69,9 +69,10 @@ const CMD_KEY = isMac ? 'Cmd' : 'Ctrl';
export const DEFAULT_LEADER_KEY = `${CMD_KEY}+O`;
export const DEFAULT_KEYBOARD_SHORTCUTS: Record<string, string> = {
export const DEFAULT_KEYBOARD_SHORTCUTS = {
submit: `${CMD_KEY}+Enter`,
abort: 'Escape',
clearPrompt: isMac ? 'Ctrl+C' : '',
toggleMode: 'T',
undo: 'Z',
redo: 'Shift+Z',
@@ -83,8 +84,16 @@ export const DEFAULT_KEYBOARD_SHORTCUTS: Record<string, string> = {
closeSession: 'W',
toggleSidebar: 'B',
selectModel: 'M',
variantCycle: `${CMD_KEY}+T`,
};
variantCycle: 'Ctrl+T',
toggleTerminal: 'Ctrl+`',
toggleSourceControl: 'D',
timeline: 'G',
exportSession: 'X',
} satisfies Record<string, string>;
export type KeyboardShortcutAction = keyof typeof DEFAULT_KEYBOARD_SHORTCUTS;
export const DEFAULT_DIRECT_SHORTCUTS = ['submit', 'abort', 'clearPrompt', 'variantCycle', 'toggleTerminal'];
export const GitCredentialSchema = z.object({
id: z.string().optional(),
@@ -233,7 +242,7 @@ export const DEFAULT_USER_PREFERENCES = {
showReasoning: false,
simpleChatMode: false,
leaderKey: DEFAULT_LEADER_KEY,
directShortcuts: ['submit', 'abort'],
directShortcuts: DEFAULT_DIRECT_SHORTCUTS,
keyboardShortcuts: DEFAULT_KEYBOARD_SHORTCUTS,
customCommands: [],
customAgents: [],