feat(keybinding): several shortcuts per action, mouse buttons, searchable picker

Shortcuts were defined in four places that drifted apart: per-action IPC channel
pairs, a hand-written VK table in the service, a second one in the renderer, and
three copies of the keycap styling. Adding an action meant editing all of them,
so two shortcuts stayed hardcoded in bootstrap and one had no settings entry at
all.

packages/core/src/keybinding.ts is now the single source for the binding type,
the selectable key catalog, the action catalog, normalization, validation,
conflict detection, display labels, search and deserialization. Main, preload
and renderer all read from it; nothing redefines keys or rules locally.

- Each action holds a list of bindings instead of one. AppConfig's four
  *Shortcut fields collapse into a single keyBindings map, migrated on launch.
- Mouse buttons can be bound. Left click is refused, right/middle need a
  modifier, side buttons are free. uiohook cannot swallow events, so the
  original click still fires and the UI says so.
- Keys can be picked from a grouped dropdown with a search box, not only by
  recording a keypress.
- HOTKEY's 14 channels become KEYBINDING's 9, taking the action as a parameter,
  so actions no longer multiply channels. The history and command popups moved
  out of bootstrap into ordinary actions.
- displayLabel is gone; labels derive from the binding and follow the app
  language and platform.

Fixes found on the way:
- Double-press hands-free was unreachable: lookup returned only the first
  matching action, and dictation shares its default binding.
- Reserved-combination checks compared joined key names, so a different modifier
  order let Ctrl+C through.
- Disabling shortcuts released every global registration in the process,
  including the popup ones, and never restored them.
- Enabling shortcuts after starting disabled left nothing registered.
- The dashboard stored the caption event payload instead of the state in it.
This commit is contained in:
Yun Chan 2026-09-21 13:41:47 +09:00
parent 0ca9e242fa
commit 4ad1ae6ed4
49 changed files with 5901 additions and 1792 deletions

View file

@ -1,315 +0,0 @@
// src/renderer/components/HotkeyRecordModal.tsx
// Speakly HotkeyRecordModal 패턴: Modal → 키 입력 대기 → Chip 표시 → 저장/취소
// 조합키: modifier(Ctrl/Alt/Shift) 누른 상태에서 일반키 입력 → 조합 완성
// 단일키: modifier만 눌렀다 놓으면 해당 modifier가 단독 핫키로 등록
import { useState, useEffect, useCallback, useRef } from 'react'
import {
Dialog,
DialogTitle,
DialogContent,
DialogActions,
Box,
Button,
Chip,
Stack,
Typography,
} from '@mui/material'
import { d3roPalette, d3roRadius, d3roTypo } from '@d3ro/ui/theme'
import { useI18n } from '@d3ro/i18n'
import type { HotkeyBinding } from '@d3ro/core/types'
import { formatHotkeyLabel, getPlatform, keyCodeToName } from '../utils/format-hotkey'
// 시스템 예약 조합
const RESERVED_COMBOS = [
'Ctrl+C', 'Ctrl+V', 'Ctrl+X', 'Ctrl+Z', 'Ctrl+A', 'Ctrl+S', 'Ctrl+W',
'Alt+F4', 'Alt+Tab', 'Ctrl+Alt+Delete',
]
const MODIFIER_KEYCODES = new Set([16, 17, 18, 91, 92, 160, 161, 162, 163, 164, 165])
function getKeyName(keyCode: number, key: string): string {
// 플랫폼별 라벨 (macOS는 ⌘/⇧/⌃/⌥). format-hotkey.ts의 단일 매핑을 사용.
const platform = getPlatform()
const mapped = keyCodeToName(keyCode, platform)
if (mapped && !mapped.startsWith('Key')) return mapped
if (key.length === 1) return key.toUpperCase()
return key
}
function isModifier(keyCode: number): boolean {
return MODIFIER_KEYCODES.has(keyCode)
}
interface HotkeyRecordModalProps {
open: boolean
onClose: () => void
onSave: (binding: HotkeyBinding) => void
currentBinding?: HotkeyBinding | null
title?: string
}
export function HotkeyRecordModal({
open,
onClose,
onSave,
currentBinding,
title,
}: HotkeyRecordModalProps): React.ReactElement {
const { t } = useI18n()
// 현재 눌려있는 키들을 실시간 추적
const [pressedKeys, setPressedKeys] = useState<Array<{ keyCode: number; name: string }>>([])
// 확정된 조합 (녹화 완료 후)
const [captured, setCaptured] = useState<Array<{ keyCode: number; name: string }> | null>(null)
const [error, setError] = useState<string | null>(null)
const pressedRef = useRef<Map<number, string>>(new Map())
// modifier-only 확정을 위한 타이머 (Alt만 눌렀을 때 바로 확정하지 않고 잠시 대기)
const modifierTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
// 가장 최근 pressedKeys 스냅샷 (타이머 콜백에서 stale closure 방지)
const lastPressedRef = useRef<Array<{ keyCode: number; name: string }>>([])
// Modal 열릴 때 리셋
useEffect(() => {
if (open) {
setPressedKeys([])
setCaptured(null)
setError(null)
pressedRef.current.clear()
lastPressedRef.current = []
if (modifierTimerRef.current) {
clearTimeout(modifierTimerRef.current)
modifierTimerRef.current = null
}
}
}, [open])
const handleKeyDown = useCallback((e: KeyboardEvent) => {
if (captured) return // 이미 확정됨
e.preventDefault()
e.stopPropagation()
// 새 키가 눌렸으므로 modifier-only 타이머 취소
if (modifierTimerRef.current) {
clearTimeout(modifierTimerRef.current)
modifierTimerRef.current = null
}
const keyCode = e.keyCode || e.which
if (pressedRef.current.has(keyCode)) return
const name = getKeyName(keyCode, e.key)
pressedRef.current.set(keyCode, name)
const keys = Array.from(pressedRef.current.entries()).map(([kc, n]) => ({ keyCode: kc, name: n }))
setPressedKeys(keys)
lastPressedRef.current = keys
// modifier가 아닌 키가 눌리면 → 조합 즉시 확정 (Alt+1, Ctrl+F5 등)
if (!isModifier(keyCode)) {
setCaptured(keys)
}
}, [captured])
const handleKeyUp = useCallback((e: KeyboardEvent) => {
if (captured) return // 이미 확정됨
const keyCode = e.keyCode || e.which
pressedRef.current.delete(keyCode)
// 모든 키를 놓았고 modifier만 눌렀었다면 → 500ms 대기 후 확정
// 이 대기 시간 동안 추가 키를 누르면 타이머가 취소되어 조합키로 확장 가능
if (pressedRef.current.size === 0 && lastPressedRef.current.length > 0 && lastPressedRef.current.every(k => isModifier(k.keyCode))) {
if (modifierTimerRef.current) clearTimeout(modifierTimerRef.current)
modifierTimerRef.current = setTimeout(() => {
// 타이머 만료: 여전히 confirmed 안됐고 추가 키 입력 없으면 단일 modifier로 확정
setCaptured(lastPressedRef.current)
modifierTimerRef.current = null
}, 500)
}
const keys = Array.from(pressedRef.current.entries()).map(([kc, n]) => ({ keyCode: kc, name: n }))
setPressedKeys(keys)
}, [captured])
useEffect(() => {
if (!open) return
window.addEventListener('keydown', handleKeyDown, true)
window.addEventListener('keyup', handleKeyUp, true)
return () => {
window.removeEventListener('keydown', handleKeyDown, true)
window.removeEventListener('keyup', handleKeyUp, true)
}
}, [open, handleKeyDown, handleKeyUp])
const displayKeys = captured ?? pressedKeys
const isReady = captured !== null && captured.length > 0
const handleSave = () => {
if (!captured || captured.length === 0) {
setError(t('hotkey.noKey'))
return
}
// 예약 단축키 체크
const label = captured.map(k => k.name).join('+')
if (RESERVED_COMBOS.includes(label)) {
setError(t('hotkey.reserved', { keys: label }))
handleReset()
return
}
// HotkeyBinding 생성
// 주 키(main key) = modifier가 아닌 키가 있으면 그것, 없으면 첫 번째 modifier
const mainKey = captured.find(k => !isModifier(k.keyCode))
const primaryKeyCode = mainKey?.keyCode ?? captured[0].keyCode
// modifier 플래그: 주 키 자체가 해당 modifier인 경우 false 유지
// 예: Right Alt 단독 → keyCode=165, alt=false (주 키가 Alt 자체이므로)
// 예: Ctrl+A → keyCode=A, ctrl=true (Ctrl은 modifier로 사용)
const isCtrlKey = (kc: number) => kc === 17 || kc === 162 || kc === 163
const isAltKey = (kc: number) => kc === 18 || kc === 164 || kc === 165
const isShiftKey = (kc: number) => kc === 16 || kc === 160 || kc === 161
const isMetaKey = (kc: number) => kc === 91 || kc === 92
// 주 키를 제외한 나머지 키들만 modifier로 취급
const modifierKeys = captured.filter(k => k.keyCode !== primaryKeyCode)
const binding: HotkeyBinding = {
keyCode: primaryKeyCode,
ctrl: modifierKeys.some(k => isCtrlKey(k.keyCode)),
alt: modifierKeys.some(k => isAltKey(k.keyCode)),
shift: modifierKeys.some(k => isShiftKey(k.keyCode)),
meta: modifierKeys.some(k => isMetaKey(k.keyCode)),
displayLabel: label,
}
onSave(binding)
onClose()
}
const handleReset = () => {
setPressedKeys([])
setCaptured(null)
pressedRef.current.clear()
}
const handleCancel = () => {
handleReset()
onClose()
}
return (
<Dialog
open={open}
onClose={handleCancel}
maxWidth="xs"
fullWidth
// aria-hidden 에러 방지: disableEnforceFocus + disableAutoFocus
disableEnforceFocus
disableAutoFocus
disableRestoreFocus
>
<DialogTitle sx={{ fontWeight: 500, fontSize: d3roTypo.heading.size }}>{title ?? t('hotkey.title')}</DialogTitle>
<DialogContent>
{/* 녹화 영역 */}
<Box
sx={{
border: `2px solid ${
error
? d3roPalette.tag.red
: isReady
? d3roPalette.tag.green
: displayKeys.length > 0
? d3roPalette.accent.main
: d3roPalette.border.strong
}`,
borderRadius: d3roRadius.inner,
p: 3,
minHeight: 80,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
bgcolor: d3roPalette.bg.inset,
transition: 'border-color 0.2s ease',
}}
>
{displayKeys.length > 0 ? (
<Stack direction="row" spacing={1} flexWrap="wrap" justifyContent="center">
{displayKeys.map((key, i) => (
<Chip
key={`${key.keyCode}-${i}`}
label={key.name}
sx={{
fontWeight: 500,
fontSize: '14px',
bgcolor: d3roPalette.bg.chassis,
color: d3roPalette.text.primary,
border: `1px solid ${d3roPalette.border.default}`,
borderRadius: '8px',
height: 40,
px: 1,
}}
/>
))}
</Stack>
) : (
<Typography
sx={{
color: d3roPalette.accent.main,
fontSize: '13px',
textAlign: 'center',
}}
>
{t('hotkey.prompt')}
</Typography>
)}
</Box>
{/* 상태 표시 */}
{isReady && !error && (
<Typography sx={{ color: d3roPalette.tag.green, fontSize: '12px', mt: 1, fontWeight: 600 }}>
{t('hotkey.ready', {
keys:
captured
?.map((k) => k.name)
.join(getPlatform() === 'darwin' ? '' : ' + ') ?? ''
})}
</Typography>
)}
{error && (
<Typography sx={{ color: d3roPalette.tag.red, fontSize: '12px', mt: 1 }}>
{error}
</Typography>
)}
{currentBinding && (
<Typography sx={{ color: d3roPalette.text.inactive, fontSize: '12px', mt: 2 }}>
{t('hotkey.current', { keys: formatHotkeyLabel(currentBinding) })}
</Typography>
)}
<Typography sx={{ color: d3roPalette.text.muted, fontSize: '11px', mt: 1 }}>
{t('hotkey.hint')}
</Typography>
</DialogContent>
<DialogActions sx={{ px: 3, pb: 2 }}>
<Button onClick={handleCancel} sx={{ color: d3roPalette.text.inactive }}>
{t('common.cancel')}
</Button>
{isReady && (
<Button onClick={handleReset} sx={{ color: d3roPalette.text.inactive }}>
{t('hotkey.reset')}
</Button>
)}
<Button
variant="contained"
onClick={handleSave}
disabled={!isReady}
>
{t('common.save')}
</Button>
</DialogActions>
</Dialog>
)
}

