text
stringlengths
9
39.2M
dir
stringlengths
25
226
lang
stringclasses
163 values
created_date
timestamp[s]
updated_date
timestamp[s]
repo_name
stringclasses
751 values
repo_full_name
stringclasses
752 values
star
int64
1.01k
183k
len_tokens
int64
1
18.5M
```javascript // Thanks to path_to_url class TributeSearch { constructor(tribute) { this.tribute = tribute this.tribute.search = this } simpleFilter(pattern, array) { return array.filter(string => { return this.test(pattern, string) }) } test(pattern, string) { return this.match(pattern, string) !== null } match(pattern, string, opts) { opts = opts || {} let patternIdx = 0, result = [], len = string.length, totalScore = 0, currScore = 0, pre = opts.pre || '', post = opts.post || '', compareString = opts.caseSensitive && string || string.toLowerCase(), ch, compareChar if (opts.skip) { return {rendered: string, score: 0} } pattern = opts.caseSensitive && pattern || pattern.toLowerCase() let patternCache = this.traverse(compareString, pattern, 0, 0, []) if (!patternCache) { return null } return { rendered: this.render(string, patternCache.cache, pre, post), score: patternCache.score } } traverse(string, pattern, stringIndex, patternIndex, patternCache) { if (this.tribute.autocompleteSeparator) { // if the pattern search at end pattern = pattern.split(this.tribute.autocompleteSeparator).splice(-1)[0]; } if (pattern.length === patternIndex) { // calculate score and copy the cache containing the indices where it's found return { score: this.calculateScore(patternCache), cache: patternCache.slice() } } // if string at end or remaining pattern > remaining string if (string.length === stringIndex || pattern.length - patternIndex > string.length - stringIndex) { return undefined } let c = pattern[patternIndex] let index = string.indexOf(c, stringIndex) let best, temp while (index > -1) { patternCache.push(index) temp = this.traverse(string, pattern, index + 1, patternIndex + 1, patternCache) patternCache.pop() // if downstream traversal failed, return best answer so far if (!temp) { return best } if (!best || best.score < temp.score) { best = temp } index = string.indexOf(c, index + 1) } return best } calculateScore(patternCache) { let score = 0 let temp = 1 patternCache.forEach((index, i) => { if (i > 0) { if (patternCache[i - 1] + 1 === index) { temp += temp + 1 } else { temp = 1 } } score += temp }) return score } render(string, indices, pre, post) { var rendered = string.substring(0, indices[0]) indices.forEach((index, i) => { rendered += pre + string[index] + post + string.substring(index + 1, (indices[i + 1]) ? indices[i + 1] : string.length) }) return rendered } filter(pattern, arr, opts) { opts = opts || {} return arr .reduce((prev, element, idx, arr) => { let str = element if (opts.extract) { str = opts.extract(element) if (!str) { // take care of undefineds / nulls / etc. str = '' } } let rendered = this.match(pattern, str, opts) if (rendered != null) { prev[prev.length] = { string: rendered.rendered, score: rendered.score, index: idx, original: element } } return prev }, []) .sort((a, b) => { let compare = b.score - a.score if (compare) return compare return a.index - b.index }) } } export default TributeSearch; ```
/content/code_sandbox/src/TributeSearch.js
javascript
2016-01-19T00:54:39
2024-08-14T11:30:58
tribute
zurb/tribute
2,017
899
```javascript /*! jQuery v1.10.2 | (c) 2005, 2013 jQuery Foundation, Inc. | jquery.org/license //@ sourceMappingURL=jquery-1.10.2.min.map */ (function(e,t){var n,r,i=typeof t,o=e.location,a=e.document,s=a.documentElement,l=e.jQuery,u=e.$,c={},p=[],f="1.10.2",d=p.concat,h=p.push,g=p.slice,m=p.indexOf,y=c.toString,v=c.hasOwnProperty,b=f.trim,x=function(e,t){return new x.fn.init(e,t,r)},w=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,T=/\S+/g,C=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,N=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,k=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,E=/^[\],:{}\s]*$/,S=/(?:^|:|,)(?:\s*\[)+/g,A=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,j=/"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g,D=/^-ms-/,L=/-([\da-z])/gi,H=function(e,t){return t.toUpperCase()},q=function(e){(a.addEventListener||"load"===e.type||"complete"===a.readyState)&&(_(),x.ready())},_=function(){a.addEventListener?(a.removeEventListener("DOMContentLoaded",q,!1),e.removeEventListener("load",q,!1)):(a.detachEvent("onreadystatechange",q),e.detachEvent("onload",q))};x.fn=x.prototype={jquery:f,constructor:x,init:function(e,n,r){var i,o;if(!e)return this;if("string"==typeof e){if(i="<"===e.charAt(0)&&">"===e.charAt(e.length-1)&&e.length>=3?[null,e,null]:N.exec(e),!i||!i[1]&&n)return!n||n.jquery?(n||r).find(e):this.constructor(n).find(e);if(i[1]){if(n=n instanceof x?n[0]:n,x.merge(this,x.parseHTML(i[1],n&&n.nodeType?n.ownerDocument||n:a,!0)),k.test(i[1])&&x.isPlainObject(n))for(i in n)x.isFunction(this[i])?this[i](n[i]):this.attr(i,n[i]);return this}if(o=a.getElementById(i[2]),o&&o.parentNode){if(o.id!==i[2])return r.find(e);this.length=1,this[0]=o}return this.context=a,this.selector=e,this}return e.nodeType?(this.context=this[0]=e,this.length=1,this):x.isFunction(e)?r.ready(e):(e.selector!==t&&(this.selector=e.selector,this.context=e.context),x.makeArray(e,this))},selector:"",length:0,toArray:function(){return g.call(this)},get:function(e){return null==e?this.toArray():0>e?this[this.length+e]:this[e]},pushStack:function(e){var t=x.merge(this.constructor(),e);return t.prevObject=this,t.context=this.context,t},each:function(e,t){return x.each(this,e,t)},ready:function(e){return x.ready.promise().done(e),this},slice:function(){return this.pushStack(g.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,n=+e+(0>e?t:0);return this.pushStack(n>=0&&t>n?[this[n]]:[])},map:function(e){return this.pushStack(x.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:h,sort:[].sort,splice:[].splice},x.fn.init.prototype=x.fn,x.extend=x.fn.extend=function(){var e,n,r,i,o,a,s=arguments[0]||{},l=1,u=arguments.length,c=!1;for("boolean"==typeof s&&(c=s,s=arguments[1]||{},l=2),"object"==typeof s||x.isFunction(s)||(s={}),u===l&&(s=this,--l);u>l;l++)if(null!=(o=arguments[l]))for(i in o)e=s[i],r=o[i],s!==r&&(c&&r&&(x.isPlainObject(r)||(n=x.isArray(r)))?(n?(n=!1,a=e&&x.isArray(e)?e:[]):a=e&&x.isPlainObject(e)?e:{},s[i]=x.extend(c,a,r)):r!==t&&(s[i]=r));return s},x.extend({expando:"jQuery"+(f+Math.random()).replace(/\D/g,""),noConflict:function(t){return e.$===x&&(e.$=u),t&&e.jQuery===x&&(e.jQuery=l),x},isReady:!1,readyWait:1,holdReady:function(e){e?x.readyWait++:x.ready(!0)},ready:function(e){if(e===!0?!--x.readyWait:!x.isReady){if(!a.body)return setTimeout(x.ready);x.isReady=!0,e!==!0&&--x.readyWait>0||(n.resolveWith(a,[x]),x.fn.trigger&&x(a).trigger("ready").off("ready"))}},isFunction:function(e){return"function"===x.type(e)},isArray:Array.isArray||function(e){return"array"===x.type(e)},isWindow:function(e){return null!=e&&e==e.window},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},type:function(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?c[y.call(e)]||"object":typeof e},isPlainObject:function(e){var n;if(!e||"object"!==x.type(e)||e.nodeType||x.isWindow(e))return!1;try{if(e.constructor&&!v.call(e,"constructor")&&!v.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(r){return!1}if(x.support.ownLast)for(n in e)return v.call(e,n);for(n in e);return n===t||v.call(e,n)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},error:function(e){throw Error(e)},parseHTML:function(e,t,n){if(!e||"string"!=typeof e)return null;"boolean"==typeof t&&(n=t,t=!1),t=t||a;var r=k.exec(e),i=!n&&[];return r?[t.createElement(r[1])]:(r=x.buildFragment([e],t,i),i&&x(i).remove(),x.merge([],r.childNodes))},parseJSON:function(n){return e.JSON&&e.JSON.parse?e.JSON.parse(n):null===n?n:"string"==typeof n&&(n=x.trim(n),n&&E.test(n.replace(A,"@").replace(j,"]").replace(S,"")))?Function("return "+n)():(x.error("Invalid JSON: "+n),t)},parseXML:function(n){var r,i;if(!n||"string"!=typeof n)return null;try{e.DOMParser?(i=new DOMParser,r=i.parseFromString(n,"text/xml")):(r=new ActiveXObject("Microsoft.XMLDOM"),r.async="false",r.loadXML(n))}catch(o){r=t}return r&&r.documentElement&&!r.getElementsByTagName("parsererror").length||x.error("Invalid XML: "+n),r},noop:function(){},globalEval:function(t){t&&x.trim(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(D,"ms-").replace(L,H)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,t,n){var r,i=0,o=e.length,a=M(e);if(n){if(a){for(;o>i;i++)if(r=t.apply(e[i],n),r===!1)break}else for(i in e)if(r=t.apply(e[i],n),r===!1)break}else if(a){for(;o>i;i++)if(r=t.call(e[i],i,e[i]),r===!1)break}else for(i in e)if(r=t.call(e[i],i,e[i]),r===!1)break;return e},trim:b&&!b.call("\ufeff\u00a0")?function(e){return null==e?"":b.call(e)}:function(e){return null==e?"":(e+"").replace(C,"")},makeArray:function(e,t){var n=t||[];return null!=e&&(M(Object(e))?x.merge(n,"string"==typeof e?[e]:e):h.call(n,e)),n},inArray:function(e,t,n){var r;if(t){if(m)return m.call(t,e,n);for(r=t.length,n=n?0>n?Math.max(0,r+n):n:0;r>n;n++)if(n in t&&t[n]===e)return n}return-1},merge:function(e,n){var r=n.length,i=e.length,o=0;if("number"==typeof r)for(;r>o;o++)e[i++]=n[o];else while(n[o]!==t)e[i++]=n[o++];return e.length=i,e},grep:function(e,t,n){var r,i=[],o=0,a=e.length;for(n=!!n;a>o;o++)r=!!t(e[o],o),n!==r&&i.push(e[o]);return i},map:function(e,t,n){var r,i=0,o=e.length,a=M(e),s=[];if(a)for(;o>i;i++)r=t(e[i],i,n),null!=r&&(s[s.length]=r);else for(i in e)r=t(e[i],i,n),null!=r&&(s[s.length]=r);return d.apply([],s)},guid:1,proxy:function(e,n){var r,i,o;return"string"==typeof n&&(o=e[n],n=e,e=o),x.isFunction(e)?(r=g.call(arguments,2),i=function(){return e.apply(n||this,r.concat(g.call(arguments)))},i.guid=e.guid=e.guid||x.guid++,i):t},access:function(e,n,r,i,o,a,s){var l=0,u=e.length,c=null==r;if("object"===x.type(r)){o=!0;for(l in r)x.access(e,n,l,r[l],!0,a,s)}else if(i!==t&&(o=!0,x.isFunction(i)||(s=!0),c&&(s?(n.call(e,i),n=null):(c=n,n=function(e,t,n){return c.call(x(e),n)})),n))for(;u>l;l++)n(e[l],r,s?i:i.call(e[l],l,n(e[l],r)));return o?e:c?n.call(e):u?n(e[0],r):a},now:function(){return(new Date).getTime()},swap:function(e,t,n,r){var i,o,a={};for(o in t)a[o]=e.style[o],e.style[o]=t[o];i=n.apply(e,r||[]);for(o in t)e.style[o]=a[o];return i}}),x.ready.promise=function(t){if(!n)if(n=x.Deferred(),"complete"===a.readyState)setTimeout(x.ready);else if(a.addEventListener)a.addEventListener("DOMContentLoaded",q,!1),e.addEventListener("load",q,!1);else{a.attachEvent("onreadystatechange",q),e.attachEvent("onload",q);var r=!1;try{r=null==e.frameElement&&a.documentElement}catch(i){}r&&r.doScroll&&function o(){if(!x.isReady){try{r.doScroll("left")}catch(e){return setTimeout(o,50)}_(),x.ready()}}()}return n.promise(t)},x.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(e,t){c["[object "+t+"]"]=t.toLowerCase()});function M(e){var t=e.length,n=x.type(e);return x.isWindow(e)?!1:1===e.nodeType&&t?!0:"array"===n||"function"!==n&&(0===t||"number"==typeof t&&t>0&&t-1 in e)}r=x(a),function(e,t){var n,r,i,o,a,s,l,u,c,p,f,d,h,g,m,y,v,b="sizzle"+-new Date,w=e.document,T=0,C=0,N=st(),k=st(),E=st(),S=!1,A=function(e,t){return e===t?(S=!0,0):0},j=typeof t,D=1<<31,L={}.hasOwnProperty,H=[],q=H.pop,_=H.push,M=H.push,O=H.slice,F=H.indexOf||function(e){var t=0,n=this.length;for(;n>t;t++)if(this[t]===e)return t;return-1},B="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",P="[\\x20\\t\\r\\n\\f]",R="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",W=R.replace("w","w#"),$="\\["+P+"*("+R+")"+P+"*(?:([*^$|!~]?=)"+P+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+W+")|)|)"+P+"*\\]",I=":("+R+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+$.replace(3,8)+")*)|.*)\\)|)",z=RegExp("^"+P+"+|((?:^|[^\\\\])(?:\\\\.)*)"+P+"+$","g"),X=RegExp("^"+P+"*,"+P+"*"),U=RegExp("^"+P+"*([>+~]|"+P+")"+P+"*"),V=RegExp(P+"*[+~]"),Y=RegExp("="+P+"*([^\\]'\"]*)"+P+"*\\]","g"),J=RegExp(I),G=RegExp("^"+W+"$"),Q={ID:RegExp("^#("+R+")"),CLASS:RegExp("^\\.("+R+")"),TAG:RegExp("^("+R.replace("w","w*")+")"),ATTR:RegExp("^"+$),PSEUDO:RegExp("^"+I),CHILD:RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+P+"*(even|odd|(([+-]|)(\\d*)n|)"+P+"*(?:([+-]|)"+P+"*(\\d+)|))"+P+"*\\)|)","i"),bool:RegExp("^(?:"+B+")$","i"),needsContext:RegExp("^"+P+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+P+"*((?:-\\d)?\\d*)"+P+"*\\)|)(?=[^-]|$)","i")},K=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,et=/^(?:input|select|textarea|button)$/i,tt=/^h\d$/i,nt=/'|\\/g,rt=RegExp("\\\\([\\da-f]{1,6}"+P+"?|("+P+")|.)","ig"),it=function(e,t,n){var r="0x"+t-65536;return r!==r||n?t:0>r?String.fromCharCode(r+65536):String.fromCharCode(55296|r>>10,56320|1023&r)};try{M.apply(H=O.call(w.childNodes),w.childNodes),H[w.childNodes.length].nodeType}catch(ot){M={apply:H.length?function(e,t){_.apply(e,O.call(t))}:function(e,t){var n=e.length,r=0;while(e[n++]=t[r++]);e.length=n-1}}}function at(e,t,n,i){var o,a,s,l,u,c,d,m,y,x;if((t?t.ownerDocument||t:w)!==f&&p(t),t=t||f,n=n||[],!e||"string"!=typeof e)return n;if(1!==(l=t.nodeType)&&9!==l)return[];if(h&&!i){if(o=Z.exec(e))if(s=o[1]){if(9===l){if(a=t.getElementById(s),!a||!a.parentNode)return n;if(a.id===s)return n.push(a),n}else if(t.ownerDocument&&(a=t.ownerDocument.getElementById(s))&&v(t,a)&&a.id===s)return n.push(a),n}else{if(o[2])return M.apply(n,t.getElementsByTagName(e)),n;if((s=o[3])&&r.getElementsByClassName&&t.getElementsByClassName)return M.apply(n,t.getElementsByClassName(s)),n}if(r.qsa&&(!g||!g.test(e))){if(m=d=b,y=t,x=9===l&&e,1===l&&"object"!==t.nodeName.toLowerCase()){c=mt(e),(d=t.getAttribute("id"))?m=d.replace(nt,"\\$&"):t.setAttribute("id",m),m="[id='"+m+"'] ",u=c.length;while(u--)c[u]=m+yt(c[u]);y=V.test(e)&&t.parentNode||t,x=c.join(",")}if(x)try{return M.apply(n,y.querySelectorAll(x)),n}catch(T){}finally{d||t.removeAttribute("id")}}}return kt(e.replace(z,"$1"),t,n,i)}function st(){var e=[];function t(n,r){return e.push(n+=" ")>o.cacheLength&&delete t[e.shift()],t[n]=r}return t}function lt(e){return e[b]=!0,e}function ut(e){var t=f.createElement("div");try{return!!e(t)}catch(n){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function ct(e,t){var n=e.split("|"),r=e.length;while(r--)o.attrHandle[n[r]]=t}function pt(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&(~t.sourceIndex||D)-(~e.sourceIndex||D);if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function ft(e){return function(t){var n=t.nodeName.toLowerCase();return"input"===n&&t.type===e}}function dt(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}function ht(e){return lt(function(t){return t=+t,lt(function(n,r){var i,o=e([],n.length,t),a=o.length;while(a--)n[i=o[a]]&&(n[i]=!(r[i]=n[i]))})})}s=at.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?"HTML"!==t.nodeName:!1},r=at.support={},p=at.setDocument=function(e){var n=e?e.ownerDocument||e:w,i=n.defaultView;return n!==f&&9===n.nodeType&&n.documentElement?(f=n,d=n.documentElement,h=!s(n),i&&i.attachEvent&&i!==i.top&&i.attachEvent("onbeforeunload",function(){p()}),r.attributes=ut(function(e){return e.className="i",!e.getAttribute("className")}),r.getElementsByTagName=ut(function(e){return e.appendChild(n.createComment("")),!e.getElementsByTagName("*").length}),r.getElementsByClassName=ut(function(e){return e.innerHTML="<div class='a'></div><div class='a i'></div>",e.firstChild.className="i",2===e.getElementsByClassName("i").length}),r.getById=ut(function(e){return d.appendChild(e).id=b,!n.getElementsByName||!n.getElementsByName(b).length}),r.getById?(o.find.ID=function(e,t){if(typeof t.getElementById!==j&&h){var n=t.getElementById(e);return n&&n.parentNode?[n]:[]}},o.filter.ID=function(e){var t=e.replace(rt,it);return function(e){return e.getAttribute("id")===t}}):(delete o.find.ID,o.filter.ID=function(e){var t=e.replace(rt,it);return function(e){var n=typeof e.getAttributeNode!==j&&e.getAttributeNode("id");return n&&n.value===t}}),o.find.TAG=r.getElementsByTagName?function(e,n){return typeof n.getElementsByTagName!==j?n.getElementsByTagName(e):t}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},o.find.CLASS=r.getElementsByClassName&&function(e,n){return typeof n.getElementsByClassName!==j&&h?n.getElementsByClassName(e):t},m=[],g=[],(r.qsa=K.test(n.querySelectorAll))&&(ut(function(e){e.innerHTML="<select><option selected=''></option></select>",e.querySelectorAll("[selected]").length||g.push("\\["+P+"*(?:value|"+B+")"),e.querySelectorAll(":checked").length||g.push(":checked")}),ut(function(e){var t=n.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("t",""),e.querySelectorAll("[t^='']").length&&g.push("[*^$]="+P+"*(?:''|\"\")"),e.querySelectorAll(":enabled").length||g.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),g.push(",.*:")})),(r.matchesSelector=K.test(y=d.webkitMatchesSelector||d.mozMatchesSelector||d.oMatchesSelector||d.msMatchesSelector))&&ut(function(e){r.disconnectedMatch=y.call(e,"div"),y.call(e,"[s!='']:x"),m.push("!=",I)}),g=g.length&&RegExp(g.join("|")),m=m.length&&RegExp(m.join("|")),v=K.test(d.contains)||d.compareDocumentPosition?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},A=d.compareDocumentPosition?function(e,t){if(e===t)return S=!0,0;var i=t.compareDocumentPosition&&e.compareDocumentPosition&&e.compareDocumentPosition(t);return i?1&i||!r.sortDetached&&t.compareDocumentPosition(e)===i?e===n||v(w,e)?-1:t===n||v(w,t)?1:c?F.call(c,e)-F.call(c,t):0:4&i?-1:1:e.compareDocumentPosition?-1:1}:function(e,t){var r,i=0,o=e.parentNode,a=t.parentNode,s=[e],l=[t];if(e===t)return S=!0,0;if(!o||!a)return e===n?-1:t===n?1:o?-1:a?1:c?F.call(c,e)-F.call(c,t):0;if(o===a)return pt(e,t);r=e;while(r=r.parentNode)s.unshift(r);r=t;while(r=r.parentNode)l.unshift(r);while(s[i]===l[i])i++;return i?pt(s[i],l[i]):s[i]===w?-1:l[i]===w?1:0},n):f},at.matches=function(e,t){return at(e,null,null,t)},at.matchesSelector=function(e,t){if((e.ownerDocument||e)!==f&&p(e),t=t.replace(Y,"='$1']"),!(!r.matchesSelector||!h||m&&m.test(t)||g&&g.test(t)))try{var n=y.call(e,t);if(n||r.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(i){}return at(t,f,null,[e]).length>0},at.contains=function(e,t){return(e.ownerDocument||e)!==f&&p(e),v(e,t)},at.attr=function(e,n){(e.ownerDocument||e)!==f&&p(e);var i=o.attrHandle[n.toLowerCase()],a=i&&L.call(o.attrHandle,n.toLowerCase())?i(e,n,!h):t;return a===t?r.attributes||!h?e.getAttribute(n):(a=e.getAttributeNode(n))&&a.specified?a.value:null:a},at.error=function(e){throw Error("Syntax error, unrecognized expression: "+e)},at.uniqueSort=function(e){var t,n=[],i=0,o=0;if(S=!r.detectDuplicates,c=!r.sortStable&&e.slice(0),e.sort(A),S){while(t=e[o++])t===e[o]&&(i=n.push(o));while(i--)e.splice(n[i],1)}return e},a=at.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(1===i||9===i||11===i){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=a(e)}else if(3===i||4===i)return e.nodeValue}else for(;t=e[r];r++)n+=a(t);return n},o=at.selectors={cacheLength:50,createPseudo:lt,match:Q,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(rt,it),e[3]=(e[4]||e[5]||"").replace(rt,it),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||at.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&at.error(e[0]),e},PSEUDO:function(e){var n,r=!e[5]&&e[2];return Q.CHILD.test(e[0])?null:(e[3]&&e[4]!==t?e[2]=e[4]:r&&J.test(r)&&(n=mt(r,!0))&&(n=r.indexOf(")",r.length-n)-r.length)&&(e[0]=e[0].slice(0,n),e[2]=r.slice(0,n)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(rt,it).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=N[e+" "];return t||(t=RegExp("(^|"+P+")"+e+"("+P+"|$)"))&&N(e,function(e){return t.test("string"==typeof e.className&&e.className||typeof e.getAttribute!==j&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r){var i=at.attr(r,e);return null==i?"!="===t:t?(i+="","="===t?i===n:"!="===t?i!==n:"^="===t?n&&0===i.indexOf(n):"*="===t?n&&i.indexOf(n)>-1:"$="===t?n&&i.slice(-n.length)===n:"~="===t?(" "+i+" ").indexOf(n)>-1:"|="===t?i===n||i.slice(0,n.length+1)===n+"-":!1):!0}},CHILD:function(e,t,n,r,i){var o="nth"!==e.slice(0,3),a="last"!==e.slice(-4),s="of-type"===t;return 1===r&&0===i?function(e){return!!e.parentNode}:function(t,n,l){var u,c,p,f,d,h,g=o!==a?"nextSibling":"previousSibling",m=t.parentNode,y=s&&t.nodeName.toLowerCase(),v=!l&&!s;if(m){if(o){while(g){p=t;while(p=p[g])if(s?p.nodeName.toLowerCase()===y:1===p.nodeType)return!1;h=g="only"===e&&!h&&"nextSibling"}return!0}if(h=[a?m.firstChild:m.lastChild],a&&v){c=m[b]||(m[b]={}),u=c[e]||[],d=u[0]===T&&u[1],f=u[0]===T&&u[2],p=d&&m.childNodes[d];while(p=++d&&p&&p[g]||(f=d=0)||h.pop())if(1===p.nodeType&&++f&&p===t){c[e]=[T,d,f];break}}else if(v&&(u=(t[b]||(t[b]={}))[e])&&u[0]===T)f=u[1];else while(p=++d&&p&&p[g]||(f=d=0)||h.pop())if((s?p.nodeName.toLowerCase()===y:1===p.nodeType)&&++f&&(v&&((p[b]||(p[b]={}))[e]=[T,f]),p===t))break;return f-=i,f===r||0===f%r&&f/r>=0}}},PSEUDO:function(e,t){var n,r=o.pseudos[e]||o.setFilters[e.toLowerCase()]||at.error("unsupported pseudo: "+e);return r[b]?r(t):r.length>1?(n=[e,e,"",t],o.setFilters.hasOwnProperty(e.toLowerCase())?lt(function(e,n){var i,o=r(e,t),a=o.length;while(a--)i=F.call(e,o[a]),e[i]=!(n[i]=o[a])}):function(e){return r(e,0,n)}):r}},pseudos:{not:lt(function(e){var t=[],n=[],r=l(e.replace(z,"$1"));return r[b]?lt(function(e,t,n,i){var o,a=r(e,null,i,[]),s=e.length;while(s--)(o=a[s])&&(e[s]=!(t[s]=o))}):function(e,i,o){return t[0]=e,r(t,null,o,n),!n.pop()}}),has:lt(function(e){return function(t){return at(e,t).length>0}}),contains:lt(function(e){return function(t){return(t.textContent||t.innerText||a(t)).indexOf(e)>-1}}),lang:lt(function(e){return G.test(e||"")||at.error("unsupported lang: "+e),e=e.replace(rt,it).toLowerCase(),function(t){var n;do if(n=h?t.lang:t.getAttribute("xml:lang")||t.getAttribute("lang"))return n=n.toLowerCase(),n===e||0===n.indexOf(e+"-");while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(t){var n=e.location&&e.location.hash;return n&&n.slice(1)===t.id},root:function(e){return e===d},focus:function(e){return e===f.activeElement&&(!f.hasFocus||f.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeName>"@"||3===e.nodeType||4===e.nodeType)return!1;return!0},parent:function(e){return!o.pseudos.empty(e)},header:function(e){return tt.test(e.nodeName)},input:function(e){return et.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||t.toLowerCase()===e.type)},first:ht(function(){return[0]}),last:ht(function(e,t){return[t-1]}),eq:ht(function(e,t,n){return[0>n?n+t:n]}),even:ht(function(e,t){var n=0;for(;t>n;n+=2)e.push(n);return e}),odd:ht(function(e,t){var n=1;for(;t>n;n+=2)e.push(n);return e}),lt:ht(function(e,t,n){var r=0>n?n+t:n;for(;--r>=0;)e.push(r);return e}),gt:ht(function(e,t,n){var r=0>n?n+t:n;for(;t>++r;)e.push(r);return e})}},o.pseudos.nth=o.pseudos.eq;for(n in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})o.pseudos[n]=ft(n);for(n in{submit:!0,reset:!0})o.pseudos[n]=dt(n);function gt(){}gt.prototype=o.filters=o.pseudos,o.setFilters=new gt;function mt(e,t){var n,r,i,a,s,l,u,c=k[e+" "];if(c)return t?0:c.slice(0);s=e,l=[],u=o.preFilter;while(s){(!n||(r=X.exec(s)))&&(r&&(s=s.slice(r[0].length)||s),l.push(i=[])),n=!1,(r=U.exec(s))&&(n=r.shift(),i.push({value:n,type:r[0].replace(z," ")}),s=s.slice(n.length));for(a in o.filter)!(r=Q[a].exec(s))||u[a]&&!(r=u[a](r))||(n=r.shift(),i.push({value:n,type:a,matches:r}),s=s.slice(n.length));if(!n)break}return t?s.length:s?at.error(e):k(e,l).slice(0)}function yt(e){var t=0,n=e.length,r="";for(;n>t;t++)r+=e[t].value;return r}function vt(e,t,n){var r=t.dir,o=n&&"parentNode"===r,a=C++;return t.first?function(t,n,i){while(t=t[r])if(1===t.nodeType||o)return e(t,n,i)}:function(t,n,s){var l,u,c,p=T+" "+a;if(s){while(t=t[r])if((1===t.nodeType||o)&&e(t,n,s))return!0}else while(t=t[r])if(1===t.nodeType||o)if(c=t[b]||(t[b]={}),(u=c[r])&&u[0]===p){if((l=u[1])===!0||l===i)return l===!0}else if(u=c[r]=[p],u[1]=e(t,n,s)||i,u[1]===!0)return!0}}function bt(e){return e.length>1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function xt(e,t,n,r,i){var o,a=[],s=0,l=e.length,u=null!=t;for(;l>s;s++)(o=e[s])&&(!n||n(o,r,i))&&(a.push(o),u&&t.push(s));return a}function wt(e,t,n,r,i,o){return r&&!r[b]&&(r=wt(r)),i&&!i[b]&&(i=wt(i,o)),lt(function(o,a,s,l){var u,c,p,f=[],d=[],h=a.length,g=o||Nt(t||"*",s.nodeType?[s]:s,[]),m=!e||!o&&t?g:xt(g,f,e,s,l),y=n?i||(o?e:h||r)?[]:a:m;if(n&&n(m,y,s,l),r){u=xt(y,d),r(u,[],s,l),c=u.length;while(c--)(p=u[c])&&(y[d[c]]=!(m[d[c]]=p))}if(o){if(i||e){if(i){u=[],c=y.length;while(c--)(p=y[c])&&u.push(m[c]=p);i(null,y=[],u,l)}c=y.length;while(c--)(p=y[c])&&(u=i?F.call(o,p):f[c])>-1&&(o[u]=!(a[u]=p))}}else y=xt(y===a?y.splice(h,y.length):y),i?i(null,a,y,l):M.apply(a,y)})}function Tt(e){var t,n,r,i=e.length,a=o.relative[e[0].type],s=a||o.relative[" "],l=a?1:0,c=vt(function(e){return e===t},s,!0),p=vt(function(e){return F.call(t,e)>-1},s,!0),f=[function(e,n,r){return!a&&(r||n!==u)||((t=n).nodeType?c(e,n,r):p(e,n,r))}];for(;i>l;l++)if(n=o.relative[e[l].type])f=[vt(bt(f),n)];else{if(n=o.filter[e[l].type].apply(null,e[l].matches),n[b]){for(r=++l;i>r;r++)if(o.relative[e[r].type])break;return wt(l>1&&bt(f),l>1&&yt(e.slice(0,l-1).concat({value:" "===e[l-2].type?"*":""})).replace(z,"$1"),n,r>l&&Tt(e.slice(l,r)),i>r&&Tt(e=e.slice(r)),i>r&&yt(e))}f.push(n)}return bt(f)}function Ct(e,t){var n=0,r=t.length>0,a=e.length>0,s=function(s,l,c,p,d){var h,g,m,y=[],v=0,b="0",x=s&&[],w=null!=d,C=u,N=s||a&&o.find.TAG("*",d&&l.parentNode||l),k=T+=null==C?1:Math.random()||.1;for(w&&(u=l!==f&&l,i=n);null!=(h=N[b]);b++){if(a&&h){g=0;while(m=e[g++])if(m(h,l,c)){p.push(h);break}w&&(T=k,i=++n)}r&&((h=!m&&h)&&v--,s&&x.push(h))}if(v+=b,r&&b!==v){g=0;while(m=t[g++])m(x,y,l,c);if(s){if(v>0)while(b--)x[b]||y[b]||(y[b]=q.call(p));y=xt(y)}M.apply(p,y),w&&!s&&y.length>0&&v+t.length>1&&at.uniqueSort(p)}return w&&(T=k,u=C),x};return r?lt(s):s}l=at.compile=function(e,t){var n,r=[],i=[],o=E[e+" "];if(!o){t||(t=mt(e)),n=t.length;while(n--)o=Tt(t[n]),o[b]?r.push(o):i.push(o);o=E(e,Ct(i,r))}return o};function Nt(e,t,n){var r=0,i=t.length;for(;i>r;r++)at(e,t[r],n);return n}function kt(e,t,n,i){var a,s,u,c,p,f=mt(e);if(!i&&1===f.length){if(s=f[0]=f[0].slice(0),s.length>2&&"ID"===(u=s[0]).type&&r.getById&&9===t.nodeType&&h&&o.relative[s[1].type]){if(t=(o.find.ID(u.matches[0].replace(rt,it),t)||[])[0],!t)return n;e=e.slice(s.shift().value.length)}a=Q.needsContext.test(e)?0:s.length;while(a--){if(u=s[a],o.relative[c=u.type])break;if((p=o.find[c])&&(i=p(u.matches[0].replace(rt,it),V.test(s[0].type)&&t.parentNode||t))){if(s.splice(a,1),e=i.length&&yt(s),!e)return M.apply(n,i),n;break}}}return l(e,f)(i,t,!h,n,V.test(e)),n}r.sortStable=b.split("").sort(A).join("")===b,r.detectDuplicates=S,p(),r.sortDetached=ut(function(e){return 1&e.compareDocumentPosition(f.createElement("div"))}),ut(function(e){return e.innerHTML="<a href='#'></a>","#"===e.firstChild.getAttribute("href")})||ct("type|href|height|width",function(e,n,r){return r?t:e.getAttribute(n,"type"===n.toLowerCase()?1:2)}),r.attributes&&ut(function(e){return e.innerHTML="<input/>",e.firstChild.setAttribute("value",""),""===e.firstChild.getAttribute("value")})||ct("value",function(e,n,r){return r||"input"!==e.nodeName.toLowerCase()?t:e.defaultValue}),ut(function(e){return null==e.getAttribute("disabled")})||ct(B,function(e,n,r){var i;return r?t:(i=e.getAttributeNode(n))&&i.specified?i.value:e[n]===!0?n.toLowerCase():null}),x.find=at,x.expr=at.selectors,x.expr[":"]=x.expr.pseudos,x.unique=at.uniqueSort,x.text=at.getText,x.isXMLDoc=at.isXML,x.contains=at.contains}(e);var O={};function F(e){var t=O[e]={};return x.each(e.match(T)||[],function(e,n){t[n]=!0}),t}x.Callbacks=function(e){e="string"==typeof e?O[e]||F(e):x.extend({},e);var n,r,i,o,a,s,l=[],u=!e.once&&[],c=function(t){for(r=e.memory&&t,i=!0,a=s||0,s=0,o=l.length,n=!0;l&&o>a;a++)if(l[a].apply(t[0],t[1])===!1&&e.stopOnFalse){r=!1;break}n=!1,l&&(u?u.length&&c(u.shift()):r?l=[]:p.disable())},p={add:function(){if(l){var t=l.length;(function i(t){x.each(t,function(t,n){var r=x.type(n);"function"===r?e.unique&&p.has(n)||l.push(n):n&&n.length&&"string"!==r&&i(n)})})(arguments),n?o=l.length:r&&(s=t,c(r))}return this},remove:function(){return l&&x.each(arguments,function(e,t){var r;while((r=x.inArray(t,l,r))>-1)l.splice(r,1),n&&(o>=r&&o--,a>=r&&a--)}),this},has:function(e){return e?x.inArray(e,l)>-1:!(!l||!l.length)},empty:function(){return l=[],o=0,this},disable:function(){return l=u=r=t,this},disabled:function(){return!l},lock:function(){return u=t,r||p.disable(),this},locked:function(){return!u},fireWith:function(e,t){return!l||i&&!u||(t=t||[],t=[e,t.slice?t.slice():t],n?u.push(t):c(t)),this},fire:function(){return p.fireWith(this,arguments),this},fired:function(){return!!i}};return p},x.extend({Deferred:function(e){var t=[["resolve","done",x.Callbacks("once memory"),"resolved"],["reject","fail",x.Callbacks("once memory"),"rejected"],["notify","progress",x.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return x.Deferred(function(n){x.each(t,function(t,o){var a=o[0],s=x.isFunction(e[t])&&e[t];i[o[1]](function(){var e=s&&s.apply(this,arguments);e&&x.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[a+"With"](this===r?n.promise():this,s?[e]:arguments)})}),e=null}).promise()},promise:function(e){return null!=e?x.extend(e,r):r}},i={};return r.pipe=r.then,x.each(t,function(e,o){var a=o[2],s=o[3];r[o[1]]=a.add,s&&a.add(function(){n=s},t[1^e][2].disable,t[2][2].lock),i[o[0]]=function(){return i[o[0]+"With"](this===i?r:this,arguments),this},i[o[0]+"With"]=a.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t=0,n=g.call(arguments),r=n.length,i=1!==r||e&&x.isFunction(e.promise)?r:0,o=1===i?e:x.Deferred(),a=function(e,t,n){return function(r){t[e]=this,n[e]=arguments.length>1?g.call(arguments):r,n===s?o.notifyWith(t,n):--i||o.resolveWith(t,n)}},s,l,u;if(r>1)for(s=Array(r),l=Array(r),u=Array(r);r>t;t++)n[t]&&x.isFunction(n[t].promise)?n[t].promise().done(a(t,u,n)).fail(o.reject).progress(a(t,l,s)):--i;return i||o.resolveWith(u,n),o.promise()}}),x.support=function(t){var n,r,o,s,l,u,c,p,f,d=a.createElement("div");if(d.setAttribute("className","t"),d.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",n=d.getElementsByTagName("*")||[],r=d.getElementsByTagName("a")[0],!r||!r.style||!n.length)return t;s=a.createElement("select"),u=s.appendChild(a.createElement("option")),o=d.getElementsByTagName("input")[0],r.style.cssText="top:1px;float:left;opacity:.5",t.getSetAttribute="t"!==d.className,t.leadingWhitespace=3===d.firstChild.nodeType,t.tbody=!d.getElementsByTagName("tbody").length,t.htmlSerialize=!!d.getElementsByTagName("link").length,t.style=/top/.test(r.getAttribute("style")),t.hrefNormalized="/a"===r.getAttribute("href"),t.opacity=/^0.5/.test(r.style.opacity),t.cssFloat=!!r.style.cssFloat,t.checkOn=!!o.value,t.optSelected=u.selected,t.enctype=!!a.createElement("form").enctype,t.html5Clone="<:nav></:nav>"!==a.createElement("nav").cloneNode(!0).outerHTML,t.inlineBlockNeedsLayout=!1,t.shrinkWrapBlocks=!1,t.pixelPosition=!1,t.deleteExpando=!0,t.noCloneEvent=!0,t.reliableMarginRight=!0,t.boxSizingReliable=!0,o.checked=!0,t.noCloneChecked=o.cloneNode(!0).checked,s.disabled=!0,t.optDisabled=!u.disabled;try{delete d.test}catch(h){t.deleteExpando=!1}o=a.createElement("input"),o.setAttribute("value",""),t.input=""===o.getAttribute("value"),o.value="t",o.setAttribute("type","radio"),t.radioValue="t"===o.value,o.setAttribute("checked","t"),o.setAttribute("name","t"),l=a.createDocumentFragment(),l.appendChild(o),t.appendChecked=o.checked,t.checkClone=l.cloneNode(!0).cloneNode(!0).lastChild.checked,d.attachEvent&&(d.attachEvent("onclick",function(){t.noCloneEvent=!1}),d.cloneNode(!0).click());for(f in{submit:!0,change:!0,focusin:!0})d.setAttribute(c="on"+f,"t"),t[f+"Bubbles"]=c in e||d.attributes[c].expando===!1;d.style.backgroundClip="content-box",d.cloneNode(!0).style.backgroundClip="",t.clearCloneStyle="content-box"===d.style.backgroundClip;for(f in x(t))break;return t.ownLast="0"!==f,x(function(){var n,r,o,s="padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;",l=a.getElementsByTagName("body")[0];l&&(n=a.createElement("div"),n.style.cssText="border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px",l.appendChild(n).appendChild(d),d.innerHTML="<table><tr><td></td><td>t</td></tr></table>",o=d.getElementsByTagName("td"),o[0].style.cssText="padding:0;margin:0;border:0;display:none",p=0===o[0].offsetHeight,o[0].style.display="",o[1].style.display="none",t.reliableHiddenOffsets=p&&0===o[0].offsetHeight,d.innerHTML="",d.style.cssText="box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;",x.swap(l,null!=l.style.zoom?{zoom:1}:{},function(){t.boxSizing=4===d.offsetWidth}),e.getComputedStyle&&(t.pixelPosition="1%"!==(e.getComputedStyle(d,null)||{}).top,t.boxSizingReliable="4px"===(e.getComputedStyle(d,null)||{width:"4px"}).width,r=d.appendChild(a.createElement("div")),r.style.cssText=d.style.cssText=s,r.style.marginRight=r.style.width="0",d.style.width="1px",t.reliableMarginRight=!parseFloat((e.getComputedStyle(r,null)||{}).marginRight)),typeof d.style.zoom!==i&&(d.innerHTML="",d.style.cssText=s+"width:1px;padding:1px;display:inline;zoom:1",t.inlineBlockNeedsLayout=3===d.offsetWidth,d.style.display="block",d.innerHTML="<div></div>",d.firstChild.style.width="5px",t.shrinkWrapBlocks=3!==d.offsetWidth,t.inlineBlockNeedsLayout&&(l.style.zoom=1)),l.removeChild(n),n=d=o=r=null)}),n=s=l=u=r=o=null,t }({});var B=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,P=/([A-Z])/g;function R(e,n,r,i){if(x.acceptData(e)){var o,a,s=x.expando,l=e.nodeType,u=l?x.cache:e,c=l?e[s]:e[s]&&s;if(c&&u[c]&&(i||u[c].data)||r!==t||"string"!=typeof n)return c||(c=l?e[s]=p.pop()||x.guid++:s),u[c]||(u[c]=l?{}:{toJSON:x.noop}),("object"==typeof n||"function"==typeof n)&&(i?u[c]=x.extend(u[c],n):u[c].data=x.extend(u[c].data,n)),a=u[c],i||(a.data||(a.data={}),a=a.data),r!==t&&(a[x.camelCase(n)]=r),"string"==typeof n?(o=a[n],null==o&&(o=a[x.camelCase(n)])):o=a,o}}function W(e,t,n){if(x.acceptData(e)){var r,i,o=e.nodeType,a=o?x.cache:e,s=o?e[x.expando]:x.expando;if(a[s]){if(t&&(r=n?a[s]:a[s].data)){x.isArray(t)?t=t.concat(x.map(t,x.camelCase)):t in r?t=[t]:(t=x.camelCase(t),t=t in r?[t]:t.split(" ")),i=t.length;while(i--)delete r[t[i]];if(n?!I(r):!x.isEmptyObject(r))return}(n||(delete a[s].data,I(a[s])))&&(o?x.cleanData([e],!0):x.support.deleteExpando||a!=a.window?delete a[s]:a[s]=null)}}}x.extend({cache:{},noData:{applet:!0,embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(e){return e=e.nodeType?x.cache[e[x.expando]]:e[x.expando],!!e&&!I(e)},data:function(e,t,n){return R(e,t,n)},removeData:function(e,t){return W(e,t)},_data:function(e,t,n){return R(e,t,n,!0)},_removeData:function(e,t){return W(e,t,!0)},acceptData:function(e){if(e.nodeType&&1!==e.nodeType&&9!==e.nodeType)return!1;var t=e.nodeName&&x.noData[e.nodeName.toLowerCase()];return!t||t!==!0&&e.getAttribute("classid")===t}}),x.fn.extend({data:function(e,n){var r,i,o=null,a=0,s=this[0];if(e===t){if(this.length&&(o=x.data(s),1===s.nodeType&&!x._data(s,"parsedAttrs"))){for(r=s.attributes;r.length>a;a++)i=r[a].name,0===i.indexOf("data-")&&(i=x.camelCase(i.slice(5)),$(s,i,o[i]));x._data(s,"parsedAttrs",!0)}return o}return"object"==typeof e?this.each(function(){x.data(this,e)}):arguments.length>1?this.each(function(){x.data(this,e,n)}):s?$(s,e,x.data(s,e)):null},removeData:function(e){return this.each(function(){x.removeData(this,e)})}});function $(e,n,r){if(r===t&&1===e.nodeType){var i="data-"+n.replace(P,"-$1").toLowerCase();if(r=e.getAttribute(i),"string"==typeof r){try{r="true"===r?!0:"false"===r?!1:"null"===r?null:+r+""===r?+r:B.test(r)?x.parseJSON(r):r}catch(o){}x.data(e,n,r)}else r=t}return r}function I(e){var t;for(t in e)if(("data"!==t||!x.isEmptyObject(e[t]))&&"toJSON"!==t)return!1;return!0}x.extend({queue:function(e,n,r){var i;return e?(n=(n||"fx")+"queue",i=x._data(e,n),r&&(!i||x.isArray(r)?i=x._data(e,n,x.makeArray(r)):i.push(r)),i||[]):t},dequeue:function(e,t){t=t||"fx";var n=x.queue(e,t),r=n.length,i=n.shift(),o=x._queueHooks(e,t),a=function(){x.dequeue(e,t)};"inprogress"===i&&(i=n.shift(),r--),i&&("fx"===t&&n.unshift("inprogress"),delete o.stop,i.call(e,a,o)),!r&&o&&o.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return x._data(e,n)||x._data(e,n,{empty:x.Callbacks("once memory").add(function(){x._removeData(e,t+"queue"),x._removeData(e,n)})})}}),x.fn.extend({queue:function(e,n){var r=2;return"string"!=typeof e&&(n=e,e="fx",r--),r>arguments.length?x.queue(this[0],e):n===t?this:this.each(function(){var t=x.queue(this,e,n);x._queueHooks(this,e),"fx"===e&&"inprogress"!==t[0]&&x.dequeue(this,e)})},dequeue:function(e){return this.each(function(){x.dequeue(this,e)})},delay:function(e,t){return e=x.fx?x.fx.speeds[e]||e:e,t=t||"fx",this.queue(t,function(t,n){var r=setTimeout(t,e);n.stop=function(){clearTimeout(r)}})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,n){var r,i=1,o=x.Deferred(),a=this,s=this.length,l=function(){--i||o.resolveWith(a,[a])};"string"!=typeof e&&(n=e,e=t),e=e||"fx";while(s--)r=x._data(a[s],e+"queueHooks"),r&&r.empty&&(i++,r.empty.add(l));return l(),o.promise(n)}});var z,X,U=/[\t\r\n\f]/g,V=/\r/g,Y=/^(?:input|select|textarea|button|object)$/i,J=/^(?:a|area)$/i,G=/^(?:checked|selected)$/i,Q=x.support.getSetAttribute,K=x.support.input;x.fn.extend({attr:function(e,t){return x.access(this,x.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){x.removeAttr(this,e)})},prop:function(e,t){return x.access(this,x.prop,e,t,arguments.length>1)},removeProp:function(e){return e=x.propFix[e]||e,this.each(function(){try{this[e]=t,delete this[e]}catch(n){}})},addClass:function(e){var t,n,r,i,o,a=0,s=this.length,l="string"==typeof e&&e;if(x.isFunction(e))return this.each(function(t){x(this).addClass(e.call(this,t,this.className))});if(l)for(t=(e||"").match(T)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(U," "):" ")){o=0;while(i=t[o++])0>r.indexOf(" "+i+" ")&&(r+=i+" ");n.className=x.trim(r)}return this},removeClass:function(e){var t,n,r,i,o,a=0,s=this.length,l=0===arguments.length||"string"==typeof e&&e;if(x.isFunction(e))return this.each(function(t){x(this).removeClass(e.call(this,t,this.className))});if(l)for(t=(e||"").match(T)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(U," "):"")){o=0;while(i=t[o++])while(r.indexOf(" "+i+" ")>=0)r=r.replace(" "+i+" "," ");n.className=e?x.trim(r):""}return this},toggleClass:function(e,t){var n=typeof e;return"boolean"==typeof t&&"string"===n?t?this.addClass(e):this.removeClass(e):x.isFunction(e)?this.each(function(n){x(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if("string"===n){var t,r=0,o=x(this),a=e.match(T)||[];while(t=a[r++])o.hasClass(t)?o.removeClass(t):o.addClass(t)}else(n===i||"boolean"===n)&&(this.className&&x._data(this,"__className__",this.className),this.className=this.className||e===!1?"":x._data(this,"__className__")||"")})},hasClass:function(e){var t=" "+e+" ",n=0,r=this.length;for(;r>n;n++)if(1===this[n].nodeType&&(" "+this[n].className+" ").replace(U," ").indexOf(t)>=0)return!0;return!1},val:function(e){var n,r,i,o=this[0];{if(arguments.length)return i=x.isFunction(e),this.each(function(n){var o;1===this.nodeType&&(o=i?e.call(this,n,x(this).val()):e,null==o?o="":"number"==typeof o?o+="":x.isArray(o)&&(o=x.map(o,function(e){return null==e?"":e+""})),r=x.valHooks[this.type]||x.valHooks[this.nodeName.toLowerCase()],r&&"set"in r&&r.set(this,o,"value")!==t||(this.value=o))});if(o)return r=x.valHooks[o.type]||x.valHooks[o.nodeName.toLowerCase()],r&&"get"in r&&(n=r.get(o,"value"))!==t?n:(n=o.value,"string"==typeof n?n.replace(V,""):null==n?"":n)}}}),x.extend({valHooks:{option:{get:function(e){var t=x.find.attr(e,"value");return null!=t?t:e.text}},select:{get:function(e){var t,n,r=e.options,i=e.selectedIndex,o="select-one"===e.type||0>i,a=o?null:[],s=o?i+1:r.length,l=0>i?s:o?i:0;for(;s>l;l++)if(n=r[l],!(!n.selected&&l!==i||(x.support.optDisabled?n.disabled:null!==n.getAttribute("disabled"))||n.parentNode.disabled&&x.nodeName(n.parentNode,"optgroup"))){if(t=x(n).val(),o)return t;a.push(t)}return a},set:function(e,t){var n,r,i=e.options,o=x.makeArray(t),a=i.length;while(a--)r=i[a],(r.selected=x.inArray(x(r).val(),o)>=0)&&(n=!0);return n||(e.selectedIndex=-1),o}}},attr:function(e,n,r){var o,a,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return typeof e.getAttribute===i?x.prop(e,n,r):(1===s&&x.isXMLDoc(e)||(n=n.toLowerCase(),o=x.attrHooks[n]||(x.expr.match.bool.test(n)?X:z)),r===t?o&&"get"in o&&null!==(a=o.get(e,n))?a:(a=x.find.attr(e,n),null==a?t:a):null!==r?o&&"set"in o&&(a=o.set(e,r,n))!==t?a:(e.setAttribute(n,r+""),r):(x.removeAttr(e,n),t))},removeAttr:function(e,t){var n,r,i=0,o=t&&t.match(T);if(o&&1===e.nodeType)while(n=o[i++])r=x.propFix[n]||n,x.expr.match.bool.test(n)?K&&Q||!G.test(n)?e[r]=!1:e[x.camelCase("default-"+n)]=e[r]=!1:x.attr(e,n,""),e.removeAttribute(Q?n:r)},attrHooks:{type:{set:function(e,t){if(!x.support.radioValue&&"radio"===t&&x.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}},propFix:{"for":"htmlFor","class":"className"},prop:function(e,n,r){var i,o,a,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return a=1!==s||!x.isXMLDoc(e),a&&(n=x.propFix[n]||n,o=x.propHooks[n]),r!==t?o&&"set"in o&&(i=o.set(e,r,n))!==t?i:e[n]=r:o&&"get"in o&&null!==(i=o.get(e,n))?i:e[n]},propHooks:{tabIndex:{get:function(e){var t=x.find.attr(e,"tabindex");return t?parseInt(t,10):Y.test(e.nodeName)||J.test(e.nodeName)&&e.href?0:-1}}}}),X={set:function(e,t,n){return t===!1?x.removeAttr(e,n):K&&Q||!G.test(n)?e.setAttribute(!Q&&x.propFix[n]||n,n):e[x.camelCase("default-"+n)]=e[n]=!0,n}},x.each(x.expr.match.bool.source.match(/\w+/g),function(e,n){var r=x.expr.attrHandle[n]||x.find.attr;x.expr.attrHandle[n]=K&&Q||!G.test(n)?function(e,n,i){var o=x.expr.attrHandle[n],a=i?t:(x.expr.attrHandle[n]=t)!=r(e,n,i)?n.toLowerCase():null;return x.expr.attrHandle[n]=o,a}:function(e,n,r){return r?t:e[x.camelCase("default-"+n)]?n.toLowerCase():null}}),K&&Q||(x.attrHooks.value={set:function(e,n,r){return x.nodeName(e,"input")?(e.defaultValue=n,t):z&&z.set(e,n,r)}}),Q||(z={set:function(e,n,r){var i=e.getAttributeNode(r);return i||e.setAttributeNode(i=e.ownerDocument.createAttribute(r)),i.value=n+="","value"===r||n===e.getAttribute(r)?n:t}},x.expr.attrHandle.id=x.expr.attrHandle.name=x.expr.attrHandle.coords=function(e,n,r){var i;return r?t:(i=e.getAttributeNode(n))&&""!==i.value?i.value:null},x.valHooks.button={get:function(e,n){var r=e.getAttributeNode(n);return r&&r.specified?r.value:t},set:z.set},x.attrHooks.contenteditable={set:function(e,t,n){z.set(e,""===t?!1:t,n)}},x.each(["width","height"],function(e,n){x.attrHooks[n]={set:function(e,r){return""===r?(e.setAttribute(n,"auto"),r):t}}})),x.support.hrefNormalized||x.each(["href","src"],function(e,t){x.propHooks[t]={get:function(e){return e.getAttribute(t,4)}}}),x.support.style||(x.attrHooks.style={get:function(e){return e.style.cssText||t},set:function(e,t){return e.style.cssText=t+""}}),x.support.optSelected||(x.propHooks.selected={get:function(e){var t=e.parentNode;return t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex),null}}),x.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){x.propFix[this.toLowerCase()]=this}),x.support.enctype||(x.propFix.enctype="encoding"),x.each(["radio","checkbox"],function(){x.valHooks[this]={set:function(e,n){return x.isArray(n)?e.checked=x.inArray(x(e).val(),n)>=0:t}},x.support.checkOn||(x.valHooks[this].get=function(e){return null===e.getAttribute("value")?"on":e.value})});var Z=/^(?:input|select|textarea)$/i,et=/^key/,tt=/^(?:mouse|contextmenu)|click/,nt=/^(?:focusinfocus|focusoutblur)$/,rt=/^([^.]*)(?:\.(.+)|)$/;function it(){return!0}function ot(){return!1}function at(){try{return a.activeElement}catch(e){}}x.event={global:{},add:function(e,n,r,o,a){var s,l,u,c,p,f,d,h,g,m,y,v=x._data(e);if(v){r.handler&&(c=r,r=c.handler,a=c.selector),r.guid||(r.guid=x.guid++),(l=v.events)||(l=v.events={}),(f=v.handle)||(f=v.handle=function(e){return typeof x===i||e&&x.event.triggered===e.type?t:x.event.dispatch.apply(f.elem,arguments)},f.elem=e),n=(n||"").match(T)||[""],u=n.length;while(u--)s=rt.exec(n[u])||[],g=y=s[1],m=(s[2]||"").split(".").sort(),g&&(p=x.event.special[g]||{},g=(a?p.delegateType:p.bindType)||g,p=x.event.special[g]||{},d=x.extend({type:g,origType:y,data:o,handler:r,guid:r.guid,selector:a,needsContext:a&&x.expr.match.needsContext.test(a),namespace:m.join(".")},c),(h=l[g])||(h=l[g]=[],h.delegateCount=0,p.setup&&p.setup.call(e,o,m,f)!==!1||(e.addEventListener?e.addEventListener(g,f,!1):e.attachEvent&&e.attachEvent("on"+g,f))),p.add&&(p.add.call(e,d),d.handler.guid||(d.handler.guid=r.guid)),a?h.splice(h.delegateCount++,0,d):h.push(d),x.event.global[g]=!0);e=null}},remove:function(e,t,n,r,i){var o,a,s,l,u,c,p,f,d,h,g,m=x.hasData(e)&&x._data(e);if(m&&(c=m.events)){t=(t||"").match(T)||[""],u=t.length;while(u--)if(s=rt.exec(t[u])||[],d=g=s[1],h=(s[2]||"").split(".").sort(),d){p=x.event.special[d]||{},d=(r?p.delegateType:p.bindType)||d,f=c[d]||[],s=s[2]&&RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),l=o=f.length;while(o--)a=f[o],!i&&g!==a.origType||n&&n.guid!==a.guid||s&&!s.test(a.namespace)||r&&r!==a.selector&&("**"!==r||!a.selector)||(f.splice(o,1),a.selector&&f.delegateCount--,p.remove&&p.remove.call(e,a));l&&!f.length&&(p.teardown&&p.teardown.call(e,h,m.handle)!==!1||x.removeEvent(e,d,m.handle),delete c[d])}else for(d in c)x.event.remove(e,d+t[u],n,r,!0);x.isEmptyObject(c)&&(delete m.handle,x._removeData(e,"events"))}},trigger:function(n,r,i,o){var s,l,u,c,p,f,d,h=[i||a],g=v.call(n,"type")?n.type:n,m=v.call(n,"namespace")?n.namespace.split("."):[];if(u=f=i=i||a,3!==i.nodeType&&8!==i.nodeType&&!nt.test(g+x.event.triggered)&&(g.indexOf(".")>=0&&(m=g.split("."),g=m.shift(),m.sort()),l=0>g.indexOf(":")&&"on"+g,n=n[x.expando]?n:new x.Event(g,"object"==typeof n&&n),n.isTrigger=o?2:3,n.namespace=m.join("."),n.namespace_re=n.namespace?RegExp("(^|\\.)"+m.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,n.result=t,n.target||(n.target=i),r=null==r?[n]:x.makeArray(r,[n]),p=x.event.special[g]||{},o||!p.trigger||p.trigger.apply(i,r)!==!1)){if(!o&&!p.noBubble&&!x.isWindow(i)){for(c=p.delegateType||g,nt.test(c+g)||(u=u.parentNode);u;u=u.parentNode)h.push(u),f=u;f===(i.ownerDocument||a)&&h.push(f.defaultView||f.parentWindow||e)}d=0;while((u=h[d++])&&!n.isPropagationStopped())n.type=d>1?c:p.bindType||g,s=(x._data(u,"events")||{})[n.type]&&x._data(u,"handle"),s&&s.apply(u,r),s=l&&u[l],s&&x.acceptData(u)&&s.apply&&s.apply(u,r)===!1&&n.preventDefault();if(n.type=g,!o&&!n.isDefaultPrevented()&&(!p._default||p._default.apply(h.pop(),r)===!1)&&x.acceptData(i)&&l&&i[g]&&!x.isWindow(i)){f=i[l],f&&(i[l]=null),x.event.triggered=g;try{i[g]()}catch(y){}x.event.triggered=t,f&&(i[l]=f)}return n.result}},dispatch:function(e){e=x.event.fix(e);var n,r,i,o,a,s=[],l=g.call(arguments),u=(x._data(this,"events")||{})[e.type]||[],c=x.event.special[e.type]||{};if(l[0]=e,e.delegateTarget=this,!c.preDispatch||c.preDispatch.call(this,e)!==!1){s=x.event.handlers.call(this,e,u),n=0;while((o=s[n++])&&!e.isPropagationStopped()){e.currentTarget=o.elem,a=0;while((i=o.handlers[a++])&&!e.isImmediatePropagationStopped())(!e.namespace_re||e.namespace_re.test(i.namespace))&&(e.handleObj=i,e.data=i.data,r=((x.event.special[i.origType]||{}).handle||i.handler).apply(o.elem,l),r!==t&&(e.result=r)===!1&&(e.preventDefault(),e.stopPropagation()))}return c.postDispatch&&c.postDispatch.call(this,e),e.result}},handlers:function(e,n){var r,i,o,a,s=[],l=n.delegateCount,u=e.target;if(l&&u.nodeType&&(!e.button||"click"!==e.type))for(;u!=this;u=u.parentNode||this)if(1===u.nodeType&&(u.disabled!==!0||"click"!==e.type)){for(o=[],a=0;l>a;a++)i=n[a],r=i.selector+" ",o[r]===t&&(o[r]=i.needsContext?x(r,this).index(u)>=0:x.find(r,this,null,[u]).length),o[r]&&o.push(i);o.length&&s.push({elem:u,handlers:o})}return n.length>l&&s.push({elem:this,handlers:n.slice(l)}),s},fix:function(e){if(e[x.expando])return e;var t,n,r,i=e.type,o=e,s=this.fixHooks[i];s||(this.fixHooks[i]=s=tt.test(i)?this.mouseHooks:et.test(i)?this.keyHooks:{}),r=s.props?this.props.concat(s.props):this.props,e=new x.Event(o),t=r.length;while(t--)n=r[t],e[n]=o[n];return e.target||(e.target=o.srcElement||a),3===e.target.nodeType&&(e.target=e.target.parentNode),e.metaKey=!!e.metaKey,s.filter?s.filter(e,o):e},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(e,t){return null==e.which&&(e.which=null!=t.charCode?t.charCode:t.keyCode),e}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(e,n){var r,i,o,s=n.button,l=n.fromElement;return null==e.pageX&&null!=n.clientX&&(i=e.target.ownerDocument||a,o=i.documentElement,r=i.body,e.pageX=n.clientX+(o&&o.scrollLeft||r&&r.scrollLeft||0)-(o&&o.clientLeft||r&&r.clientLeft||0),e.pageY=n.clientY+(o&&o.scrollTop||r&&r.scrollTop||0)-(o&&o.clientTop||r&&r.clientTop||0)),!e.relatedTarget&&l&&(e.relatedTarget=l===e.target?n.toElement:l),e.which||s===t||(e.which=1&s?1:2&s?3:4&s?2:0),e}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==at()&&this.focus)try{return this.focus(),!1}catch(e){}},delegateType:"focusin"},blur:{trigger:function(){return this===at()&&this.blur?(this.blur(),!1):t},delegateType:"focusout"},click:{trigger:function(){return x.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):t},_default:function(e){return x.nodeName(e.target,"a")}},beforeunload:{postDispatch:function(e){e.result!==t&&(e.originalEvent.returnValue=e.result)}}},simulate:function(e,t,n,r){var i=x.extend(new x.Event,n,{type:e,isSimulated:!0,originalEvent:{}});r?x.event.trigger(i,null,t):x.event.dispatch.call(t,i),i.isDefaultPrevented()&&n.preventDefault()}},x.removeEvent=a.removeEventListener?function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n,!1)}:function(e,t,n){var r="on"+t;e.detachEvent&&(typeof e[r]===i&&(e[r]=null),e.detachEvent(r,n))},x.Event=function(e,n){return this instanceof x.Event?(e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||e.returnValue===!1||e.getPreventDefault&&e.getPreventDefault()?it:ot):this.type=e,n&&x.extend(this,n),this.timeStamp=e&&e.timeStamp||x.now(),this[x.expando]=!0,t):new x.Event(e,n)},x.Event.prototype={isDefaultPrevented:ot,isPropagationStopped:ot,isImmediatePropagationStopped:ot,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=it,e&&(e.preventDefault?e.preventDefault():e.returnValue=!1)},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=it,e&&(e.stopPropagation&&e.stopPropagation(),e.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=it,this.stopPropagation()}},x.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(e,t){x.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,i=e.relatedTarget,o=e.handleObj;return(!i||i!==r&&!x.contains(r,i))&&(e.type=o.origType,n=o.handler.apply(this,arguments),e.type=t),n}}}),x.support.submitBubbles||(x.event.special.submit={setup:function(){return x.nodeName(this,"form")?!1:(x.event.add(this,"click._submit keypress._submit",function(e){var n=e.target,r=x.nodeName(n,"input")||x.nodeName(n,"button")?n.form:t;r&&!x._data(r,"submitBubbles")&&(x.event.add(r,"submit._submit",function(e){e._submit_bubble=!0}),x._data(r,"submitBubbles",!0))}),t)},postDispatch:function(e){e._submit_bubble&&(delete e._submit_bubble,this.parentNode&&!e.isTrigger&&x.event.simulate("submit",this.parentNode,e,!0))},teardown:function(){return x.nodeName(this,"form")?!1:(x.event.remove(this,"._submit"),t)}}),x.support.changeBubbles||(x.event.special.change={setup:function(){return Z.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(x.event.add(this,"propertychange._change",function(e){"checked"===e.originalEvent.propertyName&&(this._just_changed=!0)}),x.event.add(this,"click._change",function(e){this._just_changed&&!e.isTrigger&&(this._just_changed=!1),x.event.simulate("change",this,e,!0)})),!1):(x.event.add(this,"beforeactivate._change",function(e){var t=e.target;Z.test(t.nodeName)&&!x._data(t,"changeBubbles")&&(x.event.add(t,"change._change",function(e){!this.parentNode||e.isSimulated||e.isTrigger||x.event.simulate("change",this.parentNode,e,!0)}),x._data(t,"changeBubbles",!0))}),t)},handle:function(e){var n=e.target;return this!==n||e.isSimulated||e.isTrigger||"radio"!==n.type&&"checkbox"!==n.type?e.handleObj.handler.apply(this,arguments):t},teardown:function(){return x.event.remove(this,"._change"),!Z.test(this.nodeName)}}),x.support.focusinBubbles||x.each({focus:"focusin",blur:"focusout"},function(e,t){var n=0,r=function(e){x.event.simulate(t,e.target,x.event.fix(e),!0)};x.event.special[t]={setup:function(){0===n++&&a.addEventListener(e,r,!0)},teardown:function(){0===--n&&a.removeEventListener(e,r,!0)}}}),x.fn.extend({on:function(e,n,r,i,o){var a,s;if("object"==typeof e){"string"!=typeof n&&(r=r||n,n=t);for(a in e)this.on(a,n,r,e[a],o);return this}if(null==r&&null==i?(i=n,r=n=t):null==i&&("string"==typeof n?(i=r,r=t):(i=r,r=n,n=t)),i===!1)i=ot;else if(!i)return this;return 1===o&&(s=i,i=function(e){return x().off(e),s.apply(this,arguments)},i.guid=s.guid||(s.guid=x.guid++)),this.each(function(){x.event.add(this,e,i,r,n)})},one:function(e,t,n,r){return this.on(e,t,n,r,1)},off:function(e,n,r){var i,o;if(e&&e.preventDefault&&e.handleObj)return i=e.handleObj,x(e.delegateTarget).off(i.namespace?i.origType+"."+i.namespace:i.origType,i.selector,i.handler),this;if("object"==typeof e){for(o in e)this.off(o,n,e[o]);return this}return(n===!1||"function"==typeof n)&&(r=n,n=t),r===!1&&(r=ot),this.each(function(){x.event.remove(this,e,r,n)})},trigger:function(e,t){return this.each(function(){x.event.trigger(e,t,this)})},triggerHandler:function(e,n){var r=this[0];return r?x.event.trigger(e,n,r,!0):t}});var st=/^.[^:#\[\.,]*$/,lt=/^(?:parents|prev(?:Until|All))/,ut=x.expr.match.needsContext,ct={children:!0,contents:!0,next:!0,prev:!0};x.fn.extend({find:function(e){var t,n=[],r=this,i=r.length;if("string"!=typeof e)return this.pushStack(x(e).filter(function(){for(t=0;i>t;t++)if(x.contains(r[t],this))return!0}));for(t=0;i>t;t++)x.find(e,r[t],n);return n=this.pushStack(i>1?x.unique(n):n),n.selector=this.selector?this.selector+" "+e:e,n},has:function(e){var t,n=x(e,this),r=n.length;return this.filter(function(){for(t=0;r>t;t++)if(x.contains(this,n[t]))return!0})},not:function(e){return this.pushStack(ft(this,e||[],!0))},filter:function(e){return this.pushStack(ft(this,e||[],!1))},is:function(e){return!!ft(this,"string"==typeof e&&ut.test(e)?x(e):e||[],!1).length},closest:function(e,t){var n,r=0,i=this.length,o=[],a=ut.test(e)||"string"!=typeof e?x(e,t||this.context):0;for(;i>r;r++)for(n=this[r];n&&n!==t;n=n.parentNode)if(11>n.nodeType&&(a?a.index(n)>-1:1===n.nodeType&&x.find.matchesSelector(n,e))){n=o.push(n);break}return this.pushStack(o.length>1?x.unique(o):o)},index:function(e){return e?"string"==typeof e?x.inArray(this[0],x(e)):x.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){var n="string"==typeof e?x(e,t):x.makeArray(e&&e.nodeType?[e]:e),r=x.merge(this.get(),n);return this.pushStack(x.unique(r))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}});function pt(e,t){do e=e[t];while(e&&1!==e.nodeType);return e}x.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return x.dir(e,"parentNode")},parentsUntil:function(e,t,n){return x.dir(e,"parentNode",n)},next:function(e){return pt(e,"nextSibling")},prev:function(e){return pt(e,"previousSibling")},nextAll:function(e){return x.dir(e,"nextSibling")},prevAll:function(e){return x.dir(e,"previousSibling")},nextUntil:function(e,t,n){return x.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return x.dir(e,"previousSibling",n)},siblings:function(e){return x.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return x.sibling(e.firstChild)},contents:function(e){return x.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:x.merge([],e.childNodes)}},function(e,t){x.fn[e]=function(n,r){var i=x.map(this,t,n);return"Until"!==e.slice(-5)&&(r=n),r&&"string"==typeof r&&(i=x.filter(r,i)),this.length>1&&(ct[e]||(i=x.unique(i)),lt.test(e)&&(i=i.reverse())),this.pushStack(i)}}),x.extend({filter:function(e,t,n){var r=t[0];return n&&(e=":not("+e+")"),1===t.length&&1===r.nodeType?x.find.matchesSelector(r,e)?[r]:[]:x.find.matches(e,x.grep(t,function(e){return 1===e.nodeType}))},dir:function(e,n,r){var i=[],o=e[n];while(o&&9!==o.nodeType&&(r===t||1!==o.nodeType||!x(o).is(r)))1===o.nodeType&&i.push(o),o=o[n];return i},sibling:function(e,t){var n=[];for(;e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n}});function ft(e,t,n){if(x.isFunction(t))return x.grep(e,function(e,r){return!!t.call(e,r,e)!==n});if(t.nodeType)return x.grep(e,function(e){return e===t!==n});if("string"==typeof t){if(st.test(t))return x.filter(t,e,n);t=x.filter(t,e)}return x.grep(e,function(e){return x.inArray(e,t)>=0!==n})}function dt(e){var t=ht.split("|"),n=e.createDocumentFragment();if(n.createElement)while(t.length)n.createElement(t.pop());return n}var ht="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",gt=/ jQuery\d+="(?:null|\d+)"/g,mt=RegExp("<(?:"+ht+")[\\s/>]","i"),yt=/^\s+/,vt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,bt=/<([\w:]+)/,xt=/<tbody/i,wt=/<|&#?\w+;/,Tt=/<(?:script|style|link)/i,Ct=/^(?:checkbox|radio)$/i,Nt=/checked\s*(?:[^=]|=\s*.checked.)/i,kt=/^$|\/(?:java|ecma)script/i,Et=/^true\/(.*)/,St=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,At={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:x.support.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},jt=dt(a),Dt=jt.appendChild(a.createElement("div"));At.optgroup=At.option,At.tbody=At.tfoot=At.colgroup=At.caption=At.thead,At.th=At.td,x.fn.extend({text:function(e){return x.access(this,function(e){return e===t?x.text(this):this.empty().append((this[0]&&this[0].ownerDocument||a).createTextNode(e))},null,e,arguments.length)},append:function(){return this.domManip(arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=Lt(this,e);t.appendChild(e)}})},prepend:function(){return this.domManip(arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=Lt(this,e);t.insertBefore(e,t.firstChild)}})},before:function(){return this.domManip(arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return this.domManip(arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},remove:function(e,t){var n,r=e?x.filter(e,this):this,i=0;for(;null!=(n=r[i]);i++)t||1!==n.nodeType||x.cleanData(Ft(n)),n.parentNode&&(t&&x.contains(n.ownerDocument,n)&&_t(Ft(n,"script")),n.parentNode.removeChild(n));return this},empty:function(){var e,t=0;for(;null!=(e=this[t]);t++){1===e.nodeType&&x.cleanData(Ft(e,!1));while(e.firstChild)e.removeChild(e.firstChild);e.options&&x.nodeName(e,"select")&&(e.options.length=0)}return this},clone:function(e,t){return e=null==e?!1:e,t=null==t?e:t,this.map(function(){return x.clone(this,e,t)})},html:function(e){return x.access(this,function(e){var n=this[0]||{},r=0,i=this.length;if(e===t)return 1===n.nodeType?n.innerHTML.replace(gt,""):t;if(!("string"!=typeof e||Tt.test(e)||!x.support.htmlSerialize&&mt.test(e)||!x.support.leadingWhitespace&&yt.test(e)||At[(bt.exec(e)||["",""])[1].toLowerCase()])){e=e.replace(vt,"<$1></$2>");try{for(;i>r;r++)n=this[r]||{},1===n.nodeType&&(x.cleanData(Ft(n,!1)),n.innerHTML=e);n=0}catch(o){}}n&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(){var e=x.map(this,function(e){return[e.nextSibling,e.parentNode]}),t=0;return this.domManip(arguments,function(n){var r=e[t++],i=e[t++];i&&(r&&r.parentNode!==i&&(r=this.nextSibling),x(this).remove(),i.insertBefore(n,r))},!0),t?this:this.remove()},detach:function(e){return this.remove(e,!0)},domManip:function(e,t,n){e=d.apply([],e);var r,i,o,a,s,l,u=0,c=this.length,p=this,f=c-1,h=e[0],g=x.isFunction(h);if(g||!(1>=c||"string"!=typeof h||x.support.checkClone)&&Nt.test(h))return this.each(function(r){var i=p.eq(r);g&&(e[0]=h.call(this,r,i.html())),i.domManip(e,t,n)});if(c&&(l=x.buildFragment(e,this[0].ownerDocument,!1,!n&&this),r=l.firstChild,1===l.childNodes.length&&(l=r),r)){for(a=x.map(Ft(l,"script"),Ht),o=a.length;c>u;u++)i=l,u!==f&&(i=x.clone(i,!0,!0),o&&x.merge(a,Ft(i,"script"))),t.call(this[u],i,u);if(o)for(s=a[a.length-1].ownerDocument,x.map(a,qt),u=0;o>u;u++)i=a[u],kt.test(i.type||"")&&!x._data(i,"globalEval")&&x.contains(s,i)&&(i.src?x._evalUrl(i.src):x.globalEval((i.text||i.textContent||i.innerHTML||"").replace(St,"")));l=r=null}return this}});function Lt(e,t){return x.nodeName(e,"table")&&x.nodeName(1===t.nodeType?t:t.firstChild,"tr")?e.getElementsByTagName("tbody")[0]||e.appendChild(e.ownerDocument.createElement("tbody")):e}function Ht(e){return e.type=(null!==x.find.attr(e,"type"))+"/"+e.type,e}function qt(e){var t=Et.exec(e.type);return t?e.type=t[1]:e.removeAttribute("type"),e}function _t(e,t){var n,r=0;for(;null!=(n=e[r]);r++)x._data(n,"globalEval",!t||x._data(t[r],"globalEval"))}function Mt(e,t){if(1===t.nodeType&&x.hasData(e)){var n,r,i,o=x._data(e),a=x._data(t,o),s=o.events;if(s){delete a.handle,a.events={};for(n in s)for(r=0,i=s[n].length;i>r;r++)x.event.add(t,n,s[n][r])}a.data&&(a.data=x.extend({},a.data))}}function Ot(e,t){var n,r,i;if(1===t.nodeType){if(n=t.nodeName.toLowerCase(),!x.support.noCloneEvent&&t[x.expando]){i=x._data(t);for(r in i.events)x.removeEvent(t,r,i.handle);t.removeAttribute(x.expando)}"script"===n&&t.text!==e.text?(Ht(t).text=e.text,qt(t)):"object"===n?(t.parentNode&&(t.outerHTML=e.outerHTML),x.support.html5Clone&&e.innerHTML&&!x.trim(t.innerHTML)&&(t.innerHTML=e.innerHTML)):"input"===n&&Ct.test(e.type)?(t.defaultChecked=t.checked=e.checked,t.value!==e.value&&(t.value=e.value)):"option"===n?t.defaultSelected=t.selected=e.defaultSelected:("input"===n||"textarea"===n)&&(t.defaultValue=e.defaultValue)}}x.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){x.fn[e]=function(e){var n,r=0,i=[],o=x(e),a=o.length-1;for(;a>=r;r++)n=r===a?this:this.clone(!0),x(o[r])[t](n),h.apply(i,n.get());return this.pushStack(i)}});function Ft(e,n){var r,o,a=0,s=typeof e.getElementsByTagName!==i?e.getElementsByTagName(n||"*"):typeof e.querySelectorAll!==i?e.querySelectorAll(n||"*"):t;if(!s)for(s=[],r=e.childNodes||e;null!=(o=r[a]);a++)!n||x.nodeName(o,n)?s.push(o):x.merge(s,Ft(o,n));return n===t||n&&x.nodeName(e,n)?x.merge([e],s):s}function Bt(e){Ct.test(e.type)&&(e.defaultChecked=e.checked)}x.extend({clone:function(e,t,n){var r,i,o,a,s,l=x.contains(e.ownerDocument,e);if(x.support.html5Clone||x.isXMLDoc(e)||!mt.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(Dt.innerHTML=e.outerHTML,Dt.removeChild(o=Dt.firstChild)),!(x.support.noCloneEvent&&x.support.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||x.isXMLDoc(e)))for(r=Ft(o),s=Ft(e),a=0;null!=(i=s[a]);++a)r[a]&&Ot(i,r[a]);if(t)if(n)for(s=s||Ft(e),r=r||Ft(o),a=0;null!=(i=s[a]);a++)Mt(i,r[a]);else Mt(e,o);return r=Ft(o,"script"),r.length>0&&_t(r,!l&&Ft(e,"script")),r=s=i=null,o},buildFragment:function(e,t,n,r){var i,o,a,s,l,u,c,p=e.length,f=dt(t),d=[],h=0;for(;p>h;h++)if(o=e[h],o||0===o)if("object"===x.type(o))x.merge(d,o.nodeType?[o]:o);else if(wt.test(o)){s=s||f.appendChild(t.createElement("div")),l=(bt.exec(o)||["",""])[1].toLowerCase(),c=At[l]||At._default,s.innerHTML=c[1]+o.replace(vt,"<$1></$2>")+c[2],i=c[0];while(i--)s=s.lastChild;if(!x.support.leadingWhitespace&&yt.test(o)&&d.push(t.createTextNode(yt.exec(o)[0])),!x.support.tbody){o="table"!==l||xt.test(o)?"<table>"!==c[1]||xt.test(o)?0:s:s.firstChild,i=o&&o.childNodes.length;while(i--)x.nodeName(u=o.childNodes[i],"tbody")&&!u.childNodes.length&&o.removeChild(u)}x.merge(d,s.childNodes),s.textContent="";while(s.firstChild)s.removeChild(s.firstChild);s=f.lastChild}else d.push(t.createTextNode(o));s&&f.removeChild(s),x.support.appendChecked||x.grep(Ft(d,"input"),Bt),h=0;while(o=d[h++])if((!r||-1===x.inArray(o,r))&&(a=x.contains(o.ownerDocument,o),s=Ft(f.appendChild(o),"script"),a&&_t(s),n)){i=0;while(o=s[i++])kt.test(o.type||"")&&n.push(o)}return s=null,f},cleanData:function(e,t){var n,r,o,a,s=0,l=x.expando,u=x.cache,c=x.support.deleteExpando,f=x.event.special;for(;null!=(n=e[s]);s++)if((t||x.acceptData(n))&&(o=n[l],a=o&&u[o])){if(a.events)for(r in a.events)f[r]?x.event.remove(n,r):x.removeEvent(n,r,a.handle); u[o]&&(delete u[o],c?delete n[l]:typeof n.removeAttribute!==i?n.removeAttribute(l):n[l]=null,p.push(o))}},_evalUrl:function(e){return x.ajax({url:e,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})}}),x.fn.extend({wrapAll:function(e){if(x.isFunction(e))return this.each(function(t){x(this).wrapAll(e.call(this,t))});if(this[0]){var t=x(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstChild&&1===e.firstChild.nodeType)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return x.isFunction(e)?this.each(function(t){x(this).wrapInner(e.call(this,t))}):this.each(function(){var t=x(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=x.isFunction(e);return this.each(function(n){x(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){x.nodeName(this,"body")||x(this).replaceWith(this.childNodes)}).end()}});var Pt,Rt,Wt,$t=/alpha\([^)]*\)/i,It=/opacity\s*=\s*([^)]*)/,zt=/^(top|right|bottom|left)$/,Xt=/^(none|table(?!-c[ea]).+)/,Ut=/^margin/,Vt=RegExp("^("+w+")(.*)$","i"),Yt=RegExp("^("+w+")(?!px)[a-z%]+$","i"),Jt=RegExp("^([+-])=("+w+")","i"),Gt={BODY:"block"},Qt={position:"absolute",visibility:"hidden",display:"block"},Kt={letterSpacing:0,fontWeight:400},Zt=["Top","Right","Bottom","Left"],en=["Webkit","O","Moz","ms"];function tn(e,t){if(t in e)return t;var n=t.charAt(0).toUpperCase()+t.slice(1),r=t,i=en.length;while(i--)if(t=en[i]+n,t in e)return t;return r}function nn(e,t){return e=t||e,"none"===x.css(e,"display")||!x.contains(e.ownerDocument,e)}function rn(e,t){var n,r,i,o=[],a=0,s=e.length;for(;s>a;a++)r=e[a],r.style&&(o[a]=x._data(r,"olddisplay"),n=r.style.display,t?(o[a]||"none"!==n||(r.style.display=""),""===r.style.display&&nn(r)&&(o[a]=x._data(r,"olddisplay",ln(r.nodeName)))):o[a]||(i=nn(r),(n&&"none"!==n||!i)&&x._data(r,"olddisplay",i?n:x.css(r,"display"))));for(a=0;s>a;a++)r=e[a],r.style&&(t&&"none"!==r.style.display&&""!==r.style.display||(r.style.display=t?o[a]||"":"none"));return e}x.fn.extend({css:function(e,n){return x.access(this,function(e,n,r){var i,o,a={},s=0;if(x.isArray(n)){for(o=Rt(e),i=n.length;i>s;s++)a[n[s]]=x.css(e,n[s],!1,o);return a}return r!==t?x.style(e,n,r):x.css(e,n)},e,n,arguments.length>1)},show:function(){return rn(this,!0)},hide:function(){return rn(this)},toggle:function(e){return"boolean"==typeof e?e?this.show():this.hide():this.each(function(){nn(this)?x(this).show():x(this).hide()})}}),x.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Wt(e,"opacity");return""===n?"1":n}}}},cssNumber:{columnCount:!0,fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":x.support.cssFloat?"cssFloat":"styleFloat"},style:function(e,n,r,i){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var o,a,s,l=x.camelCase(n),u=e.style;if(n=x.cssProps[l]||(x.cssProps[l]=tn(u,l)),s=x.cssHooks[n]||x.cssHooks[l],r===t)return s&&"get"in s&&(o=s.get(e,!1,i))!==t?o:u[n];if(a=typeof r,"string"===a&&(o=Jt.exec(r))&&(r=(o[1]+1)*o[2]+parseFloat(x.css(e,n)),a="number"),!(null==r||"number"===a&&isNaN(r)||("number"!==a||x.cssNumber[l]||(r+="px"),x.support.clearCloneStyle||""!==r||0!==n.indexOf("background")||(u[n]="inherit"),s&&"set"in s&&(r=s.set(e,r,i))===t)))try{u[n]=r}catch(c){}}},css:function(e,n,r,i){var o,a,s,l=x.camelCase(n);return n=x.cssProps[l]||(x.cssProps[l]=tn(e.style,l)),s=x.cssHooks[n]||x.cssHooks[l],s&&"get"in s&&(a=s.get(e,!0,r)),a===t&&(a=Wt(e,n,i)),"normal"===a&&n in Kt&&(a=Kt[n]),""===r||r?(o=parseFloat(a),r===!0||x.isNumeric(o)?o||0:a):a}}),e.getComputedStyle?(Rt=function(t){return e.getComputedStyle(t,null)},Wt=function(e,n,r){var i,o,a,s=r||Rt(e),l=s?s.getPropertyValue(n)||s[n]:t,u=e.style;return s&&(""!==l||x.contains(e.ownerDocument,e)||(l=x.style(e,n)),Yt.test(l)&&Ut.test(n)&&(i=u.width,o=u.minWidth,a=u.maxWidth,u.minWidth=u.maxWidth=u.width=l,l=s.width,u.width=i,u.minWidth=o,u.maxWidth=a)),l}):a.documentElement.currentStyle&&(Rt=function(e){return e.currentStyle},Wt=function(e,n,r){var i,o,a,s=r||Rt(e),l=s?s[n]:t,u=e.style;return null==l&&u&&u[n]&&(l=u[n]),Yt.test(l)&&!zt.test(n)&&(i=u.left,o=e.runtimeStyle,a=o&&o.left,a&&(o.left=e.currentStyle.left),u.left="fontSize"===n?"1em":l,l=u.pixelLeft+"px",u.left=i,a&&(o.left=a)),""===l?"auto":l});function on(e,t,n){var r=Vt.exec(t);return r?Math.max(0,r[1]-(n||0))+(r[2]||"px"):t}function an(e,t,n,r,i){var o=n===(r?"border":"content")?4:"width"===t?1:0,a=0;for(;4>o;o+=2)"margin"===n&&(a+=x.css(e,n+Zt[o],!0,i)),r?("content"===n&&(a-=x.css(e,"padding"+Zt[o],!0,i)),"margin"!==n&&(a-=x.css(e,"border"+Zt[o]+"Width",!0,i))):(a+=x.css(e,"padding"+Zt[o],!0,i),"padding"!==n&&(a+=x.css(e,"border"+Zt[o]+"Width",!0,i)));return a}function sn(e,t,n){var r=!0,i="width"===t?e.offsetWidth:e.offsetHeight,o=Rt(e),a=x.support.boxSizing&&"border-box"===x.css(e,"boxSizing",!1,o);if(0>=i||null==i){if(i=Wt(e,t,o),(0>i||null==i)&&(i=e.style[t]),Yt.test(i))return i;r=a&&(x.support.boxSizingReliable||i===e.style[t]),i=parseFloat(i)||0}return i+an(e,t,n||(a?"border":"content"),r,o)+"px"}function ln(e){var t=a,n=Gt[e];return n||(n=un(e,t),"none"!==n&&n||(Pt=(Pt||x("<iframe frameborder='0' width='0' height='0'/>").css("cssText","display:block !important")).appendTo(t.documentElement),t=(Pt[0].contentWindow||Pt[0].contentDocument).document,t.write("<!doctype html><html><body>"),t.close(),n=un(e,t),Pt.detach()),Gt[e]=n),n}function un(e,t){var n=x(t.createElement(e)).appendTo(t.body),r=x.css(n[0],"display");return n.remove(),r}x.each(["height","width"],function(e,n){x.cssHooks[n]={get:function(e,r,i){return r?0===e.offsetWidth&&Xt.test(x.css(e,"display"))?x.swap(e,Qt,function(){return sn(e,n,i)}):sn(e,n,i):t},set:function(e,t,r){var i=r&&Rt(e);return on(e,t,r?an(e,n,r,x.support.boxSizing&&"border-box"===x.css(e,"boxSizing",!1,i),i):0)}}}),x.support.opacity||(x.cssHooks.opacity={get:function(e,t){return It.test((t&&e.currentStyle?e.currentStyle.filter:e.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":t?"1":""},set:function(e,t){var n=e.style,r=e.currentStyle,i=x.isNumeric(t)?"alpha(opacity="+100*t+")":"",o=r&&r.filter||n.filter||"";n.zoom=1,(t>=1||""===t)&&""===x.trim(o.replace($t,""))&&n.removeAttribute&&(n.removeAttribute("filter"),""===t||r&&!r.filter)||(n.filter=$t.test(o)?o.replace($t,i):o+" "+i)}}),x(function(){x.support.reliableMarginRight||(x.cssHooks.marginRight={get:function(e,n){return n?x.swap(e,{display:"inline-block"},Wt,[e,"marginRight"]):t}}),!x.support.pixelPosition&&x.fn.position&&x.each(["top","left"],function(e,n){x.cssHooks[n]={get:function(e,r){return r?(r=Wt(e,n),Yt.test(r)?x(e).position()[n]+"px":r):t}}})}),x.expr&&x.expr.filters&&(x.expr.filters.hidden=function(e){return 0>=e.offsetWidth&&0>=e.offsetHeight||!x.support.reliableHiddenOffsets&&"none"===(e.style&&e.style.display||x.css(e,"display"))},x.expr.filters.visible=function(e){return!x.expr.filters.hidden(e)}),x.each({margin:"",padding:"",border:"Width"},function(e,t){x.cssHooks[e+t]={expand:function(n){var r=0,i={},o="string"==typeof n?n.split(" "):[n];for(;4>r;r++)i[e+Zt[r]+t]=o[r]||o[r-2]||o[0];return i}},Ut.test(e)||(x.cssHooks[e+t].set=on)});var cn=/%20/g,pn=/\[\]$/,fn=/\r?\n/g,dn=/^(?:submit|button|image|reset|file)$/i,hn=/^(?:input|select|textarea|keygen)/i;x.fn.extend({serialize:function(){return x.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=x.prop(this,"elements");return e?x.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!x(this).is(":disabled")&&hn.test(this.nodeName)&&!dn.test(e)&&(this.checked||!Ct.test(e))}).map(function(e,t){var n=x(this).val();return null==n?null:x.isArray(n)?x.map(n,function(e){return{name:t.name,value:e.replace(fn,"\r\n")}}):{name:t.name,value:n.replace(fn,"\r\n")}}).get()}}),x.param=function(e,n){var r,i=[],o=function(e,t){t=x.isFunction(t)?t():null==t?"":t,i[i.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};if(n===t&&(n=x.ajaxSettings&&x.ajaxSettings.traditional),x.isArray(e)||e.jquery&&!x.isPlainObject(e))x.each(e,function(){o(this.name,this.value)});else for(r in e)gn(r,e[r],n,o);return i.join("&").replace(cn,"+")};function gn(e,t,n,r){var i;if(x.isArray(t))x.each(t,function(t,i){n||pn.test(e)?r(e,i):gn(e+"["+("object"==typeof i?t:"")+"]",i,n,r)});else if(n||"object"!==x.type(t))r(e,t);else for(i in t)gn(e+"["+i+"]",t[i],n,r)}x.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(e,t){x.fn[t]=function(e,n){return arguments.length>0?this.on(t,null,e,n):this.trigger(t)}}),x.fn.extend({hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)},bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)}});var mn,yn,vn=x.now(),bn=/\?/,xn=/#.*$/,wn=/([?&])_=[^&]*/,Tn=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Cn=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Nn=/^(?:GET|HEAD)$/,kn=/^\/\//,En=/^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,Sn=x.fn.load,An={},jn={},Dn="*/".concat("*");try{yn=o.href}catch(Ln){yn=a.createElement("a"),yn.href="",yn=yn.href}mn=En.exec(yn.toLowerCase())||[];function Hn(e){return function(t,n){"string"!=typeof t&&(n=t,t="*");var r,i=0,o=t.toLowerCase().match(T)||[];if(x.isFunction(n))while(r=o[i++])"+"===r[0]?(r=r.slice(1)||"*",(e[r]=e[r]||[]).unshift(n)):(e[r]=e[r]||[]).push(n)}}function qn(e,n,r,i){var o={},a=e===jn;function s(l){var u;return o[l]=!0,x.each(e[l]||[],function(e,l){var c=l(n,r,i);return"string"!=typeof c||a||o[c]?a?!(u=c):t:(n.dataTypes.unshift(c),s(c),!1)}),u}return s(n.dataTypes[0])||!o["*"]&&s("*")}function _n(e,n){var r,i,o=x.ajaxSettings.flatOptions||{};for(i in n)n[i]!==t&&((o[i]?e:r||(r={}))[i]=n[i]);return r&&x.extend(!0,e,r),e}x.fn.load=function(e,n,r){if("string"!=typeof e&&Sn)return Sn.apply(this,arguments);var i,o,a,s=this,l=e.indexOf(" ");return l>=0&&(i=e.slice(l,e.length),e=e.slice(0,l)),x.isFunction(n)?(r=n,n=t):n&&"object"==typeof n&&(a="POST"),s.length>0&&x.ajax({url:e,type:a,dataType:"html",data:n}).done(function(e){o=arguments,s.html(i?x("<div>").append(x.parseHTML(e)).find(i):e)}).complete(r&&function(e,t){s.each(r,o||[e.responseText,t,e])}),this},x.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){x.fn[t]=function(e){return this.on(t,e)}}),x.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:yn,type:"GET",isLocal:Cn.test(mn[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Dn,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":x.parseJSON,"text xml":x.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?_n(_n(e,x.ajaxSettings),t):_n(x.ajaxSettings,e)},ajaxPrefilter:Hn(An),ajaxTransport:Hn(jn),ajax:function(e,n){"object"==typeof e&&(n=e,e=t),n=n||{};var r,i,o,a,s,l,u,c,p=x.ajaxSetup({},n),f=p.context||p,d=p.context&&(f.nodeType||f.jquery)?x(f):x.event,h=x.Deferred(),g=x.Callbacks("once memory"),m=p.statusCode||{},y={},v={},b=0,w="canceled",C={readyState:0,getResponseHeader:function(e){var t;if(2===b){if(!c){c={};while(t=Tn.exec(a))c[t[1].toLowerCase()]=t[2]}t=c[e.toLowerCase()]}return null==t?null:t},getAllResponseHeaders:function(){return 2===b?a:null},setRequestHeader:function(e,t){var n=e.toLowerCase();return b||(e=v[n]=v[n]||e,y[e]=t),this},overrideMimeType:function(e){return b||(p.mimeType=e),this},statusCode:function(e){var t;if(e)if(2>b)for(t in e)m[t]=[m[t],e[t]];else C.always(e[C.status]);return this},abort:function(e){var t=e||w;return u&&u.abort(t),k(0,t),this}};if(h.promise(C).complete=g.add,C.success=C.done,C.error=C.fail,p.url=((e||p.url||yn)+"").replace(xn,"").replace(kn,mn[1]+"//"),p.type=n.method||n.type||p.method||p.type,p.dataTypes=x.trim(p.dataType||"*").toLowerCase().match(T)||[""],null==p.crossDomain&&(r=En.exec(p.url.toLowerCase()),p.crossDomain=!(!r||r[1]===mn[1]&&r[2]===mn[2]&&(r[3]||("http:"===r[1]?"80":"443"))===(mn[3]||("http:"===mn[1]?"80":"443")))),p.data&&p.processData&&"string"!=typeof p.data&&(p.data=x.param(p.data,p.traditional)),qn(An,p,n,C),2===b)return C;l=p.global,l&&0===x.active++&&x.event.trigger("ajaxStart"),p.type=p.type.toUpperCase(),p.hasContent=!Nn.test(p.type),o=p.url,p.hasContent||(p.data&&(o=p.url+=(bn.test(o)?"&":"?")+p.data,delete p.data),p.cache===!1&&(p.url=wn.test(o)?o.replace(wn,"$1_="+vn++):o+(bn.test(o)?"&":"?")+"_="+vn++)),p.ifModified&&(x.lastModified[o]&&C.setRequestHeader("If-Modified-Since",x.lastModified[o]),x.etag[o]&&C.setRequestHeader("If-None-Match",x.etag[o])),(p.data&&p.hasContent&&p.contentType!==!1||n.contentType)&&C.setRequestHeader("Content-Type",p.contentType),C.setRequestHeader("Accept",p.dataTypes[0]&&p.accepts[p.dataTypes[0]]?p.accepts[p.dataTypes[0]]+("*"!==p.dataTypes[0]?", "+Dn+"; q=0.01":""):p.accepts["*"]);for(i in p.headers)C.setRequestHeader(i,p.headers[i]);if(p.beforeSend&&(p.beforeSend.call(f,C,p)===!1||2===b))return C.abort();w="abort";for(i in{success:1,error:1,complete:1})C[i](p[i]);if(u=qn(jn,p,n,C)){C.readyState=1,l&&d.trigger("ajaxSend",[C,p]),p.async&&p.timeout>0&&(s=setTimeout(function(){C.abort("timeout")},p.timeout));try{b=1,u.send(y,k)}catch(N){if(!(2>b))throw N;k(-1,N)}}else k(-1,"No Transport");function k(e,n,r,i){var c,y,v,w,T,N=n;2!==b&&(b=2,s&&clearTimeout(s),u=t,a=i||"",C.readyState=e>0?4:0,c=e>=200&&300>e||304===e,r&&(w=Mn(p,C,r)),w=On(p,w,C,c),c?(p.ifModified&&(T=C.getResponseHeader("Last-Modified"),T&&(x.lastModified[o]=T),T=C.getResponseHeader("etag"),T&&(x.etag[o]=T)),204===e||"HEAD"===p.type?N="nocontent":304===e?N="notmodified":(N=w.state,y=w.data,v=w.error,c=!v)):(v=N,(e||!N)&&(N="error",0>e&&(e=0))),C.status=e,C.statusText=(n||N)+"",c?h.resolveWith(f,[y,N,C]):h.rejectWith(f,[C,N,v]),C.statusCode(m),m=t,l&&d.trigger(c?"ajaxSuccess":"ajaxError",[C,p,c?y:v]),g.fireWith(f,[C,N]),l&&(d.trigger("ajaxComplete",[C,p]),--x.active||x.event.trigger("ajaxStop")))}return C},getJSON:function(e,t,n){return x.get(e,t,n,"json")},getScript:function(e,n){return x.get(e,t,n,"script")}}),x.each(["get","post"],function(e,n){x[n]=function(e,r,i,o){return x.isFunction(r)&&(o=o||i,i=r,r=t),x.ajax({url:e,type:n,dataType:o,data:r,success:i})}});function Mn(e,n,r){var i,o,a,s,l=e.contents,u=e.dataTypes;while("*"===u[0])u.shift(),o===t&&(o=e.mimeType||n.getResponseHeader("Content-Type"));if(o)for(s in l)if(l[s]&&l[s].test(o)){u.unshift(s);break}if(u[0]in r)a=u[0];else{for(s in r){if(!u[0]||e.converters[s+" "+u[0]]){a=s;break}i||(i=s)}a=a||i}return a?(a!==u[0]&&u.unshift(a),r[a]):t}function On(e,t,n,r){var i,o,a,s,l,u={},c=e.dataTypes.slice();if(c[1])for(a in e.converters)u[a.toLowerCase()]=e.converters[a];o=c.shift();while(o)if(e.responseFields[o]&&(n[e.responseFields[o]]=t),!l&&r&&e.dataFilter&&(t=e.dataFilter(t,e.dataType)),l=o,o=c.shift())if("*"===o)o=l;else if("*"!==l&&l!==o){if(a=u[l+" "+o]||u["* "+o],!a)for(i in u)if(s=i.split(" "),s[1]===o&&(a=u[l+" "+s[0]]||u["* "+s[0]])){a===!0?a=u[i]:u[i]!==!0&&(o=s[0],c.unshift(s[1]));break}if(a!==!0)if(a&&e["throws"])t=a(t);else try{t=a(t)}catch(p){return{state:"parsererror",error:a?p:"No conversion from "+l+" to "+o}}}return{state:"success",data:t}}x.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(e){return x.globalEval(e),e}}}),x.ajaxPrefilter("script",function(e){e.cache===t&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),x.ajaxTransport("script",function(e){if(e.crossDomain){var n,r=a.head||x("head")[0]||a.documentElement;return{send:function(t,i){n=a.createElement("script"),n.async=!0,e.scriptCharset&&(n.charset=e.scriptCharset),n.src=e.url,n.onload=n.onreadystatechange=function(e,t){(t||!n.readyState||/loaded|complete/.test(n.readyState))&&(n.onload=n.onreadystatechange=null,n.parentNode&&n.parentNode.removeChild(n),n=null,t||i(200,"success"))},r.insertBefore(n,r.firstChild)},abort:function(){n&&n.onload(t,!0)}}}});var Fn=[],Bn=/(=)\?(?=&|$)|\?\?/;x.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Fn.pop()||x.expando+"_"+vn++;return this[e]=!0,e}}),x.ajaxPrefilter("json jsonp",function(n,r,i){var o,a,s,l=n.jsonp!==!1&&(Bn.test(n.url)?"url":"string"==typeof n.data&&!(n.contentType||"").indexOf("application/x-www-form-urlencoded")&&Bn.test(n.data)&&"data");return l||"jsonp"===n.dataTypes[0]?(o=n.jsonpCallback=x.isFunction(n.jsonpCallback)?n.jsonpCallback():n.jsonpCallback,l?n[l]=n[l].replace(Bn,"$1"+o):n.jsonp!==!1&&(n.url+=(bn.test(n.url)?"&":"?")+n.jsonp+"="+o),n.converters["script json"]=function(){return s||x.error(o+" was not called"),s[0]},n.dataTypes[0]="json",a=e[o],e[o]=function(){s=arguments},i.always(function(){e[o]=a,n[o]&&(n.jsonpCallback=r.jsonpCallback,Fn.push(o)),s&&x.isFunction(a)&&a(s[0]),s=a=t}),"script"):t});var Pn,Rn,Wn=0,$n=e.ActiveXObject&&function(){var e;for(e in Pn)Pn[e](t,!0)};function In(){try{return new e.XMLHttpRequest}catch(t){}}function zn(){try{return new e.ActiveXObject("Microsoft.XMLHTTP")}catch(t){}}x.ajaxSettings.xhr=e.ActiveXObject?function(){return!this.isLocal&&In()||zn()}:In,Rn=x.ajaxSettings.xhr(),x.support.cors=!!Rn&&"withCredentials"in Rn,Rn=x.support.ajax=!!Rn,Rn&&x.ajaxTransport(function(n){if(!n.crossDomain||x.support.cors){var r;return{send:function(i,o){var a,s,l=n.xhr();if(n.username?l.open(n.type,n.url,n.async,n.username,n.password):l.open(n.type,n.url,n.async),n.xhrFields)for(s in n.xhrFields)l[s]=n.xhrFields[s];n.mimeType&&l.overrideMimeType&&l.overrideMimeType(n.mimeType),n.crossDomain||i["X-Requested-With"]||(i["X-Requested-With"]="XMLHttpRequest");try{for(s in i)l.setRequestHeader(s,i[s])}catch(u){}l.send(n.hasContent&&n.data||null),r=function(e,i){var s,u,c,p;try{if(r&&(i||4===l.readyState))if(r=t,a&&(l.onreadystatechange=x.noop,$n&&delete Pn[a]),i)4!==l.readyState&&l.abort();else{p={},s=l.status,u=l.getAllResponseHeaders(),"string"==typeof l.responseText&&(p.text=l.responseText);try{c=l.statusText}catch(f){c=""}s||!n.isLocal||n.crossDomain?1223===s&&(s=204):s=p.text?200:404}}catch(d){i||o(-1,d)}p&&o(s,c,p,u)},n.async?4===l.readyState?setTimeout(r):(a=++Wn,$n&&(Pn||(Pn={},x(e).unload($n)),Pn[a]=r),l.onreadystatechange=r):r()},abort:function(){r&&r(t,!0)}}}});var Xn,Un,Vn=/^(?:toggle|show|hide)$/,Yn=RegExp("^(?:([+-])=|)("+w+")([a-z%]*)$","i"),Jn=/queueHooks$/,Gn=[nr],Qn={"*":[function(e,t){var n=this.createTween(e,t),r=n.cur(),i=Yn.exec(t),o=i&&i[3]||(x.cssNumber[e]?"":"px"),a=(x.cssNumber[e]||"px"!==o&&+r)&&Yn.exec(x.css(n.elem,e)),s=1,l=20;if(a&&a[3]!==o){o=o||a[3],i=i||[],a=+r||1;do s=s||".5",a/=s,x.style(n.elem,e,a+o);while(s!==(s=n.cur()/r)&&1!==s&&--l)}return i&&(a=n.start=+a||+r||0,n.unit=o,n.end=i[1]?a+(i[1]+1)*i[2]:+i[2]),n}]};function Kn(){return setTimeout(function(){Xn=t}),Xn=x.now()}function Zn(e,t,n){var r,i=(Qn[t]||[]).concat(Qn["*"]),o=0,a=i.length;for(;a>o;o++)if(r=i[o].call(n,t,e))return r}function er(e,t,n){var r,i,o=0,a=Gn.length,s=x.Deferred().always(function(){delete l.elem}),l=function(){if(i)return!1;var t=Xn||Kn(),n=Math.max(0,u.startTime+u.duration-t),r=n/u.duration||0,o=1-r,a=0,l=u.tweens.length;for(;l>a;a++)u.tweens[a].run(o);return s.notifyWith(e,[u,o,n]),1>o&&l?n:(s.resolveWith(e,[u]),!1)},u=s.promise({elem:e,props:x.extend({},t),opts:x.extend(!0,{specialEasing:{}},n),originalProperties:t,originalOptions:n,startTime:Xn||Kn(),duration:n.duration,tweens:[],createTween:function(t,n){var r=x.Tween(e,u.opts,t,n,u.opts.specialEasing[t]||u.opts.easing);return u.tweens.push(r),r},stop:function(t){var n=0,r=t?u.tweens.length:0;if(i)return this;for(i=!0;r>n;n++)u.tweens[n].run(1);return t?s.resolveWith(e,[u,t]):s.rejectWith(e,[u,t]),this}}),c=u.props;for(tr(c,u.opts.specialEasing);a>o;o++)if(r=Gn[o].call(u,e,c,u.opts))return r;return x.map(c,Zn,u),x.isFunction(u.opts.start)&&u.opts.start.call(e,u),x.fx.timer(x.extend(l,{elem:e,anim:u,queue:u.opts.queue})),u.progress(u.opts.progress).done(u.opts.done,u.opts.complete).fail(u.opts.fail).always(u.opts.always)}function tr(e,t){var n,r,i,o,a;for(n in e)if(r=x.camelCase(n),i=t[r],o=e[n],x.isArray(o)&&(i=o[1],o=e[n]=o[0]),n!==r&&(e[r]=o,delete e[n]),a=x.cssHooks[r],a&&"expand"in a){o=a.expand(o),delete e[r];for(n in o)n in e||(e[n]=o[n],t[n]=i)}else t[r]=i}x.Animation=x.extend(er,{tweener:function(e,t){x.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");var n,r=0,i=e.length;for(;i>r;r++)n=e[r],Qn[n]=Qn[n]||[],Qn[n].unshift(t)},prefilter:function(e,t){t?Gn.unshift(e):Gn.push(e)}});function nr(e,t,n){var r,i,o,a,s,l,u=this,c={},p=e.style,f=e.nodeType&&nn(e),d=x._data(e,"fxshow");n.queue||(s=x._queueHooks(e,"fx"),null==s.unqueued&&(s.unqueued=0,l=s.empty.fire,s.empty.fire=function(){s.unqueued||l()}),s.unqueued++,u.always(function(){u.always(function(){s.unqueued--,x.queue(e,"fx").length||s.empty.fire()})})),1===e.nodeType&&("height"in t||"width"in t)&&(n.overflow=[p.overflow,p.overflowX,p.overflowY],"inline"===x.css(e,"display")&&"none"===x.css(e,"float")&&(x.support.inlineBlockNeedsLayout&&"inline"!==ln(e.nodeName)?p.zoom=1:p.display="inline-block")),n.overflow&&(p.overflow="hidden",x.support.shrinkWrapBlocks||u.always(function(){p.overflow=n.overflow[0],p.overflowX=n.overflow[1],p.overflowY=n.overflow[2]}));for(r in t)if(i=t[r],Vn.exec(i)){if(delete t[r],o=o||"toggle"===i,i===(f?"hide":"show"))continue;c[r]=d&&d[r]||x.style(e,r)}if(!x.isEmptyObject(c)){d?"hidden"in d&&(f=d.hidden):d=x._data(e,"fxshow",{}),o&&(d.hidden=!f),f?x(e).show():u.done(function(){x(e).hide()}),u.done(function(){var t;x._removeData(e,"fxshow");for(t in c)x.style(e,t,c[t])});for(r in c)a=Zn(f?d[r]:0,r,u),r in d||(d[r]=a.start,f&&(a.end=a.start,a.start="width"===r||"height"===r?1:0))}}function rr(e,t,n,r,i){return new rr.prototype.init(e,t,n,r,i)}x.Tween=rr,rr.prototype={constructor:rr,init:function(e,t,n,r,i,o){this.elem=e,this.prop=n,this.easing=i||"swing",this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=o||(x.cssNumber[n]?"":"px")},cur:function(){var e=rr.propHooks[this.prop];return e&&e.get?e.get(this):rr.propHooks._default.get(this)},run:function(e){var t,n=rr.propHooks[this.prop];return this.pos=t=this.options.duration?x.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):e,this.now=(this.end-this.start)*t+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),n&&n.set?n.set(this):rr.propHooks._default.set(this),this}},rr.prototype.init.prototype=rr.prototype,rr.propHooks={_default:{get:function(e){var t;return null==e.elem[e.prop]||e.elem.style&&null!=e.elem.style[e.prop]?(t=x.css(e.elem,e.prop,""),t&&"auto"!==t?t:0):e.elem[e.prop]},set:function(e){x.fx.step[e.prop]?x.fx.step[e.prop](e):e.elem.style&&(null!=e.elem.style[x.cssProps[e.prop]]||x.cssHooks[e.prop])?x.style(e.elem,e.prop,e.now+e.unit):e.elem[e.prop]=e.now}}},rr.propHooks.scrollTop=rr.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},x.each(["toggle","show","hide"],function(e,t){var n=x.fn[t];x.fn[t]=function(e,r,i){return null==e||"boolean"==typeof e?n.apply(this,arguments):this.animate(ir(t,!0),e,r,i)}}),x.fn.extend({fadeTo:function(e,t,n,r){return this.filter(nn).css("opacity",0).show().end().animate({opacity:t},e,n,r)},animate:function(e,t,n,r){var i=x.isEmptyObject(e),o=x.speed(t,n,r),a=function(){var t=er(this,x.extend({},e),o);(i||x._data(this,"finish"))&&t.stop(!0)};return a.finish=a,i||o.queue===!1?this.each(a):this.queue(o.queue,a)},stop:function(e,n,r){var i=function(e){var t=e.stop;delete e.stop,t(r)};return"string"!=typeof e&&(r=n,n=e,e=t),n&&e!==!1&&this.queue(e||"fx",[]),this.each(function(){var t=!0,n=null!=e&&e+"queueHooks",o=x.timers,a=x._data(this);if(n)a[n]&&a[n].stop&&i(a[n]);else for(n in a)a[n]&&a[n].stop&&Jn.test(n)&&i(a[n]);for(n=o.length;n--;)o[n].elem!==this||null!=e&&o[n].queue!==e||(o[n].anim.stop(r),t=!1,o.splice(n,1));(t||!r)&&x.dequeue(this,e)})},finish:function(e){return e!==!1&&(e=e||"fx"),this.each(function(){var t,n=x._data(this),r=n[e+"queue"],i=n[e+"queueHooks"],o=x.timers,a=r?r.length:0;for(n.finish=!0,x.queue(this,e,[]),i&&i.stop&&i.stop.call(this,!0),t=o.length;t--;)o[t].elem===this&&o[t].queue===e&&(o[t].anim.stop(!0),o.splice(t,1));for(t=0;a>t;t++)r[t]&&r[t].finish&&r[t].finish.call(this);delete n.finish})}});function ir(e,t){var n,r={height:e},i=0;for(t=t?1:0;4>i;i+=2-t)n=Zt[i],r["margin"+n]=r["padding"+n]=e;return t&&(r.opacity=r.width=e),r}x.each({slideDown:ir("show"),slideUp:ir("hide"),slideToggle:ir("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){x.fn[e]=function(e,n,r){return this.animate(t,e,n,r)}}),x.speed=function(e,t,n){var r=e&&"object"==typeof e?x.extend({},e):{complete:n||!n&&t||x.isFunction(e)&&e,duration:e,easing:n&&t||t&&!x.isFunction(t)&&t};return r.duration=x.fx.off?0:"number"==typeof r.duration?r.duration:r.duration in x.fx.speeds?x.fx.speeds[r.duration]:x.fx.speeds._default,(null==r.queue||r.queue===!0)&&(r.queue="fx"),r.old=r.complete,r.complete=function(){x.isFunction(r.old)&&r.old.call(this),r.queue&&x.dequeue(this,r.queue)},r},x.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2}},x.timers=[],x.fx=rr.prototype.init,x.fx.tick=function(){var e,n=x.timers,r=0;for(Xn=x.now();n.length>r;r++)e=n[r],e()||n[r]!==e||n.splice(r--,1);n.length||x.fx.stop(),Xn=t},x.fx.timer=function(e){e()&&x.timers.push(e)&&x.fx.start()},x.fx.interval=13,x.fx.start=function(){Un||(Un=setInterval(x.fx.tick,x.fx.interval))},x.fx.stop=function(){clearInterval(Un),Un=null},x.fx.speeds={slow:600,fast:200,_default:400},x.fx.step={},x.expr&&x.expr.filters&&(x.expr.filters.animated=function(e){return x.grep(x.timers,function(t){return e===t.elem}).length}),x.fn.offset=function(e){if(arguments.length)return e===t?this:this.each(function(t){x.offset.setOffset(this,e,t)});var n,r,o={top:0,left:0},a=this[0],s=a&&a.ownerDocument;if(s)return n=s.documentElement,x.contains(n,a)?(typeof a.getBoundingClientRect!==i&&(o=a.getBoundingClientRect()),r=or(s),{top:o.top+(r.pageYOffset||n.scrollTop)-(n.clientTop||0),left:o.left+(r.pageXOffset||n.scrollLeft)-(n.clientLeft||0)}):o},x.offset={setOffset:function(e,t,n){var r=x.css(e,"position");"static"===r&&(e.style.position="relative");var i=x(e),o=i.offset(),a=x.css(e,"top"),s=x.css(e,"left"),l=("absolute"===r||"fixed"===r)&&x.inArray("auto",[a,s])>-1,u={},c={},p,f;l?(c=i.position(),p=c.top,f=c.left):(p=parseFloat(a)||0,f=parseFloat(s)||0),x.isFunction(t)&&(t=t.call(e,n,o)),null!=t.top&&(u.top=t.top-o.top+p),null!=t.left&&(u.left=t.left-o.left+f),"using"in t?t.using.call(e,u):i.css(u)}},x.fn.extend({position:function(){if(this[0]){var e,t,n={top:0,left:0},r=this[0];return"fixed"===x.css(r,"position")?t=r.getBoundingClientRect():(e=this.offsetParent(),t=this.offset(),x.nodeName(e[0],"html")||(n=e.offset()),n.top+=x.css(e[0],"borderTopWidth",!0),n.left+=x.css(e[0],"borderLeftWidth",!0)),{top:t.top-n.top-x.css(r,"marginTop",!0),left:t.left-n.left-x.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent||s;while(e&&!x.nodeName(e,"html")&&"static"===x.css(e,"position"))e=e.offsetParent;return e||s})}}),x.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,n){var r=/Y/.test(n);x.fn[e]=function(i){return x.access(this,function(e,i,o){var a=or(e);return o===t?a?n in a?a[n]:a.document.documentElement[i]:e[i]:(a?a.scrollTo(r?x(a).scrollLeft():o,r?o:x(a).scrollTop()):e[i]=o,t)},e,i,arguments.length,null)}});function or(e){return x.isWindow(e)?e:9===e.nodeType?e.defaultView||e.parentWindow:!1}x.each({Height:"height",Width:"width"},function(e,n){x.each({padding:"inner"+e,content:n,"":"outer"+e},function(r,i){x.fn[i]=function(i,o){var a=arguments.length&&(r||"boolean"!=typeof i),s=r||(i===!0||o===!0?"margin":"border");return x.access(this,function(n,r,i){var o;return x.isWindow(n)?n.document.documentElement["client"+e]:9===n.nodeType?(o=n.documentElement,Math.max(n.body["scroll"+e],o["scroll"+e],n.body["offset"+e],o["offset"+e],o["client"+e])):i===t?x.css(n,r,s):x.style(n,r,i,s)},n,a?i:t,a,null)}})}),x.fn.size=function(){return this.length},x.fn.andSelf=x.fn.addBack,"object"==typeof module&&module&&"object"==typeof module.exports?module.exports=x:(e.jQuery=e.$=x,"function"==typeof define&&define.amd&&define("jquery",[],function(){return x}))})(window); ```
/content/code_sandbox/test/libs/jquery-1.10.2.min.js
javascript
2016-01-19T00:54:39
2024-08-14T11:30:58
tribute
zurb/tribute
2,017
31,238
```javascript // Thanks to path_to_url import "./utils"; class TributeRange { constructor(tribute) { this.tribute = tribute this.tribute.range = this } getDocument() { let iframe if (this.tribute.current.collection) { iframe = this.tribute.current.collection.iframe } if (!iframe) { return document } return iframe.contentWindow.document } positionMenuAtCaret(scrollTo) { let context = this.tribute.current, coordinates let info = this.getTriggerInfo(false, this.tribute.hasTrailingSpace, true, this.tribute.allowSpaces, this.tribute.autocompleteMode) if (typeof info !== 'undefined') { if(!this.tribute.positionMenu){ this.tribute.menu.style.cssText = `display: block;` return } if (!this.isContentEditable(context.element)) { coordinates = this.getTextAreaOrInputUnderlinePosition(this.tribute.current.element, info.mentionPosition) } else { coordinates = this.getContentEditableCaretPosition(info.mentionPosition) } this.tribute.menu.style.cssText = `top: ${coordinates.top}px; left: ${coordinates.left}px; right: ${coordinates.right}px; bottom: ${coordinates.bottom}px; max-height: ${coordinates.maxHeight || 500}px; max-width: ${coordinates.maxWidth || 300}px; position: ${coordinates.position || 'absolute'}; display: block;` if (coordinates.left === 'auto') { this.tribute.menu.style.left = 'auto' } if (coordinates.top === 'auto') { this.tribute.menu.style.top = 'auto' } if (scrollTo) this.scrollIntoView() } else { this.tribute.menu.style.cssText = 'display: none' } } get menuContainerIsBody() { return this.tribute.menuContainer === document.body || !this.tribute.menuContainer; } selectElement(targetElement, path, offset) { let range let elem = targetElement if (path) { for (var i = 0; i < path.length; i++) { elem = elem.childNodes[path[i]] if (elem === undefined) { return } while (elem.length < offset) { offset -= elem.length elem = elem.nextSibling } if (elem.childNodes.length === 0 && !elem.length) { elem = elem.previousSibling } } } let sel = this.getWindowSelection() range = this.getDocument().createRange() range.setStart(elem, offset) range.setEnd(elem, offset) range.collapse(true) try { sel.removeAllRanges() } catch (error) {} sel.addRange(range) targetElement.focus() } replaceTriggerText(text, requireLeadingSpace, hasTrailingSpace, originalEvent, item) { let info = this.getTriggerInfo(true, hasTrailingSpace, requireLeadingSpace, this.tribute.allowSpaces, this.tribute.autocompleteMode) if (info !== undefined) { let context = this.tribute.current let replaceEvent = new CustomEvent('tribute-replaced', { detail: { item: item, instance: context, context: info, event: originalEvent, } }) if (!this.isContentEditable(context.element)) { let myField = this.tribute.current.element let textSuffix = typeof this.tribute.replaceTextSuffix == 'string' ? this.tribute.replaceTextSuffix : ' ' text += textSuffix let startPos = info.mentionPosition let endPos = info.mentionPosition + info.mentionText.length + (textSuffix === '' ? 1 : textSuffix.length) if (!this.tribute.autocompleteMode) { endPos += info.mentionTriggerChar.length - 1 } myField.value = myField.value.substring(0, startPos) + text + myField.value.substring(endPos, myField.value.length) myField.selectionStart = startPos + text.length myField.selectionEnd = startPos + text.length } else { // add a space to the end of the pasted text let textSuffix = typeof this.tribute.replaceTextSuffix == 'string' ? this.tribute.replaceTextSuffix : '\xA0' text += textSuffix let endPos = info.mentionPosition + info.mentionText.length if (!this.tribute.autocompleteMode) { endPos += info.mentionTriggerChar.length } this.pasteHtml(text, info.mentionPosition, endPos) } context.element.dispatchEvent(new CustomEvent('input', { bubbles: true })) context.element.dispatchEvent(replaceEvent) } } pasteHtml(html, startPos, endPos) { let range, sel sel = this.getWindowSelection() range = this.getDocument().createRange() range.setStart(sel.anchorNode, startPos) range.setEnd(sel.anchorNode, endPos) range.deleteContents() let el = this.getDocument().createElement('div') el.innerHTML = html let frag = this.getDocument().createDocumentFragment(), node, lastNode while ((node = el.firstChild)) { lastNode = frag.appendChild(node) } range.insertNode(frag) // Preserve the selection if (lastNode) { range = range.cloneRange() range.setStartAfter(lastNode) range.collapse(true) sel.removeAllRanges() sel.addRange(range) } } getWindowSelection() { if (this.tribute.collection.iframe) { return this.tribute.collection.iframe.contentWindow.getSelection() } return window.getSelection() } getNodePositionInParent(element) { if (element.parentNode === null) { return 0 } for (var i = 0; i < element.parentNode.childNodes.length; i++) { let node = element.parentNode.childNodes[i] if (node === element) { return i } } } getContentEditableSelectedPath(ctx) { let sel = this.getWindowSelection() let selected = sel.anchorNode let path = [] let offset if (selected != null) { let i let ce = selected.contentEditable while (selected !== null && ce !== 'true') { i = this.getNodePositionInParent(selected) path.push(i) selected = selected.parentNode if (selected !== null) { ce = selected.contentEditable } } path.reverse() // getRangeAt may not exist, need alternative offset = sel.getRangeAt(0).startOffset return { selected: selected, path: path, offset: offset } } } getTextPrecedingCurrentSelection() { let context = this.tribute.current, text = '' if (!this.isContentEditable(context.element)) { let textComponent = this.tribute.current.element; if (textComponent) { let startPos = textComponent.selectionStart if (textComponent.value && startPos >= 0) { text = textComponent.value.substring(0, startPos) } } } else { let selectedElem = this.getWindowSelection().anchorNode if (selectedElem != null) { let workingNodeContent = selectedElem.textContent let selectStartOffset = this.getWindowSelection().getRangeAt(0).startOffset if (workingNodeContent && selectStartOffset >= 0) { text = workingNodeContent.substring(0, selectStartOffset) } } } return text } getLastWordInText(text) { var wordsArray; if (this.tribute.autocompleteSeparator) { wordsArray = text.split(this.tribute.autocompleteSeparator); } else { wordsArray = text.split(/\s+/); } var wordsCount = wordsArray.length - 1; return wordsArray[wordsCount]; } getTriggerInfo(menuAlreadyActive, hasTrailingSpace, requireLeadingSpace, allowSpaces, isAutocomplete) { let ctx = this.tribute.current let selected, path, offset if (!this.isContentEditable(ctx.element)) { selected = this.tribute.current.element } else { let selectionInfo = this.getContentEditableSelectedPath(ctx) if (selectionInfo) { selected = selectionInfo.selected path = selectionInfo.path offset = selectionInfo.offset } } let effectiveRange = this.getTextPrecedingCurrentSelection() let lastWordOfEffectiveRange = this.getLastWordInText(effectiveRange) if (isAutocomplete) { return { mentionPosition: effectiveRange.length - lastWordOfEffectiveRange.length, mentionText: lastWordOfEffectiveRange, mentionSelectedElement: selected, mentionSelectedPath: path, mentionSelectedOffset: offset } } if (effectiveRange !== undefined && effectiveRange !== null) { let mostRecentTriggerCharPos = -1 let triggerChar this.tribute.collection.forEach(config => { let c = config.trigger let idx = config.requireLeadingSpace ? this.lastIndexWithLeadingSpace(effectiveRange, c) : effectiveRange.lastIndexOf(c) if (idx > mostRecentTriggerCharPos) { mostRecentTriggerCharPos = idx triggerChar = c requireLeadingSpace = config.requireLeadingSpace } }) if (mostRecentTriggerCharPos >= 0 && ( mostRecentTriggerCharPos === 0 || !requireLeadingSpace || /\s/.test( effectiveRange.substring( mostRecentTriggerCharPos - 1, mostRecentTriggerCharPos) ) ) ) { let currentTriggerSnippet = effectiveRange.substring(mostRecentTriggerCharPos + triggerChar.length, effectiveRange.length) triggerChar = effectiveRange.substring(mostRecentTriggerCharPos, mostRecentTriggerCharPos + triggerChar.length) let firstSnippetChar = currentTriggerSnippet.substring(0, 1) let leadingSpace = currentTriggerSnippet.length > 0 && ( firstSnippetChar === ' ' || firstSnippetChar === '\xA0' ) if (hasTrailingSpace) { currentTriggerSnippet = currentTriggerSnippet.trim() } let regex = allowSpaces ? /[^\S ]/g : /[\xA0\s]/g; this.tribute.hasTrailingSpace = regex.test(currentTriggerSnippet); if (!leadingSpace && (menuAlreadyActive || !(regex.test(currentTriggerSnippet)))) { return { mentionPosition: mostRecentTriggerCharPos, mentionText: currentTriggerSnippet, mentionSelectedElement: selected, mentionSelectedPath: path, mentionSelectedOffset: offset, mentionTriggerChar: triggerChar } } } } } lastIndexWithLeadingSpace (str, trigger) { let reversedStr = str.split('').reverse().join('') let index = -1 for (let cidx = 0, len = str.length; cidx < len; cidx++) { let firstChar = cidx === str.length - 1 let leadingSpace = /\s/.test(reversedStr[cidx + 1]) let match = true for (let triggerIdx = trigger.length - 1; triggerIdx >= 0; triggerIdx--) { if (trigger[triggerIdx] !== reversedStr[cidx-triggerIdx]) { match = false break } } if (match && (firstChar || leadingSpace)) { index = str.length - 1 - cidx break } } return index } isContentEditable(element) { return element.nodeName !== 'INPUT' && element.nodeName !== 'TEXTAREA' } isMenuOffScreen(coordinates, menuDimensions) { let windowWidth = window.innerWidth let windowHeight = window.innerHeight let doc = document.documentElement let windowLeft = (window.pageXOffset || doc.scrollLeft) - (doc.clientLeft || 0) let windowTop = (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0) let menuTop = typeof coordinates.top === 'number' ? coordinates.top : windowTop + windowHeight - coordinates.bottom - menuDimensions.height let menuRight = typeof coordinates.right === 'number' ? coordinates.right : coordinates.left + menuDimensions.width let menuBottom = typeof coordinates.bottom === 'number' ? coordinates.bottom : coordinates.top + menuDimensions.height let menuLeft = typeof coordinates.left === 'number' ? coordinates.left : windowLeft + windowWidth - coordinates.right - menuDimensions.width return { top: menuTop < Math.floor(windowTop), right: menuRight > Math.ceil(windowLeft + windowWidth), bottom: menuBottom > Math.ceil(windowTop + windowHeight), left: menuLeft < Math.floor(windowLeft) } } getMenuDimensions() { // Width of the menu depends of its contents and position // We must check what its width would be without any obstruction // This way, we can achieve good positioning for flipping the menu let dimensions = { width: null, height: null } this.tribute.menu.style.cssText = `top: 0px; left: 0px; position: fixed; display: block; visibility; hidden; max-height:500px;` dimensions.width = this.tribute.menu.offsetWidth dimensions.height = this.tribute.menu.offsetHeight this.tribute.menu.style.cssText = `display: none;` return dimensions } getTextAreaOrInputUnderlinePosition(element, position, flipped) { let properties = ['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' ] let isFirefox = (window.mozInnerScreenX !== null) let div = this.getDocument().createElement('div') div.id = 'input-textarea-caret-position-mirror-div' this.getDocument().body.appendChild(div) let style = div.style let computed = window.getComputedStyle ? getComputedStyle(element) : element.currentStyle style.whiteSpace = 'pre-wrap' if (element.nodeName !== 'INPUT') { style.wordWrap = 'break-word' } style.position = 'absolute' style.visibility = 'hidden' // transfer the element's properties to the div properties.forEach(prop => { style[prop] = computed[prop] }) //NOT SURE WHY THIS IS HERE AND IT DOESNT SEEM HELPFUL // if (isFirefox) { // style.width = `${(parseInt(computed.width) - 2)}px` // if (element.scrollHeight > parseInt(computed.height)) // style.overflowY = 'scroll' // } else { // style.overflow = 'hidden' // } let span0 = document.createElement('span') span0.textContent = element.value.substring(0, position) div.appendChild(span0) if (element.nodeName === 'INPUT') { div.textContent = div.textContent.replace(/\s/g, '') } //Create a span in the div that represents where the cursor //should be let span = this.getDocument().createElement('span') //we give it no content as this represents the cursor span.textContent = '&#x200B;' div.appendChild(span) let span2 = this.getDocument().createElement('span'); span2.textContent = element.value.substring(position); div.appendChild(span2); let rect = element.getBoundingClientRect() //position the div exactly over the element //so we can get the bounding client rect for the span and //it should represent exactly where the cursor is div.style.position = 'fixed'; div.style.left = rect.left + 'px'; div.style.top = rect.top + 'px'; div.style.width = rect.width + 'px'; div.style.height = rect.height + 'px'; div.scrollTop = element.scrollTop; var spanRect = span.getBoundingClientRect(); this.getDocument().body.removeChild(div) return this.getFixedCoordinatesRelativeToRect(spanRect); } getContentEditableCaretPosition(selectedNodePosition) { let range let sel = this.getWindowSelection() range = this.getDocument().createRange() range.setStart(sel.anchorNode, selectedNodePosition) range.setEnd(sel.anchorNode, selectedNodePosition) range.collapse(false) let rect = range.getBoundingClientRect() return this.getFixedCoordinatesRelativeToRect(rect); } getFixedCoordinatesRelativeToRect(rect) { let coordinates = { position: 'fixed', left: rect.left, top: rect.top + rect.height } let menuDimensions = this.getMenuDimensions() var availableSpaceOnTop = rect.top; var availableSpaceOnBottom = window.innerHeight - (rect.top + rect.height); //check to see where's the right place to put the menu vertically if (availableSpaceOnBottom < menuDimensions.height) { if (availableSpaceOnTop >= menuDimensions.height || availableSpaceOnTop > availableSpaceOnBottom) { coordinates.top = 'auto'; coordinates.bottom = window.innerHeight - rect.top; if (availableSpaceOnBottom < menuDimensions.height) { coordinates.maxHeight = availableSpaceOnTop; } } else { if (availableSpaceOnTop < menuDimensions.height) { coordinates.maxHeight = availableSpaceOnBottom; } } } var availableSpaceOnLeft = rect.left; var availableSpaceOnRight = window.innerWidth - rect.left; //check to see where's the right place to put the menu horizontally if (availableSpaceOnRight < menuDimensions.width) { if (availableSpaceOnLeft >= menuDimensions.width || availableSpaceOnLeft > availableSpaceOnRight) { coordinates.left = 'auto'; coordinates.right = window.innerWidth - rect.left; if (availableSpaceOnRight < menuDimensions.width) { coordinates.maxWidth = availableSpaceOnLeft; } } else { if (availableSpaceOnLeft < menuDimensions.width) { coordinates.maxWidth = availableSpaceOnRight; } } } return coordinates } scrollIntoView(elem) { let reasonableBuffer = 20, clientRect let maxScrollDisplacement = 100 let e = this.menu if (typeof e === 'undefined') return; while (clientRect === undefined || clientRect.height === 0) { clientRect = e.getBoundingClientRect() if (clientRect.height === 0) { e = e.childNodes[0] if (e === undefined || !e.getBoundingClientRect) { return } } } let elemTop = clientRect.top let elemBottom = elemTop + clientRect.height if (elemTop < 0) { window.scrollTo(0, window.pageYOffset + clientRect.top - reasonableBuffer) } else if (elemBottom > window.innerHeight) { let maxY = window.pageYOffset + clientRect.top - reasonableBuffer if (maxY - window.pageYOffset > maxScrollDisplacement) { maxY = window.pageYOffset + maxScrollDisplacement } let targetY = window.pageYOffset - (window.innerHeight - elemBottom) if (targetY > maxY) { targetY = maxY } window.scrollTo(0, targetY) } } } export default TributeRange; ```
/content/code_sandbox/src/TributeRange.js
javascript
2016-01-19T00:54:39
2024-08-14T11:30:58
tribute
zurb/tribute
2,017
4,294
```javascript class TributeMenuEvents { constructor(tribute) { this.tribute = tribute; this.tribute.menuEvents = this; this.menu = this.tribute.menu; } bind(menu) { this.menuClickEvent = this.tribute.events.click.bind(null, this); this.menuContainerScrollEvent = this.debounce( () => { if (this.tribute.isActive) { this.tribute.hideMenu(); } }, 10, false ); this.windowResizeEvent = this.debounce( () => { if (this.tribute.isActive) { this.tribute.hideMenu(); } }, 10, false ); // fixes IE11 issues with mousedown this.tribute.range .getDocument() .addEventListener("MSPointerDown", this.menuClickEvent, false); this.tribute.range .getDocument() .addEventListener("mousedown", this.menuClickEvent, false); window.addEventListener("resize", this.windowResizeEvent); if (this.menuContainer) { this.menuContainer.addEventListener( "scroll", this.menuContainerScrollEvent, false ); } else { window.addEventListener("scroll", this.menuContainerScrollEvent); } } unbind(menu) { this.tribute.range .getDocument() .removeEventListener("mousedown", this.menuClickEvent, false); this.tribute.range .getDocument() .removeEventListener("MSPointerDown", this.menuClickEvent, false); window.removeEventListener("resize", this.windowResizeEvent); if (this.menuContainer) { this.menuContainer.removeEventListener( "scroll", this.menuContainerScrollEvent, false ); } else { window.removeEventListener("scroll", this.menuContainerScrollEvent); } } debounce(func, wait, immediate) { var timeout; return () => { var context = this, args = arguments; var later = () => { timeout = null; if (!immediate) func.apply(context, args); }; var callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait); if (callNow) func.apply(context, args); }; } } export default TributeMenuEvents; ```
/content/code_sandbox/src/TributeMenuEvents.js
javascript
2016-01-19T00:54:39
2024-08-14T11:30:58
tribute
zurb/tribute
2,017
488
```javascript import "./utils"; import TributeEvents from "./TributeEvents"; import TributeMenuEvents from "./TributeMenuEvents"; import TributeRange from "./TributeRange"; import TributeSearch from "./TributeSearch"; class Tribute { constructor({ values = null, loadingItemTemplate = null, iframe = null, selectClass = "highlight", containerClass = "tribute-container", itemClass = "", trigger = "@", autocompleteMode = false, autocompleteSeparator = null, selectTemplate = null, menuItemTemplate = null, lookup = "key", fillAttr = "value", collection = null, menuContainer = null, noMatchTemplate = null, requireLeadingSpace = true, allowSpaces = false, replaceTextSuffix = null, positionMenu = true, spaceSelectsMatch = false, searchOpts = {}, menuItemLimit = null, menuShowMinLength = 0 }) { this.autocompleteMode = autocompleteMode; this.autocompleteSeparator = autocompleteSeparator; this.menuSelected = 0; this.current = {}; this.inputEvent = false; this.isActive = false; this.menuContainer = menuContainer; this.allowSpaces = allowSpaces; this.replaceTextSuffix = replaceTextSuffix; this.positionMenu = positionMenu; this.hasTrailingSpace = false; this.spaceSelectsMatch = spaceSelectsMatch; if (this.autocompleteMode) { trigger = ""; allowSpaces = false; } if (values) { this.collection = [ { // symbol that starts the lookup trigger: trigger, // is it wrapped in an iframe iframe: iframe, // class applied to selected item selectClass: selectClass, // class applied to the Container containerClass: containerClass, // class applied to each item itemClass: itemClass, // function called on select that retuns the content to insert selectTemplate: ( selectTemplate || Tribute.defaultSelectTemplate ).bind(this), // function called that returns content for an item menuItemTemplate: ( menuItemTemplate || Tribute.defaultMenuItemTemplate ).bind(this), // function called when menu is empty, disables hiding of menu. noMatchTemplate: (t => { if (typeof t === "string") { if (t.trim() === "") return null; return t; } if (typeof t === "function") { return t.bind(this); } return ( noMatchTemplate || function() { return "<li>No Match Found!</li>"; }.bind(this) ); })(noMatchTemplate), // column to search against in the object lookup: lookup, // column that contains the content to insert by default fillAttr: fillAttr, // array of objects or a function returning an array of objects values: values, // useful for when values is an async function loadingItemTemplate: loadingItemTemplate, requireLeadingSpace: requireLeadingSpace, searchOpts: searchOpts, menuItemLimit: menuItemLimit, menuShowMinLength: menuShowMinLength } ]; } else if (collection) { if (this.autocompleteMode) console.warn( "Tribute in autocomplete mode does not work for collections" ); this.collection = collection.map(item => { return { trigger: item.trigger || trigger, iframe: item.iframe || iframe, selectClass: item.selectClass || selectClass, containerClass: item.containerClass || containerClass, itemClass: item.itemClass || itemClass, selectTemplate: ( item.selectTemplate || Tribute.defaultSelectTemplate ).bind(this), menuItemTemplate: ( item.menuItemTemplate || Tribute.defaultMenuItemTemplate ).bind(this), // function called when menu is empty, disables hiding of menu. noMatchTemplate: (t => { if (typeof t === "string") { if (t.trim() === "") return null; return t; } if (typeof t === "function") { return t.bind(this); } return ( noMatchTemplate || function() { return "<li>No Match Found!</li>"; }.bind(this) ); })(noMatchTemplate), lookup: item.lookup || lookup, fillAttr: item.fillAttr || fillAttr, values: item.values, loadingItemTemplate: item.loadingItemTemplate, requireLeadingSpace: item.requireLeadingSpace, searchOpts: item.searchOpts || searchOpts, menuItemLimit: item.menuItemLimit || menuItemLimit, menuShowMinLength: item.menuShowMinLength || menuShowMinLength }; }); } else { throw new Error("[Tribute] No collection specified."); } new TributeRange(this); new TributeEvents(this); new TributeMenuEvents(this); new TributeSearch(this); } get isActive() { return this._isActive; } set isActive(val) { if (this._isActive != val) { this._isActive = val; if (this.current.element) { let noMatchEvent = new CustomEvent(`tribute-active-${val}`); this.current.element.dispatchEvent(noMatchEvent); } } } static defaultSelectTemplate(item) { if (typeof item === "undefined") return `${this.current.collection.trigger}${this.current.mentionText}`; if (this.range.isContentEditable(this.current.element)) { return ( '<span class="tribute-mention">' + (this.current.collection.trigger + item.original[this.current.collection.fillAttr]) + "</span>" ); } return ( this.current.collection.trigger + item.original[this.current.collection.fillAttr] ); } static defaultMenuItemTemplate(matchItem) { return matchItem.string; } static inputTypes() { return ["TEXTAREA", "INPUT"]; } triggers() { return this.collection.map(config => { return config.trigger; }); } attach(el) { if (!el) { throw new Error("[Tribute] Must pass in a DOM node or NodeList."); } // Check if it is a jQuery collection if (typeof jQuery !== "undefined" && el instanceof jQuery) { el = el.get(); } // Is el an Array/Array-like object? if ( el.constructor === NodeList || el.constructor === HTMLCollection || el.constructor === Array ) { let length = el.length; for (var i = 0; i < length; ++i) { this._attach(el[i]); } } else { this._attach(el); } } _attach(el) { if (el.hasAttribute("data-tribute")) { console.warn("Tribute was already bound to " + el.nodeName); } this.ensureEditable(el); this.events.bind(el); el.setAttribute("data-tribute", true); } ensureEditable(element) { if (Tribute.inputTypes().indexOf(element.nodeName) === -1) { if (!element.contentEditable) { throw new Error("[Tribute] Cannot bind to " + element.nodeName + ", not contentEditable"); } } } createMenu(containerClass) { let wrapper = this.range.getDocument().createElement("div"), ul = this.range.getDocument().createElement("ul"); wrapper.className = containerClass; wrapper.appendChild(ul); if (this.menuContainer) { return this.menuContainer.appendChild(wrapper); } return this.range.getDocument().body.appendChild(wrapper); } showMenuFor(element, scrollTo) { // Only proceed if menu isn't already shown for the current element & mentionText if ( this.isActive && this.current.element === element && this.current.mentionText === this.currentMentionTextSnapshot ) { return; } this.currentMentionTextSnapshot = this.current.mentionText; // create the menu if it doesn't exist. if (!this.menu) { this.menu = this.createMenu(this.current.collection.containerClass); element.tributeMenu = this.menu; this.menuEvents.bind(this.menu); } this.isActive = true; this.menuSelected = 0; if (!this.current.mentionText) { this.current.mentionText = ""; } const processValues = values => { // Tribute may not be active any more by the time the value callback returns if (!this.isActive) { return; } let items = this.search.filter(this.current.mentionText, values, { pre: this.current.collection.searchOpts.pre || "<span>", post: this.current.collection.searchOpts.post || "</span>", skip: this.current.collection.searchOpts.skip, extract: el => { if (typeof this.current.collection.lookup === "string") { return el[this.current.collection.lookup]; } else if (typeof this.current.collection.lookup === "function") { return this.current.collection.lookup(el, this.current.mentionText); } else { throw new Error( "Invalid lookup attribute, lookup must be string or function." ); } } }); if (this.current.collection.menuItemLimit) { items = items.slice(0, this.current.collection.menuItemLimit); } this.current.filteredItems = items; let ul = this.menu.querySelector("ul"); if (!items.length) { let noMatchEvent = new CustomEvent("tribute-no-match", { detail: this.menu }); this.current.element.dispatchEvent(noMatchEvent); if ( (typeof this.current.collection.noMatchTemplate === "function" && !this.current.collection.noMatchTemplate()) || !this.current.collection.noMatchTemplate ) { this.hideMenu(); } else { typeof this.current.collection.noMatchTemplate === "function" ? (ul.innerHTML = this.current.collection.noMatchTemplate()) : (ul.innerHTML = this.current.collection.noMatchTemplate); this.range.positionMenuAtCaret(scrollTo); } return; } ul.innerHTML = ""; let fragment = this.range.getDocument().createDocumentFragment(); items.forEach((item, index) => { let li = this.range.getDocument().createElement("li"); li.setAttribute("data-index", index); li.className = this.current.collection.itemClass; li.addEventListener("mousemove", e => { let [li, index] = this._findLiTarget(e.target); if (e.movementY !== 0) { this.events.setActiveLi(index); } }); if (this.menuSelected === index) { li.classList.add(this.current.collection.selectClass); } li.innerHTML = this.current.collection.menuItemTemplate(item); fragment.appendChild(li); }); ul.appendChild(fragment); this.range.positionMenuAtCaret(scrollTo); }; if (typeof this.current.collection.values === "function") { if (this.current.collection.loadingItemTemplate) { this.menu.querySelector("ul").innerHTML = this.current.collection.loadingItemTemplate; this.range.positionMenuAtCaret(scrollTo); } this.current.collection.values(this.current.mentionText, processValues); } else { processValues(this.current.collection.values); } } _findLiTarget(el) { if (!el) return []; const index = el.getAttribute("data-index"); return !index ? this._findLiTarget(el.parentNode) : [el, index]; } showMenuForCollection(element, collectionIndex) { if (element !== document.activeElement) { this.placeCaretAtEnd(element); } this.current.collection = this.collection[collectionIndex || 0]; this.current.externalTrigger = true; this.current.element = element; if (element.isContentEditable) this.insertTextAtCursor(this.current.collection.trigger); else this.insertAtCaret(element, this.current.collection.trigger); this.showMenuFor(element); } // TODO: make sure this works for inputs/textareas placeCaretAtEnd(el) { el.focus(); if ( typeof window.getSelection != "undefined" && typeof document.createRange != "undefined" ) { var range = document.createRange(); range.selectNodeContents(el); range.collapse(false); var sel = window.getSelection(); sel.removeAllRanges(); sel.addRange(range); } else if (typeof document.body.createTextRange != "undefined") { var textRange = document.body.createTextRange(); textRange.moveToElementText(el); textRange.collapse(false); textRange.select(); } } // for contenteditable insertTextAtCursor(text) { var sel, range, html; sel = window.getSelection(); range = sel.getRangeAt(0); range.deleteContents(); var textNode = document.createTextNode(text); range.insertNode(textNode); range.selectNodeContents(textNode); range.collapse(false); sel.removeAllRanges(); sel.addRange(range); } // for regular inputs insertAtCaret(textarea, text) { var scrollPos = textarea.scrollTop; var caretPos = textarea.selectionStart; var front = textarea.value.substring(0, caretPos); var back = textarea.value.substring( textarea.selectionEnd, textarea.value.length ); textarea.value = front + text + back; caretPos = caretPos + text.length; textarea.selectionStart = caretPos; textarea.selectionEnd = caretPos; textarea.focus(); textarea.scrollTop = scrollPos; } hideMenu() { if (this.menu) { this.menu.style.cssText = "display: none;"; this.isActive = false; this.menuSelected = 0; this.current = {}; } } selectItemAtIndex(index, originalEvent) { index = parseInt(index); if (typeof index !== "number" || isNaN(index)) return; let item = this.current.filteredItems[index]; let content = this.current.collection.selectTemplate(item); if (content !== null) this.replaceText(content, originalEvent, item); } replaceText(content, originalEvent, item) { this.range.replaceTriggerText(content, true, true, originalEvent, item); } _append(collection, newValues, replace) { if (typeof collection.values === "function") { throw new Error("Unable to append to values, as it is a function."); } else if (!replace) { collection.values = collection.values.concat(newValues); } else { collection.values = newValues; } } append(collectionIndex, newValues, replace) { let index = parseInt(collectionIndex); if (typeof index !== "number") throw new Error("please provide an index for the collection to update."); let collection = this.collection[index]; this._append(collection, newValues, replace); } appendCurrent(newValues, replace) { if (this.isActive) { this._append(this.current.collection, newValues, replace); } else { throw new Error( "No active state. Please use append instead and pass an index." ); } } detach(el) { if (!el) { throw new Error("[Tribute] Must pass in a DOM node or NodeList."); } // Check if it is a jQuery collection if (typeof jQuery !== "undefined" && el instanceof jQuery) { el = el.get(); } // Is el an Array/Array-like object? if ( el.constructor === NodeList || el.constructor === HTMLCollection || el.constructor === Array ) { let length = el.length; for (var i = 0; i < length; ++i) { this._detach(el[i]); } } else { this._detach(el); } } _detach(el) { this.events.unbind(el); if (el.tributeMenu) { this.menuEvents.unbind(el.tributeMenu); } setTimeout(() => { el.removeAttribute("data-tribute"); this.isActive = false; if (el.tributeMenu) { el.tributeMenu.remove(); } }); } } export default Tribute; ```
/content/code_sandbox/src/Tribute.js
javascript
2016-01-19T00:54:39
2024-08-14T11:30:58
tribute
zurb/tribute
2,017
3,473
```javascript /** * Tribute.js * Native ES6 JavaScript @mention Plugin **/ import "./tribute.scss"; import Tribute from "./Tribute"; export default Tribute; ```
/content/code_sandbox/src/index.js
javascript
2016-01-19T00:54:39
2024-08-14T11:30:58
tribute
zurb/tribute
2,017
33
```javascript class TributeEvents { constructor(tribute) { this.tribute = tribute; this.tribute.events = this; } static keys() { 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" } ]; } bind(element) { element.boundKeydown = this.keydown.bind(element, this); element.boundKeyup = this.keyup.bind(element, this); element.boundInput = this.input.bind(element, this); element.addEventListener("keydown", element.boundKeydown, true); element.addEventListener("keyup", element.boundKeyup, true); element.addEventListener("input", element.boundInput, true); } unbind(element) { element.removeEventListener("keydown", element.boundKeydown, true); element.removeEventListener("keyup", element.boundKeyup, true); element.removeEventListener("input", element.boundInput, true); delete element.boundKeydown; delete element.boundKeyup; delete element.boundInput; } keydown(instance, event) { if (instance.shouldDeactivate(event)) { instance.tribute.isActive = false; instance.tribute.hideMenu(); } let element = this; instance.commandEvent = false; TributeEvents.keys().forEach(o => { if (o.key === event.keyCode) { instance.commandEvent = true; instance.callbacks()[o.value.toLowerCase()](event, element); } }); } input(instance, event) { instance.inputEvent = true; instance.keyup.call(this, instance, event); } click(instance, event) { let tribute = instance.tribute; if (tribute.menu && tribute.menu.contains(event.target)) { let li = event.target; event.preventDefault(); event.stopPropagation(); while (li.nodeName.toLowerCase() !== "li") { li = li.parentNode; if (!li || li === tribute.menu) { throw new Error("cannot find the <li> container for the click"); } } tribute.selectItemAtIndex(li.getAttribute("data-index"), event); tribute.hideMenu(); // TODO: should fire with externalTrigger and target is outside of menu } else if (tribute.current.element && !tribute.current.externalTrigger) { tribute.current.externalTrigger = false; setTimeout(() => tribute.hideMenu()); } } keyup(instance, event) { if (instance.inputEvent) { instance.inputEvent = false; } instance.updateSelection(this); if (!event.keyCode || event.keyCode === 27) return; if (!instance.tribute.allowSpaces && instance.tribute.hasTrailingSpace) { instance.tribute.hasTrailingSpace = false; instance.commandEvent = true; instance.callbacks()["space"](event, this); return; } if (!instance.tribute.isActive) { if (instance.tribute.autocompleteMode) { instance.callbacks().triggerChar(event, this, ""); } else { let keyCode = instance.getKeyCode(instance, this, event); if (isNaN(keyCode) || !keyCode) return; let trigger = instance.tribute.triggers().find(trigger => { return trigger.charCodeAt(0) === keyCode; }); if (typeof trigger !== "undefined") { instance.callbacks().triggerChar(event, this, trigger); } } } if ( instance.tribute.current.mentionText.length < instance.tribute.current.collection.menuShowMinLength ) { return; } if ( ((instance.tribute.current.trigger || instance.tribute.autocompleteMode) && instance.commandEvent === false) || (instance.tribute.isActive && event.keyCode === 8) ) { instance.tribute.showMenuFor(this, true); } } shouldDeactivate(event) { if (!this.tribute.isActive) return false; if (this.tribute.current.mentionText.length === 0) { let eventKeyPressed = false; TributeEvents.keys().forEach(o => { if (event.keyCode === o.key) eventKeyPressed = true; }); return !eventKeyPressed; } return false; } getKeyCode(instance, el, event) { let char; let tribute = instance.tribute; let info = tribute.range.getTriggerInfo( false, tribute.hasTrailingSpace, true, tribute.allowSpaces, tribute.autocompleteMode ); if (info) { return info.mentionTriggerChar.charCodeAt(0); } else { return false; } } updateSelection(el) { this.tribute.current.element = el; let info = this.tribute.range.getTriggerInfo( false, this.tribute.hasTrailingSpace, true, this.tribute.allowSpaces, this.tribute.autocompleteMode ); if (info) { this.tribute.current.selectedPath = info.mentionSelectedPath; this.tribute.current.mentionText = info.mentionText; this.tribute.current.selectedOffset = info.mentionSelectedOffset; } } callbacks() { return { triggerChar: (e, el, trigger) => { let tribute = this.tribute; tribute.current.trigger = trigger; let collectionItem = tribute.collection.find(item => { return item.trigger === trigger; }); tribute.current.collection = collectionItem; if ( tribute.current.mentionText.length >= tribute.current.collection.menuShowMinLength && tribute.inputEvent ) { tribute.showMenuFor(el, true); } }, enter: (e, el) => { // choose selection if (this.tribute.isActive && this.tribute.current.filteredItems) { e.preventDefault(); e.stopPropagation(); setTimeout(() => { this.tribute.selectItemAtIndex(this.tribute.menuSelected, e); this.tribute.hideMenu(); }, 0); } }, escape: (e, el) => { if (this.tribute.isActive) { e.preventDefault(); e.stopPropagation(); this.tribute.isActive = false; this.tribute.hideMenu(); } }, tab: (e, el) => { // choose first match this.callbacks().enter(e, el); }, space: (e, el) => { if (this.tribute.isActive) { if (this.tribute.spaceSelectsMatch) { this.callbacks().enter(e, el); } else if (!this.tribute.allowSpaces) { e.stopPropagation(); setTimeout(() => { this.tribute.hideMenu(); this.tribute.isActive = false; }, 0); } } }, up: (e, el) => { // navigate up ul if (this.tribute.isActive && this.tribute.current.filteredItems) { e.preventDefault(); e.stopPropagation(); let count = this.tribute.current.filteredItems.length, selected = this.tribute.menuSelected; if (count > selected && selected > 0) { this.tribute.menuSelected--; this.setActiveLi(); } else if (selected === 0) { this.tribute.menuSelected = count - 1; this.setActiveLi(); this.tribute.menu.scrollTop = this.tribute.menu.scrollHeight; } } }, down: (e, el) => { // navigate down ul if (this.tribute.isActive && this.tribute.current.filteredItems) { e.preventDefault(); e.stopPropagation(); let count = this.tribute.current.filteredItems.length - 1, selected = this.tribute.menuSelected; if (count > selected) { this.tribute.menuSelected++; this.setActiveLi(); } else if (count === selected) { this.tribute.menuSelected = 0; this.setActiveLi(); this.tribute.menu.scrollTop = 0; } } }, delete: (e, el) => { if ( this.tribute.isActive && this.tribute.current.mentionText.length < 1 ) { this.tribute.hideMenu(); } else if (this.tribute.isActive) { this.tribute.showMenuFor(el); } } }; } setActiveLi(index) { let lis = this.tribute.menu.querySelectorAll("li"), length = lis.length >>> 0; if (index) this.tribute.menuSelected = parseInt(index); for (let i = 0; i < length; i++) { let li = lis[i]; if (i === this.tribute.menuSelected) { li.classList.add(this.tribute.current.collection.selectClass); let liClientRect = li.getBoundingClientRect(); let menuClientRect = this.tribute.menu.getBoundingClientRect(); if (liClientRect.bottom > menuClientRect.bottom) { let scrollDistance = liClientRect.bottom - menuClientRect.bottom; this.tribute.menu.scrollTop += scrollDistance; } else if (liClientRect.top < menuClientRect.top) { let scrollDistance = menuClientRect.top - liClientRect.top; this.tribute.menu.scrollTop -= scrollDistance; } } else { li.classList.remove(this.tribute.current.collection.selectClass); } } } getFullHeight(elem, includeMargin) { let height = elem.getBoundingClientRect().height; if (includeMargin) { let style = elem.currentStyle || window.getComputedStyle(elem); return ( height + parseFloat(style.marginTop) + parseFloat(style.marginBottom) ); } return height; } } export default TributeEvents; ```
/content/code_sandbox/src/TributeEvents.js
javascript
2016-01-19T00:54:39
2024-08-14T11:30:58
tribute
zurb/tribute
2,017
2,125
```javascript !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 function(e){if(Array.isArray(e))return e}(e)||function(e,t){if("undefined"==typeof Symbol||!(Symbol.iterator in Object(e)))return;var n=[],i=!0,r=!1,o=void 0;try{for(var u,a=e[Symbol.iterator]();!(i=(u=a.next()).done)&&(n.push(u.value),!t||n.length!==t);i=!0);}catch(e){r=!0,o=e}finally{try{i||null==a.return||a.return()}finally{if(r)throw o}}return n}(e,t)||function(e,t){if(!e)return;if("string"==typeof e)return r(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);"Object"===n&&e.constructor&&(n=e.constructor.name);if("Map"===n||"Set"===n)return Array.from(n);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return r(e,t)}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function r(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}if(Array.prototype.find||(Array.prototype.find=function(e){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 t,n=Object(this),i=n.length>>>0,r=arguments[1],o=0;o<i;o++)if(t=n[o],e.call(r,t,o,n))return t}),window&&"function"!=typeof window.CustomEvent){var o=function(e,t){t=t||{bubbles:!1,cancelable:!1,detail:void 0};var n=document.createEvent("CustomEvent");return n.initCustomEvent(e,t.bubbles,t.cancelable,t.detail),n};void 0!==window.Event&&(o.prototype=window.Event.prototype),window.CustomEvent=o}var u=function(){function t(n){e(this,t),this.tribute=n,this.tribute.events=this}return n(t,[{key:"bind",value:function(e){e.boundKeydown=this.keydown.bind(e,this),e.boundKeyup=this.keyup.bind(e,this),e.boundInput=this.input.bind(e,this),e.addEventListener("keydown",e.boundKeydown,!1),e.addEventListener("keyup",e.boundKeyup,!1),e.addEventListener("input",e.boundInput,!1)}},{key:"unbind",value:function(e){e.removeEventListener("keydown",e.boundKeydown,!1),e.removeEventListener("keyup",e.boundKeyup,!1),e.removeEventListener("input",e.boundInput,!1),delete e.boundKeydown,delete e.boundKeyup,delete e.boundInput}},{key:"keydown",value:function(e,n){e.shouldDeactivate(n)&&(e.tribute.isActive=!1,e.tribute.hideMenu());var i=this;e.commandEvent=!1,t.keys().forEach((function(t){t.key===n.keyCode&&(e.commandEvent=!0,e.callbacks()[t.value.toLowerCase()](n,i))}))}},{key:"input",value:function(e,t){e.inputEvent=!0,e.keyup.call(this,e,t)}},{key:"click",value:function(e,t){var n=e.tribute;if(n.menu&&n.menu.contains(t.target)){var i=t.target;for(t.preventDefault(),t.stopPropagation();"li"!==i.nodeName.toLowerCase();)if(!(i=i.parentNode)||i===n.menu)throw new Error("cannot find the <li> container for the click");n.selectItemAtIndex(i.getAttribute("data-index"),t),n.hideMenu()}else n.current.element&&!n.current.externalTrigger&&(n.current.externalTrigger=!1,setTimeout((function(){return n.hideMenu()})))}},{key:"keyup",value:function(e,t){if(e.inputEvent&&(e.inputEvent=!1),e.updateSelection(this),27!==t.keyCode){if(!e.tribute.allowSpaces&&e.tribute.hasTrailingSpace)return e.tribute.hasTrailingSpace=!1,e.commandEvent=!0,void e.callbacks().space(t,this);if(!e.tribute.isActive)if(e.tribute.autocompleteMode)e.callbacks().triggerChar(t,this,"");else{var n=e.getKeyCode(e,this,t);if(isNaN(n)||!n)return;var i=e.tribute.triggers().find((function(e){return e.charCodeAt(0)===n}));void 0!==i&&e.callbacks().triggerChar(t,this,i)}e.tribute.current.mentionText.length<e.tribute.current.collection.menuShowMinLength||((e.tribute.current.trigger||e.tribute.autocompleteMode)&&!1===e.commandEvent||e.tribute.isActive&&8===t.keyCode)&&e.tribute.showMenuFor(this,!0)}}},{key:"shouldDeactivate",value:function(e){if(!this.tribute.isActive)return!1;if(0===this.tribute.current.mentionText.length){var n=!1;return t.keys().forEach((function(t){e.keyCode===t.key&&(n=!0)})),!n}return!1}},{key:"getKeyCode",value:function(e,t,n){var i=e.tribute,r=i.range.getTriggerInfo(!1,i.hasTrailingSpace,!0,i.allowSpaces,i.autocompleteMode);return!!r&&r.mentionTriggerChar.charCodeAt(0)}},{key:"updateSelection",value:function(e){this.tribute.current.element=e;var t=this.tribute.range.getTriggerInfo(!1,this.tribute.hasTrailingSpace,!0,this.tribute.allowSpaces,this.tribute.autocompleteMode);t&&(this.tribute.current.selectedPath=t.mentionSelectedPath,this.tribute.current.mentionText=t.mentionText,this.tribute.current.selectedOffset=t.mentionSelectedOffset)}},{key:"callbacks",value:function(){var e=this;return{triggerChar:function(t,n,i){var r=e.tribute;r.current.trigger=i;var o=r.collection.find((function(e){return e.trigger===i}));r.current.collection=o,r.current.mentionText.length>=r.current.collection.menuShowMinLength&&r.inputEvent&&r.showMenuFor(n,!0)},enter:function(t,n){e.tribute.isActive&&e.tribute.current.filteredItems&&(t.preventDefault(),t.stopPropagation(),setTimeout((function(){e.tribute.selectItemAtIndex(e.tribute.menuSelected,t),e.tribute.hideMenu()}),0))},escape:function(t,n){e.tribute.isActive&&(t.preventDefault(),t.stopPropagation(),e.tribute.isActive=!1,e.tribute.hideMenu())},tab:function(t,n){e.callbacks().enter(t,n)},space:function(t,n){e.tribute.isActive&&(e.tribute.spaceSelectsMatch?e.callbacks().enter(t,n):e.tribute.allowSpaces||(t.stopPropagation(),setTimeout((function(){e.tribute.hideMenu(),e.tribute.isActive=!1}),0)))},up:function(t,n){if(e.tribute.isActive&&e.tribute.current.filteredItems){t.preventDefault(),t.stopPropagation();var i=e.tribute.current.filteredItems.length,r=e.tribute.menuSelected;i>r&&r>0?(e.tribute.menuSelected--,e.setActiveLi()):0===r&&(e.tribute.menuSelected=i-1,e.setActiveLi(),e.tribute.menu.scrollTop=e.tribute.menu.scrollHeight)}},down:function(t,n){if(e.tribute.isActive&&e.tribute.current.filteredItems){t.preventDefault(),t.stopPropagation();var i=e.tribute.current.filteredItems.length-1,r=e.tribute.menuSelected;i>r?(e.tribute.menuSelected++,e.setActiveLi()):i===r&&(e.tribute.menuSelected=0,e.setActiveLi(),e.tribute.menu.scrollTop=0)}},delete:function(t,n){e.tribute.isActive&&e.tribute.current.mentionText.length<1?e.tribute.hideMenu():e.tribute.isActive&&e.tribute.showMenuFor(n)}}}},{key:"setActiveLi",value:function(e){var t=this.tribute.menu.querySelectorAll("li"),n=t.length>>>0;e&&(this.tribute.menuSelected=parseInt(e));for(var i=0;i<n;i++){var r=t[i];if(i===this.tribute.menuSelected){r.classList.add(this.tribute.current.collection.selectClass);var o=r.getBoundingClientRect(),u=this.tribute.menu.getBoundingClientRect();if(o.bottom>u.bottom){var a=o.bottom-u.bottom;this.tribute.menu.scrollTop+=a}else if(o.top<u.top){var l=u.top-o.top;this.tribute.menu.scrollTop-=l}}else r.classList.remove(this.tribute.current.collection.selectClass)}}},{key:"getFullHeight",value:function(e,t){var n=e.getBoundingClientRect().height;if(t){var i=e.currentStyle||window.getComputedStyle(e);return n+parseFloat(i.marginTop)+parseFloat(i.marginBottom)}return n}}],[{key:"keys",value:function(){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}(),a=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){var t=this;this.menuClickEvent=this.tribute.events.click.bind(null,this),this.menuContainerScrollEvent=this.debounce((function(){t.tribute.isActive&&t.tribute.hideMenu()}),10,!1),this.windowResizeEvent=this.debounce((function(){t.tribute.isActive&&t.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){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){var i,r=arguments,o=this;return function(){var u=o,a=r,l=n&&!i;clearTimeout(i),i=setTimeout((function(){i=null,n||e.apply(u,a)}),t),l&&e.apply(u,a)}}}]),t}(),l=function(){function t(n){e(this,t),this.tribute=n,this.tribute.range=this}return n(t,[{key:"getDocument",value:function(){var e;return this.tribute.current.collection&&(e=this.tribute.current.collection.iframe),e?e.contentWindow.document:document}},{key:"positionMenuAtCaret",value:function(e){var t,n=this.tribute.current,i=this.getTriggerInfo(!1,this.tribute.hasTrailingSpace,!0,this.tribute.allowSpaces,this.tribute.autocompleteMode);if(void 0!==i){if(!this.tribute.positionMenu)return void(this.tribute.menu.style.cssText="display: block;");t=this.isContentEditable(n.element)?this.getContentEditableCaretPosition(i.mentionPosition):this.getTextAreaOrInputUnderlinePosition(this.tribute.current.element,i.mentionPosition),this.tribute.menu.style.cssText="top: ".concat(t.top,"px;\n left: ").concat(t.left,"px;\n right: ").concat(t.right,"px;\n bottom: ").concat(t.bottom,"px;\n max-height: ").concat(t.maxHeight||500,"px;\n max-width: ").concat(t.maxWidth||300,"px;\n position: ").concat(t.position||"absolute",";\n display: block;"),"auto"===t.left&&(this.tribute.menu.style.left="auto"),"auto"===t.top&&(this.tribute.menu.style.top="auto"),e&&this.scrollIntoView()}else this.tribute.menu.style.cssText="display: none"}},{key:"selectElement",value:function(e,t,n){var i,r=e;if(t)for(var o=0;o<t.length;o++){if(void 0===(r=r.childNodes[t[o]]))return;for(;r.length<n;)n-=r.length,r=r.nextSibling;0!==r.childNodes.length||r.length||(r=r.previousSibling)}var u=this.getWindowSelection();(i=this.getDocument().createRange()).setStart(r,n),i.setEnd(r,n),i.collapse(!0);try{u.removeAllRanges()}catch(e){}u.addRange(i),e.focus()}},{key:"replaceTriggerText",value:function(e,t,n,i,r){var o=this.getTriggerInfo(!0,n,t,this.tribute.allowSpaces,this.tribute.autocompleteMode);if(void 0!==o){var u=this.tribute.current,a=new CustomEvent("tribute-replaced",{detail:{item:r,instance:u,context:o,event:i}});if(this.isContentEditable(u.element)){e+="string"==typeof this.tribute.replaceTextSuffix?this.tribute.replaceTextSuffix:"";var l=o.mentionPosition+o.mentionText.length;this.tribute.autocompleteMode||(l+=o.mentionTriggerChar.length),this.pasteHtml(e,o.mentionPosition,l)}else{var s=this.tribute.current.element,c="string"==typeof this.tribute.replaceTextSuffix?this.tribute.replaceTextSuffix:" ";e+=c;var h=o.mentionPosition,d=o.mentionPosition+o.mentionText.length+c.length;this.tribute.autocompleteMode||(d+=o.mentionTriggerChar.length-1),s.value=s.value.substring(0,h)+e+s.value.substring(d,s.value.length),s.selectionStart=h+e.length,s.selectionEnd=h+e.length}u.element.dispatchEvent(new CustomEvent("input",{bubbles:!0})),u.element.dispatchEvent(a)}}},{key:"pasteHtml",value:function(e,t,n){var i,r;r=this.getWindowSelection(),(i=this.getDocument().createRange()).setStart(r.anchorNode,t),i.setEnd(r.anchorNode,n),i.deleteContents();var o=this.getDocument().createElement("div");o.innerHTML=e;for(var u,a,l=this.getDocument().createDocumentFragment();u=o.firstChild;)a=l.appendChild(u);i.insertNode(l),a&&((i=i.cloneRange()).setStartAfter(a),i.collapse(!0),r.removeAllRanges(),r.addRange(i))}},{key:"getWindowSelection",value:function(){return this.tribute.collection.iframe?this.tribute.collection.iframe.contentWindow.getSelection():window.getSelection()}},{key:"getNodePositionInParent",value:function(e){if(null===e.parentNode)return 0;for(var t=0;t<e.parentNode.childNodes.length;t++){if(e.parentNode.childNodes[t]===e)return t}}},{key:"getContentEditableSelectedPath",value:function(e){var t=this.getWindowSelection(),n=t.anchorNode,i=[];if(null!=n){for(var r,o=n.contentEditable;null!==n&&"true"!==o;)r=this.getNodePositionInParent(n),i.push(r),null!==(n=n.parentNode)&&(o=n.contentEditable);return i.reverse(),{selected:n,path:i,offset:t.getRangeAt(0).startOffset}}}},{key:"getTextPrecedingCurrentSelection",value:function(){var e=this.tribute.current,t="";if(this.isContentEditable(e.element)){var n=this.getWindowSelection().anchorNode;if(null!=n){var i=n.textContent,r=this.getWindowSelection().getRangeAt(0).startOffset;i&&r>=0&&(t=i.substring(0,r))}}else{var o=this.tribute.current.element;if(o){var u=o.selectionStart;o.value&&u>=0&&(t=o.value.substring(0,u))}}return t}},{key:"getLastWordInText",value:function(e){var t;return e=e.replace(/\u00A0/g," "),(t=this.tribute.autocompleteSeparator?e.split(this.tribute.autocompleteSeparator):e.split(/\s+/))[t.length-1].trim()}},{key:"getTriggerInfo",value:function(e,t,n,i,r){var o,u,a,l=this,s=this.tribute.current;if(this.isContentEditable(s.element)){var c=this.getContentEditableSelectedPath(s);c&&(o=c.selected,u=c.path,a=c.offset)}else o=this.tribute.current.element;var h=this.getTextPrecedingCurrentSelection(),d=this.getLastWordInText(h);if(r)return{mentionPosition:h.length-d.length,mentionText:d,mentionSelectedElement:o,mentionSelectedPath:u,mentionSelectedOffset:a};if(null!=h){var f,m=-1;if(this.tribute.collection.forEach((function(e){var t=e.trigger,i=e.requireLeadingSpace?l.lastIndexWithLeadingSpace(h,t):h.lastIndexOf(t);i>m&&(m=i,f=t,n=e.requireLeadingSpace)})),m>=0&&(0===m||!n||/[\xA0\s]/g.test(h.substring(m-1,m)))){var p=h.substring(m+f.length,h.length);f=h.substring(m,m+f.length);var v=p.substring(0,1),g=p.length>0&&(" "===v||""===v);t&&(p=p.trim());var b=i?/[^\S ]/g:/[\xA0\s]/g;if(this.tribute.hasTrailingSpace=b.test(p),!g&&(e||!b.test(p)))return{mentionPosition:m,mentionText:p,mentionSelectedElement:o,mentionSelectedPath:u,mentionSelectedOffset:a,mentionTriggerChar:f}}}}},{key:"lastIndexWithLeadingSpace",value:function(e,t){for(var n=e.split("").reverse().join(""),i=-1,r=0,o=e.length;r<o;r++){for(var u=r===e.length-1,a=/\s/.test(n[r+1]),l=!0,s=t.length-1;s>=0;s--)if(t[s]!==n[r-s]){l=!1;break}if(l&&(u||a)){i=e.length-1-r;break}}return i}},{key:"isContentEditable",value:function(e){return"INPUT"!==e.nodeName&&"TEXTAREA"!==e.nodeName}},{key:"isMenuOffScreen",value:function(e,t){var n=window.innerWidth,i=window.innerHeight,r=document.documentElement,o=(window.pageXOffset||r.scrollLeft)-(r.clientLeft||0),u=(window.pageYOffset||r.scrollTop)-(r.clientTop||0),a="number"==typeof e.top?e.top:u+i-e.bottom-t.height,l="number"==typeof e.right?e.right:e.left+t.width,s="number"==typeof e.bottom?e.bottom:e.top+t.height,c="number"==typeof e.left?e.left:o+n-e.right-t.width;return{top:a<Math.floor(u),right:l>Math.ceil(o+n),bottom:s>Math.ceil(u+i),left:c<Math.floor(o)}}},{key:"getMenuDimensions",value:function(){var e={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;",e.width=this.tribute.menu.offsetWidth,e.height=this.tribute.menu.offsetHeight,this.tribute.menu.style.cssText="display: none;",e}},{key:"getTextAreaOrInputUnderlinePosition",value:function(e,t,n){var i=this.getDocument().createElement("div");i.id="input-textarea-caret-position-mirror-div",this.getDocument().body.appendChild(i);var r=i.style,o=window.getComputedStyle?getComputedStyle(e):e.currentStyle;r.whiteSpace="pre-wrap","INPUT"!==e.nodeName&&(r.wordWrap="break-word"),r.position="absolute",r.visibility="hidden",["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"].forEach((function(e){r[e]=o[e]}));var u=document.createElement("span");u.textContent=e.value.substring(0,t),i.appendChild(u),"INPUT"===e.nodeName&&(i.textContent=i.textContent.replace(/\s/g,""));var a=this.getDocument().createElement("span");a.textContent="&#x200B;",i.appendChild(a);var l=this.getDocument().createElement("span");l.textContent=e.value.substring(t),i.appendChild(l);var s=e.getBoundingClientRect();i.style.position="fixed",i.style.left=s.left+"px",i.style.top=s.top+"px",i.style.width=s.width+"px",i.style.height=s.height+"px",i.scrollTop=e.scrollTop;var c=a.getBoundingClientRect();return this.getDocument().body.removeChild(i),this.getFixedCoordinatesRelativeToRect(c)}},{key:"getContentEditableCaretPosition",value:function(e){var t,n=this.getWindowSelection();(t=this.getDocument().createRange()).setStart(n.anchorNode,e),t.setEnd(n.anchorNode,e),t.collapse(!1);var i=t.getBoundingClientRect();return this.getFixedCoordinatesRelativeToRect(i)}},{key:"getFixedCoordinatesRelativeToRect",value:function(e){var t={position:"fixed",left:e.left,top:e.top+e.height},n=this.getMenuDimensions(),i=e.top,r=window.innerHeight-(e.top+e.height);r<n.height&&(i>=n.height||i>r?(t.top="auto",t.bottom=window.innerHeight-e.top,r<n.height&&(t.maxHeight=i)):i<n.height&&(t.maxHeight=r));var o=e.left,u=window.innerWidth-e.left;return u<n.width&&(o>=n.width||o>u?(t.left="auto",t.right=window.innerWidth-e.left,u<n.width&&(t.maxWidth=o)):o<n.width&&(t.maxWidth=u)),t}},{key:"scrollIntoView",value:function(e){var t,n=this.menu;if(void 0!==n){for(;void 0===t||0===t.height;)if(0===(t=n.getBoundingClientRect()).height&&(void 0===(n=n.childNodes[0])||!n.getBoundingClientRect))return;var i=t.top,r=i+t.height;if(i<0)window.scrollTo(0,window.pageYOffset+t.top-20);else if(r>window.innerHeight){var o=window.pageYOffset+t.top-20;o-window.pageYOffset>100&&(o=window.pageYOffset+100);var u=window.pageYOffset-(window.innerHeight-r);u>o&&(u=o),window.scrollTo(0,u)}}}},{key:"menuContainerIsBody",get:function(){return this.tribute.menuContainer===document.body||!this.tribute.menuContainer}}]),t}(),s=function(){function t(n){e(this,t),this.tribute=n,this.tribute.search=this}return n(t,[{key:"simpleFilter",value:function(e,t){var n=this;return t.filter((function(t){return n.test(e,t)}))}},{key:"test",value:function(e,t){return null!==this.match(e,t)}},{key:"match",value:function(e,t,n){n=n||{};t.length;var i=n.pre||"",r=n.post||"",o=n.caseSensitive&&t||t.toLowerCase();if(n.skip)return{rendered:t,score:0};e=n.caseSensitive&&e||e.toLowerCase();var u=this.traverse(o,e,0,0,[]);return u?{rendered:this.render(t,u.cache,i,r),score:u.score}:null}},{key:"traverse",value:function(e,t,n,i,r){if(this.tribute.autocompleteSeparator&&(t=t.split(this.tribute.autocompleteSeparator).splice(-1)[0]),t.length===i)return{score:this.calculateScore(r),cache:r.slice()};if(!(e.length===n||t.length-i>e.length-n)){for(var o,u,a=t[i],l=e.indexOf(a,n);l>-1;){if(r.push(l),u=this.traverse(e,t,l+1,i+1,r),r.pop(),!u)return o;(!o||o.score<u.score)&&(o=u),l=e.indexOf(a,l+1)}return o}}},{key:"calculateScore",value:function(e){var t=0,n=1;return e.forEach((function(i,r){r>0&&(e[r-1]+1===i?n+=n+1:n=1),t+=n})),t}},{key:"render",value:function(e,t,n,i){var r=e.substring(0,t[0]);return t.forEach((function(o,u){r+=n+e[o]+i+e.substring(o+1,t[u+1]?t[u+1]:e.length)})),r}},{key:"filter",value:function(e,t,n){var i=this;return n=n||{},t.reduce((function(t,r,o,u){var a=r;n.extract&&((a=n.extract(r))||(a=""));var l=i.match(e,a,n);return null!=l&&(t[t.length]={string:l.rendered,score:l.score,index:o,original:r}),t}),[]).sort((function(e,t){var n=t.score-e.score;return n||e.index-t.index}))}}]),t}();return function(){function t(n){var i,r=this,o=n.values,c=void 0===o?null:o,h=n.loadingItemTemplate,d=void 0===h?null:h,f=n.iframe,m=void 0===f?null:f,p=n.selectClass,v=void 0===p?"highlight":p,g=n.containerClass,b=void 0===g?"tribute-container":g,y=n.itemClass,w=void 0===y?"":y,T=n.trigger,S=void 0===T?"@":T,C=n.autocompleteMode,k=void 0!==C&&C,E=n.autocompleteSeparator,x=void 0===E?null:E,A=n.selectTemplate,M=void 0===A?null:A,L=n.menuItemTemplate,I=void 0===L?null:L,N=n.lookup,P=void 0===N?"key":N,R=n.fillAttr,D=void 0===R?"value":R,O=n.collection,W=void 0===O?null:O,H=n.menuContainer,F=void 0===H?null:H,_=n.noMatchTemplate,B=void 0===_?null:_,j=n.requireLeadingSpace,K=void 0===j||j,q=n.allowSpaces,U=void 0!==q&&q,z=n.replaceTextSuffix,Y=void 0===z?null:z,Q=n.positionMenu,X=void 0===Q||Q,V=n.spaceSelectsMatch,$=void 0!==V&&V,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;if(e(this,t),this.autocompleteMode=k,this.autocompleteSeparator=x,this.menuSelected=0,this.current={},this.inputEvent=!1,this.isActive=!1,this.menuContainer=F,this.allowSpaces=U,this.replaceTextSuffix=Y,this.positionMenu=X,this.hasTrailingSpace=!1,this.spaceSelectsMatch=$,this.autocompleteMode&&(S="",U=!1),c)this.collection=[{trigger:S,iframe:m,selectClass:v,containerClass:b,itemClass:w,selectTemplate:(M||t.defaultSelectTemplate).bind(this),menuItemTemplate:(I||t.defaultMenuItemTemplate).bind(this),noMatchTemplate:(i=B,"string"==typeof i?""===i.trim()?null:i:"function"==typeof i?i.bind(r):B||function(){return"<li>No Match Found!</li>"}.bind(r)),lookup:P,fillAttr:D,values:c,loadingItemTemplate:d,requireLeadingSpace:K,searchOpts:J,menuItemLimit:ee,menuShowMinLength:ne}];else{if(!W)throw new Error("[Tribute] No collection specified.");this.autocompleteMode&&console.warn("Tribute in autocomplete mode does not work for collections"),this.collection=W.map((function(e){return{trigger:e.trigger||S,iframe:e.iframe||m,selectClass:e.selectClass||v,containerClass:e.containerClass||b,itemClass:e.itemClass||w,selectTemplate:(e.selectTemplate||t.defaultSelectTemplate).bind(r),menuItemTemplate:(e.menuItemTemplate||t.defaultMenuItemTemplate).bind(r),noMatchTemplate:function(e){return"string"==typeof e?""===e.trim()?null:e:"function"==typeof e?e.bind(r):B||function(){return"<li>No Match Found!</li>"}.bind(r)}(B),lookup:e.lookup||P,fillAttr:e.fillAttr||D,values:e.values,loadingItemTemplate:e.loadingItemTemplate,requireLeadingSpace:e.requireLeadingSpace,searchOpts:e.searchOpts||J,menuItemLimit:e.menuItemLimit||ee,menuShowMinLength:e.menuShowMinLength||ne}}))}new l(this),new u(this),new a(this),new s(this)}return n(t,[{key:"triggers",value:function(){return this.collection.map((function(e){return e.trigger}))}},{key:"attach",value:function(e){if(!e)throw new Error("[Tribute] Must pass in a DOM node or NodeList.");if("undefined"!=typeof jQuery&&e instanceof jQuery&&(e=e.get()),e.constructor===NodeList||e.constructor===HTMLCollection||e.constructor===Array)for(var t=e.length,n=0;n<t;++n)this._attach(e[n]);else this._attach(e)}},{key:"_attach",value:function(e){e.hasAttribute("data-tribute")&&console.warn("Tribute was already bound to "+e.nodeName),this.ensureEditable(e),this.events.bind(e),e.setAttribute("data-tribute",!0)}},{key:"ensureEditable",value:function(e){if(-1===t.inputTypes().indexOf(e.nodeName)){if(!e.contentEditable)throw new Error("[Tribute] Cannot bind to "+e.nodeName);e.contentEditable=!0}}},{key:"createMenu",value:function(e){var t=this.range.getDocument().createElement("div"),n=this.range.getDocument().createElement("ul");return t.className=e,t.appendChild(n),this.menuContainer?this.menuContainer.appendChild(t):this.range.getDocument().body.appendChild(t)}},{key:"showMenuFor",value:function(e,t){var n=this;if(!this.isActive||this.current.element!==e||this.current.mentionText!==this.currentMentionTextSnapshot){this.currentMentionTextSnapshot=this.current.mentionText,this.menu||(this.menu=this.createMenu(this.current.collection.containerClass),e.tributeMenu=this.menu,this.menuEvents.bind(this.menu)),this.isActive=!0,this.menuSelected=0,this.current.mentionText||(this.current.mentionText="");var r=function(e){if(n.isActive){var r=n.search.filter(n.current.mentionText,e,{pre:n.current.collection.searchOpts.pre||"<span>",post:n.current.collection.searchOpts.post||"</span>",skip:n.current.collection.searchOpts.skip,extract:function(e){if("string"==typeof n.current.collection.lookup)return e[n.current.collection.lookup];if("function"==typeof n.current.collection.lookup)return n.current.collection.lookup(e,n.current.mentionText);throw new Error("Invalid lookup attribute, lookup must be string or function.")}});n.current.collection.menuItemLimit&&(r=r.slice(0,n.current.collection.menuItemLimit)),n.current.filteredItems=r;var o=n.menu.querySelector("ul");if(!r.length){var u=new CustomEvent("tribute-no-match",{detail:n.menu});return n.current.element.dispatchEvent(u),void("function"==typeof n.current.collection.noMatchTemplate&&!n.current.collection.noMatchTemplate()||!n.current.collection.noMatchTemplate?n.hideMenu():("function"==typeof n.current.collection.noMatchTemplate?o.innerHTML=n.current.collection.noMatchTemplate():o.innerHTML=n.current.collection.noMatchTemplate,n.range.positionMenuAtCaret(t)))}o.innerHTML="";var a=n.range.getDocument().createDocumentFragment();r.forEach((function(e,t){var r=n.range.getDocument().createElement("li");r.setAttribute("data-index",t),r.className=n.current.collection.itemClass,r.addEventListener("mousemove",(function(e){var t=i(n._findLiTarget(e.target),2),r=(t[0],t[1]);0!==e.movementY&&n.events.setActiveLi(r)})),n.menuSelected===t&&r.classList.add(n.current.collection.selectClass),r.innerHTML=n.current.collection.menuItemTemplate(e),a.appendChild(r)})),o.appendChild(a),n.range.positionMenuAtCaret(t)}};"function"==typeof this.current.collection.values?(this.current.collection.loadingItemTemplate&&(this.menu.querySelector("ul").innerHTML=this.current.collection.loadingItemTemplate,this.range.positionMenuAtCaret(t)),this.current.collection.values(this.current.mentionText,r)):r(this.current.collection.values)}}},{key:"_findLiTarget",value:function(e){if(!e)return[];var t=e.getAttribute("data-index");return t?[e,t]:this._findLiTarget(e.parentNode)}},{key:"showMenuForCollection",value:function(e,t){e!==document.activeElement&&this.placeCaretAtEnd(e),this.current.collection=this.collection[t||0],this.current.externalTrigger=!0,this.current.element=e,e.isContentEditable?this.insertTextAtCursor(this.current.collection.trigger):this.insertAtCaret(e,this.current.collection.trigger),this.showMenuFor(e)}},{key:"placeCaretAtEnd",value:function(e){if(e.focus(),void 0!==window.getSelection&&void 0!==document.createRange){var t=document.createRange();t.selectNodeContents(e),t.collapse(!1);var n=window.getSelection();n.removeAllRanges(),n.addRange(t)}else if(void 0!==document.body.createTextRange){var i=document.body.createTextRange();i.moveToElementText(e),i.collapse(!1),i.select()}}},{key:"insertTextAtCursor",value:function(e){var t,n;(n=(t=window.getSelection()).getRangeAt(0)).deleteContents();var i=document.createTextNode(e);n.insertNode(i),n.selectNodeContents(i),n.collapse(!1),t.removeAllRanges(),t.addRange(n)}},{key:"insertAtCaret",value:function(e,t){var n=e.scrollTop,i=e.selectionStart,r=e.value.substring(0,i),o=e.value.substring(e.selectionEnd,e.value.length);e.value=r+t+o,i+=t.length,e.selectionStart=i,e.selectionEnd=i,e.focus(),e.scrollTop=n}},{key:"hideMenu",value:function(){this.menu&&(this.menu.style.cssText="display: none;",this.isActive=!1,this.menuSelected=0,this.current={})}},{key:"selectItemAtIndex",value:function(e,t){if("number"==typeof(e=parseInt(e))&&!isNaN(e)){var n=this.current.filteredItems[e],i=this.current.collection.selectTemplate(n);null!==i&&this.replaceText(i,t,n)}}},{key:"replaceText",value:function(e,t,n){this.range.replaceTriggerText(e,!0,!0,t,n)}},{key:"_append",value:function(e,t,n){if("function"==typeof e.values)throw new Error("Unable to append to values, as it is a function.");e.values=n?t:e.values.concat(t)}},{key:"append",value:function(e,t,n){var i=parseInt(e);if("number"!=typeof i)throw new Error("please provide an index for the collection to update.");var r=this.collection[i];this._append(r,t,n)}},{key:"appendCurrent",value:function(e,t){if(!this.isActive)throw new Error("No active state. Please use append instead and pass an index.");this._append(this.current.collection,e,t)}},{key:"detach",value:function(e){if(!e)throw new Error("[Tribute] Must pass in a DOM node or NodeList.");if("undefined"!=typeof jQuery&&e instanceof jQuery&&(e=e.get()),e.constructor===NodeList||e.constructor===HTMLCollection||e.constructor===Array)for(var t=e.length,n=0;n<t;++n)this._detach(e[n]);else this._detach(e)}},{key:"_detach",value:function(e){var t=this;this.events.unbind(e),e.tributeMenu&&this.menuEvents.unbind(e.tributeMenu),setTimeout((function(){e.removeAttribute("data-tribute"),t.isActive=!1,e.tributeMenu&&e.tributeMenu.remove()}))}},{key:"isActive",get:function(){return this._isActive},set:function(e){if(this._isActive!=e&&(this._isActive=e,this.current.element)){var t=new CustomEvent("tribute-active-".concat(e));this.current.element.dispatchEvent(t)}}}],[{key:"defaultSelectTemplate",value:function(e){return void 0===e?"".concat(this.current.collection.trigger).concat(this.current.mentionText):this.range.isContentEditable(this.current.element)?'<span class="tribute-mention">'+(this.current.collection.trigger+e.original[this.current.collection.fillAttr])+"</span>":this.current.collection.trigger+e.original[this.current.collection.fillAttr]}},{key:"defaultMenuItemTemplate",value:function(e){return e.string}},{key:"inputTypes",value:function(){return["TEXTAREA","INPUT"]}}]),t}()})); //# sourceMappingURL=tribute.min.js.map ```
/content/code_sandbox/dist/tribute.min.js
javascript
2016-01-19T00:54:39
2024-08-14T11:30:58
tribute
zurb/tribute
2,017
8,133
```css .tribute-container { position: absolute; top: 0; left: 0; height: auto; overflow: auto; display: block; z-index: 999999; } .tribute-container ul { margin: 0; margin-top: 2px; padding: 0; list-style: none; background: #efefef; } .tribute-container li { padding: 5px 5px; cursor: pointer; } .tribute-container li.highlight { background: #ddd; } .tribute-container li span { font-weight: bold; } .tribute-container li.no-match { cursor: default; } .tribute-container .menu-highlighted { font-weight: bold; } ```
/content/code_sandbox/dist/tribute.css
css
2016-01-19T00:54:39
2024-08-14T11:30:58
tribute
zurb/tribute
2,017
161
```javascript if (!Array.prototype.find) { Array.prototype.find = function(predicate) { if (this === null) { throw new TypeError('Array.prototype.find called on null or undefined') } if (typeof predicate !== 'function') { throw new TypeError('predicate must be a function') } var list = Object(this); var length = list.length >>> 0; var thisArg = arguments[1]; var value; for (var i = 0; i < length; i++) { value = list[i]; if (predicate.call(thisArg, value, i, list)) { return value } } return undefined }; } if (window && typeof window.CustomEvent !== "function") { function CustomEvent$1(event, params) { params = params || { bubbles: false, cancelable: false, detail: undefined }; var evt = document.createEvent('CustomEvent'); evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail); return evt } if (typeof window.Event !== 'undefined') { CustomEvent$1.prototype = window.Event.prototype; } window.CustomEvent = CustomEvent$1; } class TributeEvents { constructor(tribute) { this.tribute = tribute; this.tribute.events = this; } static keys() { 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" } ]; } bind(element) { element.boundKeydown = this.keydown.bind(element, this); element.boundKeyup = this.keyup.bind(element, this); element.boundInput = this.input.bind(element, this); element.addEventListener("keydown", element.boundKeydown, false); element.addEventListener("keyup", element.boundKeyup, false); element.addEventListener("input", element.boundInput, false); } unbind(element) { element.removeEventListener("keydown", element.boundKeydown, false); element.removeEventListener("keyup", element.boundKeyup, false); element.removeEventListener("input", element.boundInput, false); delete element.boundKeydown; delete element.boundKeyup; delete element.boundInput; } keydown(instance, event) { if (instance.shouldDeactivate(event)) { instance.tribute.isActive = false; instance.tribute.hideMenu(); } let element = this; instance.commandEvent = false; TributeEvents.keys().forEach(o => { if (o.key === event.keyCode) { instance.commandEvent = true; instance.callbacks()[o.value.toLowerCase()](event, element); } }); } input(instance, event) { instance.inputEvent = true; instance.keyup.call(this, instance, event); } click(instance, event) { let tribute = instance.tribute; if (tribute.menu && tribute.menu.contains(event.target)) { let li = event.target; event.preventDefault(); event.stopPropagation(); while (li.nodeName.toLowerCase() !== "li") { li = li.parentNode; if (!li || li === tribute.menu) { throw new Error("cannot find the <li> container for the click"); } } tribute.selectItemAtIndex(li.getAttribute("data-index"), event); tribute.hideMenu(); // TODO: should fire with externalTrigger and target is outside of menu } else if (tribute.current.element && !tribute.current.externalTrigger) { tribute.current.externalTrigger = false; setTimeout(() => tribute.hideMenu()); } } keyup(instance, event) { if (instance.inputEvent) { instance.inputEvent = false; } instance.updateSelection(this); if (event.keyCode === 27) return; if (!instance.tribute.allowSpaces && instance.tribute.hasTrailingSpace) { instance.tribute.hasTrailingSpace = false; instance.commandEvent = true; instance.callbacks()["space"](event, this); return; } if (!instance.tribute.isActive) { if (instance.tribute.autocompleteMode) { instance.callbacks().triggerChar(event, this, ""); } else { let keyCode = instance.getKeyCode(instance, this, event); if (isNaN(keyCode) || !keyCode) return; let trigger = instance.tribute.triggers().find(trigger => { return trigger.charCodeAt(0) === keyCode; }); if (typeof trigger !== "undefined") { instance.callbacks().triggerChar(event, this, trigger); } } } if ( instance.tribute.current.mentionText.length < instance.tribute.current.collection.menuShowMinLength ) { return; } if ( ((instance.tribute.current.trigger || instance.tribute.autocompleteMode) && instance.commandEvent === false) || (instance.tribute.isActive && event.keyCode === 8) ) { instance.tribute.showMenuFor(this, true); } } shouldDeactivate(event) { if (!this.tribute.isActive) return false; if (this.tribute.current.mentionText.length === 0) { let eventKeyPressed = false; TributeEvents.keys().forEach(o => { if (event.keyCode === o.key) eventKeyPressed = true; }); return !eventKeyPressed; } return false; } getKeyCode(instance, el, event) { let tribute = instance.tribute; let info = tribute.range.getTriggerInfo( false, tribute.hasTrailingSpace, true, tribute.allowSpaces, tribute.autocompleteMode ); if (info) { return info.mentionTriggerChar.charCodeAt(0); } else { return false; } } updateSelection(el) { this.tribute.current.element = el; let info = this.tribute.range.getTriggerInfo( false, this.tribute.hasTrailingSpace, true, this.tribute.allowSpaces, this.tribute.autocompleteMode ); if (info) { this.tribute.current.selectedPath = info.mentionSelectedPath; this.tribute.current.mentionText = info.mentionText; this.tribute.current.selectedOffset = info.mentionSelectedOffset; } } callbacks() { return { triggerChar: (e, el, trigger) => { let tribute = this.tribute; tribute.current.trigger = trigger; let collectionItem = tribute.collection.find(item => { return item.trigger === trigger; }); tribute.current.collection = collectionItem; if ( tribute.current.mentionText.length >= tribute.current.collection.menuShowMinLength && tribute.inputEvent ) { tribute.showMenuFor(el, true); } }, enter: (e, el) => { // choose selection if (this.tribute.isActive && this.tribute.current.filteredItems) { e.preventDefault(); e.stopPropagation(); setTimeout(() => { this.tribute.selectItemAtIndex(this.tribute.menuSelected, e); this.tribute.hideMenu(); }, 0); } }, escape: (e, el) => { if (this.tribute.isActive) { e.preventDefault(); e.stopPropagation(); this.tribute.isActive = false; this.tribute.hideMenu(); } }, tab: (e, el) => { // choose first match this.callbacks().enter(e, el); }, space: (e, el) => { if (this.tribute.isActive) { if (this.tribute.spaceSelectsMatch) { this.callbacks().enter(e, el); } else if (!this.tribute.allowSpaces) { e.stopPropagation(); setTimeout(() => { this.tribute.hideMenu(); this.tribute.isActive = false; }, 0); } } }, up: (e, el) => { // navigate up ul if (this.tribute.isActive && this.tribute.current.filteredItems) { e.preventDefault(); e.stopPropagation(); let count = this.tribute.current.filteredItems.length, selected = this.tribute.menuSelected; if (count > selected && selected > 0) { this.tribute.menuSelected--; this.setActiveLi(); } else if (selected === 0) { this.tribute.menuSelected = count - 1; this.setActiveLi(); this.tribute.menu.scrollTop = this.tribute.menu.scrollHeight; } } }, down: (e, el) => { // navigate down ul if (this.tribute.isActive && this.tribute.current.filteredItems) { e.preventDefault(); e.stopPropagation(); let count = this.tribute.current.filteredItems.length - 1, selected = this.tribute.menuSelected; if (count > selected) { this.tribute.menuSelected++; this.setActiveLi(); } else if (count === selected) { this.tribute.menuSelected = 0; this.setActiveLi(); this.tribute.menu.scrollTop = 0; } } }, delete: (e, el) => { if ( this.tribute.isActive && this.tribute.current.mentionText.length < 1 ) { this.tribute.hideMenu(); } else if (this.tribute.isActive) { this.tribute.showMenuFor(el); } } }; } setActiveLi(index) { let lis = this.tribute.menu.querySelectorAll("li"), length = lis.length >>> 0; if (index) this.tribute.menuSelected = parseInt(index); for (let i = 0; i < length; i++) { let li = lis[i]; if (i === this.tribute.menuSelected) { li.classList.add(this.tribute.current.collection.selectClass); let liClientRect = li.getBoundingClientRect(); let menuClientRect = this.tribute.menu.getBoundingClientRect(); if (liClientRect.bottom > menuClientRect.bottom) { let scrollDistance = liClientRect.bottom - menuClientRect.bottom; this.tribute.menu.scrollTop += scrollDistance; } else if (liClientRect.top < menuClientRect.top) { let scrollDistance = menuClientRect.top - liClientRect.top; this.tribute.menu.scrollTop -= scrollDistance; } } else { li.classList.remove(this.tribute.current.collection.selectClass); } } } getFullHeight(elem, includeMargin) { let height = elem.getBoundingClientRect().height; if (includeMargin) { let style = elem.currentStyle || window.getComputedStyle(elem); return ( height + parseFloat(style.marginTop) + parseFloat(style.marginBottom) ); } return height; } } class TributeMenuEvents { constructor(tribute) { this.tribute = tribute; this.tribute.menuEvents = this; this.menu = this.tribute.menu; } bind(menu) { this.menuClickEvent = this.tribute.events.click.bind(null, this); this.menuContainerScrollEvent = this.debounce( () => { if (this.tribute.isActive) { this.tribute.hideMenu(); } }, 10, false ); this.windowResizeEvent = this.debounce( () => { if (this.tribute.isActive) { this.tribute.hideMenu(); } }, 10, false ); // fixes IE11 issues with mousedown this.tribute.range .getDocument() .addEventListener("MSPointerDown", this.menuClickEvent, false); this.tribute.range .getDocument() .addEventListener("mousedown", this.menuClickEvent, false); window.addEventListener("resize", this.windowResizeEvent); if (this.menuContainer) { this.menuContainer.addEventListener( "scroll", this.menuContainerScrollEvent, false ); } else { window.addEventListener("scroll", this.menuContainerScrollEvent); } } unbind(menu) { this.tribute.range .getDocument() .removeEventListener("mousedown", this.menuClickEvent, false); this.tribute.range .getDocument() .removeEventListener("MSPointerDown", this.menuClickEvent, false); window.removeEventListener("resize", this.windowResizeEvent); if (this.menuContainer) { this.menuContainer.removeEventListener( "scroll", this.menuContainerScrollEvent, false ); } else { window.removeEventListener("scroll", this.menuContainerScrollEvent); } } debounce(func, wait, immediate) { var timeout; return () => { var context = this, args = arguments; var later = () => { timeout = null; if (!immediate) func.apply(context, args); }; var callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait); if (callNow) func.apply(context, args); }; } } // Thanks to path_to_url class TributeRange { constructor(tribute) { this.tribute = tribute; this.tribute.range = this; } getDocument() { let iframe; if (this.tribute.current.collection) { iframe = this.tribute.current.collection.iframe; } if (!iframe) { return document } return iframe.contentWindow.document } positionMenuAtCaret(scrollTo) { let context = this.tribute.current, coordinates; let info = this.getTriggerInfo(false, this.tribute.hasTrailingSpace, true, this.tribute.allowSpaces, this.tribute.autocompleteMode); if (typeof info !== 'undefined') { if(!this.tribute.positionMenu){ this.tribute.menu.style.cssText = `display: block;`; return } if (!this.isContentEditable(context.element)) { coordinates = this.getTextAreaOrInputUnderlinePosition(this.tribute.current.element, info.mentionPosition); } else { coordinates = this.getContentEditableCaretPosition(info.mentionPosition); } this.tribute.menu.style.cssText = `top: ${coordinates.top}px; left: ${coordinates.left}px; right: ${coordinates.right}px; bottom: ${coordinates.bottom}px; max-height: ${coordinates.maxHeight || 500}px; max-width: ${coordinates.maxWidth || 300}px; position: ${coordinates.position || 'absolute'}; display: block;`; if (coordinates.left === 'auto') { this.tribute.menu.style.left = 'auto'; } if (coordinates.top === 'auto') { this.tribute.menu.style.top = 'auto'; } if (scrollTo) this.scrollIntoView(); } else { this.tribute.menu.style.cssText = 'display: none'; } } get menuContainerIsBody() { return this.tribute.menuContainer === document.body || !this.tribute.menuContainer; } selectElement(targetElement, path, offset) { let range; let elem = targetElement; if (path) { for (var i = 0; i < path.length; i++) { elem = elem.childNodes[path[i]]; if (elem === undefined) { return } while (elem.length < offset) { offset -= elem.length; elem = elem.nextSibling; } if (elem.childNodes.length === 0 && !elem.length) { elem = elem.previousSibling; } } } let sel = this.getWindowSelection(); range = this.getDocument().createRange(); range.setStart(elem, offset); range.setEnd(elem, offset); range.collapse(true); try { sel.removeAllRanges(); } catch (error) {} sel.addRange(range); targetElement.focus(); } replaceTriggerText(text, requireLeadingSpace, hasTrailingSpace, originalEvent, item) { let info = this.getTriggerInfo(true, hasTrailingSpace, requireLeadingSpace, this.tribute.allowSpaces, this.tribute.autocompleteMode); if (info !== undefined) { let context = this.tribute.current; let replaceEvent = new CustomEvent('tribute-replaced', { detail: { item: item, instance: context, context: info, event: originalEvent, } }); if (!this.isContentEditable(context.element)) { let myField = this.tribute.current.element; let textSuffix = typeof this.tribute.replaceTextSuffix == 'string' ? this.tribute.replaceTextSuffix : ' '; text += textSuffix; let startPos = info.mentionPosition; let endPos = info.mentionPosition + info.mentionText.length + textSuffix.length; if (!this.tribute.autocompleteMode) { endPos += info.mentionTriggerChar.length - 1; } myField.value = myField.value.substring(0, startPos) + text + myField.value.substring(endPos, myField.value.length); myField.selectionStart = startPos + text.length; myField.selectionEnd = startPos + text.length; } else { // add a space to the end of the pasted text let textSuffix = typeof this.tribute.replaceTextSuffix == 'string' ? this.tribute.replaceTextSuffix : '\xA0'; text += textSuffix; let endPos = info.mentionPosition + info.mentionText.length; if (!this.tribute.autocompleteMode) { endPos += info.mentionTriggerChar.length; } this.pasteHtml(text, info.mentionPosition, endPos); } context.element.dispatchEvent(new CustomEvent('input', { bubbles: true })); context.element.dispatchEvent(replaceEvent); } } pasteHtml(html, startPos, endPos) { let range, sel; sel = this.getWindowSelection(); range = this.getDocument().createRange(); range.setStart(sel.anchorNode, startPos); range.setEnd(sel.anchorNode, endPos); range.deleteContents(); let el = this.getDocument().createElement('div'); el.innerHTML = html; let frag = this.getDocument().createDocumentFragment(), node, lastNode; while ((node = el.firstChild)) { lastNode = frag.appendChild(node); } range.insertNode(frag); // Preserve the selection if (lastNode) { range = range.cloneRange(); range.setStartAfter(lastNode); range.collapse(true); sel.removeAllRanges(); sel.addRange(range); } } getWindowSelection() { if (this.tribute.collection.iframe) { return this.tribute.collection.iframe.contentWindow.getSelection() } return window.getSelection() } getNodePositionInParent(element) { if (element.parentNode === null) { return 0 } for (var i = 0; i < element.parentNode.childNodes.length; i++) { let node = element.parentNode.childNodes[i]; if (node === element) { return i } } } getContentEditableSelectedPath(ctx) { let sel = this.getWindowSelection(); let selected = sel.anchorNode; let path = []; let offset; if (selected != null) { let i; let ce = selected.contentEditable; while (selected !== null && ce !== 'true') { i = this.getNodePositionInParent(selected); path.push(i); selected = selected.parentNode; if (selected !== null) { ce = selected.contentEditable; } } path.reverse(); // getRangeAt may not exist, need alternative offset = sel.getRangeAt(0).startOffset; return { selected: selected, path: path, offset: offset } } } getTextPrecedingCurrentSelection() { let context = this.tribute.current, text = ''; if (!this.isContentEditable(context.element)) { let textComponent = this.tribute.current.element; if (textComponent) { let startPos = textComponent.selectionStart; if (textComponent.value && startPos >= 0) { text = textComponent.value.substring(0, startPos); } } } else { let selectedElem = this.getWindowSelection().anchorNode; if (selectedElem != null) { let workingNodeContent = selectedElem.textContent; let selectStartOffset = this.getWindowSelection().getRangeAt(0).startOffset; if (workingNodeContent && selectStartOffset >= 0) { text = workingNodeContent.substring(0, selectStartOffset); } } } return text } getLastWordInText(text) { text = text.replace(/\u00A0/g, ' '); // path_to_url var wordsArray; if (this.tribute.autocompleteSeparator) { wordsArray = text.split(this.tribute.autocompleteSeparator); } else { wordsArray = text.split(/\s+/); } var worldsCount = wordsArray.length - 1; return wordsArray[worldsCount].trim(); } getTriggerInfo(menuAlreadyActive, hasTrailingSpace, requireLeadingSpace, allowSpaces, isAutocomplete) { let ctx = this.tribute.current; let selected, path, offset; if (!this.isContentEditable(ctx.element)) { selected = this.tribute.current.element; } else { let selectionInfo = this.getContentEditableSelectedPath(ctx); if (selectionInfo) { selected = selectionInfo.selected; path = selectionInfo.path; offset = selectionInfo.offset; } } let effectiveRange = this.getTextPrecedingCurrentSelection(); let lastWordOfEffectiveRange = this.getLastWordInText(effectiveRange); if (isAutocomplete) { return { mentionPosition: effectiveRange.length - lastWordOfEffectiveRange.length, mentionText: lastWordOfEffectiveRange, mentionSelectedElement: selected, mentionSelectedPath: path, mentionSelectedOffset: offset } } if (effectiveRange !== undefined && effectiveRange !== null) { let mostRecentTriggerCharPos = -1; let triggerChar; this.tribute.collection.forEach(config => { let c = config.trigger; let idx = config.requireLeadingSpace ? this.lastIndexWithLeadingSpace(effectiveRange, c) : effectiveRange.lastIndexOf(c); if (idx > mostRecentTriggerCharPos) { mostRecentTriggerCharPos = idx; triggerChar = c; requireLeadingSpace = config.requireLeadingSpace; } }); if (mostRecentTriggerCharPos >= 0 && ( mostRecentTriggerCharPos === 0 || !requireLeadingSpace || /[\xA0\s]/g.test( effectiveRange.substring( mostRecentTriggerCharPos - 1, mostRecentTriggerCharPos) ) ) ) { let currentTriggerSnippet = effectiveRange.substring(mostRecentTriggerCharPos + triggerChar.length, effectiveRange.length); triggerChar = effectiveRange.substring(mostRecentTriggerCharPos, mostRecentTriggerCharPos + triggerChar.length); let firstSnippetChar = currentTriggerSnippet.substring(0, 1); let leadingSpace = currentTriggerSnippet.length > 0 && ( firstSnippetChar === ' ' || firstSnippetChar === '\xA0' ); if (hasTrailingSpace) { currentTriggerSnippet = currentTriggerSnippet.trim(); } let regex = allowSpaces ? /[^\S ]/g : /[\xA0\s]/g; this.tribute.hasTrailingSpace = regex.test(currentTriggerSnippet); if (!leadingSpace && (menuAlreadyActive || !(regex.test(currentTriggerSnippet)))) { return { mentionPosition: mostRecentTriggerCharPos, mentionText: currentTriggerSnippet, mentionSelectedElement: selected, mentionSelectedPath: path, mentionSelectedOffset: offset, mentionTriggerChar: triggerChar } } } } } lastIndexWithLeadingSpace (str, trigger) { let reversedStr = str.split('').reverse().join(''); let index = -1; for (let cidx = 0, len = str.length; cidx < len; cidx++) { let firstChar = cidx === str.length - 1; let leadingSpace = /\s/.test(reversedStr[cidx + 1]); let match = true; for (let triggerIdx = trigger.length - 1; triggerIdx >= 0; triggerIdx--) { if (trigger[triggerIdx] !== reversedStr[cidx-triggerIdx]) { match = false; break } } if (match && (firstChar || leadingSpace)) { index = str.length - 1 - cidx; break } } return index } isContentEditable(element) { return element.nodeName !== 'INPUT' && element.nodeName !== 'TEXTAREA' } isMenuOffScreen(coordinates, menuDimensions) { let windowWidth = window.innerWidth; let windowHeight = window.innerHeight; let doc = document.documentElement; let windowLeft = (window.pageXOffset || doc.scrollLeft) - (doc.clientLeft || 0); let windowTop = (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0); let menuTop = typeof coordinates.top === 'number' ? coordinates.top : windowTop + windowHeight - coordinates.bottom - menuDimensions.height; let menuRight = typeof coordinates.right === 'number' ? coordinates.right : coordinates.left + menuDimensions.width; let menuBottom = typeof coordinates.bottom === 'number' ? coordinates.bottom : coordinates.top + menuDimensions.height; let menuLeft = typeof coordinates.left === 'number' ? coordinates.left : windowLeft + windowWidth - coordinates.right - menuDimensions.width; return { top: menuTop < Math.floor(windowTop), right: menuRight > Math.ceil(windowLeft + windowWidth), bottom: menuBottom > Math.ceil(windowTop + windowHeight), left: menuLeft < Math.floor(windowLeft) } } getMenuDimensions() { // Width of the menu depends of its contents and position // We must check what its width would be without any obstruction // This way, we can achieve good positioning for flipping the menu let dimensions = { width: null, height: null }; this.tribute.menu.style.cssText = `top: 0px; left: 0px; position: fixed; display: block; visibility; hidden; max-height:500px;`; dimensions.width = this.tribute.menu.offsetWidth; dimensions.height = this.tribute.menu.offsetHeight; this.tribute.menu.style.cssText = `display: none;`; return dimensions } getTextAreaOrInputUnderlinePosition(element, position, flipped) { let properties = ['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' ]; let div = this.getDocument().createElement('div'); div.id = 'input-textarea-caret-position-mirror-div'; this.getDocument().body.appendChild(div); let style = div.style; let computed = window.getComputedStyle ? getComputedStyle(element) : element.currentStyle; style.whiteSpace = 'pre-wrap'; if (element.nodeName !== 'INPUT') { style.wordWrap = 'break-word'; } style.position = 'absolute'; style.visibility = 'hidden'; // transfer the element's properties to the div properties.forEach(prop => { style[prop] = computed[prop]; }); //NOT SURE WHY THIS IS HERE AND IT DOESNT SEEM HELPFUL // if (isFirefox) { // style.width = `${(parseInt(computed.width) - 2)}px` // if (element.scrollHeight > parseInt(computed.height)) // style.overflowY = 'scroll' // } else { // style.overflow = 'hidden' // } let span0 = document.createElement('span'); span0.textContent = element.value.substring(0, position); div.appendChild(span0); if (element.nodeName === 'INPUT') { div.textContent = div.textContent.replace(/\s/g, ''); } //Create a span in the div that represents where the cursor //should be let span = this.getDocument().createElement('span'); //we give it no content as this represents the cursor span.textContent = '&#x200B;'; div.appendChild(span); let span2 = this.getDocument().createElement('span'); span2.textContent = element.value.substring(position); div.appendChild(span2); let rect = element.getBoundingClientRect(); //position the div exactly over the element //so we can get the bounding client rect for the span and //it should represent exactly where the cursor is div.style.position = 'fixed'; div.style.left = rect.left + 'px'; div.style.top = rect.top + 'px'; div.style.width = rect.width + 'px'; div.style.height = rect.height + 'px'; div.scrollTop = element.scrollTop; var spanRect = span.getBoundingClientRect(); this.getDocument().body.removeChild(div); return this.getFixedCoordinatesRelativeToRect(spanRect); } getContentEditableCaretPosition(selectedNodePosition) { let range; let sel = this.getWindowSelection(); range = this.getDocument().createRange(); range.setStart(sel.anchorNode, selectedNodePosition); range.setEnd(sel.anchorNode, selectedNodePosition); range.collapse(false); let rect = range.getBoundingClientRect(); return this.getFixedCoordinatesRelativeToRect(rect); } getFixedCoordinatesRelativeToRect(rect) { let coordinates = { position: 'fixed', left: rect.left, top: rect.top + rect.height }; let menuDimensions = this.getMenuDimensions(); var availableSpaceOnTop = rect.top; var availableSpaceOnBottom = window.innerHeight - (rect.top + rect.height); //check to see where's the right place to put the menu vertically if (availableSpaceOnBottom < menuDimensions.height) { if (availableSpaceOnTop >= menuDimensions.height || availableSpaceOnTop > availableSpaceOnBottom) { coordinates.top = 'auto'; coordinates.bottom = window.innerHeight - rect.top; if (availableSpaceOnBottom < menuDimensions.height) { coordinates.maxHeight = availableSpaceOnTop; } } else { if (availableSpaceOnTop < menuDimensions.height) { coordinates.maxHeight = availableSpaceOnBottom; } } } var availableSpaceOnLeft = rect.left; var availableSpaceOnRight = window.innerWidth - rect.left; //check to see where's the right place to put the menu horizontally if (availableSpaceOnRight < menuDimensions.width) { if (availableSpaceOnLeft >= menuDimensions.width || availableSpaceOnLeft > availableSpaceOnRight) { coordinates.left = 'auto'; coordinates.right = window.innerWidth - rect.left; if (availableSpaceOnRight < menuDimensions.width) { coordinates.maxWidth = availableSpaceOnLeft; } } else { if (availableSpaceOnLeft < menuDimensions.width) { coordinates.maxWidth = availableSpaceOnRight; } } } return coordinates } scrollIntoView(elem) { let reasonableBuffer = 20, clientRect; let maxScrollDisplacement = 100; let e = this.menu; if (typeof e === 'undefined') return; while (clientRect === undefined || clientRect.height === 0) { clientRect = e.getBoundingClientRect(); if (clientRect.height === 0) { e = e.childNodes[0]; if (e === undefined || !e.getBoundingClientRect) { return } } } let elemTop = clientRect.top; let elemBottom = elemTop + clientRect.height; if (elemTop < 0) { window.scrollTo(0, window.pageYOffset + clientRect.top - reasonableBuffer); } else if (elemBottom > window.innerHeight) { let maxY = window.pageYOffset + clientRect.top - reasonableBuffer; if (maxY - window.pageYOffset > maxScrollDisplacement) { maxY = window.pageYOffset + maxScrollDisplacement; } let targetY = window.pageYOffset - (window.innerHeight - elemBottom); if (targetY > maxY) { targetY = maxY; } window.scrollTo(0, targetY); } } } // Thanks to path_to_url class TributeSearch { constructor(tribute) { this.tribute = tribute; this.tribute.search = this; } simpleFilter(pattern, array) { return array.filter(string => { return this.test(pattern, string) }) } test(pattern, string) { return this.match(pattern, string) !== null } match(pattern, string, opts) { opts = opts || {}; let len = string.length, pre = opts.pre || '', post = opts.post || '', compareString = opts.caseSensitive && string || string.toLowerCase(); if (opts.skip) { return {rendered: string, score: 0} } pattern = opts.caseSensitive && pattern || pattern.toLowerCase(); let patternCache = this.traverse(compareString, pattern, 0, 0, []); if (!patternCache) { return null } return { rendered: this.render(string, patternCache.cache, pre, post), score: patternCache.score } } traverse(string, pattern, stringIndex, patternIndex, patternCache) { if (this.tribute.autocompleteSeparator) { // if the pattern search at end pattern = pattern.split(this.tribute.autocompleteSeparator).splice(-1)[0]; } if (pattern.length === patternIndex) { // calculate score and copy the cache containing the indices where it's found return { score: this.calculateScore(patternCache), cache: patternCache.slice() } } // if string at end or remaining pattern > remaining string if (string.length === stringIndex || pattern.length - patternIndex > string.length - stringIndex) { return undefined } let c = pattern[patternIndex]; let index = string.indexOf(c, stringIndex); let best, temp; while (index > -1) { patternCache.push(index); temp = this.traverse(string, pattern, index + 1, patternIndex + 1, patternCache); patternCache.pop(); // if downstream traversal failed, return best answer so far if (!temp) { return best } if (!best || best.score < temp.score) { best = temp; } index = string.indexOf(c, index + 1); } return best } calculateScore(patternCache) { let score = 0; let temp = 1; patternCache.forEach((index, i) => { if (i > 0) { if (patternCache[i - 1] + 1 === index) { temp += temp + 1; } else { temp = 1; } } score += temp; }); return score } render(string, indices, pre, post) { var rendered = string.substring(0, indices[0]); indices.forEach((index, i) => { rendered += pre + string[index] + post + string.substring(index + 1, (indices[i + 1]) ? indices[i + 1] : string.length); }); return rendered } filter(pattern, arr, opts) { opts = opts || {}; return arr .reduce((prev, element, idx, arr) => { let str = element; if (opts.extract) { str = opts.extract(element); if (!str) { // take care of undefineds / nulls / etc. str = ''; } } let rendered = this.match(pattern, str, opts); if (rendered != null) { prev[prev.length] = { string: rendered.rendered, score: rendered.score, index: idx, original: element }; } return prev }, []) .sort((a, b) => { let compare = b.score - a.score; if (compare) return compare return a.index - b.index }) } } class Tribute { constructor({ values = null, loadingItemTemplate = null, iframe = null, selectClass = "highlight", containerClass = "tribute-container", itemClass = "", trigger = "@", autocompleteMode = false, autocompleteSeparator = null, selectTemplate = null, menuItemTemplate = null, lookup = "key", fillAttr = "value", collection = null, menuContainer = null, noMatchTemplate = null, requireLeadingSpace = true, allowSpaces = false, replaceTextSuffix = null, positionMenu = true, spaceSelectsMatch = false, searchOpts = {}, menuItemLimit = null, menuShowMinLength = 0 }) { this.autocompleteMode = autocompleteMode; this.autocompleteSeparator = autocompleteSeparator; this.menuSelected = 0; this.current = {}; this.inputEvent = false; this.isActive = false; this.menuContainer = menuContainer; this.allowSpaces = allowSpaces; this.replaceTextSuffix = replaceTextSuffix; this.positionMenu = positionMenu; this.hasTrailingSpace = false; this.spaceSelectsMatch = spaceSelectsMatch; if (this.autocompleteMode) { trigger = ""; allowSpaces = false; } if (values) { this.collection = [ { // symbol that starts the lookup trigger: trigger, // is it wrapped in an iframe iframe: iframe, // class applied to selected item selectClass: selectClass, // class applied to the Container containerClass: containerClass, // class applied to each item itemClass: itemClass, // function called on select that retuns the content to insert selectTemplate: ( selectTemplate || Tribute.defaultSelectTemplate ).bind(this), // function called that returns content for an item menuItemTemplate: ( menuItemTemplate || Tribute.defaultMenuItemTemplate ).bind(this), // function called when menu is empty, disables hiding of menu. noMatchTemplate: (t => { if (typeof t === "string") { if (t.trim() === "") return null; return t; } if (typeof t === "function") { return t.bind(this); } return ( noMatchTemplate || function() { return "<li>No Match Found!</li>"; }.bind(this) ); })(noMatchTemplate), // column to search against in the object lookup: lookup, // column that contains the content to insert by default fillAttr: fillAttr, // array of objects or a function returning an array of objects values: values, // useful for when values is an async function loadingItemTemplate: loadingItemTemplate, requireLeadingSpace: requireLeadingSpace, searchOpts: searchOpts, menuItemLimit: menuItemLimit, menuShowMinLength: menuShowMinLength } ]; } else if (collection) { if (this.autocompleteMode) console.warn( "Tribute in autocomplete mode does not work for collections" ); this.collection = collection.map(item => { return { trigger: item.trigger || trigger, iframe: item.iframe || iframe, selectClass: item.selectClass || selectClass, containerClass: item.containerClass || containerClass, itemClass: item.itemClass || itemClass, selectTemplate: ( item.selectTemplate || Tribute.defaultSelectTemplate ).bind(this), menuItemTemplate: ( item.menuItemTemplate || Tribute.defaultMenuItemTemplate ).bind(this), // function called when menu is empty, disables hiding of menu. noMatchTemplate: (t => { if (typeof t === "string") { if (t.trim() === "") return null; return t; } if (typeof t === "function") { return t.bind(this); } return ( noMatchTemplate || function() { return "<li>No Match Found!</li>"; }.bind(this) ); })(noMatchTemplate), lookup: item.lookup || lookup, fillAttr: item.fillAttr || fillAttr, values: item.values, loadingItemTemplate: item.loadingItemTemplate, requireLeadingSpace: item.requireLeadingSpace, searchOpts: item.searchOpts || searchOpts, menuItemLimit: item.menuItemLimit || menuItemLimit, menuShowMinLength: item.menuShowMinLength || menuShowMinLength }; }); } else { throw new Error("[Tribute] No collection specified."); } new TributeRange(this); new TributeEvents(this); new TributeMenuEvents(this); new TributeSearch(this); } get isActive() { return this._isActive; } set isActive(val) { if (this._isActive != val) { this._isActive = val; if (this.current.element) { let noMatchEvent = new CustomEvent(`tribute-active-${val}`); this.current.element.dispatchEvent(noMatchEvent); } } } static defaultSelectTemplate(item) { if (typeof item === "undefined") return `${this.current.collection.trigger}${this.current.mentionText}`; if (this.range.isContentEditable(this.current.element)) { return ( '<span class="tribute-mention">' + (this.current.collection.trigger + item.original[this.current.collection.fillAttr]) + "</span>" ); } return ( this.current.collection.trigger + item.original[this.current.collection.fillAttr] ); } static defaultMenuItemTemplate(matchItem) { return matchItem.string; } static inputTypes() { return ["TEXTAREA", "INPUT"]; } triggers() { return this.collection.map(config => { return config.trigger; }); } attach(el) { if (!el) { throw new Error("[Tribute] Must pass in a DOM node or NodeList."); } // Check if it is a jQuery collection if (typeof jQuery !== "undefined" && el instanceof jQuery) { el = el.get(); } // Is el an Array/Array-like object? if ( el.constructor === NodeList || el.constructor === HTMLCollection || el.constructor === Array ) { let length = el.length; for (var i = 0; i < length; ++i) { this._attach(el[i]); } } else { this._attach(el); } } _attach(el) { if (el.hasAttribute("data-tribute")) { console.warn("Tribute was already bound to " + el.nodeName); } this.ensureEditable(el); this.events.bind(el); el.setAttribute("data-tribute", true); } ensureEditable(element) { if (Tribute.inputTypes().indexOf(element.nodeName) === -1) { if (element.contentEditable) { element.contentEditable = true; } else { throw new Error("[Tribute] Cannot bind to " + element.nodeName); } } } createMenu(containerClass) { let wrapper = this.range.getDocument().createElement("div"), ul = this.range.getDocument().createElement("ul"); wrapper.className = containerClass; wrapper.appendChild(ul); if (this.menuContainer) { return this.menuContainer.appendChild(wrapper); } return this.range.getDocument().body.appendChild(wrapper); } showMenuFor(element, scrollTo) { // Only proceed if menu isn't already shown for the current element & mentionText if ( this.isActive && this.current.element === element && this.current.mentionText === this.currentMentionTextSnapshot ) { return; } this.currentMentionTextSnapshot = this.current.mentionText; // create the menu if it doesn't exist. if (!this.menu) { this.menu = this.createMenu(this.current.collection.containerClass); element.tributeMenu = this.menu; this.menuEvents.bind(this.menu); } this.isActive = true; this.menuSelected = 0; if (!this.current.mentionText) { this.current.mentionText = ""; } const processValues = values => { // Tribute may not be active any more by the time the value callback returns if (!this.isActive) { return; } let items = this.search.filter(this.current.mentionText, values, { pre: this.current.collection.searchOpts.pre || "<span>", post: this.current.collection.searchOpts.post || "</span>", skip: this.current.collection.searchOpts.skip, extract: el => { if (typeof this.current.collection.lookup === "string") { return el[this.current.collection.lookup]; } else if (typeof this.current.collection.lookup === "function") { return this.current.collection.lookup(el, this.current.mentionText); } else { throw new Error( "Invalid lookup attribute, lookup must be string or function." ); } } }); if (this.current.collection.menuItemLimit) { items = items.slice(0, this.current.collection.menuItemLimit); } this.current.filteredItems = items; let ul = this.menu.querySelector("ul"); if (!items.length) { let noMatchEvent = new CustomEvent("tribute-no-match", { detail: this.menu }); this.current.element.dispatchEvent(noMatchEvent); if ( (typeof this.current.collection.noMatchTemplate === "function" && !this.current.collection.noMatchTemplate()) || !this.current.collection.noMatchTemplate ) { this.hideMenu(); } else { typeof this.current.collection.noMatchTemplate === "function" ? (ul.innerHTML = this.current.collection.noMatchTemplate()) : (ul.innerHTML = this.current.collection.noMatchTemplate); this.range.positionMenuAtCaret(scrollTo); } return; } ul.innerHTML = ""; let fragment = this.range.getDocument().createDocumentFragment(); items.forEach((item, index) => { let li = this.range.getDocument().createElement("li"); li.setAttribute("data-index", index); li.className = this.current.collection.itemClass; li.addEventListener("mousemove", e => { let [li, index] = this._findLiTarget(e.target); if (e.movementY !== 0) { this.events.setActiveLi(index); } }); if (this.menuSelected === index) { li.classList.add(this.current.collection.selectClass); } li.innerHTML = this.current.collection.menuItemTemplate(item); fragment.appendChild(li); }); ul.appendChild(fragment); this.range.positionMenuAtCaret(scrollTo); }; if (typeof this.current.collection.values === "function") { if (this.current.collection.loadingItemTemplate) { this.menu.querySelector("ul").innerHTML = this.current.collection.loadingItemTemplate; this.range.positionMenuAtCaret(scrollTo); } this.current.collection.values(this.current.mentionText, processValues); } else { processValues(this.current.collection.values); } } _findLiTarget(el) { if (!el) return []; const index = el.getAttribute("data-index"); return !index ? this._findLiTarget(el.parentNode) : [el, index]; } showMenuForCollection(element, collectionIndex) { if (element !== document.activeElement) { this.placeCaretAtEnd(element); } this.current.collection = this.collection[collectionIndex || 0]; this.current.externalTrigger = true; this.current.element = element; if (element.isContentEditable) this.insertTextAtCursor(this.current.collection.trigger); else this.insertAtCaret(element, this.current.collection.trigger); this.showMenuFor(element); } // TODO: make sure this works for inputs/textareas placeCaretAtEnd(el) { el.focus(); if ( typeof window.getSelection != "undefined" && typeof document.createRange != "undefined" ) { var range = document.createRange(); range.selectNodeContents(el); range.collapse(false); var sel = window.getSelection(); sel.removeAllRanges(); sel.addRange(range); } else if (typeof document.body.createTextRange != "undefined") { var textRange = document.body.createTextRange(); textRange.moveToElementText(el); textRange.collapse(false); textRange.select(); } } // for contenteditable insertTextAtCursor(text) { var sel, range; sel = window.getSelection(); range = sel.getRangeAt(0); range.deleteContents(); var textNode = document.createTextNode(text); range.insertNode(textNode); range.selectNodeContents(textNode); range.collapse(false); sel.removeAllRanges(); sel.addRange(range); } // for regular inputs insertAtCaret(textarea, text) { var scrollPos = textarea.scrollTop; var caretPos = textarea.selectionStart; var front = textarea.value.substring(0, caretPos); var back = textarea.value.substring( textarea.selectionEnd, textarea.value.length ); textarea.value = front + text + back; caretPos = caretPos + text.length; textarea.selectionStart = caretPos; textarea.selectionEnd = caretPos; textarea.focus(); textarea.scrollTop = scrollPos; } hideMenu() { if (this.menu) { this.menu.style.cssText = "display: none;"; this.isActive = false; this.menuSelected = 0; this.current = {}; } } selectItemAtIndex(index, originalEvent) { index = parseInt(index); if (typeof index !== "number" || isNaN(index)) return; let item = this.current.filteredItems[index]; let content = this.current.collection.selectTemplate(item); if (content !== null) this.replaceText(content, originalEvent, item); } replaceText(content, originalEvent, item) { this.range.replaceTriggerText(content, true, true, originalEvent, item); } _append(collection, newValues, replace) { if (typeof collection.values === "function") { throw new Error("Unable to append to values, as it is a function."); } else if (!replace) { collection.values = collection.values.concat(newValues); } else { collection.values = newValues; } } append(collectionIndex, newValues, replace) { let index = parseInt(collectionIndex); if (typeof index !== "number") throw new Error("please provide an index for the collection to update."); let collection = this.collection[index]; this._append(collection, newValues, replace); } appendCurrent(newValues, replace) { if (this.isActive) { this._append(this.current.collection, newValues, replace); } else { throw new Error( "No active state. Please use append instead and pass an index." ); } } detach(el) { if (!el) { throw new Error("[Tribute] Must pass in a DOM node or NodeList."); } // Check if it is a jQuery collection if (typeof jQuery !== "undefined" && el instanceof jQuery) { el = el.get(); } // Is el an Array/Array-like object? if ( el.constructor === NodeList || el.constructor === HTMLCollection || el.constructor === Array ) { let length = el.length; for (var i = 0; i < length; ++i) { this._detach(el[i]); } } else { this._detach(el); } } _detach(el) { this.events.unbind(el); if (el.tributeMenu) { this.menuEvents.unbind(el.tributeMenu); } setTimeout(() => { el.removeAttribute("data-tribute"); this.isActive = false; if (el.tributeMenu) { el.tributeMenu.remove(); } }); } } /** * Tribute.js * Native ES6 JavaScript @mention Plugin **/ export default Tribute; ```
/content/code_sandbox/dist/tribute.esm.js
javascript
2016-01-19T00:54:39
2024-08-14T11:30:58
tribute
zurb/tribute
2,017
11,448
```javascript (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global = global || self, global.Tribute = factory()); }(this, (function () { 'use strict'; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } function _iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(n); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } function _nonIterableRest() { 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 (predicate) { if (this === null) { throw new TypeError('Array.prototype.find called on null or undefined'); } if (typeof predicate !== 'function') { throw new TypeError('predicate must be a function'); } var list = Object(this); var length = list.length >>> 0; var thisArg = arguments[1]; var value; for (var i = 0; i < length; i++) { value = list[i]; if (predicate.call(thisArg, value, i, list)) { return value; } } return undefined; }; } if (window && typeof window.CustomEvent !== "function") { var CustomEvent$1 = function CustomEvent(event, params) { params = params || { bubbles: false, cancelable: false, detail: undefined }; var evt = document.createEvent('CustomEvent'); evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail); return evt; }; if (typeof window.Event !== 'undefined') { CustomEvent$1.prototype = window.Event.prototype; } window.CustomEvent = CustomEvent$1; } var TributeEvents = /*#__PURE__*/function () { function TributeEvents(tribute) { _classCallCheck(this, TributeEvents); this.tribute = tribute; this.tribute.events = this; } _createClass(TributeEvents, [{ key: "bind", value: function bind(element) { element.boundKeydown = this.keydown.bind(element, this); element.boundKeyup = this.keyup.bind(element, this); element.boundInput = this.input.bind(element, this); element.addEventListener("keydown", element.boundKeydown, false); element.addEventListener("keyup", element.boundKeyup, false); element.addEventListener("input", element.boundInput, false); } }, { key: "unbind", value: function unbind(element) { element.removeEventListener("keydown", element.boundKeydown, false); element.removeEventListener("keyup", element.boundKeyup, false); element.removeEventListener("input", element.boundInput, false); delete element.boundKeydown; delete element.boundKeyup; delete element.boundInput; } }, { key: "keydown", value: function keydown(instance, event) { if (instance.shouldDeactivate(event)) { instance.tribute.isActive = false; instance.tribute.hideMenu(); } var element = this; instance.commandEvent = false; TributeEvents.keys().forEach(function (o) { if (o.key === event.keyCode) { instance.commandEvent = true; instance.callbacks()[o.value.toLowerCase()](event, element); } }); } }, { key: "input", value: function input(instance, event) { instance.inputEvent = true; instance.keyup.call(this, instance, event); } }, { key: "click", value: function click(instance, event) { var tribute = instance.tribute; if (tribute.menu && tribute.menu.contains(event.target)) { var li = event.target; event.preventDefault(); event.stopPropagation(); while (li.nodeName.toLowerCase() !== "li") { li = li.parentNode; if (!li || li === tribute.menu) { throw new Error("cannot find the <li> container for the click"); } } tribute.selectItemAtIndex(li.getAttribute("data-index"), event); tribute.hideMenu(); // TODO: should fire with externalTrigger and target is outside of menu } else if (tribute.current.element && !tribute.current.externalTrigger) { tribute.current.externalTrigger = false; setTimeout(function () { return tribute.hideMenu(); }); } } }, { key: "keyup", value: function keyup(instance, event) { if (instance.inputEvent) { instance.inputEvent = false; } instance.updateSelection(this); if (event.keyCode === 27) return; if (!instance.tribute.allowSpaces && instance.tribute.hasTrailingSpace) { instance.tribute.hasTrailingSpace = false; instance.commandEvent = true; instance.callbacks()["space"](event, this); return; } if (!instance.tribute.isActive) { if (instance.tribute.autocompleteMode) { instance.callbacks().triggerChar(event, this, ""); } else { var keyCode = instance.getKeyCode(instance, this, event); if (isNaN(keyCode) || !keyCode) return; var trigger = instance.tribute.triggers().find(function (trigger) { return trigger.charCodeAt(0) === keyCode; }); if (typeof trigger !== "undefined") { instance.callbacks().triggerChar(event, this, trigger); } } } if (instance.tribute.current.mentionText.length < instance.tribute.current.collection.menuShowMinLength) { return; } if ((instance.tribute.current.trigger || instance.tribute.autocompleteMode) && instance.commandEvent === false || instance.tribute.isActive && event.keyCode === 8) { instance.tribute.showMenuFor(this, true); } } }, { key: "shouldDeactivate", value: function shouldDeactivate(event) { if (!this.tribute.isActive) return false; if (this.tribute.current.mentionText.length === 0) { var eventKeyPressed = false; TributeEvents.keys().forEach(function (o) { if (event.keyCode === o.key) eventKeyPressed = true; }); return !eventKeyPressed; } return false; } }, { key: "getKeyCode", value: function getKeyCode(instance, el, event) { var tribute = instance.tribute; var info = tribute.range.getTriggerInfo(false, tribute.hasTrailingSpace, true, tribute.allowSpaces, tribute.autocompleteMode); if (info) { return info.mentionTriggerChar.charCodeAt(0); } else { return false; } } }, { key: "updateSelection", value: function updateSelection(el) { this.tribute.current.element = el; var info = this.tribute.range.getTriggerInfo(false, this.tribute.hasTrailingSpace, true, this.tribute.allowSpaces, this.tribute.autocompleteMode); if (info) { this.tribute.current.selectedPath = info.mentionSelectedPath; this.tribute.current.mentionText = info.mentionText; this.tribute.current.selectedOffset = info.mentionSelectedOffset; } } }, { key: "callbacks", value: function callbacks() { var _this = this; return { triggerChar: function triggerChar(e, el, trigger) { var tribute = _this.tribute; tribute.current.trigger = trigger; var collectionItem = tribute.collection.find(function (item) { return item.trigger === trigger; }); tribute.current.collection = collectionItem; if (tribute.current.mentionText.length >= tribute.current.collection.menuShowMinLength && tribute.inputEvent) { tribute.showMenuFor(el, true); } }, enter: function enter(e, el) { // choose selection if (_this.tribute.isActive && _this.tribute.current.filteredItems) { e.preventDefault(); e.stopPropagation(); setTimeout(function () { _this.tribute.selectItemAtIndex(_this.tribute.menuSelected, e); _this.tribute.hideMenu(); }, 0); } }, escape: function escape(e, el) { if (_this.tribute.isActive) { e.preventDefault(); e.stopPropagation(); _this.tribute.isActive = false; _this.tribute.hideMenu(); } }, tab: function tab(e, el) { // choose first match _this.callbacks().enter(e, el); }, space: function space(e, el) { if (_this.tribute.isActive) { if (_this.tribute.spaceSelectsMatch) { _this.callbacks().enter(e, el); } else if (!_this.tribute.allowSpaces) { e.stopPropagation(); setTimeout(function () { _this.tribute.hideMenu(); _this.tribute.isActive = false; }, 0); } } }, up: function up(e, el) { // navigate up ul if (_this.tribute.isActive && _this.tribute.current.filteredItems) { e.preventDefault(); e.stopPropagation(); var count = _this.tribute.current.filteredItems.length, selected = _this.tribute.menuSelected; if (count > selected && selected > 0) { _this.tribute.menuSelected--; _this.setActiveLi(); } else if (selected === 0) { _this.tribute.menuSelected = count - 1; _this.setActiveLi(); _this.tribute.menu.scrollTop = _this.tribute.menu.scrollHeight; } } }, down: function down(e, el) { // navigate down ul if (_this.tribute.isActive && _this.tribute.current.filteredItems) { e.preventDefault(); e.stopPropagation(); var count = _this.tribute.current.filteredItems.length - 1, selected = _this.tribute.menuSelected; if (count > selected) { _this.tribute.menuSelected++; _this.setActiveLi(); } else if (count === selected) { _this.tribute.menuSelected = 0; _this.setActiveLi(); _this.tribute.menu.scrollTop = 0; } } }, "delete": function _delete(e, el) { if (_this.tribute.isActive && _this.tribute.current.mentionText.length < 1) { _this.tribute.hideMenu(); } else if (_this.tribute.isActive) { _this.tribute.showMenuFor(el); } } }; } }, { key: "setActiveLi", value: function setActiveLi(index) { var lis = this.tribute.menu.querySelectorAll("li"), length = lis.length >>> 0; if (index) this.tribute.menuSelected = parseInt(index); for (var i = 0; i < length; i++) { var li = lis[i]; if (i === this.tribute.menuSelected) { li.classList.add(this.tribute.current.collection.selectClass); var liClientRect = li.getBoundingClientRect(); var menuClientRect = this.tribute.menu.getBoundingClientRect(); if (liClientRect.bottom > menuClientRect.bottom) { var scrollDistance = liClientRect.bottom - menuClientRect.bottom; this.tribute.menu.scrollTop += scrollDistance; } else if (liClientRect.top < menuClientRect.top) { var _scrollDistance = menuClientRect.top - liClientRect.top; this.tribute.menu.scrollTop -= _scrollDistance; } } else { li.classList.remove(this.tribute.current.collection.selectClass); } } } }, { key: "getFullHeight", value: function getFullHeight(elem, includeMargin) { var height = elem.getBoundingClientRect().height; if (includeMargin) { var style = elem.currentStyle || window.getComputedStyle(elem); return height + parseFloat(style.marginTop) + parseFloat(style.marginBottom); } return height; } }], [{ key: "keys", value: function keys() { 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" }]; } }]); return TributeEvents; }(); var TributeMenuEvents = /*#__PURE__*/function () { function TributeMenuEvents(tribute) { _classCallCheck(this, TributeMenuEvents); this.tribute = tribute; this.tribute.menuEvents = this; this.menu = this.tribute.menu; } _createClass(TributeMenuEvents, [{ key: "bind", value: function bind(menu) { var _this = this; this.menuClickEvent = this.tribute.events.click.bind(null, this); this.menuContainerScrollEvent = this.debounce(function () { if (_this.tribute.isActive) { _this.tribute.hideMenu(); } }, 10, false); this.windowResizeEvent = this.debounce(function () { if (_this.tribute.isActive) { _this.tribute.hideMenu(); } }, 10, false); // fixes IE11 issues with mousedown this.tribute.range.getDocument().addEventListener("MSPointerDown", this.menuClickEvent, false); this.tribute.range.getDocument().addEventListener("mousedown", this.menuClickEvent, false); window.addEventListener("resize", this.windowResizeEvent); if (this.menuContainer) { this.menuContainer.addEventListener("scroll", this.menuContainerScrollEvent, false); } else { window.addEventListener("scroll", this.menuContainerScrollEvent); } } }, { key: "unbind", value: function unbind(menu) { this.tribute.range.getDocument().removeEventListener("mousedown", this.menuClickEvent, false); this.tribute.range.getDocument().removeEventListener("MSPointerDown", this.menuClickEvent, false); window.removeEventListener("resize", this.windowResizeEvent); if (this.menuContainer) { this.menuContainer.removeEventListener("scroll", this.menuContainerScrollEvent, false); } else { window.removeEventListener("scroll", this.menuContainerScrollEvent); } } }, { key: "debounce", value: function debounce(func, wait, immediate) { var _arguments = arguments, _this2 = this; var timeout; return function () { var context = _this2, args = _arguments; var later = function later() { timeout = null; if (!immediate) func.apply(context, args); }; var callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait); if (callNow) func.apply(context, args); }; } }]); return TributeMenuEvents; }(); var TributeRange = /*#__PURE__*/function () { function TributeRange(tribute) { _classCallCheck(this, TributeRange); this.tribute = tribute; this.tribute.range = this; } _createClass(TributeRange, [{ key: "getDocument", value: function getDocument() { var iframe; if (this.tribute.current.collection) { iframe = this.tribute.current.collection.iframe; } if (!iframe) { return document; } return iframe.contentWindow.document; } }, { key: "positionMenuAtCaret", value: function positionMenuAtCaret(scrollTo) { var context = this.tribute.current, coordinates; var info = this.getTriggerInfo(false, this.tribute.hasTrailingSpace, true, this.tribute.allowSpaces, this.tribute.autocompleteMode); if (typeof info !== 'undefined') { if (!this.tribute.positionMenu) { this.tribute.menu.style.cssText = "display: block;"; return; } if (!this.isContentEditable(context.element)) { coordinates = this.getTextAreaOrInputUnderlinePosition(this.tribute.current.element, info.mentionPosition); } else { coordinates = this.getContentEditableCaretPosition(info.mentionPosition); } this.tribute.menu.style.cssText = "top: ".concat(coordinates.top, "px;\n left: ").concat(coordinates.left, "px;\n right: ").concat(coordinates.right, "px;\n bottom: ").concat(coordinates.bottom, "px;\n max-height: ").concat(coordinates.maxHeight || 500, "px;\n max-width: ").concat(coordinates.maxWidth || 300, "px;\n position: ").concat(coordinates.position || 'absolute', ";\n display: block;"); if (coordinates.left === 'auto') { this.tribute.menu.style.left = 'auto'; } if (coordinates.top === 'auto') { this.tribute.menu.style.top = 'auto'; } if (scrollTo) this.scrollIntoView(); } else { this.tribute.menu.style.cssText = 'display: none'; } } }, { key: "selectElement", value: function selectElement(targetElement, path, offset) { var range; var elem = targetElement; if (path) { for (var i = 0; i < path.length; i++) { elem = elem.childNodes[path[i]]; if (elem === undefined) { return; } while (elem.length < offset) { offset -= elem.length; elem = elem.nextSibling; } if (elem.childNodes.length === 0 && !elem.length) { elem = elem.previousSibling; } } } var sel = this.getWindowSelection(); range = this.getDocument().createRange(); range.setStart(elem, offset); range.setEnd(elem, offset); range.collapse(true); try { sel.removeAllRanges(); } catch (error) {} sel.addRange(range); targetElement.focus(); } }, { key: "replaceTriggerText", value: function replaceTriggerText(text, requireLeadingSpace, hasTrailingSpace, originalEvent, item) { var info = this.getTriggerInfo(true, hasTrailingSpace, requireLeadingSpace, this.tribute.allowSpaces, this.tribute.autocompleteMode); if (info !== undefined) { var context = this.tribute.current; var replaceEvent = new CustomEvent('tribute-replaced', { detail: { item: item, instance: context, context: info, event: originalEvent } }); if (!this.isContentEditable(context.element)) { var myField = this.tribute.current.element; var textSuffix = typeof this.tribute.replaceTextSuffix == 'string' ? this.tribute.replaceTextSuffix : ' '; text += textSuffix; var startPos = info.mentionPosition; var endPos = info.mentionPosition + info.mentionText.length + textSuffix.length; if (!this.tribute.autocompleteMode) { endPos += info.mentionTriggerChar.length - 1; } myField.value = myField.value.substring(0, startPos) + text + myField.value.substring(endPos, myField.value.length); myField.selectionStart = startPos + text.length; myField.selectionEnd = startPos + text.length; } else { // add a space to the end of the pasted text var _textSuffix = typeof this.tribute.replaceTextSuffix == 'string' ? this.tribute.replaceTextSuffix : '\xA0'; text += _textSuffix; var _endPos = info.mentionPosition + info.mentionText.length; if (!this.tribute.autocompleteMode) { _endPos += info.mentionTriggerChar.length; } this.pasteHtml(text, info.mentionPosition, _endPos); } context.element.dispatchEvent(new CustomEvent('input', { bubbles: true })); context.element.dispatchEvent(replaceEvent); } } }, { key: "pasteHtml", value: function pasteHtml(html, startPos, endPos) { var range, sel; sel = this.getWindowSelection(); range = this.getDocument().createRange(); range.setStart(sel.anchorNode, startPos); range.setEnd(sel.anchorNode, endPos); range.deleteContents(); var el = this.getDocument().createElement('div'); el.innerHTML = html; var frag = this.getDocument().createDocumentFragment(), node, lastNode; while (node = el.firstChild) { lastNode = frag.appendChild(node); } range.insertNode(frag); // Preserve the selection if (lastNode) { range = range.cloneRange(); range.setStartAfter(lastNode); range.collapse(true); sel.removeAllRanges(); sel.addRange(range); } } }, { key: "getWindowSelection", value: function getWindowSelection() { if (this.tribute.collection.iframe) { return this.tribute.collection.iframe.contentWindow.getSelection(); } return window.getSelection(); } }, { key: "getNodePositionInParent", value: function getNodePositionInParent(element) { if (element.parentNode === null) { return 0; } for (var i = 0; i < element.parentNode.childNodes.length; i++) { var node = element.parentNode.childNodes[i]; if (node === element) { return i; } } } }, { key: "getContentEditableSelectedPath", value: function getContentEditableSelectedPath(ctx) { var sel = this.getWindowSelection(); var selected = sel.anchorNode; var path = []; var offset; if (selected != null) { var i; var ce = selected.contentEditable; while (selected !== null && ce !== 'true') { i = this.getNodePositionInParent(selected); path.push(i); selected = selected.parentNode; if (selected !== null) { ce = selected.contentEditable; } } path.reverse(); // getRangeAt may not exist, need alternative offset = sel.getRangeAt(0).startOffset; return { selected: selected, path: path, offset: offset }; } } }, { key: "getTextPrecedingCurrentSelection", value: function getTextPrecedingCurrentSelection() { var context = this.tribute.current, text = ''; if (!this.isContentEditable(context.element)) { var textComponent = this.tribute.current.element; if (textComponent) { var startPos = textComponent.selectionStart; if (textComponent.value && startPos >= 0) { text = textComponent.value.substring(0, startPos); } } } else { var selectedElem = this.getWindowSelection().anchorNode; if (selectedElem != null) { var workingNodeContent = selectedElem.textContent; var selectStartOffset = this.getWindowSelection().getRangeAt(0).startOffset; if (workingNodeContent && selectStartOffset >= 0) { text = workingNodeContent.substring(0, selectStartOffset); } } } return text; } }, { key: "getLastWordInText", value: function getLastWordInText(text) { text = text.replace(/\u00A0/g, ' '); // path_to_url var wordsArray; if (this.tribute.autocompleteSeparator) { wordsArray = text.split(this.tribute.autocompleteSeparator); } else { wordsArray = text.split(/\s+/); } var worldsCount = wordsArray.length - 1; return wordsArray[worldsCount].trim(); } }, { key: "getTriggerInfo", value: function getTriggerInfo(menuAlreadyActive, hasTrailingSpace, requireLeadingSpace, allowSpaces, isAutocomplete) { var _this = this; var ctx = this.tribute.current; var selected, path, offset; if (!this.isContentEditable(ctx.element)) { selected = this.tribute.current.element; } else { var selectionInfo = this.getContentEditableSelectedPath(ctx); if (selectionInfo) { selected = selectionInfo.selected; path = selectionInfo.path; offset = selectionInfo.offset; } } var effectiveRange = this.getTextPrecedingCurrentSelection(); var lastWordOfEffectiveRange = this.getLastWordInText(effectiveRange); if (isAutocomplete) { return { mentionPosition: effectiveRange.length - lastWordOfEffectiveRange.length, mentionText: lastWordOfEffectiveRange, mentionSelectedElement: selected, mentionSelectedPath: path, mentionSelectedOffset: offset }; } if (effectiveRange !== undefined && effectiveRange !== null) { var mostRecentTriggerCharPos = -1; var triggerChar; this.tribute.collection.forEach(function (config) { var c = config.trigger; var idx = config.requireLeadingSpace ? _this.lastIndexWithLeadingSpace(effectiveRange, c) : effectiveRange.lastIndexOf(c); if (idx > mostRecentTriggerCharPos) { mostRecentTriggerCharPos = idx; triggerChar = c; requireLeadingSpace = config.requireLeadingSpace; } }); if (mostRecentTriggerCharPos >= 0 && (mostRecentTriggerCharPos === 0 || !requireLeadingSpace || /[\xA0\s]/g.test(effectiveRange.substring(mostRecentTriggerCharPos - 1, mostRecentTriggerCharPos)))) { var currentTriggerSnippet = effectiveRange.substring(mostRecentTriggerCharPos + triggerChar.length, effectiveRange.length); triggerChar = effectiveRange.substring(mostRecentTriggerCharPos, mostRecentTriggerCharPos + triggerChar.length); var firstSnippetChar = currentTriggerSnippet.substring(0, 1); var leadingSpace = currentTriggerSnippet.length > 0 && (firstSnippetChar === ' ' || firstSnippetChar === '\xA0'); if (hasTrailingSpace) { currentTriggerSnippet = currentTriggerSnippet.trim(); } var regex = allowSpaces ? /[^\S ]/g : /[\xA0\s]/g; this.tribute.hasTrailingSpace = regex.test(currentTriggerSnippet); if (!leadingSpace && (menuAlreadyActive || !regex.test(currentTriggerSnippet))) { return { mentionPosition: mostRecentTriggerCharPos, mentionText: currentTriggerSnippet, mentionSelectedElement: selected, mentionSelectedPath: path, mentionSelectedOffset: offset, mentionTriggerChar: triggerChar }; } } } } }, { key: "lastIndexWithLeadingSpace", value: function lastIndexWithLeadingSpace(str, trigger) { var reversedStr = str.split('').reverse().join(''); var index = -1; for (var cidx = 0, len = str.length; cidx < len; cidx++) { var firstChar = cidx === str.length - 1; var leadingSpace = /\s/.test(reversedStr[cidx + 1]); var match = true; for (var triggerIdx = trigger.length - 1; triggerIdx >= 0; triggerIdx--) { if (trigger[triggerIdx] !== reversedStr[cidx - triggerIdx]) { match = false; break; } } if (match && (firstChar || leadingSpace)) { index = str.length - 1 - cidx; break; } } return index; } }, { key: "isContentEditable", value: function isContentEditable(element) { return element.nodeName !== 'INPUT' && element.nodeName !== 'TEXTAREA'; } }, { key: "isMenuOffScreen", value: function isMenuOffScreen(coordinates, menuDimensions) { var windowWidth = window.innerWidth; var windowHeight = window.innerHeight; var doc = document.documentElement; var windowLeft = (window.pageXOffset || doc.scrollLeft) - (doc.clientLeft || 0); var windowTop = (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0); var menuTop = typeof coordinates.top === 'number' ? coordinates.top : windowTop + windowHeight - coordinates.bottom - menuDimensions.height; var menuRight = typeof coordinates.right === 'number' ? coordinates.right : coordinates.left + menuDimensions.width; var menuBottom = typeof coordinates.bottom === 'number' ? coordinates.bottom : coordinates.top + menuDimensions.height; var menuLeft = typeof coordinates.left === 'number' ? coordinates.left : windowLeft + windowWidth - coordinates.right - menuDimensions.width; return { top: menuTop < Math.floor(windowTop), right: menuRight > Math.ceil(windowLeft + windowWidth), bottom: menuBottom > Math.ceil(windowTop + windowHeight), left: menuLeft < Math.floor(windowLeft) }; } }, { key: "getMenuDimensions", value: function getMenuDimensions() { // Width of the menu depends of its contents and position // We must check what its width would be without any obstruction // This way, we can achieve good positioning for flipping the menu var dimensions = { width: null, height: null }; this.tribute.menu.style.cssText = "top: 0px;\n left: 0px;\n position: fixed;\n display: block;\n visibility; hidden;\n max-height:500px;"; dimensions.width = this.tribute.menu.offsetWidth; dimensions.height = this.tribute.menu.offsetHeight; this.tribute.menu.style.cssText = "display: none;"; return dimensions; } }, { key: "getTextAreaOrInputUnderlinePosition", value: function getTextAreaOrInputUnderlinePosition(element, position, flipped) { var properties = ['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']; var div = this.getDocument().createElement('div'); div.id = 'input-textarea-caret-position-mirror-div'; this.getDocument().body.appendChild(div); var style = div.style; var computed = window.getComputedStyle ? getComputedStyle(element) : element.currentStyle; style.whiteSpace = 'pre-wrap'; if (element.nodeName !== 'INPUT') { style.wordWrap = 'break-word'; } style.position = 'absolute'; style.visibility = 'hidden'; // transfer the element's properties to the div properties.forEach(function (prop) { style[prop] = computed[prop]; }); //NOT SURE WHY THIS IS HERE AND IT DOESNT SEEM HELPFUL // if (isFirefox) { // style.width = `${(parseInt(computed.width) - 2)}px` // if (element.scrollHeight > parseInt(computed.height)) // style.overflowY = 'scroll' // } else { // style.overflow = 'hidden' // } var span0 = document.createElement('span'); span0.textContent = element.value.substring(0, position); div.appendChild(span0); if (element.nodeName === 'INPUT') { div.textContent = div.textContent.replace(/\s/g, ''); } //Create a span in the div that represents where the cursor //should be var span = this.getDocument().createElement('span'); //we give it no content as this represents the cursor span.textContent = '&#x200B;'; div.appendChild(span); var span2 = this.getDocument().createElement('span'); span2.textContent = element.value.substring(position); div.appendChild(span2); var rect = element.getBoundingClientRect(); //position the div exactly over the element //so we can get the bounding client rect for the span and //it should represent exactly where the cursor is div.style.position = 'fixed'; div.style.left = rect.left + 'px'; div.style.top = rect.top + 'px'; div.style.width = rect.width + 'px'; div.style.height = rect.height + 'px'; div.scrollTop = element.scrollTop; var spanRect = span.getBoundingClientRect(); this.getDocument().body.removeChild(div); return this.getFixedCoordinatesRelativeToRect(spanRect); } }, { key: "getContentEditableCaretPosition", value: function getContentEditableCaretPosition(selectedNodePosition) { var range; var sel = this.getWindowSelection(); range = this.getDocument().createRange(); range.setStart(sel.anchorNode, selectedNodePosition); range.setEnd(sel.anchorNode, selectedNodePosition); range.collapse(false); var rect = range.getBoundingClientRect(); return this.getFixedCoordinatesRelativeToRect(rect); } }, { key: "getFixedCoordinatesRelativeToRect", value: function getFixedCoordinatesRelativeToRect(rect) { var coordinates = { position: 'fixed', left: rect.left, top: rect.top + rect.height }; var menuDimensions = this.getMenuDimensions(); var availableSpaceOnTop = rect.top; var availableSpaceOnBottom = window.innerHeight - (rect.top + rect.height); //check to see where's the right place to put the menu vertically if (availableSpaceOnBottom < menuDimensions.height) { if (availableSpaceOnTop >= menuDimensions.height || availableSpaceOnTop > availableSpaceOnBottom) { coordinates.top = 'auto'; coordinates.bottom = window.innerHeight - rect.top; if (availableSpaceOnBottom < menuDimensions.height) { coordinates.maxHeight = availableSpaceOnTop; } } else { if (availableSpaceOnTop < menuDimensions.height) { coordinates.maxHeight = availableSpaceOnBottom; } } } var availableSpaceOnLeft = rect.left; var availableSpaceOnRight = window.innerWidth - rect.left; //check to see where's the right place to put the menu horizontally if (availableSpaceOnRight < menuDimensions.width) { if (availableSpaceOnLeft >= menuDimensions.width || availableSpaceOnLeft > availableSpaceOnRight) { coordinates.left = 'auto'; coordinates.right = window.innerWidth - rect.left; if (availableSpaceOnRight < menuDimensions.width) { coordinates.maxWidth = availableSpaceOnLeft; } } else { if (availableSpaceOnLeft < menuDimensions.width) { coordinates.maxWidth = availableSpaceOnRight; } } } return coordinates; } }, { key: "scrollIntoView", value: function scrollIntoView(elem) { var reasonableBuffer = 20, clientRect; var maxScrollDisplacement = 100; var e = this.menu; if (typeof e === 'undefined') return; while (clientRect === undefined || clientRect.height === 0) { clientRect = e.getBoundingClientRect(); if (clientRect.height === 0) { e = e.childNodes[0]; if (e === undefined || !e.getBoundingClientRect) { return; } } } var elemTop = clientRect.top; var elemBottom = elemTop + clientRect.height; if (elemTop < 0) { window.scrollTo(0, window.pageYOffset + clientRect.top - reasonableBuffer); } else if (elemBottom > window.innerHeight) { var maxY = window.pageYOffset + clientRect.top - reasonableBuffer; if (maxY - window.pageYOffset > maxScrollDisplacement) { maxY = window.pageYOffset + maxScrollDisplacement; } var targetY = window.pageYOffset - (window.innerHeight - elemBottom); if (targetY > maxY) { targetY = maxY; } window.scrollTo(0, targetY); } } }, { key: "menuContainerIsBody", get: function get() { return this.tribute.menuContainer === document.body || !this.tribute.menuContainer; } }]); return TributeRange; }(); // Thanks to path_to_url var TributeSearch = /*#__PURE__*/function () { function TributeSearch(tribute) { _classCallCheck(this, TributeSearch); this.tribute = tribute; this.tribute.search = this; } _createClass(TributeSearch, [{ key: "simpleFilter", value: function simpleFilter(pattern, array) { var _this = this; return array.filter(function (string) { return _this.test(pattern, string); }); } }, { key: "test", value: function test(pattern, string) { return this.match(pattern, string) !== null; } }, { key: "match", value: function match(pattern, string, opts) { opts = opts || {}; var len = string.length, pre = opts.pre || '', post = opts.post || '', compareString = opts.caseSensitive && string || string.toLowerCase(); if (opts.skip) { return { rendered: string, score: 0 }; } pattern = opts.caseSensitive && pattern || pattern.toLowerCase(); var patternCache = this.traverse(compareString, pattern, 0, 0, []); if (!patternCache) { return null; } return { rendered: this.render(string, patternCache.cache, pre, post), score: patternCache.score }; } }, { key: "traverse", value: function traverse(string, pattern, stringIndex, patternIndex, patternCache) { if (this.tribute.autocompleteSeparator) { // if the pattern search at end pattern = pattern.split(this.tribute.autocompleteSeparator).splice(-1)[0]; } if (pattern.length === patternIndex) { // calculate score and copy the cache containing the indices where it's found return { score: this.calculateScore(patternCache), cache: patternCache.slice() }; } // if string at end or remaining pattern > remaining string if (string.length === stringIndex || pattern.length - patternIndex > string.length - stringIndex) { return undefined; } var c = pattern[patternIndex]; var index = string.indexOf(c, stringIndex); var best, temp; while (index > -1) { patternCache.push(index); temp = this.traverse(string, pattern, index + 1, patternIndex + 1, patternCache); patternCache.pop(); // if downstream traversal failed, return best answer so far if (!temp) { return best; } if (!best || best.score < temp.score) { best = temp; } index = string.indexOf(c, index + 1); } return best; } }, { key: "calculateScore", value: function calculateScore(patternCache) { var score = 0; var temp = 1; patternCache.forEach(function (index, i) { if (i > 0) { if (patternCache[i - 1] + 1 === index) { temp += temp + 1; } else { temp = 1; } } score += temp; }); return score; } }, { key: "render", value: function render(string, indices, pre, post) { var rendered = string.substring(0, indices[0]); indices.forEach(function (index, i) { rendered += pre + string[index] + post + string.substring(index + 1, indices[i + 1] ? indices[i + 1] : string.length); }); return rendered; } }, { key: "filter", value: function filter(pattern, arr, opts) { var _this2 = this; opts = opts || {}; return arr.reduce(function (prev, element, idx, arr) { var str = element; if (opts.extract) { str = opts.extract(element); if (!str) { // take care of undefineds / nulls / etc. str = ''; } } var rendered = _this2.match(pattern, str, opts); if (rendered != null) { prev[prev.length] = { string: rendered.rendered, score: rendered.score, index: idx, original: element }; } return prev; }, []).sort(function (a, b) { var compare = b.score - a.score; if (compare) return compare; return a.index - b.index; }); } }]); return TributeSearch; }(); var Tribute = /*#__PURE__*/function () { function Tribute(_ref) { var _this = this; var _ref$values = _ref.values, values = _ref$values === void 0 ? null : _ref$values, _ref$loadingItemTempl = _ref.loadingItemTemplate, loadingItemTemplate = _ref$loadingItemTempl === void 0 ? null : _ref$loadingItemTempl, _ref$iframe = _ref.iframe, iframe = _ref$iframe === void 0 ? null : _ref$iframe, _ref$selectClass = _ref.selectClass, selectClass = _ref$selectClass === void 0 ? "highlight" : _ref$selectClass, _ref$containerClass = _ref.containerClass, containerClass = _ref$containerClass === void 0 ? "tribute-container" : _ref$containerClass, _ref$itemClass = _ref.itemClass, itemClass = _ref$itemClass === void 0 ? "" : _ref$itemClass, _ref$trigger = _ref.trigger, trigger = _ref$trigger === void 0 ? "@" : _ref$trigger, _ref$autocompleteMode = _ref.autocompleteMode, autocompleteMode = _ref$autocompleteMode === void 0 ? false : _ref$autocompleteMode, _ref$autocompleteSepa = _ref.autocompleteSeparator, autocompleteSeparator = _ref$autocompleteSepa === void 0 ? null : _ref$autocompleteSepa, _ref$selectTemplate = _ref.selectTemplate, selectTemplate = _ref$selectTemplate === void 0 ? null : _ref$selectTemplate, _ref$menuItemTemplate = _ref.menuItemTemplate, menuItemTemplate = _ref$menuItemTemplate === void 0 ? null : _ref$menuItemTemplate, _ref$lookup = _ref.lookup, lookup = _ref$lookup === void 0 ? "key" : _ref$lookup, _ref$fillAttr = _ref.fillAttr, fillAttr = _ref$fillAttr === void 0 ? "value" : _ref$fillAttr, _ref$collection = _ref.collection, collection = _ref$collection === void 0 ? null : _ref$collection, _ref$menuContainer = _ref.menuContainer, menuContainer = _ref$menuContainer === void 0 ? null : _ref$menuContainer, _ref$noMatchTemplate = _ref.noMatchTemplate, noMatchTemplate = _ref$noMatchTemplate === void 0 ? null : _ref$noMatchTemplate, _ref$requireLeadingSp = _ref.requireLeadingSpace, requireLeadingSpace = _ref$requireLeadingSp === void 0 ? true : _ref$requireLeadingSp, _ref$allowSpaces = _ref.allowSpaces, allowSpaces = _ref$allowSpaces === void 0 ? false : _ref$allowSpaces, _ref$replaceTextSuffi = _ref.replaceTextSuffix, replaceTextSuffix = _ref$replaceTextSuffi === void 0 ? null : _ref$replaceTextSuffi, _ref$positionMenu = _ref.positionMenu, positionMenu = _ref$positionMenu === void 0 ? true : _ref$positionMenu, _ref$spaceSelectsMatc = _ref.spaceSelectsMatch, spaceSelectsMatch = _ref$spaceSelectsMatc === void 0 ? false : _ref$spaceSelectsMatc, _ref$searchOpts = _ref.searchOpts, searchOpts = _ref$searchOpts === void 0 ? {} : _ref$searchOpts, _ref$menuItemLimit = _ref.menuItemLimit, menuItemLimit = _ref$menuItemLimit === void 0 ? null : _ref$menuItemLimit, _ref$menuShowMinLengt = _ref.menuShowMinLength, menuShowMinLength = _ref$menuShowMinLengt === void 0 ? 0 : _ref$menuShowMinLengt; _classCallCheck(this, Tribute); this.autocompleteMode = autocompleteMode; this.autocompleteSeparator = autocompleteSeparator; this.menuSelected = 0; this.current = {}; this.inputEvent = false; this.isActive = false; this.menuContainer = menuContainer; this.allowSpaces = allowSpaces; this.replaceTextSuffix = replaceTextSuffix; this.positionMenu = positionMenu; this.hasTrailingSpace = false; this.spaceSelectsMatch = spaceSelectsMatch; if (this.autocompleteMode) { trigger = ""; allowSpaces = false; } if (values) { this.collection = [{ // symbol that starts the lookup trigger: trigger, // is it wrapped in an iframe iframe: iframe, // class applied to selected item selectClass: selectClass, // class applied to the Container containerClass: containerClass, // class applied to each item itemClass: itemClass, // function called on select that retuns the content to insert selectTemplate: (selectTemplate || Tribute.defaultSelectTemplate).bind(this), // function called that returns content for an item menuItemTemplate: (menuItemTemplate || Tribute.defaultMenuItemTemplate).bind(this), // function called when menu is empty, disables hiding of menu. noMatchTemplate: function (t) { if (typeof t === "string") { if (t.trim() === "") return null; return t; } if (typeof t === "function") { return t.bind(_this); } return noMatchTemplate || function () { return "<li>No Match Found!</li>"; }.bind(_this); }(noMatchTemplate), // column to search against in the object lookup: lookup, // column that contains the content to insert by default fillAttr: fillAttr, // array of objects or a function returning an array of objects values: values, // useful for when values is an async function loadingItemTemplate: loadingItemTemplate, requireLeadingSpace: requireLeadingSpace, searchOpts: searchOpts, menuItemLimit: menuItemLimit, menuShowMinLength: menuShowMinLength }]; } else if (collection) { if (this.autocompleteMode) console.warn("Tribute in autocomplete mode does not work for collections"); this.collection = collection.map(function (item) { return { trigger: item.trigger || trigger, iframe: item.iframe || iframe, selectClass: item.selectClass || selectClass, containerClass: item.containerClass || containerClass, itemClass: item.itemClass || itemClass, selectTemplate: (item.selectTemplate || Tribute.defaultSelectTemplate).bind(_this), menuItemTemplate: (item.menuItemTemplate || Tribute.defaultMenuItemTemplate).bind(_this), // function called when menu is empty, disables hiding of menu. noMatchTemplate: function (t) { if (typeof t === "string") { if (t.trim() === "") return null; return t; } if (typeof t === "function") { return t.bind(_this); } return noMatchTemplate || function () { return "<li>No Match Found!</li>"; }.bind(_this); }(noMatchTemplate), lookup: item.lookup || lookup, fillAttr: item.fillAttr || fillAttr, values: item.values, loadingItemTemplate: item.loadingItemTemplate, requireLeadingSpace: item.requireLeadingSpace, searchOpts: item.searchOpts || searchOpts, menuItemLimit: item.menuItemLimit || menuItemLimit, menuShowMinLength: item.menuShowMinLength || menuShowMinLength }; }); } else { throw new Error("[Tribute] No collection specified."); } new TributeRange(this); new TributeEvents(this); new TributeMenuEvents(this); new TributeSearch(this); } _createClass(Tribute, [{ key: "triggers", value: function triggers() { return this.collection.map(function (config) { return config.trigger; }); } }, { key: "attach", value: function attach(el) { if (!el) { throw new Error("[Tribute] Must pass in a DOM node or NodeList."); } // Check if it is a jQuery collection if (typeof jQuery !== "undefined" && el instanceof jQuery) { el = el.get(); } // Is el an Array/Array-like object? if (el.constructor === NodeList || el.constructor === HTMLCollection || el.constructor === Array) { var length = el.length; for (var i = 0; i < length; ++i) { this._attach(el[i]); } } else { this._attach(el); } } }, { key: "_attach", value: function _attach(el) { if (el.hasAttribute("data-tribute")) { console.warn("Tribute was already bound to " + el.nodeName); } this.ensureEditable(el); this.events.bind(el); el.setAttribute("data-tribute", true); } }, { key: "ensureEditable", value: function ensureEditable(element) { if (Tribute.inputTypes().indexOf(element.nodeName) === -1) { if (element.contentEditable) { element.contentEditable = true; } else { throw new Error("[Tribute] Cannot bind to " + element.nodeName); } } } }, { key: "createMenu", value: function createMenu(containerClass) { var wrapper = this.range.getDocument().createElement("div"), ul = this.range.getDocument().createElement("ul"); wrapper.className = containerClass; wrapper.appendChild(ul); if (this.menuContainer) { return this.menuContainer.appendChild(wrapper); } return this.range.getDocument().body.appendChild(wrapper); } }, { key: "showMenuFor", value: function showMenuFor(element, scrollTo) { var _this2 = this; // Only proceed if menu isn't already shown for the current element & mentionText if (this.isActive && this.current.element === element && this.current.mentionText === this.currentMentionTextSnapshot) { return; } this.currentMentionTextSnapshot = this.current.mentionText; // create the menu if it doesn't exist. if (!this.menu) { this.menu = this.createMenu(this.current.collection.containerClass); element.tributeMenu = this.menu; this.menuEvents.bind(this.menu); } this.isActive = true; this.menuSelected = 0; if (!this.current.mentionText) { this.current.mentionText = ""; } var processValues = function processValues(values) { // Tribute may not be active any more by the time the value callback returns if (!_this2.isActive) { return; } var items = _this2.search.filter(_this2.current.mentionText, values, { pre: _this2.current.collection.searchOpts.pre || "<span>", post: _this2.current.collection.searchOpts.post || "</span>", skip: _this2.current.collection.searchOpts.skip, extract: function extract(el) { if (typeof _this2.current.collection.lookup === "string") { return el[_this2.current.collection.lookup]; } else if (typeof _this2.current.collection.lookup === "function") { return _this2.current.collection.lookup(el, _this2.current.mentionText); } else { throw new Error("Invalid lookup attribute, lookup must be string or function."); } } }); if (_this2.current.collection.menuItemLimit) { items = items.slice(0, _this2.current.collection.menuItemLimit); } _this2.current.filteredItems = items; var ul = _this2.menu.querySelector("ul"); if (!items.length) { var noMatchEvent = new CustomEvent("tribute-no-match", { detail: _this2.menu }); _this2.current.element.dispatchEvent(noMatchEvent); if (typeof _this2.current.collection.noMatchTemplate === "function" && !_this2.current.collection.noMatchTemplate() || !_this2.current.collection.noMatchTemplate) { _this2.hideMenu(); } else { typeof _this2.current.collection.noMatchTemplate === "function" ? ul.innerHTML = _this2.current.collection.noMatchTemplate() : ul.innerHTML = _this2.current.collection.noMatchTemplate; _this2.range.positionMenuAtCaret(scrollTo); } return; } ul.innerHTML = ""; var fragment = _this2.range.getDocument().createDocumentFragment(); items.forEach(function (item, index) { var li = _this2.range.getDocument().createElement("li"); li.setAttribute("data-index", index); li.className = _this2.current.collection.itemClass; li.addEventListener("mousemove", function (e) { var _this2$_findLiTarget = _this2._findLiTarget(e.target), _this2$_findLiTarget2 = _slicedToArray(_this2$_findLiTarget, 2), li = _this2$_findLiTarget2[0], index = _this2$_findLiTarget2[1]; if (e.movementY !== 0) { _this2.events.setActiveLi(index); } }); if (_this2.menuSelected === index) { li.classList.add(_this2.current.collection.selectClass); } li.innerHTML = _this2.current.collection.menuItemTemplate(item); fragment.appendChild(li); }); ul.appendChild(fragment); _this2.range.positionMenuAtCaret(scrollTo); }; if (typeof this.current.collection.values === "function") { if (this.current.collection.loadingItemTemplate) { this.menu.querySelector("ul").innerHTML = this.current.collection.loadingItemTemplate; this.range.positionMenuAtCaret(scrollTo); } this.current.collection.values(this.current.mentionText, processValues); } else { processValues(this.current.collection.values); } } }, { key: "_findLiTarget", value: function _findLiTarget(el) { if (!el) return []; var index = el.getAttribute("data-index"); return !index ? this._findLiTarget(el.parentNode) : [el, index]; } }, { key: "showMenuForCollection", value: function showMenuForCollection(element, collectionIndex) { if (element !== document.activeElement) { this.placeCaretAtEnd(element); } this.current.collection = this.collection[collectionIndex || 0]; this.current.externalTrigger = true; this.current.element = element; if (element.isContentEditable) this.insertTextAtCursor(this.current.collection.trigger);else this.insertAtCaret(element, this.current.collection.trigger); this.showMenuFor(element); } // TODO: make sure this works for inputs/textareas }, { key: "placeCaretAtEnd", value: function placeCaretAtEnd(el) { el.focus(); if (typeof window.getSelection != "undefined" && typeof document.createRange != "undefined") { var range = document.createRange(); range.selectNodeContents(el); range.collapse(false); var sel = window.getSelection(); sel.removeAllRanges(); sel.addRange(range); } else if (typeof document.body.createTextRange != "undefined") { var textRange = document.body.createTextRange(); textRange.moveToElementText(el); textRange.collapse(false); textRange.select(); } } // for contenteditable }, { key: "insertTextAtCursor", value: function insertTextAtCursor(text) { var sel, range; sel = window.getSelection(); range = sel.getRangeAt(0); range.deleteContents(); var textNode = document.createTextNode(text); range.insertNode(textNode); range.selectNodeContents(textNode); range.collapse(false); sel.removeAllRanges(); sel.addRange(range); } // for regular inputs }, { key: "insertAtCaret", value: function insertAtCaret(textarea, text) { var scrollPos = textarea.scrollTop; var caretPos = textarea.selectionStart; var front = textarea.value.substring(0, caretPos); var back = textarea.value.substring(textarea.selectionEnd, textarea.value.length); textarea.value = front + text + back; caretPos = caretPos + text.length; textarea.selectionStart = caretPos; textarea.selectionEnd = caretPos; textarea.focus(); textarea.scrollTop = scrollPos; } }, { key: "hideMenu", value: function hideMenu() { if (this.menu) { this.menu.style.cssText = "display: none;"; this.isActive = false; this.menuSelected = 0; this.current = {}; } } }, { key: "selectItemAtIndex", value: function selectItemAtIndex(index, originalEvent) { index = parseInt(index); if (typeof index !== "number" || isNaN(index)) return; var item = this.current.filteredItems[index]; var content = this.current.collection.selectTemplate(item); if (content !== null) this.replaceText(content, originalEvent, item); } }, { key: "replaceText", value: function replaceText(content, originalEvent, item) { this.range.replaceTriggerText(content, true, true, originalEvent, item); } }, { key: "_append", value: function _append(collection, newValues, replace) { if (typeof collection.values === "function") { throw new Error("Unable to append to values, as it is a function."); } else if (!replace) { collection.values = collection.values.concat(newValues); } else { collection.values = newValues; } } }, { key: "append", value: function append(collectionIndex, newValues, replace) { var index = parseInt(collectionIndex); if (typeof index !== "number") throw new Error("please provide an index for the collection to update."); var collection = this.collection[index]; this._append(collection, newValues, replace); } }, { key: "appendCurrent", value: function appendCurrent(newValues, replace) { if (this.isActive) { this._append(this.current.collection, newValues, replace); } else { throw new Error("No active state. Please use append instead and pass an index."); } } }, { key: "detach", value: function detach(el) { if (!el) { throw new Error("[Tribute] Must pass in a DOM node or NodeList."); } // Check if it is a jQuery collection if (typeof jQuery !== "undefined" && el instanceof jQuery) { el = el.get(); } // Is el an Array/Array-like object? if (el.constructor === NodeList || el.constructor === HTMLCollection || el.constructor === Array) { var length = el.length; for (var i = 0; i < length; ++i) { this._detach(el[i]); } } else { this._detach(el); } } }, { key: "_detach", value: function _detach(el) { var _this3 = this; this.events.unbind(el); if (el.tributeMenu) { this.menuEvents.unbind(el.tributeMenu); } setTimeout(function () { el.removeAttribute("data-tribute"); _this3.isActive = false; if (el.tributeMenu) { el.tributeMenu.remove(); } }); } }, { key: "isActive", get: function get() { return this._isActive; }, set: function set(val) { if (this._isActive != val) { this._isActive = val; if (this.current.element) { var noMatchEvent = new CustomEvent("tribute-active-".concat(val)); this.current.element.dispatchEvent(noMatchEvent); } } } }], [{ key: "defaultSelectTemplate", value: function defaultSelectTemplate(item) { if (typeof item === "undefined") return "".concat(this.current.collection.trigger).concat(this.current.mentionText); if (this.range.isContentEditable(this.current.element)) { return '<span class="tribute-mention">' + (this.current.collection.trigger + item.original[this.current.collection.fillAttr]) + "</span>"; } return this.current.collection.trigger + item.original[this.current.collection.fillAttr]; } }, { key: "defaultMenuItemTemplate", value: function defaultMenuItemTemplate(matchItem) { return matchItem.string; } }, { key: "inputTypes", value: function inputTypes() { return ["TEXTAREA", "INPUT"]; } }]); return Tribute; }(); /** * Tribute.js * Native ES6 JavaScript @mention Plugin **/ return Tribute; }))); ```
/content/code_sandbox/dist/tribute.js
javascript
2016-01-19T00:54:39
2024-08-14T11:30:58
tribute
zurb/tribute
2,017
14,008
```unknown {"version":3,"file":"tribute.min.js","sources":["../src/utils.js","../src/TributeEvents.js","../src/TributeMenuEvents.js","../src/TributeRange.js","../src/TributeSearch.js","../src/Tribute.js"],"sourcesContent":["if (!Array.prototype.find) {\n Array.prototype.find = function(predicate) {\n if (this === null) {\n throw new TypeError('Array.prototype.find called on null or undefined')\n }\n if (typeof predicate !== 'function') {\n throw new TypeError('predicate must be a function')\n }\n var list = Object(this)\n var length = list.length >>> 0\n var thisArg = arguments[1]\n var value\n\n for (var i = 0; i < length; i++) {\n value = list[i]\n if (predicate.call(thisArg, value, i, list)) {\n return value\n }\n }\n return undefined\n }\n}\n\nif (window && typeof window.CustomEvent !== \"function\") {\n function CustomEvent(event, params) {\n params = params || {\n bubbles: false,\n cancelable: false,\n detail: undefined\n }\n var evt = document.createEvent('CustomEvent')\n evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail)\n return evt\n }\n\n if (typeof window.Event !== 'undefined') {\n CustomEvent.prototype = window.Event.prototype\n }\n\n window.CustomEvent = CustomEvent\n}","class TributeEvents {\n constructor(tribute) {\n this.tribute = tribute;\n this.tribute.events = this;\n }\n\n static keys() {\n return [\n {\n key: 9,\n value: \"TAB\"\n },\n {\n key: 8,\n value: \"DELETE\"\n },\n {\n key: 13,\n value: \"ENTER\"\n },\n {\n key: 27,\n value: \"ESCAPE\"\n },\n {\n key: 32,\n value: \"SPACE\"\n },\n {\n key: 38,\n value: \"UP\"\n },\n {\n key: 40,\n value: \"DOWN\"\n }\n ];\n }\n\n bind(element) {\n element.boundKeydown = this.keydown.bind(element, this);\n element.boundKeyup = this.keyup.bind(element, this);\n element.boundInput = this.input.bind(element, this);\n\n element.addEventListener(\"keydown\", element.boundKeydown, false);\n element.addEventListener(\"keyup\", element.boundKeyup, false);\n element.addEventListener(\"input\", element.boundInput, false);\n }\n\n unbind(element) {\n element.removeEventListener(\"keydown\", element.boundKeydown, false);\n element.removeEventListener(\"keyup\", element.boundKeyup, false);\n element.removeEventListener(\"input\", element.boundInput, false);\n\n delete element.boundKeydown;\n delete element.boundKeyup;\n delete element.boundInput;\n }\n\n keydown(instance, event) {\n if (instance.shouldDeactivate(event)) {\n instance.tribute.isActive = false;\n instance.tribute.hideMenu();\n }\n\n let element = this;\n instance.commandEvent = false;\n\n TributeEvents.keys().forEach(o => {\n if (o.key === event.keyCode) {\n instance.commandEvent = true;\n instance.callbacks()[o.value.toLowerCase()](event, element);\n }\n });\n }\n\n input(instance, event) {\n instance.inputEvent = true;\n instance.keyup.call(this, instance, event);\n }\n\n click(instance, event) {\n let tribute = instance.tribute;\n if (tribute.menu && tribute.menu.contains(event.target)) {\n let li = event.target;\n event.preventDefault();\n event.stopPropagation();\n while (li.nodeName.toLowerCase() !== \"li\") {\n li = li.parentNode;\n if (!li || li === tribute.menu) {\n throw new Error(\"cannot find the <li> container for the click\");\n }\n }\n tribute.selectItemAtIndex(li.getAttribute(\"data-index\"), event);\n tribute.hideMenu();\n\n // TODO: should fire with externalTrigger and target is outside of menu\n } else if (tribute.current.element && !tribute.current.externalTrigger) {\n tribute.current.externalTrigger = false;\n setTimeout(() => tribute.hideMenu());\n }\n }\n\n keyup(instance, event) {\n if (instance.inputEvent) {\n instance.inputEvent = false;\n }\n instance.updateSelection(this);\n\n if (event.keyCode === 27) return;\n\n if (!instance.tribute.allowSpaces && instance.tribute.hasTrailingSpace) {\n instance.tribute.hasTrailingSpace = false;\n instance.commandEvent = true;\n instance.callbacks()[\"space\"](event, this);\n return;\n }\n\n if (!instance.tribute.isActive) {\n if (instance.tribute.autocompleteMode) {\n instance.callbacks().triggerChar(event, this, \"\");\n } else {\n let keyCode = instance.getKeyCode(instance, this, event);\n\n if (isNaN(keyCode) || !keyCode) return;\n\n let trigger = instance.tribute.triggers().find(trigger => {\n return trigger.charCodeAt(0) === keyCode;\n });\n\n if (typeof trigger !== \"undefined\") {\n instance.callbacks().triggerChar(event, this, trigger);\n }\n }\n }\n\n if (\n instance.tribute.current.mentionText.length <\n instance.tribute.current.collection.menuShowMinLength\n ) {\n return;\n }\n\n if (\n ((instance.tribute.current.trigger ||\n instance.tribute.autocompleteMode) &&\n instance.commandEvent === false) ||\n (instance.tribute.isActive && event.keyCode === 8)\n ) {\n instance.tribute.showMenuFor(this, true);\n }\n }\n\n shouldDeactivate(event) {\n if (!this.tribute.isActive) return false;\n\n if (this.tribute.current.mentionText.length === 0) {\n let eventKeyPressed = false;\n TributeEvents.keys().forEach(o => {\n if (event.keyCode === o.key) eventKeyPressed = true;\n });\n\n return !eventKeyPressed;\n }\n\n return false;\n }\n\n getKeyCode(instance, el, event) {\n let char;\n let tribute = instance.tribute;\n let info = tribute.range.getTriggerInfo(\n false,\n tribute.hasTrailingSpace,\n true,\n tribute.allowSpaces,\n tribute.autocompleteMode\n );\n\n if (info) {\n return info.mentionTriggerChar.charCodeAt(0);\n } else {\n return false;\n }\n }\n\n updateSelection(el) {\n this.tribute.current.element = el;\n let info = this.tribute.range.getTriggerInfo(\n false,\n this.tribute.hasTrailingSpace,\n true,\n this.tribute.allowSpaces,\n this.tribute.autocompleteMode\n );\n\n if (info) {\n this.tribute.current.selectedPath = info.mentionSelectedPath;\n this.tribute.current.mentionText = info.mentionText;\n this.tribute.current.selectedOffset = info.mentionSelectedOffset;\n }\n }\n\n callbacks() {\n return {\n triggerChar: (e, el, trigger) => {\n let tribute = this.tribute;\n tribute.current.trigger = trigger;\n\n let collectionItem = tribute.collection.find(item => {\n return item.trigger === trigger;\n });\n\n tribute.current.collection = collectionItem;\n\n if (\n tribute.current.mentionText.length >=\n tribute.current.collection.menuShowMinLength &&\n tribute.inputEvent\n ) {\n tribute.showMenuFor(el, true);\n }\n },\n enter: (e, el) => {\n // choose selection\n if (this.tribute.isActive && this.tribute.current.filteredItems) {\n e.preventDefault();\n e.stopPropagation();\n setTimeout(() => {\n this.tribute.selectItemAtIndex(this.tribute.menuSelected, e);\n this.tribute.hideMenu();\n }, 0);\n }\n },\n escape: (e, el) => {\n if (this.tribute.isActive) {\n e.preventDefault();\n e.stopPropagation();\n this.tribute.isActive = false;\n this.tribute.hideMenu();\n }\n },\n tab: (e, el) => {\n // choose first match\n this.callbacks().enter(e, el);\n },\n space: (e, el) => {\n if (this.tribute.isActive) {\n if (this.tribute.spaceSelectsMatch) {\n this.callbacks().enter(e, el);\n } else if (!this.tribute.allowSpaces) {\n e.stopPropagation();\n setTimeout(() => {\n this.tribute.hideMenu();\n this.tribute.isActive = false;\n }, 0);\n }\n }\n },\n up: (e, el) => {\n // navigate up ul\n if (this.tribute.isActive && this.tribute.current.filteredItems) {\n e.preventDefault();\n e.stopPropagation();\n let count = this.tribute.current.filteredItems.length,\n selected = this.tribute.menuSelected;\n\n if (count > selected && selected > 0) {\n this.tribute.menuSelected--;\n this.setActiveLi();\n } else if (selected === 0) {\n this.tribute.menuSelected = count - 1;\n this.setActiveLi();\n this.tribute.menu.scrollTop = this.tribute.menu.scrollHeight;\n }\n }\n },\n down: (e, el) => {\n // navigate down ul\n if (this.tribute.isActive && this.tribute.current.filteredItems) {\n e.preventDefault();\n e.stopPropagation();\n let count = this.tribute.current.filteredItems.length - 1,\n selected = this.tribute.menuSelected;\n\n if (count > selected) {\n this.tribute.menuSelected++;\n this.setActiveLi();\n } else if (count === selected) {\n this.tribute.menuSelected = 0;\n this.setActiveLi();\n this.tribute.menu.scrollTop = 0;\n }\n }\n },\n delete: (e, el) => {\n if (\n this.tribute.isActive &&\n this.tribute.current.mentionText.length < 1\n ) {\n this.tribute.hideMenu();\n } else if (this.tribute.isActive) {\n this.tribute.showMenuFor(el);\n }\n }\n };\n }\n\n setActiveLi(index) {\n let lis = this.tribute.menu.querySelectorAll(\"li\"),\n length = lis.length >>> 0;\n\n if (index) this.tribute.menuSelected = parseInt(index);\n\n for (let i = 0; i < length; i++) {\n let li = lis[i];\n if (i === this.tribute.menuSelected) {\n li.classList.add(this.tribute.current.collection.selectClass);\n\n let liClientRect = li.getBoundingClientRect();\n let menuClientRect = this.tribute.menu.getBoundingClientRect();\n\n if (liClientRect.bottom > menuClientRect.bottom) {\n let scrollDistance = liClientRect.bottom - menuClientRect.bottom;\n this.tribute.menu.scrollTop += scrollDistance;\n } else if (liClientRect.top < menuClientRect.top) {\n let scrollDistance = menuClientRect.top - liClientRect.top;\n this.tribute.menu.scrollTop -= scrollDistance;\n }\n } else {\n li.classList.remove(this.tribute.current.collection.selectClass);\n }\n }\n }\n\n getFullHeight(elem, includeMargin) {\n let height = elem.getBoundingClientRect().height;\n\n if (includeMargin) {\n let style = elem.currentStyle || window.getComputedStyle(elem);\n return (\n height + parseFloat(style.marginTop) + parseFloat(style.marginBottom)\n );\n }\n\n return height;\n }\n}\n\nexport default TributeEvents;\n","class TributeMenuEvents {\n constructor(tribute) {\n this.tribute = tribute;\n this.tribute.menuEvents = this;\n this.menu = this.tribute.menu;\n }\n\n bind(menu) {\n this.menuClickEvent = this.tribute.events.click.bind(null, this);\n this.menuContainerScrollEvent = this.debounce(\n () => {\n if (this.tribute.isActive) {\n this.tribute.hideMenu();\n }\n },\n 10,\n false\n );\n this.windowResizeEvent = this.debounce(\n () => {\n if (this.tribute.isActive) {\n this.tribute.hideMenu();\n }\n },\n 10,\n false\n );\n\n // fixes IE11 issues with mousedown\n this.tribute.range\n .getDocument()\n .addEventListener(\"MSPointerDown\", this.menuClickEvent, false);\n this.tribute.range\n .getDocument()\n .addEventListener(\"mousedown\", this.menuClickEvent, false);\n window.addEventListener(\"resize\", this.windowResizeEvent);\n\n if (this.menuContainer) {\n this.menuContainer.addEventListener(\n \"scroll\",\n this.menuContainerScrollEvent,\n false\n );\n } else {\n window.addEventListener(\"scroll\", this.menuContainerScrollEvent);\n }\n }\n\n unbind(menu) {\n this.tribute.range\n .getDocument()\n .removeEventListener(\"mousedown\", this.menuClickEvent, false);\n this.tribute.range\n .getDocument()\n .removeEventListener(\"MSPointerDown\", this.menuClickEvent, false);\n window.removeEventListener(\"resize\", this.windowResizeEvent);\n\n if (this.menuContainer) {\n this.menuContainer.removeEventListener(\n \"scroll\",\n this.menuContainerScrollEvent,\n false\n );\n } else {\n window.removeEventListener(\"scroll\", this.menuContainerScrollEvent);\n }\n }\n\n debounce(func, wait, immediate) {\n var timeout;\n return () => {\n var context = this,\n args = arguments;\n var later = () => {\n timeout = null;\n if (!immediate) func.apply(context, args);\n };\n var callNow = immediate && !timeout;\n clearTimeout(timeout);\n timeout = setTimeout(later, wait);\n if (callNow) func.apply(context, args);\n };\n }\n}\n\nexport default TributeMenuEvents;\n","// Thanks to path_to_url \"./utils\";\n\nclass TributeRange {\n constructor(tribute) {\n this.tribute = tribute\n this.tribute.range = this\n }\n\n getDocument() {\n let iframe\n if (this.tribute.current.collection) {\n iframe = this.tribute.current.collection.iframe\n }\n\n if (!iframe) {\n return document\n }\n\n return iframe.contentWindow.document\n }\n\n positionMenuAtCaret(scrollTo) {\n let context = this.tribute.current,\n coordinates\n\n let info = this.getTriggerInfo(false, this.tribute.hasTrailingSpace, true, this.tribute.allowSpaces, this.tribute.autocompleteMode)\n\n if (typeof info !== 'undefined') {\n\n if(!this.tribute.positionMenu){\n this.tribute.menu.style.cssText = `display: block;`\n return\n }\n\n if (!this.isContentEditable(context.element)) {\n coordinates = this.getTextAreaOrInputUnderlinePosition(this.tribute.current.element,\n info.mentionPosition)\n }\n else {\n coordinates = this.getContentEditableCaretPosition(info.mentionPosition)\n }\n\n this.tribute.menu.style.cssText = `top: ${coordinates.top}px;\n left: ${coordinates.left}px;\n right: ${coordinates.right}px;\n bottom: ${coordinates.bottom}px;\n max-height: ${coordinates.maxHeight || 500}px;\n max-width: ${coordinates.maxWidth || 300}px;\n position: ${coordinates.position || 'absolute'};\n display: block;`\n\n if (coordinates.left === 'auto') {\n this.tribute.menu.style.left = 'auto'\n }\n\n if (coordinates.top === 'auto') {\n this.tribute.menu.style.top = 'auto'\n }\n\n if (scrollTo) this.scrollIntoView()\n\n } else {\n this.tribute.menu.style.cssText = 'display: none'\n }\n }\n\n get menuContainerIsBody() {\n return this.tribute.menuContainer === document.body || !this.tribute.menuContainer;\n }\n\n\n selectElement(targetElement, path, offset) {\n let range\n let elem = targetElement\n\n if (path) {\n for (var i = 0; i < path.length; i++) {\n elem = elem.childNodes[path[i]]\n if (elem === undefined) {\n return\n }\n while (elem.length < offset) {\n offset -= elem.length\n elem = elem.nextSibling\n }\n if (elem.childNodes.length === 0 && !elem.length) {\n elem = elem.previousSibling\n }\n }\n }\n let sel = this.getWindowSelection()\n\n range = this.getDocument().createRange()\n range.setStart(elem, offset)\n range.setEnd(elem, offset)\n range.collapse(true)\n\n try {\n sel.removeAllRanges()\n } catch (error) {}\n\n sel.addRange(range)\n targetElement.focus()\n }\n\n replaceTriggerText(text, requireLeadingSpace, hasTrailingSpace, originalEvent, item) {\n let info = this.getTriggerInfo(true, hasTrailingSpace, requireLeadingSpace, this.tribute.allowSpaces, this.tribute.autocompleteMode)\n\n if (info !== undefined) {\n let context = this.tribute.current\n let replaceEvent = new CustomEvent('tribute-replaced', {\n detail: {\n item: item,\n instance: context,\n context: info,\n event: originalEvent,\n }\n })\n\n if (!this.isContentEditable(context.element)) {\n let myField = this.tribute.current.element\n let textSuffix = typeof this.tribute.replaceTextSuffix == 'string'\n ? this.tribute.replaceTextSuffix\n : ' '\n text += textSuffix\n let startPos = info.mentionPosition\n let endPos = info.mentionPosition + info.mentionText.length + textSuffix.length\n if (!this.tribute.autocompleteMode) {\n endPos += info.mentionTriggerChar.length - 1\n }\n myField.value = myField.value.substring(0, startPos) + text +\n myField.value.substring(endPos, myField.value.length)\n myField.selectionStart = startPos + text.length\n myField.selectionEnd = startPos + text.length\n } else {\n // add a space to the end of the pasted text\n let textSuffix = typeof this.tribute.replaceTextSuffix == 'string'\n ? this.tribute.replaceTextSuffix\n : '\\xA0'\n text += textSuffix\n let endPos = info.mentionPosition + info.mentionText.length\n if (!this.tribute.autocompleteMode) {\n endPos += info.mentionTriggerChar.length\n }\n this.pasteHtml(text, info.mentionPosition, endPos)\n }\n\n context.element.dispatchEvent(new CustomEvent('input', { bubbles: true }))\n context.element.dispatchEvent(replaceEvent)\n }\n }\n\n pasteHtml(html, startPos, endPos) {\n let range, sel\n sel = this.getWindowSelection()\n range = this.getDocument().createRange()\n range.setStart(sel.anchorNode, startPos)\n range.setEnd(sel.anchorNode, endPos)\n range.deleteContents()\n\n let el = this.getDocument().createElement('div')\n el.innerHTML = html\n let frag = this.getDocument().createDocumentFragment(),\n node, lastNode\n while ((node = el.firstChild)) {\n lastNode = frag.appendChild(node)\n }\n range.insertNode(frag)\n\n // Preserve the selection\n if (lastNode) {\n range = range.cloneRange()\n range.setStartAfter(lastNode)\n range.collapse(true)\n sel.removeAllRanges()\n sel.addRange(range)\n }\n }\n\n getWindowSelection() {\n if (this.tribute.collection.iframe) {\n return this.tribute.collection.iframe.contentWindow.getSelection()\n }\n\n return window.getSelection()\n }\n\n getNodePositionInParent(element) {\n if (element.parentNode === null) {\n return 0\n }\n\n for (var i = 0; i < element.parentNode.childNodes.length; i++) {\n let node = element.parentNode.childNodes[i]\n\n if (node === element) {\n return i\n }\n }\n }\n\n getContentEditableSelectedPath(ctx) {\n let sel = this.getWindowSelection()\n let selected = sel.anchorNode\n let path = []\n let offset\n\n if (selected != null) {\n let i\n let ce = selected.contentEditable\n while (selected !== null && ce !== 'true') {\n i = this.getNodePositionInParent(selected)\n path.push(i)\n selected = selected.parentNode\n if (selected !== null) {\n ce = selected.contentEditable\n }\n }\n path.reverse()\n\n // getRangeAt may not exist, need alternative\n offset = sel.getRangeAt(0).startOffset\n\n return {\n selected: selected,\n path: path,\n offset: offset\n }\n }\n }\n\n getTextPrecedingCurrentSelection() {\n let context = this.tribute.current,\n text = ''\n\n if (!this.isContentEditable(context.element)) {\n let textComponent = this.tribute.current.element;\n if (textComponent) {\n let startPos = textComponent.selectionStart\n if (textComponent.value && startPos >= 0) {\n text = textComponent.value.substring(0, startPos)\n }\n }\n\n } else {\n let selectedElem = this.getWindowSelection().anchorNode\n\n if (selectedElem != null) {\n let workingNodeContent = selectedElem.textContent\n let selectStartOffset = this.getWindowSelection().getRangeAt(0).startOffset\n\n if (workingNodeContent && selectStartOffset >= 0) {\n text = workingNodeContent.substring(0, selectStartOffset)\n }\n }\n }\n\n return text\n }\n\n getLastWordInText(text) {\n text = text.replace(/\\u00A0/g, ' '); // path_to_url var wordsArray;\n if (this.tribute.autocompleteSeparator) {\n wordsArray = text.split(this.tribute.autocompleteSeparator);\n } else {\n wordsArray = text.split(/\\s+/);\n }\n var worldsCount = wordsArray.length - 1;\n return wordsArray[worldsCount].trim();\n }\n\n getTriggerInfo(menuAlreadyActive, hasTrailingSpace, requireLeadingSpace, allowSpaces, isAutocomplete) {\n let ctx = this.tribute.current\n let selected, path, offset\n\n if (!this.isContentEditable(ctx.element)) {\n selected = this.tribute.current.element\n } else {\n let selectionInfo = this.getContentEditableSelectedPath(ctx)\n\n if (selectionInfo) {\n selected = selectionInfo.selected\n path = selectionInfo.path\n offset = selectionInfo.offset\n }\n }\n\n let effectiveRange = this.getTextPrecedingCurrentSelection()\n let lastWordOfEffectiveRange = this.getLastWordInText(effectiveRange)\n\n if (isAutocomplete) {\n return {\n mentionPosition: effectiveRange.length - lastWordOfEffectiveRange.length,\n mentionText: lastWordOfEffectiveRange,\n mentionSelectedElement: selected,\n mentionSelectedPath: path,\n mentionSelectedOffset: offset\n }\n }\n\n if (effectiveRange !== undefined && effectiveRange !== null) {\n let mostRecentTriggerCharPos = -1\n let triggerChar\n\n this.tribute.collection.forEach(config => {\n let c = config.trigger\n let idx = config.requireLeadingSpace ?\n this.lastIndexWithLeadingSpace(effectiveRange, c) :\n effectiveRange.lastIndexOf(c)\n\n if (idx > mostRecentTriggerCharPos) {\n mostRecentTriggerCharPos = idx\n triggerChar = c\n requireLeadingSpace = config.requireLeadingSpace\n }\n })\n\n if (mostRecentTriggerCharPos >= 0 &&\n (\n mostRecentTriggerCharPos === 0 ||\n !requireLeadingSpace ||\n /[\\xA0\\s]/g.test(\n effectiveRange.substring(\n mostRecentTriggerCharPos - 1,\n mostRecentTriggerCharPos)\n )\n )\n ) {\n let currentTriggerSnippet = effectiveRange.substring(mostRecentTriggerCharPos + triggerChar.length,\n effectiveRange.length)\n\n triggerChar = effectiveRange.substring(mostRecentTriggerCharPos, mostRecentTriggerCharPos + triggerChar.length)\n let firstSnippetChar = currentTriggerSnippet.substring(0, 1)\n let leadingSpace = currentTriggerSnippet.length > 0 &&\n (\n firstSnippetChar === ' ' ||\n firstSnippetChar === '\\xA0'\n )\n if (hasTrailingSpace) {\n currentTriggerSnippet = currentTriggerSnippet.trim()\n }\n\n let regex = allowSpaces ? /[^\\S ]/g : /[\\xA0\\s]/g;\n\n this.tribute.hasTrailingSpace = regex.test(currentTriggerSnippet);\n\n if (!leadingSpace && (menuAlreadyActive || !(regex.test(currentTriggerSnippet)))) {\n return {\n mentionPosition: mostRecentTriggerCharPos,\n mentionText: currentTriggerSnippet,\n mentionSelectedElement: selected,\n mentionSelectedPath: path,\n mentionSelectedOffset: offset,\n mentionTriggerChar: triggerChar\n }\n }\n }\n }\n }\n\n lastIndexWithLeadingSpace (str, trigger) {\n let reversedStr = str.split('').reverse().join('')\n let index = -1\n\n for (let cidx = 0, len = str.length; cidx < len; cidx++) {\n let firstChar = cidx === str.length - 1\n let leadingSpace = /\\s/.test(reversedStr[cidx + 1])\n\n let match = true\n for (let triggerIdx = trigger.length - 1; triggerIdx >= 0; triggerIdx--) {\n if (trigger[triggerIdx] !== reversedStr[cidx-triggerIdx]) {\n match = false\n break\n }\n }\n\n if (match && (firstChar || leadingSpace)) {\n index = str.length - 1 - cidx\n break\n }\n }\n\n return index\n }\n\n isContentEditable(element) {\n return element.nodeName !== 'INPUT' && element.nodeName !== 'TEXTAREA'\n }\n\n isMenuOffScreen(coordinates, menuDimensions) {\n let windowWidth = window.innerWidth\n let windowHeight = window.innerHeight\n let doc = document.documentElement\n let windowLeft = (window.pageXOffset || doc.scrollLeft) - (doc.clientLeft || 0)\n let windowTop = (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0)\n\n let menuTop = typeof coordinates.top === 'number' ? coordinates.top : windowTop + windowHeight - coordinates.bottom - menuDimensions.height\n let menuRight = typeof coordinates.right === 'number' ? coordinates.right : coordinates.left + menuDimensions.width\n let menuBottom = typeof coordinates.bottom === 'number' ? coordinates.bottom : coordinates.top + menuDimensions.height\n let menuLeft = typeof coordinates.left === 'number' ? coordinates.left : windowLeft + windowWidth - coordinates.right - menuDimensions.width\n\n return {\n top: menuTop < Math.floor(windowTop),\n right: menuRight > Math.ceil(windowLeft + windowWidth),\n bottom: menuBottom > Math.ceil(windowTop + windowHeight),\n left: menuLeft < Math.floor(windowLeft)\n }\n }\n\n getMenuDimensions() {\n // Width of the menu depends of its contents and position\n // We must check what its width would be without any obstruction\n // This way, we can achieve good positioning for flipping the menu\n let dimensions = {\n width: null,\n height: null\n }\n\n this.tribute.menu.style.cssText = `top: 0px;\n left: 0px;\n position: fixed;\n display: block;\n visibility; hidden;\n max-height:500px;`\n dimensions.width = this.tribute.menu.offsetWidth\n dimensions.height = this.tribute.menu.offsetHeight\n\n this.tribute.menu.style.cssText = `display: none;`\n\n return dimensions\n }\n\n getTextAreaOrInputUnderlinePosition(element, position, flipped) {\n let properties = ['direction', 'boxSizing', 'width', 'height', 'overflowX',\n 'overflowY', 'borderTopWidth', 'borderRightWidth',\n 'borderBottomWidth', 'borderLeftWidth', 'borderStyle', 'paddingTop',\n 'paddingRight', 'paddingBottom', 'paddingLeft',\n 'fontStyle', 'fontVariant', 'fontWeight', 'fontStretch',\n 'fontSize', 'fontSizeAdjust', 'lineHeight', 'fontFamily',\n 'textAlign', 'textTransform', 'textIndent',\n 'textDecoration', 'letterSpacing', 'wordSpacing'\n ]\n\n let isFirefox = (window.mozInnerScreenX !== null)\n\n let div = this.getDocument().createElement('div')\n div.id = 'input-textarea-caret-position-mirror-div'\n this.getDocument().body.appendChild(div)\n\n let style = div.style\n let computed = window.getComputedStyle ? getComputedStyle(element) : element.currentStyle\n\n style.whiteSpace = 'pre-wrap'\n if (element.nodeName !== 'INPUT') {\n style.wordWrap = 'break-word'\n }\n\n style.position = 'absolute'\n style.visibility = 'hidden'\n\n // transfer the element's properties to the div\n properties.forEach(prop => {\n style[prop] = computed[prop]\n })\n\n //NOT SURE WHY THIS IS HERE AND IT DOESNT SEEM HELPFUL\n // if (isFirefox) {\n // style.width = `${(parseInt(computed.width) - 2)}px`\n // if (element.scrollHeight > parseInt(computed.height))\n // style.overflowY = 'scroll'\n // } else {\n // style.overflow = 'hidden'\n // }\n\n let span0 = document.createElement('span')\n span0.textContent = element.value.substring(0, position)\n div.appendChild(span0)\n\n if (element.nodeName === 'INPUT') {\n div.textContent = div.textContent.replace(/\\s/g, '')\n }\n\n //Create a span in the div that represents where the cursor\n //should be\n let span = this.getDocument().createElement('span')\n //we give it no content as this represents the cursor\n span.textContent = '&#x200B;'\n div.appendChild(span)\n\n let span2 = this.getDocument().createElement('span');\n span2.textContent = element.value.substring(position);\n div.appendChild(span2);\n\n let rect = element.getBoundingClientRect()\n\n //position the div exactly over the element\n //so we can get the bounding client rect for the span and\n //it should represent exactly where the cursor is\n div.style.position = 'fixed';\n div.style.left = rect.left + 'px';\n div.style.top = rect.top + 'px';\n div.style.width = rect.width + 'px';\n div.style.height = rect.height + 'px';\n div.scrollTop = element.scrollTop;\n\n var spanRect = span.getBoundingClientRect();\n this.getDocument().body.removeChild(div)\n return this.getFixedCoordinatesRelativeToRect(spanRect);\n }\n\n getContentEditableCaretPosition(selectedNodePosition) {\n let range\n let sel = this.getWindowSelection()\n\n range = this.getDocument().createRange()\n range.setStart(sel.anchorNode, selectedNodePosition)\n range.setEnd(sel.anchorNode, selectedNodePosition)\n\n range.collapse(false)\n\n let rect = range.getBoundingClientRect()\n\n return this.getFixedCoordinatesRelativeToRect(rect);\n }\n\n getFixedCoordinatesRelativeToRect(rect) {\n let coordinates = {\n position: 'fixed',\n left: rect.left,\n top: rect.top + rect.height\n }\n\n let menuDimensions = this.getMenuDimensions()\n\n var availableSpaceOnTop = rect.top;\n var availableSpaceOnBottom = window.innerHeight - (rect.top + rect.height);\n\n //check to see where's the right place to put the menu vertically\n if (availableSpaceOnBottom < menuDimensions.height) {\n if (availableSpaceOnTop >= menuDimensions.height || availableSpaceOnTop > availableSpaceOnBottom) {\n coordinates.top = 'auto';\n coordinates.bottom = window.innerHeight - rect.top;\n if (availableSpaceOnBottom < menuDimensions.height) {\n coordinates.maxHeight = availableSpaceOnTop;\n }\n } else {\n if (availableSpaceOnTop < menuDimensions.height) {\n coordinates.maxHeight = availableSpaceOnBottom;\n }\n }\n }\n\n var availableSpaceOnLeft = rect.left;\n var availableSpaceOnRight = window.innerWidth - rect.left;\n\n //check to see where's the right place to put the menu horizontally\n if (availableSpaceOnRight < menuDimensions.width) {\n if (availableSpaceOnLeft >= menuDimensions.width || availableSpaceOnLeft > availableSpaceOnRight) {\n coordinates.left = 'auto';\n coordinates.right = window.innerWidth - rect.left;\n if (availableSpaceOnRight < menuDimensions.width) {\n coordinates.maxWidth = availableSpaceOnLeft;\n }\n } else {\n if (availableSpaceOnLeft < menuDimensions.width) {\n coordinates.maxWidth = availableSpaceOnRight;\n }\n }\n }\n\n return coordinates\n }\n\n scrollIntoView(elem) {\n let reasonableBuffer = 20,\n clientRect\n let maxScrollDisplacement = 100\n let e = this.menu\n\n if (typeof e === 'undefined') return;\n\n while (clientRect === undefined || clientRect.height === 0) {\n clientRect = e.getBoundingClientRect()\n\n if (clientRect.height === 0) {\n e = e.childNodes[0]\n if (e === undefined || !e.getBoundingClientRect) {\n return\n }\n }\n }\n\n let elemTop = clientRect.top\n let elemBottom = elemTop + clientRect.height\n\n if (elemTop < 0) {\n window.scrollTo(0, window.pageYOffset + clientRect.top - reasonableBuffer)\n } else if (elemBottom > window.innerHeight) {\n let maxY = window.pageYOffset + clientRect.top - reasonableBuffer\n\n if (maxY - window.pageYOffset > maxScrollDisplacement) {\n maxY = window.pageYOffset + maxScrollDisplacement\n }\n\n let targetY = window.pageYOffset - (window.innerHeight - elemBottom)\n\n if (targetY > maxY) {\n targetY = maxY\n }\n\n window.scrollTo(0, targetY)\n }\n }\n}\n\n\nexport default TributeRange;\n","// Thanks to path_to_url TributeSearch {\n constructor(tribute) {\n this.tribute = tribute\n this.tribute.search = this\n }\n\n simpleFilter(pattern, array) {\n return array.filter(string => {\n return this.test(pattern, string)\n })\n }\n\n test(pattern, string) {\n return this.match(pattern, string) !== null\n }\n\n match(pattern, string, opts) {\n opts = opts || {}\n let patternIdx = 0,\n result = [],\n len = string.length,\n totalScore = 0,\n currScore = 0,\n pre = opts.pre || '',\n post = opts.post || '',\n compareString = opts.caseSensitive && string || string.toLowerCase(),\n ch, compareChar\n\n if (opts.skip) {\n return {rendered: string, score: 0}\n }\n\n pattern = opts.caseSensitive && pattern || pattern.toLowerCase()\n\n let patternCache = this.traverse(compareString, pattern, 0, 0, [])\n if (!patternCache) {\n return null\n }\n return {\n rendered: this.render(string, patternCache.cache, pre, post),\n score: patternCache.score\n }\n }\n\n traverse(string, pattern, stringIndex, patternIndex, patternCache) {\n if (this.tribute.autocompleteSeparator) {\n // if the pattern search at end\n pattern = pattern.split(this.tribute.autocompleteSeparator).splice(-1)[0];\n }\n\n if (pattern.length === patternIndex) {\n\n // calculate score and copy the cache containing the indices where it's found\n return {\n score: this.calculateScore(patternCache),\n cache: patternCache.slice()\n }\n }\n\n // if string at end or remaining pattern > remaining string\n if (string.length === stringIndex || pattern.length - patternIndex > string.length - stringIndex) {\n return undefined\n }\n\n let c = pattern[patternIndex]\n let index = string.indexOf(c, stringIndex)\n let best, temp\n\n while (index > -1) {\n patternCache.push(index)\n temp = this.traverse(string, pattern, index + 1, patternIndex + 1, patternCache)\n patternCache.pop()\n\n // if downstream traversal failed, return best answer so far\n if (!temp) {\n return best\n }\n\n if (!best || best.score < temp.score) {\n best = temp\n }\n\n index = string.indexOf(c, index + 1)\n }\n\n return best\n }\n\n calculateScore(patternCache) {\n let score = 0\n let temp = 1\n\n patternCache.forEach((index, i) => {\n if (i > 0) {\n if (patternCache[i - 1] + 1 === index) {\n temp += temp + 1\n }\n else {\n temp = 1\n }\n }\n\n score += temp\n })\n\n return score\n }\n\n render(string, indices, pre, post) {\n var rendered = string.substring(0, indices[0])\n\n indices.forEach((index, i) => {\n rendered += pre + string[index] + post +\n string.substring(index + 1, (indices[i + 1]) ? indices[i + 1] : string.length)\n })\n\n return rendered\n }\n\n filter(pattern, arr, opts) {\n opts = opts || {}\n return arr\n .reduce((prev, element, idx, arr) => {\n let str = element\n\n if (opts.extract) {\n str = opts.extract(element)\n\n if (!str) { // take care of undefineds / nulls / etc.\n str = ''\n }\n }\n\n let rendered = this.match(pattern, str, opts)\n\n if (rendered != null) {\n prev[prev.length] = {\n string: rendered.rendered,\n score: rendered.score,\n index: idx,\n original: element\n }\n }\n\n return prev\n }, [])\n\n .sort((a, b) => {\n let compare = b.score - a.score\n if (compare) return compare\n return a.index - b.index\n })\n }\n}\n\nexport default TributeSearch;\n","import \"./utils\";\nimport TributeEvents from \"./TributeEvents\";\nimport TributeMenuEvents from \"./TributeMenuEvents\";\nimport TributeRange from \"./TributeRange\";\nimport TributeSearch from \"./TributeSearch\";\n\nclass Tribute {\n constructor({\n values = null,\n loadingItemTemplate = null,\n iframe = null,\n selectClass = \"highlight\",\n containerClass = \"tribute-container\",\n itemClass = \"\",\n trigger = \"@\",\n autocompleteMode = false,\n autocompleteSeparator = null,\n selectTemplate = null,\n menuItemTemplate = null,\n lookup = \"key\",\n fillAttr = \"value\",\n collection = null,\n menuContainer = null,\n noMatchTemplate = null,\n requireLeadingSpace = true,\n allowSpaces = false,\n replaceTextSuffix = null,\n positionMenu = true,\n spaceSelectsMatch = false,\n searchOpts = {},\n menuItemLimit = null,\n menuShowMinLength = 0\n }) {\n this.autocompleteMode = autocompleteMode;\n this.autocompleteSeparator = autocompleteSeparator;\n this.menuSelected = 0;\n this.current = {};\n this.inputEvent = false;\n this.isActive = false;\n this.menuContainer = menuContainer;\n this.allowSpaces = allowSpaces;\n this.replaceTextSuffix = replaceTextSuffix;\n this.positionMenu = positionMenu;\n this.hasTrailingSpace = false;\n this.spaceSelectsMatch = spaceSelectsMatch;\n\n if (this.autocompleteMode) {\n trigger = \"\";\n allowSpaces = false;\n }\n\n if (values) {\n this.collection = [\n {\n // symbol that starts the lookup\n trigger: trigger,\n\n // is it wrapped in an iframe\n iframe: iframe,\n\n // class applied to selected item\n selectClass: selectClass,\n\n // class applied to the Container\n containerClass: containerClass,\n\n // class applied to each item\n itemClass: itemClass,\n\n // function called on select that retuns the content to insert\n selectTemplate: (\n selectTemplate || Tribute.defaultSelectTemplate\n ).bind(this),\n\n // function called that returns content for an item\n menuItemTemplate: (\n menuItemTemplate || Tribute.defaultMenuItemTemplate\n ).bind(this),\n\n // function called when menu is empty, disables hiding of menu.\n noMatchTemplate: (t => {\n if (typeof t === \"string\") {\n if (t.trim() === \"\") return null;\n return t;\n }\n if (typeof t === \"function\") {\n return t.bind(this);\n }\n\n return (\n noMatchTemplate ||\n function() {\n return \"<li>No Match Found!</li>\";\n }.bind(this)\n );\n })(noMatchTemplate),\n\n // column to search against in the object\n lookup: lookup,\n\n // column that contains the content to insert by default\n fillAttr: fillAttr,\n\n // array of objects or a function returning an array of objects\n values: values,\n\n // useful for when values is an async function\n loadingItemTemplate: loadingItemTemplate,\n\n requireLeadingSpace: requireLeadingSpace,\n\n searchOpts: searchOpts,\n\n menuItemLimit: menuItemLimit,\n\n menuShowMinLength: menuShowMinLength\n }\n ];\n } else if (collection) {\n if (this.autocompleteMode)\n console.warn(\n \"Tribute in autocomplete mode does not work for collections\"\n );\n this.collection = collection.map(item => {\n return {\n trigger: item.trigger || trigger,\n iframe: item.iframe || iframe,\n selectClass: item.selectClass || selectClass,\n containerClass: item.containerClass || containerClass,\n itemClass: item.itemClass || itemClass,\n selectTemplate: (\n item.selectTemplate || Tribute.defaultSelectTemplate\n ).bind(this),\n menuItemTemplate: (\n item.menuItemTemplate || Tribute.defaultMenuItemTemplate\n ).bind(this),\n // function called when menu is empty, disables hiding of menu.\n noMatchTemplate: (t => {\n if (typeof t === \"string\") {\n if (t.trim() === \"\") return null;\n return t;\n }\n if (typeof t === \"function\") {\n return t.bind(this);\n }\n\n return (\n noMatchTemplate ||\n function() {\n return \"<li>No Match Found!</li>\";\n }.bind(this)\n );\n })(noMatchTemplate),\n lookup: item.lookup || lookup,\n fillAttr: item.fillAttr || fillAttr,\n values: item.values,\n loadingItemTemplate: item.loadingItemTemplate,\n requireLeadingSpace: item.requireLeadingSpace,\n searchOpts: item.searchOpts || searchOpts,\n menuItemLimit: item.menuItemLimit || menuItemLimit,\n menuShowMinLength: item.menuShowMinLength || menuShowMinLength\n };\n });\n } else {\n throw new Error(\"[Tribute] No collection specified.\");\n }\n\n new TributeRange(this);\n new TributeEvents(this);\n new TributeMenuEvents(this);\n new TributeSearch(this);\n }\n\n get isActive() {\n return this._isActive;\n }\n\n set isActive(val) {\n if (this._isActive != val) {\n this._isActive = val;\n if (this.current.element) {\n let noMatchEvent = new CustomEvent(`tribute-active-${val}`);\n this.current.element.dispatchEvent(noMatchEvent);\n }\n }\n }\n\n static defaultSelectTemplate(item) {\n if (typeof item === \"undefined\")\n return `${this.current.collection.trigger}${this.current.mentionText}`;\n if (this.range.isContentEditable(this.current.element)) {\n return (\n '<span class=\"tribute-mention\">' +\n (this.current.collection.trigger +\n item.original[this.current.collection.fillAttr]) +\n \"</span>\"\n );\n }\n\n return (\n this.current.collection.trigger +\n item.original[this.current.collection.fillAttr]\n );\n }\n\n static defaultMenuItemTemplate(matchItem) {\n return matchItem.string;\n }\n\n static inputTypes() {\n return [\"TEXTAREA\", \"INPUT\"];\n }\n\n triggers() {\n return this.collection.map(config => {\n return config.trigger;\n });\n }\n\n attach(el) {\n if (!el) {\n throw new Error(\"[Tribute] Must pass in a DOM node or NodeList.\");\n }\n\n // Check if it is a jQuery collection\n if (typeof jQuery !== \"undefined\" && el instanceof jQuery) {\n el = el.get();\n }\n\n // Is el an Array/Array-like object?\n if (\n el.constructor === NodeList ||\n el.constructor === HTMLCollection ||\n el.constructor === Array\n ) {\n let length = el.length;\n for (var i = 0; i < length; ++i) {\n this._attach(el[i]);\n }\n } else {\n this._attach(el);\n }\n }\n\n _attach(el) {\n if (el.hasAttribute(\"data-tribute\")) {\n console.warn(\"Tribute was already bound to \" + el.nodeName);\n }\n\n this.ensureEditable(el);\n this.events.bind(el);\n el.setAttribute(\"data-tribute\", true);\n }\n\n ensureEditable(element) {\n if (Tribute.inputTypes().indexOf(element.nodeName) === -1) {\n if (element.contentEditable) {\n element.contentEditable = true;\n } else {\n throw new Error(\"[Tribute] Cannot bind to \" + element.nodeName);\n }\n }\n }\n\n createMenu(containerClass) {\n let wrapper = this.range.getDocument().createElement(\"div\"),\n ul = this.range.getDocument().createElement(\"ul\");\n wrapper.className = containerClass;\n wrapper.appendChild(ul);\n\n if (this.menuContainer) {\n return this.menuContainer.appendChild(wrapper);\n }\n\n return this.range.getDocument().body.appendChild(wrapper);\n }\n\n showMenuFor(element, scrollTo) {\n // Only proceed if menu isn't already shown for the current element & mentionText\n if (\n this.isActive &&\n this.current.element === element &&\n this.current.mentionText === this.currentMentionTextSnapshot\n ) {\n return;\n }\n this.currentMentionTextSnapshot = this.current.mentionText;\n\n // create the menu if it doesn't exist.\n if (!this.menu) {\n this.menu = this.createMenu(this.current.collection.containerClass);\n element.tributeMenu = this.menu;\n this.menuEvents.bind(this.menu);\n }\n\n this.isActive = true;\n this.menuSelected = 0;\n\n if (!this.current.mentionText) {\n this.current.mentionText = \"\";\n }\n\n const processValues = values => {\n // Tribute may not be active any more by the time the value callback returns\n if (!this.isActive) {\n return;\n }\n\n let items = this.search.filter(this.current.mentionText, values, {\n pre: this.current.collection.searchOpts.pre || \"<span>\",\n post: this.current.collection.searchOpts.post || \"</span>\",\n skip: this.current.collection.searchOpts.skip,\n extract: el => {\n if (typeof this.current.collection.lookup === \"string\") {\n return el[this.current.collection.lookup];\n } else if (typeof this.current.collection.lookup === \"function\") {\n return this.current.collection.lookup(el, this.current.mentionText);\n } else {\n throw new Error(\n \"Invalid lookup attribute, lookup must be string or function.\"\n );\n }\n }\n });\n\n if (this.current.collection.menuItemLimit) {\n items = items.slice(0, this.current.collection.menuItemLimit);\n }\n\n this.current.filteredItems = items;\n\n let ul = this.menu.querySelector(\"ul\");\n\n if (!items.length) {\n let noMatchEvent = new CustomEvent(\"tribute-no-match\", {\n detail: this.menu\n });\n this.current.element.dispatchEvent(noMatchEvent);\n if (\n (typeof this.current.collection.noMatchTemplate === \"function\" &&\n !this.current.collection.noMatchTemplate()) ||\n !this.current.collection.noMatchTemplate\n ) {\n this.hideMenu();\n } else {\n typeof this.current.collection.noMatchTemplate === \"function\"\n ? (ul.innerHTML = this.current.collection.noMatchTemplate())\n : (ul.innerHTML = this.current.collection.noMatchTemplate);\n this.range.positionMenuAtCaret(scrollTo);\n }\n\n return;\n }\n\n ul.innerHTML = \"\";\n let fragment = this.range.getDocument().createDocumentFragment();\n\n items.forEach((item, index) => {\n let li = this.range.getDocument().createElement(\"li\");\n li.setAttribute(\"data-index\", index);\n li.className = this.current.collection.itemClass;\n li.addEventListener(\"mousemove\", e => {\n let [li, index] = this._findLiTarget(e.target);\n if (e.movementY !== 0) {\n this.events.setActiveLi(index);\n }\n });\n if (this.menuSelected === index) {\n li.classList.add(this.current.collection.selectClass);\n }\n li.innerHTML = this.current.collection.menuItemTemplate(item);\n fragment.appendChild(li);\n });\n ul.appendChild(fragment);\n\n this.range.positionMenuAtCaret(scrollTo);\n };\n\n if (typeof this.current.collection.values === \"function\") {\n if (this.current.collection.loadingItemTemplate) {\n this.menu.querySelector(\"ul\").innerHTML = this.current.collection.loadingItemTemplate;\n this.range.positionMenuAtCaret(scrollTo);\n }\n\n this.current.collection.values(this.current.mentionText, processValues);\n } else {\n processValues(this.current.collection.values);\n }\n }\n\n _findLiTarget(el) {\n if (!el) return [];\n const index = el.getAttribute(\"data-index\");\n return !index ? this._findLiTarget(el.parentNode) : [el, index];\n }\n\n showMenuForCollection(element, collectionIndex) {\n if (element !== document.activeElement) {\n this.placeCaretAtEnd(element);\n }\n\n this.current.collection = this.collection[collectionIndex || 0];\n this.current.externalTrigger = true;\n this.current.element = element;\n\n if (element.isContentEditable)\n this.insertTextAtCursor(this.current.collection.trigger);\n else this.insertAtCaret(element, this.current.collection.trigger);\n\n this.showMenuFor(element);\n }\n\n // TODO: make sure this works for inputs/textareas\n placeCaretAtEnd(el) {\n el.focus();\n if (\n typeof window.getSelection != \"undefined\" &&\n typeof document.createRange != \"undefined\"\n ) {\n var range = document.createRange();\n range.selectNodeContents(el);\n range.collapse(false);\n var sel = window.getSelection();\n sel.removeAllRanges();\n sel.addRange(range);\n } else if (typeof document.body.createTextRange != \"undefined\") {\n var textRange = document.body.createTextRange();\n textRange.moveToElementText(el);\n textRange.collapse(false);\n textRange.select();\n }\n }\n\n // for contenteditable\n insertTextAtCursor(text) {\n var sel, range, html;\n sel = window.getSelection();\n range = sel.getRangeAt(0);\n range.deleteContents();\n var textNode = document.createTextNode(text);\n range.insertNode(textNode);\n range.selectNodeContents(textNode);\n range.collapse(false);\n sel.removeAllRanges();\n sel.addRange(range);\n }\n\n // for regular inputs\n insertAtCaret(textarea, text) {\n var scrollPos = textarea.scrollTop;\n var caretPos = textarea.selectionStart;\n\n var front = textarea.value.substring(0, caretPos);\n var back = textarea.value.substring(\n textarea.selectionEnd,\n textarea.value.length\n );\n textarea.value = front + text + back;\n caretPos = caretPos + text.length;\n textarea.selectionStart = caretPos;\n textarea.selectionEnd = caretPos;\n textarea.focus();\n textarea.scrollTop = scrollPos;\n }\n\n hideMenu() {\n if (this.menu) {\n this.menu.style.cssText = \"display: none;\";\n this.isActive = false;\n this.menuSelected = 0;\n this.current = {};\n }\n }\n\n selectItemAtIndex(index, originalEvent) {\n index = parseInt(index);\n if (typeof index !== \"number\" || isNaN(index)) return;\n let item = this.current.filteredItems[index];\n let content = this.current.collection.selectTemplate(item);\n if (content !== null) this.replaceText(content, originalEvent, item);\n }\n\n replaceText(content, originalEvent, item) {\n this.range.replaceTriggerText(content, true, true, originalEvent, item);\n }\n\n _append(collection, newValues, replace) {\n if (typeof collection.values === \"function\") {\n throw new Error(\"Unable to append to values, as it is a function.\");\n } else if (!replace) {\n collection.values = collection.values.concat(newValues);\n } else {\n collection.values = newValues;\n }\n }\n\n append(collectionIndex, newValues, replace) {\n let index = parseInt(collectionIndex);\n if (typeof index !== \"number\")\n throw new Error(\"please provide an index for the collection to update.\");\n\n let collection = this.collection[index];\n\n this._append(collection, newValues, replace);\n }\n\n appendCurrent(newValues, replace) {\n if (this.isActive) {\n this._append(this.current.collection, newValues, replace);\n } else {\n throw new Error(\n \"No active state. Please use append instead and pass an index.\"\n );\n }\n }\n\n detach(el) {\n if (!el) {\n throw new Error(\"[Tribute] Must pass in a DOM node or NodeList.\");\n }\n\n // Check if it is a jQuery collection\n if (typeof jQuery !== \"undefined\" && el instanceof jQuery) {\n el = el.get();\n }\n\n // Is el an Array/Array-like object?\n if (\n el.constructor === NodeList ||\n el.constructor === HTMLCollection ||\n el.constructor === Array\n ) {\n let length = el.length;\n for (var i = 0; i < length; ++i) {\n this._detach(el[i]);\n }\n } else {\n this._detach(el);\n }\n }\n\n _detach(el) {\n this.events.unbind(el);\n if (el.tributeMenu) {\n this.menuEvents.unbind(el.tributeMenu);\n }\n\n setTimeout(() => {\n el.removeAttribute(\"data-tribute\");\n this.isActive = false;\n if (el.tributeMenu) {\n el.tributeMenu.remove();\n }\n });\n }\n}\n\nexport default Tribute;\n"],"names":["Array","prototype","find","predicate","this","TypeError","value","list","Object","length","thisArg","arguments","i","call","window","CustomEvent","event","params","bubbles","cancelable","detail","undefined","evt","document","createEvent","initCustomEvent","Event","TributeEvents","tribute","events","element","boundKeydown","keydown","bind","boundKeyup","keyup","boundInput","input","addEventListener","removeEventListener","instance","shouldDeactivate","isActive","hideMenu","commandEvent","keys","forEach","o","key","keyCode","callbacks","toLowerCase","inputEvent","menu","contains","target","li","preventDefault","stopPropagation","nodeName","parentNode","Error","selectItemAtIndex","getAttribute","current","externalTrigger","setTimeout","updateSelection","allowSpaces","hasTrailingSpace","autocompleteMode","triggerChar","getKeyCode","isNaN","trigger","triggers","charCodeAt","mentionText","collection","menuShowMinLength","showMenuFor","eventKeyPressed","el","info","range","getTriggerInfo","mentionTriggerChar","selectedPath","mentionSelectedPath","selectedOffset","mentionSelectedOffset","e","_this","collectionItem","item","enter","filteredItems","menuSelected","escape","tab","space","spaceSelectsMatch","up","count","selected","setActiveLi","scrollTop","scrollHeight","down","index","lis","querySelectorAll","parseInt","classList","add","selectClass","liClientRect","getBoundingClientRect","menuClientRect","bottom","scrollDistance","top","remove","elem","includeMargin","height","style","currentStyle","getComputedStyle","parseFloat","marginTop","marginBottom","TributeMenuEvents","menuEvents","menuClickEvent","click","menuContainerScrollEvent","debounce","windowResizeEvent","getDocument","menuContainer","func","wait","immediate","timeout","context","_this2","args","callNow","clearTimeout","apply","TributeRange","iframe","contentWindow","scrollTo","coordinates","positionMenu","cssText","isContentEditable","getContentEditableCaretPosition","mentionPosition","getTextAreaOrInputUnderlinePosition","left","right","maxHeight","maxWidth","position","scrollIntoView","targetElement","path","offset","childNodes","nextSibling","previousSibling","sel","getWindowSelection","createRange","setStart","setEnd","collapse","removeAllRanges","error","addRange","focus","text","requireLeadingSpace","originalEvent","replaceEvent","replaceTextSuffix","endPos","pasteHtml","myField","textSuffix","startPos","substring","selectionStart","selectionEnd","dispatchEvent","html","anchorNode","deleteContents","createElement","innerHTML","node","lastNode","frag","createDocumentFragment","firstChild","appendChild","insertNode","cloneRange","setStartAfter","getSelection","ctx","ce","contentEditable","getNodePositionInParent","push","reverse","getRangeAt","startOffset","selectedElem","workingNodeContent","textContent","selectStartOffset","textComponent","wordsArray","replace","autocompleteSeparator","split","trim","menuAlreadyActive","isAutocomplete","selectionInfo","getContentEditableSelectedPath","effectiveRange","getTextPrecedingCurrentSelection","lastWordOfEffectiveRange","getLastWordInText","mentionSelectedElement","mostRecentTriggerCharPos","config","c","idx","lastIndexWithLeadingSpace","lastIndexOf","test","currentTriggerSnippet","firstSnippetChar","leadingSpace","regex","str","reversedStr","join","cidx","len","firstChar","match","triggerIdx","menuDimensions","windowWidth","innerWidth","windowHeight","innerHeight","doc","documentElement","windowLeft","pageXOffset","scrollLeft","clientLeft","windowTop","pageYOffset","clientTop","menuTop","menuRight","width","menuBottom","menuLeft","Math","floor","ceil","dimensions","offsetWidth","offsetHeight","flipped","div","id","body","computed","whiteSpace","wordWrap","visibility","prop","span0","span","span2","rect","spanRect","removeChild","getFixedCoordinatesRelativeToRect","selectedNodePosition","getMenuDimensions","availableSpaceOnTop","availableSpaceOnBottom","availableSpaceOnLeft","availableSpaceOnRight","clientRect","elemTop","elemBottom","maxY","targetY","TributeSearch","search","pattern","array","filter","string","opts","pre","post","compareString","caseSensitive","skip","rendered","score","patternCache","traverse","render","cache","stringIndex","patternIndex","splice","calculateScore","slice","best","temp","indexOf","pop","indices","arr","reduce","prev","extract","original","sort","a","b","compare","t","values","loadingItemTemplate","containerClass","itemClass","selectTemplate","menuItemTemplate","lookup","fillAttr","noMatchTemplate","searchOpts","menuItemLimit","Tribute","defaultSelectTemplate","defaultMenuItemTemplate","console","warn","map","jQuery","get","constructor","NodeList","HTMLCollection","_attach","hasAttribute","ensureEditable","setAttribute","inputTypes","wrapper","ul","className","currentMentionTextSnapshot","createMenu","tributeMenu","processValues","items","querySelector","noMatchEvent","positionMenuAtCaret","fragment","_findLiTarget","movementY","collectionIndex","activeElement","placeCaretAtEnd","insertTextAtCursor","insertAtCaret","selectNodeContents","createTextRange","textRange","moveToElementText","select","textNode","createTextNode","textarea","scrollPos","caretPos","front","back","content","replaceText","replaceTriggerText","newValues","concat","_append","_detach","unbind","removeAttribute","_this3","_isActive","val","matchItem"],"mappings":"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"} ```
/content/code_sandbox/dist/tribute.min.js.map
unknown
2016-01-19T00:54:39
2024-08-14T11:30:58
tribute
zurb/tribute
2,017
30,451
```go package math import "jvmgo/ch11/instructions/base" import "jvmgo/ch11/rtda" // Boolean AND int type IAND struct{ base.NoOperandsInstruction } func (self *IAND) Execute(frame *rtda.Frame) { stack := frame.OperandStack() v2 := stack.PopInt() v1 := stack.PopInt() result := v1 & v2 stack.PushInt(result) } // Boolean AND long type LAND struct{ base.NoOperandsInstruction } func (self *LAND) Execute(frame *rtda.Frame) { stack := frame.OperandStack() v2 := stack.PopLong() v1 := stack.PopLong() result := v1 & v2 stack.PushLong(result) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/instructions/math/and.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
158
```go package classfile /* LineNumberTable_attribute { u2 attribute_name_index; u4 attribute_length; u2 line_number_table_length; { u2 start_pc; u2 line_number; } line_number_table[line_number_table_length]; } */ type LineNumberTableAttribute struct { lineNumberTable []*LineNumberTableEntry } type LineNumberTableEntry struct { startPc uint16 lineNumber uint16 } func (self *LineNumberTableAttribute) readInfo(reader *ClassReader) { lineNumberTableLength := reader.readUint16() self.lineNumberTable = make([]*LineNumberTableEntry, lineNumberTableLength) for i := range self.lineNumberTable { self.lineNumberTable[i] = &LineNumberTableEntry{ startPc: reader.readUint16(), lineNumber: reader.readUint16(), } } } func (self *LineNumberTableAttribute) GetLineNumber(pc int) int { for i := len(self.lineNumberTable) - 1; i >= 0; i-- { entry := self.lineNumberTable[i] if pc >= int(entry.startPc) { return int(entry.lineNumber) } } return -1 } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/classfile/attr_line_number_table.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
255
```go package instructions import "fmt" import "jvmgo/ch11/instructions/base" import . "jvmgo/ch11/instructions/comparisons" import . "jvmgo/ch11/instructions/constants" import . "jvmgo/ch11/instructions/control" import . "jvmgo/ch11/instructions/conversions" import . "jvmgo/ch11/instructions/extended" import . "jvmgo/ch11/instructions/loads" import . "jvmgo/ch11/instructions/math" import . "jvmgo/ch11/instructions/references" import . "jvmgo/ch11/instructions/reserved" import . "jvmgo/ch11/instructions/stack" import . "jvmgo/ch11/instructions/stores" // NoOperandsInstruction singletons var ( nop = &NOP{} aconst_null = &ACONST_NULL{} iconst_m1 = &ICONST_M1{} iconst_0 = &ICONST_0{} iconst_1 = &ICONST_1{} iconst_2 = &ICONST_2{} iconst_3 = &ICONST_3{} iconst_4 = &ICONST_4{} iconst_5 = &ICONST_5{} lconst_0 = &LCONST_0{} lconst_1 = &LCONST_1{} fconst_0 = &FCONST_0{} fconst_1 = &FCONST_1{} fconst_2 = &FCONST_2{} dconst_0 = &DCONST_0{} dconst_1 = &DCONST_1{} iload_0 = &ILOAD_0{} iload_1 = &ILOAD_1{} iload_2 = &ILOAD_2{} iload_3 = &ILOAD_3{} lload_0 = &LLOAD_0{} lload_1 = &LLOAD_1{} lload_2 = &LLOAD_2{} lload_3 = &LLOAD_3{} fload_0 = &FLOAD_0{} fload_1 = &FLOAD_1{} fload_2 = &FLOAD_2{} fload_3 = &FLOAD_3{} dload_0 = &DLOAD_0{} dload_1 = &DLOAD_1{} dload_2 = &DLOAD_2{} dload_3 = &DLOAD_3{} aload_0 = &ALOAD_0{} aload_1 = &ALOAD_1{} aload_2 = &ALOAD_2{} aload_3 = &ALOAD_3{} iaload = &IALOAD{} laload = &LALOAD{} faload = &FALOAD{} daload = &DALOAD{} aaload = &AALOAD{} baload = &BALOAD{} caload = &CALOAD{} saload = &SALOAD{} istore_0 = &ISTORE_0{} istore_1 = &ISTORE_1{} istore_2 = &ISTORE_2{} istore_3 = &ISTORE_3{} lstore_0 = &LSTORE_0{} lstore_1 = &LSTORE_1{} lstore_2 = &LSTORE_2{} lstore_3 = &LSTORE_3{} fstore_0 = &FSTORE_0{} fstore_1 = &FSTORE_1{} fstore_2 = &FSTORE_2{} fstore_3 = &FSTORE_3{} dstore_0 = &DSTORE_0{} dstore_1 = &DSTORE_1{} dstore_2 = &DSTORE_2{} dstore_3 = &DSTORE_3{} astore_0 = &ASTORE_0{} astore_1 = &ASTORE_1{} astore_2 = &ASTORE_2{} astore_3 = &ASTORE_3{} iastore = &IASTORE{} lastore = &LASTORE{} fastore = &FASTORE{} dastore = &DASTORE{} aastore = &AASTORE{} bastore = &BASTORE{} castore = &CASTORE{} sastore = &SASTORE{} pop = &POP{} pop2 = &POP2{} dup = &DUP{} dup_x1 = &DUP_X1{} dup_x2 = &DUP_X2{} dup2 = &DUP2{} dup2_x1 = &DUP2_X1{} dup2_x2 = &DUP2_X2{} swap = &SWAP{} iadd = &IADD{} ladd = &LADD{} fadd = &FADD{} dadd = &DADD{} isub = &ISUB{} lsub = &LSUB{} fsub = &FSUB{} dsub = &DSUB{} imul = &IMUL{} lmul = &LMUL{} fmul = &FMUL{} dmul = &DMUL{} idiv = &IDIV{} ldiv = &LDIV{} fdiv = &FDIV{} ddiv = &DDIV{} irem = &IREM{} lrem = &LREM{} frem = &FREM{} drem = &DREM{} ineg = &INEG{} lneg = &LNEG{} fneg = &FNEG{} dneg = &DNEG{} ishl = &ISHL{} lshl = &LSHL{} ishr = &ISHR{} lshr = &LSHR{} iushr = &IUSHR{} lushr = &LUSHR{} iand = &IAND{} land = &LAND{} ior = &IOR{} lor = &LOR{} ixor = &IXOR{} lxor = &LXOR{} i2l = &I2L{} i2f = &I2F{} i2d = &I2D{} l2i = &L2I{} l2f = &L2F{} l2d = &L2D{} f2i = &F2I{} f2l = &F2L{} f2d = &F2D{} d2i = &D2I{} d2l = &D2L{} d2f = &D2F{} i2b = &I2B{} i2c = &I2C{} i2s = &I2S{} lcmp = &LCMP{} fcmpl = &FCMPL{} fcmpg = &FCMPG{} dcmpl = &DCMPL{} dcmpg = &DCMPG{} ireturn = &IRETURN{} lreturn = &LRETURN{} freturn = &FRETURN{} dreturn = &DRETURN{} areturn = &ARETURN{} _return = &RETURN{} arraylength = &ARRAY_LENGTH{} athrow = &ATHROW{} monitorenter = &MONITOR_ENTER{} monitorexit = &MONITOR_EXIT{} invoke_native = &INVOKE_NATIVE{} ) func NewInstruction(opcode byte) base.Instruction { switch opcode { case 0x00: return nop case 0x01: return aconst_null case 0x02: return iconst_m1 case 0x03: return iconst_0 case 0x04: return iconst_1 case 0x05: return iconst_2 case 0x06: return iconst_3 case 0x07: return iconst_4 case 0x08: return iconst_5 case 0x09: return lconst_0 case 0x0a: return lconst_1 case 0x0b: return fconst_0 case 0x0c: return fconst_1 case 0x0d: return fconst_2 case 0x0e: return dconst_0 case 0x0f: return dconst_1 case 0x10: return &BIPUSH{} case 0x11: return &SIPUSH{} case 0x12: return &LDC{} case 0x13: return &LDC_W{} case 0x14: return &LDC2_W{} case 0x15: return &ILOAD{} case 0x16: return &LLOAD{} case 0x17: return &FLOAD{} case 0x18: return &DLOAD{} case 0x19: return &ALOAD{} case 0x1a: return iload_0 case 0x1b: return iload_1 case 0x1c: return iload_2 case 0x1d: return iload_3 case 0x1e: return lload_0 case 0x1f: return lload_1 case 0x20: return lload_2 case 0x21: return lload_3 case 0x22: return fload_0 case 0x23: return fload_1 case 0x24: return fload_2 case 0x25: return fload_3 case 0x26: return dload_0 case 0x27: return dload_1 case 0x28: return dload_2 case 0x29: return dload_3 case 0x2a: return aload_0 case 0x2b: return aload_1 case 0x2c: return aload_2 case 0x2d: return aload_3 case 0x2e: return iaload case 0x2f: return laload case 0x30: return faload case 0x31: return daload case 0x32: return aaload case 0x33: return baload case 0x34: return caload case 0x35: return saload case 0x36: return &ISTORE{} case 0x37: return &LSTORE{} case 0x38: return &FSTORE{} case 0x39: return &DSTORE{} case 0x3a: return &ASTORE{} case 0x3b: return istore_0 case 0x3c: return istore_1 case 0x3d: return istore_2 case 0x3e: return istore_3 case 0x3f: return lstore_0 case 0x40: return lstore_1 case 0x41: return lstore_2 case 0x42: return lstore_3 case 0x43: return fstore_0 case 0x44: return fstore_1 case 0x45: return fstore_2 case 0x46: return fstore_3 case 0x47: return dstore_0 case 0x48: return dstore_1 case 0x49: return dstore_2 case 0x4a: return dstore_3 case 0x4b: return astore_0 case 0x4c: return astore_1 case 0x4d: return astore_2 case 0x4e: return astore_3 case 0x4f: return iastore case 0x50: return lastore case 0x51: return fastore case 0x52: return dastore case 0x53: return aastore case 0x54: return bastore case 0x55: return castore case 0x56: return sastore case 0x57: return pop case 0x58: return pop2 case 0x59: return dup case 0x5a: return dup_x1 case 0x5b: return dup_x2 case 0x5c: return dup2 case 0x5d: return dup2_x1 case 0x5e: return dup2_x2 case 0x5f: return swap case 0x60: return iadd case 0x61: return ladd case 0x62: return fadd case 0x63: return dadd case 0x64: return isub case 0x65: return lsub case 0x66: return fsub case 0x67: return dsub case 0x68: return imul case 0x69: return lmul case 0x6a: return fmul case 0x6b: return dmul case 0x6c: return idiv case 0x6d: return ldiv case 0x6e: return fdiv case 0x6f: return ddiv case 0x70: return irem case 0x71: return lrem case 0x72: return frem case 0x73: return drem case 0x74: return ineg case 0x75: return lneg case 0x76: return fneg case 0x77: return dneg case 0x78: return ishl case 0x79: return lshl case 0x7a: return ishr case 0x7b: return lshr case 0x7c: return iushr case 0x7d: return lushr case 0x7e: return iand case 0x7f: return land case 0x80: return ior case 0x81: return lor case 0x82: return ixor case 0x83: return lxor case 0x84: return &IINC{} case 0x85: return i2l case 0x86: return i2f case 0x87: return i2d case 0x88: return l2i case 0x89: return l2f case 0x8a: return l2d case 0x8b: return f2i case 0x8c: return f2l case 0x8d: return f2d case 0x8e: return d2i case 0x8f: return d2l case 0x90: return d2f case 0x91: return i2b case 0x92: return i2c case 0x93: return i2s case 0x94: return lcmp case 0x95: return fcmpl case 0x96: return fcmpg case 0x97: return dcmpl case 0x98: return dcmpg case 0x99: return &IFEQ{} case 0x9a: return &IFNE{} case 0x9b: return &IFLT{} case 0x9c: return &IFGE{} case 0x9d: return &IFGT{} case 0x9e: return &IFLE{} case 0x9f: return &IF_ICMPEQ{} case 0xa0: return &IF_ICMPNE{} case 0xa1: return &IF_ICMPLT{} case 0xa2: return &IF_ICMPGE{} case 0xa3: return &IF_ICMPGT{} case 0xa4: return &IF_ICMPLE{} case 0xa5: return &IF_ACMPEQ{} case 0xa6: return &IF_ACMPNE{} case 0xa7: return &GOTO{} // case 0xa8: // return &JSR{} // case 0xa9: // return &RET{} case 0xaa: return &TABLE_SWITCH{} case 0xab: return &LOOKUP_SWITCH{} case 0xac: return ireturn case 0xad: return lreturn case 0xae: return freturn case 0xaf: return dreturn case 0xb0: return areturn case 0xb1: return _return case 0xb2: return &GET_STATIC{} case 0xb3: return &PUT_STATIC{} case 0xb4: return &GET_FIELD{} case 0xb5: return &PUT_FIELD{} case 0xb6: return &INVOKE_VIRTUAL{} case 0xb7: return &INVOKE_SPECIAL{} case 0xb8: return &INVOKE_STATIC{} case 0xb9: return &INVOKE_INTERFACE{} // case 0xba: // return &INVOKE_DYNAMIC{} case 0xbb: return &NEW{} case 0xbc: return &NEW_ARRAY{} case 0xbd: return &ANEW_ARRAY{} case 0xbe: return arraylength case 0xbf: return athrow case 0xc0: return &CHECK_CAST{} case 0xc1: return &INSTANCE_OF{} case 0xc2: return monitorenter case 0xc3: return monitorexit case 0xc4: return &WIDE{} case 0xc5: return &MULTI_ANEW_ARRAY{} case 0xc6: return &IFNULL{} case 0xc7: return &IFNONNULL{} case 0xc8: return &GOTO_W{} // case 0xc9: // return &JSR_W{} // case 0xca: breakpoint case 0xfe: return invoke_native // case 0xff: impdep2 default: panic(fmt.Errorf("Unsupported opcode: 0x%x!", opcode)) } } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/instructions/factory.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
4,240
```go package stores import "jvmgo/ch11/instructions/base" import "jvmgo/ch11/rtda" // Store int into local variable type ISTORE struct{ base.Index8Instruction } func (self *ISTORE) Execute(frame *rtda.Frame) { _istore(frame, uint(self.Index)) } type ISTORE_0 struct{ base.NoOperandsInstruction } func (self *ISTORE_0) Execute(frame *rtda.Frame) { _istore(frame, 0) } type ISTORE_1 struct{ base.NoOperandsInstruction } func (self *ISTORE_1) Execute(frame *rtda.Frame) { _istore(frame, 1) } type ISTORE_2 struct{ base.NoOperandsInstruction } func (self *ISTORE_2) Execute(frame *rtda.Frame) { _istore(frame, 2) } type ISTORE_3 struct{ base.NoOperandsInstruction } func (self *ISTORE_3) Execute(frame *rtda.Frame) { _istore(frame, 3) } func _istore(frame *rtda.Frame, index uint) { val := frame.OperandStack().PopInt() frame.LocalVars().SetInt(index, val) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/instructions/stores/istore.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
270
```go package comparisons import "jvmgo/ch11/instructions/base" import "jvmgo/ch11/rtda" // Compare float type FCMPG struct{ base.NoOperandsInstruction } func (self *FCMPG) Execute(frame *rtda.Frame) { _fcmp(frame, true) } type FCMPL struct{ base.NoOperandsInstruction } func (self *FCMPL) Execute(frame *rtda.Frame) { _fcmp(frame, false) } func _fcmp(frame *rtda.Frame, gFlag bool) { stack := frame.OperandStack() v2 := stack.PopFloat() v1 := stack.PopFloat() if v1 > v2 { stack.PushInt(1) } else if v1 == v2 { stack.PushInt(0) } else if v1 < v2 { stack.PushInt(-1) } else if gFlag { stack.PushInt(1) } else { stack.PushInt(-1) } } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/instructions/comparisons/fcmp.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
217
```go package references import "jvmgo/ch11/instructions/base" import "jvmgo/ch11/rtda" import "jvmgo/ch11/rtda/heap" // Invoke a class (static) method type INVOKE_STATIC struct{ base.Index16Instruction } func (self *INVOKE_STATIC) Execute(frame *rtda.Frame) { cp := frame.Method().Class().ConstantPool() methodRef := cp.GetConstant(self.Index).(*heap.MethodRef) resolvedMethod := methodRef.ResolvedMethod() if !resolvedMethod.IsStatic() { panic("java.lang.IncompatibleClassChangeError") } class := resolvedMethod.Class() if !class.InitStarted() { frame.RevertNextPC() base.InitClass(frame.Thread(), class) return } base.InvokeMethod(frame, resolvedMethod) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/instructions/references/invokestatic.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
174
```go package comparisons import "jvmgo/ch11/instructions/base" import "jvmgo/ch11/rtda" // Branch if int comparison with zero succeeds type IFEQ struct{ base.BranchInstruction } func (self *IFEQ) Execute(frame *rtda.Frame) { val := frame.OperandStack().PopInt() if val == 0 { base.Branch(frame, self.Offset) } } type IFNE struct{ base.BranchInstruction } func (self *IFNE) Execute(frame *rtda.Frame) { val := frame.OperandStack().PopInt() if val != 0 { base.Branch(frame, self.Offset) } } type IFLT struct{ base.BranchInstruction } func (self *IFLT) Execute(frame *rtda.Frame) { val := frame.OperandStack().PopInt() if val < 0 { base.Branch(frame, self.Offset) } } type IFLE struct{ base.BranchInstruction } func (self *IFLE) Execute(frame *rtda.Frame) { val := frame.OperandStack().PopInt() if val <= 0 { base.Branch(frame, self.Offset) } } type IFGT struct{ base.BranchInstruction } func (self *IFGT) Execute(frame *rtda.Frame) { val := frame.OperandStack().PopInt() if val > 0 { base.Branch(frame, self.Offset) } } type IFGE struct{ base.BranchInstruction } func (self *IFGE) Execute(frame *rtda.Frame) { val := frame.OperandStack().PopInt() if val >= 0 { base.Branch(frame, self.Offset) } } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/instructions/comparisons/ifcond.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
348
```go package conversions import "jvmgo/ch11/instructions/base" import "jvmgo/ch11/rtda" // Convert double to float type D2F struct{ base.NoOperandsInstruction } func (self *D2F) Execute(frame *rtda.Frame) { stack := frame.OperandStack() d := stack.PopDouble() f := float32(d) stack.PushFloat(f) } // Convert double to int type D2I struct{ base.NoOperandsInstruction } func (self *D2I) Execute(frame *rtda.Frame) { stack := frame.OperandStack() d := stack.PopDouble() i := int32(d) stack.PushInt(i) } // Convert double to long type D2L struct{ base.NoOperandsInstruction } func (self *D2L) Execute(frame *rtda.Frame) { stack := frame.OperandStack() d := stack.PopDouble() l := int64(d) stack.PushLong(l) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/instructions/conversions/d2x.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
206
```go package math import "jvmgo/ch11/instructions/base" import "jvmgo/ch11/rtda" // Shift left int type ISHL struct{ base.NoOperandsInstruction } func (self *ISHL) Execute(frame *rtda.Frame) { stack := frame.OperandStack() v2 := stack.PopInt() v1 := stack.PopInt() s := uint32(v2) & 0x1f result := v1 << s stack.PushInt(result) } // Arithmetic shift right int type ISHR struct{ base.NoOperandsInstruction } func (self *ISHR) Execute(frame *rtda.Frame) { stack := frame.OperandStack() v2 := stack.PopInt() v1 := stack.PopInt() s := uint32(v2) & 0x1f result := v1 >> s stack.PushInt(result) } // Logical shift right int type IUSHR struct{ base.NoOperandsInstruction } func (self *IUSHR) Execute(frame *rtda.Frame) { stack := frame.OperandStack() v2 := stack.PopInt() v1 := stack.PopInt() s := uint32(v2) & 0x1f result := int32(uint32(v1) >> s) stack.PushInt(result) } // Shift left long type LSHL struct{ base.NoOperandsInstruction } func (self *LSHL) Execute(frame *rtda.Frame) { stack := frame.OperandStack() v2 := stack.PopInt() v1 := stack.PopLong() s := uint32(v2) & 0x3f result := v1 << s stack.PushLong(result) } // Arithmetic shift right long type LSHR struct{ base.NoOperandsInstruction } func (self *LSHR) Execute(frame *rtda.Frame) { stack := frame.OperandStack() v2 := stack.PopInt() v1 := stack.PopLong() s := uint32(v2) & 0x3f result := v1 >> s stack.PushLong(result) } // Logical shift right long type LUSHR struct{ base.NoOperandsInstruction } func (self *LUSHR) Execute(frame *rtda.Frame) { stack := frame.OperandStack() v2 := stack.PopInt() v1 := stack.PopLong() s := uint32(v2) & 0x3f result := int64(uint64(v1) >> s) stack.PushLong(result) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/instructions/math/sh.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
526
```go package extended import "jvmgo/ch11/instructions/base" import "jvmgo/ch11/rtda" // Branch if reference is null type IFNULL struct{ base.BranchInstruction } func (self *IFNULL) Execute(frame *rtda.Frame) { ref := frame.OperandStack().PopRef() if ref == nil { base.Branch(frame, self.Offset) } } // Branch if reference not null type IFNONNULL struct{ base.BranchInstruction } func (self *IFNONNULL) Execute(frame *rtda.Frame) { ref := frame.OperandStack().PopRef() if ref != nil { base.Branch(frame, self.Offset) } } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/instructions/extended/ifnull.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
144
```go package classfile /* CONSTANT_Class_info { u1 tag; u2 name_index; } */ type ConstantClassInfo struct { cp ConstantPool nameIndex uint16 } func (self *ConstantClassInfo) readInfo(reader *ClassReader) { self.nameIndex = reader.readUint16() } func (self *ConstantClassInfo) Name() string { return self.cp.getUtf8(self.nameIndex) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/classfile/cp_class.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
90
```go package classfile import "fmt" type ConstantPool []ConstantInfo func readConstantPool(reader *ClassReader) ConstantPool { cpCount := int(reader.readUint16()) cp := make([]ConstantInfo, cpCount) // The constant_pool table is indexed from 1 to constant_pool_count - 1. for i := 1; i < cpCount; i++ { cp[i] = readConstantInfo(reader, cp) // path_to_url#jvms-4.4.5 // All 8-byte constants take up two entries in the constant_pool table of the class file. // If a CONSTANT_Long_info or CONSTANT_Double_info structure is the item in the constant_pool // table at index n, then the next usable item in the pool is located at index n+2. // The constant_pool index n+1 must be valid but is considered unusable. switch cp[i].(type) { case *ConstantLongInfo, *ConstantDoubleInfo: i++ } } return cp } func (self ConstantPool) getConstantInfo(index uint16) ConstantInfo { if cpInfo := self[index]; cpInfo != nil { return cpInfo } panic(fmt.Errorf("Invalid constant pool index: %v!", index)) } func (self ConstantPool) getNameAndType(index uint16) (string, string) { ntInfo := self.getConstantInfo(index).(*ConstantNameAndTypeInfo) name := self.getUtf8(ntInfo.nameIndex) _type := self.getUtf8(ntInfo.descriptorIndex) return name, _type } func (self ConstantPool) getClassName(index uint16) string { classInfo := self.getConstantInfo(index).(*ConstantClassInfo) return self.getUtf8(classInfo.nameIndex) } func (self ConstantPool) getUtf8(index uint16) string { utf8Info := self.getConstantInfo(index).(*ConstantUtf8Info) return utf8Info.str } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/classfile/constant_pool.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
421
```go package extended import "jvmgo/ch11/instructions/base" import "jvmgo/ch11/instructions/loads" import "jvmgo/ch11/instructions/math" import "jvmgo/ch11/instructions/stores" import "jvmgo/ch11/rtda" // Extend local variable index by additional bytes type WIDE struct { modifiedInstruction base.Instruction } func (self *WIDE) FetchOperands(reader *base.BytecodeReader) { opcode := reader.ReadUint8() switch opcode { case 0x15: inst := &loads.ILOAD{} inst.Index = uint(reader.ReadUint16()) self.modifiedInstruction = inst case 0x16: inst := &loads.LLOAD{} inst.Index = uint(reader.ReadUint16()) self.modifiedInstruction = inst case 0x17: inst := &loads.FLOAD{} inst.Index = uint(reader.ReadUint16()) self.modifiedInstruction = inst case 0x18: inst := &loads.DLOAD{} inst.Index = uint(reader.ReadUint16()) self.modifiedInstruction = inst case 0x19: inst := &loads.ALOAD{} inst.Index = uint(reader.ReadUint16()) self.modifiedInstruction = inst case 0x36: inst := &stores.ISTORE{} inst.Index = uint(reader.ReadUint16()) self.modifiedInstruction = inst case 0x37: inst := &stores.LSTORE{} inst.Index = uint(reader.ReadUint16()) self.modifiedInstruction = inst case 0x38: inst := &stores.FSTORE{} inst.Index = uint(reader.ReadUint16()) self.modifiedInstruction = inst case 0x39: inst := &stores.DSTORE{} inst.Index = uint(reader.ReadUint16()) self.modifiedInstruction = inst case 0x3a: inst := &stores.ASTORE{} inst.Index = uint(reader.ReadUint16()) self.modifiedInstruction = inst case 0x84: inst := &math.IINC{} inst.Index = uint(reader.ReadUint16()) inst.Const = int32(reader.ReadInt16()) self.modifiedInstruction = inst case 0xa9: // ret panic("Unsupported opcode: 0xa9!") } } func (self *WIDE) Execute(frame *rtda.Frame) { self.modifiedInstruction.Execute(frame) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/instructions/extended/wide.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
511
```go package control import "jvmgo/ch11/instructions/base" import "jvmgo/ch11/rtda" /* lookupswitch <0-3 byte pad> defaultbyte1 defaultbyte2 defaultbyte3 defaultbyte4 npairs1 npairs2 npairs3 npairs4 match-offset pairs... */ // Access jump table by key match and jump type LOOKUP_SWITCH struct { defaultOffset int32 npairs int32 matchOffsets []int32 } func (self *LOOKUP_SWITCH) FetchOperands(reader *base.BytecodeReader) { reader.SkipPadding() self.defaultOffset = reader.ReadInt32() self.npairs = reader.ReadInt32() self.matchOffsets = reader.ReadInt32s(self.npairs * 2) } func (self *LOOKUP_SWITCH) Execute(frame *rtda.Frame) { key := frame.OperandStack().PopInt() for i := int32(0); i < self.npairs*2; i += 2 { if self.matchOffsets[i] == key { offset := self.matchOffsets[i+1] base.Branch(frame, int(offset)) return } } base.Branch(frame, int(self.defaultOffset)) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/instructions/control/lookupswitch.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
259
```go package references import "jvmgo/ch11/instructions/base" import "jvmgo/ch11/rtda" import "jvmgo/ch11/rtda/heap" // Create new object type NEW struct{ base.Index16Instruction } func (self *NEW) Execute(frame *rtda.Frame) { cp := frame.Method().Class().ConstantPool() classRef := cp.GetConstant(self.Index).(*heap.ClassRef) class := classRef.ResolvedClass() if !class.InitStarted() { frame.RevertNextPC() base.InitClass(frame.Thread(), class) return } if class.IsInterface() || class.IsAbstract() { panic("java.lang.InstantiationError") } ref := class.NewObject() frame.OperandStack().PushRef(ref) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/instructions/references/new.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
167
```go package extended import "jvmgo/ch11/instructions/base" import "jvmgo/ch11/rtda" // Branch always (wide index) type GOTO_W struct { offset int } func (self *GOTO_W) FetchOperands(reader *base.BytecodeReader) { self.offset = int(reader.ReadInt32()) } func (self *GOTO_W) Execute(frame *rtda.Frame) { base.Branch(frame, self.offset) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/instructions/extended/goto_w.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
96
```go package control import "jvmgo/ch11/instructions/base" import "jvmgo/ch11/rtda" /* tableswitch <0-3 byte pad> defaultbyte1 defaultbyte2 defaultbyte3 defaultbyte4 lowbyte1 lowbyte2 lowbyte3 lowbyte4 highbyte1 highbyte2 highbyte3 highbyte4 jump offsets... */ // Access jump table by index and jump type TABLE_SWITCH struct { defaultOffset int32 low int32 high int32 jumpOffsets []int32 } func (self *TABLE_SWITCH) FetchOperands(reader *base.BytecodeReader) { reader.SkipPadding() self.defaultOffset = reader.ReadInt32() self.low = reader.ReadInt32() self.high = reader.ReadInt32() jumpOffsetsCount := self.high - self.low + 1 self.jumpOffsets = reader.ReadInt32s(jumpOffsetsCount) } func (self *TABLE_SWITCH) Execute(frame *rtda.Frame) { index := frame.OperandStack().PopInt() var offset int if index >= self.low && index <= self.high { offset = int(self.jumpOffsets[index-self.low]) } else { offset = int(self.defaultOffset) } base.Branch(frame, offset) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/instructions/control/tableswitch.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
274
```go package math import "jvmgo/ch11/instructions/base" import "jvmgo/ch11/rtda" // Increment local variable by constant type IINC struct { Index uint Const int32 } func (self *IINC) FetchOperands(reader *base.BytecodeReader) { self.Index = uint(reader.ReadUint8()) self.Const = int32(reader.ReadInt8()) } func (self *IINC) Execute(frame *rtda.Frame) { localVars := frame.LocalVars() val := localVars.GetInt(self.Index) val += self.Const localVars.SetInt(self.Index, val) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/instructions/math/iinc.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
132
```go package stack import "jvmgo/ch11/instructions/base" import "jvmgo/ch11/rtda" // Swap the top two operand stack values type SWAP struct{ base.NoOperandsInstruction } func (self *SWAP) Execute(frame *rtda.Frame) { stack := frame.OperandStack() slot1 := stack.PopSlot() slot2 := stack.PopSlot() stack.PushSlot(slot1) stack.PushSlot(slot2) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/instructions/stack/swap.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
96
```go package references import "jvmgo/ch11/instructions/base" import "jvmgo/ch11/rtda" import "jvmgo/ch11/rtda/heap" // Determine if object is of given type type INSTANCE_OF struct{ base.Index16Instruction } func (self *INSTANCE_OF) Execute(frame *rtda.Frame) { stack := frame.OperandStack() ref := stack.PopRef() if ref == nil { stack.PushInt(0) return } cp := frame.Method().Class().ConstantPool() classRef := cp.GetConstant(self.Index).(*heap.ClassRef) class := classRef.ResolvedClass() if ref.IsInstanceOf(class) { stack.PushInt(1) } else { stack.PushInt(0) } } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/instructions/references/instanceof.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
164
```go package classfile /* attribute_info { u2 attribute_name_index; u4 attribute_length; u1 info[attribute_length]; } */ type UnparsedAttribute struct { name string length uint32 info []byte } func (self *UnparsedAttribute) readInfo(reader *ClassReader) { self.info = reader.readBytes(self.length) } func (self *UnparsedAttribute) Info() []byte { return self.info } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/classfile/attr_unparsed.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
96
```go package stores import "jvmgo/ch11/instructions/base" import "jvmgo/ch11/rtda" import "jvmgo/ch11/rtda/heap" // Store into reference array type AASTORE struct{ base.NoOperandsInstruction } func (self *AASTORE) Execute(frame *rtda.Frame) { stack := frame.OperandStack() ref := stack.PopRef() index := stack.PopInt() arrRef := stack.PopRef() checkNotNil(arrRef) refs := arrRef.Refs() checkIndex(len(refs), index) refs[index] = ref } // Store into byte or boolean array type BASTORE struct{ base.NoOperandsInstruction } func (self *BASTORE) Execute(frame *rtda.Frame) { stack := frame.OperandStack() val := stack.PopInt() index := stack.PopInt() arrRef := stack.PopRef() checkNotNil(arrRef) bytes := arrRef.Bytes() checkIndex(len(bytes), index) bytes[index] = int8(val) } // Store into char array type CASTORE struct{ base.NoOperandsInstruction } func (self *CASTORE) Execute(frame *rtda.Frame) { stack := frame.OperandStack() val := stack.PopInt() index := stack.PopInt() arrRef := stack.PopRef() checkNotNil(arrRef) chars := arrRef.Chars() checkIndex(len(chars), index) chars[index] = uint16(val) } // Store into double array type DASTORE struct{ base.NoOperandsInstruction } func (self *DASTORE) Execute(frame *rtda.Frame) { stack := frame.OperandStack() val := stack.PopDouble() index := stack.PopInt() arrRef := stack.PopRef() checkNotNil(arrRef) doubles := arrRef.Doubles() checkIndex(len(doubles), index) doubles[index] = float64(val) } // Store into float array type FASTORE struct{ base.NoOperandsInstruction } func (self *FASTORE) Execute(frame *rtda.Frame) { stack := frame.OperandStack() val := stack.PopFloat() index := stack.PopInt() arrRef := stack.PopRef() checkNotNil(arrRef) floats := arrRef.Floats() checkIndex(len(floats), index) floats[index] = float32(val) } // Store into int array type IASTORE struct{ base.NoOperandsInstruction } func (self *IASTORE) Execute(frame *rtda.Frame) { stack := frame.OperandStack() val := stack.PopInt() index := stack.PopInt() arrRef := stack.PopRef() checkNotNil(arrRef) ints := arrRef.Ints() checkIndex(len(ints), index) ints[index] = int32(val) } // Store into long array type LASTORE struct{ base.NoOperandsInstruction } func (self *LASTORE) Execute(frame *rtda.Frame) { stack := frame.OperandStack() val := stack.PopLong() index := stack.PopInt() arrRef := stack.PopRef() checkNotNil(arrRef) longs := arrRef.Longs() checkIndex(len(longs), index) longs[index] = int64(val) } // Store into short array type SASTORE struct{ base.NoOperandsInstruction } func (self *SASTORE) Execute(frame *rtda.Frame) { stack := frame.OperandStack() val := stack.PopInt() index := stack.PopInt() arrRef := stack.PopRef() checkNotNil(arrRef) shorts := arrRef.Shorts() checkIndex(len(shorts), index) shorts[index] = int16(val) } func checkNotNil(ref *heap.Object) { if ref == nil { panic("java.lang.NullPointerException") } } func checkIndex(arrLen int, index int32) { if index < 0 || index >= int32(arrLen) { panic("ArrayIndexOutOfBoundsException") } } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/instructions/stores/xastore.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
823
```go package comparisons import "jvmgo/ch11/instructions/base" import "jvmgo/ch11/rtda" // Branch if int comparison succeeds type IF_ICMPEQ struct{ base.BranchInstruction } func (self *IF_ICMPEQ) Execute(frame *rtda.Frame) { if val1, val2 := _icmpPop(frame); val1 == val2 { base.Branch(frame, self.Offset) } } type IF_ICMPNE struct{ base.BranchInstruction } func (self *IF_ICMPNE) Execute(frame *rtda.Frame) { if val1, val2 := _icmpPop(frame); val1 != val2 { base.Branch(frame, self.Offset) } } type IF_ICMPLT struct{ base.BranchInstruction } func (self *IF_ICMPLT) Execute(frame *rtda.Frame) { if val1, val2 := _icmpPop(frame); val1 < val2 { base.Branch(frame, self.Offset) } } type IF_ICMPLE struct{ base.BranchInstruction } func (self *IF_ICMPLE) Execute(frame *rtda.Frame) { if val1, val2 := _icmpPop(frame); val1 <= val2 { base.Branch(frame, self.Offset) } } type IF_ICMPGT struct{ base.BranchInstruction } func (self *IF_ICMPGT) Execute(frame *rtda.Frame) { if val1, val2 := _icmpPop(frame); val1 > val2 { base.Branch(frame, self.Offset) } } type IF_ICMPGE struct{ base.BranchInstruction } func (self *IF_ICMPGE) Execute(frame *rtda.Frame) { if val1, val2 := _icmpPop(frame); val1 >= val2 { base.Branch(frame, self.Offset) } } func _icmpPop(frame *rtda.Frame) (val1, val2 int32) { stack := frame.OperandStack() val2 = stack.PopInt() val1 = stack.PopInt() return } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/instructions/comparisons/if_icmp.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
430
```go package classfile /* SourceFile_attribute { u2 attribute_name_index; u4 attribute_length; u2 sourcefile_index; } */ type SourceFileAttribute struct { cp ConstantPool sourceFileIndex uint16 } func (self *SourceFileAttribute) readInfo(reader *ClassReader) { self.sourceFileIndex = reader.readUint16() } func (self *SourceFileAttribute) FileName() string { return self.cp.getUtf8(self.sourceFileIndex) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/classfile/attr_source_file.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
101
```go package references import "jvmgo/ch11/instructions/base" import "jvmgo/ch11/rtda" import "jvmgo/ch11/rtda/heap" // Invoke instance method; // special handling for superclass, private, and instance initialization method invocations type INVOKE_SPECIAL struct{ base.Index16Instruction } func (self *INVOKE_SPECIAL) Execute(frame *rtda.Frame) { currentClass := frame.Method().Class() cp := currentClass.ConstantPool() methodRef := cp.GetConstant(self.Index).(*heap.MethodRef) resolvedClass := methodRef.ResolvedClass() resolvedMethod := methodRef.ResolvedMethod() if resolvedMethod.Name() == "<init>" && resolvedMethod.Class() != resolvedClass { panic("java.lang.NoSuchMethodError") } if resolvedMethod.IsStatic() { panic("java.lang.IncompatibleClassChangeError") } ref := frame.OperandStack().GetRefFromTop(resolvedMethod.ArgSlotCount() - 1) if ref == nil { panic("java.lang.NullPointerException") } if resolvedMethod.IsProtected() && resolvedMethod.Class().IsSuperClassOf(currentClass) && resolvedMethod.Class().GetPackageName() != currentClass.GetPackageName() && ref.Class() != currentClass && !ref.Class().IsSubClassOf(currentClass) { panic("java.lang.IllegalAccessError") } methodToBeInvoked := resolvedMethod if currentClass.IsSuper() && resolvedClass.IsSuperClassOf(currentClass) && resolvedMethod.Name() != "<init>" { methodToBeInvoked = heap.LookupMethodInClass(currentClass.SuperClass(), methodRef.Name(), methodRef.Descriptor()) } if methodToBeInvoked == nil || methodToBeInvoked.IsAbstract() { panic("java.lang.AbstractMethodError") } base.InvokeMethod(frame, methodToBeInvoked) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/instructions/references/invokespecial.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
403
```go package constants import "jvmgo/ch11/instructions/base" import "jvmgo/ch11/rtda" // Do nothing type NOP struct{ base.NoOperandsInstruction } func (self *NOP) Execute(frame *rtda.Frame) { // really do nothing } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/instructions/constants/nop.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
62
```shell #!/bin/sh set -ex cd v1/code/java/jvmgo_java # export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home/ sh gradlew ch01:run --args ' -version' | grep -q "1.8.0" sh gradlew ch02:run --args ' java.lang.Object' | grep -q "class data" sh gradlew ch03:run --args ' java.lang.Object' | grep -q "this class: java/lang/Object" # sh gradlew ch04:run --args ' java.lang.Object' 2>&1 | grep -q "100" # sh gradlew ch05:run --args ' -cp ../java/example.jar jvmgo.book.ch05.GaussTest' 2>&1 | grep -q "5050" # sh gradlew ch06:run --args ' -cp ../java/example.jar jvmgo.book.ch06.MyObject' | grep -q "32768" # sh gradlew ch07:run --args ' -cp ../java/example.jar jvmgo.book.ch07.FibonacciTest' | grep -q "832040" # sh gradlew ch08:run --args ' -cp ../java/example.jar jvmgo.book.ch01.HelloWorld' | grep -q "Hello, world!" # sh gradlew ch08:run --args ' -cp ../java/example.jar jvmgo.book.ch08.PrintArgs foo bar' | tr -d '\n' | grep -q "foobar" # sh gradlew ch09:run --args ' -cp ../java/example.jar jvmgo.book.ch09.GetClassTest' | grep -q "Ljava.lang.String;" # sh gradlew ch09:run --args ' -cp ../java/example.jar jvmgo.book.ch09.StringTest' | tr -d '\n' | grep -q "truefalsetrue" # sh gradlew ch09:run --args ' -cp ../java/example.jar jvmgo.book.ch09.ObjectTest' | tr -d '\n' | grep -q "falsetrue" # sh gradlew ch09:run --args ' -cp ../java/example.jar jvmgo.book.ch09.CloneTest' | grep -q "3.14" # sh gradlew ch09:run --args ' -cp ../java/example.jar jvmgo.book.ch09.BoxTest' | grep -q "1, 2, 3" # sh gradlew ch10:run --args ' -cp ../java/example.jar jvmgo.book.ch10.ParseIntTest 123' | grep -q "123" # sh gradlew ch10:run --args ' -cp ../java/example.jar jvmgo.book.ch10.ParseIntTest abc' 2>&1 | grep 'For input string: "abc"' # sh gradlew ch10:run --args ' -cp ../java/example.jar jvmgo.book.ch10.ParseIntTest' 2>&1 | grep -q "at jvmgo" # sh gradlew ch11:run --args ' -cp ../java/example.jar jvmgo.book.ch01.HelloWorld' | grep -q "Hello, world!" echo OK ```
/content/code_sandbox/test_java.sh
shell
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
687
```go package main import "fmt" import "strings" import "jvmgo/ch11/classpath" import "jvmgo/ch11/instructions/base" import "jvmgo/ch11/rtda" import "jvmgo/ch11/rtda/heap" type JVM struct { cmd *Cmd classLoader *heap.ClassLoader mainThread *rtda.Thread } func newJVM(cmd *Cmd) *JVM { cp := classpath.Parse(cmd.XjreOption, cmd.cpOption) classLoader := heap.NewClassLoader(cp, cmd.verboseClassFlag) return &JVM{ cmd: cmd, classLoader: classLoader, mainThread: rtda.NewThread(), } } func (self *JVM) start() { self.initVM() self.execMain() } func (self *JVM) initVM() { vmClass := self.classLoader.LoadClass("sun/misc/VM") base.InitClass(self.mainThread, vmClass) interpret(self.mainThread, self.cmd.verboseInstFlag) } func (self *JVM) execMain() { className := strings.Replace(self.cmd.class, ".", "/", -1) mainClass := self.classLoader.LoadClass(className) mainMethod := mainClass.GetMainMethod() if mainMethod == nil { fmt.Printf("Main method not found in class %s\n", self.cmd.class) return } argsArr := self.createArgsArray() frame := self.mainThread.NewFrame(mainMethod) frame.LocalVars().SetRef(0, argsArr) self.mainThread.PushFrame(frame) interpret(self.mainThread, self.cmd.verboseInstFlag) } func (self *JVM) createArgsArray() *heap.Object { stringClass := self.classLoader.LoadClass("java/lang/String") argsLen := uint(len(self.cmd.args)) argsArr := stringClass.ArrayClass().NewArray(argsLen) jArgs := argsArr.Refs() for i, arg := range self.cmd.args { jArgs[i] = heap.JString(self.classLoader, arg) } return argsArr } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/jvm.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
434
```go package conversions import "jvmgo/ch11/instructions/base" import "jvmgo/ch11/rtda" // Convert long to double type L2D struct{ base.NoOperandsInstruction } func (self *L2D) Execute(frame *rtda.Frame) { stack := frame.OperandStack() l := stack.PopLong() d := float64(l) stack.PushDouble(d) } // Convert long to float type L2F struct{ base.NoOperandsInstruction } func (self *L2F) Execute(frame *rtda.Frame) { stack := frame.OperandStack() l := stack.PopLong() f := float32(l) stack.PushFloat(f) } // Convert long to int type L2I struct{ base.NoOperandsInstruction } func (self *L2I) Execute(frame *rtda.Frame) { stack := frame.OperandStack() l := stack.PopLong() i := int32(l) stack.PushInt(i) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/instructions/conversions/l2x.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
206
```go package references import "jvmgo/ch11/instructions/base" import "jvmgo/ch11/rtda" import "jvmgo/ch11/rtda/heap" // Fetch field from object type GET_FIELD struct{ base.Index16Instruction } func (self *GET_FIELD) Execute(frame *rtda.Frame) { cp := frame.Method().Class().ConstantPool() fieldRef := cp.GetConstant(self.Index).(*heap.FieldRef) field := fieldRef.ResolvedField() if field.IsStatic() { panic("java.lang.IncompatibleClassChangeError") } stack := frame.OperandStack() ref := stack.PopRef() if ref == nil { panic("java.lang.NullPointerException") } descriptor := field.Descriptor() slotId := field.SlotId() slots := ref.Fields() switch descriptor[0] { case 'Z', 'B', 'C', 'S', 'I': stack.PushInt(slots.GetInt(slotId)) case 'F': stack.PushFloat(slots.GetFloat(slotId)) case 'J': stack.PushLong(slots.GetLong(slotId)) case 'D': stack.PushDouble(slots.GetDouble(slotId)) case 'L', '[': stack.PushRef(slots.GetRef(slotId)) default: // todo } } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/instructions/references/getfield.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
275
```go package math import "jvmgo/ch11/instructions/base" import "jvmgo/ch11/rtda" // Add double type DADD struct{ base.NoOperandsInstruction } func (self *DADD) Execute(frame *rtda.Frame) { stack := frame.OperandStack() v1 := stack.PopDouble() v2 := stack.PopDouble() result := v1 + v2 stack.PushDouble(result) } // Add float type FADD struct{ base.NoOperandsInstruction } func (self *FADD) Execute(frame *rtda.Frame) { stack := frame.OperandStack() v2 := stack.PopFloat() v1 := stack.PopFloat() result := v1 + v2 stack.PushFloat(result) } // Add int type IADD struct{ base.NoOperandsInstruction } func (self *IADD) Execute(frame *rtda.Frame) { stack := frame.OperandStack() v2 := stack.PopInt() v1 := stack.PopInt() result := v1 + v2 stack.PushInt(result) } // Add long type LADD struct{ base.NoOperandsInstruction } func (self *LADD) Execute(frame *rtda.Frame) { stack := frame.OperandStack() v2 := stack.PopLong() v1 := stack.PopLong() result := v1 + v2 stack.PushLong(result) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/instructions/math/add.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
290
```go package loads import "jvmgo/ch11/instructions/base" import "jvmgo/ch11/rtda" // Load reference from local variable type ALOAD struct{ base.Index8Instruction } func (self *ALOAD) Execute(frame *rtda.Frame) { _aload(frame, self.Index) } type ALOAD_0 struct{ base.NoOperandsInstruction } func (self *ALOAD_0) Execute(frame *rtda.Frame) { _aload(frame, 0) } type ALOAD_1 struct{ base.NoOperandsInstruction } func (self *ALOAD_1) Execute(frame *rtda.Frame) { _aload(frame, 1) } type ALOAD_2 struct{ base.NoOperandsInstruction } func (self *ALOAD_2) Execute(frame *rtda.Frame) { _aload(frame, 2) } type ALOAD_3 struct{ base.NoOperandsInstruction } func (self *ALOAD_3) Execute(frame *rtda.Frame) { _aload(frame, 3) } func _aload(frame *rtda.Frame, index uint) { ref := frame.LocalVars().GetRef(index) frame.OperandStack().PushRef(ref) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/instructions/loads/aload.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
262
```go package constants import "jvmgo/ch11/instructions/base" import "jvmgo/ch11/rtda" // Push null type ACONST_NULL struct{ base.NoOperandsInstruction } func (self *ACONST_NULL) Execute(frame *rtda.Frame) { frame.OperandStack().PushRef(nil) } // Push double type DCONST_0 struct{ base.NoOperandsInstruction } func (self *DCONST_0) Execute(frame *rtda.Frame) { frame.OperandStack().PushDouble(0.0) } type DCONST_1 struct{ base.NoOperandsInstruction } func (self *DCONST_1) Execute(frame *rtda.Frame) { frame.OperandStack().PushDouble(1.0) } // Push float type FCONST_0 struct{ base.NoOperandsInstruction } func (self *FCONST_0) Execute(frame *rtda.Frame) { frame.OperandStack().PushFloat(0.0) } type FCONST_1 struct{ base.NoOperandsInstruction } func (self *FCONST_1) Execute(frame *rtda.Frame) { frame.OperandStack().PushFloat(1.0) } type FCONST_2 struct{ base.NoOperandsInstruction } func (self *FCONST_2) Execute(frame *rtda.Frame) { frame.OperandStack().PushFloat(2.0) } // Push int constant type ICONST_M1 struct{ base.NoOperandsInstruction } func (self *ICONST_M1) Execute(frame *rtda.Frame) { frame.OperandStack().PushInt(-1) } type ICONST_0 struct{ base.NoOperandsInstruction } func (self *ICONST_0) Execute(frame *rtda.Frame) { frame.OperandStack().PushInt(0) } type ICONST_1 struct{ base.NoOperandsInstruction } func (self *ICONST_1) Execute(frame *rtda.Frame) { frame.OperandStack().PushInt(1) } type ICONST_2 struct{ base.NoOperandsInstruction } func (self *ICONST_2) Execute(frame *rtda.Frame) { frame.OperandStack().PushInt(2) } type ICONST_3 struct{ base.NoOperandsInstruction } func (self *ICONST_3) Execute(frame *rtda.Frame) { frame.OperandStack().PushInt(3) } type ICONST_4 struct{ base.NoOperandsInstruction } func (self *ICONST_4) Execute(frame *rtda.Frame) { frame.OperandStack().PushInt(4) } type ICONST_5 struct{ base.NoOperandsInstruction } func (self *ICONST_5) Execute(frame *rtda.Frame) { frame.OperandStack().PushInt(5) } // Push long constant type LCONST_0 struct{ base.NoOperandsInstruction } func (self *LCONST_0) Execute(frame *rtda.Frame) { frame.OperandStack().PushLong(0) } type LCONST_1 struct{ base.NoOperandsInstruction } func (self *LCONST_1) Execute(frame *rtda.Frame) { frame.OperandStack().PushLong(1) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/instructions/constants/const.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
688
```go package references import "jvmgo/ch11/instructions/base" import "jvmgo/ch11/rtda" // Enter monitor for object type MONITOR_ENTER struct{ base.NoOperandsInstruction } // todo func (self *MONITOR_ENTER) Execute(frame *rtda.Frame) { ref := frame.OperandStack().PopRef() if ref == nil { panic("java.lang.NullPointerException") } } // Exit monitor for object type MONITOR_EXIT struct{ base.NoOperandsInstruction } // todo func (self *MONITOR_EXIT) Execute(frame *rtda.Frame) { ref := frame.OperandStack().PopRef() if ref == nil { panic("java.lang.NullPointerException") } } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/instructions/references/monitor.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
154
```go package references import "jvmgo/ch11/instructions/base" import "jvmgo/ch11/rtda" import "jvmgo/ch11/rtda/heap" // Create new multidimensional array type MULTI_ANEW_ARRAY struct { index uint16 dimensions uint8 } func (self *MULTI_ANEW_ARRAY) FetchOperands(reader *base.BytecodeReader) { self.index = reader.ReadUint16() self.dimensions = reader.ReadUint8() } func (self *MULTI_ANEW_ARRAY) Execute(frame *rtda.Frame) { cp := frame.Method().Class().ConstantPool() classRef := cp.GetConstant(uint(self.index)).(*heap.ClassRef) arrClass := classRef.ResolvedClass() stack := frame.OperandStack() counts := popAndCheckCounts(stack, int(self.dimensions)) arr := newMultiDimensionalArray(counts, arrClass) stack.PushRef(arr) } func popAndCheckCounts(stack *rtda.OperandStack, dimensions int) []int32 { counts := make([]int32, dimensions) for i := dimensions - 1; i >= 0; i-- { counts[i] = stack.PopInt() if counts[i] < 0 { panic("java.lang.NegativeArraySizeException") } } return counts } func newMultiDimensionalArray(counts []int32, arrClass *heap.Class) *heap.Object { count := uint(counts[0]) arr := arrClass.NewArray(count) if len(counts) > 1 { refs := arr.Refs() for i := range refs { refs[i] = newMultiDimensionalArray(counts[1:], arrClass.ComponentClass()) } } return arr } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/instructions/references/multianewarray.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
373
```go package classfile /* ConstantValue_attribute { u2 attribute_name_index; u4 attribute_length; u2 constantvalue_index; } */ type ConstantValueAttribute struct { constantValueIndex uint16 } func (self *ConstantValueAttribute) readInfo(reader *ClassReader) { self.constantValueIndex = reader.readUint16() } func (self *ConstantValueAttribute) ConstantValueIndex() uint16 { return self.constantValueIndex } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/classfile/attr_constant_value.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
95
```go package classfile /* EnclosingMethod_attribute { u2 attribute_name_index; u4 attribute_length; u2 class_index; u2 method_index; } */ type EnclosingMethodAttribute struct { cp ConstantPool classIndex uint16 methodIndex uint16 } func (self *EnclosingMethodAttribute) readInfo(reader *ClassReader) { self.classIndex = reader.readUint16() self.methodIndex = reader.readUint16() } func (self *EnclosingMethodAttribute) ClassName() string { return self.cp.getClassName(self.classIndex) } func (self *EnclosingMethodAttribute) MethodNameAndDescriptor() (string, string) { if self.methodIndex > 0 { return self.cp.getNameAndType(self.methodIndex) } else { return "", "" } } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/classfile/attr_enclosing_method.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
170
```go package loads import "jvmgo/ch11/instructions/base" import "jvmgo/ch11/rtda" // Load long from local variable type LLOAD struct{ base.Index8Instruction } func (self *LLOAD) Execute(frame *rtda.Frame) { _lload(frame, self.Index) } type LLOAD_0 struct{ base.NoOperandsInstruction } func (self *LLOAD_0) Execute(frame *rtda.Frame) { _lload(frame, 0) } type LLOAD_1 struct{ base.NoOperandsInstruction } func (self *LLOAD_1) Execute(frame *rtda.Frame) { _lload(frame, 1) } type LLOAD_2 struct{ base.NoOperandsInstruction } func (self *LLOAD_2) Execute(frame *rtda.Frame) { _lload(frame, 2) } type LLOAD_3 struct{ base.NoOperandsInstruction } func (self *LLOAD_3) Execute(frame *rtda.Frame) { _lload(frame, 3) } func _lload(frame *rtda.Frame, index uint) { val := frame.LocalVars().GetLong(index) frame.OperandStack().PushLong(val) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/instructions/loads/lload.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
263
```go package math import "jvmgo/ch11/instructions/base" import "jvmgo/ch11/rtda" // Boolean OR int type IOR struct{ base.NoOperandsInstruction } func (self *IOR) Execute(frame *rtda.Frame) { stack := frame.OperandStack() v2 := stack.PopInt() v1 := stack.PopInt() result := v1 | v2 stack.PushInt(result) } // Boolean OR long type LOR struct{ base.NoOperandsInstruction } func (self *LOR) Execute(frame *rtda.Frame) { stack := frame.OperandStack() v2 := stack.PopLong() v1 := stack.PopLong() result := v1 | v2 stack.PushLong(result) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/instructions/math/or.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
159
```go package loads import "jvmgo/ch11/instructions/base" import "jvmgo/ch11/rtda" // Load double from local variable type DLOAD struct{ base.Index8Instruction } func (self *DLOAD) Execute(frame *rtda.Frame) { _dload(frame, self.Index) } type DLOAD_0 struct{ base.NoOperandsInstruction } func (self *DLOAD_0) Execute(frame *rtda.Frame) { _dload(frame, 0) } type DLOAD_1 struct{ base.NoOperandsInstruction } func (self *DLOAD_1) Execute(frame *rtda.Frame) { _dload(frame, 1) } type DLOAD_2 struct{ base.NoOperandsInstruction } func (self *DLOAD_2) Execute(frame *rtda.Frame) { _dload(frame, 2) } type DLOAD_3 struct{ base.NoOperandsInstruction } func (self *DLOAD_3) Execute(frame *rtda.Frame) { _dload(frame, 3) } func _dload(frame *rtda.Frame, index uint) { val := frame.LocalVars().GetDouble(index) frame.OperandStack().PushDouble(val) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/instructions/loads/dload.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
263
```go package classfile /* Deprecated_attribute { u2 attribute_name_index; u4 attribute_length; } */ type DeprecatedAttribute struct { MarkerAttribute } /* Synthetic_attribute { u2 attribute_name_index; u4 attribute_length; } */ type SyntheticAttribute struct { MarkerAttribute } type MarkerAttribute struct{} func (self *MarkerAttribute) readInfo(reader *ClassReader) { // read nothing } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/classfile/attr_markers.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
90
```go package references import "jvmgo/ch11/instructions/base" import "jvmgo/ch11/rtda" import "jvmgo/ch11/rtda/heap" // Invoke interface method type INVOKE_INTERFACE struct { index uint // count uint8 // zero uint8 } func (self *INVOKE_INTERFACE) FetchOperands(reader *base.BytecodeReader) { self.index = uint(reader.ReadUint16()) reader.ReadUint8() // count reader.ReadUint8() // must be 0 } func (self *INVOKE_INTERFACE) Execute(frame *rtda.Frame) { cp := frame.Method().Class().ConstantPool() methodRef := cp.GetConstant(self.index).(*heap.InterfaceMethodRef) resolvedMethod := methodRef.ResolvedInterfaceMethod() if resolvedMethod.IsStatic() || resolvedMethod.IsPrivate() { panic("java.lang.IncompatibleClassChangeError") } ref := frame.OperandStack().GetRefFromTop(resolvedMethod.ArgSlotCount() - 1) if ref == nil { panic("java.lang.NullPointerException") // todo } if !ref.Class().IsImplements(methodRef.ResolvedClass()) { panic("java.lang.IncompatibleClassChangeError") } methodToBeInvoked := heap.LookupMethodInClass(ref.Class(), methodRef.Name(), methodRef.Descriptor()) if methodToBeInvoked == nil || methodToBeInvoked.IsAbstract() { panic("java.lang.AbstractMethodError") } if !methodToBeInvoked.IsPublic() { panic("java.lang.IllegalAccessError") } base.InvokeMethod(frame, methodToBeInvoked) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/instructions/references/invokeinterface.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
349
```go package math import "jvmgo/ch11/instructions/base" import "jvmgo/ch11/rtda" // Negate double type DNEG struct{ base.NoOperandsInstruction } func (self *DNEG) Execute(frame *rtda.Frame) { stack := frame.OperandStack() val := stack.PopDouble() stack.PushDouble(-val) } // Negate float type FNEG struct{ base.NoOperandsInstruction } func (self *FNEG) Execute(frame *rtda.Frame) { stack := frame.OperandStack() val := stack.PopFloat() stack.PushFloat(-val) } // Negate int type INEG struct{ base.NoOperandsInstruction } func (self *INEG) Execute(frame *rtda.Frame) { stack := frame.OperandStack() val := stack.PopInt() stack.PushInt(-val) } // Negate long type LNEG struct{ base.NoOperandsInstruction } func (self *LNEG) Execute(frame *rtda.Frame) { stack := frame.OperandStack() val := stack.PopLong() stack.PushLong(-val) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/instructions/math/neg.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
234
```go package math import "jvmgo/ch11/instructions/base" import "jvmgo/ch11/rtda" // Divide double type DDIV struct{ base.NoOperandsInstruction } func (self *DDIV) Execute(frame *rtda.Frame) { stack := frame.OperandStack() v2 := stack.PopDouble() v1 := stack.PopDouble() result := v1 / v2 stack.PushDouble(result) } // Divide float type FDIV struct{ base.NoOperandsInstruction } func (self *FDIV) Execute(frame *rtda.Frame) { stack := frame.OperandStack() v2 := stack.PopFloat() v1 := stack.PopFloat() result := v1 / v2 stack.PushFloat(result) } // Divide int type IDIV struct{ base.NoOperandsInstruction } func (self *IDIV) Execute(frame *rtda.Frame) { stack := frame.OperandStack() v2 := stack.PopInt() v1 := stack.PopInt() if v2 == 0 { panic("java.lang.ArithmeticException: / by zero") } result := v1 / v2 stack.PushInt(result) } // Divide long type LDIV struct{ base.NoOperandsInstruction } func (self *LDIV) Execute(frame *rtda.Frame) { stack := frame.OperandStack() v2 := stack.PopLong() v1 := stack.PopLong() if v2 == 0 { panic("java.lang.ArithmeticException: / by zero") } result := v1 / v2 stack.PushLong(result) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/instructions/math/div.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
334
```go package references import "jvmgo/ch11/instructions/base" import "jvmgo/ch11/rtda" import "jvmgo/ch11/rtda/heap" const ( //Array Type atype AT_BOOLEAN = 4 AT_CHAR = 5 AT_FLOAT = 6 AT_DOUBLE = 7 AT_BYTE = 8 AT_SHORT = 9 AT_INT = 10 AT_LONG = 11 ) // Create new array type NEW_ARRAY struct { atype uint8 } func (self *NEW_ARRAY) FetchOperands(reader *base.BytecodeReader) { self.atype = reader.ReadUint8() } func (self *NEW_ARRAY) Execute(frame *rtda.Frame) { stack := frame.OperandStack() count := stack.PopInt() if count < 0 { panic("java.lang.NegativeArraySizeException") } classLoader := frame.Method().Class().Loader() arrClass := getPrimitiveArrayClass(classLoader, self.atype) arr := arrClass.NewArray(uint(count)) stack.PushRef(arr) } func getPrimitiveArrayClass(loader *heap.ClassLoader, atype uint8) *heap.Class { switch atype { case AT_BOOLEAN: return loader.LoadClass("[Z") case AT_BYTE: return loader.LoadClass("[B") case AT_CHAR: return loader.LoadClass("[C") case AT_SHORT: return loader.LoadClass("[S") case AT_INT: return loader.LoadClass("[I") case AT_LONG: return loader.LoadClass("[J") case AT_FLOAT: return loader.LoadClass("[F") case AT_DOUBLE: return loader.LoadClass("[D") default: panic("Invalid atype!") } } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/instructions/references/newarray.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
368
```go package math import "jvmgo/ch11/instructions/base" import "jvmgo/ch11/rtda" // Boolean XOR int type IXOR struct{ base.NoOperandsInstruction } func (self *IXOR) Execute(frame *rtda.Frame) { stack := frame.OperandStack() v1 := stack.PopInt() v2 := stack.PopInt() result := v1 ^ v2 stack.PushInt(result) } // Boolean XOR long type LXOR struct{ base.NoOperandsInstruction } func (self *LXOR) Execute(frame *rtda.Frame) { stack := frame.OperandStack() v1 := stack.PopLong() v2 := stack.PopLong() result := v1 ^ v2 stack.PushLong(result) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/instructions/math/xor.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
161
```go package math import "jvmgo/ch11/instructions/base" import "jvmgo/ch11/rtda" // Subtract double type DSUB struct{ base.NoOperandsInstruction } func (self *DSUB) Execute(frame *rtda.Frame) { stack := frame.OperandStack() v2 := stack.PopDouble() v1 := stack.PopDouble() result := v1 - v2 stack.PushDouble(result) } // Subtract float type FSUB struct{ base.NoOperandsInstruction } func (self *FSUB) Execute(frame *rtda.Frame) { stack := frame.OperandStack() v2 := stack.PopFloat() v1 := stack.PopFloat() result := v1 - v2 stack.PushFloat(result) } // Subtract int type ISUB struct{ base.NoOperandsInstruction } func (self *ISUB) Execute(frame *rtda.Frame) { stack := frame.OperandStack() v2 := stack.PopInt() v1 := stack.PopInt() result := v1 - v2 stack.PushInt(result) } // Subtract long type LSUB struct{ base.NoOperandsInstruction } func (self *LSUB) Execute(frame *rtda.Frame) { stack := frame.OperandStack() v2 := stack.PopLong() v1 := stack.PopLong() result := v1 - v2 stack.PushLong(result) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/instructions/math/sub.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
290
```go package constants import "jvmgo/ch11/instructions/base" import "jvmgo/ch11/rtda" import "jvmgo/ch11/rtda/heap" // Push item from run-time constant pool type LDC struct{ base.Index8Instruction } func (self *LDC) Execute(frame *rtda.Frame) { _ldc(frame, self.Index) } // Push item from run-time constant pool (wide index) type LDC_W struct{ base.Index16Instruction } func (self *LDC_W) Execute(frame *rtda.Frame) { _ldc(frame, self.Index) } func _ldc(frame *rtda.Frame, index uint) { stack := frame.OperandStack() class := frame.Method().Class() c := class.ConstantPool().GetConstant(index) switch c.(type) { case int32: stack.PushInt(c.(int32)) case float32: stack.PushFloat(c.(float32)) case string: internedStr := heap.JString(class.Loader(), c.(string)) stack.PushRef(internedStr) case *heap.ClassRef: classRef := c.(*heap.ClassRef) classObj := classRef.ResolvedClass().JClass() stack.PushRef(classObj) // case MethodType, MethodHandle default: panic("todo: ldc!") } } // Push long or double from run-time constant pool (wide index) type LDC2_W struct{ base.Index16Instruction } func (self *LDC2_W) Execute(frame *rtda.Frame) { stack := frame.OperandStack() cp := frame.Method().Class().ConstantPool() c := cp.GetConstant(self.Index) switch c.(type) { case int64: stack.PushLong(c.(int64)) case float64: stack.PushDouble(c.(float64)) default: panic("java.lang.ClassFormatError") } } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/instructions/constants/ldc.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
403
```go package comparisons import "jvmgo/ch11/instructions/base" import "jvmgo/ch11/rtda" // Branch if reference comparison succeeds type IF_ACMPEQ struct{ base.BranchInstruction } func (self *IF_ACMPEQ) Execute(frame *rtda.Frame) { if _acmp(frame) { base.Branch(frame, self.Offset) } } type IF_ACMPNE struct{ base.BranchInstruction } func (self *IF_ACMPNE) Execute(frame *rtda.Frame) { if !_acmp(frame) { base.Branch(frame, self.Offset) } } func _acmp(frame *rtda.Frame) bool { stack := frame.OperandStack() ref2 := stack.PopRef() ref1 := stack.PopRef() return ref1 == ref2 // todo } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/instructions/comparisons/if_acmp.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
173
```go package control import "jvmgo/ch11/instructions/base" import "jvmgo/ch11/rtda" // Branch always type GOTO struct{ base.BranchInstruction } func (self *GOTO) Execute(frame *rtda.Frame) { base.Branch(frame, self.Offset) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/instructions/control/goto.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
63
```go package classfile // Constant pool tags const ( CONSTANT_Class = 7 CONSTANT_Fieldref = 9 CONSTANT_Methodref = 10 CONSTANT_InterfaceMethodref = 11 CONSTANT_String = 8 CONSTANT_Integer = 3 CONSTANT_Float = 4 CONSTANT_Long = 5 CONSTANT_Double = 6 CONSTANT_NameAndType = 12 CONSTANT_Utf8 = 1 CONSTANT_MethodHandle = 15 CONSTANT_MethodType = 16 CONSTANT_InvokeDynamic = 18 ) /* cp_info { u1 tag; u1 info[]; } */ type ConstantInfo interface { readInfo(reader *ClassReader) } func readConstantInfo(reader *ClassReader, cp ConstantPool) ConstantInfo { tag := reader.readUint8() c := newConstantInfo(tag, cp) c.readInfo(reader) return c } // todo ugly code func newConstantInfo(tag uint8, cp ConstantPool) ConstantInfo { switch tag { case CONSTANT_Integer: return &ConstantIntegerInfo{} case CONSTANT_Float: return &ConstantFloatInfo{} case CONSTANT_Long: return &ConstantLongInfo{} case CONSTANT_Double: return &ConstantDoubleInfo{} case CONSTANT_Utf8: return &ConstantUtf8Info{} case CONSTANT_String: return &ConstantStringInfo{cp: cp} case CONSTANT_Class: return &ConstantClassInfo{cp: cp} case CONSTANT_Fieldref: return &ConstantFieldrefInfo{ConstantMemberrefInfo{cp: cp}} case CONSTANT_Methodref: return &ConstantMethodrefInfo{ConstantMemberrefInfo{cp: cp}} case CONSTANT_InterfaceMethodref: return &ConstantInterfaceMethodrefInfo{ConstantMemberrefInfo{cp: cp}} case CONSTANT_NameAndType: return &ConstantNameAndTypeInfo{} case CONSTANT_MethodType: return &ConstantMethodTypeInfo{} case CONSTANT_MethodHandle: return &ConstantMethodHandleInfo{} case CONSTANT_InvokeDynamic: return &ConstantInvokeDynamicInfo{} default: panic("java.lang.ClassFormatError: constant pool tag!") } } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/classfile/constant_info.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
468
```go package control import "jvmgo/ch11/instructions/base" import "jvmgo/ch11/rtda" // Return void from method type RETURN struct{ base.NoOperandsInstruction } func (self *RETURN) Execute(frame *rtda.Frame) { frame.Thread().PopFrame() } // Return reference from method type ARETURN struct{ base.NoOperandsInstruction } func (self *ARETURN) Execute(frame *rtda.Frame) { thread := frame.Thread() currentFrame := thread.PopFrame() invokerFrame := thread.TopFrame() ref := currentFrame.OperandStack().PopRef() invokerFrame.OperandStack().PushRef(ref) } // Return double from method type DRETURN struct{ base.NoOperandsInstruction } func (self *DRETURN) Execute(frame *rtda.Frame) { thread := frame.Thread() currentFrame := thread.PopFrame() invokerFrame := thread.TopFrame() val := currentFrame.OperandStack().PopDouble() invokerFrame.OperandStack().PushDouble(val) } // Return float from method type FRETURN struct{ base.NoOperandsInstruction } func (self *FRETURN) Execute(frame *rtda.Frame) { thread := frame.Thread() currentFrame := thread.PopFrame() invokerFrame := thread.TopFrame() val := currentFrame.OperandStack().PopFloat() invokerFrame.OperandStack().PushFloat(val) } // Return int from method type IRETURN struct{ base.NoOperandsInstruction } func (self *IRETURN) Execute(frame *rtda.Frame) { thread := frame.Thread() currentFrame := thread.PopFrame() invokerFrame := thread.TopFrame() val := currentFrame.OperandStack().PopInt() invokerFrame.OperandStack().PushInt(val) } // Return double from method type LRETURN struct{ base.NoOperandsInstruction } func (self *LRETURN) Execute(frame *rtda.Frame) { thread := frame.Thread() currentFrame := thread.PopFrame() invokerFrame := thread.TopFrame() val := currentFrame.OperandStack().PopLong() invokerFrame.OperandStack().PushLong(val) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/instructions/control/return.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
454
```go package base import "fmt" import "strings" import "jvmgo/ch11/rtda" import "jvmgo/ch11/rtda/heap" func InvokeMethod(invokerFrame *rtda.Frame, method *heap.Method) { //_logInvoke(callerFrame.Thread().StackDepth(), method) thread := invokerFrame.Thread() newFrame := thread.NewFrame(method) thread.PushFrame(newFrame) argSlotCount := int(method.ArgSlotCount()) if argSlotCount > 0 { for i := argSlotCount - 1; i >= 0; i-- { slot := invokerFrame.OperandStack().PopSlot() newFrame.LocalVars().SetSlot(uint(i), slot) } } } func _logInvoke(stackSize uint, method *heap.Method) { space := strings.Repeat(" ", int(stackSize)) className := method.Class().Name() methodName := method.Name() fmt.Printf("[method]%v %v.%v()\n", space, className, methodName) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/instructions/base/method_invoke_logic.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
218
```go package classfile /* BootstrapMethods_attribute { u2 attribute_name_index; u4 attribute_length; u2 num_bootstrap_methods; { u2 bootstrap_method_ref; u2 num_bootstrap_arguments; u2 bootstrap_arguments[num_bootstrap_arguments]; } bootstrap_methods[num_bootstrap_methods]; } */ type BootstrapMethodsAttribute struct { bootstrapMethods []*BootstrapMethod } func (self *BootstrapMethodsAttribute) readInfo(reader *ClassReader) { numBootstrapMethods := reader.readUint16() self.bootstrapMethods = make([]*BootstrapMethod, numBootstrapMethods) for i := range self.bootstrapMethods { self.bootstrapMethods[i] = &BootstrapMethod{ bootstrapMethodRef: reader.readUint16(), bootstrapArguments: reader.readUint16s(), } } } type BootstrapMethod struct { bootstrapMethodRef uint16 bootstrapArguments []uint16 } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/classfile/attr_bootstrap_methods.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
184
```go package math import "jvmgo/ch11/instructions/base" import "jvmgo/ch11/rtda" // Multiply double type DMUL struct{ base.NoOperandsInstruction } func (self *DMUL) Execute(frame *rtda.Frame) { stack := frame.OperandStack() v2 := stack.PopDouble() v1 := stack.PopDouble() result := v1 * v2 stack.PushDouble(result) } // Multiply float type FMUL struct{ base.NoOperandsInstruction } func (self *FMUL) Execute(frame *rtda.Frame) { stack := frame.OperandStack() v2 := stack.PopFloat() v1 := stack.PopFloat() result := v1 * v2 stack.PushFloat(result) } // Multiply int type IMUL struct{ base.NoOperandsInstruction } func (self *IMUL) Execute(frame *rtda.Frame) { stack := frame.OperandStack() v2 := stack.PopInt() v1 := stack.PopInt() result := v1 * v2 stack.PushInt(result) } // Multiply long type LMUL struct{ base.NoOperandsInstruction } func (self *LMUL) Execute(frame *rtda.Frame) { stack := frame.OperandStack() v2 := stack.PopLong() v1 := stack.PopLong() result := v1 * v2 stack.PushLong(result) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/instructions/math/mul.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
290
```go package comparisons import "jvmgo/ch11/instructions/base" import "jvmgo/ch11/rtda" // Compare double type DCMPG struct{ base.NoOperandsInstruction } func (self *DCMPG) Execute(frame *rtda.Frame) { _dcmp(frame, true) } type DCMPL struct{ base.NoOperandsInstruction } func (self *DCMPL) Execute(frame *rtda.Frame) { _dcmp(frame, false) } func _dcmp(frame *rtda.Frame, gFlag bool) { stack := frame.OperandStack() v2 := stack.PopDouble() v1 := stack.PopDouble() if v1 > v2 { stack.PushInt(1) } else if v1 == v2 { stack.PushInt(0) } else if v1 < v2 { stack.PushInt(-1) } else if gFlag { stack.PushInt(1) } else { stack.PushInt(-1) } } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/instructions/comparisons/dcmp.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
217
```shell #!/bin/sh set -ex cd v1/code/go/src/jvmgo # export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_201.jdk/Contents/Home/ go run jvmgo/ch01 -version | grep -q "version 0.0.1" go run jvmgo/ch02 java.lang.Object | grep -q "class data" go run jvmgo/ch03 java.lang.Object | grep -q "this class: java/lang/Object" go run jvmgo/ch04 java.lang.Object 2>&1 | grep -q "100" go run jvmgo/ch05 -cp ../../../java/example.jar jvmgo.book.ch05.GaussTest 2>&1 | grep -q "5050" go run jvmgo/ch06 -cp ../../../java/example.jar jvmgo.book.ch06.MyObject | grep -q "32768" go run jvmgo/ch07 -cp ../../../java/example.jar jvmgo.book.ch07.FibonacciTest | grep -q "832040" go run jvmgo/ch08 -cp ../../../java/example.jar jvmgo.book.ch01.HelloWorld | grep -q "Hello, world!" go run jvmgo/ch08 -cp ../../../java/example.jar jvmgo.book.ch08.PrintArgs foo bar | tr -d '\n' | grep -q "foobar" go run jvmgo/ch09 -cp ../../../java/example.jar jvmgo.book.ch09.GetClassTest | grep -q "Ljava.lang.String;" go run jvmgo/ch09 -cp ../../../java/example.jar jvmgo.book.ch09.StringTest | tr -d '\n' | grep -q "truefalsetrue" go run jvmgo/ch09 -cp ../../../java/example.jar jvmgo.book.ch09.ObjectTest | tr -d '\n' | grep -q "falsetrue" go run jvmgo/ch09 -cp ../../../java/example.jar jvmgo.book.ch09.CloneTest | grep -q "3.14" go run jvmgo/ch09 -cp ../../../java/example.jar jvmgo.book.ch09.BoxTest | grep -q "1, 2, 3" go run jvmgo/ch10 -cp ../../../java/example.jar jvmgo.book.ch10.ParseIntTest 123 | grep -q "123" go run jvmgo/ch10 -cp ../../../java/example.jar jvmgo.book.ch10.ParseIntTest abc 2>&1 | grep 'For input string: "abc"' go run jvmgo/ch10 -cp ../../../java/example.jar jvmgo.book.ch10.ParseIntTest 2>&1 | grep -q "at jvmgo" go run jvmgo/ch11 -cp ../../../java/example.jar jvmgo.book.ch01.HelloWorld | grep -q "Hello, world!" echo OK ```
/content/code_sandbox/test.sh
shell
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
604
```go package references import "jvmgo/ch11/instructions/base" import "jvmgo/ch11/rtda" // Get length of array type ARRAY_LENGTH struct{ base.NoOperandsInstruction } func (self *ARRAY_LENGTH) Execute(frame *rtda.Frame) { stack := frame.OperandStack() arrRef := stack.PopRef() if arrRef == nil { panic("java.lang.NullPointerException") } arrLen := arrRef.ArrayLength() stack.PushInt(arrLen) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/instructions/references/arraylength.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
104
```go package loads import "jvmgo/ch11/instructions/base" import "jvmgo/ch11/rtda" // Load int from local variable type ILOAD struct{ base.Index8Instruction } func (self *ILOAD) Execute(frame *rtda.Frame) { _iload(frame, self.Index) } type ILOAD_0 struct{ base.NoOperandsInstruction } func (self *ILOAD_0) Execute(frame *rtda.Frame) { _iload(frame, 0) } type ILOAD_1 struct{ base.NoOperandsInstruction } func (self *ILOAD_1) Execute(frame *rtda.Frame) { _iload(frame, 1) } type ILOAD_2 struct{ base.NoOperandsInstruction } func (self *ILOAD_2) Execute(frame *rtda.Frame) { _iload(frame, 2) } type ILOAD_3 struct{ base.NoOperandsInstruction } func (self *ILOAD_3) Execute(frame *rtda.Frame) { _iload(frame, 3) } func _iload(frame *rtda.Frame, index uint) { val := frame.LocalVars().GetInt(index) frame.OperandStack().PushInt(val) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/instructions/loads/iload.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
262
```go package base type BytecodeReader struct { code []byte // bytecodes pc int } func (self *BytecodeReader) Reset(code []byte, pc int) { self.code = code self.pc = pc } func (self *BytecodeReader) PC() int { return self.pc } func (self *BytecodeReader) ReadInt8() int8 { return int8(self.ReadUint8()) } func (self *BytecodeReader) ReadUint8() uint8 { i := self.code[self.pc] self.pc++ return i } func (self *BytecodeReader) ReadInt16() int16 { return int16(self.ReadUint16()) } func (self *BytecodeReader) ReadUint16() uint16 { byte1 := uint16(self.ReadUint8()) byte2 := uint16(self.ReadUint8()) return (byte1 << 8) | byte2 } func (self *BytecodeReader) ReadInt32() int32 { byte1 := int32(self.ReadUint8()) byte2 := int32(self.ReadUint8()) byte3 := int32(self.ReadUint8()) byte4 := int32(self.ReadUint8()) return (byte1 << 24) | (byte2 << 16) | (byte3 << 8) | byte4 } // used by lookupswitch and tableswitch func (self *BytecodeReader) ReadInt32s(n int32) []int32 { ints := make([]int32, n) for i := range ints { ints[i] = self.ReadInt32() } return ints } // used by lookupswitch and tableswitch func (self *BytecodeReader) SkipPadding() { for self.pc%4 != 0 { self.ReadUint8() } } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/instructions/base/bytecode_reader.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
376
```go package stores import "jvmgo/ch11/instructions/base" import "jvmgo/ch11/rtda" // Store float into local variable type FSTORE struct{ base.Index8Instruction } func (self *FSTORE) Execute(frame *rtda.Frame) { _fstore(frame, uint(self.Index)) } type FSTORE_0 struct{ base.NoOperandsInstruction } func (self *FSTORE_0) Execute(frame *rtda.Frame) { _fstore(frame, 0) } type FSTORE_1 struct{ base.NoOperandsInstruction } func (self *FSTORE_1) Execute(frame *rtda.Frame) { _fstore(frame, 1) } type FSTORE_2 struct{ base.NoOperandsInstruction } func (self *FSTORE_2) Execute(frame *rtda.Frame) { _fstore(frame, 2) } type FSTORE_3 struct{ base.NoOperandsInstruction } func (self *FSTORE_3) Execute(frame *rtda.Frame) { _fstore(frame, 3) } func _fstore(frame *rtda.Frame, index uint) { val := frame.OperandStack().PopFloat() frame.LocalVars().SetFloat(index, val) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/instructions/stores/fstore.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
265
```go package classfile import "fmt" /* ClassFile { u4 magic; u2 minor_version; u2 major_version; u2 constant_pool_count; cp_info constant_pool[constant_pool_count-1]; u2 access_flags; u2 this_class; u2 super_class; u2 interfaces_count; u2 interfaces[interfaces_count]; u2 fields_count; field_info fields[fields_count]; u2 methods_count; method_info methods[methods_count]; u2 attributes_count; attribute_info attributes[attributes_count]; } */ type ClassFile struct { //magic uint32 minorVersion uint16 majorVersion uint16 constantPool ConstantPool accessFlags uint16 thisClass uint16 superClass uint16 interfaces []uint16 fields []*MemberInfo methods []*MemberInfo attributes []AttributeInfo } func Parse(classData []byte) (cf *ClassFile, err error) { defer func() { if r := recover(); r != nil { var ok bool err, ok = r.(error) if !ok { err = fmt.Errorf("%v", r) } } }() cr := &ClassReader{classData} cf = &ClassFile{} cf.read(cr) return } func (self *ClassFile) read(reader *ClassReader) { self.readAndCheckMagic(reader) self.readAndCheckVersion(reader) self.constantPool = readConstantPool(reader) self.accessFlags = reader.readUint16() self.thisClass = reader.readUint16() self.superClass = reader.readUint16() self.interfaces = reader.readUint16s() self.fields = readMembers(reader, self.constantPool) self.methods = readMembers(reader, self.constantPool) self.attributes = readAttributes(reader, self.constantPool) } func (self *ClassFile) readAndCheckMagic(reader *ClassReader) { magic := reader.readUint32() if magic != 0xCAFEBABE { panic("java.lang.ClassFormatError: magic!") } } func (self *ClassFile) readAndCheckVersion(reader *ClassReader) { self.minorVersion = reader.readUint16() self.majorVersion = reader.readUint16() switch self.majorVersion { case 45: return case 46, 47, 48, 49, 50, 51, 52: if self.minorVersion == 0 { return } } panic("java.lang.UnsupportedClassVersionError!") } func (self *ClassFile) MinorVersion() uint16 { return self.minorVersion } func (self *ClassFile) MajorVersion() uint16 { return self.majorVersion } func (self *ClassFile) ConstantPool() ConstantPool { return self.constantPool } func (self *ClassFile) AccessFlags() uint16 { return self.accessFlags } func (self *ClassFile) Fields() []*MemberInfo { return self.fields } func (self *ClassFile) Methods() []*MemberInfo { return self.methods } func (self *ClassFile) ClassName() string { return self.constantPool.getClassName(self.thisClass) } func (self *ClassFile) SuperClassName() string { if self.superClass > 0 { return self.constantPool.getClassName(self.superClass) } return "" } func (self *ClassFile) InterfaceNames() []string { interfaceNames := make([]string, len(self.interfaces)) for i, cpIndex := range self.interfaces { interfaceNames[i] = self.constantPool.getClassName(cpIndex) } return interfaceNames } func (self *ClassFile) SourceFileAttribute() *SourceFileAttribute { for _, attrInfo := range self.attributes { switch attrInfo.(type) { case *SourceFileAttribute: return attrInfo.(*SourceFileAttribute) } } return nil } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/classfile/class_file.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
845
```go package classfile import "math" /* CONSTANT_Integer_info { u1 tag; u4 bytes; } */ type ConstantIntegerInfo struct { val int32 } func (self *ConstantIntegerInfo) readInfo(reader *ClassReader) { bytes := reader.readUint32() self.val = int32(bytes) } func (self *ConstantIntegerInfo) Value() int32 { return self.val } /* CONSTANT_Float_info { u1 tag; u4 bytes; } */ type ConstantFloatInfo struct { val float32 } func (self *ConstantFloatInfo) readInfo(reader *ClassReader) { bytes := reader.readUint32() self.val = math.Float32frombits(bytes) } func (self *ConstantFloatInfo) Value() float32 { return self.val } /* CONSTANT_Long_info { u1 tag; u4 high_bytes; u4 low_bytes; } */ type ConstantLongInfo struct { val int64 } func (self *ConstantLongInfo) readInfo(reader *ClassReader) { bytes := reader.readUint64() self.val = int64(bytes) } func (self *ConstantLongInfo) Value() int64 { return self.val } /* CONSTANT_Double_info { u1 tag; u4 high_bytes; u4 low_bytes; } */ type ConstantDoubleInfo struct { val float64 } func (self *ConstantDoubleInfo) readInfo(reader *ClassReader) { bytes := reader.readUint64() self.val = math.Float64frombits(bytes) } func (self *ConstantDoubleInfo) Value() float64 { return self.val } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/classfile/cp_numeric.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
341
```go package stores import "jvmgo/ch11/instructions/base" import "jvmgo/ch11/rtda" // Store double into local variable type DSTORE struct{ base.Index8Instruction } func (self *DSTORE) Execute(frame *rtda.Frame) { _dstore(frame, uint(self.Index)) } type DSTORE_0 struct{ base.NoOperandsInstruction } func (self *DSTORE_0) Execute(frame *rtda.Frame) { _dstore(frame, 0) } type DSTORE_1 struct{ base.NoOperandsInstruction } func (self *DSTORE_1) Execute(frame *rtda.Frame) { _dstore(frame, 1) } type DSTORE_2 struct{ base.NoOperandsInstruction } func (self *DSTORE_2) Execute(frame *rtda.Frame) { _dstore(frame, 2) } type DSTORE_3 struct{ base.NoOperandsInstruction } func (self *DSTORE_3) Execute(frame *rtda.Frame) { _dstore(frame, 3) } func _dstore(frame *rtda.Frame, index uint) { val := frame.OperandStack().PopDouble() frame.LocalVars().SetDouble(index, val) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/instructions/stores/dstore.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
265
```go package stores import "jvmgo/ch11/instructions/base" import "jvmgo/ch11/rtda" // Store reference into local variable type ASTORE struct{ base.Index8Instruction } func (self *ASTORE) Execute(frame *rtda.Frame) { _astore(frame, uint(self.Index)) } type ASTORE_0 struct{ base.NoOperandsInstruction } func (self *ASTORE_0) Execute(frame *rtda.Frame) { _astore(frame, 0) } type ASTORE_1 struct{ base.NoOperandsInstruction } func (self *ASTORE_1) Execute(frame *rtda.Frame) { _astore(frame, 1) } type ASTORE_2 struct{ base.NoOperandsInstruction } func (self *ASTORE_2) Execute(frame *rtda.Frame) { _astore(frame, 2) } type ASTORE_3 struct{ base.NoOperandsInstruction } func (self *ASTORE_3) Execute(frame *rtda.Frame) { _astore(frame, 3) } func _astore(frame *rtda.Frame, index uint) { ref := frame.OperandStack().PopRef() frame.LocalVars().SetRef(index, ref) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/instructions/stores/astore.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
265
```go package classfile import "fmt" import "unicode/utf16" /* CONSTANT_Utf8_info { u1 tag; u2 length; u1 bytes[length]; } */ type ConstantUtf8Info struct { str string } func (self *ConstantUtf8Info) readInfo(reader *ClassReader) { length := uint32(reader.readUint16()) bytes := reader.readBytes(length) self.str = decodeMUTF8(bytes) } func (self *ConstantUtf8Info) Str() string { return self.str } /* func decodeMUTF8(bytes []byte) string { return string(bytes) // not correct! } */ // mutf8 -> utf16 -> utf32 -> string // see java.io.DataInputStream.readUTF(DataInput) func decodeMUTF8(bytearr []byte) string { utflen := len(bytearr) chararr := make([]uint16, utflen) var c, char2, char3 uint16 count := 0 chararr_count := 0 for count < utflen { c = uint16(bytearr[count]) if c > 127 { break } count++ chararr[chararr_count] = c chararr_count++ } for count < utflen { c = uint16(bytearr[count]) switch c >> 4 { case 0, 1, 2, 3, 4, 5, 6, 7: /* 0xxxxxxx*/ count++ chararr[chararr_count] = c chararr_count++ case 12, 13: /* 110x xxxx 10xx xxxx*/ count += 2 if count > utflen { panic("malformed input: partial character at end") } char2 = uint16(bytearr[count-1]) if char2&0xC0 != 0x80 { panic(fmt.Errorf("malformed input around byte %v", count)) } chararr[chararr_count] = c&0x1F<<6 | char2&0x3F chararr_count++ case 14: /* 1110 xxxx 10xx xxxx 10xx xxxx*/ count += 3 if count > utflen { panic("malformed input: partial character at end") } char2 = uint16(bytearr[count-2]) char3 = uint16(bytearr[count-1]) if char2&0xC0 != 0x80 || char3&0xC0 != 0x80 { panic(fmt.Errorf("malformed input around byte %v", (count - 1))) } chararr[chararr_count] = c&0x0F<<12 | char2&0x3F<<6 | char3&0x3F<<0 chararr_count++ default: /* 10xx xxxx, 1111 xxxx */ panic(fmt.Errorf("malformed input around byte %v", count)) } } // The number of chars produced may be less than utflen chararr = chararr[0:chararr_count] runes := utf16.Decode(chararr) return string(runes) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/classfile/cp_utf8.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
702
```go package references import "jvmgo/ch11/instructions/base" import "jvmgo/ch11/rtda" import "jvmgo/ch11/rtda/heap" // Get static field from class type GET_STATIC struct{ base.Index16Instruction } func (self *GET_STATIC) Execute(frame *rtda.Frame) { cp := frame.Method().Class().ConstantPool() fieldRef := cp.GetConstant(self.Index).(*heap.FieldRef) field := fieldRef.ResolvedField() class := field.Class() if !class.InitStarted() { frame.RevertNextPC() base.InitClass(frame.Thread(), class) return } if !field.IsStatic() { panic("java.lang.IncompatibleClassChangeError") } descriptor := field.Descriptor() slotId := field.SlotId() slots := class.StaticVars() stack := frame.OperandStack() switch descriptor[0] { case 'Z', 'B', 'C', 'S', 'I': stack.PushInt(slots.GetInt(slotId)) case 'F': stack.PushFloat(slots.GetFloat(slotId)) case 'J': stack.PushLong(slots.GetLong(slotId)) case 'D': stack.PushDouble(slots.GetDouble(slotId)) case 'L', '[': stack.PushRef(slots.GetRef(slotId)) default: // todo } } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/instructions/references/getstatic.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
290
```go package references import "jvmgo/ch11/instructions/base" import "jvmgo/ch11/rtda" import "jvmgo/ch11/rtda/heap" // Invoke instance method; dispatch based on class type INVOKE_VIRTUAL struct{ base.Index16Instruction } func (self *INVOKE_VIRTUAL) Execute(frame *rtda.Frame) { currentClass := frame.Method().Class() cp := currentClass.ConstantPool() methodRef := cp.GetConstant(self.Index).(*heap.MethodRef) resolvedMethod := methodRef.ResolvedMethod() if resolvedMethod.IsStatic() { panic("java.lang.IncompatibleClassChangeError") } ref := frame.OperandStack().GetRefFromTop(resolvedMethod.ArgSlotCount() - 1) if ref == nil { panic("java.lang.NullPointerException") } if resolvedMethod.IsProtected() && resolvedMethod.Class().IsSuperClassOf(currentClass) && resolvedMethod.Class().GetPackageName() != currentClass.GetPackageName() && ref.Class() != currentClass && !ref.Class().IsSubClassOf(currentClass) { if !(ref.Class().IsArray() && resolvedMethod.Name() == "clone") { panic("java.lang.IllegalAccessError") } } methodToBeInvoked := heap.LookupMethodInClass(ref.Class(), methodRef.Name(), methodRef.Descriptor()) if methodToBeInvoked == nil || methodToBeInvoked.IsAbstract() { panic("java.lang.AbstractMethodError") } base.InvokeMethod(frame, methodToBeInvoked) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/instructions/references/invokevirtual.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
331
```go package base import "jvmgo/ch11/rtda" import "jvmgo/ch11/rtda/heap" // jvms 5.5 func InitClass(thread *rtda.Thread, class *heap.Class) { class.StartInit() scheduleClinit(thread, class) initSuperClass(thread, class) } func scheduleClinit(thread *rtda.Thread, class *heap.Class) { clinit := class.GetClinitMethod() if clinit != nil && clinit.Class() == class { // exec <clinit> newFrame := thread.NewFrame(clinit) thread.PushFrame(newFrame) } } func initSuperClass(thread *rtda.Thread, class *heap.Class) { if !class.IsInterface() { superClass := class.SuperClass() if superClass != nil && !superClass.InitStarted() { InitClass(thread, superClass) } } } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/instructions/base/class_init_logic.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
199
```go package loads import "jvmgo/ch11/instructions/base" import "jvmgo/ch11/rtda" import "jvmgo/ch11/rtda/heap" // Load reference from array type AALOAD struct{ base.NoOperandsInstruction } func (self *AALOAD) Execute(frame *rtda.Frame) { stack := frame.OperandStack() index := stack.PopInt() arrRef := stack.PopRef() checkNotNil(arrRef) refs := arrRef.Refs() checkIndex(len(refs), index) stack.PushRef(refs[index]) } // Load byte or boolean from array type BALOAD struct{ base.NoOperandsInstruction } func (self *BALOAD) Execute(frame *rtda.Frame) { stack := frame.OperandStack() index := stack.PopInt() arrRef := stack.PopRef() checkNotNil(arrRef) bytes := arrRef.Bytes() checkIndex(len(bytes), index) stack.PushInt(int32(bytes[index])) } // Load char from array type CALOAD struct{ base.NoOperandsInstruction } func (self *CALOAD) Execute(frame *rtda.Frame) { stack := frame.OperandStack() index := stack.PopInt() arrRef := stack.PopRef() checkNotNil(arrRef) chars := arrRef.Chars() checkIndex(len(chars), index) stack.PushInt(int32(chars[index])) } // Load double from array type DALOAD struct{ base.NoOperandsInstruction } func (self *DALOAD) Execute(frame *rtda.Frame) { stack := frame.OperandStack() index := stack.PopInt() arrRef := stack.PopRef() checkNotNil(arrRef) doubles := arrRef.Doubles() checkIndex(len(doubles), index) stack.PushDouble(doubles[index]) } // Load float from array type FALOAD struct{ base.NoOperandsInstruction } func (self *FALOAD) Execute(frame *rtda.Frame) { stack := frame.OperandStack() index := stack.PopInt() arrRef := stack.PopRef() checkNotNil(arrRef) floats := arrRef.Floats() checkIndex(len(floats), index) stack.PushFloat(floats[index]) } // Load int from array type IALOAD struct{ base.NoOperandsInstruction } func (self *IALOAD) Execute(frame *rtda.Frame) { stack := frame.OperandStack() index := stack.PopInt() arrRef := stack.PopRef() checkNotNil(arrRef) ints := arrRef.Ints() checkIndex(len(ints), index) stack.PushInt(ints[index]) } // Load long from array type LALOAD struct{ base.NoOperandsInstruction } func (self *LALOAD) Execute(frame *rtda.Frame) { stack := frame.OperandStack() index := stack.PopInt() arrRef := stack.PopRef() checkNotNil(arrRef) longs := arrRef.Longs() checkIndex(len(longs), index) stack.PushLong(longs[index]) } // Load short from array type SALOAD struct{ base.NoOperandsInstruction } func (self *SALOAD) Execute(frame *rtda.Frame) { stack := frame.OperandStack() index := stack.PopInt() arrRef := stack.PopRef() checkNotNil(arrRef) shorts := arrRef.Shorts() checkIndex(len(shorts), index) stack.PushInt(int32(shorts[index])) } func checkNotNil(ref *heap.Object) { if ref == nil { panic("java.lang.NullPointerException") } } func checkIndex(arrLen int, index int32) { if index < 0 || index >= int32(arrLen) { panic("ArrayIndexOutOfBoundsException") } } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/instructions/loads/xaload.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
766
```go package references import "jvmgo/ch11/instructions/base" import "jvmgo/ch11/rtda" import "jvmgo/ch11/rtda/heap" // Set static field in class type PUT_STATIC struct{ base.Index16Instruction } func (self *PUT_STATIC) Execute(frame *rtda.Frame) { currentMethod := frame.Method() currentClass := currentMethod.Class() cp := currentClass.ConstantPool() fieldRef := cp.GetConstant(self.Index).(*heap.FieldRef) field := fieldRef.ResolvedField() class := field.Class() if !class.InitStarted() { frame.RevertNextPC() base.InitClass(frame.Thread(), class) return } if !field.IsStatic() { panic("java.lang.IncompatibleClassChangeError") } if field.IsFinal() { if currentClass != class || currentMethod.Name() != "<clinit>" { panic("java.lang.IllegalAccessError") } } descriptor := field.Descriptor() slotId := field.SlotId() slots := class.StaticVars() stack := frame.OperandStack() switch descriptor[0] { case 'Z', 'B', 'C', 'S', 'I': slots.SetInt(slotId, stack.PopInt()) case 'F': slots.SetFloat(slotId, stack.PopFloat()) case 'J': slots.SetLong(slotId, stack.PopLong()) case 'D': slots.SetDouble(slotId, stack.PopDouble()) case 'L', '[': slots.SetRef(slotId, stack.PopRef()) default: // todo } } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/instructions/references/putstatic.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
342
```go package reserved import "jvmgo/ch11/instructions/base" import "jvmgo/ch11/rtda" import "jvmgo/ch11/native" import _ "jvmgo/ch11/native/java/io" import _ "jvmgo/ch11/native/java/lang" import _ "jvmgo/ch11/native/java/security" import _ "jvmgo/ch11/native/java/util/concurrent/atomic" import _ "jvmgo/ch11/native/sun/io" import _ "jvmgo/ch11/native/sun/misc" import _ "jvmgo/ch11/native/sun/reflect" // Invoke native method type INVOKE_NATIVE struct{ base.NoOperandsInstruction } func (self *INVOKE_NATIVE) Execute(frame *rtda.Frame) { method := frame.Method() className := method.Class().Name() methodName := method.Name() methodDescriptor := method.Descriptor() nativeMethod := native.FindNativeMethod(className, methodName, methodDescriptor) if nativeMethod == nil { methodInfo := className + "." + methodName + methodDescriptor panic("java.lang.UnsatisfiedLinkError: " + methodInfo) } nativeMethod(frame) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/instructions/reserved/invokenative.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
244
```go package classfile /* Signature_attribute { u2 attribute_name_index; u4 attribute_length; u2 signature_index; } */ type SignatureAttribute struct { cp ConstantPool signatureIndex uint16 } func (self *SignatureAttribute) readInfo(reader *ClassReader) { self.signatureIndex = reader.readUint16() } func (self *SignatureAttribute) Signature() string { return self.cp.getUtf8(self.signatureIndex) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/classfile/attr_signature.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
94
```go package math import "math" import "jvmgo/ch11/instructions/base" import "jvmgo/ch11/rtda" // Remainder double type DREM struct{ base.NoOperandsInstruction } func (self *DREM) Execute(frame *rtda.Frame) { stack := frame.OperandStack() v2 := stack.PopDouble() v1 := stack.PopDouble() result := math.Mod(v1, v2) // todo stack.PushDouble(result) } // Remainder float type FREM struct{ base.NoOperandsInstruction } func (self *FREM) Execute(frame *rtda.Frame) { stack := frame.OperandStack() v2 := stack.PopFloat() v1 := stack.PopFloat() result := float32(math.Mod(float64(v1), float64(v2))) // todo stack.PushFloat(result) } // Remainder int type IREM struct{ base.NoOperandsInstruction } func (self *IREM) Execute(frame *rtda.Frame) { stack := frame.OperandStack() v2 := stack.PopInt() v1 := stack.PopInt() if v2 == 0 { panic("java.lang.ArithmeticException: / by zero") } result := v1 % v2 stack.PushInt(result) } // Remainder long type LREM struct{ base.NoOperandsInstruction } func (self *LREM) Execute(frame *rtda.Frame) { stack := frame.OperandStack() v2 := stack.PopLong() v1 := stack.PopLong() if v2 == 0 { panic("java.lang.ArithmeticException: / by zero") } result := v1 % v2 stack.PushLong(result) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/instructions/math/rem.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
358
```go package constants import "jvmgo/ch11/instructions/base" import "jvmgo/ch11/rtda" // Push byte type BIPUSH struct { val int8 } func (self *BIPUSH) FetchOperands(reader *base.BytecodeReader) { self.val = reader.ReadInt8() } func (self *BIPUSH) Execute(frame *rtda.Frame) { i := int32(self.val) frame.OperandStack().PushInt(i) } // Push short type SIPUSH struct { val int16 } func (self *SIPUSH) FetchOperands(reader *base.BytecodeReader) { self.val = reader.ReadInt16() } func (self *SIPUSH) Execute(frame *rtda.Frame) { i := int32(self.val) frame.OperandStack().PushInt(i) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/instructions/constants/ipush.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
177
```go package conversions import "jvmgo/ch11/instructions/base" import "jvmgo/ch11/rtda" // Convert float to double type F2D struct{ base.NoOperandsInstruction } func (self *F2D) Execute(frame *rtda.Frame) { stack := frame.OperandStack() f := stack.PopFloat() d := float64(f) stack.PushDouble(d) } // Convert float to int type F2I struct{ base.NoOperandsInstruction } func (self *F2I) Execute(frame *rtda.Frame) { stack := frame.OperandStack() f := stack.PopFloat() i := int32(f) stack.PushInt(i) } // Convert float to long type F2L struct{ base.NoOperandsInstruction } func (self *F2L) Execute(frame *rtda.Frame) { stack := frame.OperandStack() f := stack.PopFloat() l := int64(f) stack.PushLong(l) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/instructions/conversions/f2x.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
206
```go package classfile /* field_info { u2 access_flags; u2 name_index; u2 descriptor_index; u2 attributes_count; attribute_info attributes[attributes_count]; } method_info { u2 access_flags; u2 name_index; u2 descriptor_index; u2 attributes_count; attribute_info attributes[attributes_count]; } */ type MemberInfo struct { cp ConstantPool accessFlags uint16 nameIndex uint16 descriptorIndex uint16 attributes []AttributeInfo } // read field or method table func readMembers(reader *ClassReader, cp ConstantPool) []*MemberInfo { memberCount := reader.readUint16() members := make([]*MemberInfo, memberCount) for i := range members { members[i] = readMember(reader, cp) } return members } func readMember(reader *ClassReader, cp ConstantPool) *MemberInfo { return &MemberInfo{ cp: cp, accessFlags: reader.readUint16(), nameIndex: reader.readUint16(), descriptorIndex: reader.readUint16(), attributes: readAttributes(reader, cp), } } func (self *MemberInfo) AccessFlags() uint16 { return self.accessFlags } func (self *MemberInfo) Name() string { return self.cp.getUtf8(self.nameIndex) } func (self *MemberInfo) Descriptor() string { return self.cp.getUtf8(self.descriptorIndex) } func (self *MemberInfo) CodeAttribute() *CodeAttribute { for _, attrInfo := range self.attributes { switch attrInfo.(type) { case *CodeAttribute: return attrInfo.(*CodeAttribute) } } return nil } func (self *MemberInfo) ConstantValueAttribute() *ConstantValueAttribute { for _, attrInfo := range self.attributes { switch attrInfo.(type) { case *ConstantValueAttribute: return attrInfo.(*ConstantValueAttribute) } } return nil } func (self *MemberInfo) ExceptionsAttribute() *ExceptionsAttribute { for _, attrInfo := range self.attributes { switch attrInfo.(type) { case *ExceptionsAttribute: return attrInfo.(*ExceptionsAttribute) } } return nil } func (self *MemberInfo) RuntimeVisibleAnnotationsAttributeData() []byte { return self.getUnparsedAttributeData("RuntimeVisibleAnnotations") } func (self *MemberInfo) RuntimeVisibleParameterAnnotationsAttributeData() []byte { return self.getUnparsedAttributeData("RuntimeVisibleParameterAnnotationsAttribute") } func (self *MemberInfo) AnnotationDefaultAttributeData() []byte { return self.getUnparsedAttributeData("AnnotationDefault") } func (self *MemberInfo) getUnparsedAttributeData(name string) []byte { for _, attrInfo := range self.attributes { switch attrInfo.(type) { case *UnparsedAttribute: unparsedAttr := attrInfo.(*UnparsedAttribute) if unparsedAttr.name == name { return unparsedAttr.info } } } return nil } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/classfile/member_info.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
662
```go package stack import "jvmgo/ch11/instructions/base" import "jvmgo/ch11/rtda" // Pop the top operand stack value type POP struct{ base.NoOperandsInstruction } func (self *POP) Execute(frame *rtda.Frame) { stack := frame.OperandStack() stack.PopSlot() } // Pop the top one or two operand stack values type POP2 struct{ base.NoOperandsInstruction } func (self *POP2) Execute(frame *rtda.Frame) { stack := frame.OperandStack() stack.PopSlot() stack.PopSlot() } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/instructions/stack/pop.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
125
```go package main import "fmt" import "jvmgo/ch11/instructions" import "jvmgo/ch11/instructions/base" import "jvmgo/ch11/rtda" func interpret(thread *rtda.Thread, logInst bool) { defer catchErr(thread) loop(thread, logInst) } func catchErr(thread *rtda.Thread) { if r := recover(); r != nil { logFrames(thread) panic(r) } } func loop(thread *rtda.Thread, logInst bool) { reader := &base.BytecodeReader{} for { frame := thread.CurrentFrame() pc := frame.NextPC() thread.SetPC(pc) // decode reader.Reset(frame.Method().Code(), pc) opcode := reader.ReadUint8() inst := instructions.NewInstruction(opcode) inst.FetchOperands(reader) frame.SetNextPC(reader.PC()) if logInst { logInstruction(frame, inst) } // execute inst.Execute(frame) if thread.IsStackEmpty() { break } } } func logInstruction(frame *rtda.Frame, inst base.Instruction) { method := frame.Method() className := method.Class().Name() methodName := method.Name() pc := frame.Thread().PC() fmt.Printf("%v.%v() #%2d %T %v\n", className, methodName, pc, inst, inst) } func logFrames(thread *rtda.Thread) { for !thread.IsStackEmpty() { frame := thread.PopFrame() method := frame.Method() className := method.Class().Name() lineNum := method.GetLineNumber(frame.NextPC()) fmt.Printf(">> line:%4d pc:%4d %v.%v%v \n", lineNum, frame.NextPC(), className, method.Name(), method.Descriptor()) } } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/interpreter.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
393
```go package base import "jvmgo/ch11/rtda" type Instruction interface { FetchOperands(reader *BytecodeReader) Execute(frame *rtda.Frame) } type NoOperandsInstruction struct { // empty } func (self *NoOperandsInstruction) FetchOperands(reader *BytecodeReader) { // nothing to do } type BranchInstruction struct { Offset int } func (self *BranchInstruction) FetchOperands(reader *BytecodeReader) { self.Offset = int(reader.ReadInt16()) } type Index8Instruction struct { Index uint } func (self *Index8Instruction) FetchOperands(reader *BytecodeReader) { self.Index = uint(reader.ReadUint8()) } type Index16Instruction struct { Index uint } func (self *Index16Instruction) FetchOperands(reader *BytecodeReader) { self.Index = uint(reader.ReadUint16()) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/instructions/base/instruction.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
191
```go package classfile /* LocalVariableTable_attribute { u2 attribute_name_index; u4 attribute_length; u2 local_variable_table_length; { u2 start_pc; u2 length; u2 name_index; u2 descriptor_index; u2 index; } local_variable_table[local_variable_table_length]; } */ type LocalVariableTableAttribute struct { localVariableTable []*LocalVariableTableEntry } type LocalVariableTableEntry struct { startPc uint16 length uint16 nameIndex uint16 descriptorIndex uint16 index uint16 } func (self *LocalVariableTableAttribute) readInfo(reader *ClassReader) { localVariableTableLength := reader.readUint16() self.localVariableTable = make([]*LocalVariableTableEntry, localVariableTableLength) for i := range self.localVariableTable { self.localVariableTable[i] = &LocalVariableTableEntry{ startPc: reader.readUint16(), length: reader.readUint16(), nameIndex: reader.readUint16(), descriptorIndex: reader.readUint16(), index: reader.readUint16(), } } } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/classfile/attr_local_variable_table.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
251
```go package classfile import "encoding/binary" type ClassReader struct { data []byte } // u1 func (self *ClassReader) readUint8() uint8 { val := self.data[0] self.data = self.data[1:] return val } // u2 func (self *ClassReader) readUint16() uint16 { val := binary.BigEndian.Uint16(self.data) self.data = self.data[2:] return val } // u4 func (self *ClassReader) readUint32() uint32 { val := binary.BigEndian.Uint32(self.data) self.data = self.data[4:] return val } func (self *ClassReader) readUint64() uint64 { val := binary.BigEndian.Uint64(self.data) self.data = self.data[8:] return val } func (self *ClassReader) readUint16s() []uint16 { n := self.readUint16() s := make([]uint16, n) for i := range s { s[i] = self.readUint16() } return s } func (self *ClassReader) readBytes(n uint32) []byte { bytes := self.data[:n] self.data = self.data[n:] return bytes } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/classfile/class_reader.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
262
```go package references import "jvmgo/ch11/instructions/base" import "jvmgo/ch11/rtda" import "jvmgo/ch11/rtda/heap" // Create new array of reference type ANEW_ARRAY struct{ base.Index16Instruction } func (self *ANEW_ARRAY) Execute(frame *rtda.Frame) { cp := frame.Method().Class().ConstantPool() classRef := cp.GetConstant(self.Index).(*heap.ClassRef) componentClass := classRef.ResolvedClass() // if componentClass.InitializationNotStarted() { // thread := frame.Thread() // frame.SetNextPC(thread.PC()) // undo anewarray // thread.InitClass(componentClass) // return // } stack := frame.OperandStack() count := stack.PopInt() if count < 0 { panic("java.lang.NegativeArraySizeException") } arrClass := componentClass.ArrayClass() arr := arrClass.NewArray(uint(count)) stack.PushRef(arr) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/instructions/references/anewarray.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
214
```go package main import "flag" import "fmt" import "os" // java [-options] class [args...] type Cmd struct { helpFlag bool versionFlag bool verboseClassFlag bool verboseInstFlag bool cpOption string XjreOption string class string args []string } func parseCmd() *Cmd { cmd := &Cmd{} flag.Usage = printUsage flag.BoolVar(&cmd.helpFlag, "help", false, "print help message") flag.BoolVar(&cmd.helpFlag, "?", false, "print help message") flag.BoolVar(&cmd.versionFlag, "version", false, "print version and exit") flag.BoolVar(&cmd.verboseClassFlag, "verbose", false, "enable verbose output") flag.BoolVar(&cmd.verboseClassFlag, "verbose:class", false, "enable verbose output") flag.BoolVar(&cmd.verboseInstFlag, "verbose:inst", false, "enable verbose output") flag.StringVar(&cmd.cpOption, "classpath", "", "classpath") flag.StringVar(&cmd.cpOption, "cp", "", "classpath") flag.StringVar(&cmd.XjreOption, "Xjre", "", "path to jre") flag.Parse() args := flag.Args() if len(args) > 0 { cmd.class = args[0] cmd.args = args[1:] } return cmd } func printUsage() { fmt.Printf("Usage: %s [-options] class [args...]\n", os.Args[0]) //flag.PrintDefaults() } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/cmd.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
328
```go package references import "jvmgo/ch11/instructions/base" import "jvmgo/ch11/rtda" import "jvmgo/ch11/rtda/heap" // Check whether object is of given type type CHECK_CAST struct{ base.Index16Instruction } func (self *CHECK_CAST) Execute(frame *rtda.Frame) { stack := frame.OperandStack() ref := stack.PopRef() stack.PushRef(ref) if ref == nil { return } cp := frame.Method().Class().ConstantPool() classRef := cp.GetConstant(self.Index).(*heap.ClassRef) class := classRef.ResolvedClass() if !ref.IsInstanceOf(class) { panic("java.lang.ClassCastException") } } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/instructions/references/checkcast.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
153
```go package base import "jvmgo/ch11/rtda" func Branch(frame *rtda.Frame, offset int) { pc := frame.Thread().PC() nextPC := pc + offset frame.SetNextPC(nextPC) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/instructions/base/branch_logic.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
50
```go package classfile /* CONSTANT_NameAndType_info { u1 tag; u2 name_index; u2 descriptor_index; } */ type ConstantNameAndTypeInfo struct { nameIndex uint16 descriptorIndex uint16 } func (self *ConstantNameAndTypeInfo) readInfo(reader *ClassReader) { self.nameIndex = reader.readUint16() self.descriptorIndex = reader.readUint16() } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/classfile/cp_name_and_type.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
88
```go package stack import "jvmgo/ch11/instructions/base" import "jvmgo/ch11/rtda" // Duplicate the top operand stack value type DUP struct{ base.NoOperandsInstruction } func (self *DUP) Execute(frame *rtda.Frame) { stack := frame.OperandStack() slot := stack.PopSlot() stack.PushSlot(slot) stack.PushSlot(slot) } // Duplicate the top operand stack value and insert two values down type DUP_X1 struct{ base.NoOperandsInstruction } func (self *DUP_X1) Execute(frame *rtda.Frame) { stack := frame.OperandStack() slot1 := stack.PopSlot() slot2 := stack.PopSlot() stack.PushSlot(slot1) stack.PushSlot(slot2) stack.PushSlot(slot1) } // Duplicate the top operand stack value and insert two or three values down type DUP_X2 struct{ base.NoOperandsInstruction } func (self *DUP_X2) Execute(frame *rtda.Frame) { stack := frame.OperandStack() slot1 := stack.PopSlot() slot2 := stack.PopSlot() slot3 := stack.PopSlot() stack.PushSlot(slot1) stack.PushSlot(slot3) stack.PushSlot(slot2) stack.PushSlot(slot1) } // Duplicate the top one or two operand stack values type DUP2 struct{ base.NoOperandsInstruction } func (self *DUP2) Execute(frame *rtda.Frame) { stack := frame.OperandStack() slot1 := stack.PopSlot() slot2 := stack.PopSlot() stack.PushSlot(slot2) stack.PushSlot(slot1) stack.PushSlot(slot2) stack.PushSlot(slot1) } // Duplicate the top one or two operand stack values and insert two or three values down type DUP2_X1 struct{ base.NoOperandsInstruction } func (self *DUP2_X1) Execute(frame *rtda.Frame) { stack := frame.OperandStack() slot1 := stack.PopSlot() slot2 := stack.PopSlot() slot3 := stack.PopSlot() stack.PushSlot(slot2) stack.PushSlot(slot1) stack.PushSlot(slot3) stack.PushSlot(slot2) stack.PushSlot(slot1) } // Duplicate the top one or two operand stack values and insert two, three, or four values down type DUP2_X2 struct{ base.NoOperandsInstruction } func (self *DUP2_X2) Execute(frame *rtda.Frame) { stack := frame.OperandStack() slot1 := stack.PopSlot() slot2 := stack.PopSlot() slot3 := stack.PopSlot() slot4 := stack.PopSlot() stack.PushSlot(slot2) stack.PushSlot(slot1) stack.PushSlot(slot4) stack.PushSlot(slot3) stack.PushSlot(slot2) stack.PushSlot(slot1) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/instructions/stack/dup.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
584