-
Notifications
You must be signed in to change notification settings - Fork 3
/
TrivialComboBox.ts
651 lines (579 loc) · 25.8 KB
/
TrivialComboBox.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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
/*!
Trivial Components (https://github.com/trivial-components/trivial-components)
Copyright 2016 Yann Massard (https://github.com/yamass) and other contributors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import * as $ from "jquery";
import {place} from 'place-to';
import {
DEFAULT_TEMPLATES, defaultListQueryFunctionFactory, EditingMode, HighlightDirection, objectEquals, QueryFunction, setTimeoutOrDoImmediately, TrivialComponent, keyCodes,
RenderingFunction, DEFAULT_RENDERING_FUNCTIONS
} from "./TrivialCore";
import {TrivialListBox, TrivialListBoxConfig} from "./TrivialListBox";
import {TrivialEvent} from "./TrivialEvent";
export interface TrivialComboBoxConfig<E> extends TrivialListBoxConfig<E> {
/**
* Calculates the value to set on the original input.
*
* @param entry the selected entry
* @return the string to set as the value of the original input
*/
valueFunction?: (entry: E) => string,
/**
* Rendering function used to display a _selected_ entry
* (i.e. an entry inside the editor area of the component, not the dropdown).
*
* @param entry
* @return HTML string
* @default `wrapWithDefaultTagWrapper(entryRenderingFunction(entry))`
*/
selectedEntryRenderingFunction?: RenderingFunction<E>,
/**
* Initially selected entry.
*
* @default `null`
*/
selectedEntry?: E,
/**
* Performance setting. Defines the maximum number of entries until which text highlighting is performed.
* Set to `0` to disable text highlighting.
*
* @default `100`
*/
textHighlightingEntryLimit?: number,
/**
* Used to retrieve the entries ("suggestions") to be displayed in the dropdown box.
*
* @see QueryFunction
* @default creates a client-side query function using the provided [[entries]]
*/
queryFunction?: QueryFunction<E>,
/**
* Whether or not to provide auto-completion.
*
* @default `true`
*/
autoComplete?: boolean,
/**
* The number of milliseconds to wait until auto-completion is performed.
*
* @default `0`
*/
autoCompleteDelay?: number,
/**
* Generates an autocompletion string for the current input of the user and currently highlighted entry in the dropdown.
*
* @param editorText the current text input from the user
* @param entry the currently highlighted entry in the dropdown
* @return The _full_ string (not only the completion part) to apply for auto-completion.
* @default best effort implementation using entry properties
*/
autoCompleteFunction?: (editorText: string, entry: E) => string,
/**
* Similar to [[autoCompleteFunction]]. Used to set the editor's text when focusing the component.
*
* @default `entry["displayValue"]`
*/
entryToEditorTextFunction?: (entry: E) => string,
/**
* Whether or not to allow free text to be entered by the user.
*
* @default `false`
*/
allowFreeText?: boolean,
/**
* Creates an entry (object) from a string entered by the user.
*
* @param freeText the text entered by the user
* @default `{ displayValue: freeText, _isFreeTextEntry: true }`
*/
freeTextEntryFactory?: (freeText: string) => E | any,
/**
* The clear button is a the small 'x' at the right of the entry display that can be clicked to clear the selection.
*/
showClearButton?: boolean,
/**
* The trigger is the button on the right side of the component that can be clicket to open the dropdown.
*
* @default `true`
*/
showTrigger?: boolean,
editingMode?: EditingMode,
/**
* It `true`, opening the dropdown will be delayed until the result callback of the [[queryFunction]] is called.
*
* @default `false`
*/
showDropDownOnResultsOnly?: boolean,
/**
* HTML string defining the spinner to be displayed while entries are being retrieved.
*/
spinnerTemplate?: string
}
/**
* A templateable combobox.
*/
export class TrivialComboBox<E> implements TrivialComponent{
private config: TrivialComboBoxConfig<E>;
private $spinners: JQuery = $();
private $originalInput: JQuery;
private $comboBox: JQuery;
private $selectedEntryWrapper: JQuery;
private $dropDown: JQuery;
private $trigger: JQuery;
private $clearButton: JQuery;
private $editor: JQuery;
private $dropDownTargetElement:JQuery;
public readonly onSelectedEntryChanged = new TrivialEvent<E>(this);
public readonly onFocus = new TrivialEvent<void>(this);
public readonly onBlur = new TrivialEvent<void>(this);
private listBox: TrivialListBox<E>;
private isDropDownOpen = false;
private isEditorVisible = false;
private entries: E[];
private selectedEntry: E = null;
private lastCommittedValue: E = null;
private blurCausedByClickInsideComponent = false;
private autoCompleteTimeoutId = -1;
private doNoAutoCompleteBecauseBackspaceWasPressed = false;
private listBoxDirty = true;
private editingMode: EditingMode;
private usingDefaultQueryFunction: boolean = false;
constructor(originalInput: JQuery|Element|string, options: TrivialComboBoxConfig<E> = {}) {
this.config = $.extend(<TrivialComboBoxConfig<E>> {
valueFunction: (entry:E) => entry ? "" + (entry as any).id : null,
entryRenderingFunction: DEFAULT_RENDERING_FUNCTIONS.image2Lines,
selectedEntryRenderingFunction: (entry: E) => {
return this.config.entryRenderingFunction(entry);
},
selectedEntry: undefined,
spinnerTemplate: DEFAULT_TEMPLATES.defaultSpinnerTemplate,
noEntriesTemplate: DEFAULT_TEMPLATES.defaultNoEntriesTemplate,
textHighlightingEntryLimit: 100,
entries: null,
queryFunction: null, // defined below...
autoComplete: true,
autoCompleteDelay: 0,
entryToEditorTextFunction: (entry: E) => {
return (entry as any)["displayValue"];
},
autoCompleteFunction: (editorText: string, entry: E) => {
if (editorText) {
for (let propertyName in entry) {
if (entry.hasOwnProperty(propertyName)) {
let propertyValue = entry[propertyName];
if (propertyValue && (propertyValue as any).toString().toLowerCase().indexOf(editorText.toLowerCase()) === 0) {
return (propertyValue as any).toString();
}
}
}
return null;
} else {
return entry ? this.config.entryToEditorTextFunction(entry) : null;
}
},
allowFreeText: false,
freeTextEntryFactory: (freeText: string) => {
return {
displayValue: freeText,
_isFreeTextEntry: true
};
},
showClearButton: false,
showTrigger: true,
matchingOptions: {
matchingMode: 'contains',
ignoreCase: true,
maxLevenshteinDistance: 2
},
editingMode: 'editable', // one of 'editable', 'disabled' and 'readonly'
showDropDownOnResultsOnly: false
}, options);
if (!this.config.queryFunction) {
this.config.queryFunction = defaultListQueryFunctionFactory(this.config.entries || [], this.config.matchingOptions);
this.usingDefaultQueryFunction = true;
}
this.entries = this.config.entries;
this.$originalInput = $(originalInput);
this.$comboBox = $('<div class="tr-combobox tr-input-wrapper"/>')
.insertAfter(this.$originalInput);
this.$selectedEntryWrapper = $('<div class="tr-combobox-selected-entry-wrapper"/>').appendTo(this.$comboBox);
if (this.config.showClearButton) {
this.$clearButton = $('<div class="tr-remove-button">').appendTo(this.$comboBox);
this.$clearButton.mousedown((e) => {
this.$editor.val("");
this.setSelectedEntry(null, true, true, e);
});
}
if (this.config.showTrigger) {
this.$trigger = $('<div class="tr-trigger"><span class="tr-trigger-icon"/></div>').appendTo(this.$comboBox);
this.$trigger.mousedown(() => {
if (this.isDropDownOpen) {
this.showEditor();
this.closeDropDown();
} else {
setTimeout(() => { // TODO remove this when Chrome bug is fixed. Chrome scrolls to the top of the page if we do this synchronously. Maybe this has something to do with https://code.google.com/p/chromium/issues/detail?id=342307 .
this.showEditor();
this.$editor.select();
this.openDropDown();
this.query();
});
}
});
}
this.$dropDown = $('<div class="tr-dropdown"></div>')
.scroll(() => {
return false;
});
this.$dropDownTargetElement = $("body");
this.setEditingMode(this.config.editingMode);
this.$originalInput.addClass("tr-original-input");
this.$editor = $('<input type="text" autocomplete="off"/>');
this.$editor.prependTo(this.$comboBox).addClass("tr-combobox-editor tr-editor")
.focus(() => {
if (this.blurCausedByClickInsideComponent) {
// do nothing!
} else {
this.$originalInput.triggerHandler('focus');
this.onFocus.fire();
this.$comboBox.addClass('focus');
this.showEditor();
}
})
.blur((e) => {
if (this.blurCausedByClickInsideComponent) {
this.$editor.focus();
} else {
this.$originalInput.triggerHandler('blur');
this.onBlur.fire();
this.$comboBox.removeClass('focus');
if (this.editorContainsFreeText()) {
if (!objectEquals(this.getSelectedEntry(), this.lastCommittedValue)) {
this.setSelectedEntry(this.getSelectedEntry(), true, true, e);
}
} else {
this.$editor.val("");
this.setSelectedEntry(this.lastCommittedValue, false, true, e);
}
this.hideEditor();
this.closeDropDown();
}
})
.keydown((e: KeyboardEvent) => {
if (keyCodes.isModifierKey(e)) {
return;
} else if (e.which == keyCodes.tab) {
const highlightedEntry = this.listBox.getHighlightedEntry();
if (this.isDropDownOpen && highlightedEntry) {
this.setSelectedEntry(highlightedEntry, true, true, e);
} else if (!this.$editor.val()) {
this.setSelectedEntry(null, true, true);
} else if (this.config.allowFreeText) {
this.setSelectedEntry(this.getSelectedEntry(), true, true, e);
}
return;
} else if (e.which == keyCodes.left_arrow || e.which == keyCodes.right_arrow) {
this.showEditor();
return; // let the user navigate freely left and right...
}
setTimeout(() => {
// After the keystroke has taken effect to the editor, check if the editor content has changed and if yes, deselect the currently selected entry!
let isNonIgnoredKey = !keyCodes.isModifierKey(e) && [keyCodes.enter, keyCodes.escape, keyCodes.tab].indexOf(e.which) === -1;
let editorValueDoesNotCorrespondToSelectedValue = this.isEntrySelected() && this.$editor.val() !== this.config.entryToEditorTextFunction(this.selectedEntry);
if (isNonIgnoredKey && (editorValueDoesNotCorrespondToSelectedValue || this.config.valueFunction(this.listBox.getHighlightedEntry())) !== this.config.valueFunction(this.getSelectedEntry())) {
this.setSelectedEntry(null, false, false, e);
}
});
if (e.which == keyCodes.backspace || e.which == keyCodes.delete) {
this.doNoAutoCompleteBecauseBackspaceWasPressed = true; // we want query results, but no autocomplete
}
if (e.which == keyCodes.up_arrow || e.which == keyCodes.down_arrow) {
if (!this.isEditorVisible) {
this.$editor.select();
this.showEditor();
}
const direction = e.which == keyCodes.up_arrow ? -1 : 1;
if (!this.isDropDownOpen) {
this.query(direction);
this.openDropDown(); // directly open the dropdown (the user definitely wants to see it)
} else {
this.listBox.highlightNextEntry(direction);
this.autoCompleteIfPossible(this.config.autoCompleteDelay);
}
return false; // some browsers move the caret to the beginning on up key
} else if (e.which == keyCodes.enter) {
if (this.isEditorVisible || this.editorContainsFreeText()) {
e.preventDefault(); // do not submit form
const highlightedEntry = this.listBox.getHighlightedEntry();
if (this.isDropDownOpen && highlightedEntry) {
this.setSelectedEntry(highlightedEntry, true, true, e);
} else if (!this.$editor.val()) {
this.setSelectedEntry(null, true, true, e);
} else if (this.config.allowFreeText) {
this.setSelectedEntry(this.getSelectedEntry(), true, true, e);
}
this.closeDropDown();
this.hideEditor();
}
} else if (e.which == keyCodes.escape) {
e.preventDefault(); // prevent ie from doing its text field magic...
if (!(this.editorContainsFreeText() && this.isDropDownOpen)) { // TODO if list is empty, still reset, even if there is freetext.
this.hideEditor();
this.$editor.val("");
this.entries = null; // so we will query again when we combobox is re-focused
this.setSelectedEntry(this.lastCommittedValue, false, true, e);
}
this.closeDropDown();
} else {
if (!this.isEditorVisible) {
this.showEditor();
this.$editor.select();
}
if (!this.config.showDropDownOnResultsOnly) {
this.openDropDown();
}
setTimeout(() => { // We need the new editor value (after the keydown event). Therefore setTimeout().
if (this.$editor.val()) {
this.query(1);
} else {
this.query(0);
this.listBox.setHighlightedEntry(null);
}
})
}
})
.mousedown(() => {
if (!this.config.showDropDownOnResultsOnly) {
this.openDropDown();
}
this.query();
});
if (this.$originalInput.attr("tabindex")) {
this.$editor.attr("tabindex", this.$originalInput.attr("tabindex"));
}
if (this.$originalInput.attr("autofocus")) {
this.$editor.focus();
}
this.$comboBox.add(this.$dropDown).mousedown(() => {
if (this.$editor.is(":focus")) {
this.blurCausedByClickInsideComponent = true;
}
}).mouseup(() => {
if (this.blurCausedByClickInsideComponent) {
this.$editor.focus();
this.blurCausedByClickInsideComponent = false;
}
}).mouseout(() => {
if (this.blurCausedByClickInsideComponent) {
this.$editor.focus();
this.blurCausedByClickInsideComponent = false;
}
});
const configWithoutEntries = $.extend({}, this.config);
configWithoutEntries.entries = []; // for init performance reasons, initialize the dropdown content lazily
this.listBox = new TrivialListBox<E>(this.$dropDown, configWithoutEntries);
this.listBox.onSelectedEntryChanged.addListener((selectedEntry: E, eventSource, originalEvent) => {
if (selectedEntry) {
this.setSelectedEntry(selectedEntry, true, !objectEquals(selectedEntry, this.lastCommittedValue), originalEvent);
this.listBox.setSelectedEntry(null);
this.closeDropDown();
}
this.hideEditor();
});
this.setSelectedEntry(this.config.selectedEntry, true, false);
this.$selectedEntryWrapper.click(() => {
this.showEditor();
this.$editor.select();
if (!this.config.showDropDownOnResultsOnly) {
this.openDropDown();
}
this.query();
});
}
private query(highlightDirection?: HighlightDirection) {
if (this.$spinners.length === 0) {
const $spinner = $(this.config.spinnerTemplate).appendTo(this.$dropDown);
this.$spinners = this.$spinners.add($spinner);
}
this.config.queryFunction(this.getNonSelectedEditorValue(), (newEntries: E[]) => {
this.updateEntries(newEntries, highlightDirection);
if (this.config.showDropDownOnResultsOnly && newEntries && newEntries.length > 0 && this.$editor.is(":focus")) {
this.openDropDown();
}
});
}
private fireChangeEvents(entry: E, originalEvent: Event) {
this.$originalInput.trigger("change");
this.onSelectedEntryChanged.fire(entry, originalEvent);
}
public setSelectedEntry(entry: E, commit = true, fireEvent = false, originalEvent?: Event) {
this.$originalInput.val(this.config.valueFunction(entry));
this.selectedEntry = entry;
let $selectedEntry = $(this.config.selectedEntryRenderingFunction(entry))
.addClass("tr-combobox-entry");
this.$selectedEntryWrapper.empty().append($selectedEntry);
if (entry != null) {
this.$editor.val(this.config.entryToEditorTextFunction(entry));
}
if (commit) {
this.lastCommittedValue = entry;
if (fireEvent) {
this.fireChangeEvents(entry, originalEvent);
}
}
if (this.$clearButton) {
this.$clearButton.toggle(entry != null);
}
if (this.isEditorVisible) {
this.showEditor(); // reposition editor
}
if (this.isDropDownOpen) {
this.repositionDropDown();
}
}
private isEntrySelected() {
return this.selectedEntry != null;
}
private showEditor() {
let $editorArea = this.$selectedEntryWrapper.find(".tr-editor-area");
if ($editorArea.length === 0) {
$editorArea = this.$selectedEntryWrapper;
}
this.$editor.css({
"width": Math.min($editorArea[0].offsetWidth, this.$trigger ? this.$trigger[0].offsetLeft - $editorArea[0].offsetLeft : 99999999) + "px", // prevent the editor from surpassing the trigger!
"height": ($editorArea[0].offsetHeight) + "px"
});
place(this.$editor[0], "top left")
.to($editorArea[0], "top left");
this.isEditorVisible = true;
}
private editorContainsFreeText() {
return this.config.allowFreeText && this.$editor.val().length > 0 && !this.isEntrySelected();
};
private hideEditor() {
this.$editor.width(0).height(0);
this.isEditorVisible = false;
}
private repositionDropDown() {
this.$dropDown.show();
place(this.$dropDown[0], "top left")
.to(this.$comboBox[0], "bottom left");
this.$comboBox.removeClass("dropdown-flipped"); // TODO
this.$dropDown.removeClass("flipped"); // TODO
this.$dropDown.width(this.$comboBox.width());
};
public openDropDown() {
if (this.isDropDownNeeded()) {
if (this.listBoxDirty) {
this.updateListBoxEntries();
}
this.$comboBox.addClass("open");
this.repositionDropDown();
this.isDropDownOpen = true;
}
}
public closeDropDown() {
this.$comboBox.removeClass("open");
this.$dropDown.hide();
this.isDropDownOpen = false;
}
private getNonSelectedEditorValue() {
return this.$editor.val().substring(0, (this.$editor[0] as any).selectionStart);
}
private autoCompleteIfPossible(delay?: number) {
if (this.config.autoComplete) {
clearTimeout(this.autoCompleteTimeoutId);
const highlightedEntry = this.listBox.getHighlightedEntry();
if (highlightedEntry && !this.doNoAutoCompleteBecauseBackspaceWasPressed) {
this.autoCompleteTimeoutId = setTimeoutOrDoImmediately(() => {
const currentEditorValue = this.getNonSelectedEditorValue();
const autoCompleteString = this.config.autoCompleteFunction(currentEditorValue, highlightedEntry) || currentEditorValue;
this.$editor.val(currentEditorValue + autoCompleteString.substr(currentEditorValue.length));
if (this.$editor.is(":focus")) {
(this.$editor[0] as any).setSelectionRange(currentEditorValue.length, autoCompleteString.length);
}
}, delay);
}
this.doNoAutoCompleteBecauseBackspaceWasPressed = false;
}
}
private updateListBoxEntries() {
this.blurCausedByClickInsideComponent = false; // we won't get any mouseout or mouseup events for entries if they get removed. so do this here proactively
this.listBox.updateEntries(this.entries);
this.listBox.highlightTextMatches(this.entries && this.entries.length <= this.config.textHighlightingEntryLimit ? this.getNonSelectedEditorValue() : null);
this.listBoxDirty = false;
}
public updateEntries(newEntries:E[], highlightDirection?:number) {
this.blurCausedByClickInsideComponent = false; // we won't get any mouseout or mouseup events for entries if they get removed. so do this here proactively
this.entries = newEntries;
this.$spinners.remove();
this.$spinners = $();
if (this.isDropDownOpen) {
this.updateListBoxEntries();
} else {
this.listBoxDirty = true;
}
if (highlightDirection == null) {
if (this.selectedEntry) {
this.listBox.setHighlightedEntry(null);
} else {
this.listBox.highlightNextEntry(1);
}
} else if (highlightDirection === 0) {
this.listBox.setHighlightedEntry(null)
} else {
this.listBox.highlightNextEntry(highlightDirection);
}
this.autoCompleteIfPossible(this.config.autoCompleteDelay);
if (this.isDropDownOpen) {
this.openDropDown(); // only for repositioning!
}
}
private isDropDownNeeded() {
return this.editingMode == 'editable' && (this.config.entries && this.config.entries.length > 0 || !this.usingDefaultQueryFunction || this.config.showTrigger);
}
public setEditingMode(newEditingMode:EditingMode) {
this.editingMode = newEditingMode;
this.$comboBox.removeClass("editable readonly disabled").addClass(this.editingMode);
if (this.isDropDownNeeded()) {
this.$dropDown.appendTo(this.$dropDownTargetElement);
}
}
public getSelectedEntry(): E {
if (this.selectedEntry == null && (!this.config.allowFreeText || !this.$editor.val())) {
return null;
} else if (this.selectedEntry == null && this.config.allowFreeText) {
return this.config.freeTextEntryFactory(this.$editor.val());
} else {
const selectedEntryToReturn = $.extend({}, this.selectedEntry);
delete selectedEntryToReturn._trEntryElement;
return selectedEntryToReturn;
}
};
public focus() {
this.showEditor();
this.$editor.select();
};
public getEditor(): Element {
return this.$editor[0];
}
public getDropDown() {
return this.$dropDown;
};
public destroy() {
this.$originalInput.removeClass('tr-original-input').insertBefore(this.$comboBox);
this.$comboBox.remove();
this.$dropDown.remove();
};
getMainDomElement(): Element {
return this.$comboBox[0];
}
}