Skip to content

Commit

Permalink
Fix dropdown keys to open menu (#32750)
Browse files Browse the repository at this point in the history
Co-authored-by: XhmikosR <[email protected]>
  • Loading branch information
sijusamson and XhmikosR authored Feb 3, 2021
1 parent 2a9d721 commit b376a3d
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
6 changes: 6 additions & 0 deletions js/src/dropdown.js
Original file line number Diff line number Diff line change
Expand Up @@ -468,6 +468,12 @@ class Dropdown extends BaseComponent {
return
}

if (!isActive && (event.key === ARROW_UP_KEY || event.key === ARROW_DOWN_KEY)) {
const button = this.matches(SELECTOR_DATA_TOGGLE) ? this : SelectorEngine.prev(this, SELECTOR_DATA_TOGGLE)[0]
button.click()
return
}

if (!isActive || event.key === SPACE_KEY) {
Dropdown.clearMenus()
return
Expand Down
48 changes: 48 additions & 0 deletions js/tests/unit/dropdown.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -1626,4 +1626,52 @@ describe('Dropdown', () => {
expect(Dropdown.getInstance(div)).toEqual(null)
})
})

it('should open dropdown when pressing keydown or keyup', done => {
fixtureEl.innerHTML = [
'<div class="dropdown">',
' <button class="btn dropdown-toggle" data-bs-toggle="dropdown">Dropdown</button>',
' <div class="dropdown-menu">',
' <a class="dropdown-item disabled" href="#sub1">Submenu 1</a>',
' <button class="dropdown-item" type="button" disabled>Disabled button</button>',
' <a id="item1" class="dropdown-item" href="#">Another link</a>',
' </div>',
'</div>'
].join('')

const triggerDropdown = fixtureEl.querySelector('[data-bs-toggle="dropdown"]')
const dropdown = fixtureEl.querySelector('.dropdown')

const keydown = createEvent('keydown')
keydown.key = 'ArrowDown'

const keyup = createEvent('keyup')
keyup.key = 'ArrowUp'

const handleArrowDown = () => {
expect(triggerDropdown.classList.contains('show')).toEqual(true)
expect(triggerDropdown.getAttribute('aria-expanded')).toEqual('true')
setTimeout(() => {
dropdown.hide()
keydown.key = 'ArrowUp'
triggerDropdown.dispatchEvent(keyup)
}, 20)
}

const handleArrowUp = () => {
expect(triggerDropdown.classList.contains('show')).toEqual(true)
expect(triggerDropdown.getAttribute('aria-expanded')).toEqual('true')
done()
}

dropdown.addEventListener('shown.bs.dropdown', event => {
if (event.target.key === 'ArrowDown') {
handleArrowDown()
} else {
handleArrowUp()
}
})

triggerDropdown.dispatchEvent(keydown)
})
})

0 comments on commit b376a3d

Please sign in to comment.