View file

@ -20,21 +20,21 @@ import {
InputLabel,
FormControl,
Button,
Chip,
Stack,
Paper,
} from '@mui/material'
import { X, Keyboard, Pencil, Mic, Lock, Cloud, RefreshCw, Play, Cpu, HelpCircle } from 'lucide-react'
import { X, Keyboard, Mic, Lock, Cloud, RefreshCw, Play, Cpu, HelpCircle } from 'lucide-react'
import { d3roPalette, d3roFontMono, d3roShadow, d3roRadius, d3roTypo } from '@d3ro/ui/theme'
import { Led } from '@d3ro/ui/components/ds'
import { HotkeyRecordModal } from './HotkeyRecordModal'
import { formatHotkeyLabel, formatHotkeySegments } from '../utils/format-hotkey'
import { LicenseTab } from './LicenseTab'
import { CloudSyncSection } from './CloudSyncSection'
import { STTTab } from './STTTab'
import { KeyBindingField } from './keybinding/KeyBindingField'
import { asTranslationKey } from './keybinding/translation-key'
import { useI18n, LOCALE_META } from '@d3ro/i18n'
import type { Locale } from '@d3ro/i18n'
import type { ThemeMode, AppConfig, HotkeyBinding, AudioDevice, LLMModel, LLMStatus } from '@d3ro/core/types'
import type { KeyBindingActionGroup } from '@d3ro/core/keybinding'
import { KEYBINDING_ACTIONS } from '@d3ro/core/keybinding'
import type { ThemeMode, AppConfig, AudioDevice, LLMModel, LLMStatus } from '@d3ro/core/types'
interface SettingsModalProps {
open: boolean
@ -53,135 +53,13 @@ function TabPanel({ children, value, index }: TabPanelProps): React.ReactElement
return <Box sx={{ pt: 2 }}>{children}</Box>
}
// ── 핫키 표시 컴포넌트 ──────────────────────────────────
function HotkeyDisplay({
binding,
onEdit,
label,
notSetLabel,
}: {
binding: HotkeyBinding | null
onEdit: () => void
label: string
notSetLabel: string
}): React.ReactElement {
return (
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
<Typography variant="body2" sx={{ color: d3roPalette.text.secondary, minWidth: 40 }}>
{label}
</Typography>
{binding ? (
<Stack direction="row" spacing={0.5} alignItems="center">
{formatHotkeySegments(binding).map((key, idx) => (
<Chip
key={`${key}-${idx}`}
label={key}
size="small"
sx={{
fontWeight: 500,
fontSize: d3roTypo.label.size,
bgcolor: d3roPalette.bg.elevated,
color: d3roPalette.text.primary,
border: `1px solid ${d3roPalette.border.default}`,
borderRadius: d3roRadius.xs,
height: 28,
}}
/>
))}
</Stack>
) : (
<Typography variant="body2" sx={{ color: d3roPalette.text.disabled }}>
{notSetLabel}
</Typography>
)}
<IconButton size="small" onClick={onEdit} sx={{ color: d3roPalette.text.inactive, ml: 'auto' }}>
<Pencil size={16} />
</IconButton>
</Box>
)
// ── 액션 그룹 섹션 ─────────────────────────────────────
const ACTION_GROUP_LABEL_KEYS: Readonly<Record<KeyBindingActionGroup, string>> = {
voice: 'keybinding.ui.sectionVoice',
window: 'keybinding.ui.sectionWindow',
}
// ── 음성 모드 카드 ──────────────────────────────────────
function VoiceModeCard({
title,
description,
enabled,
onToggle,
disabled,
enabledLabel,
disabledLabel,
children,
}: {
title: string
description: string
enabled: boolean
onToggle: (enabled: boolean) => void
disabled?: boolean
enabledLabel: string
disabledLabel: string
children?: React.ReactNode
}): React.ReactElement {
return (
<Paper
elevation={0}
sx={{
p: 2,
bgcolor: d3roPalette.bg.inset,
borderRadius: '10px',
border: 'none',
boxShadow: d3roShadow.inset,
}}
>
<Box sx={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between' }}>
<Box sx={{ flex: 1 }}>
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 0.5 }}>
<Typography
variant="subtitle2"
sx={{ fontWeight: 500, fontFamily: d3roFontMono, fontSize: d3roTypo.small.size, letterSpacing: '0.5px' }}
>
{title}
</Typography>
<FormControlLabel
control={
<Switch
checked={enabled}
onChange={(e) => onToggle(e.target.checked)}
disabled={disabled}
size="small"
sx={{
'& .MuiSwitch-switchBase.Mui-checked': { color: d3roPalette.tag.green },
'& .MuiSwitch-switchBase.Mui-checked + .MuiSwitch-track': {
backgroundColor: d3roPalette.tag.green,
},
}}
/>
}
label={
<Chip
label={enabled ? enabledLabel : disabledLabel}
size="small"
sx={{
fontSize: '10px', // P4: 토큰에 없는 10px 보존
fontWeight: 500,
height: 20,
bgcolor: enabled ? d3roPalette.tag.greenBg : 'transparent',
color: enabled ? d3roPalette.tag.green : d3roPalette.text.disabled,
border: enabled ? 'none' : `1px solid ${d3roPalette.border.subtle}`,
}}
/>
}
sx={{ ml: 0, mr: 0 }}
/>
</Box>
<Typography variant="body2" sx={{ color: d3roPalette.text.inactive, fontSize: d3roTypo.label.size }}>
{description}
</Typography>
</Box>
</Box>
{children && <Box sx={{ mt: 1.5 }}>{children}</Box>}
</Paper>
)
}
const ACTION_GROUP_ORDER: readonly KeyBindingActionGroup[] = ['voice', 'window']
export function SettingsModal({ open, initialTab = 0, onClose }: SettingsModalProps): React.ReactElement {
const { t, locale, setLocale } = useI18n()
@ -213,18 +91,8 @@ export function SettingsModal({ open, initialTab = 0, onClose }: SettingsModalPr
}
}, [open])
// 음성 모드 상태
const [dictationEnabled, setDictationEnabled] = useState(true)
const [dictationBinding, setDictationBinding] = useState<HotkeyBinding | null>(null)
const [handsFreeEnabled, setHandsFreeEnabled] = useState(false)
const [handsFreeBinding, setHandsFreeBinding] = useState<HotkeyBinding | null>(null)
const [captionBinding, setCaptionBinding] = useState<HotkeyBinding | null>(null)
const [, setHotkeyGlobalEnabled] = useState(true)
// 핫키 녹화 모달
const [hotkeyModalOpen, setHotkeyModalOpen] = useState(false)
const [hotkeyModalTarget, setHotkeyModalTarget] = useState<'dictation' | 'handsFree' | 'caption'>('dictation')
// 전역 단축키 on/off (개별 바인딩은 KeyBindingField 가 담당한다)
const [keybindingEnabled, setKeybindingEnabled] = useState(true)
// 오디오 디바이스
const [audioDevices, setAudioDevices] = useState<AudioDevice[]>([])
@ -261,20 +129,11 @@ export function SettingsModal({ open, initialTab = 0, onClose }: SettingsModalPr
Promise.all([
window.electronAPI.config.getAll(),
window.electronAPI.hotkey.getDictationShortcut(),
window.electronAPI.hotkey.getHandsFreeShortcut(),
window.electronAPI.hotkey.getCaptionShortcut(),
window.electronAPI.hotkey.isEnabled(),
window.electronAPI.keybinding.isEnabled(),
])
.then(([configResult, dictResult, hfResult, capResult, enabledResult]) => {
.then(([configResult, enabledResult]) => {
if (configResult.success) setConfig(configResult.data)
if (dictResult.success && dictResult.data) setDictationBinding(dictResult.data)
if (hfResult.success && hfResult.data) setHandsFreeBinding(hfResult.data)
if (capResult.success && capResult.data) setCaptionBinding(capResult.data)
if (enabledResult.success) {
setHotkeyGlobalEnabled(enabledResult.data)
setDictationEnabled(enabledResult.data)
}
if (enabledResult.success) setKeybindingEnabled(enabledResult.data)
})
.finally(() => setLoading(false))
@ -293,48 +152,9 @@ export function SettingsModal({ open, initialTab = 0, onClose }: SettingsModalPr
window.electronAPI.config.set({ key, value })
}, [])
const handleDictationToggle = useCallback(
(enabled: boolean) => {
setDictationEnabled(enabled)
window.electronAPI.hotkey.setEnabled({ enabled })
if (!enabled && handsFreeEnabled) {
setHandsFreeEnabled(false)
}
},
[handsFreeEnabled]
)
const handleHandsFreeToggle = useCallback((enabled: boolean) => {
if (enabled && !handsFreeBinding) {
setHotkeyModalTarget('handsFree')
setHotkeyModalOpen(true)
return
}
setHandsFreeEnabled(enabled)
}, [handsFreeBinding])
const handleHotkeySave = useCallback(
(binding: HotkeyBinding) => {
if (hotkeyModalTarget === 'dictation') {
setDictationBinding(binding)
window.electronAPI.hotkey.setDictationShortcut({ binding })
setDictationEnabled(true)
window.electronAPI.hotkey.setEnabled({ enabled: true })
} else if (hotkeyModalTarget === 'handsFree') {
setHandsFreeBinding(binding)
window.electronAPI.hotkey.setHandsFreeShortcut({ binding })
setHandsFreeEnabled(true)
} else {
setCaptionBinding(binding)
window.electronAPI.hotkey.setCaptionShortcut({ binding })
}
},
[hotkeyModalTarget]
)
const openHotkeyModal = useCallback((target: 'dictation' | 'handsFree' | 'caption') => {
setHotkeyModalTarget(target)
setHotkeyModalOpen(true)
const handleKeybindingToggle = useCallback((enabled: boolean) => {
setKeybindingEnabled(enabled)
void window.electronAPI.keybinding.setEnabled({ enabled })
}, [])
const handleLanguageChange = useCallback((newLocale: string) => {
@ -418,73 +238,48 @@ export function SettingsModal({ open, initialTab = 0, onClose }: SettingsModalPr
{/* ── 일반 탭 ─────────────────────────────── */}
<TabPanel value={activeTab} index={0}>
<Box sx={{ display: 'flex', flexDirection: 'column', gap: 2.5 }}>
<Typography variant="overline" sx={{ color: d3roPalette.text.label, letterSpacing: '1.5px' }}>
{t('settings.shortcuts')}
</Typography>
<Stack spacing={1.5}>
<VoiceModeCard
title={t('settings.dictation')}
description={t('settings.dictation.desc')}
enabled={dictationEnabled}
onToggle={handleDictationToggle}
enabledLabel={t('settings.enabled')}
disabledLabel={t('settings.disabled')}
>
<HotkeyDisplay
binding={dictationBinding}
onEdit={() => openHotkeyModal('dictation')}
label={t('settings.key')}
notSetLabel={t('settings.notSet')}
/>
</VoiceModeCard>
<VoiceModeCard
title={t('settings.agent')}
description={
dictationBinding
? t('settings.agent.descWithKey', { key: formatHotkeyLabel(dictationBinding) })
: t('settings.agent.descNoKey')
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
<Typography variant="overline" sx={{ color: d3roPalette.text.label, letterSpacing: '1.5px' }}>
{t('settings.shortcuts')}
</Typography>
<FormControlLabel
sx={{ ml: 'auto', mr: 0 }}
control={
<Switch
size="small"
checked={keybindingEnabled}
onChange={(e) => handleKeybindingToggle(e.target.checked)}
/>
}
label={
<Typography sx={{ fontSize: d3roTypo.label.size, color: d3roPalette.text.secondary }}>
{t('keybinding.ui.globalEnabled')}
</Typography>
}
enabled={dictationEnabled}
onToggle={handleDictationToggle}
disabled={!dictationEnabled}
enabledLabel={t('settings.enabled')}
disabledLabel={t('settings.disabled')}
/>
</Box>
<VoiceModeCard
title={t('settings.oneTouch')}
description={t('settings.oneTouch.desc')}
enabled={handsFreeEnabled}
onToggle={handleHandsFreeToggle}
disabled={!dictationEnabled}
enabledLabel={t('settings.enabled')}
disabledLabel={t('settings.disabled')}
>
<HotkeyDisplay
binding={handsFreeBinding}
onEdit={() => openHotkeyModal('handsFree')}
label={t('settings.key')}
notSetLabel={t('settings.notSet')}
/>
</VoiceModeCard>
<VoiceModeCard
title={t('settings.caption')}
description={t('settings.caption.desc')}
enabled={true}
enabledLabel={t('settings.enabled')}
disabledLabel={t('settings.disabled')}
>
<HotkeyDisplay
binding={captionBinding}
onEdit={() => openHotkeyModal('caption')}
label={t('settings.key')}
notSetLabel={t('settings.notSet')}
/>
</VoiceModeCard>
</Stack>
{ACTION_GROUP_ORDER.map((group) => {
const actions = KEYBINDING_ACTIONS.filter((action) => action.group === group)
if (actions.length === 0) return null
return (
<Box key={group} sx={{ display: 'flex', flexDirection: 'column', gap: 1.25 }}>
<Typography
sx={{
color: d3roPalette.text.dimLabel,
fontSize: d3roTypo.engrave.size,
letterSpacing: '0.1em',
textTransform: 'uppercase',
}}
>
{t(asTranslationKey(ACTION_GROUP_LABEL_KEYS[group]))}
</Typography>
{actions.map((action) => (
<KeyBindingField key={action.id} actionId={action.id} />
))}
</Box>
)
})}
<Divider sx={{ borderColor: d3roPalette.border.subtle }} />
@ -981,14 +776,6 @@ export function SettingsModal({ open, initialTab = 0, onClose }: SettingsModalPr
</Box>
</DialogContent>
</Dialog>
<HotkeyRecordModal
open={hotkeyModalOpen}
onClose={() => setHotkeyModalOpen(false)}
onSave={handleHotkeySave}
currentBinding={hotkeyModalTarget === 'dictation' ? dictationBinding : hotkeyModalTarget === 'handsFree' ? handsFreeBinding : captionBinding}
title={hotkeyModalTarget === 'dictation' ? t('hotkey.dictationTitle') : hotkeyModalTarget === 'handsFree' ? t('hotkey.oneTouchTitle') : t('hotkey.captionTitle')}
/>
</>
)
}

View file

@ -0,0 +1,171 @@
// apps/desktop/src/renderer/components/keybinding/KeyBindingField.tsx
// 액션 하나의 바인딩 목록 전체를 담당한다. 앱에서 키바인딩을 다루는 유일한 진입점이다.
//
// 라벨 · 설명 · 기본값은 KEYBINDING_ACTIONS 에서 파생하므로 호출부는 actionId 만 넘긴다.
import { useCallback, useState } from 'react'
import { Box, IconButton, Tooltip, Typography } from '@mui/material'
import { Plus, RotateCcw, X } from 'lucide-react'
import { d3roPalette, d3roRadius, d3roShadow, d3roTypo } from '@d3ro/ui/theme'
import { TactileBadge } from '@d3ro/ui/components/ds'
import { useI18n } from '@d3ro/i18n'
import type { KeyBinding, KeyBindingActionId } from '@d3ro/core/keybinding'
import { bindingKey, bindingsEqual, findActionSpec } from '@d3ro/core/keybinding'
import { useKeyBindingMap } from '../../hooks/useKeyBindingMap'
import { BindingKeycaps, useBindingLabel } from './Keycap'
import { KeyBindingPicker } from './KeyBindingPicker'
import { asTranslationKey } from './translation-key'
interface KeyBindingFieldProps {
actionId: KeyBindingActionId
}
export function KeyBindingField({ actionId }: KeyBindingFieldProps): React.ReactElement | null {
const { t } = useI18n()
const map = useKeyBindingMap()
const bindingLabel = useBindingLabel()
const [pickerOpen, setPickerOpen] = useState(false)
const [failed, setFailed] = useState(false)
const spec = findActionSpec(actionId)
const bindings = map === null ? [] : (map[actionId] ?? [])
const commit = useCallback(
(next: KeyBinding[]) => {
void window.electronAPI.keybinding
.setBindings({ actionId, bindings: next })
.then((result) => setFailed(!result.success))
},
[actionId]
)
const handleAdd = useCallback(
(binding: KeyBinding) => {
commit([...bindings, binding])
},
[bindings, commit]
)
const handleRemove = useCallback(
(binding: KeyBinding) => {
commit(bindings.filter((existing) => !bindingsEqual(existing, binding)))
},
[bindings, commit]
)
const handleReset = useCallback(() => {
void window.electronAPI.keybinding
.resetAction({ actionId })
.then((result) => setFailed(!result.success))
}, [actionId])
if (spec === null) return null
return (
<Box
data-testid={`keybinding-field-${actionId}`}
sx={{
p: 2,
bgcolor: d3roPalette.bg.inset,
borderRadius: d3roRadius.inner,
boxShadow: d3roShadow.inset,
display: 'flex',
flexDirection: 'column',
gap: 1.25,
}}
>
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
<Typography
sx={{
fontSize: d3roTypo.compact.size,
fontWeight: 500,
color: d3roPalette.text.primary,
}}
>
{t(asTranslationKey(spec.labelKey))}
</Typography>
{spec.holdMode && <TactileBadge mono>{t('keybinding.ui.holdMode')}</TactileBadge>}
{spec.doublePress && <TactileBadge mono>{t('keybinding.ui.doublePress')}</TactileBadge>}
<Tooltip title={t('keybinding.ui.reset')}>
<IconButton
size="small"
onClick={handleReset}
sx={{ color: d3roPalette.text.inactive, ml: 'auto' }}
>
<RotateCcw size={14} />
</IconButton>
</Tooltip>
</Box>
<Typography sx={{ color: d3roPalette.text.inactive, fontSize: d3roTypo.label.size }}>
{t(asTranslationKey(spec.descriptionKey))}
</Typography>
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1, flexWrap: 'wrap' }}>
{bindings.length === 0 && (
<Typography sx={{ color: d3roPalette.text.disabled, fontSize: d3roTypo.small.size }}>
{t('keybinding.ui.noBindings')}
</Typography>
)}
{bindings.map((binding) => (
<Box
key={bindingKey(binding)}
data-testid="keybinding-binding"
sx={{
display: 'inline-flex',
alignItems: 'center',
gap: 0.5,
pr: 0.25,
borderRadius: d3roRadius.xs,
border: `1px solid ${d3roPalette.border.subtle}`,
}}
>
<BindingKeycaps binding={binding} size="sm" />
<IconButton
size="small"
data-testid="keybinding-remove"
onClick={() => handleRemove(binding)}
aria-label={t('keybinding.ui.remove', { keys: bindingLabel(binding) })}
sx={{ color: d3roPalette.text.inactive, p: 0.25 }}
>
<X size={12} />
</IconButton>
</Box>
))}
<IconButton
size="small"
data-testid={`keybinding-add-${actionId}`}
onClick={() => setPickerOpen(true)}
aria-label={t('keybinding.ui.add')}
sx={{
color: d3roPalette.accent.main,
border: `1px dashed ${d3roPalette.border.strong}`,
borderRadius: d3roRadius.xs,
px: 1,
height: 22,
}}
>
<Plus size={13} />
<Typography component="span" sx={{ ml: 0.5, fontSize: d3roTypo.label.size }}>
{t('keybinding.ui.add')}
</Typography>
</IconButton>
</Box>
{failed && (
<Typography sx={{ color: d3roPalette.tag.red, fontSize: d3roTypo.label.size }}>
{t('keybinding.ui.saveFailed')}
</Typography>
)}
<KeyBindingPicker
open={pickerOpen}
actionId={actionId}
existingBindings={bindings}
onClose={() => setPickerOpen(false)}
onConfirm={handleAdd}
/>
</Box>
)
}

View file

@ -0,0 +1,696 @@
// apps/desktop/src/renderer/components/keybinding/KeyBindingPicker.tsx
// 바인딩 하나를 고르는 모달. 입력 방식이 두 가지다.
//
// 녹화 탭 — 실제로 키(또는 마우스 버튼)를 눌러 캡처한다.
// 목록 탭 — 검색 인풋이 달린 드롭다운에서 고르고 수정자를 토글한다.
//
// 키 목록 · 라벨 · 검증 · 충돌 판정은 전부 @d3ro/core/keybinding 이 정본이다.
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import {
Autocomplete,
Box,
ButtonBase,
Dialog,
DialogActions,
DialogContent,
DialogTitle,
TextField,
Typography,
} from '@mui/material'
import type { AutocompleteRenderGroupParams } from '@mui/material'
import { Keyboard, ListFilter, MousePointerClick } from 'lucide-react'
import { d3roFontMono, d3roPalette, d3roRadius, d3roShadow, d3roTypo } from '@d3ro/ui/theme'
import { PhysicalButton, SegmentControl } from '@d3ro/ui/components/ds'
import { useI18n } from '@d3ro/i18n'
import type {
BindingPlatform,
KeyBinding,
KeyBindingActionId,
KeyBindingValidationResult,
KeyCatalogEntry,
} from '@d3ro/core/keybinding'
import {
KEY_CATALOG,
KEY_CATALOG_GROUP_LABEL_KEYS,
KEY_CATALOG_GROUP_ORDER,
MouseButton,
VK,
bindingsEqual,
findActionSpec,
formatBindingSegments,
isModifierKeyCode,
normalizeBinding,
searchKeyCatalog,
validateBinding,
} from '@d3ro/core/keybinding'
import { getPlatform } from '../../utils/format-hotkey'
import { BindingKeycaps, Keycap } from './Keycap'
import { asTranslationKey } from './translation-key'
type PickerMode = 'record' | 'list'
interface ModifierState {
ctrl: boolean
alt: boolean
shift: boolean
meta: boolean
}
const NO_MODIFIERS: ModifierState = { ctrl: false, alt: false, shift: false, meta: false }
const MODIFIER_SLOTS = ['ctrl', 'alt', 'shift', 'meta'] as const
type ModifierSlot = (typeof MODIFIER_SLOTS)[number]
/** 단일 modifier 를 눌렀다 뗐을 때 조합으로 확장할 시간을 준다. */
const MODIFIER_COMMIT_DELAY_MS = 500
/**
* 브라우저 MouseEvent.button → libuiohook MOUSE_BUTTON 코드.
* 두 체계의 가운데/오른쪽 순서가 서로 다르므로 그대로 쓰면 안 된다.
*/
const BROWSER_BUTTON_TO_MOUSE: Readonly<Record<number, number>> = {
0: MouseButton.Left,
1: MouseButton.Middle,
2: MouseButton.Right,
3: MouseButton.Back,
4: MouseButton.Forward,
}
const GROUP_RANK: ReadonlyMap<string, number> = new Map(
KEY_CATALOG_GROUP_ORDER.map((group, index) => [group, index])
)
function byGroupOrder(a: KeyCatalogEntry, b: KeyCatalogEntry): number {
return (GROUP_RANK.get(a.group) ?? 0) - (GROUP_RANK.get(b.group) ?? 0)
}
const CATALOG_OPTIONS: readonly KeyCatalogEntry[] = [...KEY_CATALOG].sort(byGroupOrder)
/**
* 브라우저 KeyboardEvent 의 keyCode 를 Windows VK 로 맞춘다.
*
* keyCode 는 수정자를 좌/우 구분 없이 16/17/18 로 주는데 카탈로그는 좌/우 코드만 담고 있다.
* location 으로 보정하지 않으면 수정자 단독 바인딩이 전부 unknown-key 로 거부된다.
*/
function resolveKeyCode(event: KeyboardEvent): number {
const code = event.keyCode || event.which
const right = event.location === 2
if (code === 16) return right ? VK.ShiftRight : VK.ShiftLeft
if (code === 17) return right ? VK.CtrlRight : VK.CtrlLeft
if (code === 18) return right ? VK.AltRight : VK.AltLeft
// macOS 오른쪽 Command 는 93 으로 온다 (Windows 의 93 은 ContextMenu 라 구분이 필요하다).
if (code === 93 && right) return VK.MetaRight
return code
}
/**
* 눌린 키들 → 바인딩.
*
* 주 키는 수정자가 아닌 키가 있으면 그것, 없으면 **가장 나중에 누른** 수정자다.
* "Ctrl 누른 채 오른쪽 Alt" 가 `Ctrl + Right Alt` 로 잡히려면 마지막 것이어야 한다.
*/
function buildBinding(codes: readonly number[], mods: ModifierState): KeyBinding | null {
if (codes.length === 0) return null
const main = codes.find((code) => !isModifierKeyCode(code)) ?? codes[codes.length - 1]
return normalizeBinding({ device: 'keyboard', code: main, ...mods })
}
function probeBinding(slot: ModifierSlot): KeyBinding {
return {
device: 'keyboard',
code: VK.F1,
ctrl: slot === 'ctrl',
alt: slot === 'alt',
shift: slot === 'shift',
meta: slot === 'meta',
}
}
/** 수정자 토글에 붙일 표기 — 플랫폼 표기 규칙도 코어가 정본이다. */
function modifierLabel(slot: ModifierSlot, platform: BindingPlatform): string {
return formatBindingSegments(probeBinding(slot), platform)[0]?.label ?? ''
}
interface KeyBindingPickerProps {
open: boolean
actionId: KeyBindingActionId
/** 이 액션에 이미 걸려 있는 바인딩 — 같은 것을 두 번 추가하지 못하게 한다. */
existingBindings: readonly KeyBinding[]
onClose: () => void
onConfirm: (binding: KeyBinding) => void
}
export function KeyBindingPicker({
open,
actionId,
existingBindings,
onClose,
onConfirm,
}: KeyBindingPickerProps): React.ReactElement {
const { t } = useI18n()
const platform = getPlatform()
const [mode, setMode] = useState<PickerMode>('record')
const [recorded, setRecorded] = useState<KeyBinding | null>(null)
const [preview, setPreview] = useState<KeyBinding | null>(null)
const [listEntry, setListEntry] = useState<KeyCatalogEntry | null>(null)
const [listMods, setListMods] = useState<ModifierState>(NO_MODIFIERS)
const [remote, setRemote] = useState<KeyBindingValidationResult | null>(null)
const [remotePending, setRemotePending] = useState(false)
const pressedRef = useRef<Set<number>>(new Set())
const modsRef = useRef<ModifierState>(NO_MODIFIERS)
const pendingRef = useRef<{ codes: number[]; binding: KeyBinding } | null>(null)
const commitTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
const clearCommitTimer = useCallback(() => {
if (commitTimerRef.current !== null) {
clearTimeout(commitTimerRef.current)
commitTimerRef.current = null
}
}, [])
const resetRecording = useCallback(() => {
clearCommitTimer()
pressedRef.current.clear()
modsRef.current = NO_MODIFIERS
pendingRef.current = null
setRecorded(null)
setPreview(null)
}, [clearCommitTimer])
useEffect(() => {
if (!open) return
setMode('record')
setListEntry(null)
setListMods(NO_MODIFIERS)
setRemote(null)
setRemotePending(false)
resetRecording()
}, [open, actionId, resetRecording])
useEffect(() => clearCommitTimer, [clearCommitTimer])
// ── 키보드 녹화 ────────────────────────────────────────
const handleKeyDown = useCallback(
(event: KeyboardEvent) => {
if (recorded !== null) return
event.preventDefault()
event.stopPropagation()
clearCommitTimer()
const code = resolveKeyCode(event)
if (pressedRef.current.has(code)) return
pressedRef.current.add(code)
modsRef.current = {
ctrl: event.ctrlKey,
alt: event.altKey,
shift: event.shiftKey,
meta: event.metaKey,
}
const codes = [...pressedRef.current]
const binding = buildBinding(codes, modsRef.current)
if (binding === null) return
pendingRef.current = { codes, binding }
setPreview(binding)
// 수정자가 아닌 키가 들어오면 조합이 완성된 것이므로 즉시 확정한다.
if (!isModifierKeyCode(code)) setRecorded(binding)
},
[recorded, clearCommitTimer]
)
const handleKeyUp = useCallback(
(event: KeyboardEvent) => {
if (recorded !== null) return
pressedRef.current.delete(resolveKeyCode(event))
if (pressedRef.current.size > 0) return
const pending = pendingRef.current
if (pending === null) return
// 수정자만 눌렸다 놓인 경우에만 지연 확정한다. 그 사이 다른 키를 누르면 타이머가 취소되고
// 조합키로 확장된다.
if (!pending.codes.every(isModifierKeyCode)) return
clearCommitTimer()
commitTimerRef.current = setTimeout(() => {
setRecorded(pending.binding)
commitTimerRef.current = null
}, MODIFIER_COMMIT_DELAY_MS)
},
[recorded, clearCommitTimer]
)
useEffect(() => {
// 목록 탭에서는 검색 인풋에 타이핑해야 하므로 캡처를 걸지 않는다.
if (!open || mode !== 'record') return
window.addEventListener('keydown', handleKeyDown, true)
window.addEventListener('keyup', handleKeyUp, true)
return () => {
window.removeEventListener('keydown', handleKeyDown, true)
window.removeEventListener('keyup', handleKeyUp, true)
}
}, [open, mode, handleKeyDown, handleKeyUp])
// ── 마우스 녹화 ────────────────────────────────────────
const handleMouseDown = useCallback(
(event: React.MouseEvent<HTMLDivElement>) => {
if (recorded !== null) return
const code = BROWSER_BUTTON_TO_MOUSE[event.button]
if (code === undefined) return
event.preventDefault()
event.stopPropagation()
clearCommitTimer()
pressedRef.current.clear()
pendingRef.current = null
setPreview(null)
setRecorded(
normalizeBinding({
device: 'mouse',
code,
ctrl: event.ctrlKey,
alt: event.altKey,
shift: event.shiftKey,
meta: event.metaKey,
})
)
},
[recorded, clearCommitTimer]
)
// ── 후보 바인딩과 검증 ─────────────────────────────────
const candidate = useMemo((): KeyBinding | null => {
if (mode === 'record') return recorded
if (listEntry === null) return null
return normalizeBinding({ device: listEntry.device, code: listEntry.code, ...listMods })
}, [mode, recorded, listEntry, listMods])
const localValidation = useMemo(
() => (candidate === null ? null : validateBinding(candidate)),
[candidate]
)
useEffect(() => {
if (candidate === null || localValidation === null || !localValidation.valid) {
setRemote(null)
setRemotePending(false)
return
}
let cancelled = false
setRemotePending(true)
void window.electronAPI.keybinding
.validate({ actionId, binding: candidate })
.then((result) => {
if (cancelled) return
setRemote(result.success ? result.data : null)
setRemotePending(false)
})
return () => {
cancelled = true
}
}, [candidate, localValidation, actionId])
const conflicts = remote?.conflicts ?? []
const remoteValidation = remote?.validation ?? null
const isDuplicate =
candidate !== null && existingBindings.some((existing) => bindingsEqual(existing, candidate))
const rejectionKey = localValidation?.reasonKey ?? remoteValidation?.reasonKey ?? null
const warningKey = remoteValidation?.warningKey ?? localValidation?.warningKey ?? null
const canConfirm =
candidate !== null &&
!isDuplicate &&
localValidation?.valid === true &&
remoteValidation?.valid === true &&
conflicts.length === 0 &&
!remotePending
// ── 목록 탭 ────────────────────────────────────────────
const localizedLabels = useMemo(() => {
const out: Record<string, string> = {}
for (const entry of KEY_CATALOG) {
if (entry.labelKey === undefined) continue
out[`${entry.device}:${entry.code}`] = t(asTranslationKey(entry.labelKey))
}
return out
}, [t])
const entryText = useCallback(
(entry: KeyCatalogEntry): string =>
entry.labelKey === undefined ? entry.label : t(asTranslationKey(entry.labelKey)),
[t]
)
/** 키캡에 찍힐 표기 — formatBindingSegments() 가 확정 후에 쓰는 규칙과 같아야 한다. */
const entryKeycapText = useCallback(
(entry: KeyCatalogEntry): string => {
if (entry.labelKey !== undefined) return t(asTranslationKey(entry.labelKey))
return platform === 'darwin' ? (entry.macLabel ?? entry.label) : entry.label
},
[t, platform]
)
const actionSpec = findActionSpec(actionId)
const actionName = actionSpec === null ? '' : t(asTranslationKey(actionSpec.labelKey))
const handleConfirm = (): void => {
if (candidate === null || !canConfirm) return
onConfirm(candidate)
onClose()
}
const renderGroupSection = (params: AutocompleteRenderGroupParams): React.ReactElement => (
<li key={params.key}>
<Box
sx={{
position: 'sticky',
top: 0,
zIndex: 1,
px: 1.5,
py: 0.75,
bgcolor: d3roPalette.bg.inset,
color: d3roPalette.text.label,
fontSize: d3roTypo.engrave.size,
fontWeight: 500,
letterSpacing: '0.1em',
textTransform: 'uppercase',
borderBottom: `1px solid ${d3roPalette.border.subtle}`,
}}
>
{t(
asTranslationKey(
KEY_CATALOG_GROUP_LABEL_KEYS[params.group as keyof typeof KEY_CATALOG_GROUP_LABEL_KEYS]
)
)}
</Box>
<Box component="ul" sx={{ p: 0, m: 0, listStyle: 'none' }}>
{params.children}
</Box>
</li>
)
return (
<Dialog
open={open}
onClose={onClose}
maxWidth="xs"
fullWidth
data-testid="keybinding-picker"
disableEnforceFocus
disableRestoreFocus
PaperProps={{
sx: {
bgcolor: d3roPalette.bg.chassis,
backgroundImage: 'none',
border: `1px solid ${d3roPalette.border.subtle}`,
borderRadius: d3roRadius.card,
},
}}
>
<DialogTitle sx={{ fontWeight: 500, fontSize: d3roTypo.heading.size, pb: 1.5 }}>
{t('keybinding.ui.pickerTitle', { action: actionName })}
</DialogTitle>
<DialogContent sx={{ display: 'flex', flexDirection: 'column', gap: 2, pb: 1 }}>
<Box
data-testid="keybinding-picker-tabs"
sx={{ display: 'flex', justifyContent: 'center' }}
>
<SegmentControl<PickerMode>
value={mode}
onChange={setMode}
size="small"
options={[
{ value: 'record', label: t('keybinding.ui.tabRecord'), icon: <Keyboard size={14} /> },
{ value: 'list', label: t('keybinding.ui.tabList'), icon: <ListFilter size={14} /> },
]}
/>
</Box>
{mode === 'record' ? (
<Box
data-testid="keybinding-record-area"
onMouseDown={handleMouseDown}
onContextMenu={(event) => event.preventDefault()}
sx={{
border: `2px solid ${
rejectionKey !== null
? d3roPalette.tag.red
: recorded !== null
? d3roPalette.tag.green
: preview !== null
? d3roPalette.accent.main
: d3roPalette.border.strong
}`,
borderRadius: d3roRadius.inner,
bgcolor: d3roPalette.bg.inset,
p: 3,
minHeight: 104,
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
gap: 1.25,
cursor: 'pointer',
userSelect: 'none',
transition: 'border-color 0.2s ease',
}}
>
{candidate !== null ? (
<BindingKeycaps binding={candidate} size="lg" />
) : preview !== null ? (
<BindingKeycaps binding={preview} size="lg" />
) : (
<>
<MousePointerClick size={18} color={d3roPalette.accent.main} />
<Typography
sx={{
color: d3roPalette.accent.main,
fontSize: d3roTypo.compact.size,
textAlign: 'center',
}}
>
{t('keybinding.ui.pressKeys')}
</Typography>
</>
)}
</Box>
) : (
<Box sx={{ display: 'flex', flexDirection: 'column', gap: 1.75 }}>
<Box
sx={{
border: `1px solid ${d3roPalette.border.default}`,
borderRadius: d3roRadius.inner,
bgcolor: d3roPalette.bg.inset,
px: 2,
py: 1.75,
display: 'flex',
flexDirection: 'column',
gap: 1.25,
}}
>
<Typography
sx={{
color: d3roPalette.text.label,
fontSize: d3roTypo.engrave.size,
letterSpacing: '0.1em',
textTransform: 'uppercase',
}}
>
{t('keybinding.ui.modifiers')}
</Typography>
<Box sx={{ display: 'flex', gap: 1, flexWrap: 'wrap' }}>
{MODIFIER_SLOTS.map((slot) => {
const active = listMods[slot]
return (
<ButtonBase
key={slot}
onClick={() => setListMods((prev) => ({ ...prev, [slot]: !prev[slot] }))}
sx={{
borderRadius: d3roRadius.xs,
px: 1.25,
height: 30,
fontFamily: d3roFontMono,
fontSize: d3roTypo.small.size,
fontWeight: 500,
letterSpacing: '0.04em',
color: active ? d3roPalette.text.primary : d3roPalette.text.inactive,
bgcolor: active ? d3roPalette.accent.dim : d3roPalette.bg.chassis,
border: `1px solid ${
active ? d3roPalette.accent.main : d3roPalette.border.default
}`,
boxShadow: active ? d3roShadow.inset : 'none',
transition: 'all 0.15s ease',
}}
>
{modifierLabel(slot, platform)}
</ButtonBase>
)
})}
</Box>
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1, minHeight: 30 }}>
<Typography
sx={{ color: d3roPalette.text.inactive, fontSize: d3roTypo.small.size }}
>
{t('keybinding.ui.selectedKey')}
</Typography>
{candidate !== null && <BindingKeycaps binding={candidate} size="md" />}
</Box>
</Box>
<Autocomplete<KeyCatalogEntry, false, false, false>
open
options={CATALOG_OPTIONS as KeyCatalogEntry[]}
value={listEntry}
onChange={(_, value) => setListEntry(value)}
groupBy={(option) => option.group}
getOptionLabel={entryText}
getOptionDisabled={(option) => option.disabledReasonKey !== undefined}
isOptionEqualToValue={(a, b) => a.device === b.device && a.code === b.code}
filterOptions={(_, state) =>
[...searchKeyCatalog(state.inputValue, localizedLabels)].sort(byGroupOrder)
}
noOptionsText={t('keybinding.ui.searchEmpty')}
renderGroup={renderGroupSection}
renderOption={(props, option) => {
const { key, ...liProps } = props
const keycapText = entryKeycapText(option)
// 키캡에 찍히는 표기와 다를 때만 로케일 무관 원표기를 보조로 보여준다.
const secondary = keycapText === option.label ? null : option.label
return (
<Box
component="li"
key={key}
{...liProps}
data-testid="keybinding-key-option"
sx={{ display: 'flex', alignItems: 'center', gap: 1.25, py: 0.75 }}
>
<Keycap size="sm" muted={option.disabledReasonKey !== undefined}>
{keycapText}
</Keycap>
<Typography
sx={{
flex: 1,
minWidth: 0,
fontSize: d3roTypo.small.size,
color: d3roPalette.text.secondary,
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
}}
>
{secondary}
</Typography>
{option.disabledReasonKey !== undefined && (
<Typography
sx={{ fontSize: d3roTypo.nano.size, color: d3roPalette.text.disabled }}
>
{t(asTranslationKey(option.disabledReasonKey))}
</Typography>
)}
</Box>
)
}}
renderInput={(params) => (
<TextField
{...params}
size="small"
autoFocus
data-testid="keybinding-search"
placeholder={t('keybinding.ui.search')}
/>
)}
slotProps={{
popper: { placement: 'bottom-start', modifiers: [{ name: 'flip', enabled: false }] },
paper: {
sx: {
bgcolor: d3roPalette.bg.chassis,
backgroundImage: 'none',
border: `1px solid ${d3roPalette.border.default}`,
borderRadius: d3roRadius.inner,
boxShadow: d3roShadow.card,
},
},
listbox: { sx: { maxHeight: 260, py: 0 } },
}}
/>
</Box>
)}
<Box sx={{ minHeight: 34, display: 'flex', flexDirection: 'column', gap: 0.5 }}>
{rejectionKey !== null && (
<Typography
data-testid="keybinding-rejection"
sx={{ color: d3roPalette.tag.red, fontSize: d3roTypo.label.size }}
>
{t(asTranslationKey(rejectionKey))}
</Typography>
)}
{isDuplicate && (
<Typography
data-testid="keybinding-rejection"
sx={{ color: d3roPalette.tag.red, fontSize: d3roTypo.label.size }}
>
{t('keybinding.ui.duplicate')}
</Typography>
)}
{conflicts.map((conflict) => {
const spec = findActionSpec(conflict.actionId)
return (
<Typography
key={conflict.actionId}
data-testid="keybinding-rejection"
sx={{ color: d3roPalette.tag.red, fontSize: d3roTypo.label.size }}
>
{t('keybinding.ui.conflictWith', {
action: spec === null ? conflict.actionId : t(asTranslationKey(spec.labelKey)),
})}
</Typography>
)
})}
{rejectionKey === null && warningKey !== null && (
<Typography sx={{ color: d3roPalette.tag.orange, fontSize: d3roTypo.label.size }}>
{t(asTranslationKey(warningKey))}
</Typography>
)}
{mode === 'record' && candidate === null && (
<Typography sx={{ color: d3roPalette.text.muted, fontSize: d3roTypo.meta.size }}>
{t('keybinding.ui.recordHint')}
</Typography>
)}
</Box>
</DialogContent>
<DialogActions sx={{ px: 3, pb: 2.5, gap: 1 }}>
<PhysicalButton
tone="ghost"
data-testid="keybinding-cancel"
onClick={onClose}
sx={{ height: 34 }}
>
{t('common.cancel')}
</PhysicalButton>
{mode === 'record' && recorded !== null && (
<PhysicalButton
tone="glass"
data-testid="keybinding-record-again"
onClick={resetRecording}
sx={{ height: 34 }}
>
{t('keybinding.ui.recordAgain')}
</PhysicalButton>
)}
<PhysicalButton
tone="accent"
data-testid="keybinding-confirm"
onClick={handleConfirm}
disabled={!canConfirm}
sx={{ height: 34 }}
>
{t('common.save')}
</PhysicalButton>
</DialogActions>
</Dialog>
)
}

View file

@ -0,0 +1,116 @@
// apps/desktop/src/renderer/components/keybinding/Keycap.tsx
// 키캡 표기 SSOT. 대시보드 · 설정 · 피커가 전부 이 컴포넌트로 키를 그린다.
//
// 표기할 문자열은 @d3ro/core/keybinding 의 formatBindingSegments() 가 정본이다 —
// 여기서는 그리기만 한다.
import { Box } from '@mui/material'
import { d3roFontMono, d3roPalette, d3roRadius, d3roShadow, d3roTypo } from '@d3ro/ui/theme'
import { useI18n } from '@d3ro/i18n'
import type { BindingSegment, KeyBinding } from '@d3ro/core/keybinding'
import { formatBindingSegments, joinBindingSegments } from '@d3ro/core/keybinding'
import { getPlatform } from '../../utils/format-hotkey'
import { asTranslationKey } from './translation-key'
export type KeycapSize = 'sm' | 'md' | 'lg'
const SIZE_SPEC = {
sm: { height: 22, fontSize: d3roTypo.label.size, px: 0.85, radius: d3roRadius.xs },
md: { height: 28, fontSize: d3roTypo.small.size, px: 1.1, radius: d3roRadius.xs },
lg: { height: 38, fontSize: d3roTypo.body.size, px: 1.6, radius: d3roRadius.small },
} as const
interface KeycapProps {
children: React.ReactNode
size?: KeycapSize
/** 선택 불가 항목을 흐리게 표시 */
muted?: boolean
}
export function Keycap({ children, size = 'md', muted = false }: KeycapProps): React.ReactElement {
const spec = SIZE_SPEC[size]
return (
<Box
component="span"
sx={{
display: 'inline-flex',
alignItems: 'center',
justifyContent: 'center',
flexShrink: 0,
height: spec.height,
px: spec.px,
borderRadius: spec.radius,
bgcolor: d3roPalette.bg.inset,
border: `1px solid ${
muted ? d3roPalette.border.subtle : d3roPalette.glass.hairlineStrong
}`,
boxShadow: muted ? 'none' : d3roShadow.inset,
fontFamily: d3roFontMono,
fontSize: spec.fontSize,
fontWeight: 500,
letterSpacing: '0.04em',
lineHeight: 1,
whiteSpace: 'nowrap',
color: muted ? d3roPalette.text.disabled : d3roPalette.text.primary,
}}
>
{children}
</Box>
)
}
/** 세그먼트 하나를 표시 문자열로 — i18nKey 가 있으면 번역이 우선이다. */
function useSegmentText(): (segment: BindingSegment) => string {
const { t } = useI18n()
return (segment) =>
segment.i18nKey === undefined ? segment.label : t(asTranslationKey(segment.i18nKey))
}
/** 바인딩 하나 → 결합된 한 줄 문자열. 접근성 라벨 · 본문 문구용. */
export function useBindingLabel(): (binding: KeyBinding | null) => string {
const segmentText = useSegmentText()
const platform = getPlatform()
return (binding) =>
joinBindingSegments(formatBindingSegments(binding, platform).map(segmentText), platform)
}
interface BindingKeycapsProps {
binding: KeyBinding
size?: KeycapSize
muted?: boolean
}
/** 바인딩 하나 → 키캡 나열. Windows/Linux 는 키캡 사이에 `+` 를 넣는다. */
export function BindingKeycaps({
binding,
size = 'md',
muted = false,
}: BindingKeycapsProps): React.ReactElement {
const segmentText = useSegmentText()
const platform = getPlatform()
const segments = formatBindingSegments(binding, platform)
const showSeparator = platform !== 'darwin'
return (
<Box sx={{ display: 'inline-flex', alignItems: 'center', gap: showSeparator ? 0.5 : 0.35 }}>
{segments.map((segment, index) => (
<Box
key={`${segment.i18nKey ?? segment.label}-${index}`}
sx={{ display: 'inline-flex', alignItems: 'center', gap: showSeparator ? 0.5 : 0.35 }}
>
{index > 0 && showSeparator && (
<Box
component="span"
sx={{ color: d3roPalette.text.dimLabel, fontSize: d3roTypo.label.size }}
>
+
</Box>
)}
<Keycap size={size} muted={muted}>
{segmentText(segment)}
</Keycap>
</Box>
))}
</Box>
)
}

View file

@ -0,0 +1,9 @@
// apps/desktop/src/renderer/components/keybinding/translation-key.ts
// @d3ro/core/keybinding 은 i18n 키를 평범한 문자열로 노출한다(코어가 로케일 패키지에 의존하지
// 않게 하려는 의도). t() 에 넘기는 경계에서만 TranslationKey 로 좁힌다.
import type { TranslationKey } from '@d3ro/i18n'
export function asTranslationKey(key: string): TranslationKey {
return key as TranslationKey
}

View file

@ -0,0 +1,44 @@
// apps/desktop/src/renderer/hooks/useKeyBindingMap.ts
// 렌더러 쪽 바인딩 맵 캐시.
//
// 액션마다 KeyBindingField 가 하나씩 붙으므로 컴포넌트별로 getMap() 을 부르면 같은 맵을
// 액션 수만큼 가져오게 된다. 구독을 모듈 스코프에 한 벌만 두고 changed 이벤트로 갱신한다.
import { useEffect, useState } from 'react'
import type { KeyBindingMap } from '@d3ro/core/keybinding'
type Listener = (map: KeyBindingMap) => void
let cached: KeyBindingMap | null = null
let subscribed = false
const listeners = new Set<Listener>()
function publish(map: KeyBindingMap): void {
cached = map
for (const listener of listeners) listener(map)
}
function ensureSubscribed(): void {
if (subscribed) return
subscribed = true
window.electronAPI.keybinding.onChanged((event) => publish(event.map))
void window.electronAPI.keybinding.getMap().then((result) => {
if (result.success) publish(result.data)
})
}
/** 맵이 아직 도착하지 않았으면 null. */
export function useKeyBindingMap(): KeyBindingMap | null {
const [map, setMap] = useState<KeyBindingMap | null>(cached)
useEffect(() => {
listeners.add(setMap)
ensureSubscribed()
if (cached !== null) setMap(cached)
return () => {
listeners.delete(setMap)
}
}, [])
return map
}

View file

@ -33,12 +33,13 @@ import {
AudioVisualizerBar,
} from '@d3ro/ui/components/ds'
import { EmptyStateCard, HistoryEntryCard } from '../components/shared'
import { d3roPalette, d3roFontSans, d3roFontMono, d3roRadius, d3roShadow, d3roTypo } from '@d3ro/ui/theme'
import { d3roPalette, d3roFontSans, d3roFontMono, d3roRadius, d3roTypo } from '@d3ro/ui/theme'
import { useI18n } from '@d3ro/i18n'
import { formatRecordingTime, formatRecordingTimeUnit, formatNumber, getDateKey } from '../utils/formatters'
import { formatHotkeyLabel } from '../utils/format-hotkey'
import { BindingKeycaps } from '../components/keybinding/Keycap'
import { useKeyBindingMap } from '../hooks/useKeyBindingMap'
import { FileDropZone } from '../components/FileDropZone'
import type { StatsSummary, HistoryEntry, HotkeyBinding, CaptionState, LicenseTier, UsageQuota } from '@d3ro/core/types'
import type { StatsSummary, HistoryEntry, CaptionState, LicenseTier, UsageQuota } from '@d3ro/core/types'
/** 카드 섹션 헤더 (제목 + 우측 액세서리) — 헤어라인 하단 구분 */
function CardHeader({
@ -100,7 +101,8 @@ export function DashboardPage(): React.ReactElement {
const [history, setHistory] = useState<HistoryEntry[]>([])
const [ollamaConnected, setOllamaConnected] = useState(false)
const [llmModel, setLlmModel] = useState<string | null>(null)
const [dictationBinding, setDictationBinding] = useState<HotkeyBinding | null>(null)
const bindingMap = useKeyBindingMap()
const dictationBinding = bindingMap?.dictation[0] ?? null
const [captionState, setCaptionState] = useState<CaptionState>('inactive')
const [audioLevel, setAudioLevel] = useState(0)
const audioDecayRef = useRef<ReturnType<typeof setInterval> | null>(null)
@ -122,9 +124,6 @@ export function DashboardPage(): React.ReactElement {
window.electronAPI.history.getAll({ page: 0, pageSize: 10, sortOrder: 'desc' }).then((r) => {
if (r.success) setHistory(r.data.entries)
})
window.electronAPI.hotkey.getDictationShortcut().then((r) => {
if (r.success && r.data) setDictationBinding(r.data)
})
window.electronAPI.caption.getState().then((r) => {
if (r.success) setCaptionState(r.data)
})
@ -145,8 +144,8 @@ export function DashboardPage(): React.ReactElement {
const unsub = window.electronAPI.app.onDataChanged(() => {
loadData()
})
const unsubCaption = window.electronAPI.caption.onStateChanged((state) => {
setCaptionState(state)
const unsubCaption = window.electronAPI.caption.onStateChanged((e) => {
setCaptionState(e.state)
})
const unsubAudio = window.electronAPI.voice.onAudioLevel((e) => {
setAudioLevel(e.level)
@ -272,27 +271,9 @@ export function DashboardPage(): React.ReactElement {
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1.25, mb: 2.5, flexWrap: 'wrap' }}>
<PhosphorText variant="body" sx={{ color: d3roPalette.text.secondary }}>
{dictationBinding ? t('dashboard.pressToRecord', { key: '' }) : t('dashboard.hotkeyNotSet')}
{dictationBinding ? t('keybinding.ui.pressToRecord') : t('dashboard.hotkeyNotSet')}
</PhosphorText>
{dictationBinding && (
<Box
sx={{
px: 1.25,
py: 0.35,
borderRadius: d3roRadius.xs,
bgcolor: d3roPalette.bg.inset,
border: `1px solid ${d3roPalette.glass.hairlineStrong}`,
boxShadow: d3roShadow.inset,
fontFamily: d3roFontMono,
fontSize: '12px',
fontWeight: 500,
color: d3roPalette.accent.light,
letterSpacing: '0.04em',
}}
>
{formatHotkeyLabel(dictationBinding).toUpperCase()}
</Box>
)}
{dictationBinding && <BindingKeycaps binding={dictationBinding} size="sm" />}
</Box>
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1.5 }}>

View file

@ -1,13 +1,12 @@
// apps/desktop/src/renderer/utils/format-hotkey.ts
// HotkeyBinding → 플랫폼별 표시 라벨 (segments + 결합 문자열).
// macOS: ⌘/⌥/⌃/⇧ + key, Windows/Linux: Ctrl/Alt/Win/Shift + key.
// 렌더러가 실행 중인 플랫폼을 알아내는 얇은 어댑터.
//
// 기존 binding.displayLabel은 키 녹화 시 만들어진 정적 문자열이라
// 플랫폼이 다르면 잘못 보임 — 이 헬퍼가 단일 진입점.
// 키 이름 · 수정자 표기 · 결합 규칙의 정본은 @d3ro/core/keybinding 이다
// (formatBindingSegments / joinBindingSegments). 매핑 테이블을 여기에 두지 않는다.
import type { HotkeyBinding } from '@d3ro/core/types'
import type { BindingPlatform } from '@d3ro/core/keybinding'
export type Platform = 'darwin' | 'win32' | 'linux'
export type Platform = BindingPlatform
export function getPlatform(): Platform {
const p = (window as { electronAPI?: { platform?: string } }).electronAPI?.platform
@ -16,104 +15,3 @@ export function getPlatform(): Platform {
if (typeof navigator !== 'undefined' && /Mac/i.test(navigator.platform)) return 'darwin'
return 'win32'
}
// keyCode → 키명. Windows VK_* 기준 + 일부 macOS 분기.
export function keyCodeToName(keyCode: number, platform: Platform = getPlatform()): string {
// Modifier 표기 — 플랫폼별
if (platform === 'darwin') {
if (keyCode === 16 || keyCode === 160 || keyCode === 161) return '⇧'
if (keyCode === 17 || keyCode === 162 || keyCode === 163) return '⌃'
if (keyCode === 18 || keyCode === 164 || keyCode === 165) return '⌥'
if (keyCode === 91 || keyCode === 92) return '⌘'
} else {
if (keyCode === 16 || keyCode === 160 || keyCode === 161) return 'Shift'
if (keyCode === 17 || keyCode === 162 || keyCode === 163) return 'Ctrl'
if (keyCode === 18 || keyCode === 164 || keyCode === 165) return 'Alt'
if (keyCode === 91 || keyCode === 92) return 'Win'
}
// 공통 키
switch (keyCode) {
case 8: return 'Backspace'
case 9: return 'Tab'
case 13: return platform === 'darwin' ? '↩' : 'Enter'
case 19: return 'Pause'
case 20: return 'CapsLock'
case 27: return 'Esc'
case 32: return 'Space'
case 33: return 'PgUp'
case 34: return 'PgDn'
case 35: return 'End'
case 36: return 'Home'
case 37: return '←'
case 38: return '↑'
case 39: return '→'
case 40: return '↓'
case 45: return 'Insert'
case 46: return platform === 'darwin' ? '⌫' : 'Delete'
case 186: return ';'
case 187: return '='
case 188: return ','
case 189: return '-'
case 190: return '.'
case 191: return '/'
case 192: return '`'
case 219: return '['
case 220: return '\\'
case 221: return ']'
case 222: return "'"
default: break
}
// F1~F24
if (keyCode >= 112 && keyCode <= 135) return `F${keyCode - 111}`
// Numpad
if (keyCode >= 96 && keyCode <= 105) return `Num${keyCode - 96}`
// 알파벳/숫자
if ((keyCode >= 48 && keyCode <= 57) || (keyCode >= 65 && keyCode <= 90)) {
return String.fromCharCode(keyCode)
}
return `Key${keyCode}`
}
/**
* binding을 플랫폼별 segment 배열로 변환.
* 예) Mac: ['⌘', '⇧', '1'], Win: ['Win', 'Shift', '1']
*
* 순서:
* - macOS: ⌃ ⌥ ⇧ ⌘ + key (Apple 표준)
* - Win/Linux: Ctrl Win Alt Shift + key
*/
export function formatHotkeySegments(binding: HotkeyBinding | null): string[] {
if (!binding) return []
const platform = getPlatform()
const segments: string[] = []
if (platform === 'darwin') {
if (binding.ctrl) segments.push('⌃')
if (binding.alt) segments.push('⌥')
if (binding.shift) segments.push('⇧')
if (binding.meta) segments.push('⌘')
} else {
if (binding.ctrl) segments.push('Ctrl')
if (binding.meta) segments.push('Win')
if (binding.alt) segments.push('Alt')
if (binding.shift) segments.push('Shift')
}
segments.push(keyCodeToName(binding.keyCode, platform))
return segments
}
/**
* 사람이 읽기 위한 단일 문자열 형태.
* macOS: '⌘⇧1' (구분자 없음 — Apple 표준)
* Win/Linux: 'Ctrl + Shift + 1'
*/
export function formatHotkeyLabel(binding: HotkeyBinding | null): string {
const segments = formatHotkeySegments(binding)
if (segments.length === 0) return ''
const platform = getPlatform()
return platform === 'darwin' ? segments.join('') : segments.join(' + ')
}