import { useCallback, useMemo, useState } from 'react' import { View, Text, Pressable } from 'react-native' import { ChevronLeft } from 'lucide-react-native' import { colors, pressedStyle } from '../theme/mobile-theme' import { useMobileColorScheme } from '../theme/use-mobile-color-scheme' import { BottomDrawer } from './bottom-drawer/BottomDrawer' import { TextField } from './composer-input/TextField' import { buildTerminalShortcutKey, normalizeShortcutKeyInput, TERMINAL_SHORTCUT_SPECIAL_KEYS, type TerminalShortcutModifier, type TerminalShortcutSpecialKey } from '../terminal/terminal-accessory-keys' import { customKeyModalStyles as styles } from './CustomKeyModal.styles' import { updateStoredCustomKeys, type CustomKey } from '../terminal/terminal-custom-keys' import type { Translate } from '../i18n/mobile-i18n' import { useMobileTranslation } from '../i18n/use-mobile-translation' import { MobileSwitch } from './MobileSwitch' import { ListGroup, ListRow } from './list/ListGroup' import { FieldTextInput } from './composer-input/FieldTextInput' import { SmartRailRow } from './SmartRailRow' type Step = 'choose-type' | 'shortcut-combo' | 'special-keys' | 'text-macro' // Alt/Option emits terminal-readable ESC prefix; Cmd is absent because macOS swallows it before shell. Render Alt as ⌥. const SHORTCUT_MODIFIERS: { id: TerminalShortcutModifier; label: string; glyph?: string }[] = [ { id: 'ctrl', label: 'Ctrl' }, { id: 'alt', label: 'Alt', glyph: '⌥' }, { id: 'shift', label: 'Shift' } ] // Group keys into three fixed grids; ragged wrapping clipped F7–F12. function specialKeyGroups(t: Translate) { return [ { id: 'editing', title: t('components.customKeyModal.editing', 'Editing'), ids: ['escape', 'tab', 'enter', 'backspace', 'delete', 'insert', 'space'], columns: 4 }, { id: 'navigation', title: t('components.customKeyModal.navigation', 'Navigation'), ids: ['arrowUp', 'arrowDown', 'arrowLeft', 'arrowRight', 'home', 'end', 'pageUp', 'pageDown'], columns: 4 }, { id: 'function', title: t('components.customKeyModal.function', 'Function'), ids: ['f1', 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9', 'f10', 'f11', 'f12'], columns: 6 } ] } const SPECIAL_KEY_BY_ID: Record = Object.fromEntries( TERMINAL_SHORTCUT_SPECIAL_KEYS.map((key) => [key.id, key]) ) type Props = { visible: boolean onClose: () => void onKeysChanged: (keys: CustomKey[]) => void onManageShortcuts?: () => void smartRail?: { enabled: boolean; onChange: (enabled: boolean) => void } } export function CustomKeyModal(props: Props) { const { visible, onClose, onKeysChanged, onManageShortcuts, smartRail } = props useMobileColorScheme() const t = useMobileTranslation() const [step, setStep] = useState('choose-type') const [shortcutKey, setShortcutKey] = useState('c') const [shortcutModifiers, setShortcutModifiers] = useState(['ctrl']) const [macroLabel, setMacroLabel] = useState('') const [macroText, setMacroText] = useState('') const [macroEnter, setMacroEnter] = useState(true) const [previousVisible, setPreviousVisible] = useState(visible) // Reset draft before opening commit to avoid old-key flash; retain close state through slide-out. if (visible !== previousVisible) { setPreviousVisible(visible) if (visible) { setStep('choose-type') setShortcutKey('c') setShortcutModifiers(['ctrl']) setMacroLabel('') setMacroText('') setMacroEnter(true) } } const addKey = useCallback( async (key: Omit) => { const newKey: CustomKey = { ...key, id: `custom-${Date.now()}` } let updated: CustomKey[] // Catch both void addKey callers: page storage can refuse size/unseeded-key writes (ruling 33.6), and uncaught rejection would fault/drop generation. // Other allowlisted writers in this closure already catch saves. try { updated = await updateStoredCustomKeys((keys) => [...keys, newKey]) } catch (error) { // Keep failed-save drawer open without announcing success; otherwise accessory row would lack persisted key. console.warn('[custom-keys] the store would not take this key', error) return } onKeysChanged(updated) onClose() }, [onClose, onKeysChanged] ) const shortcutPreview = useMemo( () => buildTerminalShortcutKey({ key: shortcutKey, modifiers: shortcutModifiers }), [shortcutKey, shortcutModifiers] ) const previewKeyLabel = useMemo(() => { const special = SPECIAL_KEY_BY_ID[shortcutKey] if (special) { return special.label } return shortcutKey.length === 1 ? shortcutKey.toUpperCase() : shortcutKey }, [shortcutKey]) const orderedActiveModifiers = useMemo( () => SHORTCUT_MODIFIERS.filter((m) => shortcutModifiers.includes(m.id)), [shortcutModifiers] ) const toggleShortcutModifier = useCallback((modifier: TerminalShortcutModifier) => { setShortcutModifiers((current) => current.includes(modifier) ? current.filter((item) => item !== modifier) : [...current, modifier] ) }, []) const handleShortcutKeyInput = useCallback((value: string) => { if (value === '') { // Allow empty field for backspace; Save still requires valid key. setShortcutKey('') return } const next = normalizeShortcutKeyInput(value) if (next) { setShortcutKey(next) } }, []) const handleSpecialKeyPick = useCallback((id: string) => { setShortcutKey(id) setStep('shortcut-combo') }, []) const handleShortcutSave = useCallback(() => { const built = buildTerminalShortcutKey({ key: shortcutKey, modifiers: shortcutModifiers }) if (!built) { return } void addKey({ label: built.label, bytes: built.bytes, enter: false }) }, [addKey, shortcutKey, shortcutModifiers]) const handleMacroSave = useCallback(() => { const label = macroLabel.trim() || macroText.trim().slice(0, 12) const text = macroText if (!label || !text) { return } const bytes = macroEnter ? `${text}\r` : text void addKey({ label, bytes, enter: false }) }, [addKey, macroLabel, macroText, macroEnter]) const showBack = step !== 'choose-type' const onBack = useCallback(() => { if (step === 'special-keys') { setStep('shortcut-combo') } else { setStep('choose-type') } }, [step]) return ( {showBack ? ( [styles.backButton, pressed && styles.backButtonPressed]} onPress={onBack} accessibilityRole="button" accessibilityLabel={t('common.back', 'Back')} > ) : ( )} {step === 'choose-type' && t('components.customKeyModal.addShortcut', 'Add Shortcut')} {step === 'shortcut-combo' && t('components.customKeyModal.shortcutCombo', 'Shortcut Combo')} {step === 'special-keys' && t('components.customKeyModal.pickKey', 'Pick a key')} {step === 'text-macro' && t('components.customKeyModal.textMacro', 'Text Macro')} {step === 'choose-type' && ( setStep('shortcut-combo')} /> setStep('text-macro')} /> {onManageShortcuts ? ( ) : null} )} {step === 'choose-type' && smartRail ? ( ) : null} {step === 'shortcut-combo' && ( {orderedActiveModifiers.map((modifier, index) => ( {index > 0 ? + : null} {modifier.label} ))} {orderedActiveModifiers.length > 0 ? + : null} {previewKeyLabel} {t('components.customKeyModal.modifiers', 'Modifiers')} {SHORTCUT_MODIFIERS.map((modifier) => { const selected = shortcutModifiers.includes(modifier.id) return ( [ styles.chip, selected && styles.chipSelected, pressed && !selected && styles.chipPressed ]} onPress={() => toggleShortcutModifier(modifier.id)} accessibilityRole="button" accessibilityState={{ selected }} > {modifier.label} {modifier.glyph ? ( {modifier.glyph} ) : null} ) })} {t('components.customKeyModal.key', 'Key')} [styles.moreLink, pressed && styles.moreLinkPressed]} onPress={() => setStep('special-keys')} > {t('components.customKeyModal.moreKeys', 'More keys — Tab, arrows, F1–F12…')} [ styles.saveButton, !shortcutPreview && styles.saveButtonDisabled, pressed && pressedStyle ]} disabled={!shortcutPreview} onPress={handleShortcutSave} > {t('components.customKeyModal.add', 'Add')} )} {step === 'special-keys' && ( {specialKeyGroups(t).map((group) => ( {group.title} {group.ids.map((id) => { const key = SPECIAL_KEY_BY_ID[id] if (!key) { return null } const selected = shortcutKey === id const flexBasis = `${100 / group.columns}%` as const return ( [ styles.keyCell, selected && styles.keyCellSelected, pressed && !selected && styles.keyCellPressed ]} onPress={() => handleSpecialKeyPick(id)} accessibilityLabel={key.accessibilityLabel} accessibilityState={{ selected }} > {key.label} ) })} ))} )} {step === 'text-macro' && ( {t('components.customKeyModal.label', 'Label')} {t('components.customKeyModal.command', 'Command')} {t('components.customKeyModal.pressEnter', 'Press Enter')} [ styles.saveButton, !macroText.trim() && styles.saveButtonDisabled, pressed && pressedStyle ]} disabled={!macroText.trim()} onPress={handleMacroSave} > {t('components.customKeyModal.addShortcut', 'Add Shortcut')} )} ) }