/
index.ts
237 lines (207 loc) · 8.17 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
export type ComboboxSettings = {
tabInsertsSuggestions?: boolean
/**
* Indicates the default behaviour for the first option when the list is shown:
*
* - `'none'`: Don't auto-select the first option at all.
* - `'active'`: Place the first option in an 'active' state where it is not
* selected (is not the `aria-activedescendant`) but will still be applied
* if the user presses `Enter`. To select the second item, the user would
* need to press the down arrow twice. This approach allows quick application
* of selections without disrupting screen reader users.
* - `'selected'`: Select the first item by navigating to it. This allows quick
* application of selections and makes it faster to select the second item,
* but can be disruptive or confusing for screen reader users.
*/
firstOptionSelectionMode?: FirstOptionSelectionMode
scrollIntoViewOptions?: boolean | ScrollIntoViewOptions
}
// Indicates the default behaviour for the first option when the list is shown.
export type FirstOptionSelectionMode = 'none' | 'active' | 'selected'
export default class Combobox {
isComposing: boolean
list: HTMLElement
input: HTMLTextAreaElement | HTMLInputElement
keyboardEventHandler: (event: KeyboardEvent) => void
compositionEventHandler: (event: Event) => void
inputHandler: (event: Event) => void
ctrlBindings: boolean
tabInsertsSuggestions: boolean
firstOptionSelectionMode: FirstOptionSelectionMode
scrollIntoViewOptions?: boolean | ScrollIntoViewOptions
constructor(
input: HTMLTextAreaElement | HTMLInputElement,
list: HTMLElement,
{tabInsertsSuggestions, firstOptionSelectionMode, scrollIntoViewOptions}: ComboboxSettings = {},
) {
this.input = input
this.list = list
this.tabInsertsSuggestions = tabInsertsSuggestions ?? true
this.firstOptionSelectionMode = firstOptionSelectionMode ?? 'none'
this.scrollIntoViewOptions = scrollIntoViewOptions ?? {block: 'nearest', inline: 'nearest'}
this.isComposing = false
if (!list.id) {
list.id = `combobox-${Math.random().toString().slice(2, 6)}`
}
this.ctrlBindings = !!navigator.userAgent.match(/Macintosh/)
this.keyboardEventHandler = event => keyboardBindings(event, this)
this.compositionEventHandler = event => trackComposition(event, this)
this.inputHandler = this.clearSelection.bind(this)
input.setAttribute('role', 'combobox')
input.setAttribute('aria-controls', list.id)
input.setAttribute('aria-expanded', 'false')
input.setAttribute('aria-autocomplete', 'list')
input.setAttribute('aria-haspopup', 'listbox')
}
destroy() {
this.clearSelection()
this.stop()
this.input.removeAttribute('role')
this.input.removeAttribute('aria-controls')
this.input.removeAttribute('aria-expanded')
this.input.removeAttribute('aria-autocomplete')
this.input.removeAttribute('aria-haspopup')
}
start(): void {
this.input.setAttribute('aria-expanded', 'true')
this.input.addEventListener('compositionstart', this.compositionEventHandler)
this.input.addEventListener('compositionend', this.compositionEventHandler)
this.input.addEventListener('input', this.inputHandler)
;(this.input as HTMLElement).addEventListener('keydown', this.keyboardEventHandler)
this.list.addEventListener('click', commitWithElement)
this.resetSelection()
}
stop(): void {
this.clearSelection()
this.input.setAttribute('aria-expanded', 'false')
this.input.removeEventListener('compositionstart', this.compositionEventHandler)
this.input.removeEventListener('compositionend', this.compositionEventHandler)
this.input.removeEventListener('input', this.inputHandler)
;(this.input as HTMLElement).removeEventListener('keydown', this.keyboardEventHandler)
this.list.removeEventListener('click', commitWithElement)
}
indicateDefaultOption(): void {
if (this.firstOptionSelectionMode === 'active') {
Array.from(this.list.querySelectorAll<HTMLElement>('[role="option"]:not([aria-disabled="true"])'))
.filter(visible)[0]
?.setAttribute('data-combobox-option-default', 'true')
} else if (this.firstOptionSelectionMode === 'selected') {
this.navigate(1)
}
}
navigate(indexDiff: -1 | 1 = 1): void {
const focusEl = Array.from(this.list.querySelectorAll<HTMLElement>('[aria-selected="true"]')).filter(visible)[0]
const els = Array.from(this.list.querySelectorAll<HTMLElement>('[role="option"]')).filter(visible)
const focusIndex = els.indexOf(focusEl)
if ((focusIndex === els.length - 1 && indexDiff === 1) || (focusIndex === 0 && indexDiff === -1)) {
this.clearSelection()
this.input.focus()
return
}
let indexOfItem = indexDiff === 1 ? 0 : els.length - 1
if (focusEl && focusIndex >= 0) {
const newIndex = focusIndex + indexDiff
if (newIndex >= 0 && newIndex < els.length) indexOfItem = newIndex
}
const target = els[indexOfItem]
if (!target) return
for (const el of els) {
el.removeAttribute('data-combobox-option-default')
if (target === el) {
this.input.setAttribute('aria-activedescendant', target.id)
target.setAttribute('aria-selected', 'true')
fireSelectEvent(target)
target.scrollIntoView(this.scrollIntoViewOptions)
} else {
el.removeAttribute('aria-selected')
}
}
}
clearSelection(): void {
this.input.removeAttribute('aria-activedescendant')
for (const el of this.list.querySelectorAll('[aria-selected="true"], [data-combobox-option-default="true"]')) {
el.removeAttribute('aria-selected')
el.removeAttribute('data-combobox-option-default')
}
}
resetSelection(): void {
this.clearSelection()
this.indicateDefaultOption()
}
}
function keyboardBindings(event: KeyboardEvent, combobox: Combobox) {
if (event.shiftKey || event.metaKey || event.altKey) return
if (!combobox.ctrlBindings && event.ctrlKey) return
if (combobox.isComposing) return
switch (event.key) {
case 'Enter':
if (commit(combobox.input, combobox.list)) {
event.preventDefault()
}
break
case 'Tab':
if (combobox.tabInsertsSuggestions && commit(combobox.input, combobox.list)) {
event.preventDefault()
}
break
case 'Escape':
combobox.clearSelection()
break
case 'ArrowDown':
combobox.navigate(1)
event.preventDefault()
break
case 'ArrowUp':
combobox.navigate(-1)
event.preventDefault()
break
case 'n':
if (combobox.ctrlBindings && event.ctrlKey) {
combobox.navigate(1)
event.preventDefault()
}
break
case 'p':
if (combobox.ctrlBindings && event.ctrlKey) {
combobox.navigate(-1)
event.preventDefault()
}
break
default:
if (event.ctrlKey) break
combobox.resetSelection()
}
}
function commitWithElement(event: MouseEvent) {
if (!(event.target instanceof Element)) return
const target = event.target.closest('[role="option"]')
if (!target) return
if (target.getAttribute('aria-disabled') === 'true') return
fireCommitEvent(target, {event})
}
function commit(input: HTMLTextAreaElement | HTMLInputElement, list: HTMLElement): boolean {
const target = list.querySelector<HTMLElement>('[aria-selected="true"], [data-combobox-option-default="true"]')
if (!target) return false
if (target.getAttribute('aria-disabled') === 'true') return true
target.click()
return true
}
function fireCommitEvent(target: Element, detail?: Record<string, unknown>): void {
target.dispatchEvent(new CustomEvent('combobox-commit', {bubbles: true, detail}))
}
function fireSelectEvent(target: Element): void {
target.dispatchEvent(new Event('combobox-select', {bubbles: true}))
}
function visible(el: HTMLElement): boolean {
return (
!el.hidden &&
!(el instanceof HTMLInputElement && el.type === 'hidden') &&
(el.offsetWidth > 0 || el.offsetHeight > 0)
)
}
function trackComposition(event: Event, combobox: Combobox): void {
combobox.isComposing = event.type === 'compositionstart'
const list = document.getElementById(combobox.input.getAttribute('aria-controls') || '')
if (!list) return
combobox.clearSelection()
}