diff --git a/src/components/dropdown/dropdown.tsx b/src/components/dropdown/dropdown.tsx index 8e95c4034..ada935048 100644 --- a/src/components/dropdown/dropdown.tsx +++ b/src/components/dropdown/dropdown.tsx @@ -1,4 +1,5 @@ import { Component, Element, Event, EventEmitter, Method, Prop, Watch, h } from '@stencil/core'; +import { scrollIntoView } from '../../utilities/scroll'; import Popover from '../../utilities/popover'; let id = 0; @@ -187,6 +188,8 @@ export class Dropdown { } handleDocumentKeyDown(event: KeyboardEvent) { + const menu = this.getMenu(); + // Close when escape is pressed if (event.key === 'Escape') { this.hide(); @@ -207,17 +210,25 @@ export class Dropdown { }); } - // Prevent scrolling when certain keys are pressed + // Prevent the page from scrolling when certain keys are pressed if (['ArrowDown', 'ArrowUp', 'Home', 'End'].includes(event.key)) { event.preventDefault(); } // If a menu is present, focus on it when certain keys are pressed - const menu = this.getMenu(); if (menu && ['ArrowDown', 'ArrowUp'].includes(event.key)) { event.preventDefault(); menu.setFocus(); - return; + } + + // If a menu is present, ensure the active menu item stays in view when the selection changes + if (menu && ['ArrowDown', 'ArrowUp', 'Home', 'End'].includes(event.key)) { + const menuItems = [...menu.querySelectorAll('sl-menu-item')]; + const activeItem = menuItems.find(item => item.active); + + if (activeItem) { + scrollIntoView(activeItem, this.panel); + } } } diff --git a/src/components/menu/menu.tsx b/src/components/menu/menu.tsx index 965299e3b..7316c608e 100644 --- a/src/components/menu/menu.tsx +++ b/src/components/menu/menu.tsx @@ -1,5 +1,4 @@ import { Component, Event, EventEmitter, Method, State, h } from '@stencil/core'; -import { scrollIntoView } from '../../utilities/scroll'; import { getTextContent } from '../../utilities/slot'; /** @@ -96,12 +95,6 @@ export class Menu { this.getItems().map(i => (i.active = i === item)); } - scrollItemIntoView(item: HTMLSlMenuItemElement) { - if (item) { - scrollIntoView(item, this.menu); - } - } - handleFocus() { const item = this.getActiveItem(); if (!item) { @@ -170,7 +163,6 @@ export class Menu { if (index > items.length - 1) index = items.length - 1; this.setActiveItem(items[index]); - this.scrollItemIntoView(items[index]); return; }