Debian Codegraph @

packages/commands/tests/src/index.spec.ts

raw
1 /* eslint-disable @typescript-eslint/no-empty-function */
2 // Copyright (c) Jupyter Development Team.
3 // Distributed under the terms of the Modified BSD License.
4 /*-----------------------------------------------------------------------------
5 | Copyright (c) 2014-2017, PhosphorJS Contributors
6 |
7 | Distributed under the terms of the BSD 3-Clause License.
8 |
9 | The full license is in the file LICENSE, distributed with this software.
10 |----------------------------------------------------------------------------*/
11 import { expect } from 'chai';
12
13 import { CommandRegistry } from '@lumino/commands';
14
15 import { JSONObject, ReadonlyJSONObject } from '@lumino/coreutils';
16
17 import { Platform } from '@lumino/domutils';
18
19 const NULL_COMMAND = {
20 execute: (args: JSONObject) => {
21 return args;
22 }
23 };
24
25 describe('@lumino/commands', () => {
26 describe('CommandRegistry', () => {
27 let registry: CommandRegistry = null!;
28
29 beforeEach(() => {
30 registry = new CommandRegistry();
31 });
32
33 describe('#constructor()', () => {
34 it('should take no arguments', () => {
35 expect(registry).to.be.an.instanceof(CommandRegistry);
36 });
37 });
38
39 describe('#commandChanged', () => {
40 it('should be emitted when a command is added', () => {
41 let called = false;
42 registry.commandChanged.connect((reg, args) => {
43 expect(reg).to.equal(registry);
44 expect(args.id).to.equal('test');
45 expect(args.type).to.equal('added');
46 called = true;
47 });
48 registry.addCommand('test', NULL_COMMAND);
49 expect(called).to.equal(true);
50 });
51
52 it('should be emitted when a command is changed', () => {
53 let called = false;
54 registry.addCommand('test', NULL_COMMAND);
55 registry.commandChanged.connect((reg, args) => {
56 expect(reg).to.equal(registry);
57 expect(args.id).to.equal('test');
58 expect(args.type).to.equal('changed');
59 called = true;
60 });
61 registry.notifyCommandChanged('test');
62 expect(called).to.equal(true);
63 });
64
65 it('should be emitted when a command is removed', () => {
66 let called = false;
67 let disposable = registry.addCommand('test', NULL_COMMAND);
68 registry.commandChanged.connect((reg, args) => {
69 expect(reg).to.equal(registry);
70 expect(args.id).to.equal('test');
71 expect(args.type).to.equal('removed');
72 called = true;
73 });
74 disposable.dispose();
75 expect(called).to.equal(true);
76 });
77 });
78
79 describe('#commandExecuted', () => {
80 it('should be emitted when a command is executed', () => {
81 let called = false;
82 registry.addCommand('test', NULL_COMMAND);
83 registry.commandExecuted.connect((reg, args) => {
84 expect(reg).to.equal(registry);
85 expect(args.id).to.equal('test');
86 expect(args.args).to.deep.equal({});
87 expect(args.result).to.be.an.instanceof(Promise);
88 called = true;
89 });
90 registry.execute('test');
91 expect(called).to.equal(true);
92 });
93 });
94
95 describe('#keyBindings', () => {
96 it('should be the keybindings in the palette', () => {
97 registry.addCommand('test', { execute: () => {} });
98 registry.addKeyBinding({
99 keys: ['Ctrl ;'],
100 selector: `body`,
101 command: 'test'
102 });
103 expect(registry.keyBindings.length).to.equal(1);
104 expect(registry.keyBindings[0].command).to.equal('test');
105 });
106 });
107
108 describe('#listCommands()', () => {
109 it('should list the ids of the registered commands', () => {
110 registry.addCommand('test0', NULL_COMMAND);
111 registry.addCommand('test1', NULL_COMMAND);
112 expect(registry.listCommands()).to.deep.equal(['test0', 'test1']);
113 });
114
115 it('should be a new array', () => {
116 registry.addCommand('test0', NULL_COMMAND);
117 registry.addCommand('test1', NULL_COMMAND);
118 let cmds = registry.listCommands();
119 cmds.push('test2');
120 expect(registry.listCommands()).to.deep.equal(['test0', 'test1']);
121 });
122 });
123
124 describe('#hasCommand()', () => {
125 it('should test whether a specific command is registerd', () => {
126 registry.addCommand('test', NULL_COMMAND);
127 expect(registry.hasCommand('test')).to.equal(true);
128 expect(registry.hasCommand('foo')).to.equal(false);
129 });
130 });
131
132 describe('#addCommand()', () => {
133 it('should add a command to the registry', () => {
134 registry.addCommand('test', NULL_COMMAND);
135 expect(registry.hasCommand('test')).to.equal(true);
136 });
137
138 it('should return a disposable which will unregister the command', () => {
139 let disposable = registry.addCommand('test', NULL_COMMAND);
140 disposable.dispose();
141 expect(registry.hasCommand('test')).to.equal(false);
142 });
143
144 it('should throw an error if the given `id` is already registered', () => {
145 registry.addCommand('test', NULL_COMMAND);
146 expect(() => {
147 registry.addCommand('test', NULL_COMMAND);
148 }).to.throw(Error);
149 });
150
151 it('should clone the `cmd` before adding it to the registry', () => {
152 let cmd = {
153 execute: (args: JSONObject) => {
154 return args;
155 },
156 label: 'foo'
157 };
158 registry.addCommand('test', cmd);
159 cmd.label = 'bar';
160 expect(registry.label('test')).to.equal('foo');
161 });
162 });
163
164 describe('#notifyCommandChanged()', () => {
165 it('should emit the `commandChanged` signal for the command', () => {
166 let called = false;
167 registry.addCommand('test', NULL_COMMAND);
168 registry.commandChanged.connect((reg, args) => {
169 expect(reg).to.equal(registry);
170 expect(args.id).to.equal('test');
171 expect(args.type).to.equal('changed');
172 called = true;
173 });
174 registry.notifyCommandChanged('test');
175 expect(called).to.equal(true);
176 });
177
178 it('should throw an error if the command is not registered', () => {
179 expect(() => {
180 registry.notifyCommandChanged('foo');
181 }).to.throw(Error);
182 });
183 });
184
185 describe('#label()', () => {
186 it('should get the display label for a specific command', () => {
187 let cmd = {
188 execute: (args: JSONObject) => {
189 return args;
190 },
191 label: 'foo'
192 };
193 registry.addCommand('test', cmd);
194 expect(registry.label('test')).to.equal('foo');
195 });
196
197 it('should give the appropriate label given arguments', () => {
198 let cmd = {
199 execute: (args: JSONObject) => {
200 return args;
201 },
202 label: (args: JSONObject) => {
203 return JSON.stringify(args);
204 }
205 };
206 registry.addCommand('test', cmd);
207 expect(registry.label('test', {})).to.equal('{}');
208 });
209
210 it('should return an empty string if the command is not registered', () => {
211 expect(registry.label('foo')).to.equal('');
212 });
213
214 it('should default to an empty string for a command', () => {
215 registry.addCommand('test', NULL_COMMAND);
216 expect(registry.label('test')).to.equal('');
217 });
218 });
219
220 describe('#mnemonic()', () => {
221 it('should get the mnemonic index for a specific command', () => {
222 let cmd = {
223 execute: (args: JSONObject) => {
224 return args;
225 },
226 mnemonic: 1
227 };
228 registry.addCommand('test', cmd);
229 expect(registry.mnemonic('test')).to.equal(1);
230 });
231
232 it('should give the appropriate mnemonic given arguments', () => {
233 let cmd = {
234 execute: (args: JSONObject) => {
235 return args;
236 },
237 mnemonic: (args: JSONObject) => {
238 return JSON.stringify(args).length;
239 }
240 };
241 registry.addCommand('test', cmd);
242 expect(registry.mnemonic('test', {})).to.equal(2);
243 });
244
245 it('should return a `-1` if the command is not registered', () => {
246 expect(registry.mnemonic('foo')).to.equal(-1);
247 });
248
249 it('should default to `-1` for a command', () => {
250 registry.addCommand('test', NULL_COMMAND);
251 expect(registry.mnemonic('test')).to.equal(-1);
252 });
253 });
254
255 describe('#icon()', () => {
256 const iconRenderer = {
257 render: (host: HTMLElement, options?: any) => {
258 const renderNode = document.createElement('div');
259 renderNode.className = 'lm-render';
260 host.appendChild(renderNode);
261 }
262 };
263
264 it('should get the icon for a specific command', () => {
265 let cmd = {
266 execute: (args: JSONObject) => {
267 return args;
268 },
269 icon: iconRenderer
270 };
271 registry.addCommand('test', cmd);
272 expect(registry.icon('test')).to.equal(iconRenderer);
273 });
274
275 it('should give the appropriate icon given arguments', () => {
276 let cmd = {
277 execute: (args: JSONObject) => {
278 return args;
279 },
280 icon: iconRenderer
281 };
282 registry.addCommand('test', cmd);
283 expect(registry.icon('test', {})).to.equal(iconRenderer);
284 });
285
286 it('should return undefined if the command is not registered', () => {
287 expect(registry.icon('foo')).to.equal(undefined);
288 });
289
290 it('should default to undefined for a command', () => {
291 registry.addCommand('test', NULL_COMMAND);
292 expect(registry.icon('test')).to.equal(undefined);
293 });
294 });
295
296 describe('#caption()', () => {
297 it('should get the caption for a specific command', () => {
298 let cmd = {
299 execute: (args: JSONObject) => {
300 return args;
301 },
302 caption: 'foo'
303 };
304 registry.addCommand('test', cmd);
305 expect(registry.caption('test')).to.equal('foo');
306 });
307
308 it('should give the appropriate caption given arguments', () => {
309 let cmd = {
310 execute: (args: JSONObject) => {
311 return args;
312 },
313 caption: (args: JSONObject) => {
314 return JSON.stringify(args);
315 }
316 };
317 registry.addCommand('test', cmd);
318 expect(registry.caption('test', {})).to.equal('{}');
319 });
320
321 it('should return an empty string if the command is not registered', () => {
322 expect(registry.caption('foo')).to.equal('');
323 });
324
325 it('should default to an empty string for a command', () => {
326 registry.addCommand('test', NULL_COMMAND);
327 expect(registry.caption('test')).to.equal('');
328 });
329 });
330
331 describe('#describedBy()', () => {
332 it('should get the description for a specific command', async () => {
333 const description = {
334 args: {
335 properties: {},
336 additionalProperties: false,
337 type: 'object'
338 }
339 };
340 let cmd = {
341 execute: (args: JSONObject) => {
342 return args;
343 },
344 describedBy: description
345 };
346 registry.addCommand('test', cmd);
347 expect(await registry.describedBy('test')).to.deep.equal(description);
348 });
349
350 it('should accept a function', async () => {
351 const description = {
352 args: {
353 properties: {},
354 additionalProperties: false,
355 type: 'object'
356 }
357 };
358
359 let cmd = {
360 execute: (args: JSONObject) => {
361 return args;
362 },
363 describedBy: () => description
364 };
365 registry.addCommand('test', cmd);
366 expect(await registry.describedBy('test')).to.deep.equal(description);
367 });
368
369 it('should accept an asynchronous function', async () => {
370 const description = {
371 args: {
372 properties: {},
373 additionalProperties: false,
374 type: 'object'
375 }
376 };
377
378 let cmd = {
379 execute: (args: JSONObject) => {
380 return args;
381 },
382 describedBy: () => Promise.resolve(description)
383 };
384 registry.addCommand('test', cmd);
385 expect(await registry.describedBy('test')).to.deep.equal(description);
386 });
387
388 it('should accept args', async () => {
389 const description = {
390 properties: {},
391 additionalProperties: false,
392 type: 'object'
393 };
394
395 let cmd = {
396 execute: (args: JSONObject) => {
397 return args;
398 },
399 describedBy: (args: ReadonlyJSONObject) => {
400 return {
401 args
402 };
403 }
404 };
405 registry.addCommand('test', cmd);
406 expect(
407 await registry.describedBy('test', description as any)
408 ).to.deep.equal({ args: description });
409 });
410
411 it('should return an empty description if the command is not registered', async () => {
412 expect(await registry.describedBy('foo')).to.deep.equal({ args: null });
413 });
414
415 it('should default to an empty description for a command', async () => {
416 registry.addCommand('test', NULL_COMMAND);
417 expect(await registry.describedBy('test')).to.deep.equal({
418 args: null
419 });
420 });
421 });
422
423 describe('#usage()', () => {
424 it('should get the usage text for a specific command', () => {
425 let cmd = {
426 execute: (args: JSONObject) => {
427 return args;
428 },
429 usage: 'foo'
430 };
431 registry.addCommand('test', cmd);
432 expect(registry.usage('test')).to.equal('foo');
433 });
434
435 it('should give the appropriate usage text given arguments', () => {
436 let cmd = {
437 execute: (args: JSONObject) => {
438 return args;
439 },
440 usage: (args: JSONObject) => {
441 return JSON.stringify(args);
442 }
443 };
444 registry.addCommand('test', cmd);
445 expect(registry.usage('test', {})).to.equal('{}');
446 });
447
448 it('should return an empty string if the command is not registered', () => {
449 expect(registry.usage('foo')).to.equal('');
450 });
451
452 it('should default to an empty string for a command', () => {
453 registry.addCommand('test', NULL_COMMAND);
454 expect(registry.usage('test')).to.equal('');
455 });
456 });
457
458 describe('#className()', () => {
459 it('should get the extra class name for a specific command', () => {
460 let cmd = {
461 execute: (args: JSONObject) => {
462 return args;
463 },
464 className: 'foo'
465 };
466 registry.addCommand('test', cmd);
467 expect(registry.className('test')).to.equal('foo');
468 });
469
470 it('should give the appropriate class name given arguments', () => {
471 let cmd = {
472 execute: (args: JSONObject) => {
473 return args;
474 },
475 className: (args: JSONObject) => {
476 return JSON.stringify(args);
477 }
478 };
479 registry.addCommand('test', cmd);
480 expect(registry.className('test', {})).to.equal('{}');
481 });
482
483 it('should return an empty string if the command is not registered', () => {
484 expect(registry.className('foo')).to.equal('');
485 });
486
487 it('should default to an empty string for a command', () => {
488 registry.addCommand('test', NULL_COMMAND);
489 expect(registry.className('test')).to.equal('');
490 });
491 });
492
493 describe('#isEnabled()', () => {
494 it('should test whether a specific command is enabled', () => {
495 let cmd = {
496 execute: (args: JSONObject) => {
497 return args;
498 },
499 isEnabled: (args: JSONObject) => {
500 return args.enabled as boolean;
501 }
502 };
503 registry.addCommand('test', cmd);
504 expect(registry.isEnabled('test', { enabled: true })).to.equal(true);
505 expect(registry.isEnabled('test', { enabled: false })).to.equal(false);
506 });
507
508 it('should return `false` if the command is not registered', () => {
509 expect(registry.isEnabled('foo')).to.equal(false);
510 });
511
512 it('should default to `true` for a command', () => {
513 registry.addCommand('test', NULL_COMMAND);
514 expect(registry.isEnabled('test')).to.equal(true);
515 });
516 });
517
518 describe('#isToggled()', () => {
519 it('should test whether a specific command is toggled', () => {
520 let cmd = {
521 execute: (args: JSONObject) => {
522 return args;
523 },
524 isToggled: (args: JSONObject) => {
525 return args.toggled as boolean;
526 }
527 };
528 registry.addCommand('test', cmd);
529 expect(registry.isToggled('test', { toggled: true })).to.equal(true);
530 expect(registry.isToggled('test', { toggled: false })).to.equal(false);
531 });
532
533 it('should return `false` if the command is not registered', () => {
534 expect(registry.isToggled('foo')).to.equal(false);
535 });
536
537 it('should default to `false` for a command', () => {
538 registry.addCommand('test', NULL_COMMAND);
539 expect(registry.isToggled('test')).to.equal(false);
540 });
541 });
542
543 describe('#isVisible()', () => {
544 it('should test whether a specific command is visible', () => {
545 let cmd = {
546 execute: (args: JSONObject) => {
547 return args;
548 },
549 isVisible: (args: JSONObject) => {
550 return args.visible as boolean;
551 }
552 };
553 registry.addCommand('test', cmd);
554 expect(registry.isVisible('test', { visible: true })).to.equal(true);
555 expect(registry.isVisible('test', { visible: false })).to.equal(false);
556 });
557
558 it('should return `false` if the command is not registered', () => {
559 expect(registry.isVisible('foo')).to.equal(false);
560 });
561
562 it('should default to `true` for a command', () => {
563 registry.addCommand('test', NULL_COMMAND);
564 expect(registry.isVisible('test')).to.equal(true);
565 });
566 });
567
568 describe('#execute()', () => {
569 it('should execute a specific command', () => {
570 let called = false;
571 let cmd = {
572 execute: (args: JSONObject) => {
573 called = true;
574 }
575 };
576 registry.addCommand('test', cmd);
577 registry.execute('test');
578 expect(called).to.equal(true);
579 });
580
581 it('should resolve with the result of the command', done => {
582 let cmd = {
583 execute: (args: JSONObject) => {
584 return args;
585 }
586 };
587 registry.addCommand('test', cmd);
588 registry.execute('test', { foo: 12 }).then(result => {
589 expect(result).to.deep.equal({ foo: 12 });
590 done();
591 });
592 });
593
594 it('should reject if the command throws an error', done => {
595 let cmd = {
596 execute: (args: JSONObject) => {
597 throw new Error('');
598 }
599 };
600 registry.addCommand('test', cmd);
601 registry.execute('test').catch(() => {
602 done();
603 });
604 });
605
606 it('should reject if the command is not registered', done => {
607 registry.execute('foo').catch(() => {
608 done();
609 });
610 });
611 });
612
613 let elemID = 0;
614 let elem: HTMLElement = null!;
615 let parent: HTMLElement = null!;
616
617 beforeEach(() => {
618 parent = document.createElement('div') as HTMLElement;
619 elem = document.createElement('div') as HTMLElement;
620 parent.classList.add('lm-test-parent');
621 elem.id = `test${elemID++}`;
622 elem.addEventListener('keydown', event => {
623 registry.processKeydownEvent(event);
624 });
625 parent.appendChild(elem);
626 document.body.appendChild(parent);
627 });
628
629 afterEach(() => {
630 document.body.removeChild(parent);
631 });
632
633 describe('#addKeyBinding()', () => {
634 it('should add key bindings to the registry', () => {
635 let called = false;
636 registry.addCommand('test', {
637 execute: () => {
638 called = true;
639 }
640 });
641 registry.addKeyBinding({
642 keys: ['Ctrl ;'],
643 selector: `#${elem.id}`,
644 command: 'test'
645 });
646 elem.dispatchEvent(
647 new KeyboardEvent('keydown', {
648 keyCode: 59,
649 ctrlKey: true
650 })
651 );
652 expect(called).to.equal(true);
653 });
654
655 it('should remove a binding when disposed', () => {
656 let called = false;
657 registry.addCommand('test', {
658 execute: () => {
659 called = true;
660 }
661 });
662 let binding = registry.addKeyBinding({
663 keys: ['Ctrl ;'],
664 selector: `#${elem.id}`,
665 command: 'test'
666 });
667 binding.dispose();
668 elem.dispatchEvent(
669 new KeyboardEvent('keydown', {
670 keyCode: 59,
671 ctrlKey: true
672 })
673 );
674 expect(called).to.equal(false);
675 });
676
677 it('should emit a key binding changed signal when added and removed', () => {
678 let added = false;
679 registry.addCommand('test', { execute: () => {} });
680 registry.keyBindingChanged.connect((sender, args) => {
681 added = args.type === 'added';
682 });
683 let binding = registry.addKeyBinding({
684 keys: ['Ctrl ;'],
685 selector: `#${elem.id}`,
686 command: 'test'
687 });
688 expect(added).to.equal(true);
689 binding.dispose();
690 expect(added).to.equal(false);
691 });
692
693 it('should throw an error if binding has an invalid selector', () => {
694 let options = { keys: ['Ctrl ;'], selector: '..', command: 'test' };
695 expect(() => {
696 registry.addKeyBinding(options);
697 }).to.throw(Error);
698 });
699 });
700
701 describe('#processKeydownEvent()', () => {
702 it('should dispatch on a correct keyboard event', () => {
703 let called = false;
704 let _luminoEventType;
705 let _luminoEventKeys;
706 registry.addCommand('test', {
707 execute: args => {
708 called = true;
709 _luminoEventType = (args._luminoEvent as ReadonlyJSONObject).type;
710 _luminoEventKeys = (args._luminoEvent as ReadonlyJSONObject).keys;
711 }
712 });
713 registry.addKeyBinding({
714 keys: ['Ctrl ;'],
715 selector: `#${elem.id}`,
716 command: 'test'
717 });
718 elem.dispatchEvent(
719 new KeyboardEvent('keydown', {
720 keyCode: 59,
721 ctrlKey: true
722 })
723 );
724 expect(called).to.equal(true);
725 expect(_luminoEventType).to.equal('keybinding');
726 expect(_luminoEventKeys).to.contain('Ctrl ;');
727 });
728
729 it('should not dispatch on a suppressed node', () => {
730 let called = false;
731 registry.addCommand('test', {
732 execute: () => {
733 called = true;
734 }
735 });
736 registry.addKeyBinding({
737 keys: ['Ctrl ;'],
738 selector: `.lm-test-parent`,
739 command: 'test'
740 });
741 parent.setAttribute('data-lm-suppress-shortcuts', 'true');
742 elem.dispatchEvent(
743 new KeyboardEvent('keydown', {
744 keyCode: 59,
745 ctrlKey: true
746 })
747 );
748 expect(called).to.equal(false);
749 });
750
751 it('should not dispatch on a non-matching keyboard event', () => {
752 let called = false;
753 registry.addCommand('test', {
754 execute: () => {
755 called = true;
756 }
757 });
758 registry.addKeyBinding({
759 keys: ['Ctrl ;'],
760 selector: `#${elem.id}`,
761 command: 'test'
762 });
763 elem.dispatchEvent(
764 new KeyboardEvent('keydown', {
765 keyCode: 45,
766 ctrlKey: true
767 })
768 );
769 expect(called).to.equal(false);
770 });
771
772 it('should not dispatch with non-matching modifiers', () => {
773 let count = 0;
774 registry.addCommand('test', {
775 execute: () => {
776 count++;
777 }
778 });
779 registry.addKeyBinding({
780 keys: ['Ctrl S'],
781 selector: `#${elem.id}`,
782 command: 'test'
783 });
784 elem.dispatchEvent(
785 new KeyboardEvent('keydown', {
786 keyCode: 83,
787 altKey: true
788 })
789 );
790 expect(count).to.equal(0);
791 elem.dispatchEvent(
792 new KeyboardEvent('keydown', {
793 keyCode: 83,
794 shiftKey: true
795 })
796 );
797 expect(count).to.equal(0);
798 });
799
800 it('should not dispatch on a prevented keydown event', () => {
801 let called = false;
802 registry.addCommand('test', {
803 execute: args => {
804 called = true;
805 }
806 });
807 registry.addKeyBinding({
808 keys: ['Ctrl ;'],
809 selector: `#${elem.id}`,
810 command: 'test'
811 });
812 const event = new KeyboardEvent('keydown', {
813 keyCode: 59,
814 ctrlKey: true,
815 cancelable: true
816 });
817
818 event.preventDefault();
819
820 elem.dispatchEvent(event);
821 expect(called).to.equal(false);
822 });
823
824 it('should prevent default on dispatch', () => {
825 registry.addCommand('test', {
826 execute: () => void 0
827 });
828 registry.addKeyBinding({
829 keys: ['Ctrl ;'],
830 selector: `#${elem.id}`,
831 command: 'test'
832 });
833 const event = new KeyboardEvent('keydown', {
834 keyCode: 59,
835 ctrlKey: true
836 });
837 let defaultPrevented = false;
838 event.preventDefault = () => {
839 defaultPrevented = true;
840 };
841 elem.dispatchEvent(event);
842 expect(defaultPrevented).to.equal(true);
843 });
844
845 it('should not prevent default when sequence does not match', () => {
846 registry.addCommand('test', {
847 execute: () => void 0
848 });
849 registry.addKeyBinding({
850 keys: ['Ctrl ;'],
851 selector: `#${elem.id}`,
852 command: 'test'
853 });
854 const event = new KeyboardEvent('keydown', {
855 keyCode: 59,
856 ctrlKey: false
857 });
858 let defaultPrevented = false;
859 event.preventDefault = () => {
860 defaultPrevented = true;
861 };
862 elem.dispatchEvent(event);
863 expect(defaultPrevented).to.equal(false);
864 });
865
866 it('should not prevent default if keybinding opts out', () => {
867 registry.addCommand('test', {
868 execute: () => void 0
869 });
870 registry.addKeyBinding({
871 keys: ['Ctrl ;'],
872 selector: `#${elem.id}`,
873 command: 'test',
874 preventDefault: false
875 });
876 const event = new KeyboardEvent('keydown', {
877 keyCode: 59,
878 ctrlKey: true
879 });
880 let defaultPrevented = false;
881 event.preventDefault = () => {
882 defaultPrevented = true;
883 };
884 elem.dispatchEvent(event);
885 expect(defaultPrevented).to.equal(false);
886 });
887
888 it('should dispatch with multiple chords in a key sequence', () => {
889 let count = 0;
890 registry.addCommand('test', {
891 execute: () => {
892 count++;
893 }
894 });
895 registry.addKeyBinding({
896 keys: ['Ctrl K', 'Ctrl L'],
897 selector: `#${elem.id}`,
898 command: 'test'
899 });
900 elem.dispatchEvent(
901 new KeyboardEvent('keydown', {
902 keyCode: 75, // `K` key
903 ctrlKey: true
904 })
905 );
906 expect(count).to.equal(0);
907 elem.dispatchEvent(
908 new KeyboardEvent('keydown', {
909 keyCode: 76, // `L` key
910 ctrlKey: true
911 })
912 );
913 expect(count).to.equal(1);
914 elem.dispatchEvent(
915 new KeyboardEvent('keydown', {
916 keyCode: 76, // `L` key
917 ctrlKey: true
918 })
919 );
920 expect(count).to.equal(1);
921 elem.dispatchEvent(
922 new KeyboardEvent('keydown', {
923 keyCode: 75, // `K` key
924 ctrlKey: true
925 })
926 );
927 expect(count).to.equal(1);
928 elem.dispatchEvent(
929 new KeyboardEvent('keydown', {
930 keyCode: 76, // `L` key
931 ctrlKey: true
932 })
933 );
934 expect(count).to.equal(2);
935 });
936
937 it('should not execute handler without matching selector', () => {
938 let count = 0;
939 registry.addCommand('test', {
940 execute: () => {
941 count++;
942 }
943 });
944 registry.addKeyBinding({
945 keys: ['Shift P'],
946 selector: '.inaccessible-scope',
947 command: 'test'
948 });
949 expect(count).to.equal(0);
950 elem.dispatchEvent(
951 new KeyboardEvent('keydown', {
952 keyCode: 80, // `P` key
953 ctrlKey: true
954 })
955 );
956 expect(count).to.equal(0);
957 });
958
959 it('should not execute a handler when missing a modifier', () => {
960 let count = 0;
961 registry.addCommand('test', {
962 execute: () => {
963 count++;
964 }
965 });
966 registry.addKeyBinding({
967 keys: ['Ctrl P'],
968 selector: `#${elem.id}`,
969 command: 'test'
970 });
971 expect(count).to.equal(0);
972 // Dispatch `P` without ctrl
973 elem.dispatchEvent(new KeyboardEvent('keydown', { keyCode: 80 }));
974 expect(count).to.equal(0);
975 });
976
977 it('should register partial and exact matches', () => {
978 let count1 = 0;
979 let count2 = 0;
980 registry.addCommand('test1', {
981 execute: () => {
982 count1++;
983 }
984 });
985 registry.addCommand('test2', {
986 execute: () => {
987 count2++;
988 }
989 });
990 registry.addKeyBinding({
991 keys: ['Ctrl S'],
992 selector: `#${elem.id}`,
993 command: 'test1'
994 });
995 registry.addKeyBinding({
996 keys: ['Ctrl S', 'Ctrl D'],
997 selector: `#${elem.id}`,
998 command: 'test2'
999 });
1000 expect(count1).to.equal(0);
1001 expect(count2).to.equal(0);
1002 elem.dispatchEvent(
1003 new KeyboardEvent('keydown', {
1004 keyCode: 83,
1005 ctrlKey: true
1006 })
1007 );
1008 expect(count1).to.equal(0);
1009 expect(count2).to.equal(0);
1010 elem.dispatchEvent(
1011 new KeyboardEvent('keydown', {
1012 keyCode: 68,
1013 ctrlKey: true
1014 })
1015 );
1016 expect(count1).to.equal(0);
1017 expect(count2).to.equal(1);
1018 });
1019
1020 it('should recognize permutations of modifiers', () => {
1021 let count1 = 0;
1022 let count2 = 0;
1023 registry.addCommand('test1', {
1024 execute: () => {
1025 count1++;
1026 }
1027 });
1028 registry.addCommand('test2', {
1029 execute: () => {
1030 count2++;
1031 }
1032 });
1033 registry.addKeyBinding({
1034 keys: ['Shift Alt Ctrl T'],
1035 selector: `#${elem.id}`,
1036 command: 'test1'
1037 });
1038 registry.addKeyBinding({
1039 keys: ['Alt Shift Ctrl Q'],
1040 selector: `#${elem.id}`,
1041 command: 'test2'
1042 });
1043 expect(count1).to.equal(0);
1044 elem.dispatchEvent(
1045 new KeyboardEvent('keydown', {
1046 keyCode: 84,
1047 ctrlKey: true,
1048 altKey: true,
1049 shiftKey: true
1050 })
1051 );
1052 expect(count1).to.equal(1);
1053 expect(count2).to.equal(0);
1054 elem.dispatchEvent(
1055 new KeyboardEvent('keydown', {
1056 keyCode: 81,
1057 ctrlKey: true,
1058 altKey: true,
1059 shiftKey: true
1060 })
1061 );
1062 expect(count2).to.equal(1);
1063 });
1064
1065 it('should play back a partial match that was not completed', () => {
1066 let codes: number[] = [];
1067 let keydown = (event: KeyboardEvent) => {
1068 codes.push(event.keyCode);
1069 };
1070 document.body.addEventListener('keydown', keydown);
1071 let called = false;
1072 registry.addCommand('test', {
1073 execute: () => {
1074 called = true;
1075 }
1076 });
1077 registry.addKeyBinding({
1078 keys: ['D', 'D'],
1079 selector: `#${elem.id}`,
1080 command: 'test'
1081 });
1082 elem.dispatchEvent(
1083 new KeyboardEvent('keydown', {
1084 keyCode: 68,
1085 bubbles: true
1086 })
1087 );
1088 expect(codes.length).to.equal(0);
1089 elem.dispatchEvent(
1090 new KeyboardEvent('keydown', {
1091 keyCode: 69,
1092 bubbles: true
1093 })
1094 );
1095 expect(called).to.equal(false);
1096 expect(codes).to.deep.equal([68, 69]);
1097 document.body.removeEventListener('keydown', keydown);
1098 });
1099
1100 it('should play back a partial match that times out', done => {
1101 let codes: number[] = [];
1102 let keydown = (event: KeyboardEvent) => {
1103 codes.push(event.keyCode);
1104 };
1105 document.body.addEventListener('keydown', keydown);
1106 let called = false;
1107 registry.addCommand('test', {
1108 execute: () => {
1109 called = true;
1110 }
1111 });
1112 registry.addKeyBinding({
1113 keys: ['D', 'D'],
1114 selector: `#${elem.id}`,
1115 command: 'test'
1116 });
1117 elem.dispatchEvent(new KeyboardEvent('keydown', { keyCode: 68 }));
1118 expect(codes.length).to.equal(0);
1119 setTimeout(() => {
1120 expect(codes).to.deep.equal([68]);
1121 expect(called).to.equal(false);
1122 document.body.removeEventListener('keydown', keydown);
1123 done();
1124 }, 1300);
1125 });
1126
1127 it('should resolve an exact match of partial match time out', done => {
1128 let called1 = false;
1129 let called2 = false;
1130 registry.addCommand('test1', {
1131 execute: () => {
1132 called1 = true;
1133 }
1134 });
1135 registry.addCommand('test2', {
1136 execute: () => {
1137 called2 = true;
1138 }
1139 });
1140 registry.addKeyBinding({
1141 keys: ['D', 'D'],
1142 selector: `#${elem.id}`,
1143 command: 'test1'
1144 });
1145 registry.addKeyBinding({
1146 keys: ['D'],
1147 selector: `#${elem.id}`,
1148 command: 'test2'
1149 });
1150 elem.dispatchEvent(new KeyboardEvent('keydown', { keyCode: 68 }));
1151 expect(called1).to.equal(false);
1152 expect(called2).to.equal(false);
1153 setTimeout(() => {
1154 expect(called1).to.equal(false);
1155 expect(called2).to.equal(true);
1156 done();
1157 }, 1300);
1158 });
1159
1160 it('should pick the selector with greater specificity', () => {
1161 elem.classList.add('test');
1162 let called1 = false;
1163 let called2 = false;
1164 registry.addCommand('test1', {
1165 execute: () => {
1166 called1 = true;
1167 }
1168 });
1169 registry.addCommand('test2', {
1170 execute: () => {
1171 called2 = true;
1172 }
1173 });
1174 registry.addKeyBinding({
1175 keys: ['Ctrl ;'],
1176 selector: '.test',
1177 command: 'test1'
1178 });
1179 registry.addKeyBinding({
1180 keys: ['Ctrl ;'],
1181 selector: `#${elem.id}`,
1182 command: 'test2'
1183 });
1184 elem.dispatchEvent(
1185 new KeyboardEvent('keydown', {
1186 keyCode: 59,
1187 ctrlKey: true
1188 })
1189 );
1190 expect(called1).to.equal(false);
1191 expect(called2).to.equal(true);
1192 });
1193
1194 it('should propagate if partial binding selector does not match', () => {
1195 let codes: number[] = [];
1196 let keydown = (event: KeyboardEvent) => {
1197 codes.push(event.keyCode);
1198 };
1199 document.body.addEventListener('keydown', keydown);
1200 let called = false;
1201 registry.addCommand('test', {
1202 execute: () => {
1203 called = true;
1204 }
1205 });
1206 registry.addKeyBinding({
1207 keys: ['D', 'D'],
1208 selector: '#baz',
1209 command: 'test'
1210 });
1211 elem.dispatchEvent(
1212 new KeyboardEvent('keydown', {
1213 keyCode: 68,
1214 bubbles: true
1215 })
1216 );
1217 expect(codes).to.deep.equal([68]);
1218 expect(called).to.equal(false);
1219 document.body.removeEventListener('keydown', keydown);
1220 });
1221
1222 it('should propagate if exact binding selector does not match', () => {
1223 let codes: number[] = [];
1224 let keydown = (event: KeyboardEvent) => {
1225 codes.push(event.keyCode);
1226 };
1227 document.body.addEventListener('keydown', keydown);
1228 let called = false;
1229 registry.addCommand('test', {
1230 execute: () => {
1231 called = true;
1232 }
1233 });
1234 registry.addKeyBinding({
1235 keys: ['D'],
1236 selector: '#baz',
1237 command: 'test'
1238 });
1239 elem.dispatchEvent(
1240 new KeyboardEvent('keydown', {
1241 keyCode: 68,
1242 bubbles: true
1243 })
1244 );
1245 expect(codes).to.deep.equal([68]);
1246 expect(called).to.equal(false);
1247 document.body.removeEventListener('keydown', keydown);
1248 });
1249
1250 it('should ignore modifier keys pressed in the middle of key sequence', () => {
1251 let count = 0;
1252 registry.addCommand('test', {
1253 execute: () => {
1254 count++;
1255 }
1256 });
1257 registry.addKeyBinding({
1258 keys: ['Ctrl K', 'Ctrl L'],
1259 selector: `#${elem.id}`,
1260 command: 'test'
1261 });
1262 elem.dispatchEvent(
1263 new KeyboardEvent('keydown', {
1264 keyCode: 75, // `K` key
1265 ctrlKey: true
1266 })
1267 );
1268 expect(count).to.equal(0);
1269 // User presses `ctrl` again - this should not break the sequence.
1270 elem.dispatchEvent(
1271 new KeyboardEvent('keydown', {
1272 keyCode: 17,
1273 ctrlKey: true
1274 })
1275 );
1276 expect(count).to.equal(0);
1277 elem.dispatchEvent(
1278 new KeyboardEvent('keydown', {
1279 keyCode: 76, // `L` key
1280 ctrlKey: true
1281 })
1282 );
1283 expect(count).to.equal(1);
1284 });
1285
1286 it('should process key sequences that use different modifier keys', () => {
1287 let count = 0;
1288 registry.addCommand('test', {
1289 execute: () => {
1290 count++;
1291 }
1292 });
1293 registry.addKeyBinding({
1294 keys: ['Shift K', 'Ctrl L'],
1295 selector: `#${elem.id}`,
1296 command: 'test'
1297 });
1298 let eventShift = new KeyboardEvent('keydown', {
1299 keyCode: 16,
1300 shiftKey: true
1301 });
1302 let eventK = new KeyboardEvent('keydown', {
1303 keyCode: 75,
1304 shiftKey: true
1305 });
1306 let eventCtrl = new KeyboardEvent('keydown', {
1307 keyCode: 17,
1308 ctrlKey: true
1309 });
1310 let eventL = new KeyboardEvent('keydown', {
1311 keyCode: 76,
1312 ctrlKey: true
1313 });
1314 elem.dispatchEvent(eventShift);
1315 expect(count).to.equal(0);
1316 elem.dispatchEvent(eventK);
1317 expect(count).to.equal(0);
1318 elem.dispatchEvent(eventCtrl);
1319 expect(count).to.equal(0);
1320 elem.dispatchEvent(eventL);
1321 expect(count).to.equal(1);
1322 });
1323 });
1324
1325 describe('.holdKeyBindingExecution()', () => {
1326 let calledPromise: Promise<boolean>;
1327 let execute: () => void;
1328
1329 beforeEach(() => {
1330 calledPromise = Promise.race([
1331 new Promise<boolean>(_resolve => {
1332 execute = () => _resolve(true);
1333 }),
1334 new Promise<boolean>(resolve =>
1335 setTimeout(() => resolve(false), 1000)
1336 )
1337 ]);
1338 });
1339
1340 it('should proceed with command execution if permission of the event resolves to true', async () => {
1341 registry.addCommand('test', {
1342 execute
1343 });
1344 registry.addKeyBinding({
1345 keys: ['Ctrl ;'],
1346 selector: `#${elem.id}`,
1347 command: 'test'
1348 });
1349 const event = new KeyboardEvent('keydown', {
1350 keyCode: 59,
1351 ctrlKey: true
1352 });
1353 registry.holdKeyBindingExecution(event, Promise.resolve(true));
1354 elem.dispatchEvent(event);
1355 const called = await calledPromise;
1356 expect(called).to.equal(true);
1357 });
1358
1359 it('should prevent command execution if permission of the event resolves to false', async () => {
1360 registry.addCommand('test', {
1361 execute
1362 });
1363 registry.addKeyBinding({
1364 keys: ['Ctrl ;'],
1365 selector: `#${elem.id}`,
1366 command: 'test'
1367 });
1368 const event = new KeyboardEvent('keydown', {
1369 keyCode: 59,
1370 ctrlKey: true
1371 });
1372 registry.holdKeyBindingExecution(event, Promise.resolve(false));
1373 elem.dispatchEvent(event);
1374 const called = await calledPromise;
1375 expect(called).to.equal(false);
1376 });
1377
1378 it('should prevent command execution if permission for any of the events resolves to false', async () => {
1379 registry.addCommand('test', {
1380 execute
1381 });
1382 registry.addKeyBinding({
1383 keys: ['Shift ['],
1384 selector: `#${elem.id}`,
1385 command: 'test'
1386 });
1387 const shiftEvent = new KeyboardEvent('keydown', {
1388 keyCode: 16,
1389 shiftKey: true
1390 });
1391 const bracketEvent = new KeyboardEvent('keydown', {
1392 keyCode: 219,
1393 shiftKey: true
1394 });
1395 registry.holdKeyBindingExecution(shiftEvent, Promise.resolve(true));
1396 registry.holdKeyBindingExecution(bracketEvent, Promise.resolve(false));
1397 elem.dispatchEvent(shiftEvent);
1398 elem.dispatchEvent(bracketEvent);
1399 const called = await calledPromise;
1400 expect(called).to.equal(false);
1401 });
1402 });
1403
1404 describe('.parseKeystroke()', () => {
1405 it('should parse a keystroke into its parts', () => {
1406 let parts = CommandRegistry.parseKeystroke('Ctrl Shift Alt S');
1407 expect(parts.cmd).to.equal(false);
1408 expect(parts.ctrl).to.equal(true);
1409 expect(parts.alt).to.equal(true);
1410 expect(parts.shift).to.equal(true);
1411 expect(parts.key).to.equal('S');
1412 });
1413
1414 it('should preserve arrow names in key without formatting', () => {
1415 let parts = CommandRegistry.parseKeystroke('ArrowRight');
1416 expect(parts.key).to.equal('ArrowRight');
1417 });
1418
1419 it('should be a tolerant parse', () => {
1420 let parts = CommandRegistry.parseKeystroke('G Ctrl Shift S Shift K');
1421 expect(parts.cmd).to.equal(false);
1422 expect(parts.ctrl).to.equal(true);
1423 expect(parts.alt).to.equal(false);
1424 expect(parts.shift).to.equal(true);
1425 expect(parts.key).to.equal('K');
1426 });
1427 });
1428
1429 describe('.formatKeystroke()', () => {
1430 it('should prepend modifiers', () => {
1431 let label = CommandRegistry.formatKeystroke('Ctrl Alt Shift S');
1432 if (Platform.IS_MAC) {
1433 expect(label).to.equal('\u2303 \u2325 \u21E7 S');
1434 } else {
1435 expect(label).to.equal('Ctrl+Alt+Shift+S');
1436 }
1437 });
1438
1439 it('should format arrow', () => {
1440 let label = CommandRegistry.formatKeystroke('Alt ArrowDown');
1441 if (Platform.IS_MAC) {
1442 expect(label).to.equal('\u2325 \u2193');
1443 } else {
1444 expect(label).to.equal('Alt+Down');
1445 }
1446 });
1447
1448 it('should format a list of keys', () => {
1449 let label = CommandRegistry.formatKeystroke(['D', 'D']);
1450 expect(label).to.equal('D, D');
1451 });
1452 });
1453
1454 describe('.normalizeKeystroke()', () => {
1455 it('should normalize and validate a keystroke', () => {
1456 let stroke = CommandRegistry.normalizeKeystroke('Ctrl S');
1457 expect(stroke).to.equal('Ctrl S');
1458 });
1459
1460 it('should handle multiple modifiers', () => {
1461 let stroke = CommandRegistry.normalizeKeystroke('Ctrl Shift Alt S');
1462 expect(stroke).to.equal('Ctrl Alt Shift S');
1463 });
1464
1465 it('should handle platform specific modifiers', () => {
1466 let stroke = '';
1467 if (Platform.IS_MAC) {
1468 stroke = CommandRegistry.normalizeKeystroke('Cmd S');
1469 expect(stroke).to.equal('Cmd S');
1470 stroke = CommandRegistry.normalizeKeystroke('Accel S');
1471 expect(stroke).to.equal('Cmd S');
1472 } else {
1473 stroke = CommandRegistry.normalizeKeystroke('Cmd S');
1474 expect(stroke).to.equal('S');
1475 stroke = CommandRegistry.normalizeKeystroke('Accel S');
1476 expect(stroke).to.equal('Ctrl S');
1477 }
1478 });
1479 });
1480
1481 describe('.keystrokeForKeydownEvent()', () => {
1482 it('should create a normalized keystroke', () => {
1483 let keystroke = CommandRegistry.keystrokeForKeydownEvent(
1484 new KeyboardEvent('keydown', {
1485 ctrlKey: true,
1486 keyCode: 83
1487 })
1488 );
1489 expect(keystroke).to.equal('Ctrl S');
1490 });
1491
1492 it('should handle multiple modifiers', () => {
1493 let keystroke = CommandRegistry.keystrokeForKeydownEvent(
1494 new KeyboardEvent('keydown', {
1495 ctrlKey: true,
1496 altKey: true,
1497 shiftKey: true,
1498 keyCode: 83
1499 })
1500 );
1501 expect(keystroke).to.equal('Ctrl Alt Shift S');
1502 });
1503
1504 it('should fail on an invalid shortcut', () => {
1505 let keystroke = CommandRegistry.keystrokeForKeydownEvent(
1506 new KeyboardEvent('keydown', { keyCode: -1 })
1507 );
1508 expect(keystroke).to.equal('');
1509 });
1510
1511 it('should return keys that are marked as modifier in keyboard layout', () => {
1512 let keystroke = CommandRegistry.keystrokeForKeydownEvent(
1513 new KeyboardEvent('keydown', { keyCode: 17, ctrlKey: true })
1514 );
1515 expect(keystroke).to.equal('Ctrl');
1516 });
1517 });
1518 });
1519 });