UNPKG

@yaireo/tagify

Version:

lightweight, efficient Tags input component in Vanilla JS / React / Angular [super customizable, tiny size & top performance]

28 lines (23 loc) 68.6 kB
/* Tagify v4.38.0 - tags input component By: Yair Even-Or <vsync.design@gmail.com> https://github.com/yairEO/tagify Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. This Software may not be rebranded and sold as a library under any other name other than "Tagify" (by owner) or as part of another library. */ var t="&#8203;";const e={isEnabled:()=>window.TAGIFY_DEBUG??!0,log(...t){this.isEnabled()&&console.log("[Tagify]:",...t)},warn(...t){this.isEnabled()&&console.warn("[Tagify]:",...t)}},s=(t,e,s,i)=>(t=""+t,e=""+e,i&&(t=t.trim(),e=e.trim()),s?t==e:t.toLowerCase()==e.toLowerCase()),i=(t,e)=>t&&Array.isArray(t)&&t.map((t=>a(t,e)));function a(t,e){var s,i={};for(s in t)e.indexOf(s)<0&&(i[s]=t[s]);return i}function n(t){return(new DOMParser).parseFromString(t.trim(),"text/html").body.firstElementChild}function o(t,e){for(e=e||"previous";t=t[e+"Sibling"];)if(3==t.nodeType)return t}function r(t){return"string"==typeof t?t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/`|'/g,"&#039;"):t}function l(t){var e=Object.prototype.toString.call(t).split(" ")[1].slice(0,-1);return t===Object(t)&&"Array"!=e&&"Function"!=e&&"RegExp"!=e&&"HTMLUnknownElement"!=e}function d(t,e,s){function i(t,e){for(var s in e)if(e.hasOwnProperty(s)){if(l(e[s])){l(t[s])?i(t[s],e[s]):t[s]=Object.assign({},e[s]);continue}if(Array.isArray(e[s])){t[s]=Object.assign([],e[s]);continue}t[s]=e[s]}}return t instanceof Object||(t={}),i(t,e),s&&i(t,s),t}function h(){const t=[],e={};for(let s of arguments)for(let i of s)l(i)?e[i.value]||(t.push(i),e[i.value]=1):t.includes(i)||t.push(i);return t}function g(t){return String.prototype.normalize?"string"==typeof t?t.normalize("NFD").replace(/[\u0300-\u036f]/g,""):void 0:t}var c=()=>/(?=.*chrome)(?=.*android)/i.test(navigator.userAgent);function p(){return([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,(t=>(t^crypto.getRandomValues(new Uint8Array(1))[0]&15>>t/4).toString(16)))}function u(t){const e=v.call(this,t),s=t?.classList?.contains(this.settings.classNames.tag);return e&&s}function m(t){return v.call(this,t)&&t?.closest(this.settings.classNames.tagSelector)}function v(t){let e=t?.closest?.(this.settings.classNames.namespaceSelector);return e===this.DOM.scope}function f(t,e){var s=window.getSelection();return e=e||(s.rangeCount?s.getRangeAt(0):null),"string"==typeof t&&(t=document.createTextNode(t)),e&&(e.deleteContents(),e.insertNode(t)),t}function T(t,s,i){return t?(s&&(t.__tagifyTagData=i?s:d({},t.__tagifyTagData||{},s)),t.__tagifyTagData):(e.warn("tag element doesn't exist",{tagElm:t,data:s}),s)}function w(t){if(t&&t.parentNode){var e=window.getSelection();if(e){var s=document.createRange();s.setStartAfter(t),s.collapse(!0),e.removeAllRanges(),e.addRange(s)}}}function b(t,e){t.forEach((t=>{if(T(t.previousSibling)||!t.previousSibling){var s=document.createTextNode("​");t.before(s),e&&w(s)}}))}var y={delimiters:",",pattern:null,tagTextProp:"value",maxTags:1/0,callbacks:{},addTagOnBlur:!0,addTagOn:["blur","tab","enter"],onChangeAfterBlur:!0,duplicates:!1,whitelist:[],blacklist:[],enforceWhitelist:!1,userInput:!0,focusable:!0,focusInputOnRemove:!0,keepInvalidTags:!1,createInvalidTags:!0,mixTagsAllowedAfter:/,|\.|\:|\s/,mixTagsInterpolator:["[[","]]"],backspace:!0,allowCaretBetweenTags:!0,skipInvalid:!1,pasteAsTags:!0,editTags:{clicks:2,keepInvalid:!0},transformTag:()=>{},trim:!0,a11y:{focusableTags:!1,inputAriaLabel:"Tags input field"},mixMode:{insertAfterTag:" "},autoComplete:{enabled:!0,rightKey:!1,tabKey:!1},classNames:{namespace:"tagify",mixMode:"tagify--mix",selectMode:"tagify--select",input:"tagify__input",focus:"tagify--focus",tagNoAnimation:"tagify--noAnim",tagInvalid:"tagify--invalid",tagNotAllowed:"tagify--notAllowed",scopeLoading:"tagify--loading",hasMaxTags:"tagify--hasMaxTags",hasNoTags:"tagify--noTags",empty:"tagify--empty",inputInvalid:"tagify__input--invalid",dropdown:"tagify__dropdown",dropdownWrapper:"tagify__dropdown__wrapper",dropdownHeader:"tagify__dropdown__header",dropdownFooter:"tagify__dropdown__footer",dropdownItem:"tagify__dropdown__item",dropdownItemActive:"tagify__dropdown__item--active",dropdownItemHidden:"tagify__dropdown__item--hidden",dropdownItemSelected:"tagify__dropdown__item--selected",dropdownInital:"tagify__dropdown--initial",tag:"tagify__tag",tagText:"tagify__tag-text",tagX:"tagify__tag__removeBtn",tagLoading:"tagify__tag--loading",tagEditing:"tagify__tag--editable",tagFlash:"tagify__tag--flash",tagHide:"tagify__tag--hide"},dropdown:{classname:"",enabled:2,maxItems:10,searchKeys:["value","searchBy"],fuzzySearch:!0,caseSensitive:!1,accentedSearch:!0,includeSelectedTags:!1,escapeHTML:!0,highlightFirst:!0,closeOnSelect:!0,clearOnSelect:!0,position:"all",appendTarget:null},hooks:{beforeRemoveTag:()=>Promise.resolve(),beforePaste:()=>Promise.resolve(),suggestionClick:()=>Promise.resolve(),beforeKeyDown:()=>Promise.resolve()}};function x(){this.dropdown={};for(let t in this._dropdown)this.dropdown[t]="function"==typeof this._dropdown[t]?this._dropdown[t].bind(this):this._dropdown[t];this.dropdown.refs(),this.DOM.dropdown.__tagify=this}var D={...{events:{binding(t=!0){var e=this.dropdown.events.callbacks,s=this.listeners.dropdown=this.listeners.dropdown||{position:this.dropdown.position.bind(this,null),onKeyDown:e.onKeyDown.bind(this),onMouseOver:e.onMouseOver.bind(this),onMouseLeave:e.onMouseLeave.bind(this),onClick:e.onClick.bind(this),onScroll:e.onScroll.bind(this)},i=t?"addEventListener":"removeEventListener";"manual"!=this.settings.dropdown.position&&(document[i]("scroll",s.position,!0),window[i]("resize",s.position),window[i]("keydown",s.onKeyDown)),this.DOM.dropdown[i]("mouseover",s.onMouseOver),this.DOM.dropdown[i]("mouseleave",s.onMouseLeave),this.DOM.dropdown[i]("mousedown",s.onClick),this.DOM.dropdown.content[i]("scroll",s.onScroll)},callbacks:{onKeyDown(t){if(this.state.hasFocus&&!this.state.composing){var s=this.settings,i=s.dropdown.includeSelectedTags,a=this.DOM.dropdown.querySelector(s.classNames.dropdownItemActiveSelector),n=this.dropdown.getSuggestionDataByNode(a),o="mix"==s.mode,r="select"==s.mode;s.hooks.beforeKeyDown(t,{tagify:this}).then((l=>{switch(t.key){case"ArrowDown":case"ArrowUp":case"Down":case"Up":t.preventDefault();var d=this.dropdown.getAllSuggestionsRefs(),h="ArrowUp"==t.key||"Up"==t.key;a&&(a=this.dropdown.getNextOrPrevOption(a,!h)),a&&a.matches(s.classNames.dropdownItemSelector)||(a=d[h?d.length-1:0]),this.dropdown.highlightOption(a,!0);break;case"PageUp":case"PageDown":{t.preventDefault();const e=this.dropdown.getAllSuggestionsRefs(),s=Math.floor(this.DOM.dropdown.content.clientHeight/e[0]?.offsetHeight)||1,i="PageUp"===t.key;if(a){const t=e.indexOf(a),n=i?Math.max(0,t-s):Math.min(e.length-1,t+s);a=e[n]}else a=e[0];this.dropdown.highlightOption(a,!0);break}case"Home":case"End":{t.preventDefault();const e=this.dropdown.getAllSuggestionsRefs();a=e["Home"===t.key?0:e.length-1],this.dropdown.highlightOption(a,!0);break}case"Escape":case"Esc":this.dropdown.hide();break;case"ArrowRight":if(this.state.actions.ArrowLeft||s.autoComplete.rightKey||s.allowCaretBetweenTags)return;case"Tab":{let e=!s.autoComplete.rightKey||!s.autoComplete.tabKey;if(!o&&!r&&a&&e&&!this.state.editing&&n){t.preventDefault();var g=this.dropdown.getMappedValue(n);return this.state.autoCompleteData=n,this.input.autocomplete.set.call(this,g),!1}return!0}case"Enter":t.preventDefault(),this.state.actions.selectOption=!0,setTimeout((()=>this.state.actions.selectOption=!1),100),s.hooks.suggestionClick(t,{tagify:this,tagData:n,suggestionElm:a}).then((()=>{if(a){var e=i?a:this.dropdown.getNextOrPrevOption(a,!h);this.dropdown.selectOption(a,t,(()=>{if(e){var t=e.getAttribute("value");e=this.dropdown.getSuggestionNodeByValue(t),this.dropdown.highlightOption(e)}}))}else this.dropdown.hide(),o||this.addTags(this.state.inputText.trim(),!0)})).catch((t=>e.warn(t)));break;case"Backspace":{if(o||this.state.editing.scope)return;const t=this.input.raw.call(this);""!=t&&8203!=t.charCodeAt(0)||(!0===s.backspace?this.removeTags():"edit"==s.backspace&&setTimeout(this.editTag.bind(this),0))}}}))}},onMouseOver(t){var e=t.target.closest(this.settings.classNames.dropdownItemSelector);this.dropdown.highlightOption(e)},onMouseLeave(t){this.dropdown.highlightOption()},onClick(t){if(0==t.button&&t.target!=this.DOM.dropdown&&t.target!=this.DOM.dropdown.content){var s=t.target.closest(this.settings.classNames.dropdownItemSelector),i=this.dropdown.getSuggestionDataByNode(s);this.state.actions.selectOption=!0,setTimeout((()=>this.state.actions.selectOption=!1),100),this.settings.hooks.suggestionClick(t,{tagify:this,tagData:i,suggestionElm:s}).then((()=>{s?this.dropdown.selectOption(s,t):this.dropdown.hide()})).catch((t=>e.warn(t)))}},onScroll(t){var e=t.target,s=e.scrollTop/(e.scrollHeight-e.parentNode.clientHeight)*100;this.trigger("dropdown:scroll",{percentage:Math.round(s)})}}},refilter(t){t=t||this.state.dropdown.query||"",this.suggestedListItems=this.dropdown.filterListItems(t),this.dropdown.fill(),this.suggestedListItems.length||this.dropdown.hide(),this.trigger("dropdown:updated",this.DOM.dropdown)},getSuggestionDataByNode(t){for(var e,s=t&&t.getAttribute("value"),i=this.suggestedListItems.length;i--;){if(l(e=this.suggestedListItems[i])&&e.value==s)return e;if(e==s)return{value:e}}},getSuggestionNodeByValue(t){return this.dropdown.getAllSuggestionsRefs().find((e=>e.getAttribute("value")===t))},getNextOrPrevOption(t,e=!0){var s=this.dropdown.getAllSuggestionsRefs(),i=s.findIndex((e=>e===t));return e?s[i+1]:s[i-1]},highlightOption(t,e){var s,i=this.settings.classNames.dropdownItemActive;if(this.state.ddItemElm&&(this.state.ddItemElm.classList.remove(i),this.state.ddItemElm.removeAttribute("aria-selected")),!t)return this.state.ddItemData=null,this.state.ddItemElm=null,void this.input.autocomplete.suggest.call(this);s=this.dropdown.getSuggestionDataByNode(t),this.state.ddItemData=s,this.state.ddItemElm=t,t.classList.add(i),t.setAttribute("aria-selected",!0),e&&(t.parentNode.scrollTop=t.clientHeight+t.offsetTop-t.parentNode.clientHeight),this.settings.autoComplete&&(this.input.autocomplete.suggest.call(this,s),this.dropdown.position())},selectOption(t,e,s){var i=this.settings,a=i.dropdown.includeSelectedTags,{clearOnSelect:n,closeOnSelect:o}=i.dropdown;if(!t)return this.addTags(this.state.inputText,!0),void(o&&this.dropdown.hide());e=e||{};var r=t.getAttribute("value"),l="noMatch"==r,h="mix"==i.mode,g=this.suggestedListItems.find((t=>(t.value??t)==r));if(this.trigger("dropdown:select",{data:g,elm:t,event:e}),g||l){if(this.state.editing){let t=this.normalizeTags([g])[0];g=i.transformTag.call(this,t)||t,this.onEditTagDone(null,d({__isValid:!0},g))}else this[h?"addMixTags":"addTags"]([g||this.input.raw.call(this)],n);(h||this.DOM.input.parentNode)&&(setTimeout((()=>{this.DOM.input.focus(),this.toggleFocusClass(!0)})),o&&setTimeout(this.dropdown.hide.bind(this)),a?s&&s():(t.addEventListener("transitionend",(()=>{this.dropdown.fillHeaderFooter(),setTimeout((()=>{t.remove(),this.dropdown.refilter(),s&&s()}),100)}),{once:!0}),t.classList.add(this.settings.classNames.dropdownItemHidden)))}else o&&setTimeout(this.dropdown.hide.bind(this))},selectAll(t){this.suggestedListItems.length=0,this.dropdown.hide(),this.dropdown.filterListItems("");var e=this.dropdown.filterListItems("");return t||(e=this.state.dropdown.suggestions),this.addTags(e,!0),this},filterListItems(t,e){var s,i,a,n,o,r=this.settings,d=r.dropdown,h=(e=e||{},[]),c=[],p=r.whitelist,u=d.maxItems>=0?d.maxItems:1/0,m=d.includeSelectedTags,v="function"==typeof d.sortby,f=d.searchKeys,T=0;if(!(t="select"==r.mode&&this.value.length&&this.value[0][r.tagTextProp]==t?"":t)||!f.length){h=m?p:p.filter((t=>!this.isTagDuplicate(l(t)?t.value:t)));var w=v?d.sortby(h,o):h.slice(0,u);return this.state.dropdown.suggestions=w,w}function b(t,e){return e.toLowerCase().split(" ").every((e=>t.includes(e.toLowerCase())))}for(o=d.caseSensitive?""+t:(""+t).toLowerCase();T<p.length;T++){let t,r;s=p[T]instanceof Object?p[T]:{value:p[T]};let u=!Object.keys(s).some((t=>f.includes(t)))?["value"]:f;d.fuzzySearch&&!e.exact?(a=u.reduce(((t,e)=>t+" "+(s[e]||"")),"").toLowerCase().trim(),d.accentedSearch&&(a=g(a),o=g(o)),t=0==a.indexOf(o),r=a===o,i=b(a,o)):(t=!0,i=u.some((t=>{var i=""+(s[t]||"");return d.accentedSearch&&(i=g(i),o=g(o)),d.caseSensitive||(i=i.toLowerCase()),r=i===o,e.exact?i===o:0==i.indexOf(o)}))),n=!d.includeSelectedTags&&this.isTagDuplicate(l(s)?s.value:s),i&&!n&&(r&&t?c.push(s):"startsWith"==d.sortby&&t?h.unshift(s):h.push(s))}this.state.dropdown.suggestions=c.concat(h);w=v?d.sortby(c.concat(h),o):c.concat(h).slice(0,u);return this.state.dropdown.suggestions=w,w},getMappedValue(t){var e=this.settings.dropdown.mapValueTo;return e?"function"==typeof e?e(t):t[e]||t.value:t.value},createListHTML(t){return d([],t).map(((t,e)=>{"string"!=typeof t&&"number"!=typeof t||(t={value:t});var s=this.dropdown.getMappedValue(t);return s="string"==typeof s&&this.settings.dropdown.escapeHTML?r(s):s,this.settings.templates.dropdownItem.apply(this,[{...t,mappedValue:s},this])})).join("")}},refs(){this.DOM.dropdown=this.parseTemplate("dropdown",[this.settings]),this.DOM.dropdown.content=this.DOM.dropdown.querySelector("[data-selector='tagify-suggestions-wrapper']")},getHeaderRef(){return this.DOM.dropdown.querySelector("[data-selector='tagify-suggestions-header']")},getFooterRef(){return this.DOM.dropdown.querySelector("[data-selector='tagify-suggestions-footer']")},getAllSuggestionsRefs(){return[...this.DOM.dropdown.content.querySelectorAll(this.settings.classNames.dropdownItemSelector)]},show(t){var e,i,a,n=this.settings,o="mix"==n.mode&&!n.enforceWhitelist,r=!n.whitelist||!n.whitelist.length,d="manual"==n.dropdown.position;if(t=void 0===t?this.state.inputText:t,!(r&&!o&&!n.templates.dropdownItemNoMatch||!1===n.dropdown.enabled||this.state.isLoading||this.settings.readonly)){if(clearTimeout(this.dropdownHide__bindEventsTimeout),this.suggestedListItems=this.dropdown.filterListItems(t),t&&!this.suggestedListItems.length&&(this.trigger("dropdown:noMatch",t),n.templates.dropdownItemNoMatch&&(a=n.templates.dropdownItemNoMatch.call(this,{value:t}))),!a){if(this.suggestedListItems.length)t&&o&&!this.state.editing.scope&&!s(this.suggestedListItems[0].value,t)&&this.suggestedListItems.unshift({value:t});else{if(!t||!o||this.state.editing.scope)return this.input.autocomplete.suggest.call(this),void this.dropdown.hide();this.suggestedListItems=[{value:t}]}i=""+(l(e=this.suggestedListItems[0])?e.value:e),n.autoComplete&&i&&0==i.indexOf(t)&&this.input.autocomplete.suggest.call(this,e)}this.dropdown.fill(a),n.dropdown.highlightFirst&&this.dropdown.highlightOption(this.DOM.dropdown.content.querySelector(n.classNames.dropdownItemSelector)),this.state.dropdown.visible||setTimeout(this.dropdown.events.binding.bind(this)),this.state.dropdown.visible=t||!0,this.state.dropdown.query=t,this.setStateSelection(),d||setTimeout((()=>{this.dropdown.position(),this.dropdown.render()})),setTimeout((()=>{this.trigger("dropdown:show",this.DOM.dropdown)}))}},hide(t){var{scope:e,dropdown:s}=this.DOM,i="manual"==this.settings.dropdown.position&&!t;if(s&&document.body.contains(s)&&!i)return window.removeEventListener("resize",this.dropdown.position),this.dropdown.events.binding.call(this,!1),e.setAttribute("aria-expanded",!1),s.parentNode.removeChild(s),setTimeout((()=>{this.state.dropdown.visible=!1}),100),this.state.dropdown.query=this.state.ddItemData=this.state.ddItemElm=this.state.selection=null,this.state.tag&&this.state.tag.value.length&&(this.state.flaggedTags[this.state.tag.baseOffset]=this.state.tag),this.trigger("dropdown:hide",s),this},toggle(t){this.dropdown[this.state.dropdown.visible&&!t?"hide":"show"]()},getAppendTarget(){var t=this.settings.dropdown;return"function"==typeof t.appendTarget?t.appendTarget():t.appendTarget},render(){var t,e,s,i=(t=this.DOM.dropdown,(s=t.cloneNode(!0)).style.cssText="position:fixed; top:-9999px; opacity:0",document.body.appendChild(s),e=s.clientHeight,s.parentNode.removeChild(s),e),a=this.settings,n=this.dropdown.getAppendTarget();return!1===a.dropdown.enabled||(this.DOM.scope.setAttribute("aria-expanded",!0),document.body.contains(this.DOM.dropdown)||(this.DOM.dropdown.classList.add(a.classNames.dropdownInital),this.dropdown.position(i),n.appendChild(this.DOM.dropdown),setTimeout((()=>this.DOM.dropdown.classList.remove(a.classNames.dropdownInital))))),this},fill(t){t="string"==typeof t?t:this.dropdown.createListHTML(t||this.suggestedListItems);var e,s=this.settings.templates.dropdownContent.call(this,t);this.DOM.dropdown.content.innerHTML=(e=s)?e.replace(/\>[\r\n ]+\</g,"><").split(/>\s+</).join("><").trim():""},fillHeaderFooter(){var t=this.dropdown.filterListItems(this.state.dropdown.query),e=this.parseTemplate("dropdownHeader",[t]),s=this.parseTemplate("dropdownFooter",[t]),i=this.dropdown.getHeaderRef(),a=this.dropdown.getFooterRef();e&&i?.parentNode.replaceChild(e,i),s&&a?.parentNode.replaceChild(s,a)},position(t){var e=this.settings.dropdown,s=this.dropdown.getAppendTarget();if("manual"!=e.position&&s){var i,a,n,o,r,l,d,h,g,c,p=this.DOM.dropdown,u=e.RTL,m=s===document.body,v=s===this.DOM.scope,f=m?window.pageYOffset:s.scrollTop,T=document.fullscreenElement||document.webkitFullscreenElement||document.documentElement,w=T.clientHeight,b=Math.max(T.clientWidth||0,window.innerWidth||0),y=b>480?e.position:"all",x=this.DOM["input"==y?"input":"scope"];if(t=t||p.clientHeight,this.state.dropdown.visible){if("text"==y?(n=(i=function(){const t=document.getSelection();if(t.rangeCount){const e=t.getRangeAt(0),s=e.startContainer,i=e.startOffset;let a,n;if(i>0)return n=document.createRange(),n.setStart(s,i-1),n.setEnd(s,i),a=n.getBoundingClientRect(),{left:a.right,top:a.top,bottom:a.bottom};if(s.getBoundingClientRect)return s.getBoundingClientRect()}return{left:-9999,top:-9999}}()).bottom,a=i.top,o=i.left,r="auto"):(l=function(t){var e=0,s=0;for(t=t.parentNode;t&&t!=T;)e+=t.offsetTop||0,s+=t.offsetLeft||0,t=t.parentNode;return{top:e,left:s}}(s),i=x.getBoundingClientRect(),a=v?-1:i.top-l.top,n=(v?i.height:i.bottom-l.top)-1,o=v?-1:i.left-l.left,r=i.width+"px"),!m){let t=function(){for(var t=0,s=e.appendTarget.parentNode;s;)t+=s.scrollTop||0,s=s.parentNode;return t}();a+=t,n+=t}a=Math.floor(a),n=Math.ceil(n),h=b-o<120,g=((d=e.placeAbove??w-i.bottom<t)?a:n)+f,c=o+(u&&i.width||0)+window.pageXOffset,c="text"==y&&h?"right: 0;":`left: ${c}px;`,p.style.cssText=`${c} top: ${g}px; min-width: ${r}; max-width: ${r}`,p.setAttribute("placement",d?"top":"bottom"),p.setAttribute("position",y)}}}};const O="@yaireo/tagify/";var I={empty:"empty",exceed:"number of tags exceeded",pattern:"pattern mismatch",duplicate:"already exists",notAllowed:"not allowed"},M={wrapper(e,s){return`<tags class="${s.classNames.namespace} ${s.mode?`${s.classNames[s.mode+"Mode"]}`:""} ${e.className}"\n ${s.readonly?"readonly":""}\n ${s.disabled?"disabled":""}\n ${s.required?"required":""}\n ${"select"===s.mode?"spellcheck='false'":""}\n tabIndex="-1">\n ${this.settings.templates.input.call(this)}\n ${t}\n </tags>`},input(){var e=this.settings,s=e.placeholder||t;return`<span ${!e.readonly&&e.userInput?"contenteditable":""} data-can-editable tabIndex="0" data-placeholder="${s}" aria-placeholder="${e.placeholder||""}"\n class="${e.classNames.input}"\n role="textbox"\n autocapitalize="false"\n autocorrect="off"\n aria-label="${e.a11y.inputAriaLabel}"\n aria-autocomplete="both"\n aria-multiline="${"mix"==e.mode}"></span>`},tag(t,{settings:e}){return`<tag title="${t.title||t.value}"\n contenteditable='false'\n tabIndex="${e.a11y.focusableTags?0:-1}"\n class="${e.classNames.tag} ${t.class||""}"\n ${this.getAttributes(t)}>\n <x title='' tabIndex="${e.a11y.focusableTags?0:-1}" class="${e.classNames.tagX}" role='button' aria-label='remove tag'></x>\n <div>\n <span ${"select"===e.mode&&e.userInput?"contenteditable='true'":""} autocapitalize="false" autocorrect="off" spellcheck='false' class="${e.classNames.tagText}">${t[e.tagTextProp]||t.value}</span>\n </div>\n </tag>`},dropdown(t){var e=t.dropdown;return`<div class="${"manual"==e.position?"":t.classNames.dropdown} ${e.classname}" role="listbox" aria-labelledby="dropdown" dir="${e.RTL?"rtl":""}">\n <div data-selector='tagify-suggestions-wrapper' class="${t.classNames.dropdownWrapper}"></div>\n </div>`},dropdownContent(t){var e=this.settings.templates,s=this.state.dropdown.suggestions;return`\n ${e.dropdownHeader.call(this,s)}\n ${t}\n ${e.dropdownFooter.call(this,s)}\n `},dropdownItem(t){return`<div ${this.getAttributes(t)}\n class='${this.settings.classNames.dropdownItem} ${this.isTagDuplicate(t.value)?this.settings.classNames.dropdownItemSelected:""} ${t.class||""}'\n tabindex="0"\n role="option">${t.mappedValue||t.value}</div>`},dropdownHeader(t){return`<header data-selector='tagify-suggestions-header' class="${this.settings.classNames.dropdownHeader}"></header>`},dropdownFooter(t){var e=t.length-this.settings.dropdown.maxItems;return e>0?`<footer data-selector='tagify-suggestions-footer' class="${this.settings.classNames.dropdownFooter}">\n ${e} more items. Refine your search.\n </footer>`:""},dropdownItemNoMatch:null};var E={customBinding(){this.customEventsList.forEach((t=>{this.on(t,this.settings.callbacks[t])}))},binding(t=!0){var e,s=this.settings,i=this.events.callbacks,a=t?"addEventListener":"removeEventListener";if(!(this.state.mainEvents&&t||s.disabled||s.readonly)){for(var n in this.state.mainEvents=t,t&&!this.listeners.main&&(this.events.bindGlobal.call(this),this.settings.isJQueryPlugin&&jQuery(this.DOM.originalInput).on("tagify.removeAllTags",this.removeAllTags.bind(this))),e=this.listeners.main=this.listeners.main||{keydown:["input",i.onKeydown.bind(this)],click:["scope",i.onClickScope.bind(this)],dblclick:"select"!=s.mode&&["scope",i.onDoubleClickScope.bind(this)],paste:["input",i.onPaste.bind(this)],drop:["input",i.onDrop.bind(this)],compositionstart:["input",i.onCompositionStart.bind(this)],compositionend:["input",i.onCompositionEnd.bind(this)]})e[n]&&this.DOM[e[n][0]][a](n,e[n][1]);var o=this.listeners.main.inputMutationObserver||new MutationObserver(i.onInputDOMChange.bind(this));o.disconnect(),"mix"==s.mode&&o.observe(this.DOM.input,{childList:!0}),this.events.bindOriginaInputListener.call(this),t&&(this.listeners.main=void 0)}},bindOriginaInputListener(t){const e=(t||0)+500;this.listeners.main&&(clearInterval(this.listeners.main.originalInputValueObserverInterval),this.listeners.main.originalInputValueObserverInterval=setInterval(this.events.callbacks.observeOriginalInputValue.bind(this),e))},bindGlobal(t){var e,s=this.events.callbacks,i=t?"removeEventListener":"addEventListener";if(this.listeners&&(t||!this.listeners.global)){for(e of(this.listeners.global=this.listeners.global||[{type:this.isIE?"keydown":"input",target:this.DOM.input,cb:s[this.isIE?"onInputIE":"onInput"].bind(this)},{type:"keydown",target:window,cb:s.onWindowKeyDown.bind(this)},{type:"focusin",target:this.DOM.scope,cb:s.onFocusBlur.bind(this)},{type:"focusout",target:this.DOM.scope,cb:s.onFocusBlur.bind(this)},{type:"click",target:document,cb:s.onClickAnywhere.bind(this),useCapture:!0}],this.listeners.global))e.target[i](e.type,e.cb,!!e.useCapture);t&&(this.listeners.global=void 0)}},unbindGlobal(){this.events.bindGlobal.call(this,!0)},callbacks:{onFocusBlur(t){var e=this.settings,s=m.call(this,t.relatedTarget),i=u.call(this,t.target),a=t.target.matches(e.classNames.tagXSelector),n="focusin"==t.type,o="focusout"==t.type;a&&"mix"!=e.mode&&e.focusInputOnRemove&&this.DOM.input.focus(),s&&n&&!i&&!a&&this.toggleFocusClass(this.state.hasFocus=+new Date);var r=t.target?this.trim(this.DOM.input.textContent):"",l=this.value?.[0]?.[e.tagTextProp],d=e.dropdown.enabled>=0,h={relatedTarget:t.relatedTarget},g=this.state.actions.selectOption&&(d||!e.dropdown.closeOnSelect),c=this.state.actions.addNew&&d;if(o){if("mix"!=e.mode)t.relatedTarget&&this.DOM.dropdown?.contains(t.relatedTarget)||this.repositionScopeInput("reset",{focus:!1});if(t.relatedTarget===this.DOM.scope)return this.dropdown.hide(),void this.DOM.input.focus();this.postUpdate(),e.onChangeAfterBlur&&this.triggerChangeEvent()}if(!(g||c||a))if(this.state.hasFocus=!(!n&&!s)&&+new Date,this.toggleFocusClass(this.state.hasFocus),"mix"!=e.mode){if(n){if(!e.focusable)return;var p=0===e.dropdown.enabled&&!this.state.dropdown.visible,v=this.DOM.scope.querySelector(this.settings.classNames.tagTextSelector);return this.trigger("focus",h),void(p&&!i&&(this.dropdown.show(this.value.length?"":void 0),"select"===e.mode&&this.setRangeAtStartEnd(!1,v)))}if(o){if(this.trigger("blur",h),this.loading(!1),"select"==e.mode){if(this.value.length){let t=this.getTagElms()[0];r=this.trim(t.textContent)}l===r&&(r="")}r&&!this.state.actions.selectOption&&e.addTagOnBlur&&e.addTagOn.includes("blur")&&this.addTags(r,!0)}s||(this.DOM.input.removeAttribute("style"),this.dropdown.hide())}else n?this.trigger("focus",h):o&&(this.trigger("blur",h),this.loading(!1),this.dropdown.hide(),this.state.dropdown.visible=void 0,this.setStateSelection())},onCompositionStart(t){this.state.composing=!0},onCompositionEnd(t){this.state.composing=!1},onWindowKeyDown(t){var e,s=this.settings,i=document.activeElement,a=m.call(this,i)&&this.DOM.scope.contains(i),n=i===this.DOM.input,o=a&&i.hasAttribute("readonly"),r=this.DOM.scope.querySelector(this.settings.classNames.tagTextSelector),l=this.state.dropdown.visible;if(("Tab"===t.key&&l||this.state.hasFocus||a&&!o)&&!n){e=i.nextElementSibling;var d=t.target.matches(s.classNames.tagXSelector);switch(t.key){case"Backspace":s.readonly||this.state.editing||(this.removeTags(i),(e||this.DOM.input).focus());break;case"Enter":if(d)return void this.removeTags(t.target.parentNode);s.a11y.focusableTags&&u.call(this,i)&&setTimeout(this.editTag.bind(this),0,i);break;case"ArrowDown":this.state.dropdown.visible||"mix"==s.mode||this.dropdown.show();break;case"Tab":r?.focus()}}},onKeydown(t){var e=this.settings;if(!this.state.composing&&e.userInput){"select"==e.mode&&e.enforceWhitelist&&this.value.length&&"Tab"!=t.key&&t.preventDefault();var s=this.trim(t.target.textContent);this.trigger("keydown",{event:t}),e.hooks.beforeKeyDown(t,{tagify:this}).then((i=>{if("mix"==e.mode){switch(t.key){case"Left":case"ArrowLeft":this.state.actions.ArrowLeft=!0;break;case"Delete":case"Backspace":if(this.state.editing)return;var a=document.getSelection(),n="Delete"==t.key&&a.anchorOffset==(a.anchorNode.length||0),r=a.anchorNode.previousSibling,l=1==a.anchorNode.nodeType||!a.anchorOffset&&r&&1==r.nodeType&&a.anchorNode.previousSibling;!function(t){var e=document.createElement("div");t.replace(/\&#?[0-9a-z]+;/gi,(function(t){return e.innerHTML=t,e.innerText}))}(this.DOM.input.innerHTML);var d,h,g,p=this.getTagElms(),u=1===a.anchorNode.length&&a.anchorNode.nodeValue==String.fromCharCode(8203);if("edit"==e.backspace&&l)return d=1==a.anchorNode.nodeType?null:a.anchorNode.previousElementSibling,setTimeout(this.editTag.bind(this),0,d),void t.preventDefault();if(c()&&l instanceof Element)return g=o(l),l.hasAttribute("readonly")||l.remove(),this.DOM.input.focus(),void setTimeout((()=>{w(g),this.DOM.input.click()}));if("BR"==a.anchorNode.nodeName)return;if((n||l)&&1==a.anchorNode.nodeType?h=0==a.anchorOffset?n?p[0]:null:p[Math.min(p.length,a.anchorOffset)-1]:n?h=a.anchorNode.nextElementSibling:l instanceof Element&&(h=l),3==a.anchorNode.nodeType&&!a.anchorNode.nodeValue&&a.anchorNode.previousElementSibling&&t.preventDefault(),(l||n)&&!e.backspace)return void t.preventDefault();if("Range"!=a.type&&!a.anchorOffset&&a.anchorNode==this.DOM.input&&"Delete"!=t.key)return void t.preventDefault();if("Range"!=a.type&&h&&h.hasAttribute("readonly"))return void w(o(h));"Delete"==t.key&&u&&T(a.anchorNode.nextSibling)&&this.removeTags(a.anchorNode.nextSibling);break;case"Enter":{if(t.preventDefault(),this.state.tag)return;let e=window.getSelection();e.getRangeAt(0).insertNode(document.createElement("br")),e.collapseToEnd()}}return!0}var m="manual"==e.dropdown.position;switch(t.key){case"Backspace":var v=this.getTagElmBeforeInput();"select"==e.mode&&e.enforceWhitelist&&this.value.length?v&&this.removeTags(v):this.state.dropdown.visible&&"manual"!=e.dropdown.position||""!=t.target.textContent&&8203!=s.charCodeAt(0)||(!0===e.backspace?v&&this.removeTags(v):"edit"==e.backspace&&v&&setTimeout((()=>this.editTag(v)),0));break;case"Esc":case"Escape":if(this.state.dropdown.visible)return;t.target.blur();break;case"Down":case"ArrowDown":this.state.dropdown.visible||this.dropdown.show();break;case"ArrowLeft":this.repositionScopeInput("left")&&t.preventDefault();break;case"ArrowRight":{if(this.repositionScopeInput("right")){t.preventDefault();break}let s=this.state.inputSuggestion||this.state.ddItemData;if(s&&e.autoComplete.rightKey)return void this.addTags([s],!0);break}case"Tab":if(!e.addTagOn.includes(t.key.toLowerCase()))break;case"Enter":if(this.state.dropdown.visible&&!m)return;var f=this.state.autoCompleteData||s;if(!f&&"Tab"===t.key)return!0;t.preventDefault(),setTimeout((()=>{this.state.dropdown.visible&&!m||this.state.actions.selectOption||!e.addTagOn.includes(t.key.toLowerCase())||(this.addTags([f],!0),this.state.autoCompleteData=null)}))}})).catch((t=>t))}},onInput(t){this.postUpdate();var e=this.settings;if("mix"==e.mode)return this.events.callbacks.onMixTagsInput.call(this,t);var s=this.input.normalize.call(this,void 0,{trim:!1}),i=s.length>=e.dropdown.enabled,a={value:s,inputElm:this.DOM.input},n=this.validateTag({value:s});"select"==e.mode&&this.toggleScopeValidation(n),a.isValid=n,this.state.inputText!=s&&(this.input.set.call(this,s,!1),-1!=s.search(e.delimiters)?this.addTags(s)&&this.input.set.call(this):e.dropdown.enabled>=0&&this.dropdown[i?"show":"hide"](s),this.trigger("input",a))},onMixTagsInput(t){var e,s,i,a,n,o,r,l,h=this.settings,g=this.value.length,p=this.getTagElms(),u=document.createDocumentFragment(),m=(l=window.getSelection()).rangeCount?l.getRangeAt(0):null,v=[].map.call(p,(t=>T(t).value));if("deleteContentBackward"==t.inputType&&c()&&this.events.callbacks.onKeydown.call(this,{target:t.target,key:"Backspace"}),b(this.getTagElms()),this.value.slice().forEach((t=>{t.readonly&&!v.includes(t.value)&&u.appendChild(this.createTagElem(t))})),u.childNodes.length&&m&&(m.insertNode(u),this.setRangeAtStartEnd(!1,u.lastChild)),p.length!=g)return this.value=[].map.call(this.getTagElms(),(t=>T(t))),void this.update({withoutChangeEvent:!0});if(this.hasMaxTags())return!0;if(window.getSelection&&(l=window.getSelection()).rangeCount>0&&3==l.anchorNode.nodeType){if((m=l.getRangeAt(0).cloneRange()).collapse(!0),m.setStart(l.focusNode,0),i=(e=m.toString().slice(0,m.endOffset)).split(h.pattern).length-1,(s=e.match(h.pattern))&&(a=e.slice(e.lastIndexOf(s[s.length-1]))),a){if(this.state.actions.ArrowLeft=!1,this.state.tag={prefix:a.match(h.pattern)[0],value:a.replace(h.pattern,"")},this.state.tag.baseOffset=l.baseOffset-this.state.tag.value.length,r=this.state.tag.value.match(h.delimiters))return this.state.tag.value=this.state.tag.value.replace(h.delimiters,""),this.state.tag.delimiters=r[0],this.addTags(this.state.tag.value,h.dropdown.clearOnSelect),void this.dropdown.hide();n=this.state.tag.value.length>=h.dropdown.enabled;try{o=(o=this.state.flaggedTags[this.state.tag.baseOffset]).prefix==this.state.tag.prefix&&o.value[0]==this.state.tag.value[0],this.state.flaggedTags[this.state.tag.baseOffset]&&!this.state.tag.value&&delete this.state.flaggedTags[this.state.tag.baseOffset]}catch(t){}(o||i<this.state.mixMode.matchedPatternCount)&&(n=!1)}else this.state.flaggedTags={};this.state.mixMode.matchedPatternCount=i}setTimeout((()=>{this.update({withoutChangeEvent:!0}),this.trigger("input",d({},this.state.tag,{textContent:this.DOM.input.textContent})),this.state.tag&&this.dropdown[n?"show":"hide"](this.state.tag.value)}),10)},onInputIE(t){var e=this;setTimeout((function(){e.events.callbacks.onInput.call(e,t)}))},observeOriginalInputValue(){this.DOM.originalInput.parentNode||this.destroy(),this.DOM.originalInput.value!=this.DOM.originalInput.tagifyValue&&this.loadOriginalValues()},onClickAnywhere(t){if(t.target!=this.DOM.scope&&!this.DOM.scope.contains(t.target)){this.toggleFocusClass(!1),this.state.hasFocus=!1;let e=t.target.closest(this.settings.classNames.dropdownSelector);e?.__tagify!=this&&this.dropdown.hide()}},onClickScope(t){var e=this.settings,s=t.target.closest("."+e.classNames.tag);t.target,this.DOM.scope;var i=+new Date-this.state.hasFocus;if(!t.target.matches(e.classNames.tagXSelector))return s&&!this.state.editing?(this.trigger("click",{tag:s,index:this.getNodeIndex(s),data:T(s),event:t}),void(1!==e.editTags&&1!==e.editTags.clicks&&"select"!=e.mode||this.events.callbacks.onDoubleClickScope.call(this,t))):void(t.target==this.DOM.input&&("mix"==e.mode&&this.fixFirefoxLastTagNoCaret(),i>500||!e.focusable)?this.state.dropdown.visible?this.dropdown.hide():0===e.dropdown.enabled&&"mix"!=e.mode&&this.dropdown.show(this.value.length?"":void 0):"select"!=e.mode||0!==e.dropdown.enabled||this.state.dropdown.visible||(this.events.callbacks.onDoubleClickScope.call(this,{...t,target:this.getTagElms()[0]}),!e.userInput&&this.dropdown.show()));this.removeTags(t.target.parentNode)},onPaste(t){t.preventDefault();var e,s,i,a=this.settings;if(!a.userInput)return!1;a.readonly||(s=t.clipboardData||window.clipboardData,i=s.getData("Text"),a.hooks.beforePaste(t,{tagify:this,pastedText:i,clipboardData:s}).then((a=>{if(void 0===a&&(a=i),a)if("mix"==this.settings.mode){if(this.settings.pasteAsTags){const t=this.convertPastedTextToMixTags(a),e=this.parseMixTags(t,{skipDOM:!0}),s=e.__tagifyTagsData||[];this.injectAtCaret(e,window.getSelection().getRangeAt(0)),s.forEach((t=>this.value.push(t)));const i=this.getTagElms().slice(-s.length);i.forEach(((t,e)=>T(t,s[e]))),this.update(),b(i)}else this.injectAtCaret(a,window.getSelection().getRangeAt(0));this.events.callbacks.onMixTagsInput.call(this,t)}else this.injectAtCaret(a,window.getSelection().getRangeAt(0)),this.settings.pasteAsTags?e=this.addTags(this.state.inputText+a,!0):(this.state.inputText=a,this.dropdown.show(a));this.trigger("paste",{event:t,pastedText:i,clipboardData:s,tagsElems:e})})).catch((t=>t)))},onDrop(t){t.preventDefault()},onEditTagInput(t,e){var s=t.closest("."+this.settings.classNames.tag),i=this.getNodeIndex(s),a=T(s),n=this.input.normalize.call(this,t),o={[this.settings.tagTextProp]:n,__tagId:a.__tagId},r=this.validateTag(o);this.editTagChangeDetected(d(a,o))||!0!==t.originalIsValid||(r=!0),s.classList.toggle(this.settings.classNames.tagInvalid,!0!==r),a.__isValid=r,s.title=!0===r?a.title||a.value:r,n.length>=this.settings.dropdown.enabled&&(this.state.editing&&(this.state.editing.value=n),this.dropdown.show(n)),this.trigger("edit:input",{tag:s,index:i,data:d({},this.value[i],{newValue:n}),event:e})},onEditTagPaste(t,e){var s=(e.clipboardData||window.clipboardData).getData("Text");e.preventDefault();var i=f(s);this.setRangeAtStartEnd(!1,i)},onEditTagClick(t,e){this.events.callbacks.onClickScope.call(this,e)},onEditTagFocus(t){this.state.editing={scope:t,input:t.querySelector("[contenteditable]")}},onEditTagBlur(t,e){var s=u.call(this,e.relatedTarget);if("select"==this.settings.mode&&s&&e.relatedTarget.contains(e.target))this.dropdown.hide();else if(this.state.editing&&(this.state.hasFocus||this.toggleFocusClass(),this.DOM.scope.contains(document.activeElement)||this.trigger("blur",{}),this.DOM.scope.contains(t))){var i,a,n=this.settings,o=t.closest("."+n.classNames.tag),r=T(o),l=this.input.normalize.call(this,t),h={[n.tagTextProp]:l,__tagId:r.__tagId},g=r.__originalData,c=this.editTagChangeDetected(d(r,h)),p=this.validateTag(h);if(l)if(c){if(i=this.hasMaxTags(),a=d({},g,{[n.tagTextProp]:this.trim(l),__isValid:p}),n.transformTag.call(this,a,g),!0!==(p=(!i||!0===g.__isValid)&&this.validateTag(a))){if(this.trigger("invalid",{data:a,tag:o,message:p}),n.editTags.keepInvalid)return;n.keepInvalidTags?a.__isValid=p:a=g}else n.keepInvalidTags&&(delete a.title,delete a["aria-invalid"],delete a.class);this.onEditTagDone(o,a)}else this.onEditTagDone(o,g);else this.onEditTagDone(o)}},onEditTagkeydown(t,e){if(!this.state.composing)switch(this.trigger("edit:keydown",{event:t}),t.key){case"Esc":case"Escape":this.state.editing=!1,!!e.__tagifyTagData.__originalData.value?e.parentNode.replaceChild(e.__tagifyTagData.__originalHTML,e):e.remove();break;case"Enter":case"Tab":t.preventDefault();setTimeout((()=>t.target.blur()),0)}},onDoubleClickScope(t){var e=t.target.closest("."+this.settings.classNames.tag);if(e){var s,i,a=T(e),n=this.settings;!1!==a?.editable&&(s=e.classList.contains(this.settings.classNames.tagEditing),i=e.hasAttribute("readonly"),n.readonly||s||i||!this.settings.editTags||!n.userInput||(this.events.callbacks.onEditTagFocus.call(this,e),this.editTag(e)),this.toggleFocusClass(!0),"select"!=n.mode&&this.trigger("dblclick",{tag:e,index:this.getNodeIndex(e),data:T(e)}))}},onInputDOMChange(t){var e=this.DOM.input.lastChild;t.forEach((t=>{t.addedNodes.forEach((t=>{if("<div><br></div>"==t.outerHTML)t.replaceWith(document.createElement("br"));else if(1==t.nodeType&&t.querySelector(this.settings.classNames.tagSelector)){let e=document.createTextNode("");3==t.childNodes[0].nodeType&&"BR"!=t.previousSibling.nodeName&&(e=document.createTextNode("\n")),t.replaceWith(e,...[...t.childNodes].slice(0,-1)),w(e)}else if(u.call(this,t))if(3!=t.previousSibling?.nodeType||t.previousSibling.textContent||t.previousSibling.remove(),t.previousSibling&&"BR"==t.previousSibling.nodeName){t.previousSibling.replaceWith("\n​");let e=t.nextSibling,s="";for(;e;)s+=e.textContent,e=e.nextSibling;s.trim()&&w(t.previousSibling)}else t.previousSibling&&!T(t.previousSibling)||t.before("​")})),t.removedNodes.forEach((t=>{t&&"BR"==t.nodeName&&u.call(this,e)&&(this.removeTags(e),this.fixFirefoxLastTagNoCaret())}))})),e&&""==e.nodeValue&&e.remove(),e&&"BR"==e.nodeName||this.DOM.input.appendChild(document.createElement("br"))}}};function N(t,s){if(!t){e.warn("input element not found",t);const s=new Proxy(this,{get:()=>()=>s});return s}if(t.__tagify)return e.warn("input element is already Tagified - Same instance is returned.",t),t.__tagify;var i;d(this,function(t){var s=document.createTextNode(""),i={};function a(t,e,i){i&&e.split(/\s+/g).forEach((e=>s[t+"EventListener"].call(s,e,i)))}return{removeAllCustomListeners(){Object.entries(i).forEach((([t,e])=>{e.forEach((e=>a("remove",t,e)))})),i={}},off(t,e){return t&&(e?a("remove",t,e):t.split(/\s+/g).forEach((t=>{i[t]?.forEach((e=>a("remove",t,e))),delete i[t]}))),this},on(t,e){return e&&"function"==typeof e&&(t.split(/\s+/g).forEach((t=>{Array.isArray(i[t])?i[t].push(e):i[t]=[e]})),a("add",t,e)),this},trigger(i,a,n){var o;if(n=n||{cloneData:!0},i)if(t.settings.isJQueryPlugin)"remove"==i&&(i="removeTag"),jQuery(t.DOM.originalInput).triggerHandler(i,[a]);else{try{var r="object"==typeof a?a:{value:a};if((r=n.cloneData?d({},r):r).tagify=this,a.event&&(r.event=this.cloneEvent(a.event)),a instanceof Object)for(var l in a)a[l]instanceof HTMLElement&&(r[l]=a[l]);o=new CustomEvent(i,{detail:r})}catch(t){e.warn(t)}s.dispatchEvent(o)}}}}(this)),this.isFirefox=/firefox|fxios/i.test(navigator.userAgent)&&!/seamonkey/i.test(navigator.userAgent),this.isIE=window.document.documentMode,s=s||{},this.getPersistedData=(i=s.id,t=>{if(!i)return;let e,s="/"+t,a=localStorage?.getItem(O+i+"/v");if(1===a)try{e=JSON.parse(localStorage[O+i+s])}catch(t){}return e}),this.setPersistedData=(t=>t?(localStorage?.setItem(O+t+"/v",1),(e,s)=>{let i="/"+s,a=JSON.stringify(e);e&&s&&(localStorage?.setItem(O+t+i,a),dispatchEvent(new Event("storage")))}):()=>{})(s.id),this.clearPersistedData=(t=>e=>{const s=O+"/"+t+"/";if(e)localStorage.removeItem(s+e);else for(let t in localStorage)t.includes(s)&&localStorage.removeItem(t)})(s.id),this.applySettings(t,s),this.state={inputText:"",editing:!1,composing:!1,actions:{},mixMode:{},dropdown:{},flaggedTags:{}},this.value=[],this.listeners={},this.DOM={},this.build(t),x.call(this),this.getCSSVars(),this.loadOriginalValues(),this.events.customBinding.call(this),this.events.binding.call(this),t.autofocus&&this.DOM.input.focus(),t.__tagify=this}N.prototype={_dropdown:D,placeCaretAfterNode:w,getSetTagData:T,helpers:{sameStr:s,removeCollectionProp:i,omit:a,isObject:l,parseHTML:n,escapeHTML:r,extend:d,concatWithoutDups:h,getUID:p,isNodeTag:u},customEventsList:["change","add","remove","invalid","input","paste","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"],trim(t){return this.settings.trim&&t&&"string"==typeof t?t.trim():t},parseHTML:n,templates:M,parseTemplate(t,e){return n((t=this.settings.templates[t]||t).apply(this,e))},set whitelist(t){const e=t&&Array.isArray(t);this.settings.whitelist=e?t:[],this.setPersistedData(e?t:[],"whitelist")},get whitelist(){return this.settings.whitelist},set userInput(t){this.settings.userInput=!!t,this.setContentEditable(!!t)},get userInput(){return this.settings.userInput},generateClassSelectors(t){for(let e in t){let s=e;Object.defineProperty(t,s+"Selector",{get(){return"."+this[s].split(" ")[0]}})}},applySettings(t,e){y.templates=this.templates;var s=d({},y,"mix"==e.mode?{pasteAsTags:!1,dropdown:{position:"text"}}:{});this.origSettings=d({},e);var i=this.settings=d({},s,e);if(i.disabled=t.hasAttribute("disabled"),i.readonly=i.readonly||t.hasAttribute("readonly"),i.placeholder=r(t.getAttribute("placeholder")||i.placeholder||""),i.required=t.hasAttribute("required"),this.generateClassSelectors(i.classNames),this.isIE&&(i.autoComplete=!1),["whitelist","blacklist"].forEach((e=>{var s=t.getAttribute("data-"+e);s&&(s=s.split(i.delimiters))instanceof Array&&(i[e]=s)})),"autoComplete"in e&&!l(e.autoComplete)&&(i.autoComplete=y.autoComplete,i.autoComplete.enabled=e.autoComplete),"mix"==i.mode&&(i.pattern=i.pattern||/@/,i.autoComplete.rightKey=!0,i.delimiters=e.delimiters||null,i.tagTextProp&&!i.dropdown.searchKeys.includes(i.tagTextProp)&&i.dropdown.searchKeys.push(i.tagTextProp)),t.pattern)try{i.pattern=new RegExp(t.pattern)}catch(t){}if(i.delimiters){i._delimiters=i.delimiters;try{i.delimiters=new RegExp(this.settings.delimiters,"g")}catch(t){}}(i.disabled||i.readonly)&&(i.userInput=!1),this.TEXTS={...I,...i.texts||{}},"select"==i.mode&&(i.dropdown.includeSelectedTags=!0),("select"!=i.mode||e.dropdown?.enabled)&&i.userInput||(i.dropdown.enabled=0),i.disabled&&(i.dropdown.enabled=!1),i.dropdown.appendTarget=e.dropdown?.appendTarget||document.body,void 0===i.dropdown.includeSelectedTags&&(i.dropdown.includeSelectedTags=i.duplicates);let a=this.getPersistedData("whitelist");Array.isArray(a)&&(this.whitelist=Array.isArray(i.whitelist)?h(i.whitelist,a):a)},getAttributes(t){var e,s=this.getCustomAttributes(t),i="";for(e in s)i+=" "+e+(void 0!==t[e]?`="${s[e]}"`:"");return i},getCustomAttributes(t){if(!l(t))return"";var e,s={};for(e in t)"__"!=e.slice(0,2)&&"class"!=e&&t.hasOwnProperty(e)&&void 0!==t[e]&&(s[e]=r(t[e]));return s},setStateSelection(){var t=window.getSelection(),e={anchorOffset:t.anchorOffset,anchorNode:t.anchorNode,range:t.getRangeAt&&t.rangeCount&&t.getRangeAt(0)};return this.state.selection=e,e},getCSSVars(){var t=getComputedStyle(this.DOM.scope,null);var e;this.CSSVars={tagHideTransition:(({value:t,unit:e})=>"s"==e?1e3*t:t)(function(t){if(!t)return{};var e=(t=t.trim().split(" ")[0]).split(/\d+/g).filter((t=>t)).pop().trim();return{value:+t.split(e).filter((t=>t))[0].trim(),unit:e}}((e="tag-hide-transition",t.getPropertyValue("--"+e))))}},build(t){var e=this.DOM,s=t.closest("label");this.settings.mixMode.integrated?(e.originalInput=null,e.scope=t,e.input=t):(e.originalInput=t,e.originalInput_tabIndex=t.tabIndex,e.scope=this.parseTemplate("wrapper",[t,this.settings]),e.input=e.scope.querySelector(this.settings.classNames.inputSelector),t.parentNode.insertBefore(e.scope,t),t.tabIndex=-1),s&&s.setAttribute("for","")},destroy(){this.events.unbindGlobal.call(this),this.DOM.scope.parentNode?.removeChild(this.DOM.scope),this.DOM.originalInput.tabIndex=this.DOM.originalInput_tabIndex,delete this.DOM.originalInput.__tagify,this.dropdown.hide(!0),this.removeAllCustomListeners(),clearTimeout(this.dropdownHide__bindEventsTimeout),clearInterval(this.listeners?.main?.originalInputValueObserverInterval)},loadOriginalValues(t){var e,s=this.settings;if(this.state.blockChangeEvent=!0,void 0===t){const e=this.getPersistedData("value");t=e&&!this.DOM.originalInput.value?e:s.mixMode.integrated?this.DOM.input.textContent:this.DOM.originalInput.value}if(this.removeAllTags(),t)if("mix"==s.mode)this.parseMixTags(t),(e=this.DOM.input.lastChild)&&"BR"==e.tagName||this.DOM.input.insertAdjacentHTML("beforeend","<br>");else{try{JSON.parse(t)instanceof Array&&(t=JSON.parse(t))}catch(t){}this.addTags(t,!0).forEach((t=>t&&t.classList.add(s.classNames.tagNoAnimation)))}else this.postUpdate();this.state.lastOriginalValueReported=s.mixMode.integrated?"":this.DOM.originalInput.value},cloneEvent(t){var e={};for(var s in t)"path"!=s&&(e[s]=t[s]);return e},loading(t){return this.state.isLoading=t,this.DOM.scope.classList[t?"add":"remove"](this.settings.classNames.scopeLoading),this},tagLoading(t,e){return t&&t.classList[e?"add":"remove"](this.settings.classNames.tagLoading),this},toggleClass(t,e){"string"==typeof t&&this.DOM.scope.classList.toggle(t,e)},toggleScopeValidation(t){var e=!0===t||void 0===t;!this.settings.required&&t&&t===this.TEXTS.empty&&(e=!0),this.toggleClass(this.settings.classNames.tagInvalid,!e),this.DOM.scope.title=e?"":t},toggleFocusClass(t){this.toggleClass(this.settings.classNames.focus,!!t)},setPlaceholder(t){["data","aria"].forEach((e=>this.DOM.input.setAttribute(`${e}-placeholder`,t)))},triggerChangeEvent:function(){if(!this.settings.mixMode.integrated){var t=this.DOM.originalInput,e=this.state.lastOriginalValueReported!==t.value,s=new CustomEvent("change",{bubbles:!0});e&&(this.state.lastOriginalValueReported=t.value,s.simulated=!0,t._valueTracker&&t._valueTracker.setValue(Math.random()),t.dispatchEvent(s),this.trigger("change",this.state.lastOriginalValueReported),t.value=this.state.lastOriginalValueReported)}},events:E,fixFirefoxLastTagNoCaret(){},setRangeAtStartEnd(t,e){if(e){t="number"==typeof t?t:!!t,e=e.lastChild||e;var s=document.getSelection();if(s.focusNode instanceof Element&&!this.DOM.input.contains(s.focusNode))return!0;try{s.rangeCount>=1&&["Start","End"].forEach((i=>s.getRangeAt(0)["set"+i](e,t||e.length)))}catch(t){console.warn(t)}}},insertAfterTag(t,e){if(e=e||this.settings.mixMode.insertAfterTag,t&&t.parentNode&&e)return e="string"==typeof e?document.createTextNode(e):e,t.parentNode.insertBefore(e,t.nextSibling),e},editTagChangeDetected(t){var e=t.__originalData;for(var s in e)if(!this.dataProps.includes(s)&&t[s]!=e[s])return!0;return!1},getTagTextNode(t){return t.querySelector(this.settings.classNames.tagTextSelector)},setTagTextNode(t,e){this.getTagTextNode(t).innerHTML=r(e)},editTag(t,s){t=t||this.getLastTag(),s=s||{};var i=this.settings,a=this.getTagTextNode(t),n=this.getNodeIndex(t),o=T(t),r=this.events.callbacks,l=!0,h="select"==i.mode;if(!h&&this.dropdown.hide(),a){if(!(o instanceof Object&&"editable"in o)||o.editable)return o=T(t,{__originalData:d({},o),__originalHTML:t.cloneNode(!0)}),T(o.__originalHTML,o.__originalData),a.setAttribute("contenteditable",!0),t.classList.add(i.classNames.tagEditing),this.events.callbacks.onEditTagFocus.call(this,t),a.addEventListener("click",r.onEditTagClick.bind(this,t)),a.addEventListener("blur",r.onEditTagBlur.bind(this,this.getTagTextNode(t))),a.addEventListener("input",r.onEditTagInput.bind(this,a)),a.addEventListener("paste",r.onEditTagPaste.bind(this,a)),a.addEventListener("keydown",(e=>r.onEditTagkeydown.call(this,e,t))),a.addEventListener("compositionstart",r.onCompositionStart.bind(this)),a.addEventListener("compositionend",r.onCompositionEnd.bind(this)),s.skipValidation||(l=this.editTagToggleValidity(t)),a.originalIsValid=l,this.trigger("edit:start",{tag:t,index:n,data:o,isValid:l}),a.focus(),!h&&this.setRangeAtStartEnd(!1,a),0===i.dropdown.enabled&&!h&&this.dropdown.show(),this.state.hasFocus=!0,this}else e.warn("Cannot find element in Tag template: .",i.classNames.tagText