Skip to content

Commit

Permalink
Handle multiple navigation shortcuts
Browse files Browse the repository at this point in the history
  • Loading branch information
luin committed Nov 20, 2023
1 parent 69134e4 commit ceed3d9
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 2 deletions.
7 changes: 5 additions & 2 deletions modules/uiNode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ import Quill from '../core/quill';

const isMac = /Mac/i.test(navigator.platform);

// Export for testing
export const TTL_FOR_VALID_SELECTION_CHANGE = 100;

// A loose check to determine if the shortcut can move the caret before a UI node:
// <ANY_PARENT>[CARET]<div class="ql-ui"></div>[CONTENT]</ANY_PARENT>
const canMoveCaretBeforeUINode = (event: KeyboardEvent) => {
Expand Down Expand Up @@ -78,10 +81,10 @@ class UINode extends Module {
* the selection within the handler of a `selectionchange` event.
*/
private ensureListeningToSelectionChange() {
if (this.isListening) return;
this.selectionChangeDeadline = Date.now() + TTL_FOR_VALID_SELECTION_CHANGE;

if (this.isListening) return;
this.isListening = true;
this.selectionChangeDeadline = Date.now() + 100;

const listener = () => {
this.isListening = false;
Expand Down
41 changes: 41 additions & 0 deletions test/unit/modules/uiNode.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import '../../../quill';
import { describe, expect, test } from 'vitest';
import UINode, {
TTL_FOR_VALID_SELECTION_CHANGE,
} from '../../../modules/uiNode';
import Quill, { Delta } from '../../../core';

// Fake timer is not supported in browser mode yet.
const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));

describe('uiNode', () => {
test('extends deadline when multiple possible shortcuts are pressed', async () => {
const quill = new Quill(document.createElement('div'));
document.body.appendChild(quill.container);
quill.setContents(
new Delta().insert('item 1').insert('\n', { list: 'bullet' }),
);
new UINode(quill, {});

for (let i = 0; i < 2; i += 1) {
quill.root.dispatchEvent(
new KeyboardEvent('keydown', { key: 'ArrowRight', metaKey: true }),
);
await delay(TTL_FOR_VALID_SELECTION_CHANGE / 2);
}

quill.root.dispatchEvent(
new KeyboardEvent('keydown', { key: 'ArrowLeft', metaKey: true }),
);
const range = document.createRange();
range.setStart(quill.root.querySelector('li')!, 0);
range.setEnd(quill.root.querySelector('li')!, 0);

const selection = document.getSelection();
selection?.removeAllRanges();
selection?.addRange(range);

await delay(TTL_FOR_VALID_SELECTION_CHANGE / 2);
expect(selection?.getRangeAt(0).startOffset).toEqual(1);
});
});

0 comments on commit ceed3d9

Please sign in to comment.