1
0
mirror of https://github.com/twbs/bootstrap.git synced 2025-08-08 22:56:46 +02:00

Automatically select an item in the dropdown when using arrow keys (#34052)

This commit is contained in:
alpadev
2021-05-22 09:58:52 +02:00
committed by GitHub
parent 8033975548
commit b39b665072
5 changed files with 61 additions and 26 deletions

View File

@@ -354,18 +354,16 @@ class Dropdown extends BaseComponent {
}
}
_selectMenuItem(event) {
if (![ARROW_UP_KEY, ARROW_DOWN_KEY].includes(event.key)) {
return
}
_selectMenuItem({ key, target }) {
const items = SelectorEngine.find(SELECTOR_VISIBLE_ITEMS, this._menu).filter(isVisible)
if (!items.length) {
return
}
getNextActiveElement(items, event.target, event.key === ARROW_DOWN_KEY, false).focus()
// if target isn't included in items (e.g. when expanding the dropdown)
// allow cycling to get the last item in case key equals ARROW_UP_KEY
getNextActiveElement(items, target, key === ARROW_DOWN_KEY, !items.includes(target)).focus()
}
// Static
@@ -480,17 +478,18 @@ class Dropdown extends BaseComponent {
return
}
if (!isActive && (event.key === ARROW_UP_KEY || event.key === ARROW_DOWN_KEY)) {
getToggleButton().click()
if (event.key === ARROW_UP_KEY || event.key === ARROW_DOWN_KEY) {
if (!isActive) {
getToggleButton().click()
}
Dropdown.getInstance(getToggleButton())._selectMenuItem(event)
return
}
if (!isActive || event.key === SPACE_KEY) {
Dropdown.clearMenus()
return
}
Dropdown.getInstance(getToggleButton())._selectMenuItem(event)
}
}

View File

@@ -264,9 +264,9 @@ const execute = callback => {
const getNextActiveElement = (list, activeElement, shouldGetNext, isCycleAllowed) => {
let index = list.indexOf(activeElement)
// if the element does not exist in the list initialize it as the first element
// if the element does not exist in the list return an element depending on the direction and if cycle is allowed
if (index === -1) {
return list[0]
return list[!shouldGetNext && isCycleAllowed ? list.length - 1 : 0]
}
const listLength = list.length