Line data Source code
1 : import { KeybindingImpl } from '@comfyorg/keybindings/keybinding'
2 : import { useKeybindingStore } from '@comfyorg/keybindings/keybindingStore'
3 :
4 : import { CORE_KEYBINDINGS } from './defaults'
5 :
6 1 : const EQUIVALENT_MODIFIER: Record<string, string> = {
7 : CMD: 'CTRL',
8 : COMMAND: 'CTRL',
9 : CONTROL: 'CTRL',
10 : META: 'CTRL',
11 : '⌘': 'CTRL',
12 : OPTION: 'ALT',
13 : OPT: 'ALT',
14 : '⌥': 'ALT',
15 : '⇧': 'SHIFT'
16 : }
17 :
18 1 : const EQUIVALENT_KEY: Record<string, string> = {
19 : RETURN: 'ENTER',
20 : ESC: 'ESCAPE',
21 : DEL: 'DELETE',
22 : SPACEBAR: 'SPACE'
23 : }
24 :
25 1 : const MODIFIER_LABELS: Record<string, string> = {
26 : CTRL: 'Ctrl',
27 : ALT: 'Alt',
28 : SHIFT: 'Shift'
29 : }
30 :
31 1 : const MODIFIER_ORDER = ['CTRL', 'ALT', 'SHIFT']
32 :
33 51 : function fold(key: string): string {
34 51 : const upper = key.toUpperCase()
35 51 : const modifier = EQUIVALENT_MODIFIER[upper] ?? upper
36 51 : return MODIFIER_ORDER.includes(modifier)
37 : ? modifier
38 : : (EQUIVALENT_KEY[upper] ?? upper)
39 : }
40 :
41 : /** This app's label for a modifier however it was spelled, else undefined. */
42 0 : export function modifierLabel(key: string): string | undefined {
43 0 : return MODIFIER_LABELS[fold(key)]
44 : }
45 :
46 : /** One spelling for a combo, with modifiers ordered and synonyms folded. */
47 22 : export function canonicalCombo(keys: string[]): string {
48 22 : const folded = keys.map(fold)
49 22 : const modifiers = MODIFIER_ORDER.filter((modifier) =>
50 : folded.includes(modifier)
51 : )
52 22 : const rest = folded.filter((key) => !MODIFIER_ORDER.includes(key))
53 22 : return [...modifiers, ...rest].join('+')
54 : }
55 :
56 1 : const COMMAND_ID_BY_DEFAULT_COMBO = new Map(
57 : CORE_KEYBINDINGS.map(
58 : (keybinding) => [new KeybindingImpl(keybinding).combo, keybinding] as const
59 : )
60 : .filter(([combo]) => combo.hasModifier)
61 : .map(([combo, keybinding]) => [
62 : canonicalCombo(combo.getKeySequences()),
63 : keybinding.commandId
64 : ])
65 : )
66 :
67 : /** The canvas command that ships `keys` as a default, else undefined. */
68 0 : export function canvasCommandForWrittenKeys(
69 : keys: string[]
70 : ): string | undefined {
71 0 : return COMMAND_ID_BY_DEFAULT_COMBO.get(canonicalCombo(keys))
72 : }
73 :
74 : /** Returns a reader for every key sequence a command is bound to now. */
75 0 : export function useCanvasActionShortcutKeys(): (
76 : commandId: string
77 : ) => string[][] {
78 0 : const keybindingStore = useKeybindingStore()
79 0 : return (commandId) =>
80 : keybindingStore
81 : .getKeybindingsByCommandId(commandId)
82 : .map((keybinding) => keybinding.combo.getKeySequences())
83 : }
|