Key handling improvements

This commit is contained in:
Cory LaViska
2020-06-19 19:37:34 -04:00
parent c47bd6adc4
commit f52d236fdf
3 changed files with 9 additions and 19 deletions

4
src/components.d.ts vendored
View File

@@ -376,10 +376,6 @@ export namespace Components {
* Removes focus from the menu.
*/
"removeFocus": () => Promise<void>;
/**
* Passes key presses to the control. Useful for managing the menu when other elements have focus.
*/
"sendKeyEvent": (event: KeyboardEvent) => Promise<void>;
/**
* Sets focus on the menu.
*/

View File

@@ -189,6 +189,11 @@ export class Dropdown {
});
}
// Prevent scrolling when certain keys are pressed
if ([' ', 'ArrowDown', 'ArrowUp', 'Home', 'End'].includes(event.key)) {
event.preventDefault();
}
const menu = this.getMenu();
// If a menu is present, focus on it when certain keys are pressed
@@ -198,10 +203,10 @@ export class Dropdown {
return;
}
// All other keys should focus the menu and pass through the event to type-to-search
// All other keys focus the menu and pass the event through to menu (necessary for type-to-search to work)
if (menu && event.target !== menu) {
menu.setFocus();
menu.sendKeyEvent(event);
menu.dispatchEvent(new KeyboardEvent(event.type, event));
return;
}
}

View File

@@ -54,12 +54,6 @@ export class Menu {
this.host.blur();
}
/** Passes key presses to the control. Useful for managing the menu when other elements have focus. */
@Method()
async sendKeyEvent(event: KeyboardEvent) {
this.handleKeyDown(event);
}
getItems() {
const slot = this.host.shadowRoot.querySelector('slot');
return [...slot.assignedElements({ flatten: true })].filter(
@@ -111,11 +105,6 @@ export class Menu {
this.ignoreMouseTimeout = setTimeout(() => (this.ignoreMouseEvents = false), 500);
this.ignoreMouseEvents = true;
// Prevent scrolling when certain keys are pressed
if ([' ', 'ArrowDown', 'ArrowUp', 'Home', 'End'].includes(event.key)) {
event.preventDefault();
}
// Make a selection when pressing enter
if (event.key === 'Enter') {
const item = this.getActiveItem();
@@ -145,8 +134,8 @@ export class Menu {
index = items.length - 1;
}
if (index < 0) index = 0;
if (index > items.length - 1) index = items.length - 1;
if (index < 0) index = items.length - 1;
if (index > items.length - 1) index = 0;
this.setActiveItem(items[index]);
this.scrollItemIntoView(items[index]);