-
Notifications
You must be signed in to change notification settings - Fork 3
/
TrivialTagComboBox.ts
782 lines (697 loc) · 33 KB
/
TrivialTagComboBox.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
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
/*!
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 {TrivialListBox, TrivialListBoxConfig} from "./TrivialListBox";
import {
DEFAULT_TEMPLATES, defaultListQueryFunctionFactory, EditingMode, escapeSpecialRegexCharacter, HighlightDirection, minimallyScrollTo, QueryFunction, selectElementContents, TrivialComponent,
wrapWithDefaultTagWrapper, keyCodes, RenderingFunction, DEFAULT_RENDERING_FUNCTIONS
} from "./TrivialCore";
import {TrivialEvent} from "./TrivialEvent";
import {place} from "place-to";
export interface TrivialTagComboBoxConfig<E> extends TrivialListBoxConfig<E> {
/**
* Calculates the value to set on the original input.
*
* @param entries the list of selected entries
* @return the string to set as the value of the original input
*/
valueFunction?: (entries: 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 entries.
*
* @default `[]`
*/
selectedEntries?: 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,
/**
* List of characters that, when entered by the user, trigger the creation of a tag/entry.
*
* @default `[",", ";"]`
*/
freeTextSeparators?: string[],
/**
* 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 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,
/**
* Function deciding whether an entry entered by the user is complete or not (partial).
* A partial entry is an entry that needs more input from the user's side.
*
* @param entry
* @return `true` if the entry is considered complete, `false` if not
* @default always returns `true`
*/
tagCompleteDecider?: (entry: E) => boolean,
/**
* Used to merge the current partial tag with the newly selected by the user.
* (composite tags feature)
*
* @param partialEntry the current partial entry
* @param newEntryPart the entry selected/entered by the user
* @return a new entry that will replace the current partial entry. This may in turn be a partial or complete entry.
* @default always returns the `newEntryPart`
*/
entryMerger?: (partialEntry: E, newEntryPart: E) => E,
/**
* Whether or not a partial tag should be removed when the component
* looses the focus.
*
* @default `true`
*/
removePartialTagOnBlur?: boolean,
/**
* Decides whether the user's input/selection is accepted or not.
* This can serve many purposes, including
* * implementing duplicate prevention
* * limiting the number of selectable tags
* * allowing or disallowing free text entries (this was previously possible using the now removed `allowFreeText` option)
* * allowing only free text entries of a certain form
* * ...
*
* @param entry the entry to be accepted or not
* @return `true` if the entry is accepted, `false` if not
* @default accepting all non-free-text entries
*/
selectionAcceptor?: (entry: E) => boolean,
/**
* HTML string defining the spinner to be displayed while entries are being retrieved.
*/
spinnerTemplate?: string
}
export class TrivialTagComboBox<E> implements TrivialComponent {
private config: TrivialTagComboBoxConfig<E>;
private $spinners = $();
private $originalInput: JQuery;
private $tagComboBox: JQuery;
private $dropDown: JQuery;
private $trigger: JQuery;
private $editor: JQuery;
private $dropDownTargetElement: JQuery;
private $tagArea: 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 entries: E[];
private selectedEntries: E[] = [];
private blurCausedByClickInsideComponent = false;
private autoCompleteTimeoutId = -1;
private doNoAutoCompleteBecauseBackspaceWasPressed = false;
private listBoxDirty = true;
private repositionDropDownScheduler: number = null;
private editingMode: EditingMode;
private usingDefaultQueryFunction: boolean;
private currentPartialTag: E;
constructor(originalInput: JQuery|Element|string, options: TrivialTagComboBoxConfig<E> = {} as any) {
this.config = $.extend(<TrivialTagComboBoxConfig<E>>{
valueFunction: (entries:E[]) => entries.map(e => (e as any)._isFreeTextEntry ? (e as any).displayValue : (e as any).id).join(','),
entryRenderingFunction: DEFAULT_RENDERING_FUNCTIONS.image2Lines,
selectedEntryRenderingFunction: (entry: E) => {
return wrapWithDefaultTagWrapper(this.config.entryRenderingFunction(entry));
},
spinnerTemplate: DEFAULT_TEMPLATES.defaultSpinnerTemplate,
textHighlightingEntryLimit: 100,
entries: null,
selectedEntries: [],
maxSelectedEntries: null,
queryFunction: null, // defined below...
autoComplete: true,
autoCompleteDelay: 0,
autoCompleteFunction: (editorText: string, entry: E) => {
if (editorText) {
for (let propertyName in entry) {
if (entry.hasOwnProperty(propertyName)) {
const propertyValue = entry[propertyName];
if (propertyValue && ("" + propertyValue).toLowerCase().indexOf(editorText.toLowerCase()) === 0) {
return "" + propertyValue;
}
}
}
return null;
} else {
return null;
}
},
freeTextSeparators: [',', ';'], // TODO function here
freeTextEntryFactory: (freeText: string) => {
return {
displayValue: freeText,
_isFreeTextEntry: true
};
},
tagCompleteDecider: (mergedEntry: E) => {
return true;
},
entryMerger: (partialEntry: E, newEntry: E) => {
return newEntry;
},
removePartialTagOnBlur: true,
showTrigger: true,
matchingOptions: {
matchingMode: 'contains',
ignoreCase: true,
maxLevenshteinDistance: 2
},
editingMode: "editable", // one of 'editable', 'disabled' and 'readonly'
showDropDownOnResultsOnly: false,
selectionAcceptor: (e) => !(e as any)._isFreeTextEntry // do not allow free text entries by default
}, 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).addClass("tr-original-input");
this.$tagComboBox = $('<div class="tr-tagbox tr-input-wrapper"/>')
.insertAfter(this.$originalInput);
this.$originalInput.appendTo(this.$tagComboBox);
this.$tagArea = $('<div class="tr-tagbox-tagarea"/>').appendTo(this.$tagComboBox);
if (this.config.showTrigger) {
this.$trigger = $('<div class="tr-trigger"><span class="tr-trigger-icon"/></div>').appendTo(this.$tagComboBox);
this.$trigger.mousedown(() => {
this.focusEditor();
if (this.isDropDownOpen) {
this.closeDropDown();
} else {
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.$editor = $('<span contenteditable="true" class="tagbox-editor" autocomplete="off"></span>');
this.$editor.appendTo(this.$tagArea).addClass("tr-tagbox-editor tr-editor")
.focus(() => {
if (this.blurCausedByClickInsideComponent) {
// do nothing!
} else {
this.$originalInput.triggerHandler('focus');
this.onFocus.fire();
this.$tagComboBox.addClass('focus');
}
setTimeout(() => { // the editor needs to apply its new css sheets (:focus) before we scroll to it...
minimallyScrollTo(this.$tagArea, this.$editor);
});
})
.blur((e) => {
if (this.blurCausedByClickInsideComponent) {
this.$editor.focus();
} else {
this.$originalInput.triggerHandler('blur');
this.onBlur.fire();
this.$tagComboBox.removeClass('focus');
this.entries = null;
this.closeDropDown();
if (this.$editor.text().trim().length > 0) {
this.addSelectedEntry(this.config.freeTextEntryFactory(this.$editor.text()), true, e);
}
if (this.config.removePartialTagOnBlur && this.currentPartialTag != null) {
this.cancelPartialTag();
}
this.$editor.text("");
}
})
.keydown((e: KeyboardEvent) => {
if (keyCodes.isModifierKey(e)) {
return;
} else if (e.which == keyCodes.tab || e.which == keyCodes.enter) {
const highlightedEntry = this.listBox.getHighlightedEntry();
if (this.isDropDownOpen && highlightedEntry != null) {
this.addSelectedEntry(highlightedEntry, true, e);
e.preventDefault(); // do not tab away from the tag box nor insert a newline character
} else if (this.$editor.text().trim().length > 0) {
this.addSelectedEntry(this.config.freeTextEntryFactory(this.$editor.text()), true, e);
e.preventDefault(); // do not tab away from the tag box nor insert a newline character
} else if (this.currentPartialTag) {
if (e.shiftKey) { // we do not want the editor to get the focus right back, so we need to position the $editor intelligently...
this.doIgnoringBlurEvents(() => this.$editor.insertAfter((this.currentPartialTag as any)._trEntryElement));
} else {
this.doIgnoringBlurEvents(() => this.$editor.insertBefore((this.currentPartialTag as any)._trEntryElement));
}
(this.currentPartialTag as any)._trEntryElement.remove();
this.currentPartialTag = null;
}
this.closeDropDown(); console.log("closing dropdown!");
if (e.which == keyCodes.enter) {
e.preventDefault(); // under any circumstances, prevent the new line to be added to the editor!
}
} else if (e.which == keyCodes.left_arrow || e.which == keyCodes.right_arrow) {
if (e.which == keyCodes.left_arrow && this.$editor.text().length === 0 && window.getSelection().anchorOffset === 0) {
if (this.$editor.prev()) {
this.doIgnoringBlurEvents(() => this.$editor.insertBefore(this.$editor.prev()));
this.focusEditor();
}
} else if (e.which == keyCodes.right_arrow && this.$editor.text().length === 0 && window.getSelection().anchorOffset === 0) {
if (this.$editor.next()) {
this.doIgnoringBlurEvents(() => this.$editor.insertAfter(this.$editor.next()));
this.focusEditor();
}
}
} else if (e.which == keyCodes.backspace || e.which == keyCodes.delete) {
if (this.$editor.text() == "") {
if (this.currentPartialTag != null) {
this.cancelPartialTag();
this.focusEditor();
} else {
const tagToBeRemoved = this.selectedEntries[this.$editor.index() + (e.which == keyCodes.backspace ? -1 : 0)];
if (tagToBeRemoved) {
this.removeTag(tagToBeRemoved, e);
this.closeDropDown();
}
}
} else {
this.doNoAutoCompleteBecauseBackspaceWasPressed = true; // we want query results, but no autocomplete
setTimeout(() => this.query(1)); // asynchronously to make sure the editor has been updated
}
} else if (e.which == keyCodes.up_arrow || e.which == keyCodes.down_arrow) {
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.escape) {
this.closeDropDown();
if (this.$editor.text().length > 0) {
this.$editor.text("");
} else if (this.currentPartialTag != null) {
this.cancelPartialTag();
this.focusEditor();
}
} else {
if (!this.config.showDropDownOnResultsOnly) {
this.openDropDown();
}
setTimeout(() => this.query(1)); // asynchronously to make sure the editor has been updated
}
})
.keyup((e) => {
function splitStringBySeparatorChars(s: string, separatorChars: string[]) {
return s.split(new RegExp("[" + escapeSpecialRegexCharacter(separatorChars.join()) + "]"));
}
if (this.$editor.find('*').length > 0) {
this.$editor.text(this.$editor.text()); // removes possible <div> or <br> or whatever the browser likes to put inside...
}
const editorValueBeforeCursor = this.getNonSelectedEditorValue();
if (editorValueBeforeCursor.length > 0) {
const tagValuesEnteredByUser = splitStringBySeparatorChars(editorValueBeforeCursor, this.config.freeTextSeparators);
for (let i = 0; i < tagValuesEnteredByUser.length - 1; i++) {
const value = tagValuesEnteredByUser[i].trim();
if (value.length > 0) {
this.addSelectedEntry(this.config.freeTextEntryFactory(value), true, e);
}
this.$editor.text(tagValuesEnteredByUser[tagValuesEnteredByUser.length - 1]);
selectElementContents(this.$editor[0], this.$editor.text().length, this.$editor.text().length);
this.entries = null;
this.closeDropDown();
}
}
})
.mousedown(() => {
if (!this.config.showDropDownOnResultsOnly) {
this.openDropDown();
}
this.query();
});
if (this.$originalInput.attr("placeholder")) {
this.$editor.attr("placeholder", this.$originalInput.attr("placeholder"));
}
if (this.$originalInput.attr("tabindex")) {
this.$editor.attr("tabindex", this.$originalInput.attr("tabindex"));
}
if (this.$originalInput.attr("autofocus")) {
this.$editor.focus();
}
this.$tagComboBox.add(this.$dropDown).mousedown(() => {
if (this.$editor.is(":focus")) {
this.blurCausedByClickInsideComponent = true;
}
}).mouseup(() => {
if (this.blurCausedByClickInsideComponent) {
this.focusEditor();
setTimeout(() => this.blurCausedByClickInsideComponent = false); // let the other handlers do their job before removing event blocker
}
}).mouseout(() => {
if (this.blurCausedByClickInsideComponent) {
this.focusEditor();
setTimeout(() => this.blurCausedByClickInsideComponent = false); // let the other handlers do their job before removing event blocker
}
});
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?: any, originalEvent?: Event) => {
if (selectedEntry) {
this.addSelectedEntry(selectedEntry, true, originalEvent);
this.listBox.setSelectedEntry(null);
this.closeDropDown();
}
});
this.$tagArea.mousedown((e) => {
if (this.currentPartialTag == null) {
let $nearestTag = this.findNearestTag(e);
if ($nearestTag) {
const tagBoundingRect = $nearestTag[0].getBoundingClientRect();
const isRightSide = e.clientX > (tagBoundingRect.left + tagBoundingRect.right) / 2;
if (isRightSide) {
this.doIgnoringBlurEvents(() => this.$editor.insertAfter($nearestTag));
} else {
this.doIgnoringBlurEvents(() => this.$editor.insertBefore($nearestTag));
}
}
}
this.$editor.focus();
}).click((e) => {
if (!this.config.showDropDownOnResultsOnly) {
this.openDropDown();
}
this.query();
});
this.setSelectedEntries(this.config.selectedEntries, true);
// ===
this.$tagComboBox.data("trivialTagComboBox", this);
}
private cancelPartialTag() {
this.doIgnoringBlurEvents(() => this.$editor.insertBefore((this.currentPartialTag as any)._trEntryElement));
(this.currentPartialTag as any)._trEntryElement.remove();
this.currentPartialTag = null;
}
private findNearestTag(mouseEvent: JQueryMouseEventObject) {
let $nearestTag: JQuery = null;
let smallestDistanceX = 1000000;
for (let i = 0; i < this.selectedEntries.length; i++) {
const selectedEntry = this.selectedEntries[i];
const $tag = (selectedEntry as any)._trEntryElement;
const tagBoundingRect = $tag[0].getBoundingClientRect();
const sameRow = mouseEvent.clientY >= tagBoundingRect.top && mouseEvent.clientY < tagBoundingRect.bottom;
const sameCol = mouseEvent.clientX >= tagBoundingRect.left && mouseEvent.clientX < tagBoundingRect.right;
const distanceX = sameCol ? 0 : Math.min(Math.abs(mouseEvent.clientX - tagBoundingRect.left), Math.abs(mouseEvent.clientX - tagBoundingRect.right));
if (sameRow && distanceX < smallestDistanceX) {
$nearestTag = $tag;
smallestDistanceX = distanceX;
if (distanceX === 0) {
break;
}
}
}
return $nearestTag;
}
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?: HighlightDirection) {
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) {
this.listBox.highlightNextEntry(highlightDirection);
} else {
this.listBox.setHighlightedEntry(null);
}
this.autoCompleteIfPossible(this.config.autoCompleteDelay);
if (this.isDropDownOpen) {
this.openDropDown(); // only for repositioning!
}
}
private removeTag(tagToBeRemoved: E, originalEvent?: Event) {
const index = this.selectedEntries.indexOf(tagToBeRemoved);
if (index > -1) {
this.selectedEntries.splice(index, 1);
}
(tagToBeRemoved as any)._trEntryElement.remove();
this.$originalInput.val(this.config.valueFunction(this.getSelectedEntries()));
this.fireChangeEvents(this.getSelectedEntries(), originalEvent);
}
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(entries: E[], originalEvent: Event) {
this.$originalInput.trigger("change");
this.onSelectedEntryChanged.fire(entries, originalEvent);
}
private addSelectedEntry(entry: E, fireEvent = false, originalEvent?: Event, forceAcceptance?: boolean) {
if (entry == null) {
return; // do nothing
}
if (!forceAcceptance && !this.config.selectionAcceptor(entry)) {
return;
}
let wasPartial = !!this.currentPartialTag;
const editorIndex = wasPartial ? (this.currentPartialTag as any)._trEntryElement.index() : this.$editor.index();
if (wasPartial) {
this.doIgnoringBlurEvents(() => this.$editor.appendTo(this.$tagArea)); // make sure the event handlers don't get detached when removing the partial tag
(this.currentPartialTag as any)._trEntryElement.remove();
entry = this.config.entryMerger(this.currentPartialTag, entry);
}
const tag = $.extend({}, entry);
if (this.config.tagCompleteDecider(entry)) {
this.selectedEntries.splice(editorIndex, 0, tag);
this.$originalInput.val(this.config.valueFunction(this.getSelectedEntries()));
this.currentPartialTag = null;
} else {
this.currentPartialTag = tag;
}
const $entry = $(this.config.selectedEntryRenderingFunction(tag));
const $tagWrapper = $('<div class="tr-tagbox-tag"></div>')
.append($entry);
this.doIgnoringBlurEvents(() => this.insertAtIndex($tagWrapper, editorIndex));
tag._trEntryElement = $tagWrapper;
$entry.find('.tr-remove-button').click((e) => {
this.removeTag(tag);
return false;
});
if (this.config.tagCompleteDecider(entry)) {
this.doIgnoringBlurEvents(() => this.insertAtIndex(this.$editor, editorIndex + 1));
} else {
this.doIgnoringBlurEvents(() => this.$editor.appendTo($entry.find('.tr-editor')));
}
this.$editor.text("");
this.focusEditor();
if (this.config.tagCompleteDecider(entry) && fireEvent) {
this.fireChangeEvents(this.getSelectedEntries(), originalEvent);
}
}
private focusEditor() {
selectElementContents(this.$editor[0], 0, 0); // we need to do this, else the cursor does not appear in Chrome...
this.$editor.focus();
}
private repositionDropDown() {
place(this.$dropDown[0], "top left")
.to(this.$tagComboBox[0], "bottom left");
this.$tagComboBox.removeClass("dropdown-flipped"); // TODO
this.$dropDown.removeClass("flipped"); // TODO
this.$dropDown.width(this.$tagComboBox.width());
}
public openDropDown() {
if (this.isDropDownNeeded()) {
if (this.listBoxDirty) {
this.updateListBoxEntries();
}
this.$tagComboBox.addClass("open");
this.$dropDown.show();
this.repositionDropDown();
this.isDropDownOpen = true;
}
if (this.repositionDropDownScheduler == null) {
this.repositionDropDownScheduler = window.setInterval(() => this.repositionDropDown(), 300); // make sure that under no circumstances the dropdown is mal-positioned
}
}
public closeDropDown() {
this.$tagComboBox.removeClass("open");
this.$dropDown.hide();
this.isDropDownOpen = false;
if (this.repositionDropDownScheduler != null) {
clearInterval(this.repositionDropDownScheduler);
this.repositionDropDownScheduler = null;
}
}
private getNonSelectedEditorValue() {
const editorText = this.$editor.text().replace(String.fromCharCode(160), " ");
const selection = window.getSelection();
if (selection.anchorOffset != selection.focusOffset) {
return editorText.substring(0, Math.min((window.getSelection() as any).baseOffset, window.getSelection().focusOffset));
} else {
return editorText;
}
}
private autoCompleteIfPossible(delay: number) {
if (this.config.autoComplete) {
clearTimeout(this.autoCompleteTimeoutId);
const highlightedEntry = this.listBox.getHighlightedEntry();
if (highlightedEntry && !this.doNoAutoCompleteBecauseBackspaceWasPressed) {
this.autoCompleteTimeoutId = window.setTimeout(() => {
const currentEditorValue = this.getNonSelectedEditorValue();
const autoCompleteString = this.config.autoCompleteFunction(currentEditorValue, highlightedEntry) || currentEditorValue;
this.$editor.text(currentEditorValue + autoCompleteString.replace(' ', String.fromCharCode(160)).substr(currentEditorValue.length)); // I have to replace whitespaces by 160 because text() trims whitespaces...
this.repositionDropDown(); // the auto-complete might cause a line-break, so the dropdown would cover the editor...
if (this.$editor.is(":focus")) {
selectElementContents(this.$editor[0], currentEditorValue.length, autoCompleteString.length);
}
}, delay || 0);
}
this.doNoAutoCompleteBecauseBackspaceWasPressed = false;
}
}
private isDropDownNeeded() {
return this.editingMode == 'editable' && (this.config.entries && this.config.entries.length > 0 || !this.usingDefaultQueryFunction || this.config.showTrigger);
}
private insertAtIndex($element: JQuery, index: number) {
const lastIndex = this.$tagArea.children().length;
if (index < lastIndex) {
this.$tagArea.children().eq(index).before($element);
} else {
this.$tagArea.append($element);
}
}
private doIgnoringBlurEvents(f:Function) {
let oldValueOfBlurCausedByClickInsideComponent = this.blurCausedByClickInsideComponent;
this.blurCausedByClickInsideComponent = true;
try {
return f.call(this);
} finally {
this.blurCausedByClickInsideComponent = oldValueOfBlurCausedByClickInsideComponent;
}
}
public setEditingMode(newEditingMode: EditingMode) {
this.editingMode = newEditingMode;
this.$tagComboBox.removeClass("editable readonly disabled").addClass(this.editingMode);
if (this.isDropDownNeeded()) {
this.$dropDown.appendTo(this.$dropDownTargetElement);
}
}
public setSelectedEntries(entries: E[], forceAcceptance?: boolean) {
this.selectedEntries
.slice() // copy the array as it gets changed during the forEach loop
.forEach((e) => this.removeTag(e));
if (entries) {
for (let i = 0; i < entries.length; i++) {
this.addSelectedEntry(entries[i], false, null, forceAcceptance);
}
}
}
public getSelectedEntries() {
const selectedEntriesToReturn: E[] = [];
for (let i = 0; i < this.selectedEntries.length; i++) {
const selectedEntryToReturn = $.extend({}, this.selectedEntries[i]);
delete selectedEntryToReturn._trEntryElement;
selectedEntriesToReturn.push(selectedEntryToReturn);
}
return selectedEntriesToReturn;
};
public getCurrentPartialTag() {
return this.currentPartialTag;
}
public focus() {
this.$editor.focus();
selectElementContents(this.$editor[0], 0, this.$editor.text().length);
};
public getEditor(): Element {
return this.$editor[0];
}
public destroy() {
this.$originalInput.removeClass('tr-original-input').insertBefore(this.$tagComboBox);
this.$tagComboBox.remove();
this.$dropDown.remove();
};
getMainDomElement(): Element {
return this.$tagComboBox[0];
}
}