-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathautocomplete-light.js
More file actions
410 lines (340 loc) · 10.9 KB
/
Copy pathautocomplete-light.js
File metadata and controls
410 lines (340 loc) · 10.9 KB
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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
class AutocompleteLight extends HTMLElement {
box = null
xhr = null
timeoutId = null
input = null
box = null
get input() {
return this.querySelector('autocomplete-light')
}
connectedCallback() {
this.input = this.querySelector('[slot=input]')
if (!this.input) return setTimeout(this.connectedCallback.bind(this), 100)
this.input.addEventListener(
'focus',
() => this.input.value.length >= this.minimumCharacters && this.onInput()
)
this.input.addEventListener('keydown', this.keyboard.bind(this))
this.input.addEventListener('input', this.onInput.bind(this))
window.addEventListener(
'resize',
() => this.box && this.box.setAttribute('hidden', 'true')
)
this.setAttribute('data-bound', 'true')
}
get hidden() {
return this.input.getAttribute('hidden')
}
set hidden(value) {
if (value) {
this.input.setAttribute('hidden', 'true')
} else {
this.input.removeAttribute('hidden')
}
}
disconnectedCallback() {
console.log('disconnected')
}
attributeChangedCallback(attrName, oldVal, newVal) {
console.log('changed')
}
onInput() {
// clear any unset xhr
this.xhr && this.xhr.readyState === 0 && this.xhr.abort()
// clear any planned xhr
this.timeoutId && window.clearTimeout(this.timeoutId)
// plan an xhr
this.timeoutId = window.setTimeout(this.download.bind(this), 200)
}
hilight(choice) {
this.selected.forEach((item) => item.classList.remove('hilight'))
choice.classList.add('hilight')
}
selectChoice(choice) {
let eventName = 'autocompleteChoiceSelected'
let data = {choice}
if (window.CustomEvent && typeof window.CustomEvent === 'function') {
var event = new CustomEvent(eventName, {detail: data});
this.dispatchEvent(event)
} else {
var event2 = document.createEvent('CustomEvent');
event2.initCustomEvent(eventName, true, true, data);
this.dispatchEvent(event2)
}
this.box.setAttribute('hidden', 'true')
}
get url() {
return this.getAttribute('url') + '?q=' + this.input.value
}
download() {
this.xhr = new XMLHttpRequest()
this.xhr.addEventListener('load', this.receive.bind(this))
this.xhr.open('GET', this.url)
this.xhr.send()
}
keyboard(ev) {
switch(ev.keyCode) {
// with Webkit, both keyCode and charCode are set to 38/40 for &/(.
// charCode is 0 for arrow keys.
// Ref: http://stackoverflow.com/a/12046935/15690
case 40: // down arrow
case 38: // up arrow
// Avoid moving the cursor in the input.
ev.preventDefault()
ev.stopPropagation()
this.move(ev.keyCode == 38 ? 'up' : 'down');
break;
case 9: // tab
case 13: // enter
if (this.box.getAttribute('hidden')) return
var choice = this.box.querySelector('.hilight');
if (!choice) {
// Don't get in the way, let the browser submit form or focus
// on next element.
return
}
ev.preventDefault()
ev.stopPropagation()
this.selectChoice(choice)
break
case 27: // escape
this.box.setAttribute('hidden', 'true')
break
}
}
move(way) {
// If the autocomplete should not be displayed then return.
if (this.input.value.length < this.minimumCharacters) return true;
// The current choice if any.
var current = this.box.querySelector('.hilight');
// The first and last choices. If the user presses down on the last
// choice, then the first one will be hilighted.
var first = this.choices[0];
var last = this.choices[this.choices.length - 1];
// The choice that should be hilighted after the move.
var target;
// The autocomplete must be shown so that the user sees what choice
// he is hilighting.
this.draw()
// If a choice is currently hilighted:
if (current) {
if (way === 'up') {
var next = this.choices.indexOf(current) - 1
target = next < 0 ? last : this.choices[next]
} else {
var next = this.choices.indexOf(current) + 1
target = next >= this.choices.length ? first : this.choices[next]
}
} else {
target = way === 'up' ? last : first;
}
target !== undefined && this.hilight(target)
}
get choices() {
return Array.from(this.box.querySelectorAll(this.choiceSelector))
}
get selected() {
return this.box.querySelectorAll(this.choiceSelector + '.hilight')
}
get choiceSelector() {
return this.getAttribute('choice-selector') || '[data-value]'
}
get minimumCharacters() {
return this.getAttribute('minimum-characters') || 0
}
receive(ev) {
this.draw()
this.box.innerHTML = ev.target.response
this.box.querySelectorAll(this.choiceSelector).forEach((item) => {
// item idempotence
if (item.getAttribute('data-bound'))
return
// bind mouse events
item.addEventListener(
'mouseenter',
(ev) => this.hilight(ev.target)
)
item.addEventListener(
'mouseleave',
(ev) => ev.target.classList.remove('hilight')
)
item.addEventListener(
'mousedown',
(ev) => this.selectChoice(ev.target)
)
// idempotence mark
item.setAttribute('data-bound', 'true')
})
}
boxBuild() {
this.box = document.createElement('div')
this.box.classList.add('autocomplete-light-box')
document.querySelector('body').appendChild(this.box)
this.input.addEventListener(
'focusout',
() => this.box.setAttribute('hidden', 'true')
)
this.input.addEventListener(
'blur',
() => this.box.setAttribute('hidden', 'true')
)
}
draw() {
if (!this.box) this.boxBuild()
var rect = this.input.getBoundingClientRect()
this.box.style.top = rect.bottom + window.scrollY + 'px'
this.box.style.left = rect.left + 'px'
// keep some space for the border, avoid overflow on x
this.box.style.width = rect.width - 2 + 'px'
this.box.removeAttribute('hidden')
}
}
class AutocompleteSelectInput extends AutocompleteLight {
get url() {
if (!this.getAttribute('url')) return
var url = this.getAttribute('url') + '?q=' + this.input.value
this.parentNode.querySelectorAll('option[selected]').forEach((option) => {
url += '&_=' + option.value
})
return url
}
download() {
if (this.url) {
return super.download()
}
// No URL ? Try to receive from option tags of parent node
this.receive({
target: {
response: Array.from(
this.closest('autocomplete-select').select.options
).filter(
(item) => !item.selected && item.innerText.startsWith(this.input.value)
).map(
(item) => `<div data-value="${item.getAttribute('value')}">${item.innerHTML}</div>`
).join('\n'),
}
})
}
}
class AutocompleteSelect extends HTMLElement {
maxChoices = 0
bound = false
name = null
connectedCallback() {
if (!this.select || !this.input.input) {
return setTimeout(this.connectedCallback.bind(this), 100)
}
if (!this.select.multiple) {
this.maxChoices = 1
}
this.input.addEventListener(
'autocompleteChoiceSelected',
(ev) => this.choiceSelect(ev.detail.choice)
)
this.input.hidden = this.maxChoices && this.selected.length >= this.maxChoices
// ensure all selected options are in deck
Array.from(
this.select.querySelectorAll('option[selected]')
).map((option) => {
var exists = this.deck.querySelectorAll(
'[data-value="' + option.getAttribute('value') + '"]'
)
if (exists.length) return
var cmp = document.createElement('div')
cmp.setAttribute('selected', 'selected')
cmp.setAttribute('data-value', option.getAttribute('value'))
cmp.innerHTML = option['innerHTML']
this.choiceSelect(cmp, false)
})
// ensure all deck values are in select
Array.from(
this.deck.querySelectorAll('[data-value]')
).map((choice) => {
if (!this.select.querySelector('option[value="' + choice.getAttribute('data-value') + '"]')) {
this.choiceSelect(choice, false)
}
this.addClear(choice)
})
this.setAttribute('data-bound', 'true')
}
get deck() {
return this.querySelector('[slot=deck]')
}
get select() {
return this.querySelector('[slot=select]')
}
get selected() {
return this.deck.querySelectorAll('[data-value]')
}
get input() {
return this.querySelector('autocomplete-select-input, autocomplete-light')
}
onClearClick(ev) {
this.choiceUnselect(ev.target.parentNode)
ev.preventDefault()
ev.stopPropagation()
}
choiceUnselect(choice, noShowHide = false) {
var value = choice.getAttribute('data-value')
var option = this.select.querySelector('option[value="' + value + '"]')
if (option) {
option.removeAttribute('selected')
}
var decked = this.deck.querySelector('[data-value="' + value + '"]')
if (decked) {
decked.parentNode.removeChild(decked)
}
if (!this.selected.length) {
// clear select value
this.select.value = ''
}
if (!noShowHide)
this.input.hidden = this.maxChoices && this.selected.length >= this.maxChoices
this.changeTrigger()
}
choiceSelect(choice, trigger=true, option=false) {
if (this.maxChoices && this.selected.length >= this.maxChoices) {
this.choiceUnselect(this.selected[0], true)
}
var value = choice.getAttribute('data-value')
// update select value
if (!this.select.multiple) {
this.select.value = value
}
// insert option in select if not present
option = this.select.querySelector('option[value="' + value + '"]')
if (!option) {
option = document.createElement('option')
option.setAttribute('value', value)
option.innerHTML = choice.innerHTML
this.select.appendChild(option)
}
option.setAttribute('selected', 'selected')
// insert choice on deck if not present, based on a choice node clone
if (!this.deck.querySelector('[data-value="' + value + '"]')) {
choice = choice.cloneNode(9)
choice.classList.remove('hilight')
this.addClear(choice)
this.deck.appendChild(choice)
}
this.input.hidden = this.maxChoices && this.selected.length >= this.maxChoices
trigger && this.changeTrigger()
}
changeTrigger() {
this.select.dispatchEvent(
new Event('change', {bubbles: true, cancelable: false})
)
}
addClear(choice) {
if (choice.querySelector('.clear'))
return
var clear = document.createElement('span')
clear.classList.add('clear')
clear.addEventListener('click', this.onClearClick.bind(this))
clear.innerHTML = '❌'
choice.appendChild(clear)
}
}
window.customElements.define('autocomplete-light', AutocompleteLight);
window.customElements.define('autocomplete-select-input', AutocompleteSelectInput);
window.customElements.define('autocomplete-select', AutocompleteSelect);