Skip to content

Commit

Permalink
fix(useCombobox): prevent default on Escape when open or has content (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
silviuaavram authored Sep 14, 2022
1 parent 1054249 commit 3eb7b44
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 3 deletions.
23 changes: 21 additions & 2 deletions src/hooks/useCombobox/__tests__/getInputProps.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ describe('getInputProps', () => {
result.current.toggleMenu()
})
act(() => {
onKeyDown({key: 'Escape', preventDefault: noop})
onKeyDown({key: 'Escape', preventDefault: noop, stopPropagation: noop})
})

expect(userOnKeyDown).toHaveBeenCalledTimes(1)
Expand Down Expand Up @@ -228,7 +228,7 @@ describe('getInputProps', () => {

inputRef({focus: noop})
result.current.toggleMenu()
onBlur({key: 'Escape', preventDefault: noop})
onBlur({preventDefault: noop})
})

expect(userOnBlur).toHaveBeenCalledTimes(1)
Expand Down Expand Up @@ -771,6 +771,25 @@ describe('getInputProps', () => {
expect(renderSpy).toHaveBeenCalledTimes(1) // re-render on key
})

test('escape stops propagation when it closes the menu or clears the input', () => {
const {input} = renderCombobox({
initialIsOpen: true,
initialSelectedItem: items[0],
})
const keyDownEvents = [
createEvent.keyDown(input, {key: 'Escape'}),
createEvent.keyDown(input, {key: 'Escape'}),
createEvent.keyDown(input, {key: 'Escape'}),
]

for (let index = 0; index < keyDownEvents.length; index++) {
fireEvent(input, keyDownEvents[index])
expect(keyDownEvents[index].defaultPrevented).toBe(
index !== keyDownEvents.length - 1,
)
}
})

test('enter it closes the menu and selects highlighted item', () => {
const initialHighlightedIndex = 2
const {keyDownOnInput, input, getItems} = renderCombobox({
Expand Down
4 changes: 3 additions & 1 deletion src/hooks/useCombobox/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -190,14 +190,16 @@ function useCombobox(userProps = {}) {
getItemNodeFromIndex,
})
},
Escape() {
Escape(event) {
const latestState = latest.current.state
if (
latestState.isOpen ||
latestState.inputValue ||
latestState.selectedItem ||
latestState.highlightedIndex > -1
) {
event.preventDefault()

dispatch({
type: stateChangeTypes.InputKeyDownEscape,
})
Expand Down

0 comments on commit 3eb7b44

Please sign in to comment.