forked from denis-taran/autocomplete
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdropcomplete.ts
432 lines (367 loc) · 13.1 KB
/
dropcomplete.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
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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
/**
* @param {T} item - selected item
*/
type OnSelect<T> = (item: T, input: HTMLInputElement | HTMLTextAreaElement) => void;
/**
* @param {string} text - text in the input field
* @param {(items: T[] | false) => void} update - a callback function that must be called after suggestions are prepared
* @param {boolean} isFocus - type of the event that triggered the fetch
* @param {number} cursorPos - position of the cursor in the input field
*/
type Fetch<T> = (text: string, update: (items: T[] | false) => void, isFocus: boolean, cursorPos: number) => void;
export interface DropcompleteItem {
label?: string;
group?: string;
}
export interface DropcompleteSettings<T extends DropcompleteItem> {
/**
* Dropcomplete will be attached to this element
*/
input: HTMLInputElement | HTMLTextAreaElement;
/**
* Minimum text length required to show dropcomplete
*/
minLength?: number;
/**
* Shown when there are no suggestions that match the input
*/
emptyMsg?: string;
/**
* Show dropcomplete on focus event
*/
showOnFocus?: boolean;
/**
* Prevents form submission when `Enter` is pressed
*/
preventSubmit?: boolean;
/**
* Called when user choose an item in dropcomplete
*/
onSelect: OnSelect<T>;
/**
* Called to prepare suggestions and then pass them to dropcomplete
*/
fetch: Fetch<T>;
}
export default class Dropcomplete<T extends DropcompleteItem> {
input: HTMLInputElement | HTMLTextAreaElement;
minLen: number;
emptyMsg?: string;
showOnFocus?: boolean;
preventSubmit: boolean;
onSelect: OnSelect<T>
fetch: Fetch<T>;
container: HTMLDivElement;
items: T[];
inputValue: string;
selected?: T;
keypressCounter: number;
constructor(settings: DropcompleteSettings<T>) {
this.input = settings.input;
this.minLen = settings.minLength ?? 2;
this.emptyMsg = settings.emptyMsg;
this.showOnFocus = settings.showOnFocus;
this.preventSubmit = settings.preventSubmit || false;
this.onSelect = settings.onSelect;
this.fetch = settings.fetch;
this.container = document.createElement("div");
this.container.classList.add("dropcomplete");
this.container.style.position = "absolute";
this.items = [];
this.inputValue = "";
this.keypressCounter = 0;
this.input.addEventListener("keydown", event => this.keydownEventHandler(event as KeyboardEvent));
this.input.addEventListener("keyup", event => this.keyupEventHandler(event as KeyboardEvent));
this.input.addEventListener("blur", () => this.blurEventHandler());
this.input.addEventListener("focus", () => this.focusEventHandler());
window.addEventListener("resize", () => this.resizeEventHandler());
document.addEventListener("scroll", event => this.scrollEventHandler(event), true);
}
/**
* Detach container from DOM
*/
detach(): void {
const parent = this.container.parentNode;
if (parent) {
parent.removeChild(this.container);
}
}
/**
* Attach container to DOM
*/
attach(): void {
if (!this.container.parentNode) {
document.body.appendChild(this.container);
}
}
/**
* Check if container is displayed
*/
containerDisplayed(): boolean {
return !!this.container.parentNode;
}
/**
* Clear state and hide container
*/
clear(): void {
// Prevent the update call if there are pending AJAX requests
this.keypressCounter++;
this.items = [];
this.inputValue = "";
this.selected = undefined;
this.detach();
}
updatePosition(): void {
if (!this.containerDisplayed()) {
return;
}
this.container.style.height = "auto";
this.container.style.width = this.input.offsetWidth + "px";
this.calculatePosition()
}
calculatePosition(): void {
const docEl = document.documentElement;
const clientTop = docEl.clientTop || document.body.clientTop || 0;
const clientLeft = docEl.clientLeft || document.body.clientLeft || 0;
const scrollTop = window.pageYOffset || docEl.scrollTop;
const scrollLeft = window.pageXOffset || docEl.scrollLeft;
const inputRect = this.input.getBoundingClientRect();
const top = inputRect.top + this.input.offsetHeight + scrollTop - clientTop;
const left = inputRect.left + scrollLeft - clientLeft;
this.container.style.top = top + "px";
this.container.style.left = left + "px";
let maxHeight = window.innerHeight - (inputRect.top + this.input.offsetHeight);
if (maxHeight < 0) {
maxHeight = 0;
}
this.container.style.top = top + "px";
this.container.style.bottom = "";
this.container.style.left = left + "px";
this.container.style.maxHeight = maxHeight + "px";
}
/**
* Redraw with suggestions
*/
update(): void {
// Delete all children from dropcomplete DOM container
while (this.container.firstChild) {
this.container.removeChild(this.container.firstChild);
}
const fragment = document.createDocumentFragment();
let prevGroup = "#9?$";
for (const item of this.items) {
if (item.group && item.group !== prevGroup) {
prevGroup = item.group;
const groupDiv = this.renderGroup(item.group);
if (groupDiv) {
groupDiv.classList.add("group");
fragment.appendChild(groupDiv);
}
}
const div = this.render(item);
if (div) {
div.addEventListener("click", (event) => {
this.onSelect(item, this.input);
this.clear();
event.preventDefault();
event.stopPropagation();
});
if (item === this.selected) {
div.classList.add("selected");
}
fragment.appendChild(div);
}
}
this.container.appendChild(fragment);
if (this.items.length < 1) {
if (this.emptyMsg) {
const empty = document.createElement("div");
empty.className = "empty";
empty.textContent = this.emptyMsg;
this.container.appendChild(empty);
} else {
this.clear();
return;
}
}
this.attach();
this.updatePosition();
this.updateScroll();
}
/**
* Renders an item
*/
render(item: T): HTMLDivElement | undefined {
const itemElement = document.createElement("div");
itemElement.textContent = item.label || "";
return itemElement;
};
/**
* Renders a group
*/
renderGroup(group: string): HTMLDivElement | undefined {
const groupDiv = document.createElement("div");
groupDiv.textContent = group;
return groupDiv;
};
updateIfDisplayed(): void {
if (this.containerDisplayed()) {
this.update();
}
}
resizeEventHandler(): void {
this.updateIfDisplayed();
}
scrollEventHandler(event: Event): void {
if (event.target !== this.container) {
this.updateIfDisplayed();
} else {
event.preventDefault();
}
}
keyupEventHandler(event: KeyboardEvent): void {
const key = event.key;
const ignores = ["ArrowUp", "Enter", "Escape", "ArrowRight", "ArrowLeft", "Shift", "Control", "Alt", "CapsLock", "Meta", "Tab"];
for (const ignore of ignores) {
if (ignore === key) {
return;
}
}
if (key === "Fn") {
return;
}
// `ArrowDown` is used to open dropcomplete
if (key === "ArrowDown" && this.containerDisplayed()) {
return;
}
this.startFetch(false);
}
/**
* Move scroll bar if selected item is not visible
*/
updateScroll(): void {
const elements = this.container.getElementsByClassName("selected");
if (elements.length > 0) {
let element = elements[0] as HTMLDivElement;
// make group visible
const previous = element.previousElementSibling as HTMLDivElement;
if (previous && previous.className.indexOf("group") !== -1 && !previous.previousElementSibling) {
element = previous;
}
if (element.offsetTop < this.container.scrollTop) {
this.container.scrollTop = element.offsetTop;
} else {
const selectBottom = element.offsetTop + element.offsetHeight;
const containerBottom = this.container.scrollTop + this.container.offsetHeight;
if (selectBottom > containerBottom) {
this.container.scrollTop += selectBottom - containerBottom;
}
}
}
}
selectPrev(): void {
if (this.items.length < 1) {
this.selected = undefined;
} else {
if (this.selected === this.items[0]) {
this.selected = this.items[this.items.length - 1];
} else {
for (let i = this.items.length - 1; i > 0; i--) {
if (this.selected === this.items[i] || i === 1) {
this.selected = this.items[i - 1];
break;
}
}
}
}
}
selectNext(): void {
if (this.items.length < 1) {
this.selected = undefined;
}
if (!this.selected || this.selected === this.items[this.items.length - 1]) {
this.selected = this.items[0];
return;
}
for (let i = 0; i < (this.items.length - 1); i++) {
if (this.selected === this.items[i]) {
this.selected = this.items[i + 1];
break;
}
}
}
keydownEventHandler(event: KeyboardEvent): void {
const key = event.key;
if (key === "ArrowUp" || key === "ArrowDown" || key === "Escape") {
const containerIsDisplayed = this.containerDisplayed();
if (key === "Escape") {
this.clear();
} else {
if (!containerIsDisplayed || this.items.length < 1) {
return;
}
key === "ArrowUp" ? this.selectPrev() : this.selectNext();
this.update();
}
event.preventDefault();
if (containerIsDisplayed) {
event.stopPropagation();
}
return;
}
if (key === "Enter") {
if (this.selected) {
this.onSelect(this.selected, this.input);
this.clear();
}
if (this.preventSubmit) {
event.preventDefault();
}
}
}
focusEventHandler(): void {
if (this.showOnFocus) {
this.startFetch(true);
}
}
startFetch(isFocus: boolean) {
// If multiple keys were pressed, before we get an update from server,
// this may cause redrawing dropcomplete multiple times after the last key was pressed.
// To avoid this, the number of times keyboard was pressed will be saved and checked before redraw.
const savedKeypressCounter = ++this.keypressCounter;
const inputText = this.input.value;
const cursorPos = this.input.selectionStart || 0;
if (inputText.length >= this.minLen || isFocus) {
this.fetch(inputText, (items) => {
if (this.keypressCounter === savedKeypressCounter && items) {
this.items = items
this.inputValue = inputText;
this.selected = (items.length < 1) ? undefined : items[0];
this.update();
}
}, isFocus, cursorPos);
} else {
this.clear();
}
}
blurEventHandler(): void {
// we need to delay clear, because when we click on an item, blur will be called before click and remove items from DOM
setTimeout(() => {
if (document.activeElement !== this.input) {
this.clear();
}
}, 200);
}
/**
* Remove elements and clear event handlers
*/
destroy(): void {
this.input.removeEventListener("keydown", this.keydownEventHandler as EventListenerOrEventListenerObject);
this.input.removeEventListener("keyup", this.keyupEventHandler as EventListenerOrEventListenerObject);
this.input.removeEventListener("focus", this.focusEventHandler);
this.input.removeEventListener("blur", this.blurEventHandler);
window.removeEventListener("resize", this.resizeEventHandler);
document.removeEventListener("scroll", this.scrollEventHandler, true);
this.clear();
}
}