]> BookStack Code Mirror - bookstack/blob - resources/js/components/shortcuts.js
Merge branch 'lexical' into development
[bookstack] / resources / js / components / shortcuts.js
1 import {Component} from './component';
2
3 function reverseMap(map) {
4     const reversed = {};
5     for (const [key, value] of Object.entries(map)) {
6         reversed[value] = key;
7     }
8     return reversed;
9 }
10
11 export class Shortcuts extends Component {
12
13     setup() {
14         this.container = this.$el;
15         this.mapById = JSON.parse(this.$opts.keyMap);
16         this.mapByShortcut = reverseMap(this.mapById);
17
18         this.hintsShowing = false;
19
20         this.hideHints = this.hideHints.bind(this);
21         this.hintAbortController = null;
22
23         this.setupListeners();
24     }
25
26     setupListeners() {
27         window.addEventListener('keydown', event => {
28             if (event.target.closest('input, select, textarea, .cm-editor, .editor-container')) {
29                 return;
30             }
31
32             if (event.key === '?') {
33                 if (this.hintsShowing) {
34                     this.hideHints();
35                 } else {
36                     this.showHints();
37                 }
38                 return;
39             }
40
41             this.handleShortcutPress(event);
42         });
43     }
44
45     /**
46      * @param {KeyboardEvent} event
47      */
48     handleShortcutPress(event) {
49         const keys = [
50             event.ctrlKey ? 'Ctrl' : '',
51             event.metaKey ? 'Cmd' : '',
52             event.key,
53         ];
54
55         const combo = keys.filter(s => Boolean(s)).join(' + ');
56
57         const shortcutId = this.mapByShortcut[combo];
58         if (shortcutId) {
59             const wasHandled = this.runShortcut(shortcutId);
60             if (wasHandled) {
61                 event.preventDefault();
62             }
63         }
64     }
65
66     /**
67      * Run the given shortcut, and return a boolean to indicate if the event
68      * was successfully handled by a shortcut action.
69      * @param {String} id
70      * @return {boolean}
71      */
72     runShortcut(id) {
73         const el = this.container.querySelector(`[data-shortcut="${id}"]`);
74         if (!el) {
75             return false;
76         }
77
78         if (el.matches('input, textarea, select')) {
79             el.focus();
80             return true;
81         }
82
83         if (el.matches('a, button')) {
84             el.click();
85             return true;
86         }
87
88         if (el.matches('div[tabindex]')) {
89             el.click();
90             el.focus();
91             return true;
92         }
93
94         console.error('Shortcut attempted to be ran for element type that does not have handling setup', el);
95
96         return false;
97     }
98
99     showHints() {
100         const wrapper = document.createElement('div');
101         wrapper.classList.add('shortcut-container');
102         this.container.append(wrapper);
103
104         const shortcutEls = this.container.querySelectorAll('[data-shortcut]');
105         const displayedIds = new Set();
106         for (const shortcutEl of shortcutEls) {
107             const id = shortcutEl.getAttribute('data-shortcut');
108             if (displayedIds.has(id)) {
109                 continue;
110             }
111
112             const key = this.mapById[id];
113             this.showHintLabel(shortcutEl, key, wrapper);
114             displayedIds.add(id);
115         }
116
117         this.hintAbortController = new AbortController();
118         const signal = this.hintAbortController.signal;
119         window.addEventListener('scroll', this.hideHints, {signal});
120         window.addEventListener('focus', this.hideHints, {signal});
121         window.addEventListener('blur', this.hideHints, {signal});
122         window.addEventListener('click', this.hideHints, {signal});
123
124         this.hintsShowing = true;
125     }
126
127     /**
128      * @param {Element} targetEl
129      * @param {String} key
130      * @param {Element} wrapper
131      */
132     showHintLabel(targetEl, key, wrapper) {
133         const targetBounds = targetEl.getBoundingClientRect();
134
135         const label = document.createElement('div');
136         label.classList.add('shortcut-hint');
137         label.textContent = key;
138
139         const linkage = document.createElement('div');
140         linkage.classList.add('shortcut-linkage');
141         linkage.style.left = `${targetBounds.x}px`;
142         linkage.style.top = `${targetBounds.y}px`;
143         linkage.style.width = `${targetBounds.width}px`;
144         linkage.style.height = `${targetBounds.height}px`;
145
146         wrapper.append(label, linkage);
147
148         const labelBounds = label.getBoundingClientRect();
149
150         label.style.insetInlineStart = `${((targetBounds.x + targetBounds.width) - (labelBounds.width + 6))}px`;
151         label.style.insetBlockStart = `${(targetBounds.y + (targetBounds.height - labelBounds.height) / 2)}px`;
152     }
153
154     hideHints() {
155         const wrapper = this.container.querySelector('.shortcut-container');
156         wrapper.remove();
157         this.hintAbortController?.abort();
158         this.hintsShowing = false;
159     }
160
161 }