forked from storybookjs/storybook
-
Notifications
You must be signed in to change notification settings - Fork 0
/
shortcuts.ts
361 lines (319 loc) 路 10 KB
/
shortcuts.ts
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
import global from 'global';
import { PREVIEW_KEYDOWN } from '@storybook/core-events';
import type { ModuleFn } from '../index';
import { shortcutMatchesShortcut, eventToShortcut } from '../lib/shortcut';
import { focusableUIElements } from './layout';
const { navigator, document } = global;
export const isMacLike = () =>
navigator && navigator.platform ? !!navigator.platform.match(/(Mac|iPhone|iPod|iPad)/i) : false;
export const controlOrMetaKey = () => (isMacLike() ? 'meta' : 'control');
export function keys<O>(o: O) {
return Object.keys(o) as (keyof O)[];
}
export interface SubState {
shortcuts: Shortcuts;
}
export interface SubAPI {
getShortcutKeys(): Shortcuts;
getDefaultShortcuts(): Shortcuts | AddonShortcutDefaults;
getAddonsShortcuts(): AddonShortcuts;
getAddonsShortcutLabels(): AddonShortcutLabels;
getAddonsShortcutDefaults(): AddonShortcutDefaults;
setShortcuts(shortcuts: Shortcuts): Promise<Shortcuts>;
setShortcut(action: Action, value: KeyCollection): Promise<KeyCollection>;
setAddonShortcut(addon: string, shortcut: AddonShortcut): Promise<AddonShortcut>;
restoreAllDefaultShortcuts(): Promise<Shortcuts>;
restoreDefaultShortcut(action: Action): Promise<KeyCollection>;
handleKeydownEvent(event: Event): void;
handleShortcutFeature(feature: Action): void;
}
export type KeyCollection = string[];
export interface Shortcuts {
fullScreen: KeyCollection;
togglePanel: KeyCollection;
panelPosition: KeyCollection;
toggleNav: KeyCollection;
toolbar: KeyCollection;
search: KeyCollection;
focusNav: KeyCollection;
focusIframe: KeyCollection;
focusPanel: KeyCollection;
prevComponent: KeyCollection;
nextComponent: KeyCollection;
prevStory: KeyCollection;
nextStory: KeyCollection;
shortcutsPage: KeyCollection;
aboutPage: KeyCollection;
escape: KeyCollection;
collapseAll: KeyCollection;
expandAll: KeyCollection;
}
export type Action = keyof Shortcuts;
interface AddonShortcut {
label: string;
defaultShortcut: KeyCollection;
actionName: string;
showInMenu?: boolean;
action: (...args: any[]) => any;
}
type AddonShortcuts = Record<string, AddonShortcut>;
type AddonShortcutLabels = Record<string, string>;
type AddonShortcutDefaults = Record<string, KeyCollection>;
export const defaultShortcuts: Shortcuts = Object.freeze({
fullScreen: ['F'],
togglePanel: ['A'],
panelPosition: ['D'],
toggleNav: ['S'],
toolbar: ['T'],
search: ['/'],
focusNav: ['1'],
focusIframe: ['2'],
focusPanel: ['3'],
prevComponent: ['alt', 'ArrowUp'],
nextComponent: ['alt', 'ArrowDown'],
prevStory: ['alt', 'ArrowLeft'],
nextStory: ['alt', 'ArrowRight'],
shortcutsPage: [controlOrMetaKey(), 'shift', ','],
aboutPage: [','],
escape: ['escape'], // This one is not customizable
collapseAll: [controlOrMetaKey(), 'shift', 'ArrowUp'],
expandAll: [controlOrMetaKey(), 'shift', 'ArrowDown'],
});
const addonsShortcuts: AddonShortcuts = {};
interface TaggedEventTarget extends EventTarget {
tagName: string;
getAttribute(attr: string): string | null;
}
export interface Event extends KeyboardEvent {
target: TaggedEventTarget;
}
function focusInInput(event: Event) {
return (
/input|textarea/i.test(event.target.tagName) ||
event.target.getAttribute('contenteditable') !== null
);
}
export const init: ModuleFn = ({ store, fullAPI }) => {
const api: SubAPI = {
// Getting and setting shortcuts
getShortcutKeys(): Shortcuts {
return store.getState().shortcuts;
},
getDefaultShortcuts(): Shortcuts | AddonShortcutDefaults {
return {
...defaultShortcuts,
...api.getAddonsShortcutDefaults(),
};
},
getAddonsShortcuts(): AddonShortcuts {
return addonsShortcuts;
},
getAddonsShortcutLabels(): AddonShortcutLabels {
const labels: AddonShortcutLabels = {};
Object.entries(api.getAddonsShortcuts()).forEach(([actionName, { label }]) => {
labels[actionName] = label;
});
return labels;
},
getAddonsShortcutDefaults(): AddonShortcutDefaults {
const defaults: AddonShortcutDefaults = {};
Object.entries(api.getAddonsShortcuts()).forEach(([actionName, { defaultShortcut }]) => {
defaults[actionName] = defaultShortcut;
});
return defaults;
},
async setShortcuts(shortcuts: Shortcuts) {
await store.setState({ shortcuts }, { persistence: 'permanent' });
return shortcuts;
},
async restoreAllDefaultShortcuts() {
return api.setShortcuts(api.getDefaultShortcuts() as Shortcuts);
},
async setShortcut(action, value) {
const shortcuts = api.getShortcutKeys();
await api.setShortcuts({ ...shortcuts, [action]: value });
return value;
},
async setAddonShortcut(addon: string, shortcut: AddonShortcut) {
const shortcuts = api.getShortcutKeys();
await api.setShortcuts({
...shortcuts,
[`${addon}-${shortcut.actionName}`]: shortcut.defaultShortcut,
});
addonsShortcuts[`${addon}-${shortcut.actionName}`] = shortcut;
return shortcut;
},
async restoreDefaultShortcut(action) {
const defaultShortcut = api.getDefaultShortcuts()[action];
return api.setShortcut(action, defaultShortcut);
},
// Listening to shortcut events
handleKeydownEvent(event) {
const shortcut = eventToShortcut(event);
const shortcuts = api.getShortcutKeys();
const actions = keys(shortcuts);
const matchedFeature = actions.find((feature: Action) =>
shortcutMatchesShortcut(shortcut, shortcuts[feature])
);
if (matchedFeature) {
// Event.prototype.preventDefault is missing when received from the MessageChannel.
if (event?.preventDefault) event.preventDefault();
api.handleShortcutFeature(matchedFeature);
}
},
// warning: event might not have a full prototype chain because it may originate from the channel
handleShortcutFeature(feature) {
const {
layout: { isFullscreen, showNav, showPanel },
ui: { enableShortcuts },
} = store.getState();
if (!enableShortcuts) {
return;
}
switch (feature) {
case 'escape': {
if (isFullscreen) {
fullAPI.toggleFullscreen();
} else if (!showNav) {
fullAPI.toggleNav();
}
break;
}
case 'focusNav': {
if (isFullscreen) {
fullAPI.toggleFullscreen();
}
if (!showNav) {
fullAPI.toggleNav();
}
fullAPI.focusOnUIElement(focusableUIElements.storyListMenu);
break;
}
case 'search': {
if (isFullscreen) {
fullAPI.toggleFullscreen();
}
if (!showNav) {
fullAPI.toggleNav();
}
setTimeout(() => {
fullAPI.focusOnUIElement(focusableUIElements.storySearchField, true);
}, 0);
break;
}
case 'focusIframe': {
const element = document.getElementById('storybook-preview-iframe');
if (element) {
try {
// should be like a channel message and all that, but yolo for now
element.contentWindow.focus();
} catch (e) {
//
}
}
break;
}
case 'focusPanel': {
if (isFullscreen) {
fullAPI.toggleFullscreen();
}
if (!showPanel) {
fullAPI.togglePanel();
}
fullAPI.focusOnUIElement(focusableUIElements.storyPanelRoot);
break;
}
case 'nextStory': {
fullAPI.jumpToStory(1);
break;
}
case 'prevStory': {
fullAPI.jumpToStory(-1);
break;
}
case 'nextComponent': {
fullAPI.jumpToComponent(1);
break;
}
case 'prevComponent': {
fullAPI.jumpToComponent(-1);
break;
}
case 'fullScreen': {
fullAPI.toggleFullscreen();
break;
}
case 'togglePanel': {
if (isFullscreen) {
fullAPI.toggleFullscreen();
fullAPI.resetLayout();
}
fullAPI.togglePanel();
break;
}
case 'toggleNav': {
if (isFullscreen) {
fullAPI.toggleFullscreen();
fullAPI.resetLayout();
}
fullAPI.toggleNav();
break;
}
case 'toolbar': {
fullAPI.toggleToolbar();
break;
}
case 'panelPosition': {
if (isFullscreen) {
fullAPI.toggleFullscreen();
}
if (!showPanel) {
fullAPI.togglePanel();
}
fullAPI.togglePanelPosition();
break;
}
case 'aboutPage': {
fullAPI.navigate('/settings/about');
break;
}
case 'shortcutsPage': {
fullAPI.navigate('/settings/shortcuts');
break;
}
case 'collapseAll': {
fullAPI.collapseAll();
break;
}
case 'expandAll': {
fullAPI.expandAll();
break;
}
default:
addonsShortcuts[feature].action();
break;
}
},
};
const { shortcuts: persistedShortcuts = defaultShortcuts }: SubState = store.getState();
const state: SubState = {
// Any saved shortcuts that are still in our set of defaults
shortcuts: keys(defaultShortcuts).reduce(
(acc, key) => ({ ...acc, [key]: persistedShortcuts[key] || defaultShortcuts[key] }),
defaultShortcuts
),
};
const initModule = () => {
// Listen for keydown events in the manager
document.addEventListener('keydown', (event: Event) => {
if (!focusInInput(event)) {
fullAPI.handleKeydownEvent(event);
}
});
// Also listen to keydown events sent over the channel
fullAPI.on(PREVIEW_KEYDOWN, (data: { event: Event }) => {
fullAPI.handleKeydownEvent(data.event);
});
};
return { api, state, init: initModule };
};