* Add new keymap * @param {string} id Keymap id * @param {string} keys Keymap keys, eg. `ctrl+a`, `⌘+z, ctrl+z` * @param {Function|string} handler Keymap handler, might be a function * @param {Object} [opts={}] Options * @param {Boolean} [opts.force=false] Force the handler to be exec
(id: Keymap['id'], keys: Keymap['keys'], handler: Keymap['handler'], opts: KeymapOptions = {})
| 98 | * }) |
| 99 | */ |
| 100 | add(id: Keymap['id'], keys: Keymap['keys'], handler: Keymap['handler'], opts: KeymapOptions = {}) { |
| 101 | const { em, events } = this; |
| 102 | const cmd = em.Commands; |
| 103 | const editor = em.getEditor(); |
| 104 | const canvas = em.Canvas; |
| 105 | const keymap: Keymap = { id, keys, handler }; |
| 106 | const pk = this.keymaps[id]; |
| 107 | pk && this.remove(id); |
| 108 | this.keymaps[id] = keymap; |
| 109 | keymaster( |
| 110 | keys, |
| 111 | (e: any, h: any) => { |
| 112 | // It's safer putting handlers resolution inside the callback |
| 113 | const opt = { event: e, h }; |
| 114 | const handlerRes = isString(handler) ? cmd.get(handler) : handler; |
| 115 | const ableTorun = !em.isEditing() && !editor.Canvas.isInputFocused(); |
| 116 | if (ableTorun || opts.force) { |
| 117 | opts.prevent && canvas.getCanvasView()?.preventDefault(e); |
| 118 | isFunction(handlerRes) ? handlerRes(editor, 0, opt) : cmd.runCommand(handlerRes, opt); |
| 119 | const args = [id, h.shortcut, e]; |
| 120 | // @ts-ignore |
| 121 | em.trigger(events.emit, ...args); |
| 122 | // @ts-ignore |
| 123 | em.trigger(`${events.emitId}${id}`, ...args); |
| 124 | } |
| 125 | }, |
| 126 | undefined, |
| 127 | ); |
| 128 | em.trigger(events.add, keymap); |
| 129 | return keymap; |
| 130 | } |
| 131 | |
| 132 | /** |
| 133 | * Get the keymap by id |
no test coverage detected