-
Notifications
You must be signed in to change notification settings - Fork 440
/
Copy pathtagify.js
1621 lines (1293 loc) · 56.2 KB
/
tagify.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
import { sameStr, removeCollectionProp, omit, isObject, parseHTML, removeTextChildNodes, escapeHTML, extend, getUID } from './parts/helpers'
import _dropdown, { initDropdown } from './parts/dropdown'
import DEFAULTS from './parts/defaults'
import templates from './parts/templates'
import EventDispatcher from './parts/EventDispatcher'
import events, { triggerChangeEvent } from './parts/events'
/**
* @constructor
* @param {Object} input DOM element
* @param {Object} settings settings object
*/
function Tagify( input, settings ){
if( !input ){
console.warn('Tagify: ', 'input element not found', input)
return this
}
if( input.previousElementSibling && input.previousElementSibling.classList.contains('tagify') ){
console.warn('Tagify: ', 'input element is already Tagified', input)
return this
}
extend(this, EventDispatcher(this))
this.isFirefox = typeof InstallTrigger !== 'undefined'
this.isIE = window.document.documentMode; // https://developer.mozilla.org/en-US/docs/Web/API/Document/compatMode#Browser_compatibility
this.applySettings(input, settings||{})
this.state = {
inputText: '',
editing : false,
actions : {}, // UI actions for state-locking
mixMode : {},
dropdown: {},
flaggedTags: {} // in mix-mode, when a string is detetced as potential tag, and the user has chocen to close the suggestions dropdown, keep the record of the tasg here
}
this.value = [] // tags' data
// events' callbacks references will be stores here, so events could be unbinded
this.listeners = {}
this.DOM = {} // Store all relevant DOM elements in an Object
this.build(input)
initDropdown.call(this)
this.getCSSVars()
this.loadOriginalValues()
this.events.customBinding.call(this);
this.events.binding.call(this)
input.autofocus && this.DOM.input.focus()
}
Tagify.prototype = {
_dropdown,
TEXTS : {
empty : "empty",
exceed : "number of tags exceeded",
pattern : "pattern mismatch",
duplicate : "already exists",
notAllowed : "not allowed"
},
customEventsList : ['change', 'add', 'remove', 'invalid', 'input', 'click', 'keydown', 'focus', 'blur', 'edit:input', 'edit:beforeUpdate', 'edit:updated', 'edit:start', 'edit:keydown', 'dropdown:show', 'dropdown:hide', 'dropdown:select', 'dropdown:updated', 'dropdown:noMatch', 'dropdown:scroll'],
dataProps: ['__isValid', '__removed', '__originalData', '__originalHTML', '__tagId'], // internal-uasge props
trim(text){
return this.settings.trim && text && typeof text == "string" ? text.trim() : text
},
// expose this handy utility function
parseHTML,
templates,
parseTemplate(template, data){
template = this.settings.templates[template] || template;
return this.parseHTML( template.apply(this, data) )
},
set whitelist( arr ){
this.settings.whitelist = arr && Array.isArray(arr) ? arr : []
},
get whitelist(){
return this.settings.whitelist
},
applySettings( input, settings ){
DEFAULTS.templates = this.templates
var _s = this.settings = extend({}, DEFAULTS, settings)
_s.disabled = input.hasAttribute('disabled')
_s.readonly = input.hasAttribute('readonly') // if "readonly" do not include an "input" element inside the Tags component
_s.placeholder = input.getAttribute('placeholder') || _s.placeholder || ""
_s.required = input.hasAttribute('required')
for( let name in _s.classNames )
Object.defineProperty(_s.classNames, name + "Selector" , {
get(){ return "."+this[name].split(" ").join(".") }
})
if( this.isIE )
_s.autoComplete = false; // IE goes crazy if this isn't false
["whitelist", "blacklist"].forEach(name => {
var attrVal = input.getAttribute('data-' + name)
if( attrVal ){
attrVal = attrVal.split(_s.delimiters)
if( attrVal instanceof Array )
_s[name] = attrVal
}
})
// backward-compatibility for old version of "autoComplete" setting:
if( "autoComplete" in settings && !isObject(settings.autoComplete) ){
_s.autoComplete = DEFAULTS.autoComplete
_s.autoComplete.enabled = settings.autoComplete
}
if( _s.mode == 'mix' ){
_s.autoComplete.rightKey = true
_s.delimiters = settings.delimiters || null // default dlimiters in mix-mode must be NULL
// needed for "filterListItems". This assumes the user might have forgotten to manually
// define the same term in "dropdown.searchKeys" as defined in "tagTextProp" setting, so
// by automatically adding it, tagify is "helping" out, guessing the intesntions of the developer.
if( _s.tagTextProp && !_s.dropdown.searchKeys.includes(_s.tagTextProp) )
_s.dropdown.searchKeys.push(_s.tagTextProp)
}
if( input.pattern )
try { _s.pattern = new RegExp(input.pattern) }
catch(e){}
// Convert the "delimiters" setting into a REGEX object
if( this.settings.delimiters ){
try { _s.delimiters = new RegExp(this.settings.delimiters, "g") }
catch(e){}
}
// make sure the dropdown will be shown on "focus" and not only after typing something (in "select" mode)
if( _s.mode == 'select' )
_s.dropdown.enabled = 0
_s.dropdown.appendTarget = settings.dropdown && settings.dropdown.appendTarget
? settings.dropdown.appendTarget
: document.body
},
/**
* Returns a string of HTML element attributes
* @param {Object} data [Tag data]
*/
getAttributes( data ){
var attrs = this.getCustomAttributes(data), s = '', k;
for( k in attrs )
s += " " + k + (data[k] !== undefined ? `="${data[k]}"` : "");
return s;
},
/**
* Returns an object of attributes to be used for the templates
*/
getCustomAttributes( data ){
// only items which are objects have properties which can be used as attributes
if( !isObject(data) )
return '';
var output = {}, propName, k;
for( propName in data ){
if( propName.slice(0,2) != '__' && propName != 'class' && data.hasOwnProperty(propName) && data[propName] !== undefined )
output[propName] = data[propName]
}
return output
},
setStateSelection(){
var selection = window.getSelection()
// save last selection place to be able to inject anything from outside to that specific place
var sel = {
anchorOffset: selection.anchorOffset,
anchorNode : selection.anchorNode,
range : selection.getRangeAt && selection.rangeCount && selection.getRangeAt(0)
}
this.state.selection = sel
return sel
},
/**
* Get the caret position relative to the viewport
* https://stackoverflow.com/q/58985076/104380
*
* @returns {object} left, top distance in pixels
*/
getCaretGlobalPosition(){
const sel = document.getSelection()
if( sel.rangeCount ){
const r = sel.getRangeAt(0)
const node = r.startContainer
const offset = r.startOffset
let rect, r2;
if (offset > 0) {
r2 = document.createRange()
r2.setStart(node, offset - 1)
r2.setEnd(node, offset)
rect = r2.getBoundingClientRect()
return {left:rect.right, top:rect.top, bottom:rect.bottom}
}
if( node.getBoundingClientRect )
return node.getBoundingClientRect()
}
return {left:-9999, top:-9999}
},
/**
* Get specific CSS variables which are relevant to this script and parse them as needed.
* The result is saved on the instance in "this.CSSVars"
*/
getCSSVars(){
var compStyle = getComputedStyle(this.DOM.scope, null)
const getProp = name => compStyle.getPropertyValue('--'+name)
function seprateUnitFromValue(a){
if( !a ) return {}
a = a.trim().split(' ')[0]
var unit = a.split(/\d+/g).filter(n=>n).pop().trim(),
value = +a.split(unit).filter(n=>n)[0].trim()
return {value, unit}
}
this.CSSVars = {
tagHideTransition: (({value, unit}) => unit=='s' ? value * 1000 : value)(seprateUnitFromValue(getProp('tag-hide-transition')))
}
},
/**
* builds the HTML of this component
* @param {Object} input [DOM element which would be "transformed" into "Tags"]
*/
build( input ){
var DOM = this.DOM;
if( this.settings.mixMode.integrated ){
DOM.originalInput = null;
DOM.scope = input;
DOM.input = input;
}
else {
DOM.originalInput = input
DOM.scope = this.parseTemplate('wrapper', [input, this.settings])
DOM.input = DOM.scope.querySelector(this.settings.classNames.inputSelector)
input.parentNode.insertBefore(DOM.scope, input)
}
},
/**
* revert any changes made by this component
*/
destroy(){
this.DOM.scope.parentNode.removeChild(this.DOM.scope)
this.dropdown.hide(true)
clearTimeout(this.dropdownHide__bindEventsTimeout)
},
/**
* if the original input had any values, add them as tags
*/
loadOriginalValues( value ){
var lastChild,
_s = this.settings;
if( value === undefined )
value = _s.mixMode.integrated ? this.DOM.input.textContent : this.DOM.originalInput.value
this.removeAllTags({ withoutChangeEvent:true })
if( value ){
if( _s.mode == 'mix' ){
this.parseMixTags(value.trim())
lastChild = this.DOM.input.lastChild;
if( !lastChild || lastChild.tagName != 'BR' )
this.DOM.input.insertAdjacentHTML('beforeend', '<br>')
}
else{
try{
if( JSON.parse(value) instanceof Array )
value = JSON.parse(value)
}
catch(err){}
this.addTags(value).forEach(tag => tag && tag.classList.add(_s.classNames.tagNoAnimation))
}
}
else
this.postUpdate()
this.state.lastOriginalValueReported = _s.mixMode.integrated ? '' : this.DOM.originalInput.value
this.state.loadedOriginalValues = true
},
cloneEvent(e){
var clonedEvent = {}
for( var v in e )
clonedEvent[v] = e[v]
return clonedEvent
},
/**
* Toogle global loading state on/off
* Useful when fetching async whitelist while user is typing
* @param {Boolean} isLoading
*/
loading( isLoading ){
this.state.isLoading = isLoading
// IE11 doesn't support toggle with second parameter
this.DOM.scope.classList[isLoading?"add":"remove"](this.settings.classNames.scopeLoading)
return this
},
/**
* Toogle specieif tag loading state on/off
* @param {Boolean} isLoading
*/
tagLoading( tagElm, isLoading ){
if( tagElm )
// IE11 doesn't support toggle with second parameter
tagElm.classList[isLoading?"add":"remove"](this.settings.classNames.tagLoading)
return this
},
/**
* Toggles class on the main tagify container ("scope")
* @param {String} className
* @param {Boolean} force
*/
toggleClass( className, force ){
if( typeof className == 'string' )
this.DOM.scope.classList.toggle(className, force)
},
toggleFocusClass( force ){
this.toggleClass(this.settings.classNames.focus, !!force)
},
triggerChangeEvent,
events,
fixFirefoxLastTagNoCaret(){
return // seems to be fixed in newer version of FF, so retiring below code (for now)
var inputElm = this.DOM.input
if( this.isFirefox && inputElm.childNodes.length && inputElm.lastChild.nodeType == 1 ){
inputElm.appendChild(document.createTextNode("\u200b"))
this.setRangeAtStartEnd(true)
return true
}
},
placeCaretAfterNode( node ){
if( !node || !node.parentNode ) return
var nextSibling = node.nextSibling,
sel = window.getSelection(),
range = sel.getRangeAt(0);
if (sel.rangeCount) {
range.setStartBefore(nextSibling || node);
range.setEndBefore(nextSibling || node);
sel.removeAllRanges();
sel.addRange(range);
}
},
insertAfterTag( tagElm, newNode ){
newNode = newNode || this.settings.mixMode.insertAfterTag;
if( !tagElm || !tagElm.parentNode || !newNode ) return
newNode = typeof newNode == 'string'
? document.createTextNode(newNode)
: newNode
tagElm.parentNode.insertBefore(newNode, tagElm.nextSibling)
return newNode
},
/**
* Enters a tag into "edit" mode
* @param {Node} tagElm the tag element to edit. if nothing specified, use last last
*/
editTag( tagElm, opts ){
tagElm = tagElm || this.getLastTag()
opts = opts || {}
this.dropdown.hide()
var _s = this.settings;
function getEditableElm(){
return tagElm.querySelector(_s.classNames.tagTextSelector)
}
var editableElm = getEditableElm(),
tagIdx = this.getNodeIndex(tagElm),
tagData = this.tagData(tagElm),
_CB = this.events.callbacks,
that = this,
isValid = true,
delayed_onEditTagBlur = function(){
setTimeout(() => _CB.onEditTagBlur.call(that, getEditableElm()))
}
if( !editableElm ){
console.warn('Cannot find element in Tag template: .', _s.classNames.tagTextSelector);
return;
}
if( tagData instanceof Object && "editable" in tagData && !tagData.editable )
return
editableElm.setAttribute('contenteditable', true)
tagElm.classList.add( _s.classNames.tagEditing )
// cache the original data, on the DOM node, before any modification ocurs, for possible revert
this.tagData(tagElm, {
__originalData: extend({}, tagData),
__originalHTML: tagElm.innerHTML
})
editableElm.addEventListener('focus', _CB.onEditTagFocus.bind(this, tagElm))
editableElm.addEventListener('blur', delayed_onEditTagBlur)
editableElm.addEventListener('input', _CB.onEditTagInput.bind(this, editableElm))
editableElm.addEventListener('keydown', e => _CB.onEditTagkeydown.call(this, e, tagElm))
editableElm.focus()
this.setRangeAtStartEnd(false, editableElm)
if( !opts.skipValidation )
isValid = this.editTagToggleValidity(tagElm)
editableElm.originalIsValid = isValid
this.trigger("edit:start", { tag:tagElm, index:tagIdx, data:tagData, isValid })
return this
},
/**
* If a tag is invalid, for any reason, set its class to as "not allowed" (see defaults file)
* @param {Node} tagElm required
* @param {Object} tagData optional
* @returns true if valid, a string (reason) if not
*/
editTagToggleValidity( tagElm, tagData ){
var tagData = tagData || this.tagData(tagElm),
isValid;
if( !tagData ){
console.warn("tag has no data: ", tagElm, tagData)
return;
}
isValid = !("__isValid" in tagData) || tagData.__isValid === true
if( !isValid ){
this.removeTagsFromValue(tagElm)
}
this.update()
//this.validateTag(tagData);
tagElm.classList.toggle(this.settings.classNames.tagNotAllowed, !isValid)
return tagData.__isValid
},
onEditTagDone(tagElm, tagData){
tagElm = tagElm || this.state.editing.scope
tagData = tagData || {}
var eventData = {
tag : tagElm,
index : this.getNodeIndex(tagElm),
previousData: this.tagData(tagElm),
data : tagData
}
this.trigger("edit:beforeUpdate", eventData, {cloneData:false})
this.state.editing = false;
delete tagData.__originalData
delete tagData.__originalHTML
if( tagElm && tagData[this.settings.tagTextProp] ){
tagElm = this.replaceTag(tagElm, tagData)
this.editTagToggleValidity(tagElm, tagData)
if( this.settings.a11y.focusableTags )
tagElm.focus()
}
else if(tagElm)
this.removeTags(tagElm)
this.trigger("edit:updated", eventData)
this.dropdown.hide()
// check if any of the current tags which might have been marked as "duplicate" should be now un-marked
if( this.settings.keepInvalidTags )
this.reCheckInvalidTags()
},
/**
* Replaces an exisitng tag with a new one. Used for updating a tag's data
* @param {Object} tagElm [DOM node to replace]
* @param {Object} tagData [data to create new tag from]
*/
replaceTag(tagElm, tagData){
if( !tagData || !tagData.value )
tagData = tagElm.__tagifyTagData
// if tag is invalid, make the according changes in the newly created element
if( tagData.__isValid && tagData.__isValid != true )
extend( tagData, this.getInvalidTagAttrs(tagData, tagData.__isValid) )
var newTagElm = this.createTagElem(tagData)
// update DOM
tagElm.parentNode.replaceChild(newTagElm, tagElm)
this.updateValueByDOMTags()
return newTagElm
},
/**
* update "value" (Array of Objects) by traversing all valid tags
*/
updateValueByDOMTags(){
this.value.length = 0;
[].forEach.call(this.getTagElms(), node => {
if( node.classList.contains(this.settings.classNames.tagNotAllowed.split(' ')[0]) ) return
this.value.push( this.tagData(node) )
})
this.update()
},
/** https://stackoverflow.com/a/59156872/104380
* @param {Boolean} start indicating where to place it (start or end of the node)
* @param {Object} node DOM node to place the caret at
*/
setRangeAtStartEnd( start, node ){
start = typeof start == 'number' ? start : !!start
node = node || this.DOM.input;
node = node.lastChild || node;
var sel = document.getSelection()
try{
if( sel.rangeCount >= 1 ){
['Start', 'End'].forEach(pos =>
sel.getRangeAt(0)["set" + pos](node, start ? start : node.length)
)
}
} catch(err){
console.warn("Tagify: ", err)
}
},
/**
* injects nodes/text at caret position, which is saved on the "state" when "blur" event gets triggered
* @param {Node} injectedNode [the node to inject at the caret position]
* @param {Object} selection [optional range Object. must have "anchorNode" & "anchorOffset"]
*/
injectAtCaret( injectedNode, range ){
range = range || this.state.selection.range
if( !range ) return;
if( typeof injectedNode == 'string' )
injectedNode = document.createTextNode(injectedNode);
range.deleteContents()
range.insertNode(injectedNode)
this.setRangeAtStartEnd(false, injectedNode)
this.updateValueByDOMTags() // updates internal "this.value"
this.update() // updates original input/textarea
return this
},
/**
* input bridge for accessing & setting
* @type {Object}
*/
input : {
set( s = '', updateDOM = true ){
var hideDropdown = this.settings.dropdown.closeOnSelect
this.state.inputText = s
if( updateDOM )
this.DOM.input.innerHTML = escapeHTML(""+s);
if( !s && hideDropdown )
this.dropdown.hide.bind(this)
this.input.autocomplete.suggest.call(this);
this.input.validate.call(this);
},
/**
* Marks the tagify's input as "invalid" if the value did not pass "validateTag()"
*/
validate(){
var isValid = !this.state.inputText || this.validateTag({value:this.state.inputText}) === true;
this.DOM.input.classList.toggle(this.settings.classNames.inputInvalid, !isValid)
return isValid
},
// remove any child DOM elements that aren't of type TEXT (like <br>)
normalize( node ){
var clone = node || this.DOM.input, //.cloneNode(true),
v = [];
// when a text was pasted in FF, the "this.DOM.input" element will have <br> but no newline symbols (\n), and this will
// result in tags not being properly created if one wishes to create a separate tag per newline.
clone.childNodes.forEach(n => n.nodeType==3 && v.push(n.nodeValue))
v = v.join("\n")
try{
// "delimiters" might be of a non-regex value, where this will fail ("Tags With Properties" example in demo page):
v = v.replace(/(?:\r\n|\r|\n)/g, this.settings.delimiters.source.charAt(0))
}
catch(err){}
v = v.replace(/\s/g, ' ') // replace NBSPs with spaces characters
if( this.settings.trim )
v = v.replace(/^\s+/, '') // trimLeft
return v
},
/**
* suggest the rest of the input's value (via CSS "::after" using "content:attr(...)")
* @param {String} s [description]
*/
autocomplete : {
suggest( data ){
if( !this.settings.autoComplete.enabled ) return;
data = data || {}
if( typeof data == 'string' )
data = {value:data}
var suggestedText = data.value ? ''+data.value : '',
suggestionStart = suggestedText.substr(0, this.state.inputText.length).toLowerCase(),
suggestionTrimmed = suggestedText.substring(this.state.inputText.length);
if( !suggestedText || !this.state.inputText || suggestionStart != this.state.inputText.toLowerCase() ){
this.DOM.input.removeAttribute("data-suggest");
delete this.state.inputSuggestion
}
else{
this.DOM.input.setAttribute("data-suggest", suggestionTrimmed);
this.state.inputSuggestion = data
}
},
/**
* sets the suggested text as the input's value & cleanup the suggestion autocomplete.
* @param {String} s [text]
*/
set( s ){
var dataSuggest = this.DOM.input.getAttribute('data-suggest'),
suggestion = s || (dataSuggest ? this.state.inputText + dataSuggest : null);
if( suggestion ){
if( this.settings.mode == 'mix' ){
this.replaceTextWithNode( document.createTextNode(this.state.tag.prefix + suggestion) )
}
else{
this.input.set.call(this, suggestion);
this.setRangeAtStartEnd()
}
this.input.autocomplete.suggest.call(this);
this.dropdown.hide();
return true;
}
return false;
}
}
},
/**
* returns the index of the the tagData within the "this.value" array collection.
* since values should be unique, it is suffice to only search by "value" property
* @param {Object} tagData
*/
getTagIdx( tagData ){
return this.value.findIndex(item => item.__tagId == (tagData||{}).__tagId )
},
getNodeIndex( node ){
var index = 0;
if( node )
while( (node = node.previousElementSibling) )
index++;
return index;
},
getTagElms( ...classess ){
var classname = '.' + [...this.settings.classNames.tag.split(' '), ...classess].join('.')
return [].slice.call(this.DOM.scope.querySelectorAll(classname)) // convert nodeList to Array - https://stackoverflow.com/a/3199627/104380
},
/**
* gets the last non-readonly, not-in-the-proccess-of-removal tag
*/
getLastTag(){
var lastTag = this.DOM.scope.querySelectorAll(`${this.settings.classNames.tagSelector}:not(.${this.settings.classNames.tagHide}):not([readonly])`);
return lastTag[lastTag.length - 1];
},
/** Setter/Getter
* Each tag DOM node contains a custom property called "__tagifyTagData" which hosts its data
* @param {Node} tagElm
* @param {Object} data
*/
tagData(tagElm, data, override){
if( !tagElm ){
console.warn("tag elment doesn't exist",tagElm, data)
return data
}
if( data )
tagElm.__tagifyTagData = override
? data
: extend({}, tagElm.__tagifyTagData || {}, data)
return tagElm.__tagifyTagData
},
/**
* Searches if any tag with a certain value already exis
* @param {String/Object} v [text value / tag data object]
* @return {Boolean}
*/
isTagDuplicate( value, caseSensitive ){
var duplications,
_s = this.settings;
// duplications are irrelevant for this scenario
if( _s.mode == 'select' )
return false
duplications = this.value.reduce((acc, item) =>
sameStr( this.trim(""+value), item.value, caseSensitive || _s.dropdown.caseSensitive )
? acc+1
: acc
, 0)
return duplications
},
getTagIndexByValue( value ){
var indices = [];
this.getTagElms().forEach((tagElm, i) => {
if( sameStr( this.trim(tagElm.textContent), value, this.settings.dropdown.caseSensitive ) )
indices.push(i)
})
return indices;
},
getTagElmByValue( value ){
var tagIdx = this.getTagIndexByValue(value)[0]
return this.getTagElms()[tagIdx]
},
/**
* Temporarily marks a tag element (by value or Node argument)
* @param {Object} tagElm [a specific "tag" element to compare to the other tag elements siblings]
*/
flashTag( tagElm ){
if( tagElm ){
tagElm.classList.add(this.settings.classNames.tagFlash)
setTimeout(() => { tagElm.classList.remove(this.settings.classNames.tagFlash) }, 100)
}
},
/**
* checks if text is in the blacklist
*/
isTagBlacklisted( v ){
v = this.trim(v.toLowerCase());
return this.settings.blacklist.filter(x => (""+x).toLowerCase() == v).length;
},
/**
* checks if text is in the whitelist
*/
isTagWhitelisted( v ){
return !!this.getWhitelistItem(v)
/*
return this.settings.whitelist.some(item =>
typeof v == 'string'
? sameStr(this.trim(v), (item.value || item))
: sameStr(JSON.stringify(item), JSON.stringify(v))
)
*/
},
/**
* Returns the first whitelist item matched, by value (if match found)
* @param {String} value [text to match by]
*/
getWhitelistItem( value, prop, whitelist ){
var result,
prop = prop || 'value',
_s = this.settings,
whitelist = whitelist || _s.whitelist;
whitelist.some(_wi => {
var _wiv = typeof _wi == 'string' ? _wi : (_wi[prop] || _wi.value),
isSameStr = sameStr(_wiv, value, _s.dropdown.caseSensitive, _s.trim)
if( isSameStr ){
result = typeof _wi == 'string' ? {value:_wi} : _wi
return true
}
})
// first iterate the whitelist, try find maches by "value" and if that fails
// and a "tagTextProp" is set to be other than "value", try that also
if( !result && prop == 'value' && _s.tagTextProp != 'value' ){
// if found, adds the first which matches
result = this.getWhitelistItem(value, _s.tagTextProp, whitelist)
}
return result
},
/**
* validate a tag object BEFORE the actual tag will be created & appeneded
* @param {String} s
* @param {String} uid [unique ID, to not inclue own tag when cheking for duplicates]
* @return {Boolean/String} ["true" if validation has passed, String for a fail]
*/
validateTag( tagData ){
var _s = this.settings,
// when validating a tag in edit-mode, need to take "tagTextProp" into consideration
prop = "value" in tagData ? "value" : _s.tagTextProp,
v = this.trim(tagData[prop] + "");
// check for definitive empty value
if( !(tagData[prop]+"").trim() )
return this.TEXTS.empty;
// check if pattern should be used and if so, use it to test the value
if( _s.pattern && _s.pattern instanceof RegExp && !(_s.pattern.test(v)) )
return this.TEXTS.pattern;
// if duplicates are not allowed and there is a duplicate
if( !_s.duplicates && this.isTagDuplicate(v, this.state.editing) )
return this.TEXTS.duplicate;
if( this.isTagBlacklisted(v) || (_s.enforceWhitelist && !this.isTagWhitelisted(v)) )
return this.TEXTS.notAllowed;
if( _s.validate )
return _s.validate(tagData)
return true
},
getInvalidTagAttrs(tagData, validation){
return {
"aria-invalid" : true,
"class": `${tagData.class || ''} ${this.settings.classNames.tagNotAllowed}`.trim(),
"title": validation
}
},
hasMaxTags(){
return this.value.length >= this.settings.maxTags
? this.TEXTS.exceed
: false
},
setReadonly( toggle, attrribute ){
var _s = this.settings
document.activeElement.blur() // exists possible edit-mode
_s[attrribute || 'readonly'] = toggle
this.DOM.scope[(toggle ? 'set' : 'remove') + 'Attribute'](attrribute || 'readonly', true)
if( _s.mode == 'mix' ){
this.DOM.input.contentEditable = !toggle
}
},
setDisabled( isDisabled ){
this.setReadonly(isDisabled, 'disabled')
},
/**
* pre-proccess the tagsItems, which can be a complex tagsItems like an Array of Objects or a string comprised of multiple words
* so each item should be iterated on and a tag created for.
* @return {Array} [Array of Objects]
*/
normalizeTags( tagsItems ){
var {whitelist, delimiters, mode, tagTextProp, enforceWhitelist} = this.settings,
whitelistMatches = [],
whitelistWithProps = whitelist ? whitelist[0] instanceof Object : false,
// checks if this is a "collection", meanning an Array of Objects
isArray = tagsItems instanceof Array,
mapStringToCollection = s => (s+"").split(delimiters).filter(n => n).map(v => ({ [tagTextProp]:this.trim(v), value:this.trim(v) }))
if( typeof tagsItems == 'number' )
tagsItems = tagsItems.toString()
// if the argument is a "simple" String, ex: "aaa, bbb, ccc"
if( typeof tagsItems == 'string' ){
if( !tagsItems.trim() ) return [];
// go over each tag and add it (if there were multiple ones)
tagsItems = mapStringToCollection(tagsItems)
}
// is is an Array of Strings, convert to an Array of Objects
else if( isArray ){
// flatten the 2D array
tagsItems = [].concat(...tagsItems.map(item => item.value
? item // mapStringToCollection(item.value).map(newItem => ({...item,...newItem}))
: mapStringToCollection(item)
))
}
// search if the tag exists in the whitelist as an Object (has props),
// to be able to use its properties
if( whitelistWithProps ){
tagsItems.forEach(item => {
var whitelistMatchesValues = whitelistMatches.map(a=>a.value)
// if suggestions are shown, they are already filtered, so it's easier to use them,
// because the whitelist might also include items which have already been added
var filteredList = this.dropdown.filterListItems.call(this, item[tagTextProp], { exact:true })
// also filter out items which have already been matches in previous iterations
.filter(filteredItem => !whitelistMatchesValues.includes(filteredItem.value))
// get the best match out of list of possible matches.
// if there was a single item in the filtered list, use that one
var matchObj = filteredList.length > 1
? this.getWhitelistItem(item[tagTextProp], tagTextProp, filteredList)
: filteredList[0]
if( matchObj && matchObj instanceof Object ){
whitelistMatches.push( matchObj ) // set the Array (with the found Object) as the new value
}
else if( mode != 'mix' ){
if( item.value == undefined )
item.value = item[tagTextProp]
whitelistMatches.push(item)
}