Skip to content

Commit 3df86d6

Browse files
committed
Support escape to clear selection and only prevent default if committed
1 parent b4450a8 commit 3df86d6

File tree

1 file changed

+18
-8
lines changed

1 file changed

+18
-8
lines changed

combobox-nav.js

Lines changed: 18 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -30,8 +30,12 @@ function keyboardBindings(event: KeyboardEvent) {
3030
switch (event.key) {
3131
case 'Enter':
3232
case 'Tab':
33-
commit(input, list)
34-
event.preventDefault()
33+
if (commit(input, list)) {
34+
event.preventDefault()
35+
}
36+
break
37+
case 'Escape':
38+
clearSelection(list)
3539
break
3640
case 'ArrowDown':
3741
navigate(input, list, 1)
@@ -64,10 +68,11 @@ function commitWithElement(event: MouseEvent) {
6468
event.preventDefault()
6569
}
6670

67-
function commit(input: HTMLTextAreaElement | HTMLInputElement, list: HTMLElement): void {
71+
function commit(input: HTMLTextAreaElement | HTMLInputElement, list: HTMLElement): boolean {
6872
const target = list.querySelector('[aria-selected="true"]')
69-
if (!target) return
73+
if (!target) return false
7074
fireCommitEvent(target)
75+
return true
7176
}
7277

7378
function fireCommitEvent(target: Element): void {
@@ -104,14 +109,19 @@ export function navigate(
104109
}
105110
}
106111

107-
function trackComposition(event: Event) {
112+
function clearSelection(list): void {
113+
const target = list.querySelector('[aria-selected="true"]')
114+
if (!target) return
115+
target.setAttribute('aria-selected', 'false')
116+
}
117+
118+
function trackComposition(event: Event): void {
108119
const input = event.currentTarget
109120
if (!(input instanceof HTMLTextAreaElement || input instanceof HTMLInputElement)) return
110121
compositionMap.set(input, event.type === 'compositionstart')
111122

112123
const list = document.getElementById(input.getAttribute('aria-owns') || '')
113124
if (!list) return
114-
const target = list.querySelector('[aria-selected="true"]')
115-
if (!target) return
116-
target.setAttribute('aria-selected', 'false')
125+
126+
clearSelection(list)
117127
}

0 commit comments

Comments
 (0)