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 { formatEventModifiers, formatShortcutEvent, formatShortcutLabel, isModifierOnlyEvent, normalizeShortcut, resolveShortcutBindings } from '@/lib/keyboardShortcuts' import { applyTuiKeybindImport, parseTuiKeybindConfig } from '@/lib/tuiKeybindImport' import { showToast } from '@/lib/toast' const CONVERSATION_ACTIONS = ['submit', 'abort', 'clearPrompt', 'toggleMode', 'undo', 'redo', 'compact', 'fork', 'timeline', 'exportSession', 'selectModel', 'variantCycle', 'favoriteCycle', 'halfPageUp', 'halfPageDown'] const NAVIGATION_ACTIONS = ['settings', 'sessions', 'switchPickerTab', 'newSession', 'closeSession', 'toggleSidebar', 'toggleTerminal', 'toggleSourceControl'] const formatActionLabel = (action: string): string => { return action.replace(/([A-Z])/g, ' $1').trim() } interface ShortcutGroup { title: string 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): ShortcutGroup[] => { const knownActions = new Set([...CONVERSATION_ACTIONS, ...NAVIGATION_ACTIONS]) const unknownActions = Object.keys(shortcuts).filter((action) => !knownActions.has(action)) return [ { title: 'Conversation actions', actions: CONVERSATION_ACTIONS.filter((action) => action in shortcuts), }, { title: 'Navigation', actions: [...NAVIGATION_ACTIONS.filter((action) => action in shortcuts), ...unknownActions], }, ] } interface RecordingInputProps { value: string onStop: () => void } function RecordingInput({ value, onStop }: RecordingInputProps) { return (
) } interface ShortcutRowProps { action: string keys: string isDirect: boolean display: string isRecording: boolean currentKeys: string onToggleDirect: (action: string) => void onStartRecording: (action: string) => void onStopRecording: () => void onClear: (action: string) => void } function ShortcutRow({ action, keys, isDirect, display, isRecording, currentKeys, onToggleDirect, onStartRecording, onStopRecording, onClear }: ShortcutRowProps) { return (

{formatActionLabel(action)}

{isRecording ? ( ) : (
{keys && ( )}
)}
) } export function KeyboardShortcuts() { const { preferences, isLoading, updateSettings } = useSettings() const isMobile = useMobile() const [recordingKey, setRecordingKey] = useState(null) const [recordingLeader, setRecordingLeader] = useState(false) const [tempShortcuts, setTempShortcuts] = useState>({}) const [tempLeaderKey, setTempLeaderKey] = useState(null) const [currentKeys, setCurrentKeys] = useState('') const bindings = useMemo(() => resolveShortcutBindings(preferences), [preferences]) const leaderKey = tempLeaderKey ?? bindings.leaderKey const directShortcuts = bindings.directShortcuts const shortcuts = useMemo>(() => ({ ...bindings.shortcuts, ...tempShortcuts }), [bindings.shortcuts, tempShortcuts]) const shortcutGroups = useMemo(() => buildShortcutGroups(shortcuts), [shortcuts]) 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(null) const startRecording = (action: string) => { setRecordingKey(action) setRecordingLeader(false) setCurrentKeys('') } const startRecordingLeader = () => { setRecordingLeader(true) setRecordingKey(null) setCurrentKeys('') } const stopRecording = useCallback(() => { setRecordingKey(null) setRecordingLeader(false) setCurrentKeys('') }, []) const clearShortcut = useCallback((action: string) => { setTempShortcuts(prev => ({ ...prev, [action]: '' })) updateSettingsRef.current({ keyboardShortcuts: { ...shortcutsRef.current, [action]: '' } }) }, []) useEffect(() => { if (!recordingKey && !recordingLeader) return let leaderPressed = false const leaderPrefix = () => (leaderPressed ? `${normalizeShortcut(leaderKeyRef.current)} → ` : '') const handleKeyDown = (e: KeyboardEvent) => { e.preventDefault() e.stopPropagation() 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 (isModifierOnlyEvent(e)) { setCurrentKeys(leaderPrefix()) } } document.addEventListener('keydown', handleKeyDown, true) document.addEventListener('keyup', handleKeyUp) return () => { document.removeEventListener('keydown', handleKeyDown, true) document.removeEventListener('keyup', handleKeyUp) } }, [recordingKey, recordingLeader]) if (isLoading) { return (
) } const formatShortcutDisplay = (action: string, keys: string) => { if (!keys) return 'Not set' return formatShortcutLabel(keys, directShortcuts.includes(action), leaderKey) } const toggleDirectShortcut = (action: string) => { const newDirectShortcuts = directShortcuts.includes(action) ? directShortcuts.filter(s => s !== action) : [...directShortcuts, action] updateSettings({ directShortcuts: newDirectShortcuts }) } const importFromTui = async (event: React.ChangeEvent) => { 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) => formatActionLabel(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 (

Keyboard Shortcuts

Keyboard shortcuts are not available on mobile devices.

) } return (

Keyboard Shortcuts

Select your OpenCode cli.json (or legacy tui.json), usually in ~/.config/opencode.

Leader Key

Press this first, then the shortcut key

{recordingLeader ? ( ) : ( )}
{shortcutGroups.map((group) => (

{group.title}

{group.actions.map((action) => ( ))}
))}

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.

) }