Debian Codegraph @

packages/commands/src/index.ts

raw
1 // Copyright (c) Jupyter Development Team.
2 // Distributed under the terms of the Modified BSD License.
3 /*-----------------------------------------------------------------------------
4 | Copyright (c) 2014-2017, PhosphorJS Contributors
5 |
6 | Distributed under the terms of the BSD 3-Clause License.
7 |
8 | The full license is in the file LICENSE, distributed with this software.
9 |----------------------------------------------------------------------------*/
10 /**
11 * @packageDocumentation
12 * @module commands
13 */
14 import { ArrayExt } from '@lumino/algorithm';
15
16 import {
17 JSONExt,
18 ReadonlyJSONObject,
19 ReadonlyPartialJSONObject
20 } from '@lumino/coreutils';
21
22 import { DisposableDelegate, IDisposable } from '@lumino/disposable';
23
24 import { Platform, Selector } from '@lumino/domutils';
25
26 import { getKeyboardLayout } from '@lumino/keyboard';
27
28 import { ISignal, Signal } from '@lumino/signaling';
29
30 import { VirtualElement } from '@lumino/virtualdom';
31
32 /**
33 * An object which manages a collection of commands.
34 *
35 * #### Notes
36 * A command registry can be used to populate a variety of action-based
37 * widgets, such as command palettes, menus, and toolbars.
38 */
39 export class CommandRegistry {
40 /**
41 * A signal emitted when a command has changed.
42 *
43 * #### Notes
44 * This signal is useful for visual representations of commands which
45 * need to refresh when the state of a relevant command has changed.
46 */
47 get commandChanged(): ISignal<this, CommandRegistry.ICommandChangedArgs> {
48 return this._commandChanged;
49 }
50
51 /**
52 * A signal emitted when a command has executed.
53 *
54 * #### Notes
55 * Care should be taken when consuming this signal. The command system is used
56 * by many components for many user actions. Handlers registered with this
57 * signal must return quickly to ensure the overall application remains responsive.
58 */
59 get commandExecuted(): ISignal<this, CommandRegistry.ICommandExecutedArgs> {
60 return this._commandExecuted;
61 }
62
63 /**
64 * A signal emitted when a key binding is changed.
65 */
66 get keyBindingChanged(): ISignal<
67 this,
68 CommandRegistry.IKeyBindingChangedArgs
69 > {
70 return this._keyBindingChanged;
71 }
72
73 /**
74 * A read-only array of the key bindings in the registry.
75 */
76 get keyBindings(): ReadonlyArray<CommandRegistry.IKeyBinding> {
77 return this._keyBindings;
78 }
79
80 /**
81 * List the ids of the registered commands.
82 *
83 * @returns A new array of the registered command ids.
84 */
85 listCommands(): string[] {
86 return Array.from(this._commands.keys());
87 }
88
89 /**
90 * Test whether a specific command is registered.
91 *
92 * @param id - The id of the command of interest.
93 *
94 * @returns `true` if the command is registered, `false` otherwise.
95 */
96 hasCommand(id: string): boolean {
97 return this._commands.has(id);
98 }
99
100 /**
101 * Add a command to the registry.
102 *
103 * @param id - The unique id of the command.
104 *
105 * @param options - The options for the command.
106 *
107 * @returns A disposable which will remove the command.
108 *
109 * @throws An error if the given `id` is already registered.
110 */
111 addCommand(
112 id: string,
113 options: CommandRegistry.ICommandOptions
114 ): IDisposable {
115 // Throw an error if the id is already registered.
116 if (this._commands.has(id)) {
117 throw new Error(`Command '${id}' already registered.`);
118 }
119
120 // Add the command to the registry.
121 this._commands.set(id, Private.createCommand(options));
122
123 // Emit the `commandChanged` signal.
124 this._commandChanged.emit({ id, type: 'added' });
125
126 // Return a disposable which will remove the command.
127 return new DisposableDelegate(() => {
128 // Remove the command from the registry.
129 this._commands.delete(id);
130
131 // Emit the `commandChanged` signal.
132 this._commandChanged.emit({ id, type: 'removed' });
133 });
134 }
135
136 /**
137 * Notify listeners that the state of a command has changed.
138 *
139 * @param id - The id of the command which has changed. If more than
140 * one command has changed, this argument should be omitted.
141 *
142 * @throws An error if the given `id` is not registered.
143 *
144 * #### Notes
145 * This method should be called by the command author whenever the
146 * application state changes such that the results of the command
147 * metadata functions may have changed.
148 *
149 * This will cause the `commandChanged` signal to be emitted.
150 */
151 notifyCommandChanged(id?: string): void {
152 if (id !== undefined && !this._commands.has(id)) {
153 throw new Error(`Command '${id}' is not registered.`);
154 }
155 this._commandChanged.emit({ id, type: id ? 'changed' : 'many-changed' });
156 }
157
158 /**
159 * Get the description for a specific command.
160 *
161 * @param id - The id of the command of interest.
162 *
163 * @param args - The arguments for the command.
164 *
165 * @returns The description for the command.
166 */
167 describedBy(
168 id: string,
169 args: ReadonlyPartialJSONObject = JSONExt.emptyObject
170 ): Promise<CommandRegistry.Description> {
171 let cmd = this._commands.get(id);
172 return Promise.resolve(
173 cmd?.describedBy.call(undefined, args) ?? { args: null }
174 );
175 }
176
177 /**
178 * Get the display label for a specific command.
179 *
180 * @param id - The id of the command of interest.
181 *
182 * @param args - The arguments for the command.
183 *
184 * @returns The display label for the command, or an empty string
185 * if the command is not registered.
186 */
187 label(
188 id: string,
189 args: ReadonlyPartialJSONObject = JSONExt.emptyObject
190 ): string {
191 let cmd = this._commands.get(id);
192 return cmd?.label.call(undefined, args) ?? '';
193 }
194
195 /**
196 * Get the mnemonic index for a specific command.
197 *
198 * @param id - The id of the command of interest.
199 *
200 * @param args - The arguments for the command.
201 *
202 * @returns The mnemonic index for the command, or `-1` if the
203 * command is not registered.
204 */
205 mnemonic(
206 id: string,
207 args: ReadonlyPartialJSONObject = JSONExt.emptyObject
208 ): number {
209 let cmd = this._commands.get(id);
210 return cmd ? cmd.mnemonic.call(undefined, args) : -1;
211 }
212
213 /**
214 * Get the icon renderer for a specific command.
215 *
216 * DEPRECATED: if set to a string value, the .icon field will
217 * function as an alias for the .iconClass field, for backwards
218 * compatibility. In the future when this is removed, the default
219 * return type will become undefined.
220 *
221 * @param id - The id of the command of interest.
222 *
223 * @param args - The arguments for the command.
224 *
225 * @returns The icon renderer for the command or `undefined`.
226 */
227 icon(
228 id: string,
229 args: ReadonlyPartialJSONObject = JSONExt.emptyObject
230 ): VirtualElement.IRenderer | undefined {
231 return this._commands.get(id)?.icon.call(undefined, args);
232 }
233
234 /**
235 * Get the icon class for a specific command.
236 *
237 * @param id - The id of the command of interest.
238 *
239 * @param args - The arguments for the command.
240 *
241 * @returns The icon class for the command, or an empty string if
242 * the command is not registered.
243 */
244 iconClass(
245 id: string,
246 args: ReadonlyPartialJSONObject = JSONExt.emptyObject
247 ): string {
248 let cmd = this._commands.get(id);
249 return cmd ? cmd.iconClass.call(undefined, args) : '';
250 }
251
252 /**
253 * Get the icon label for a specific command.
254 *
255 * @param id - The id of the command of interest.
256 *
257 * @param args - The arguments for the command.
258 *
259 * @returns The icon label for the command, or an empty string if
260 * the command is not registered.
261 */
262 iconLabel(
263 id: string,
264 args: ReadonlyPartialJSONObject = JSONExt.emptyObject
265 ): string {
266 let cmd = this._commands.get(id);
267 return cmd ? cmd.iconLabel.call(undefined, args) : '';
268 }
269
270 /**
271 * Get the short form caption for a specific command.
272 *
273 * @param id - The id of the command of interest.
274 *
275 * @param args - The arguments for the command.
276 *
277 * @returns The caption for the command, or an empty string if the
278 * command is not registered.
279 */
280 caption(
281 id: string,
282 args: ReadonlyPartialJSONObject = JSONExt.emptyObject
283 ): string {
284 let cmd = this._commands.get(id);
285 return cmd ? cmd.caption.call(undefined, args) : '';
286 }
287
288 /**
289 * Get the usage help text for a specific command.
290 *
291 * @param id - The id of the command of interest.
292 *
293 * @param args - The arguments for the command.
294 *
295 * @returns The usage text for the command, or an empty string if
296 * the command is not registered.
297 */
298 usage(
299 id: string,
300 args: ReadonlyPartialJSONObject = JSONExt.emptyObject
301 ): string {
302 let cmd = this._commands.get(id);
303 return cmd ? cmd.usage.call(undefined, args) : '';
304 }
305
306 /**
307 * Get the extra class name for a specific command.
308 *
309 * @param id - The id of the command of interest.
310 *
311 * @param args - The arguments for the command.
312 *
313 * @returns The class name for the command, or an empty string if
314 * the command is not registered.
315 */
316 className(
317 id: string,
318 args: ReadonlyPartialJSONObject = JSONExt.emptyObject
319 ): string {
320 let cmd = this._commands.get(id);
321 return cmd ? cmd.className.call(undefined, args) : '';
322 }
323
324 /**
325 * Get the dataset for a specific command.
326 *
327 * @param id - The id of the command of interest.
328 *
329 * @param args - The arguments for the command.
330 *
331 * @returns The dataset for the command, or an empty dataset if
332 * the command is not registered.
333 */
334 dataset(
335 id: string,
336 args: ReadonlyPartialJSONObject = JSONExt.emptyObject
337 ): CommandRegistry.Dataset {
338 let cmd = this._commands.get(id);
339 return cmd ? cmd.dataset.call(undefined, args) : {};
340 }
341
342 /**
343 * Test whether a specific command is enabled.
344 *
345 * @param id - The id of the command of interest.
346 *
347 * @param args - The arguments for the command.
348 *
349 * @returns A boolean indicating whether the command is enabled,
350 * or `false` if the command is not registered.
351 */
352 isEnabled(
353 id: string,
354 args: ReadonlyPartialJSONObject = JSONExt.emptyObject
355 ): boolean {
356 let cmd = this._commands.get(id);
357 return cmd ? cmd.isEnabled.call(undefined, args) : false;
358 }
359
360 /**
361 * Test whether a specific command is toggled.
362 *
363 * @param id - The id of the command of interest.
364 *
365 * @param args - The arguments for the command.
366 *
367 * @returns A boolean indicating whether the command is toggled,
368 * or `false` if the command is not registered.
369 */
370 isToggled(
371 id: string,
372 args: ReadonlyPartialJSONObject = JSONExt.emptyObject
373 ): boolean {
374 let cmd = this._commands.get(id);
375 return cmd ? cmd.isToggled.call(undefined, args) : false;
376 }
377
378 /**
379 * Test whether a specific command is toggleable.
380 *
381 * @param id - The id of the command of interest.
382 *
383 * @param args - The arguments for the command.
384 *
385 * @returns A boolean indicating whether the command is toggleable,
386 * or `false` if the command is not registered.
387 */
388 isToggleable(
389 id: string,
390 args: ReadonlyJSONObject = JSONExt.emptyObject
391 ): boolean {
392 let cmd = this._commands.get(id);
393 return cmd ? cmd.isToggleable : false;
394 }
395
396 /**
397 * Test whether a specific command is visible.
398 *
399 * @param id - The id of the command of interest.
400 *
401 * @param args - The arguments for the command.
402 *
403 * @returns A boolean indicating whether the command is visible,
404 * or `false` if the command is not registered.
405 */
406 isVisible(
407 id: string,
408 args: ReadonlyPartialJSONObject = JSONExt.emptyObject
409 ): boolean {
410 let cmd = this._commands.get(id);
411 return cmd ? cmd.isVisible.call(undefined, args) : false;
412 }
413
414 /**
415 * Execute a specific command.
416 *
417 * @param id - The id of the command of interest.
418 *
419 * @param args - The arguments for the command.
420 *
421 * @returns A promise which resolves with the result of the command.
422 *
423 * #### Notes
424 * The promise will reject if the command throws an exception,
425 * or if the command is not registered.
426 */
427 execute(
428 id: string,
429 args: ReadonlyPartialJSONObject = JSONExt.emptyObject
430 ): Promise<any> {
431 // Reject if the command is not registered.
432 let cmd = this._commands.get(id);
433 if (!cmd) {
434 return Promise.reject(new Error(`Command '${id}' not registered.`));
435 }
436
437 // Execute the command and reject if an exception is thrown.
438 let value: any;
439 try {
440 value = cmd.execute.call(undefined, args);
441 } catch (err) {
442 value = Promise.reject(err);
443 }
444
445 // Create the return promise which resolves the result.
446 let result = Promise.resolve(value);
447
448 // Emit the command executed signal.
449 this._commandExecuted.emit({ id, args, result });
450
451 // Return the result promise to the caller.
452 return result;
453 }
454
455 /**
456 * Add a key binding to the registry.
457 *
458 * @param options - The options for creating the key binding.
459 *
460 * @returns A disposable which removes the added key binding.
461 *
462 * #### Notes
463 * If multiple key bindings are registered for the same sequence, the
464 * binding with the highest selector specificity is executed first. A
465 * tie is broken by using the most recently added key binding.
466 *
467 * Ambiguous key bindings are resolved with a timeout. As an example,
468 * suppose two key bindings are registered: one with the key sequence
469 * `['Ctrl D']`, and another with `['Ctrl D', 'Ctrl W']`. If the user
470 * presses `Ctrl D`, the first binding cannot be immediately executed
471 * since the user may intend to complete the chord with `Ctrl W`. For
472 * such cases, a timer is used to allow the chord to be completed. If
473 * the chord is not completed before the timeout, the first binding
474 * is executed.
475 */
476 addKeyBinding(options: CommandRegistry.IKeyBindingOptions): IDisposable {
477 // Create the binding for the given options.
478 let binding = Private.createKeyBinding(options);
479
480 // Add the key binding to the bindings array.
481 this._keyBindings.push(binding);
482
483 // Emit the `bindingChanged` signal.
484 this._keyBindingChanged.emit({ binding, type: 'added' });
485
486 // Return a disposable which will remove the binding.
487 return new DisposableDelegate(() => {
488 // Remove the binding from the array.
489 ArrayExt.removeFirstOf(this._keyBindings, binding);
490
491 // Emit the `bindingChanged` signal.
492 this._keyBindingChanged.emit({ binding, type: 'removed' });
493 });
494 }
495
496 /**
497 * Process a `'keydown'` event and invoke a matching key binding.
498 *
499 * @param event - The event object for a `'keydown'` event.
500 *
501 * #### Notes
502 * This should be called in response to a `'keydown'` event in order
503 * to invoke the command for the best matching key binding.
504 *
505 * The registry **does not** install its own listener for `'keydown'`
506 * events. This allows the application full control over the nodes
507 * and phase for which the registry processes `'keydown'` events.
508 *
509 * When the keydown event is processed, if the event target or any of its
510 * ancestor nodes has a `data-lm-suppress-shortcuts` attribute, its keydown
511 * events will not invoke commands.
512 */
513 processKeydownEvent(event: KeyboardEvent): void {
514 // Bail immediately if playing back keystrokes.
515 if (event.defaultPrevented || this._replaying) {
516 return;
517 }
518
519 // Get the normalized keystroke for the event.
520 const keystroke = CommandRegistry.keystrokeForKeydownEvent(event);
521
522 // If the keystroke is not valid for the keyboard layout, replay
523 // any suppressed events and clear the pending state.
524 if (!keystroke) {
525 this._replayKeydownEvents();
526 this._clearPendingState();
527 return;
528 }
529
530 // Check that only mod key(s) have been pressed.
531 if (CommandRegistry.isModifierKeyPressed(event)) {
532 // Find the exact match for the modifier keys.
533 let { exact } = Private.matchKeyBinding(
534 this._keyBindings,
535 [keystroke],
536 event
537 );
538 if (exact) {
539 // If the mod keys match an exact shortcut, start a dedicated timer.
540 event.preventDefault();
541 event.stopPropagation();
542 this._startModifierTimer(exact);
543 } else {
544 // Otherwise stop potential existing timer.
545 this._clearModifierTimer();
546 }
547 return;
548 }
549
550 // Add the keystroke to the current key sequence.
551 this._keystrokes.push(keystroke);
552
553 // Find the exact and partial matches for the key sequence.
554 const { exact, partial } = Private.matchKeyBinding(
555 this._keyBindings,
556 this._keystrokes,
557 event
558 );
559 // Whether there is any partial match.
560 const hasPartial = partial.length !== 0;
561
562 // If there is no exact match and no partial match, replay
563 // any suppressed events and clear the pending state.
564 if (!exact && !hasPartial) {
565 this._replayKeydownEvents();
566 this._clearPendingState();
567 return;
568 }
569
570 // Stop propagation of the event. If there is only a partial match,
571 // the event will be replayed if a final exact match never occurs.
572 if (exact?.preventDefault || partial.some(match => match.preventDefault)) {
573 event.preventDefault();
574 event.stopPropagation();
575 }
576
577 // Store the event for possible playback in the future and for
578 // the use in execution hold check.
579 this._keydownEvents.push(event);
580
581 // If there is an exact match but no partial match, the exact match
582 // can be dispatched immediately. The pending state is cleared so
583 // the next key press starts from the default state.
584 if (exact && !hasPartial) {
585 this._executeKeyBinding(exact);
586 this._clearPendingState();
587 return;
588 }
589
590 // If there is both an exact match and a partial match, the exact
591 // match is stored for future dispatch in case the timer expires
592 // before a more specific match is triggered.
593 if (exact) {
594 this._exactKeyMatch = exact;
595 }
596
597 // (Re)start the timer to dispatch the most recent exact match
598 // in case the partial match fails to result in an exact match.
599 this._startTimer();
600 }
601
602 /**
603 * Delay the execution of any command matched against the given 'keydown' event
604 * until the `permission` to execute is granted.
605 *
606 * @param event - The event object for a `'keydown'` event.
607 * @param permission - The promise with value indicating whether to proceed with the execution.
608 *
609 * ### Note
610 * This enables the caller of `processKeydownEvent` to asynchronously prevent the
611 * execution of the command based on external events.
612 */
613 holdKeyBindingExecution(event: KeyboardEvent, permission: Promise<boolean>) {
614 this._holdKeyBindingPromises.set(event, permission);
615 }
616
617 /**
618 * Process a ``keyup`` event to clear the timer on the modifier, if it exists.
619 *
620 * @param event - The event object for a `'keydown'` event.
621 */
622 processKeyupEvent(event: KeyboardEvent): void {
623 this._clearModifierTimer();
624 }
625
626 /**
627 * Start or restart the timeout on the modifier keys.
628 *
629 * This timeout will end only if the keys are hold.
630 */
631 private _startModifierTimer(exact: CommandRegistry.IKeyBinding): void {
632 this._clearModifierTimer();
633 this._timerModifierID = window.setTimeout(() => {
634 this._executeKeyBinding(exact);
635 }, Private.modifierkeyTimeOut);
636 }
637
638 /**
639 * Clear the timeout on modifier keys.
640 */
641 private _clearModifierTimer(): void {
642 if (this._timerModifierID !== 0) {
643 clearTimeout(this._timerModifierID);
644 this._timerModifierID = 0;
645 }
646 }
647 /**
648 * Start or restart the pending timeout.
649 */
650 private _startTimer(): void {
651 this._clearTimer();
652 this._timerID = window.setTimeout(() => {
653 this._onPendingTimeout();
654 }, Private.CHORD_TIMEOUT);
655 }
656
657 /**
658 * Clear the pending timeout.
659 */
660 private _clearTimer(): void {
661 if (this._timerID !== 0) {
662 clearTimeout(this._timerID);
663 this._timerID = 0;
664 }
665 }
666
667 /**
668 * Replay the keydown events which were suppressed.
669 */
670 private _replayKeydownEvents(): void {
671 if (this._keydownEvents.length === 0) {
672 return;
673 }
674 this._replaying = true;
675 this._keydownEvents.forEach(Private.replayKeyEvent);
676 this._replaying = false;
677 }
678
679 /**
680 * Execute the command for the given key binding.
681 *
682 * If the command is missing or disabled, a warning will be logged.
683 *
684 * The execution will not proceed if any of the events leading to
685 * the keybinding matching were held with the permission resolving to false.
686 */
687 private async _executeKeyBinding(
688 binding: CommandRegistry.IKeyBinding
689 ): Promise<void> {
690 if (this._holdKeyBindingPromises.size !== 0) {
691 // Copy keydown events list to ensure it is available in async code.
692 const keydownEvents = [...this._keydownEvents];
693 // Wait until all hold requests on execution are lifted.
694 const executionAllowed = (
695 await Promise.race([
696 Promise.all(
697 keydownEvents.map(
698 async event =>
699 this._holdKeyBindingPromises.get(event) ?? Promise.resolve(true)
700 )
701 ),
702 new Promise<boolean[]>(resolve => {
703 setTimeout(() => resolve([false]), Private.KEYBINDING_HOLD_TIMEOUT);
704 })
705 ])
706 ).every(Boolean);
707 // Clear the hold requests.
708 this._holdKeyBindingPromises.clear();
709 // Do not proceed with the execution if any of the hold requests did not get the permission to proceed.
710 if (!executionAllowed) {
711 return;
712 }
713 }
714
715 let { command, args } = binding;
716 let newArgs: ReadonlyPartialJSONObject = {
717 _luminoEvent: { type: 'keybinding', keys: binding.keys },
718 ...args
719 };
720 if (!this.hasCommand(command) || !this.isEnabled(command, newArgs)) {
721 let word = this.hasCommand(command) ? 'enabled' : 'registered';
722 let keys = binding.keys.join(', ');
723 let msg1 = `Cannot execute key binding '${keys}':`;
724 let msg2 = `command '${command}' is not ${word}.`;
725 console.warn(`${msg1} ${msg2}`);
726 return;
727 }
728 await this.execute(command, newArgs);
729 }
730
731 /**
732 * Clear the internal pending state.
733 */
734 private _clearPendingState(): void {
735 this._clearTimer();
736 this._clearModifierTimer();
737 this._exactKeyMatch = null;
738 this._keystrokes.length = 0;
739 this._keydownEvents.length = 0;
740 }
741
742 /**
743 * Handle the partial match timeout.
744 */
745 private _onPendingTimeout(): void {
746 this._timerID = 0;
747 if (this._exactKeyMatch) {
748 this._executeKeyBinding(this._exactKeyMatch);
749 } else {
750 this._replayKeydownEvents();
751 }
752 this._clearPendingState();
753 }
754
755 private _timerID = 0;
756 private _timerModifierID = 0;
757 private _replaying = false;
758 private _keystrokes: string[] = [];
759 private _keydownEvents: KeyboardEvent[] = [];
760 private _keyBindings: CommandRegistry.IKeyBinding[] = [];
761 private _exactKeyMatch: CommandRegistry.IKeyBinding | null = null;
762 private _commands = new Map<string, Private.ICommand>();
763 private _commandChanged = new Signal<
764 this,
765 CommandRegistry.ICommandChangedArgs
766 >(this);
767 private _commandExecuted = new Signal<
768 this,
769 CommandRegistry.ICommandExecutedArgs
770 >(this);
771 private _keyBindingChanged = new Signal<
772 this,
773 CommandRegistry.IKeyBindingChangedArgs
774 >(this);
775 private _holdKeyBindingPromises = new Map<KeyboardEvent, Promise<boolean>>();
776 }
777
778 /**
779 * The namespace for the `CommandRegistry` class statics.
780 */
781 export namespace CommandRegistry {
782 /**
783 * A type alias for a user-defined command function.
784 */
785 export type CommandFunc<T> = (args: ReadonlyPartialJSONObject) => T;
786
787 /**
788 * A type alias for a simple immutable string dataset.
789 */
790 export type Dataset = { readonly [key: string]: string };
791
792 /**
793 * Commands description.
794 */
795 export type Description = { args: ReadonlyJSONObject | null };
796
797 /**
798 * An options object for creating a command.
799 *
800 * #### Notes
801 * A command is an abstract representation of code to be executed along
802 * with metadata for describing how the command should be displayed in
803 * a visual representation.
804 *
805 * A command is a collection of functions, *not* methods. The command
806 * registry will always invoke the command functions with a `thisArg`
807 * which is `undefined`.
808 */
809 export interface ICommandOptions {
810 /**
811 * The function to invoke when the command is executed.
812 *
813 * #### Notes
814 * This should return the result of the command (if applicable) or
815 * a promise which yields the result. The result is resolved as a
816 * promise and that promise is returned to the code which executed
817 * the command.
818 *
819 * This may be invoked even when `isEnabled` returns `false`.
820 *
821 * If called via a keybinding the passed args will include a `_luminoEvent` that specify the event type and keys pressed for customization.
822 */
823 execute: CommandFunc<any | Promise<any>>;
824
825 /**
826 * JSON Schemas describing the command.
827 *
828 * #### Notes
829 * For now, the command arguments are the only one that can be
830 * described.
831 */
832 describedBy?:
833 | Partial<Description>
834 | CommandFunc<Partial<Description> | Promise<Partial<Description>>>;
835
836 /**
837 * The label for the command.
838 *
839 * #### Notes
840 * This can be a string literal, or a function which returns the
841 * label based on the provided command arguments.
842 *
843 * The label is often used as the primary text for the command.
844 *
845 * The default value is an empty string.
846 */
847 label?: string | CommandFunc<string>;
848
849 /**
850 * The index of the mnemonic character in the command's label.
851 *
852 * #### Notes
853 * This can be an index literal, or a function which returns the
854 * mnemonic index based on the provided command arguments.
855 *
856 * The mnemonic character is often used by menus to provide easy
857 * single-key keyboard access for triggering a menu item. It is
858 * typically rendered as an underlined character in the label.
859 *
860 * The default value is `-1`.
861 */
862 mnemonic?: number | CommandFunc<number>;
863
864 /**
865 * The icon renderer for the command.
866 *
867 * #### Notes
868 * This can be an IRenderer object, or a function which returns the
869 * renderer based on the provided command arguments.
870 *
871 * The default value is `undefined`.
872 */
873 icon?:
874 | VirtualElement.IRenderer
875 | undefined
876 | CommandFunc<VirtualElement.IRenderer | undefined>;
877
878 /**
879 * The icon class for the command.
880 *
881 * #### Notes
882 * This class name will be added to the icon node for the visual
883 * representation of the command.
884 *
885 * Multiple class names can be separated with white space.
886 *
887 * This can be a string literal, or a function which returns the
888 * icon based on the provided command arguments.
889 *
890 * The default value is an empty string.
891 */
892 iconClass?: string | CommandFunc<string>;
893
894 /**
895 * The icon label for the command.
896 *
897 * #### Notes
898 * This label will be added as text to the icon node for the visual
899 * representation of the command.
900 *
901 * This can be a string literal, or a function which returns the
902 * label based on the provided command arguments.
903 *
904 * The default value is an empty string.
905 */
906 iconLabel?: string | CommandFunc<string>;
907
908 /**
909 * The caption for the command.
910 *
911 * #### Notes
912 * This should be a simple one line description of the command. It
913 * is used by some visual representations to show quick info about
914 * the command.
915 *
916 * This can be a string literal, or a function which returns the
917 * caption based on the provided command arguments.
918 *
919 * The default value is an empty string.
920 */
921 caption?: string | CommandFunc<string>;
922
923 /**
924 * The usage text for the command.
925 *
926 * #### Notes
927 * This should be a full description of the command, which includes
928 * information about the structure of the arguments and the type of
929 * the return value. It is used by some visual representations when
930 * displaying complete help info about the command.
931 *
932 * This can be a string literal, or a function which returns the
933 * usage text based on the provided command arguments.
934 *
935 * The default value is an empty string.
936 */
937 usage?: string | CommandFunc<string>;
938
939 /**
940 * The general class name for the command.
941 *
942 * #### Notes
943 * This class name will be added to the primary node for the visual
944 * representation of the command.
945 *
946 * Multiple class names can be separated with white space.
947 *
948 * This can be a string literal, or a function which returns the
949 * class name based on the provided command arguments.
950 *
951 * The default value is an empty string.
952 */
953 className?: string | CommandFunc<string>;
954
955 /**
956 * The dataset for the command.
957 *
958 * #### Notes
959 * The dataset values will be added to the primary node for the
960 * visual representation of the command.
961 *
962 * This can be a dataset object, or a function which returns the
963 * dataset object based on the provided command arguments.
964 *
965 * The default value is an empty dataset.
966 */
967 dataset?: Dataset | CommandFunc<Dataset>;
968
969 /**
970 * A function which indicates whether the command is enabled.
971 *
972 * #### Notes
973 * Visual representations may use this value to display a disabled
974 * command as grayed-out or in some other non-interactive fashion.
975 *
976 * The default value is `() => true`.
977 *
978 * If called via a keybinding the passed args will include a `_luminoEvent` that specify the event type and keys pressed for customization
979 */
980 isEnabled?: CommandFunc<boolean>;
981
982 /**
983 * A function which indicates whether the command is toggled.
984 *
985 * #### Notes
986 * Visual representations may use this value to display a toggled
987 * command in a different form, such as a check mark icon for a
988 * menu item or a depressed state for a toggle button.
989 *
990 * The default value is `() => false`.
991 */
992 isToggled?: CommandFunc<boolean>;
993
994 /**
995 * A function which indicates whether the command is toggleable.
996 *
997 * #### Notes
998 * Visual representations may use this value to display a toggled command in
999 * a different form, such as a check box for a menu item or a depressed
1000 * state for a toggle button. This attribute also allows for accessible
1001 * interfaces to notify the user that the command corresponds to some state.
1002 *
1003 * The default value is `true` if an `isToggled` function is given, `false`
1004 * otherwise.
1005 */
1006 isToggleable?: boolean;
1007
1008 /**
1009 * A function which indicates whether the command is visible.
1010 *
1011 * #### Notes
1012 * Visual representations may use this value to hide or otherwise
1013 * not display a non-visible command.
1014 *
1015 * The default value is `() => true`.
1016 */
1017 isVisible?: CommandFunc<boolean>;
1018 }
1019
1020 /**
1021 * An arguments object for the `commandChanged` signal.
1022 */
1023 export interface ICommandChangedArgs {
1024 /**
1025 * The id of the associated command.
1026 *
1027 * This will be `undefined` when the type is `'many-changed'`.
1028 */
1029 readonly id: string | undefined;
1030
1031 /**
1032 * Whether the command was added, removed, or changed.
1033 */
1034 readonly type: 'added' | 'removed' | 'changed' | 'many-changed';
1035 }
1036
1037 /**
1038 * An arguments object for the `commandExecuted` signal.
1039 */
1040 export interface ICommandExecutedArgs {
1041 /**
1042 * The id of the associated command.
1043 */
1044 readonly id: string;
1045
1046 /**
1047 * The arguments object passed to the command.
1048 */
1049 readonly args: ReadonlyPartialJSONObject;
1050
1051 /**
1052 * The promise which resolves with the result of the command.
1053 */
1054 readonly result: Promise<any>;
1055 }
1056
1057 /**
1058 * An options object for creating a key binding.
1059 */
1060 export interface IKeyBindingOptions {
1061 /**
1062 * The default key sequence for the key binding.
1063 *
1064 * A key sequence is composed of one or more keystrokes, where each
1065 * keystroke is a combination of modifiers and a primary key.
1066 *
1067 * Most key sequences will contain a single keystroke. Key sequences
1068 * with multiple keystrokes are called "chords", and are useful for
1069 * implementing modal input (ala Vim).
1070 *
1071 * Each keystroke in the sequence should be of the form:
1072 * `[<modifier 1> [<modifier 2> [<modifier N> ]]]<primary key>`
1073 *
1074 * The supported modifiers are: `Accel`, `Alt`, `Cmd`, `Ctrl`, and
1075 * `Shift`. The `Accel` modifier is translated to `Cmd` on Mac and
1076 * `Ctrl` on all other platforms. The `Cmd` modifier is ignored on
1077 * non-Mac platforms.
1078 *
1079 * Keystrokes are case sensitive.
1080 *
1081 * **Examples:** `['Accel C']`, `['Shift F11']`, `['D', 'D']`
1082 */
1083 keys: string[];
1084
1085 /**
1086 * The CSS selector for the key binding.
1087 *
1088 * The key binding will only be invoked when the selector matches a
1089 * node on the propagation path of the keydown event. This allows
1090 * the key binding to be restricted to user-defined contexts.
1091 *
1092 * The selector must not contain commas.
1093 */
1094 selector: string;
1095
1096 /**
1097 * The id of the command to execute when the binding is matched.
1098 */
1099 command: string;
1100
1101 /**
1102 * The arguments for the command, if necessary.
1103 *
1104 * The default value is an empty object. If a command is activated by _executeKeyBinding, `args = {_luminoEvent: {type: <string>, keys: <string[]>}}`
1105 */
1106 args?: ReadonlyPartialJSONObject;
1107
1108 /**
1109 * The key sequence to use when running on Windows.
1110 *
1111 * If provided, this will override `keys` on Windows platforms.
1112 */
1113 winKeys?: string[];
1114
1115 /**
1116 * The key sequence to use when running on Mac.
1117 *
1118 * If provided, this will override `keys` on Mac platforms.
1119 */
1120 macKeys?: string[];
1121
1122 /**
1123 * The key sequence to use when running on Linux.
1124 *
1125 * If provided, this will override `keys` on Linux platforms.
1126 */
1127 linuxKeys?: string[];
1128
1129 /**
1130 * Whether to prevent default action of the keyboard events during sequence matching.
1131 *
1132 * The default value is `true`.
1133 */
1134 preventDefault?: boolean;
1135 }
1136
1137 /**
1138 * An object which represents a key binding.
1139 *
1140 * #### Notes
1141 * A key binding is an immutable object created by a registry.
1142 */
1143 export interface IKeyBinding {
1144 /**
1145 * The key sequence for the binding.
1146 */
1147 readonly keys: ReadonlyArray<string>;
1148
1149 /**
1150 * The CSS selector for the binding.
1151 */
1152 readonly selector: string;
1153
1154 /**
1155 * The command executed when the binding is matched.
1156 */
1157 readonly command: string;
1158
1159 /**
1160 * The arguments for the command.
1161 */
1162 readonly args: ReadonlyPartialJSONObject;
1163
1164 /**
1165 * Whether to prevent default action of the keyboard events during sequence matching.
1166 *
1167 * The default value is `true`.
1168 */
1169 readonly preventDefault?: boolean;
1170 }
1171
1172 /**
1173 * An arguments object for the `keyBindingChanged` signal.
1174 */
1175 export interface IKeyBindingChangedArgs {
1176 /**
1177 * The key binding which was changed.
1178 */
1179 readonly binding: IKeyBinding;
1180
1181 /**
1182 * Whether the key binding was added or removed.
1183 */
1184 readonly type: 'added' | 'removed';
1185 }
1186
1187 /**
1188 * An object which holds the results of parsing a keystroke.
1189 */
1190 export interface IKeystrokeParts {
1191 /**
1192 * Whether `'Cmd'` appears in the keystroke.
1193 */
1194 cmd: boolean;
1195
1196 /**
1197 * Whether `'Ctrl'` appears in the keystroke.
1198 */
1199 ctrl: boolean;
1200
1201 /**
1202 * Whether `'Alt'` appears in the keystroke.
1203 */
1204 alt: boolean;
1205
1206 /**
1207 * Whether `'Shift'` appears in the keystroke.
1208 */
1209 shift: boolean;
1210
1211 /**
1212 * The primary key for the keystroke.
1213 */
1214 key: string;
1215 }
1216
1217 /**
1218 * Parse a keystroke into its constituent components.
1219 *
1220 * @param keystroke - The keystroke of interest.
1221 *
1222 * @returns The parsed components of the keystroke.
1223 *
1224 * #### Notes
1225 * The keystroke should be of the form:
1226 * `[<modifier 1> [<modifier 2> [<modifier N> ]]]<primary key>`
1227 *
1228 * The supported modifiers are: `Accel`, `Alt`, `Cmd`, `Ctrl`, and
1229 * `Shift`. The `Accel` modifier is translated to `Cmd` on Mac and
1230 * `Ctrl` on all other platforms.
1231 *
1232 * The parsing is tolerant and will not throw exceptions. Notably:
1233 * - Duplicate modifiers are ignored.
1234 * - Extra primary keys are ignored.
1235 * - The order of modifiers and primary key is irrelevant.
1236 * - The keystroke parts should be separated by whitespace.
1237 * - The keystroke is case sensitive.
1238 */
1239 export function parseKeystroke(keystroke: string): IKeystrokeParts {
1240 let key = '';
1241 let alt = false;
1242 let cmd = false;
1243 let ctrl = false;
1244 let shift = false;
1245 for (let token of keystroke.split(/\s+/)) {
1246 if (token === 'Accel') {
1247 if (Platform.IS_MAC) {
1248 cmd = true;
1249 } else {
1250 ctrl = true;
1251 }
1252 } else if (token === 'Alt') {
1253 alt = true;
1254 } else if (token === 'Cmd') {
1255 cmd = true;
1256 } else if (token === 'Ctrl') {
1257 ctrl = true;
1258 } else if (token === 'Shift') {
1259 shift = true;
1260 } else if (token.length > 0) {
1261 key = token;
1262 }
1263 }
1264 return { cmd, ctrl, alt, shift, key };
1265 }
1266
1267 /**
1268 * Normalize a keystroke into a canonical representation.
1269 *
1270 * @param keystroke - The keystroke of interest.
1271 *
1272 * @returns The normalized representation of the keystroke.
1273 *
1274 * #### Notes
1275 * This normalizes the keystroke by removing duplicate modifiers and
1276 * extra primary keys, and assembling the parts in a canonical order.
1277 *
1278 * The `Cmd` modifier is ignored on non-Mac platforms.
1279 */
1280 export function normalizeKeystroke(keystroke: string): string {
1281 let mods = '';
1282 let parts = parseKeystroke(keystroke);
1283 if (parts.ctrl) {
1284 mods += 'Ctrl ';
1285 }
1286 if (parts.alt) {
1287 mods += 'Alt ';
1288 }
1289 if (parts.shift) {
1290 mods += 'Shift ';
1291 }
1292 if (parts.cmd && Platform.IS_MAC) {
1293 mods += 'Cmd ';
1294 }
1295 if (!parts.key) {
1296 return mods.trim();
1297 }
1298 return mods + parts.key;
1299 }
1300
1301 /**
1302 * Get the platform-specific normalized keys for an options object.
1303 *
1304 * @param options - The options for the key binding.
1305 *
1306 * @returns Array of combined, normalized keys.
1307 */
1308 export function normalizeKeys(options: IKeyBindingOptions): string[] {
1309 let keys: string[];
1310 if (Platform.IS_WIN) {
1311 keys = options.winKeys || options.keys;
1312 } else if (Platform.IS_MAC) {
1313 keys = options.macKeys || options.keys;
1314 } else {
1315 keys = options.linuxKeys || options.keys;
1316 }
1317 return keys.map(normalizeKeystroke);
1318 }
1319
1320 /**
1321 * Format keystrokes for display on the local system.
1322 *
1323 * If a list of keystrokes is provided, it will be displayed as
1324 * a comma-separated string
1325 *
1326 * @param keystroke The keystrokes to format
1327 * @returns The keystrokes representation
1328 */
1329 export function formatKeystroke(
1330 keystroke: string | readonly string[]
1331 ): string {
1332 return typeof keystroke === 'string'
1333 ? formatSingleKey(keystroke)
1334 : keystroke.map(formatSingleKey).join(', ');
1335
1336 function formatSingleKey(key: string) {
1337 let mods = [];
1338 let separator = Platform.IS_MAC ? ' ' : '+';
1339 let parts = parseKeystroke(key);
1340 if (parts.ctrl) {
1341 mods.push('Ctrl');
1342 }
1343 if (parts.alt) {
1344 mods.push('Alt');
1345 }
1346 if (parts.shift) {
1347 mods.push('Shift');
1348 }
1349 if (Platform.IS_MAC && parts.cmd) {
1350 mods.push('Cmd');
1351 }
1352 mods.push(parts.key);
1353 return mods.map(Private.formatKey).join(separator);
1354 }
1355 }
1356
1357 /**
1358 * Check if `'keydown'` event is caused by pressing a modifier key that should be ignored.
1359 *
1360 * @param event - The event object for a `'keydown'` event.
1361 *
1362 * @returns `true` if modifier key was pressed, `false` otherwise.
1363 */
1364 export function isModifierKeyPressed(event: KeyboardEvent): boolean {
1365 let layout = getKeyboardLayout();
1366 let key = layout.keyForKeydownEvent(event);
1367 return layout.isModifierKey(key);
1368 }
1369
1370 /**
1371 * Create a normalized keystroke for a `'keydown'` event.
1372 *
1373 * @param event - The event object for a `'keydown'` event.
1374 *
1375 * @returns A normalized keystroke, or an empty string if the event
1376 * does not represent a valid keystroke for the given layout.
1377 */
1378 export function keystrokeForKeydownEvent(event: KeyboardEvent): string {
1379 let layout = getKeyboardLayout();
1380 let key = layout.keyForKeydownEvent(event);
1381 let mods = [];
1382 if (event.ctrlKey) {
1383 mods.push('Ctrl');
1384 }
1385 if (event.altKey) {
1386 mods.push('Alt');
1387 }
1388 if (event.shiftKey) {
1389 mods.push('Shift');
1390 }
1391 if (event.metaKey && Platform.IS_MAC) {
1392 mods.push('Cmd');
1393 }
1394 if (!layout.isModifierKey(key)) {
1395 mods.push(key);
1396 }
1397 // for purely modifier key strings
1398 return mods.join(' ');
1399 }
1400 }
1401
1402 /**
1403 * The namespace for the module implementation details.
1404 */
1405 namespace Private {
1406 /**
1407 * The timeout in ms for triggering a key binding chord.
1408 */
1409 export const CHORD_TIMEOUT = 1000;
1410
1411 /**
1412 * The timeout in ms for stopping the hold on keybinding execution.
1413 */
1414 export const KEYBINDING_HOLD_TIMEOUT = 1000;
1415
1416 /**
1417 * The timeout in ms for triggering a modifer key binding.
1418 */
1419 export const modifierkeyTimeOut = 500;
1420
1421 /**
1422 * A convenience type alias for a command func.
1423 */
1424 export type CommandFunc<T> = CommandRegistry.CommandFunc<T>;
1425
1426 /**
1427 * A convenience type alias for a command dataset.
1428 */
1429 export type Dataset = CommandRegistry.Dataset;
1430
1431 /**
1432 * A normalized command object.
1433 */
1434 export interface ICommand {
1435 readonly execute: CommandFunc<any>;
1436 readonly describedBy: CommandFunc<
1437 CommandRegistry.Description | Promise<CommandRegistry.Description>
1438 >;
1439 readonly label: CommandFunc<string>;
1440 readonly mnemonic: CommandFunc<number>;
1441 readonly icon: CommandFunc<VirtualElement.IRenderer | undefined>;
1442 readonly iconClass: CommandFunc<string>;
1443 readonly iconLabel: CommandFunc<string>;
1444 readonly caption: CommandFunc<string>;
1445 readonly usage: CommandFunc<string>;
1446 readonly className: CommandFunc<string>;
1447 readonly dataset: CommandFunc<Dataset>;
1448 readonly isEnabled: CommandFunc<boolean>;
1449 readonly isToggled: CommandFunc<boolean>;
1450 readonly isToggleable: boolean;
1451 readonly isVisible: CommandFunc<boolean>;
1452 }
1453
1454 /**
1455 * Create a normalized command from an options object.
1456 */
1457 export function createCommand(
1458 options: CommandRegistry.ICommandOptions
1459 ): ICommand {
1460 return {
1461 execute: options.execute,
1462 describedBy: asFunc<
1463 CommandRegistry.Description | Promise<CommandRegistry.Description>
1464 >(
1465 typeof options.describedBy === 'function'
1466 ? (options.describedBy as CommandFunc<
1467 CommandRegistry.Description | Promise<CommandRegistry.Description>
1468 >)
1469 : { args: null, ...options.describedBy },
1470 () => {
1471 return { args: null };
1472 }
1473 ),
1474 label: asFunc(options.label, emptyStringFunc),
1475 mnemonic: asFunc(options.mnemonic, negativeOneFunc),
1476 icon: asFunc(options.icon, undefinedFunc),
1477 iconClass: asFunc(options.iconClass, emptyStringFunc),
1478 iconLabel: asFunc(options.iconLabel, emptyStringFunc),
1479 caption: asFunc(options.caption, emptyStringFunc),
1480 usage: asFunc(options.usage, emptyStringFunc),
1481 className: asFunc(options.className, emptyStringFunc),
1482 dataset: asFunc(options.dataset, emptyDatasetFunc),
1483 isEnabled: options.isEnabled || trueFunc,
1484 isToggled: options.isToggled || falseFunc,
1485 isToggleable: options.isToggleable || !!options.isToggled,
1486 isVisible: options.isVisible || trueFunc
1487 };
1488 }
1489
1490 /**
1491 * Create a key binding object from key binding options.
1492 */
1493 export function createKeyBinding(
1494 options: CommandRegistry.IKeyBindingOptions
1495 ): CommandRegistry.IKeyBinding {
1496 return {
1497 keys: CommandRegistry.normalizeKeys(options),
1498 selector: validateSelector(options),
1499 command: options.command,
1500 args: options.args || JSONExt.emptyObject,
1501 preventDefault: options.preventDefault ?? true
1502 };
1503 }
1504
1505 /**
1506 * An object which holds the results of a key binding match.
1507 */
1508 export interface IMatchResult {
1509 /**
1510 * The best key binding which exactly matches the key sequence.
1511 */
1512 exact: CommandRegistry.IKeyBinding | null;
1513
1514 /**
1515 * The key bindings which partially match the sequence.
1516 */
1517 partial: CommandRegistry.IKeyBinding[];
1518 }
1519
1520 /**
1521 * Find the key bindings which match a key sequence.
1522 *
1523 * This returns a match result which contains the best exact matching
1524 * binding, and a flag which indicates if there are partial matches.
1525 */
1526 export function matchKeyBinding(
1527 bindings: ReadonlyArray<CommandRegistry.IKeyBinding>,
1528 keys: ReadonlyArray<string>,
1529 event: KeyboardEvent
1530 ): IMatchResult {
1531 // The current best exact match.
1532 let exact: CommandRegistry.IKeyBinding | null = null;
1533
1534 // Partial matches.
1535 let partial = [];
1536
1537 // The match distance for the exact match.
1538 let distance = Infinity;
1539
1540 // The specificity for the exact match.
1541 let specificity = 0;
1542
1543 // Iterate over the bindings and search for the best match.
1544 for (let i = 0, n = bindings.length; i < n; ++i) {
1545 // Lookup the current binding.
1546 let binding = bindings[i];
1547
1548 // Check whether the key binding sequence is a match.
1549 let sqm = matchSequence(binding.keys, keys);
1550
1551 // If there is no match, the binding is ignored.
1552 if (sqm === SequenceMatch.None) {
1553 continue;
1554 }
1555
1556 // If it is a partial match and no other partial match has been
1557 // found, ensure the selector matches and set the partial flag.
1558 if (sqm === SequenceMatch.Partial) {
1559 if (targetDistance(binding.selector, event) !== -1) {
1560 partial.push(binding);
1561 }
1562 continue;
1563 }
1564
1565 // Ignore the match if the selector doesn't match, or if the
1566 // matched node is farther away than the current best match.
1567 let td = targetDistance(binding.selector, event);
1568 if (td === -1 || td > distance) {
1569 continue;
1570 }
1571
1572 // Get the specificity for the selector.
1573 let sp = Selector.calculateSpecificity(binding.selector);
1574
1575 // Update the best match if this match is stronger.
1576 if (!exact || td < distance || sp >= specificity) {
1577 exact = binding;
1578 distance = td;
1579 specificity = sp;
1580 }
1581 }
1582
1583 // Return the match result.
1584 return { exact, partial };
1585 }
1586
1587 /**
1588 * Replay a keyboard event.
1589 *
1590 * This synthetically dispatches a clone of the keyboard event.
1591 */
1592 export function replayKeyEvent(event: KeyboardEvent): void {
1593 event.target!.dispatchEvent(cloneKeyboardEvent(event));
1594 }
1595
1596 export function formatKey(key: string): string {
1597 if (Platform.IS_MAC) {
1598 return MAC_DISPLAY.hasOwnProperty(key) ? MAC_DISPLAY[key] : key;
1599 } else {
1600 return WIN_DISPLAY.hasOwnProperty(key) ? WIN_DISPLAY[key] : key;
1601 }
1602 }
1603
1604 const MAC_DISPLAY: { [key: string]: string } = {
1605 Backspace: '⌫',
1606 Tab: '⇥',
1607 Enter: '⏎',
1608 Shift: '⇧',
1609 Ctrl: '⌃',
1610 Alt: '⌥',
1611 Escape: '⎋',
1612 PageUp: '⇞',
1613 PageDown: '⇟',
1614 End: '↘',
1615 Home: '↖',
1616 ArrowLeft: '←',
1617 ArrowUp: '↑',
1618 ArrowRight: '→',
1619 ArrowDown: '↓',
1620 Delete: '⌦',
1621 Cmd: '⌘'
1622 };
1623
1624 const WIN_DISPLAY: { [key: string]: string } = {
1625 Escape: 'Esc',
1626 PageUp: 'Page Up',
1627 PageDown: 'Page Down',
1628 ArrowLeft: 'Left',
1629 ArrowUp: 'Up',
1630 ArrowRight: 'Right',
1631 ArrowDown: 'Down',
1632 Delete: 'Del'
1633 };
1634
1635 /**
1636 * A singleton empty string function.
1637 */
1638 const emptyStringFunc = () => '';
1639
1640 /**
1641 * A singleton `-1` number function
1642 */
1643 const negativeOneFunc = () => -1;
1644
1645 /**
1646 * A singleton true boolean function.
1647 */
1648 const trueFunc = () => true;
1649
1650 /**
1651 * A singleton false boolean function.
1652 */
1653 const falseFunc = () => false;
1654
1655 /**
1656 * A singleton empty dataset function.
1657 */
1658 const emptyDatasetFunc = () => ({});
1659
1660 /**
1661 * A singleton undefined function
1662 */
1663 const undefinedFunc = () => undefined;
1664
1665 /**
1666 * Cast a value or command func to a command func.
1667 */
1668 function asFunc<T>(
1669 value: undefined | T | CommandFunc<T>,
1670 dfault: CommandFunc<T>
1671 ): CommandFunc<T> {
1672 if (value === undefined) {
1673 return dfault;
1674 }
1675 if (typeof value === 'function') {
1676 return value as CommandFunc<T>;
1677 }
1678 return () => value;
1679 }
1680
1681 /**
1682 * Validate the selector for an options object.
1683 *
1684 * This returns the validated selector, or throws if the selector is
1685 * invalid or contains commas.
1686 */
1687 function validateSelector(
1688 options: CommandRegistry.IKeyBindingOptions
1689 ): string {
1690 if (options.selector.indexOf(',') !== -1) {
1691 throw new Error(`Selector cannot contain commas: ${options.selector}`);
1692 }
1693 if (!Selector.isValid(options.selector)) {
1694 throw new Error(`Invalid selector: ${options.selector}`);
1695 }
1696 return options.selector;
1697 }
1698
1699 /**
1700 * An enum which describes the possible sequence matches.
1701 */
1702 const enum SequenceMatch {
1703 None,
1704 Exact,
1705 Partial
1706 }
1707
1708 /**
1709 * Test whether a key binding sequence matches a key sequence.
1710 *
1711 * Returns a `SequenceMatch` value indicating the type of match.
1712 */
1713 function matchSequence(
1714 bindKeys: ReadonlyArray<string>,
1715 userKeys: ReadonlyArray<string>
1716 ): SequenceMatch {
1717 if (bindKeys.length < userKeys.length) {
1718 return SequenceMatch.None;
1719 }
1720 for (let i = 0, n = userKeys.length; i < n; ++i) {
1721 if (bindKeys[i] !== userKeys[i]) {
1722 return SequenceMatch.None;
1723 }
1724 }
1725 if (bindKeys.length > userKeys.length) {
1726 return SequenceMatch.Partial;
1727 }
1728 return SequenceMatch.Exact;
1729 }
1730
1731 /**
1732 * Find the distance from the target node to the first matching node.
1733 *
1734 * This traverses the event path from `target` to `currentTarget` and
1735 * computes the distance from `target` to the first node which matches
1736 * the CSS selector. If no match is found, `-1` is returned.
1737 */
1738 function targetDistance(selector: string, event: KeyboardEvent): number {
1739 let targ = event.target as Element | null;
1740 let curr = event.currentTarget as Element | null;
1741 for (let dist = 0; targ !== null; targ = targ.parentElement, ++dist) {
1742 if (targ.hasAttribute('data-lm-suppress-shortcuts')) {
1743 return -1;
1744 }
1745 if (Selector.matches(targ, selector)) {
1746 return dist;
1747 }
1748 if (targ === curr) {
1749 return -1;
1750 }
1751 }
1752 return -1;
1753 }
1754
1755 /**
1756 * Clone a keyboard event.
1757 */
1758 function cloneKeyboardEvent(event: KeyboardEvent): KeyboardEvent {
1759 // A custom event is required because Chrome nulls out the
1760 // `keyCode` field in user-generated `KeyboardEvent` types.
1761 let clone = document.createEvent('Event') as any;
1762 let bubbles = event.bubbles || true;
1763 let cancelable = event.cancelable || true;
1764 clone.initEvent(event.type || 'keydown', bubbles, cancelable);
1765 clone.key = event.key || '';
1766 clone.keyCode = event.keyCode || 0;
1767 clone.which = event.keyCode || 0;
1768 clone.ctrlKey = event.ctrlKey || false;
1769 clone.altKey = event.altKey || false;
1770 clone.shiftKey = event.shiftKey || false;
1771 clone.metaKey = event.metaKey || false;
1772 clone.view = event.view || window;
1773 return clone as KeyboardEvent;
1774 }
1775 }