tribute-min.js
30.1 KB
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e=e||self).Tribute=t()}(this,(function(){"use strict";function e(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function t(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}function n(e,n,i){return n&&t(e.prototype,n),i&&t(e,i),e}function i(e,t){return r(e)||o(e,t)||u(e,t)||l()}function r(e){if(Array.isArray(e))return e}function o(e,t){if("undefined"!=typeof Symbol&&Symbol.iterator in Object(e)){var n=[],i=!0,r=!1,o=void 0;try{for(var u=e[Symbol.iterator](),a;!(i=(a=u.next()).done)&&(n.push(a.value),!t||n.length!==t);i=!0);}catch(e){r=!0,o=e}finally{try{i||null==u.return||u.return()}finally{if(r)throw o}}return n}}function u(e,t){if(e){if("string"==typeof e)return a(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(n):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?a(e,t):void 0}}function a(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,i=new Array(t);n<t;n++)i[n]=e[n];return i}function l(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}if(Array.prototype.find||(Array.prototype.find=function(e,t){if(null===this)throw new TypeError("Array.prototype.find called on null or undefined");if("function"!=typeof e)throw new TypeError("predicate must be a function");for(var n=Object(this),i=n.length>>>0,r=t,o,u=0;u<i;u++)if(o=n[u],e.call(r,o,u,n))return o}),window&&"function"!=typeof window.CustomEvent){var s=function e(t,n){n=n||{bubbles:!1,cancelable:!1,detail:void 0};var i=document.createEvent("CustomEvent");return i.initCustomEvent(t,n.bubbles,n.cancelable,n.detail),i};void 0!==window.Event&&(s.prototype=window.Event.prototype),window.CustomEvent=s}var c=function(){function t(n){e(this,t),this.tribute=n,this.tribute.events=this}return n(t,[{key:"bind",value:function e(t){t.boundKeydown=this.keydown.bind(t,this),t.boundKeyup=this.keyup.bind(t,this),t.boundInput=this.input.bind(t,this),t.addEventListener("keydown",t.boundKeydown,!1),t.addEventListener("keyup",t.boundKeyup,!1),t.addEventListener("input",t.boundInput,!1)}},{key:"unbind",value:function e(t){t.removeEventListener("keydown",t.boundKeydown,!1),t.removeEventListener("keyup",t.boundKeyup,!1),t.removeEventListener("input",t.boundInput,!1),delete t.boundKeydown,delete t.boundKeyup,delete t.boundInput}},{key:"keydown",value:function e(n,i){n.shouldDeactivate(i)&&(n.tribute.isActive=!1,n.tribute.hideMenu());var r=this;n.commandEvent=!1,t.keys().forEach((function(e){e.key===i.keyCode&&(n.commandEvent=!0,n.callbacks()[e.value.toLowerCase()](i,r))}))}},{key:"input",value:function e(t,n){t.inputEvent=!0,t.keyup.call(this,t,n)}},{key:"click",value:function e(t,n){var i=t.tribute;if(i.menu&&i.menu.contains(n.target)){var r=n.target;for(n.preventDefault(),n.stopPropagation();"li"!==r.nodeName.toLowerCase();)if(!(r=r.parentNode)||r===i.menu)throw new Error("cannot find the <li> container for the click");i.selectItemAtIndex(r.getAttribute("data-index"),n),i.hideMenu()}else i.current.element&&!i.current.externalTrigger&&(i.current.externalTrigger=!1,setTimeout((function(){return i.hideMenu()})))}},{key:"keyup",value:function e(t,n){if(t.inputEvent&&(t.inputEvent=!1),t.updateSelection(this),27!==n.keyCode){if(!t.tribute.allowSpaces&&t.tribute.hasTrailingSpace)return t.tribute.hasTrailingSpace=!1,t.commandEvent=!0,void t.callbacks().space(n,this);if(!t.tribute.isActive)if(t.tribute.autocompleteMode)t.callbacks().triggerChar(n,this,"");else{var i=t.getKeyCode(t,this,n);if(isNaN(i)||!i)return;var r=t.tribute.triggers().find((function(e){return e.charCodeAt(0)===i}));void 0!==r&&t.callbacks().triggerChar(n,this,r)}t.tribute.current.mentionText.length<t.tribute.current.collection.menuShowMinLength||((t.tribute.current.trigger||t.tribute.autocompleteMode)&&!1===t.commandEvent||t.tribute.isActive&&8===n.keyCode)&&t.tribute.showMenuFor(this,!0)}}},{key:"shouldDeactivate",value:function e(n){if(!this.tribute.isActive)return!1;if(0===this.tribute.current.mentionText.length){var i=!1;return t.keys().forEach((function(e){n.keyCode===e.key&&(i=!0)})),!i}return!1}},{key:"getKeyCode",value:function e(t,n,i){var r=t.tribute,o=r.range.getTriggerInfo(!1,r.hasTrailingSpace,!0,r.allowSpaces,r.autocompleteMode);return!!o&&o.mentionTriggerChar.charCodeAt(0)}},{key:"updateSelection",value:function e(t){this.tribute.current.element=t;var n=this.tribute.range.getTriggerInfo(!1,this.tribute.hasTrailingSpace,!0,this.tribute.allowSpaces,this.tribute.autocompleteMode);n&&(this.tribute.current.selectedPath=n.mentionSelectedPath,this.tribute.current.mentionText=n.mentionText,this.tribute.current.selectedOffset=n.mentionSelectedOffset)}},{key:"callbacks",value:function e(){var t=this;return{triggerChar:function e(n,i,r){var o=t.tribute;o.current.trigger=r;var u=o.collection.find((function(e){return e.trigger===r}));o.current.collection=u,o.current.mentionText.length>=o.current.collection.menuShowMinLength&&o.inputEvent&&o.showMenuFor(i,!0)},enter:function e(n,i){t.tribute.isActive&&t.tribute.current.filteredItems&&(n.preventDefault(),n.stopPropagation(),setTimeout((function(){t.tribute.selectItemAtIndex(t.tribute.menuSelected,n),t.tribute.hideMenu()}),0))},escape:function e(n,i){t.tribute.isActive&&(n.preventDefault(),n.stopPropagation(),t.tribute.isActive=!1,t.tribute.hideMenu())},tab:function e(n,i){t.callbacks().enter(n,i)},space:function e(n,i){t.tribute.isActive&&(t.tribute.spaceSelectsMatch?t.callbacks().enter(n,i):t.tribute.allowSpaces||(n.stopPropagation(),setTimeout((function(){t.tribute.hideMenu(),t.tribute.isActive=!1}),0)))},up:function e(n,i){if(t.tribute.isActive&&t.tribute.current.filteredItems){n.preventDefault(),n.stopPropagation();var r=t.tribute.current.filteredItems.length,o=t.tribute.menuSelected;r>o&&o>0?(t.tribute.menuSelected--,t.setActiveLi()):0===o&&(t.tribute.menuSelected=r-1,t.setActiveLi(),t.tribute.menu.scrollTop=t.tribute.menu.scrollHeight)}},down:function e(n,i){if(t.tribute.isActive&&t.tribute.current.filteredItems){n.preventDefault(),n.stopPropagation();var r=t.tribute.current.filteredItems.length-1,o=t.tribute.menuSelected;r>o?(t.tribute.menuSelected++,t.setActiveLi()):r===o&&(t.tribute.menuSelected=0,t.setActiveLi(),t.tribute.menu.scrollTop=0)}},delete:function e(n,i){t.tribute.isActive&&t.tribute.current.mentionText.length<1?t.tribute.hideMenu():t.tribute.isActive&&t.tribute.showMenuFor(i)}}}},{key:"setActiveLi",value:function e(t){var n=this.tribute.menu.querySelectorAll("li"),i=n.length>>>0;t&&(this.tribute.menuSelected=parseInt(t));for(var r=0;r<i;r++){var o=n[r];if(r===this.tribute.menuSelected){o.classList.add(this.tribute.current.collection.selectClass);var u=o.getBoundingClientRect(),a=this.tribute.menu.getBoundingClientRect();if(u.bottom>a.bottom){var l=u.bottom-a.bottom;this.tribute.menu.scrollTop+=l}else if(u.top<a.top){var s=a.top-u.top;this.tribute.menu.scrollTop-=s}}else o.classList.remove(this.tribute.current.collection.selectClass)}}},{key:"getFullHeight",value:function e(t,n){var i=t.getBoundingClientRect().height;if(n){var r=t.currentStyle||window.getComputedStyle(t);return i+parseFloat(r.marginTop)+parseFloat(r.marginBottom)}return i}}],[{key:"keys",value:function e(){return[{key:9,value:"TAB"},{key:8,value:"DELETE"},{key:13,value:"ENTER"},{key:27,value:"ESCAPE"},{key:32,value:"SPACE"},{key:38,value:"UP"},{key:40,value:"DOWN"}]}}]),t}(),h=function(){function t(n){e(this,t),this.tribute=n,this.tribute.menuEvents=this,this.menu=this.tribute.menu}return n(t,[{key:"bind",value:function e(t){var n=this;this.menuClickEvent=this.tribute.events.click.bind(null,this),this.menuContainerScrollEvent=this.debounce((function(){n.tribute.isActive&&n.tribute.hideMenu()}),10,!1),this.windowResizeEvent=this.debounce((function(){n.tribute.isActive&&n.tribute.hideMenu()}),10,!1),this.tribute.range.getDocument().addEventListener("MSPointerDown",this.menuClickEvent,!1),this.tribute.range.getDocument().addEventListener("mousedown",this.menuClickEvent,!1),window.addEventListener("resize",this.windowResizeEvent),this.menuContainer?this.menuContainer.addEventListener("scroll",this.menuContainerScrollEvent,!1):window.addEventListener("scroll",this.menuContainerScrollEvent)}},{key:"unbind",value:function e(t){this.tribute.range.getDocument().removeEventListener("mousedown",this.menuClickEvent,!1),this.tribute.range.getDocument().removeEventListener("MSPointerDown",this.menuClickEvent,!1),window.removeEventListener("resize",this.windowResizeEvent),this.menuContainer?this.menuContainer.removeEventListener("scroll",this.menuContainerScrollEvent,!1):window.removeEventListener("scroll",this.menuContainerScrollEvent)}},{key:"debounce",value:function e(t,n,i){var r=arguments,o=this,u;return function(){var e=o,a=r,l=function n(){u=null,i||t.apply(e,a)},s=i&&!u;clearTimeout(u),u=setTimeout(l,n),s&&t.apply(e,a)}}}]),t}(),d=function(){function t(n){e(this,t),this.tribute=n,this.tribute.range=this}return n(t,[{key:"getDocument",value:function e(){var t;return this.tribute.current.collection&&(t=this.tribute.current.collection.iframe),t?t.contentWindow.document:document}},{key:"positionMenuAtCaret",value:function e(t){var n=this.tribute.current,i,r=this.getTriggerInfo(!1,this.tribute.hasTrailingSpace,!0,this.tribute.allowSpaces,this.tribute.autocompleteMode);if(void 0!==r){if(!this.tribute.positionMenu)return void(this.tribute.menu.style.cssText="display: block;");i=this.isContentEditable(n.element)?this.getContentEditableCaretPosition(r.mentionPosition):this.getTextAreaOrInputUnderlinePosition(this.tribute.current.element,r.mentionPosition),this.tribute.menu.style.cssText="top: ".concat(i.top,"px;\n left: ").concat(i.left,"px;\n right: ").concat(i.right,"px;\n bottom: ").concat(i.bottom,"px;\n max-height: ").concat(i.maxHeight||500,"px;\n max-width: ").concat(i.maxWidth||300,"px;\n position: ").concat(i.position||"absolute",";\n display: block;"),"auto"===i.left&&(this.tribute.menu.style.left="auto"),"auto"===i.top&&(this.tribute.menu.style.top="auto"),t&&this.scrollIntoView()}else this.tribute.menu.style.cssText="display: none"}},{key:"selectElement",value:function e(t,n,i){var r,o=t;if(n)for(var u=0;u<n.length;u++){if(void 0===(o=o.childNodes[n[u]]))return;for(;o.length<i;)i-=o.length,o=o.nextSibling;0!==o.childNodes.length||o.length||(o=o.previousSibling)}var a=this.getWindowSelection();(r=this.getDocument().createRange()).setStart(o,i),r.setEnd(o,i),r.collapse(!0);try{a.removeAllRanges()}catch(e){}a.addRange(r),t.focus()}},{key:"replaceTriggerText",value:function e(t,n,i,r,o){var u=this.getTriggerInfo(!0,i,n,this.tribute.allowSpaces,this.tribute.autocompleteMode);if(void 0!==u){var a=this.tribute.current,l=new CustomEvent("tribute-replaced",{detail:{item:o,instance:a,context:u,event:r}});if(this.isContentEditable(a.element)){var s;t+="string"==typeof this.tribute.replaceTextSuffix?this.tribute.replaceTextSuffix:" ";var c=u.mentionPosition+u.mentionText.length;this.tribute.autocompleteMode||(c+=u.mentionTriggerChar.length),this.pasteHtml(t,u.mentionPosition,c)}else{var h=this.tribute.current.element,d="string"==typeof this.tribute.replaceTextSuffix?this.tribute.replaceTextSuffix:" ";t+=d;var f=u.mentionPosition,m=u.mentionPosition+u.mentionText.length+d.length;this.tribute.autocompleteMode||(m+=u.mentionTriggerChar.length-1),h.value=h.value.substring(0,f)+t+h.value.substring(m,h.value.length),h.selectionStart=f+t.length,h.selectionEnd=f+t.length}a.element.dispatchEvent(new CustomEvent("input",{bubbles:!0})),a.element.dispatchEvent(l)}}},{key:"pasteHtml",value:function e(t,n,i){var r,o;o=this.getWindowSelection(),(r=this.getDocument().createRange()).setStart(o.anchorNode,n),r.setEnd(o.anchorNode,i),r.deleteContents();var u=this.getDocument().createElement("div");u.innerHTML=t;for(var a=this.getDocument().createDocumentFragment(),l,s;l=u.firstChild;)s=a.appendChild(l);r.insertNode(a),s&&((r=r.cloneRange()).setStartAfter(s),r.collapse(!0),o.removeAllRanges(),o.addRange(r))}},{key:"getWindowSelection",value:function e(){return this.tribute.collection.iframe?this.tribute.collection.iframe.contentWindow.getSelection():window.getSelection()}},{key:"getNodePositionInParent",value:function e(t){if(null===t.parentNode)return 0;for(var n=0;n<t.parentNode.childNodes.length;n++){var i;if(t.parentNode.childNodes[n]===t)return n}}},{key:"getContentEditableSelectedPath",value:function e(t){var n=this.getWindowSelection(),i=n.anchorNode,r=[],o;if(null!=i){for(var u,a=i.contentEditable;null!==i&&"true"!==a;)u=this.getNodePositionInParent(i),r.push(u),null!==(i=i.parentNode)&&(a=i.contentEditable);return r.reverse(),{selected:i,path:r,offset:o=n.getRangeAt(0).startOffset}}}},{key:"getTextPrecedingCurrentSelection",value:function e(){var t=this.tribute.current,n="";if(this.isContentEditable(t.element)){var i=this.getWindowSelection().anchorNode;if(null!=i){var r=i.textContent,o=this.getWindowSelection().getRangeAt(0).startOffset;r&&o>=0&&(n=r.substring(0,o))}}else{var u=this.tribute.current.element;if(u){var a=u.selectionStart;u.value&&a>=0&&(n=u.value.substring(0,a))}}return n}},{key:"getLastWordInText",value:function e(t){var n,i;return t=t.replace(/\u00A0/g," "),(n=this.tribute.autocompleteSeparator?t.split(this.tribute.autocompleteSeparator):t.split(/\s+/))[n.length-1].trim()}},{key:"getTriggerInfo",value:function e(t,n,i,r,o){var u=this,a=this.tribute.current,l,s,c;if(this.isContentEditable(a.element)){var h=this.getContentEditableSelectedPath(a);h&&(l=h.selected,s=h.path,c=h.offset)}else l=this.tribute.current.element;var d=this.getTextPrecedingCurrentSelection(),f=this.getLastWordInText(d);if(o)return{mentionPosition:d.length-f.length,mentionText:f,mentionSelectedElement:l,mentionSelectedPath:s,mentionSelectedOffset:c};if(null!=d){var m=-1,p;if(this.tribute.collection.forEach((function(e){var t=e.trigger,n=e.requireLeadingSpace?u.lastIndexWithLeadingSpace(d,t):d.lastIndexOf(t);n>m&&(m=n,p=t,i=e.requireLeadingSpace)})),m>=0&&(0===m||!i||/[\xA0\s]/g.test(d.substring(m-1,m)))){var v=d.substring(m+p.length,d.length);p=d.substring(m,m+p.length);var g=v.substring(0,1),b=v.length>0&&(" "===g||" "===g);n&&(v=v.trim());var y=r?/[^\S ]/g:/[\xA0\s]/g;if(this.tribute.hasTrailingSpace=y.test(v),!b&&(t||!y.test(v)))return{mentionPosition:m,mentionText:v,mentionSelectedElement:l,mentionSelectedPath:s,mentionSelectedOffset:c,mentionTriggerChar:p}}}}},{key:"lastIndexWithLeadingSpace",value:function e(t,n){for(var i=t.split("").reverse().join(""),r=-1,o=0,u=t.length;o<u;o++){for(var a=o===t.length-1,l=/\s/.test(i[o+1]),s=!0,c=n.length-1;c>=0;c--)if(n[c]!==i[o-c]){s=!1;break}if(s&&(a||l)){r=t.length-1-o;break}}return r}},{key:"isContentEditable",value:function e(t){return"INPUT"!==t.nodeName&&"TEXTAREA"!==t.nodeName}},{key:"isMenuOffScreen",value:function e(t,n){var i=window.innerWidth,r=window.innerHeight,o=document.documentElement,u=(window.pageXOffset||o.scrollLeft)-(o.clientLeft||0),a=(window.pageYOffset||o.scrollTop)-(o.clientTop||0),l="number"==typeof t.top?t.top:a+r-t.bottom-n.height,s="number"==typeof t.right?t.right:t.left+n.width,c="number"==typeof t.bottom?t.bottom:t.top+n.height,h="number"==typeof t.left?t.left:u+i-t.right-n.width;return{top:l<Math.floor(a),right:s>Math.ceil(u+i),bottom:c>Math.ceil(a+r),left:h<Math.floor(u)}}},{key:"getMenuDimensions",value:function e(){var t={width:null,height:null};return this.tribute.menu.style.cssText="top: 0px;\n left: 0px;\n position: fixed;\n display: block;\n visibility; hidden;\n max-height:500px;",t.width=this.tribute.menu.offsetWidth,t.height=this.tribute.menu.offsetHeight,this.tribute.menu.style.cssText="display: none;",t}},{key:"getTextAreaOrInputUnderlinePosition",value:function e(t,n,i){var r=["direction","boxSizing","width","height","overflowX","overflowY","borderTopWidth","borderRightWidth","borderBottomWidth","borderLeftWidth","borderStyle","paddingTop","paddingRight","paddingBottom","paddingLeft","fontStyle","fontVariant","fontWeight","fontStretch","fontSize","fontSizeAdjust","lineHeight","fontFamily","textAlign","textTransform","textIndent","textDecoration","letterSpacing","wordSpacing"],o=this.getDocument().createElement("div");o.id="input-textarea-caret-position-mirror-div",this.getDocument().body.appendChild(o);var u=o.style,a=window.getComputedStyle?getComputedStyle(t):t.currentStyle;u.whiteSpace="pre-wrap","INPUT"!==t.nodeName&&(u.wordWrap="break-word"),u.position="absolute",u.visibility="hidden",r.forEach((function(e){u[e]=a[e]}));var l=document.createElement("span");l.textContent=t.value.substring(0,n),o.appendChild(l),"INPUT"===t.nodeName&&(o.textContent=o.textContent.replace(/\s/g," "));var s=this.getDocument().createElement("span");s.textContent="​",o.appendChild(s);var c=this.getDocument().createElement("span");c.textContent=t.value.substring(n),o.appendChild(c);var h=t.getBoundingClientRect();o.style.position="fixed",o.style.left=h.left+"px",o.style.top=h.top+"px",o.style.width=h.width+"px",o.style.height=h.height+"px",o.scrollTop=t.scrollTop;var d=s.getBoundingClientRect();return this.getDocument().body.removeChild(o),this.getFixedCoordinatesRelativeToRect(d)}},{key:"getContentEditableCaretPosition",value:function e(t){var n,i=this.getWindowSelection();(n=this.getDocument().createRange()).setStart(i.anchorNode,t),n.setEnd(i.anchorNode,t),n.collapse(!1);var r=n.getBoundingClientRect();return this.getFixedCoordinatesRelativeToRect(r)}},{key:"getFixedCoordinatesRelativeToRect",value:function e(t){var n={position:"fixed",left:t.left,top:t.top+t.height},i=this.getMenuDimensions(),r=t.top,o=window.innerHeight-(t.top+t.height);o<i.height&&(r>=i.height||r>o?(n.top="auto",n.bottom=window.innerHeight-t.top,o<i.height&&(n.maxHeight=r)):r<i.height&&(n.maxHeight=o));var u=t.left,a=window.innerWidth-t.left;return a<i.width&&(u>=i.width||u>a?(n.left="auto",n.right=window.innerWidth-t.left,a<i.width&&(n.maxWidth=u)):u<i.width&&(n.maxWidth=a)),n}},{key:"scrollIntoView",value:function e(t){var n=20,i,r=100,o=this.menu;if(void 0!==o){for(;void 0===i||0===i.height;)if(0===(i=o.getBoundingClientRect()).height&&(void 0===(o=o.childNodes[0])||!o.getBoundingClientRect))return;var u=i.top,a=u+i.height;if(u<0)window.scrollTo(0,window.pageYOffset+i.top-n);else if(a>window.innerHeight){var l=window.pageYOffset+i.top-n;l-window.pageYOffset>r&&(l=window.pageYOffset+r);var s=window.pageYOffset-(window.innerHeight-a);s>l&&(s=l),window.scrollTo(0,s)}}}},{key:"menuContainerIsBody",get:function e(){return this.tribute.menuContainer===document.body||!this.tribute.menuContainer}}]),t}(),f=function(){function t(n){e(this,t),this.tribute=n,this.tribute.search=this}return n(t,[{key:"simpleFilter",value:function e(t,n){var i=this;return n.filter((function(e){return i.test(t,e)}))}},{key:"test",value:function e(t,n){return null!==this.match(t,n)}},{key:"match",value:function e(t,n,i){i=i||{};var r=n.length,o=i.pre||"",u=i.post||"",a=i.caseSensitive&&n||n.toLowerCase();if(i.skip)return{rendered:n,score:0};t=i.caseSensitive&&t||t.toLowerCase();var l=this.traverse(a,t,0,0,[]);return l?{rendered:this.render(n,l.cache,o,u),score:l.score}:null}},{key:"traverse",value:function e(t,n,i,r,o){if(this.tribute.autocompleteSeparator&&(n=n.split(this.tribute.autocompleteSeparator).splice(-1)[0]),n.length===r)return{score:this.calculateScore(o),cache:o.slice()};if(!(t.length===i||n.length-r>t.length-i)){for(var u=n[r],a=t.indexOf(u,i),l,s;a>-1;){if(o.push(a),s=this.traverse(t,n,a+1,r+1,o),o.pop(),!s)return l;(!l||l.score<s.score)&&(l=s),a=t.indexOf(u,a+1)}return l}}},{key:"calculateScore",value:function e(t){var n=0,i=1;return t.forEach((function(e,r){r>0&&(t[r-1]+1===e?i+=i+1:i=1),n+=i})),n}},{key:"render",value:function e(t,n,i,r){var o=t.substring(0,n[0]);return n.forEach((function(e,u){o+=i+t[e]+r+t.substring(e+1,n[u+1]?n[u+1]:t.length)})),o}},{key:"filter",value:function e(t,n,i){var r=this;return i=i||{},n.reduce((function(e,n,o,u){var a=n;i.extract&&((a=i.extract(n))||(a=""));var l=r.match(t,a,i);return null!=l&&(e[e.length]={string:l.rendered,score:l.score,index:o,original:n}),e}),[]).sort((function(e,t){var n=t.score-e.score;return n||e.index-t.index}))}}]),t}(),m;return function(){function t(n){var i=this,r=n.values,o=void 0===r?null:r,u=n.loadingItemTemplate,a=void 0===u?null:u,l=n.iframe,s=void 0===l?null:l,m=n.selectClass,p=void 0===m?"highlight":m,v=n.containerClass,g=void 0===v?"tribute-container":v,b=n.itemClass,y=void 0===b?"":b,w=n.trigger,T=void 0===w?"@":w,S=n.autocompleteMode,C=void 0!==S&&S,k=n.autocompleteSeparator,E=void 0===k?null:k,x=n.selectTemplate,A=void 0===x?null:x,M=n.menuItemTemplate,L=void 0===M?null:M,I=n.lookup,N=void 0===I?"key":I,P=n.fillAttr,R=void 0===P?"value":P,D=n.collection,O=void 0===D?null:D,W=n.menuContainer,H=void 0===W?null:W,F=n.noMatchTemplate,_=void 0===F?null:F,B=n.requireLeadingSpace,j=void 0===B||B,K=n.allowSpaces,q=void 0!==K&&K,U=n.replaceTextSuffix,z=void 0===U?null:U,Y=n.positionMenu,Q=void 0===Y||Y,X=n.spaceSelectsMatch,V=void 0!==X&&X,G=n.searchOpts,J=void 0===G?{}:G,Z=n.menuItemLimit,ee=void 0===Z?null:Z,te=n.menuShowMinLength,ne=void 0===te?0:te,ie;if(e(this,t),this.autocompleteMode=C,this.autocompleteSeparator=E,this.menuSelected=0,this.current={},this.inputEvent=!1,this.isActive=!1,this.menuContainer=H,this.allowSpaces=q,this.replaceTextSuffix=z,this.positionMenu=Q,this.hasTrailingSpace=!1,this.spaceSelectsMatch=V,this.autocompleteMode&&(T="",q=!1),o)this.collection=[{trigger:T,iframe:s,selectClass:p,containerClass:g,itemClass:y,selectTemplate:(A||t.defaultSelectTemplate).bind(this),menuItemTemplate:(L||t.defaultMenuItemTemplate).bind(this),noMatchTemplate:(ie=_,"string"==typeof ie?""===ie.trim()?null:ie:"function"==typeof ie?ie.bind(i):_||function(){return"<li>No Match Found!</li>"}.bind(i)),lookup:N,fillAttr:R,values:o,loadingItemTemplate:a,requireLeadingSpace:j,searchOpts:J,menuItemLimit:ee,menuShowMinLength:ne}];else{if(!O)throw new Error("[Tribute] No collection specified.");this.autocompleteMode&&console.warn("Tribute in autocomplete mode does not work for collections"),this.collection=O.map((function(e){return{trigger:e.trigger||T,iframe:e.iframe||s,selectClass:e.selectClass||p,containerClass:e.containerClass||g,itemClass:e.itemClass||y,selectTemplate:(e.selectTemplate||t.defaultSelectTemplate).bind(i),menuItemTemplate:(e.menuItemTemplate||t.defaultMenuItemTemplate).bind(i),noMatchTemplate:function(e){return"string"==typeof e?""===e.trim()?null:e:"function"==typeof e?e.bind(i):_||function(){return"<li>No Match Found!</li>"}.bind(i)}(_),lookup:e.lookup||N,fillAttr:e.fillAttr||R,values:e.values,loadingItemTemplate:e.loadingItemTemplate,requireLeadingSpace:e.requireLeadingSpace,searchOpts:e.searchOpts||J,menuItemLimit:e.menuItemLimit||ee,menuShowMinLength:e.menuShowMinLength||ne}}))}new d(this),new c(this),new h(this),new f(this)}return n(t,[{key:"triggers",value:function e(){return this.collection.map((function(e){return e.trigger}))}},{key:"attach",value:function e(t){if(!t)throw new Error("[Tribute] Must pass in a DOM node or NodeList.");if("undefined"!=typeof jQuery&&t instanceof jQuery&&(t=t.get()),t.constructor===NodeList||t.constructor===HTMLCollection||t.constructor===Array)for(var n=t.length,i=0;i<n;++i)this._attach(t[i]);else this._attach(t)}},{key:"_attach",value:function e(t){t.hasAttribute("data-tribute")&&console.warn("Tribute was already bound to "+t.nodeName),this.ensureEditable(t),this.events.bind(t),t.setAttribute("data-tribute",!0)}},{key:"ensureEditable",value:function e(n){if(-1===t.inputTypes().indexOf(n.nodeName)){if(!n.contentEditable)throw new Error("[Tribute] Cannot bind to "+n.nodeName);n.contentEditable=!0}}},{key:"createMenu",value:function e(t){var n=this.range.getDocument().createElement("div"),i=this.range.getDocument().createElement("ul");return n.className=t,n.appendChild(i),this.menuContainer?this.menuContainer.appendChild(n):this.range.getDocument().body.appendChild(n)}},{key:"showMenuFor",value:function e(t,n){var r=this;if(!this.isActive||this.current.element!==t||this.current.mentionText!==this.currentMentionTextSnapshot){this.currentMentionTextSnapshot=this.current.mentionText,this.menu||(this.menu=this.createMenu(this.current.collection.containerClass),t.tributeMenu=this.menu,this.menuEvents.bind(this.menu)),this.isActive=!0,this.menuSelected=0,this.current.mentionText||(this.current.mentionText="");var o=function e(t){if(r.isActive){var o=r.search.filter(r.current.mentionText,t,{pre:r.current.collection.searchOpts.pre||"<span>",post:r.current.collection.searchOpts.post||"</span>",skip:r.current.collection.searchOpts.skip,extract:function e(t){if("string"==typeof r.current.collection.lookup)return t[r.current.collection.lookup];if("function"==typeof r.current.collection.lookup)return r.current.collection.lookup(t,r.current.mentionText);throw new Error("Invalid lookup attribute, lookup must be string or function.")}});r.current.collection.menuItemLimit&&(o=o.slice(0,r.current.collection.menuItemLimit)),r.current.filteredItems=o;var u=r.menu.querySelector("ul");if(!o.length){var a=new CustomEvent("tribute-no-match",{detail:r.menu});return r.current.element.dispatchEvent(a),void("function"==typeof r.current.collection.noMatchTemplate&&!r.current.collection.noMatchTemplate()||!r.current.collection.noMatchTemplate?r.hideMenu():("function"==typeof r.current.collection.noMatchTemplate?u.innerHTML=r.current.collection.noMatchTemplate():u.innerHTML=r.current.collection.noMatchTemplate,r.range.positionMenuAtCaret(n)))}u.innerHTML="";var l=r.range.getDocument().createDocumentFragment();o.forEach((function(e,t){var n=r.range.getDocument().createElement("li");n.setAttribute("data-index",t),n.className=r.current.collection.itemClass,n.addEventListener("mousemove",(function(e){var t,n=i(r._findLiTarget(e.target),2),o=n[0],u=n[1];0!==e.movementY&&r.events.setActiveLi(u)})),r.menuSelected===t&&n.classList.add(r.current.collection.selectClass),n.innerHTML=r.current.collection.menuItemTemplate(e),l.appendChild(n)})),u.appendChild(l),r.range.positionMenuAtCaret(n)}};"function"==typeof this.current.collection.values?(this.current.collection.loadingItemTemplate&&(this.menu.querySelector("ul").innerHTML=this.current.collection.loadingItemTemplate,this.range.positionMenuAtCaret(n)),this.current.collection.values(this.current.mentionText,o)):o(this.current.collection.values)}}},{key:"_findLiTarget",value:function e(t){if(!t)return[];var n=t.getAttribute("data-index");return n?[t,n]:this._findLiTarget(t.parentNode)}},{key:"showMenuForCollection",value:function e(t,n){t!==document.activeElement&&this.placeCaretAtEnd(t),this.current.collection=this.collection[n||0],this.current.externalTrigger=!0,this.current.element=t,t.isContentEditable?this.insertTextAtCursor(this.current.collection.trigger):this.insertAtCaret(t,this.current.collection.trigger),this.showMenuFor(t)}},{key:"placeCaretAtEnd",value:function e(t){if(t.focus(),void 0!==window.getSelection&&void 0!==document.createRange){var n=document.createRange();n.selectNodeContents(t),n.collapse(!1);var i=window.getSelection();i.removeAllRanges(),i.addRange(n)}else if(void 0!==document.body.createTextRange){var r=document.body.createTextRange();r.moveToElementText(t),r.collapse(!1),r.select()}}},{key:"insertTextAtCursor",value:function e(t){var n,i;(i=(n=window.getSelection()).getRangeAt(0)).deleteContents();var r=document.createTextNode(t);i.insertNode(r),i.selectNodeContents(r),i.collapse(!1),n.removeAllRanges(),n.addRange(i)}},{key:"insertAtCaret",value:function e(t,n){var i=t.scrollTop,r=t.selectionStart,o=t.value.substring(0,r),u=t.value.substring(t.selectionEnd,t.value.length);t.value=o+n+u,r+=n.length,t.selectionStart=r,t.selectionEnd=r,t.focus(),t.scrollTop=i}},{key:"hideMenu",value:function e(){this.menu&&(this.menu.style.cssText="display: none;",this.isActive=!1,this.menuSelected=0,this.current={})}},{key:"selectItemAtIndex",value:function e(t,n){if("number"==typeof(t=parseInt(t))&&!isNaN(t)){var i=this.current.filteredItems[t],r=this.current.collection.selectTemplate(i);null!==r&&this.replaceText(r,n,i)}}},{key:"replaceText",value:function e(t,n,i){this.range.replaceTriggerText(t,!0,!0,n,i)}},{key:"_append",value:function e(t,n,i){if("function"==typeof t.values)throw new Error("Unable to append to values, as it is a function.");t.values=i?n:t.values.concat(n)}},{key:"append",value:function e(t,n,i){var r=parseInt(t);if("number"!=typeof r)throw new Error("please provide an index for the collection to update.");var o=this.collection[r];this._append(o,n,i)}},{key:"appendCurrent",value:function e(t,n){if(!this.isActive)throw new Error("No active state. Please use append instead and pass an index.");this._append(this.current.collection,t,n)}},{key:"detach",value:function e(t){if(!t)throw new Error("[Tribute] Must pass in a DOM node or NodeList.");if("undefined"!=typeof jQuery&&t instanceof jQuery&&(t=t.get()),t.constructor===NodeList||t.constructor===HTMLCollection||t.constructor===Array)for(var n=t.length,i=0;i<n;++i)this._detach(t[i]);else this._detach(t)}},{key:"_detach",value:function e(t){var n=this;this.events.unbind(t),t.tributeMenu&&this.menuEvents.unbind(t.tributeMenu),setTimeout((function(){t.removeAttribute("data-tribute"),n.isActive=!1,t.tributeMenu&&t.tributeMenu.remove()}))}},{key:"isActive",get:function e(){return this._isActive},set:function e(t){if(this._isActive!=t&&(this._isActive=t,this.current.element)){var n=new CustomEvent("tribute-active-".concat(t));this.current.element.dispatchEvent(n)}}}],[{key:"defaultSelectTemplate",value:function e(t){return void 0===t?"".concat(this.current.collection.trigger).concat(this.current.mentionText):this.range.isContentEditable(this.current.element)?'<span class="tribute-mention">'+(this.current.collection.trigger+t.original[this.current.collection.fillAttr])+"</span>":this.current.collection.trigger+t.original[this.current.collection.fillAttr]}},{key:"defaultMenuItemTemplate",value:function e(t){return t.string}},{key:"inputTypes",value:function e(){return["TEXTAREA","INPUT"]}}]),t}()}));