1 import { Keys, Platform, Shortcut } from "./types"
2
3 export const findFirstPlatformMatch = (keys: Keys) => {
4 const match =
5 Object.entries(keys as Record<any, any>).filter(
6 ([, value]) => value.length > 0
7 )[0] ?? []
8
9 return match.length
10 ? {
11 platform: match[0] as Platform,
12 keys: match[1] as string[],
13 }
14 : null
15 }
16
17 export const getShortcutKeys = (shortcut: Shortcut) => {
18 const platform: Platform = "Mac"
19
20 const keys: string[] | undefined = shortcut.keys[platform]
21
22 if (!keys) {
23 const defaultPlatform = findFirstPlatformMatch(shortcut.keys)
24
25 console.warn(
26 `No keys found for platform "${platform}" in "${shortcut.label}" ${
27 defaultPlatform
28 ? `using keys for platform "${defaultPlatform.platform}"`
29 : ""
30 }`
31 )
32
33 return defaultPlatform ? defaultPlatform.keys : []
34 }
35
36 return keys
37 }
38
39 const keysMatch = (keys1: string[], keys2: string[]) => {
40 return (
41 keys1.length === keys2.length &&
42 keys1.every(
43 (key, index) => key.toLowerCase() === keys2[index].toLowerCase()
44 )
45 )
46 }
47
48 export const findShortcutIndex = (shortcuts: Shortcut[], keys: string[]) => {
49 if (!keys.length) {
50 return -1
51 }
52
53 let index = 0
54 for (const shortcut of shortcuts) {
55 const shortcutKeys = getShortcutKeys(shortcut)
56
57 if (keysMatch(shortcutKeys, keys)) {
58 return index
59 }
60
61 index++
62 }
63
64 return -1
65 }
66
67 export const findShortcut = (shortcuts: Shortcut[], keys: string[]) => {
68 const shortcutIndex = findShortcutIndex(shortcuts, keys)
69 return shortcutIndex > -1 ? shortcuts[shortcutIndex] : null
70 }
71
72 export const getShortcutWithDefaultValues = (
73 shortcut: Shortcut,
74 platform: Platform = "Mac"
75 ): Shortcut => {
76 const platforms: Platform[] = ["Mac", "Windows", "Linux"]
77
78 const defaultKeys = Object.values(shortcut.keys)[0] ?? shortcut.keys[platform]
79
80 const keys = platforms.reduce((acc, curr) => {
81 return {
82 ...acc,
83 [curr]: shortcut.keys[curr] ?? defaultKeys,
84 }
85 }, {})
86
87 return {
88 ...shortcut,
89 keys,
90 _defaultKeys: shortcut.keys,
91 }
92 }