fix(context-menu): correctly tab in/out of nested menus

This commit is contained in:
Eric Y Liu 2021-03-19 16:54:19 -07:00
commit 1101fe3bff
2 changed files with 25 additions and 2 deletions

View file

@ -113,6 +113,7 @@
}}" }}"
on:keydown on:keydown
on:keydown="{(e) => { on:keydown="{(e) => {
if ($hasPopup) return;
if (e.key === 'ArrowDown') { if (e.key === 'ArrowDown') {
if (focusIndex < options.length - 1) focusIndex++; if (focusIndex < options.length - 1) focusIndex++;
} else if (e.key === 'ArrowUp') { } else if (e.key === 'ArrowUp') {

View file

@ -60,6 +60,8 @@
let rootMenuPosition = [0, 0]; let rootMenuPosition = [0, 0];
let currentIndex = -1; let currentIndex = -1;
let submenuOpen = false; let submenuOpen = false;
let focusIndex = 0;
let options = [];
const unsubCurrentIndex = ctx.currentIndex.subscribe((index) => { const unsubCurrentIndex = ctx.currentIndex.subscribe((index) => {
currentIndex = index; currentIndex = index;
@ -186,13 +188,33 @@
await tick(); await tick();
const options = ref.querySelectorAll('li[tabindex]'); options = [...ref.querySelectorAll('li[tabindex]')];
if (options[0]) options[0].focus(); if (options[focusIndex]) options[focusIndex].focus();
return; return;
} }
if (submenuOpen) {
if (key === 'ArrowLeft') {
submenuOpen = false;
focusIndex = 0;
return;
}
if (key === 'ArrowDown') {
if (focusIndex < options.length - 1) focusIndex++;
} else if (key === 'ArrowUp') {
if (focusIndex === -1) {
focusIndex = options.length - 1;
} else {
if (focusIndex > 0) focusIndex--;
}
}
if (options[focusIndex]) options[focusIndex].focus();
}
if (key === ' ' || key === 'Enter') { if (key === ' ' || key === 'Enter') {
handleClick({ fromKeyboard: true }); handleClick({ fromKeyboard: true });
} }