-
Notifications
You must be signed in to change notification settings - Fork 426
/
tagify.min.js
3073 lines (2591 loc) 路 122 KB
/
tagify.min.js
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
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global = global || self, global.Tagify = factory());
}(this, (function () { 'use strict';
function _typeof(obj) {
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function (obj) {
return typeof obj;
};
} else {
_typeof = function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof(obj);
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function _toConsumableArray(arr) {
return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread();
}
function _arrayWithoutHoles(arr) {
if (Array.isArray(arr)) {
for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];
return arr2;
}
}
function _iterableToArray(iter) {
if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
}
function _nonIterableSpread() {
throw new TypeError("Invalid attempt to spread non-iterable instance");
}
// console.json = console.json || function(argument){
// for(var arg=0; arg < arguments.length; ++arg)
// console.log( JSON.stringify(arguments[arg], null, 4) )
// }
// const isEdge = /Edge/.test(navigator.userAgent)
var sameStr = function sameStr(s1, s2, caseSensitive, trim) {
// cast to String
s1 = "" + s1;
s2 = "" + s2;
if (trim) {
s1 = s1.trim();
s2 = s2.trim();
}
return caseSensitive ? s1 == s2 : s1.toLowerCase() == s2.toLowerCase();
}; // const getUID = () => (new Date().getTime() + Math.floor((Math.random()*10000)+1)).toString(16)
var removeCollectionProp = function removeCollectionProp(collection, unwantedProps) {
return collection.map(function (v) {
var props = {};
for (var p in v) {
if (unwantedProps.indexOf(p) < 0) props[p] = v[p];
}
return props;
});
};
function decode(s) {
var el = document.createElement('div');
return s.replace(/\&#?[0-9a-z]+;/gi, function (enc) {
el.innerHTML = enc;
return el.innerText;
});
}
/**
* utility method
* https://stackoverflow.com/a/35385518/104380
* @param {String} s [HTML string]
* @return {Object} [DOM node]
*/
function parseHTML(s) {
var parser = new DOMParser(),
node = parser.parseFromString(s.trim(), "text/html");
return node.body.firstElementChild;
}
/**
* Removed new lines and irrelevant spaces which might affect layout, and are better gone
* @param {string} s [HTML string]
*/
function minify(s) {
return s ? s.replace(/\>[\r\n ]+\</g, "><").replace(/(<.*?>)|\s+/g, function (m, $1) {
return $1 ? $1 : ' ';
}) // https://stackoverflow.com/a/44841484/104380
: "";
}
function removeTextChildNodes(elm) {
var iter = document.createNodeIterator(elm, NodeFilter.SHOW_TEXT, null, false),
textnode; // print all text nodes
while (textnode = iter.nextNode()) {
if (!textnode.textContent.trim()) textnode.parentNode.removeChild(textnode);
}
}
function getfirstTextNode(elm, action) {
action = action || 'previous';
while (elm = elm[action + 'Sibling']) {
if (elm.nodeType == 3) return elm;
}
}
/**
* utility method
* https://stackoverflow.com/a/6234804/104380
*/
function escapeHTML(s) {
return s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/`|'/g, "'");
}
function isArray(a) {
return a instanceof Array;
}
/**
* Checks if an argument is a javascript Object
*/
function isObject(obj) {
var type = Object.prototype.toString.call(obj).split(' ')[1].slice(0, -1);
return obj === Object(obj) && type != 'Array' && type != 'Function' && type != 'RegExp' && type != 'HTMLUnknownElement';
}
/**
* merge objects into a single new one
* TEST: extend({}, {a:{foo:1}, b:[]}, {a:{bar:2}, b:[1], c:()=>{}})
*/
function extend(o, o1, o2) {
if (!(o instanceof Object)) o = {};
copy(o, o1);
if (o2) copy(o, o2);
function copy(a, b) {
// copy o2 to o
for (var key in b) {
if (b.hasOwnProperty(key)) {
if (isObject(b[key])) {
if (!isObject(a[key])) a[key] = Object.assign({}, b[key]);else copy(a[key], b[key]);
continue;
}
if (isArray(b[key])) {
a[key] = Object.assign([], b[key]);
continue;
}
a[key] = b[key];
}
}
}
return o;
}
/**
* Extracted from: https://stackoverflow.com/a/37511463/104380
* @param {String} s
*/
function unaccent(s) {
// if not supported, do not continue.
// developers should use a polyfill:
// https://github.com/walling/unorm
if (!String.prototype.normalize) return s;
if (typeof s === 'string') return s.normalize("NFD").replace(/[\u0300-\u036f]/g, "");
}
/**
* Meassures an element's height, which might yet have been added DOM
* https://stackoverflow.com/q/5944038/104380
* @param {DOM} node
*/
function getNodeHeight(node) {
var height,
clone = node.cloneNode(true);
clone.style.cssText = "position:fixed; top:-9999px; opacity:0";
document.body.appendChild(clone);
height = clone.clientHeight;
clone.parentNode.removeChild(clone);
return height;
}
var isChromeAndroidBrowser = /(?=.*chrome)(?=.*android)/i.test(navigator.userAgent);
var dropdownMethods = {
init: function init() {
this.DOM.dropdown = this.parseTemplate('dropdown', [this.settings]);
this.DOM.dropdown.content = this.DOM.dropdown.querySelector(this.settings.classNames.dropdownWrapperSelector);
},
/**
* shows the suggestions select box
* @param {String} value [optional, filter the whitelist by this value]
*/
show: function show(value) {
var _this = this;
var _s = this.settings,
firstListItem,
firstListItemValue,
selection = window.getSelection(),
allowNewTags = _s.mode == 'mix' && !_s.enforceWhitelist,
noWhitelist = !_s.whitelist || !_s.whitelist.length,
noMatchListItem,
isManual = _s.dropdown.position == 'manual'; // if text still exists in the input, and `show` method has no argument, then the input's text should be used
value = value === undefined ? this.state.inputText : value; // 鈿狅笍 Do not render suggestions list if:
// 1. there's no whitelist (can happen while async loading) AND new tags arn't allowed
// 2. dropdown is disabled
// 3. loader is showing (controlled outside of this code)
if (noWhitelist && !allowNewTags && !_s.templates.dropdownItemNoMatch || _s.dropdown.enable === false || this.state.isLoading) return;
clearTimeout(this.dropdownHide__bindEventsTimeout); // if no value was supplied, show all the "whitelist" items in the dropdown
// @type [Array] listItems
// TODO: add a Setting to control items' sort order for "listItems"
this.suggestedListItems = this.dropdown.filterListItems.call(this, value); // trigger at this exact point to let the developer the chance to manually set "this.suggestedListItems"
if (value && !this.suggestedListItems.length) {
this.trigger('dropdown:noMatch', value);
if (_s.templates.dropdownItemNoMatch) noMatchListItem = _s.templates.dropdownItemNoMatch.call(this, {
value: value
});
} // if "dropdownItemNoMatch" was no defined, procceed regular flow.
//
if (!noMatchListItem) {
// in mix-mode, if the value isn't included in the whilelist & "enforceWhitelist" setting is "false",
// then add a custom suggestion item to the dropdown
if (this.suggestedListItems.length) {
if (value && allowNewTags && !this.state.editing.scope && !sameStr(this.suggestedListItems[0].value, value)) this.suggestedListItems.unshift({
value: value
});
} else {
if (value && allowNewTags && !this.state.editing.scope) {
this.suggestedListItems = [{
value: value
}];
} // hide suggestions list if no suggestion matched
else {
this.input.autocomplete.suggest.call(this);
this.dropdown.hide.call(this);
return;
}
}
firstListItem = this.suggestedListItems[0];
firstListItemValue = "" + (isObject(firstListItem) ? firstListItem.value : firstListItem);
if (_s.autoComplete && firstListItemValue) {
// only fill the sugegstion if the value of the first list item STARTS with the input value (regardless of "fuzzysearch" setting)
if (firstListItemValue.indexOf(value) == 0) this.input.autocomplete.suggest.call(this, firstListItem);
}
}
this.dropdown.fill.call(this, noMatchListItem);
if (_s.dropdown.highlightFirst) this.dropdown.highlightOption.call(this, this.DOM.dropdown.content.children[0]); // bind events, exactly at this stage of the code. "dropdown.show" method is allowed to be
// called multiple times, regardless if the dropdown is currently visible, but the events-binding
// should only be called if the dropdown wasn't previously visible.
if (!this.state.dropdown.visible) // timeout is needed for when pressing arrow down to show the dropdown,
// so the key event won't get registered in the dropdown events listeners
setTimeout(this.dropdown.events.binding.bind(this)); // set the dropdown visible state to be the same as the searched value.
// MUST be set *before* position() is called
this.state.dropdown.visible = value || true;
this.state.dropdown.query = value;
this.state.selection = {
anchorOffset: selection.anchorOffset,
anchorNode: selection.anchorNode
}; // try to positioning the dropdown (it might not yet be on the page, doesn't matter, next code handles this)
if (!isManual) {
// a slight delay is needed if the dropdown "position" setting is "text", and nothing was typed in the input,
// so sadly the "getCaretGlobalPosition" method doesn't recognize the caret position without this delay
setTimeout(function () {
_this.dropdown.position.call(_this);
_this.dropdown.render.call(_this);
});
} // a delay is needed because of the previous delay reason.
// this event must be fired after the dropdown was rendered & positioned
setTimeout(function () {
_this.trigger("dropdown:show", _this.DOM.dropdown);
});
},
hide: function hide(force) {
var _this2 = this;
var _this$DOM = this.DOM,
scope = _this$DOM.scope,
dropdown = _this$DOM.dropdown,
isManual = this.settings.dropdown.position == 'manual' && !force; // if there's no dropdown, this means the dropdown events aren't binded
if (!dropdown || !document.body.contains(dropdown) || isManual) return;
window.removeEventListener('resize', this.dropdown.position);
this.dropdown.events.binding.call(this, false); // unbind all events
// if the dropdown is open, and the input (scope) is clicked,
// the dropdown should be now "close", and the next click (on the scope)
// should re-open it, and without a timeout, clicking to close will re-open immediately
// clearTimeout(this.dropdownHide__bindEventsTimeout)
// this.dropdownHide__bindEventsTimeout = setTimeout(this.events.binding.bind(this), 250) // re-bind main events
scope.setAttribute("aria-expanded", false);
dropdown.parentNode.removeChild(dropdown); // scenario: clicking the scope to show the dropdown, clicking again to hide -> calls dropdown.hide() and then re-focuses the input
// which casues another onFocus event, which checked "this.state.dropdown.visible" and see it as "false" and re-open the dropdown
setTimeout(function () {
_this2.state.dropdown.visible = false;
}, 100);
this.state.dropdown.query = this.state.ddItemData = this.state.ddItemElm = this.state.selection = null; // if the user closed the dropdown (in mix-mode) while a potential tag was detected, flag the current tag
// so the dropdown won't be shown on following user input for that "tag"
if (this.state.tag && this.state.tag.value.length) {
this.state.flaggedTags[this.state.tag.baseOffset] = this.state.tag;
}
this.trigger("dropdown:hide", dropdown);
return this;
},
render: function render() {
var _this3 = this;
// let the element render in the DOM first, to accurately measure it.
// this.DOM.dropdown.style.cssText = "left:-9999px; top:-9999px;";
var ddHeight = getNodeHeight(this.DOM.dropdown),
_s = this.settings;
this.DOM.scope.setAttribute("aria-expanded", true); // if the dropdown has yet to be appended to the DOM,
// append the dropdown to the body element & handle events
if (!document.body.contains(this.DOM.dropdown)) {
this.DOM.dropdown.classList.add(_s.classNames.dropdownInital);
this.dropdown.position.call(this, ddHeight);
_s.dropdown.appendTarget.appendChild(this.DOM.dropdown);
setTimeout(function () {
return _this3.DOM.dropdown.classList.remove(_s.classNames.dropdownInital);
});
}
return this;
},
/**
*
* @param {String/Array} HTMLContent - optional
*/
fill: function fill(HTMLContent) {
HTMLContent = typeof HTMLContent == 'string' ? HTMLContent : this.dropdown.createListHTML.call(this, HTMLContent || this.suggestedListItems);
this.DOM.dropdown.content.innerHTML = minify(HTMLContent);
},
/**
* fill data into the suggestions list
* (mainly used to update the list when removing tags, so they will be re-added to the list. not efficient)
*/
refilter: function refilter(value) {
value = value || this.state.dropdown.query || '';
this.suggestedListItems = this.dropdown.filterListItems.call(this, value);
this.dropdown.fill.call(this);
if (!this.suggestedListItems.length) this.dropdown.hide.call(this);
this.trigger("dropdown:updated", this.DOM.dropdown);
},
position: function position(ddHeight) {
if (this.settings.dropdown.position == 'manual') return;
var placeAbove,
rect,
top,
bottom,
left,
width,
parentsPositions,
ddElm = this.DOM.dropdown,
viewportHeight = document.documentElement.clientHeight,
viewportWidth = Math.max(document.documentElement.clientWidth || 0, window.innerWidth || 0),
positionTo = viewportWidth > 480 ? this.settings.dropdown.position : 'all',
ddTarget = this.DOM[positionTo == 'input' ? 'input' : 'scope'];
ddHeight = ddHeight || ddElm.clientHeight;
function getParentsPositions(p) {
var left = 0,
top = 0;
while (p) {
left += p.offsetLeft || 0;
top += p.offsetTop || 0;
p = p.parentNode;
}
return {
left: left,
top: top
};
}
if (!this.state.dropdown.visible) return;
if (positionTo == 'text') {
rect = this.getCaretGlobalPosition();
bottom = rect.bottom;
top = rect.top;
left = rect.left;
width = 'auto';
} else {
parentsPositions = getParentsPositions(this.settings.dropdown.appendTarget);
rect = ddTarget.getBoundingClientRect();
top = rect.top + 2 - parentsPositions.top;
bottom = rect.bottom - 1 - parentsPositions.top;
left = rect.left - parentsPositions.left;
width = rect.width + 'px';
}
top = Math.floor(top);
bottom = Math.ceil(bottom);
placeAbove = viewportHeight - rect.bottom < ddHeight; // flip vertically if there is no space for the dropdown below the input
ddElm.style.cssText = "left:" + (left + window.pageXOffset) + "px; width:" + width + ";" + (placeAbove ? "top: " + (top + window.pageYOffset) + "px" : "top: " + (bottom + window.pageYOffset) + "px");
ddElm.setAttribute('placement', placeAbove ? "top" : "bottom");
ddElm.setAttribute('position', positionTo);
},
events: {
/**
* Events should only be binded when the dropdown is rendered and removed when isn't
* because there might be multiple Tagify instances on a certain page
* @param {Boolean} bindUnbind [optional. true when wanting to unbind all the events]
*/
binding: function binding() {
var bindUnbind = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
// references to the ".bind()" methods must be saved so they could be unbinded later
var _CB = this.dropdown.events.callbacks,
// callback-refs
_CBR = this.listeners.dropdown = this.listeners.dropdown || {
position: this.dropdown.position.bind(this),
onKeyDown: _CB.onKeyDown.bind(this),
onMouseOver: _CB.onMouseOver.bind(this),
onMouseLeave: _CB.onMouseLeave.bind(this),
onClick: _CB.onClick.bind(this),
onScroll: _CB.onScroll.bind(this)
},
action = bindUnbind ? 'addEventListener' : 'removeEventListener';
if (this.settings.dropdown.position != 'manual') {
window[action]('resize', _CBR.position);
window[action]('keydown', _CBR.onKeyDown);
}
this.DOM.dropdown[action]('mouseover', _CBR.onMouseOver);
this.DOM.dropdown[action]('mouseleave', _CBR.onMouseLeave);
this.DOM.dropdown[action]('mousedown', _CBR.onClick);
this.DOM.dropdown.content[action]('scroll', _CBR.onScroll);
},
callbacks: {
onKeyDown: function onKeyDown(e) {
// get the "active" element, and if there was none (yet) active, use first child
var activeListElm = this.DOM.dropdown.querySelector(this.settings.classNames.dropdownItemActiveSelector),
selectedElm = activeListElm;
switch (e.key) {
case 'ArrowDown':
case 'ArrowUp':
case 'Down': // >IE11
case 'Up':
{
// >IE11
e.preventDefault();
var dropdownItems;
if (selectedElm) selectedElm = selectedElm[(e.key == 'ArrowUp' || e.key == 'Up' ? "previous" : "next") + "ElementSibling"]; // if no element was found, loop
if (!selectedElm) {
dropdownItems = this.DOM.dropdown.content.children;
selectedElm = dropdownItems[e.key == 'ArrowUp' || e.key == 'Up' ? dropdownItems.length - 1 : 0];
}
this.dropdown.highlightOption.call(this, selectedElm, true);
break;
}
case 'Escape':
case 'Esc':
// IE11
this.dropdown.hide.call(this);
break;
case 'ArrowRight':
if (this.state.actions.ArrowLeft) return;
case 'Tab':
{
// in mix-mode, treat arrowRight like Enter key, so a tag will be created
if (this.settings.mode != 'mix' && selectedElm && !this.settings.autoComplete.rightKey && !this.state.editing) {
e.preventDefault(); // prevents blur so the autocomplete suggestion will not become a tag
var tagifySuggestionIdx = selectedElm.getAttribute('tagifySuggestionIdx'),
data = tagifySuggestionIdx ? this.suggestedListItems[+tagifySuggestionIdx] : '';
this.input.autocomplete.set.call(this, data.value || data);
return false;
}
return true;
}
case 'Enter':
{
e.preventDefault();
this.dropdown.selectOption.call(this, activeListElm);
break;
}
case 'Backspace':
{
if (this.settings.mode == 'mix' || this.state.editing.scope) return;
var value = this.state.inputText.trim();
if (value == "" || value.charCodeAt(0) == 8203) {
if (this.settings.backspace === true) this.removeTags();else if (this.settings.backspace == 'edit') setTimeout(this.editTag.bind(this), 0);
}
}
}
},
onMouseOver: function onMouseOver(e) {
var ddItem = e.target.closest(this.settings.classNames.dropdownItemSelector); // event delegation check
ddItem && this.dropdown.highlightOption.call(this, ddItem);
},
onMouseLeave: function onMouseLeave(e) {
// de-highlight any previously highlighted option
this.dropdown.highlightOption.call(this);
},
onClick: function onClick(e) {
var _this4 = this;
if (e.button != 0 || e.target == this.DOM.dropdown) return; // allow only mouse left-clicks
var listItemElm = e.target.closest(this.settings.classNames.dropdownItemSelector); // temporary set the "actions" state to indicate to the main "blur" event it shouldn't run
this.state.actions.selectOption = true;
setTimeout(function () {
return _this4.state.actions.selectOption = false;
}, 50);
this.settings.hooks.suggestionClick(e, {
tagify: this,
suggestionElm: listItemElm
}).then(function () {
if (listItemElm) _this4.dropdown.selectOption.call(_this4, listItemElm);else _this4.dropdown.hide.call(_this4);
}).catch(function (err) {
return err;
});
},
onScroll: function onScroll(e) {
var elm = e.target,
pos = elm.scrollTop / (elm.scrollHeight - elm.parentNode.clientHeight) * 100;
this.trigger("dropdown:scroll", {
percentage: Math.round(pos)
});
}
}
},
/**
* mark the currently active suggestion option
* @param {Object} elm option DOM node
* @param {Boolean} adjustScroll when navigation with keyboard arrows (up/down), aut-scroll to always show the highlighted element
*/
highlightOption: function highlightOption(elm, adjustScroll) {
var className = this.settings.classNames.dropdownItemActive,
itemData; // focus casues a bug in Firefox with the placeholder been shown on the input element
// if( this.settings.dropdown.position != 'manual' )
// elm.focus();
if (this.state.ddItemElm) {
this.state.ddItemElm.classList.remove(className);
this.state.ddItemElm.removeAttribute("aria-selected");
}
if (!elm) {
this.state.ddItemData = null;
this.state.ddItemElm = null;
this.input.autocomplete.suggest.call(this);
return;
}
itemData = this.suggestedListItems[this.getNodeIndex(elm)];
this.state.ddItemData = itemData;
this.state.ddItemElm = elm; // this.DOM.dropdown.querySelectorAll("." + this.settings.classNames.dropdownItemActive).forEach(activeElm => activeElm.classList.remove(className));
elm.classList.add(className);
elm.setAttribute("aria-selected", true);
if (adjustScroll) elm.parentNode.scrollTop = elm.clientHeight + elm.offsetTop - elm.parentNode.clientHeight; // Try to autocomplete the typed value with the currently highlighted dropdown item
if (this.settings.autoComplete) {
this.input.autocomplete.suggest.call(this, itemData);
this.dropdown.position.call(this); // suggestions might alter the height of the tagify wrapper because of unkown suggested term length that could drop to the next line
}
},
/**
* Create a tag from the currently active suggestion option
* @param {Object} elm DOM node to select
*/
selectOption: function selectOption(elm) {
var _this5 = this;
var _this$settings$dropdo = this.settings.dropdown,
clearOnSelect = _this$settings$dropdo.clearOnSelect,
closeOnSelect = _this$settings$dropdo.closeOnSelect;
if (!elm) {
this.addTags(this.state.inputText, true);
closeOnSelect && this.dropdown.hide.call(this);
return;
} // if in edit-mode, do not continue but instead replace the tag's text.
// the scenario is that "addTags" was called from a dropdown suggested option selected while editing
var tagifySuggestionIdx = elm.getAttribute('tagifySuggestionIdx'),
tagData = this.suggestedListItems[+tagifySuggestionIdx];
this.trigger("dropdown:select", {
data: tagData,
elm: elm
}); // above event must be triggered, regardless of anything else which might go wrong
if (!tagifySuggestionIdx || !tagData) {
this.dropdown.hide.call(this);
return;
}
if (this.state.editing) this.onEditTagDone(null, extend({
__isValid: true
}, tagData)); // Tagify instances should re-focus to the input element once an option was selected, to allow continuous typing
else {
this[this.settings.mode == 'mix' ? "addMixTags" : "addTags"]([tagData], clearOnSelect);
} // todo: consider not doing this on mix-mode
setTimeout(function () {
_this5.DOM.input.focus();
_this5.toggleFocusClass(true);
});
if (closeOnSelect) {
return this.dropdown.hide.call(this);
}
this.dropdown.refilter.call(this);
},
selectAll: function selectAll() {
// having suggestedListItems with items messes with "normalizeTags" when wanting
// to add all tags
this.suggestedListItems.length = 0;
this.dropdown.hide.call(this); // some whitelist items might have already been added as tags so when addings all of them,
// skip adding already-added ones, so best to use "filterListItems" method over "settings.whitelist"
this.addTags(this.dropdown.filterListItems.call(this, ''), true);
return this;
},
/**
* returns an HTML string of the suggestions' list items
* @param {String} value string to filter the whitelist by
* @param {Object} options "exact" - for exact complete match
* @return {Array} list of filtered whitelist items according to the settings provided and current value
*/
filterListItems: function filterListItems(value, options) {
var _this6 = this;
var _s = this.settings,
_sd = _s.dropdown,
options = options || {},
list = [],
whitelist = _s.whitelist,
suggestionsCount = _sd.maxItems || Infinity,
searchKeys = _sd.searchKeys,
whitelistItem,
valueIsInWhitelist,
searchBy,
isDuplicate,
niddle,
i = 0;
if (!value || !searchKeys.length) {
return (_s.duplicates ? whitelist : whitelist.filter(function (item) {
return !_this6.isTagDuplicate(isObject(item) ? item.value : item);
}) // don't include tags which have already been added.
).slice(0, suggestionsCount); // respect "maxItems" dropdown setting
}
niddle = _sd.caseSensitive ? "" + value : ("" + value).toLowerCase();
function stringHasAll(s, query) {
return query.toLowerCase().split(' ').every(function (q) {
return s.includes(q.toLowerCase());
});
}
for (; i < whitelist.length; i++) {
whitelistItem = whitelist[i] instanceof Object ? whitelist[i] : {
value: whitelist[i]
}; //normalize value as an Object
if (_sd.fuzzySearch && !options.exact) {
searchBy = searchKeys.reduce(function (values, k) {
return values + " " + (whitelistItem[k] || "");
}, "").toLowerCase();
if (_sd.accentedSearch) {
searchBy = unaccent(searchBy);
niddle = unaccent(niddle);
}
valueIsInWhitelist = stringHasAll(searchBy, niddle);
} else {
valueIsInWhitelist = searchKeys.some(function (k) {
var v = '' + (whitelistItem[k] || ''); // if key exists, cast to type String
if (_sd.accentedSearch) {
v = unaccent(v);
niddle = unaccent(niddle);
}
if (!_sd.caseSensitive) v = v.toLowerCase();
return options.exact ? v == niddle : v.indexOf(niddle) == 0;
});
}
isDuplicate = !_s.duplicates && this.isTagDuplicate(isObject(whitelistItem) ? whitelistItem.value : whitelistItem); // match for the value within each "whitelist" item
if (valueIsInWhitelist && !isDuplicate && suggestionsCount--) list.push(whitelistItem);
if (suggestionsCount == 0) break;
}
return list;
},
/**
* Creates the dropdown items' HTML
* @param {Array} list [Array of Objects]
* @return {String}
*/
createListHTML: function createListHTML(optionsArr) {
var _this7 = this;
return extend([], optionsArr).map(function (suggestion, idx) {
if (typeof suggestion == 'string' || typeof suggestion == 'number') suggestion = {
value: suggestion
};
var mapValueTo = _this7.settings.dropdown.mapValueTo,
value = mapValueTo ? typeof mapValueTo == 'function' ? mapValueTo(suggestion) : suggestion[mapValueTo] || suggestion.value : suggestion.value;
suggestion.value = value && typeof value == 'string' ? escapeHTML(value) : value;
var tagHTMLString = _this7.settings.templates.dropdownItem.call(_this7, suggestion); // make sure the sugestion index is present as attribute, to match the data when one is selected
tagHTMLString = tagHTMLString.replace(/\s*tagifySuggestionIdx=(["'])(.*?)\1/gmi, '') // remove the "tagifySuggestionIdx" attribute if for some reason was there
.replace('>', " tagifySuggestionIdx=\"".concat(idx, "\">")); // add "tagifySuggestionIdx"
return tagHTMLString;
}).join("");
}
};
var DEFAULTS = {
delimiters: ",",
// [RegEx] split tags by any of these delimiters ("null" to cancel) Example: ",| |."
pattern: null,
// RegEx pattern to validate input by. Ex: /[1-9]/
tagTextProp: 'value',
// tag data Object property which will be displayed as the tag's text
maxTags: Infinity,
// Maximum number of tags
callbacks: {},
// Exposed callbacks object to be triggered on certain events
addTagOnBlur: true,
// Flag - automatically adds the text which was inputed as a tag when blur event happens
duplicates: false,
// Flag - allow tuplicate tags
whitelist: [],
// Array of tags to suggest as the user types (can be used along with "enforceWhitelist" setting)
blacklist: [],
// A list of non-allowed tags
enforceWhitelist: false,
// Flag - Only allow tags allowed in whitelist
keepInvalidTags: false,
// Flag - if true, do not remove tags which did not pass validation
mixTagsAllowedAfter: /,|\.|\:|\s/,
// RegEx - Define conditions in which mix-tags content allows a tag to be added after
mixTagsInterpolator: ['[[', ']]'],
// Interpolation for mix mode. Everything between this will becmoe a tag
backspace: true,
// false / true / "edit"
skipInvalid: false,
// If `true`, do not add invalid, temporary, tags before automatically removing them
editTags: {
clicks: 2,
// clicks to enter "edit-mode": 1 for single click. any other value is considered as double-click
keepInvalid: true // keeps invalid edits as-is until `esc` is pressed while in focus
},
// 1 or 2 clicks to edit a tag. false/null for not allowing editing
transformTag: function transformTag() {},
// Takes a tag input string as argument and returns a transformed value
trim: true,
// whether or not the value provided should be trimmed, before being added as a tag
mixMode: {
insertAfterTag: "\xA0" // String/Node to inject after a tag has been added (see #588)
},
autoComplete: {
enabled: true,
// Tries to suggest the input's value while typing (match from whitelist) by adding the rest of term as grayed-out text
rightKey: false // If `true`, when Right key is pressed, use the suggested value to create a tag, else just auto-completes the input. in mixed-mode this is set to "true"
},
classNames: {
namespace: 'tagify',
mixMode: 'tagify--mix',
selectMode: 'tagify--select',
input: 'tagify__input',
focus: 'tagify--focus',
tag: 'tagify__tag',
tagNoAnimation: 'tagify--noAnim',
tagInvalid: 'tagify--invalid',
tagNotAllowed: 'tagify--notAllowed',
inputInvalid: 'tagify__input--invalid',
tagX: 'tagify__tag__removeBtn',
tagText: 'tagify__tag-text',
dropdown: 'tagify__dropdown',
dropdownWrapper: 'tagify__dropdown__wrapper',
dropdownItem: 'tagify__dropdown__item',
dropdownItemActive: 'tagify__dropdown__item--active',
dropdownInital: 'tagify__dropdown--initial',
scopeLoading: 'tagify--loading',
tagLoading: 'tagify__tag--loading',
tagEditing: 'tagify__tag--editable',
tagFlash: 'tagify__tag--flash',
tagHide: 'tagify__tag--hide',
hasMaxTags: 'tagify--hasMaxTags',
hasNoTags: 'tagify--noTags',
empty: 'tagify--empty'
},
dropdown: {
classname: '',
enabled: 2,
// minimum input characters needs to be typed for the suggestions dropdown to show
maxItems: 10,
searchKeys: ["value", "searchBy"],
fuzzySearch: true,
caseSensitive: false,
accentedSearch: true,
highlightFirst: false,
// highlights first-matched item in the list
closeOnSelect: true,
// closes the dropdown after selecting an item, if `enabled:0` (which means always show dropdown)
clearOnSelect: true,
// after selecting a suggetion, should the typed text input remain or be cleared
position: 'all',
// 'manual' / 'text' / 'all'
appendTarget: null // defaults to document.body one DOM has been loaded
},
hooks: {
beforeRemoveTag: function beforeRemoveTag() {
return Promise.resolve();
},
suggestionClick: function suggestionClick() {
return Promise.resolve();
}
}
};
var templates = {
/**
*
* @param {DOM Object} input Original input DOm element
* @param {Object} settings Tagify instance settings Object
*/
wrapper: function wrapper(input, _s) {
return "<tags class=\"".concat(_s.classNames.namespace, " ").concat(_s.mode ? "".concat(_s.classNames[_s.mode + "Mode"]) : "", " ").concat(input.className, "\"\n ").concat(_s.readonly ? 'readonly' : '', "\n ").concat(_s.required ? 'required' : '', "\n tabIndex=\"-1\">\n <span ").concat(!_s.readonly || _s.mode != 'mix' ? 'contenteditable' : '', " data-placeholder=\"").concat(_s.placeholder || '​', "\" aria-placeholder=\"").concat(_s.placeholder || '', "\"\n class=\"").concat(_s.classNames.input, "\"\n role=\"textbox\"\n aria-autocomplete=\"both\"\n aria-multiline=\"").concat(_s.mode == 'mix' ? true : false, "\"></span>\n </tags>");
},
tag: function tag(tagData) {
return "<tag title=\"".concat(tagData.title || tagData.value, "\"\n contenteditable='false'\n spellcheck='false'\n tabIndex=\"-1\"\n class=\"").concat(this.settings.classNames.tag, " ").concat(tagData.class ? tagData.class : "", "\"\n ").concat(this.getAttributes(tagData), ">\n <x title='' class=\"").concat(this.settings.classNames.tagX, "\" role='button' aria-label='remove tag'></x>\n <div>\n <span class=\"").concat(this.settings.classNames.tagText, "\">").concat(tagData[this.settings.tagTextProp] || tagData.value, "</span>\n </div>\n </tag>");
},
dropdown: function dropdown(settings) {
var _sd = settings.dropdown,
isManual = _sd.position == 'manual',
className = "".concat(settings.classNames.dropdown);
return "<div class=\"".concat(isManual ? "" : className, " ").concat(_sd.classname, "\" role=\"listbox\" aria-labelledby=\"dropdown\">\n <div class=\"").concat(settings.classNames.dropdownWrapper, "\"></div>\n </div>");
},
dropdownItem: function dropdownItem(item) {
return "<div ".concat(this.getAttributes(item), "\n class='").concat(this.settings.classNames.dropdownItem, " ").concat(item.class ? item.class : "", "'\n tabindex=\"0\"\n role=\"option\">").concat(item.value, "</div>");
},
dropdownItemNoMatch: null
};
function EventDispatcher(instance) {
// Create a DOM EventTarget object
var target = document.createTextNode('');
function addRemove(op, events, cb) {
if (cb) events.split(/\s+/g).forEach(function (name) {
return target[op + 'EventListener'].call(target, name, cb);
});
} // Pass EventTarget interface calls to DOM EventTarget object
return {
off: function off(events, cb) {
addRemove('remove', events, cb);
return this;
},
on: function on(events, cb) {
if (cb && typeof cb == 'function') addRemove('add', events, cb);
return this;
},
trigger: function trigger(eventName, data) {
var e;
if (!eventName) return;
if (instance.settings.isJQueryPlugin) {
if (eventName == 'remove') eventName = 'removeTag'; // issue #222
jQuery(instance.DOM.originalInput).triggerHandler(eventName, [data]);
} else {
try {
var eventData = extend({}, _typeof(data) === 'object' ? data : {
value: data
});
eventData.tagify = this; // TODO: move the below to the "extend" function
if (data instanceof Object) for (var prop in data) {
if (data[prop] instanceof HTMLElement) eventData[prop] = data[prop];
}
e = new CustomEvent(eventName, {
"detail": eventData
});
} catch (err) {
console.warn(err);
}
target.dispatchEvent(e);
}
}
};
}
function triggerChangeEvent() {
if (this.settings.mixMode.integrated) return;
var inputElm = this.DOM.originalInput,
changed = this.state.lastOriginalValueReported !== inputElm.value,
event = new CustomEvent("change", {
bubbles: true
}); // must use "CustomEvent" and not "Event" to support IE
if (!changed) return; // must apply this BEFORE triggering the simulated event
this.state.lastOriginalValueReported = inputElm.value; // React hack: https://github.com/facebook/react/issues/11488
event.simulated = true;
if (inputElm._valueTracker) inputElm._valueTracker.setValue(Math.random());
inputElm.dispatchEvent(event); // also trigger a Tagify event
this.trigger("change", this.state.lastOriginalValueReported); // React, for some reason, clears the input's value after "dispatchEvent" is fired
inputElm.value = this.state.lastOriginalValueReported;
}
var events = {
// bind custom events which were passed in the settings
customBinding: function customBinding() {
var _this2 = this;