forked from marktext/marktext
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommandCenter.js
More file actions
74 lines (65 loc) · 1.92 KB
/
commandCenter.js
File metadata and controls
74 lines (65 loc) · 1.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import { ipcRenderer } from 'electron'
import log from 'electron-log'
import bus from '../bus'
import staticCommands, { RootCommand } from '../commands'
const state = {
rootCommand: new RootCommand(staticCommands)
}
const getters = {}
const mutations = {
REGISTER_COMMAND (state, command) {
state.rootCommand.subcommands.push(command)
},
SORT_COMMANDS (state) {
state.rootCommand.subcommands.sort((a, b) => a.description.localeCompare(b.description))
}
}
const actions = {
LISTEN_COMMAND_CENTER_BUS ({ commit, state }) {
// Init stuff
bus.$on('cmd::sort-commands', () => {
commit('SORT_COMMANDS')
})
ipcRenderer.on('mt::keybindings-response', (e, keybindingMap) => {
const { subcommands } = state.rootCommand
for (const entry of subcommands) {
const value = keybindingMap[entry.id]
if (value) {
entry.shortcut = normalizeAccelerator(value)
}
}
})
// Register commands that are created at runtime.
bus.$on('cmd::register-command', command => {
commit('REGISTER_COMMAND', command)
})
// Allow other compontents to execute commands with predefined values.
bus.$on('cmd::execute', commandId => {
executeCommand(state, commandId)
})
ipcRenderer.on('mt::execute-command-by-id', (e, commandId) => {
executeCommand(state, commandId)
})
}
}
const executeCommand = (state, commandId) => {
const { subcommands } = state.rootCommand
const command = subcommands.find(c => c.id === commandId)
if (!command) {
const errorMsg = `Cannot execute command "${commandId}" because it's missing.`
log.error(errorMsg)
throw new Error(errorMsg)
}
command.execute()
}
const normalizeAccelerator = acc => {
try {
return acc
.replace(/cmdorctrl|cmd/i, 'Cmd')
.replace(/ctrl/i, 'Ctrl')
.split('+')
} catch (_) {
return [acc]
}
}
export default { state, getters, mutations, actions }