Skip to content

Commit

Permalink
fix: Escape key should always close drop (#271)
Browse files Browse the repository at this point in the history
- also resolve a Promise for open() method to know when it finished
  • Loading branch information
ghiscoding authored May 7, 2024
1 parent ee56dfc commit 84e317b
Showing 1 changed file with 27 additions and 11 deletions.
38 changes: 27 additions & 11 deletions packages/multiple-select-vanilla/src/MultipleSelectInstance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -826,9 +826,8 @@ export class MultipleSelectInstance {
}

this._bindEventService.bind(this.parentElm, 'keydown', ((e: KeyboardEvent) => {
if (e.code === 'Escape' && !this.options.keepOpen) {
this.close();
this.choiceElm.focus();
if (e.code === 'Escape') {
this.handleEscapeKey();
}
}) as EventListener);

Expand Down Expand Up @@ -1037,6 +1036,9 @@ export class MultipleSelectInstance {
e.preventDefault();
this.moveHighlightDown();
break;
case 'Escape':
this.handleEscapeKey();
break;
case 'Enter':
case ' ': {
// if we're focused on the OK button then don't execute following block
Expand Down Expand Up @@ -1073,6 +1075,7 @@ export class MultipleSelectInstance {
this.changeCurrentOptionHighlight();
this.okButtonElm?.focus();
}
break;
}
}
}) as EventListener,
Expand All @@ -1086,6 +1089,13 @@ export class MultipleSelectInstance {
}
}

protected handleEscapeKey() {
if (!this.options.keepOpen) {
this.close();
this.choiceElm.focus();
}
}

/**
* Checks if user reached the end of the list through mouse scrolling and/or arrow down,
* then scroll back to the top whenever that happens.
Expand Down Expand Up @@ -1118,14 +1128,20 @@ export class MultipleSelectInstance {
* The default delay is 0ms (which is 1 CPU cycle) when nothing is provided, to avoid a delay we can pass `-1` or `null`
* @param {number} [openDelay=0] - provide an optional delay, defaults to 0
*/
open(openDelay: number | null = 0) {
if (openDelay !== null && openDelay >= 0) {
// eslint-disable-next-line prefer-const
clearTimeout(this.openDelayTimer);
this.openDelayTimer = setTimeout(() => this.openDrop(), openDelay);
} else {
this.openDrop();
}
open(openDelay: number | null = 0): Promise<void> {
return new Promise(resolve => {
if (openDelay !== null && openDelay >= 0) {
// eslint-disable-next-line prefer-const
clearTimeout(this.openDelayTimer);
this.openDelayTimer = setTimeout(() => {
this.openDrop();
resolve();
}, openDelay);
} else {
this.openDrop();
resolve();
}
});
}

protected openDrop() {
Expand Down

0 comments on commit 84e317b

Please sign in to comment.