From be44db8e35b35958a31464f6b3edd4766a380766 Mon Sep 17 00:00:00 2001 From: Cory LaViska Date: Sat, 8 Aug 2020 15:26:21 -0400 Subject: [PATCH] Move scrollIntoView logic from menu to dropdown --- src/components/dropdown/dropdown.tsx | 17 ++++++++++++++--- src/components/menu/menu.tsx | 8 -------- 2 files changed, 14 insertions(+), 11 deletions(-) diff --git a/src/components/dropdown/dropdown.tsx b/src/components/dropdown/dropdown.tsx index 8e95c403..ada93504 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 965299e3..7316c608 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; }