You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
38064 lines
1.5 MiB
38064 lines
1.5 MiB
// Console-polyfill. MIT license. |
||
// https://github.com/paulmillr/console-polyfill |
||
// Make it safe to do console.log() always. |
||
(function (con) { |
||
'use strict'; |
||
var prop, method; |
||
var empty = {}; |
||
var dummy = function() {}; |
||
var properties = 'memory'.split(','); |
||
var methods = ('assert,count,debug,dir,dirxml,error,exception,group,' + |
||
'groupCollapsed,groupEnd,info,log,markTimeline,profile,profileEnd,' + |
||
'time,timeEnd,trace,warn').split(','); |
||
while (prop = properties.pop()) con[prop] = con[prop] || empty; |
||
while (method = methods.pop()) con[method] = con[method] || dummy; |
||
})(this.console = this.console || {}); |
||
|
||
// For Workers compatibility `window` object is replaced with `this` keyword |
||
/*! jQuery v1.10.2 | (c) 2005, 2013 jQuery Foundation, Inc. | jquery.org/license |
||
//@ sourceMappingURL=jquery.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); |
||
|
||
/*! nanoScrollerJS - v0.7.6 - 2013 |
||
* http://jamesflorentino.github.com/nanoScrollerJS/ |
||
* Copyright (c) 2013 James Florentino; Licensed MIT */ |
||
(function($, window, document) { |
||
"use strict"; |
||
var BROWSER_IS_IE7, BROWSER_SCROLLBAR_WIDTH, DOMSCROLL, DOWN, DRAG, KEYDOWN, KEYUP, MOUSEDOWN, MOUSEMOVE, MOUSEUP, MOUSEWHEEL, NanoScroll, PANEDOWN, RESIZE, SCROLL, SCROLLBAR, TOUCHMOVE, UP, WHEEL, cAF, defaults, getBrowserScrollbarWidth, hasTransform, isFFWithBuggyScrollbar, rAF, transform, _elementStyle, _prefixStyle, _vendor; |
||
defaults = { |
||
/** |
||
a classname for the pane element. |
||
@property paneClass |
||
@type String |
||
@default 'pane' |
||
*/ |
||
|
||
paneClass: 'pane', |
||
/** |
||
a classname for the slider element. |
||
@property sliderClass |
||
@type String |
||
@default 'slider' |
||
*/ |
||
|
||
sliderClass: 'slider', |
||
/** |
||
a classname for the content element. |
||
@property contentClass |
||
@type String |
||
@default 'content' |
||
*/ |
||
|
||
contentClass: 'content', |
||
/** |
||
a setting to enable native scrolling in iOS devices. |
||
@property iOSNativeScrolling |
||
@type Boolean |
||
@default false |
||
*/ |
||
|
||
iOSNativeScrolling: false, |
||
/** |
||
a setting to prevent the rest of the page being |
||
scrolled when user scrolls the `.content` element. |
||
@property preventPageScrolling |
||
@type Boolean |
||
@default false |
||
*/ |
||
|
||
preventPageScrolling: false, |
||
/** |
||
a setting to disable binding to the resize event. |
||
@property disableResize |
||
@type Boolean |
||
@default false |
||
*/ |
||
|
||
disableResize: false, |
||
/** |
||
a setting to make the scrollbar always visible. |
||
@property alwaysVisible |
||
@type Boolean |
||
@default false |
||
*/ |
||
|
||
alwaysVisible: false, |
||
/** |
||
a default timeout for the `flash()` method. |
||
@property flashDelay |
||
@type Number |
||
@default 1500 |
||
*/ |
||
|
||
flashDelay: 1500, |
||
/** |
||
a minimum height for the `.slider` element. |
||
@property sliderMinHeight |
||
@type Number |
||
@default 20 |
||
*/ |
||
|
||
sliderMinHeight: 20, |
||
/** |
||
a maximum height for the `.slider` element. |
||
@property sliderMaxHeight |
||
@type Number |
||
@default null |
||
*/ |
||
|
||
sliderMaxHeight: null, |
||
/** |
||
an alternate document context. |
||
@property documentContext |
||
@type Document |
||
@default null |
||
*/ |
||
|
||
documentContext: null, |
||
/** |
||
an alternate window context. |
||
@property windowContext |
||
@type Window |
||
@default null |
||
*/ |
||
|
||
windowContext: null |
||
}; |
||
/** |
||
@property SCROLLBAR |
||
@type String |
||
@static |
||
@final |
||
@private |
||
*/ |
||
|
||
SCROLLBAR = 'scrollbar'; |
||
/** |
||
@property SCROLL |
||
@type String |
||
@static |
||
@final |
||
@private |
||
*/ |
||
|
||
SCROLL = 'scroll'; |
||
/** |
||
@property MOUSEDOWN |
||
@type String |
||
@final |
||
@private |
||
*/ |
||
|
||
MOUSEDOWN = 'mousedown'; |
||
/** |
||
@property MOUSEMOVE |
||
@type String |
||
@static |
||
@final |
||
@private |
||
*/ |
||
|
||
MOUSEMOVE = 'mousemove'; |
||
/** |
||
@property MOUSEWHEEL |
||
@type String |
||
@final |
||
@private |
||
*/ |
||
|
||
MOUSEWHEEL = 'mousewheel'; |
||
/** |
||
@property MOUSEUP |
||
@type String |
||
@static |
||
@final |
||
@private |
||
*/ |
||
|
||
MOUSEUP = 'mouseup'; |
||
/** |
||
@property RESIZE |
||
@type String |
||
@final |
||
@private |
||
*/ |
||
|
||
RESIZE = 'resize'; |
||
/** |
||
@property DRAG |
||
@type String |
||
@static |
||
@final |
||
@private |
||
*/ |
||
|
||
DRAG = 'drag'; |
||
/** |
||
@property UP |
||
@type String |
||
@static |
||
@final |
||
@private |
||
*/ |
||
|
||
UP = 'up'; |
||
/** |
||
@property PANEDOWN |
||
@type String |
||
@static |
||
@final |
||
@private |
||
*/ |
||
|
||
PANEDOWN = 'panedown'; |
||
/** |
||
@property DOMSCROLL |
||
@type String |
||
@static |
||
@final |
||
@private |
||
*/ |
||
|
||
DOMSCROLL = 'DOMMouseScroll'; |
||
/** |
||
@property DOWN |
||
@type String |
||
@static |
||
@final |
||
@private |
||
*/ |
||
|
||
DOWN = 'down'; |
||
/** |
||
@property WHEEL |
||
@type String |
||
@static |
||
@final |
||
@private |
||
*/ |
||
|
||
WHEEL = 'wheel'; |
||
/** |
||
@property KEYDOWN |
||
@type String |
||
@static |
||
@final |
||
@private |
||
*/ |
||
|
||
KEYDOWN = 'keydown'; |
||
/** |
||
@property KEYUP |
||
@type String |
||
@static |
||
@final |
||
@private |
||
*/ |
||
|
||
KEYUP = 'keyup'; |
||
/** |
||
@property TOUCHMOVE |
||
@type String |
||
@static |
||
@final |
||
@private |
||
*/ |
||
|
||
TOUCHMOVE = 'touchmove'; |
||
/** |
||
@property BROWSER_IS_IE7 |
||
@type Boolean |
||
@static |
||
@final |
||
@private |
||
*/ |
||
|
||
BROWSER_IS_IE7 = window.navigator.appName === 'Microsoft Internet Explorer' && /msie 7./i.test(window.navigator.appVersion) && window.ActiveXObject; |
||
/** |
||
@property BROWSER_SCROLLBAR_WIDTH |
||
@type Number |
||
@static |
||
@default null |
||
@private |
||
*/ |
||
|
||
BROWSER_SCROLLBAR_WIDTH = null; |
||
rAF = window.requestAnimationFrame; |
||
cAF = window.cancelAnimationFrame; |
||
_elementStyle = document.createElement('div').style; |
||
_vendor = (function() { |
||
var i, transform, vendor, vendors, _i, _len; |
||
vendors = ['t', 'webkitT', 'MozT', 'msT', 'OT']; |
||
for (i = _i = 0, _len = vendors.length; _i < _len; i = ++_i) { |
||
vendor = vendors[i]; |
||
transform = vendors[i] + 'ransform'; |
||
if (transform in _elementStyle) { |
||
return vendors[i].substr(0, vendors[i].length - 1); |
||
} |
||
} |
||
return false; |
||
})(); |
||
_prefixStyle = function(style) { |
||
if (_vendor === false) { |
||
return false; |
||
} |
||
if (_vendor === '') { |
||
return style; |
||
} |
||
return _vendor + style.charAt(0).toUpperCase() + style.substr(1); |
||
}; |
||
transform = _prefixStyle('transform'); |
||
hasTransform = transform !== false; |
||
/** |
||
Returns browser's native scrollbar width |
||
@method getBrowserScrollbarWidth |
||
@return {Number} the scrollbar width in pixels |
||
@static |
||
@private |
||
*/ |
||
|
||
getBrowserScrollbarWidth = function() { |
||
var outer, outerStyle, scrollbarWidth; |
||
outer = document.createElement('div'); |
||
outerStyle = outer.style; |
||
outerStyle.position = 'absolute'; |
||
outerStyle.width = '100px'; |
||
outerStyle.height = '100px'; |
||
outerStyle.overflow = SCROLL; |
||
outerStyle.top = '-9999px'; |
||
document.body.appendChild(outer); |
||
scrollbarWidth = outer.offsetWidth - outer.clientWidth; |
||
document.body.removeChild(outer); |
||
return scrollbarWidth; |
||
}; |
||
isFFWithBuggyScrollbar = function() { |
||
var isOSXFF, ua, version; |
||
ua = window.navigator.userAgent; |
||
isOSXFF = /(?=.+Mac OS X)(?=.+Firefox)/.test(ua); |
||
if (!isOSXFF) { |
||
return false; |
||
} |
||
version = /Firefox\/\d{2}\./.exec(ua); |
||
if (version) { |
||
version = version[0].replace(/\D+/g, ''); |
||
} |
||
return isOSXFF && +version > 23; |
||
}; |
||
/** |
||
@class NanoScroll |
||
@param element {HTMLElement|Node} the main element |
||
@param options {Object} nanoScroller's options |
||
@constructor |
||
*/ |
||
|
||
NanoScroll = (function() { |
||
function NanoScroll(el, options) { |
||
this.el = el; |
||
this.options = options; |
||
BROWSER_SCROLLBAR_WIDTH || (BROWSER_SCROLLBAR_WIDTH = getBrowserScrollbarWidth()); |
||
this.$el = $(this.el); |
||
this.doc = $(this.options.documentContext || document); |
||
this.win = $(this.options.windowContext || window); |
||
this.$content = this.$el.children("." + options.contentClass); |
||
this.$content.attr('tabindex', this.options.tabIndex || 0); |
||
this.content = this.$content[0]; |
||
if (this.options.iOSNativeScrolling && (this.el.style.WebkitOverflowScrolling != null)) { |
||
this.nativeScrolling(); |
||
} else { |
||
this.generate(); |
||
} |
||
this.createEvents(); |
||
this.addEvents(); |
||
this.reset(); |
||
} |
||
|
||
/** |
||
Prevents the rest of the page being scrolled |
||
when user scrolls the `.content` element. |
||
@method preventScrolling |
||
@param event {Event} |
||
@param direction {String} Scroll direction (up or down) |
||
@private |
||
*/ |
||
|
||
|
||
NanoScroll.prototype.preventScrolling = function(e, direction) { |
||
if (!this.isActive) { |
||
return; |
||
} |
||
if (e.type === DOMSCROLL) { |
||
if (direction === DOWN && e.originalEvent.detail > 0 || direction === UP && e.originalEvent.detail < 0) { |
||
e.preventDefault(); |
||
} |
||
} else if (e.type === MOUSEWHEEL) { |
||
if (!e.originalEvent || !e.originalEvent.wheelDelta) { |
||
return; |
||
} |
||
if (direction === DOWN && e.originalEvent.wheelDelta < 0 || direction === UP && e.originalEvent.wheelDelta > 0) { |
||
e.preventDefault(); |
||
} |
||
} |
||
}; |
||
|
||
/** |
||
Enable iOS native scrolling |
||
@method nativeScrolling |
||
@private |
||
*/ |
||
|
||
|
||
NanoScroll.prototype.nativeScrolling = function() { |
||
this.$content.css({ |
||
WebkitOverflowScrolling: 'touch' |
||
}); |
||
this.iOSNativeScrolling = true; |
||
this.isActive = true; |
||
}; |
||
|
||
/** |
||
Updates those nanoScroller properties that |
||
are related to current scrollbar position. |
||
@method updateScrollValues |
||
@private |
||
*/ |
||
|
||
|
||
NanoScroll.prototype.updateScrollValues = function() { |
||
var content; |
||
content = this.content; |
||
this.maxScrollTop = content.scrollHeight - content.clientHeight; |
||
this.prevScrollTop = this.contentScrollTop || 0; |
||
this.contentScrollTop = content.scrollTop; |
||
if (!this.iOSNativeScrolling) { |
||
// console.log(this.maxScrollTop, this.contentScrollTop, this.maxSliderTop, this.maxScrollTop); |
||
// console.trace(); |
||
this.maxSliderTop = this.paneHeight - this.sliderHeight; |
||
this.sliderTop = this.maxScrollTop === 0 ? 0 : this.contentScrollTop * this.maxSliderTop / this.maxScrollTop; |
||
} |
||
}; |
||
|
||
/** |
||
Updates CSS styles for current scroll position. |
||
Uses CSS 2d transfroms and `window.requestAnimationFrame` if available. |
||
@method setOnScrollStyles |
||
@private |
||
*/ |
||
|
||
|
||
NanoScroll.prototype.setOnScrollStyles = function() { |
||
var cssValue, |
||
_this = this; |
||
if (hasTransform) { |
||
cssValue = {}; |
||
cssValue[transform] = "translate(0, " + this.sliderTop + "px)"; |
||
|
||
// console.log(this.sliderTop, cssValue, this.scrollRAF, rAF); |
||
} else { |
||
cssValue = { |
||
top: this.sliderTop |
||
}; |
||
} |
||
if (rAF) { |
||
if (!this.scrollRAF) { |
||
this.scrollRAF = rAF(function() { |
||
// console.log('raf called', cssValue); |
||
_this.scrollRAF = null; |
||
_this.slider.css(cssValue); |
||
}); |
||
} |
||
} else { |
||
this.slider.css(cssValue); |
||
} |
||
}; |
||
|
||
/** |
||
Creates event related methods |
||
@method createEvents |
||
@private |
||
*/ |
||
|
||
|
||
NanoScroll.prototype.createEvents = function() { |
||
var _this = this; |
||
this.events = { |
||
down: function(e) { |
||
_this.isBeingDragged = true; |
||
_this.offsetY = e.pageY - _this.slider.offset().top; |
||
_this.pane.addClass('active'); |
||
_this.doc.bind(MOUSEMOVE, _this.events[DRAG]).bind(MOUSEUP, _this.events[UP]); |
||
return false; |
||
}, |
||
drag: function(e) { |
||
_this.sliderY = e.pageY - _this.$el.offset().top - _this.offsetY; |
||
_this.scroll(); |
||
_this.updateScrollValues(); |
||
if (_this.contentScrollTop >= _this.maxScrollTop && _this.prevScrollTop !== _this.maxScrollTop) { |
||
_this.$el.trigger('scrollend'); |
||
} else if (_this.contentScrollTop === 0 && _this.prevScrollTop !== 0) { |
||
_this.$el.trigger('scrolltop'); |
||
} |
||
return false; |
||
}, |
||
up: function(e) { |
||
_this.isBeingDragged = false; |
||
_this.pane.removeClass('active'); |
||
_this.doc.unbind(MOUSEMOVE, _this.events[DRAG]).unbind(MOUSEUP, _this.events[UP]); |
||
return false; |
||
}, |
||
resize: function(e) { |
||
_this.reset(); |
||
}, |
||
panedown: function(e) { |
||
_this.sliderY = (e.offsetY || e.originalEvent.layerY) - (_this.sliderHeight * 0.5); |
||
_this.scroll(); |
||
_this.events.down(e); |
||
return false; |
||
}, |
||
scroll: function(e) { |
||
if (_this.isBeingDragged) { |
||
return; |
||
} |
||
_this.updateScrollValues(); |
||
if (!_this.iOSNativeScrolling) { |
||
_this.sliderY = _this.sliderTop; |
||
_this.setOnScrollStyles(); |
||
} |
||
if (e == null) { |
||
return; |
||
} |
||
if (_this.contentScrollTop >= _this.maxScrollTop) { |
||
if (_this.options.preventPageScrolling) { |
||
_this.preventScrolling(e, DOWN); |
||
} |
||
if (_this.prevScrollTop !== _this.maxScrollTop) { |
||
_this.$el.trigger('scrollend'); |
||
} |
||
} else if (_this.contentScrollTop === 0) { |
||
if (_this.options.preventPageScrolling) { |
||
_this.preventScrolling(e, UP); |
||
} |
||
if (_this.prevScrollTop !== 0) { |
||
_this.$el.trigger('scrolltop'); |
||
} |
||
} |
||
}, |
||
wheel: function(e) { |
||
var delta; |
||
if (e == null) { |
||
return; |
||
} |
||
delta = e.delta || e.wheelDelta || (e.originalEvent && e.originalEvent.wheelDelta) || -e.detail || (e.originalEvent && -e.originalEvent.detail); |
||
if (delta) { |
||
_this.sliderY += -delta / 3; |
||
} |
||
_this.scroll(); |
||
return false; |
||
} |
||
}; |
||
}; |
||
|
||
/** |
||
Adds event listeners with jQuery. |
||
@method addEvents |
||
@private |
||
*/ |
||
|
||
|
||
NanoScroll.prototype.addEvents = function() { |
||
var events; |
||
this.removeEvents(); |
||
events = this.events; |
||
if (!this.options.disableResize) { |
||
this.win.bind(RESIZE, events[RESIZE]); |
||
} |
||
if (!this.iOSNativeScrolling) { |
||
this.slider.bind(MOUSEDOWN, events[DOWN]); |
||
this.pane.bind(MOUSEDOWN, events[PANEDOWN]).bind("" + MOUSEWHEEL + " " + DOMSCROLL, events[WHEEL]); |
||
} |
||
this.$content.bind("" + SCROLL + " " + MOUSEWHEEL + " " + DOMSCROLL + " " + TOUCHMOVE, events[SCROLL]); |
||
}; |
||
|
||
/** |
||
Removes event listeners with jQuery. |
||
@method removeEvents |
||
@private |
||
*/ |
||
|
||
|
||
NanoScroll.prototype.removeEvents = function() { |
||
var events; |
||
events = this.events; |
||
this.win.unbind(RESIZE, events[RESIZE]); |
||
if (!this.iOSNativeScrolling) { |
||
this.slider.unbind(); |
||
this.pane.unbind(); |
||
} |
||
this.$content.unbind("" + SCROLL + " " + MOUSEWHEEL + " " + DOMSCROLL + " " + TOUCHMOVE, events[SCROLL]); |
||
}; |
||
|
||
/** |
||
Generates nanoScroller's scrollbar and elements for it. |
||
@method generate |
||
@chainable |
||
@private |
||
*/ |
||
|
||
|
||
NanoScroll.prototype.generate = function() { |
||
var contentClass, cssRule, currentPadding, options, paneClass, sliderClass; |
||
options = this.options; |
||
paneClass = options.paneClass, sliderClass = options.sliderClass, contentClass = options.contentClass; |
||
if (!this.$el.find("." + paneClass).length && !this.$el.find("." + sliderClass).length) { |
||
this.$el.append("<div class=\"" + paneClass + "\"><div class=\"" + sliderClass + "\" /></div>"); |
||
} |
||
this.pane = this.$el.children("." + paneClass); |
||
this.slider = this.pane.find("." + sliderClass); |
||
if (BROWSER_SCROLLBAR_WIDTH === 0 && isFFWithBuggyScrollbar()) { |
||
currentPadding = window.getComputedStyle(this.content, null).getPropertyValue('padding-right').replace(/\D+/g, ''); |
||
cssRule = { |
||
right: -14, |
||
paddingRight: +currentPadding + 14 |
||
}; |
||
} else if (BROWSER_SCROLLBAR_WIDTH) { |
||
cssRule = { |
||
right: -BROWSER_SCROLLBAR_WIDTH |
||
}; |
||
this.$el.addClass('has-scrollbar'); |
||
} |
||
if (cssRule != null) { |
||
this.$content.css(cssRule); |
||
} |
||
return this; |
||
}; |
||
|
||
/** |
||
@method restore |
||
@private |
||
*/ |
||
|
||
|
||
NanoScroll.prototype.restore = function() { |
||
this.stopped = false; |
||
if (!this.iOSNativeScrolling) { |
||
this.pane.show(); |
||
} |
||
this.addEvents(); |
||
}; |
||
|
||
/** |
||
Resets nanoScroller's scrollbar. |
||
@method reset |
||
@chainable |
||
@example |
||
$(".nano").nanoScroller(); |
||
*/ |
||
|
||
|
||
NanoScroll.prototype.reset = function() { |
||
var content, contentHeight, contentStyle, contentStyleOverflowY, paneBottom, paneHeight, paneOuterHeight, paneTop, parentMaxHeight, sliderHeight; |
||
if (this.iOSNativeScrolling) { |
||
this.contentHeight = this.content.scrollHeight; |
||
return; |
||
} |
||
if (!this.$el.find("." + this.options.paneClass).length) { |
||
this.generate().stop(); |
||
} |
||
if (this.stopped) { |
||
this.restore(); |
||
} |
||
content = this.content; |
||
contentStyle = content.style; |
||
contentStyleOverflowY = contentStyle.overflowY; |
||
if (BROWSER_IS_IE7) { |
||
this.$content.css({ |
||
height: this.$content.height() |
||
}); |
||
} |
||
contentHeight = content.scrollHeight + BROWSER_SCROLLBAR_WIDTH; |
||
parentMaxHeight = parseInt(this.$el.css("max-height"), 10); |
||
if (parentMaxHeight > 0) { |
||
this.$el.height(""); |
||
this.$el.height(content.scrollHeight > parentMaxHeight ? parentMaxHeight : content.scrollHeight); |
||
} |
||
paneHeight = this.pane.outerHeight(false); |
||
paneTop = parseInt(this.pane.css('top'), 10); |
||
paneBottom = parseInt(this.pane.css('bottom'), 10); |
||
paneOuterHeight = paneHeight + paneTop + paneBottom; |
||
sliderHeight = Math.round(paneOuterHeight / contentHeight * paneOuterHeight); |
||
if (sliderHeight < this.options.sliderMinHeight) { |
||
sliderHeight = this.options.sliderMinHeight; |
||
} else if ((this.options.sliderMaxHeight != null) && sliderHeight > this.options.sliderMaxHeight) { |
||
sliderHeight = this.options.sliderMaxHeight; |
||
} |
||
if (contentStyleOverflowY === SCROLL && contentStyle.overflowX !== SCROLL) { |
||
sliderHeight += BROWSER_SCROLLBAR_WIDTH; |
||
} |
||
this.maxSliderTop = paneOuterHeight - sliderHeight; |
||
this.contentHeight = contentHeight; |
||
this.paneHeight = paneHeight; |
||
this.paneOuterHeight = paneOuterHeight; |
||
this.sliderHeight = sliderHeight; |
||
this.slider.height(sliderHeight); |
||
this.events.scroll(); |
||
this.pane.show(); |
||
this.isActive = true; |
||
if ((content.scrollHeight === content.clientHeight) || (this.pane.outerHeight(true) >= content.scrollHeight && contentStyleOverflowY !== SCROLL)) { |
||
this.pane.hide(); |
||
this.isActive = false; |
||
} else if (this.el.clientHeight === content.scrollHeight && contentStyleOverflowY === SCROLL) { |
||
this.slider.hide(); |
||
} else { |
||
this.slider.show(); |
||
} |
||
this.pane.css({ |
||
opacity: (this.options.alwaysVisible ? 1 : ''), |
||
visibility: (this.options.alwaysVisible ? 'visible' : '') |
||
}); |
||
return this; |
||
}; |
||
|
||
/** |
||
@method scroll |
||
@private |
||
@example |
||
$(".nano").nanoScroller({ scroll: 'top' }); |
||
*/ |
||
|
||
|
||
NanoScroll.prototype.scroll = function() { |
||
if (!this.isActive) { |
||
return; |
||
} |
||
this.sliderY = Math.max(0, this.sliderY); |
||
this.sliderY = Math.min(this.maxSliderTop, this.sliderY); |
||
this.$content.scrollTop((this.paneHeight - this.contentHeight + BROWSER_SCROLLBAR_WIDTH) * this.sliderY / this.maxSliderTop * -1); |
||
if (!this.iOSNativeScrolling) { |
||
this.updateScrollValues(); |
||
this.setOnScrollStyles(); |
||
} |
||
return this; |
||
}; |
||
|
||
/** |
||
Scroll at the bottom with an offset value |
||
@method scrollBottom |
||
@param offsetY {Number} |
||
@chainable |
||
@example |
||
$(".nano").nanoScroller({ scrollBottom: value }); |
||
*/ |
||
|
||
|
||
NanoScroll.prototype.scrollBottom = function(offsetY) { |
||
if (!this.isActive) { |
||
return; |
||
} |
||
this.reset(); |
||
this.$content.scrollTop(this.contentHeight - this.$content.height() - offsetY).trigger(MOUSEWHEEL); |
||
return this; |
||
}; |
||
|
||
/** |
||
Scroll at the top with an offset value |
||
@method scrollTop |
||
@param offsetY {Number} |
||
@chainable |
||
@example |
||
$(".nano").nanoScroller({ scrollTop: value }); |
||
*/ |
||
|
||
|
||
NanoScroll.prototype.scrollTop = function(offsetY) { |
||
if (!this.isActive) { |
||
return; |
||
} |
||
this.reset(); |
||
this.$content.scrollTop(+offsetY).trigger(MOUSEWHEEL); |
||
return this; |
||
}; |
||
|
||
/** |
||
Scroll to an element |
||
@method scrollTo |
||
@param node {Node} A node to scroll to. |
||
@chainable |
||
@example |
||
$(".nano").nanoScroller({ scrollTo: $('#a_node') }); |
||
*/ |
||
|
||
|
||
NanoScroll.prototype.scrollTo = function(node) { |
||
if (!this.isActive) { |
||
return; |
||
} |
||
this.reset(); |
||
this.scrollTop($(node).get(0).offsetTop); |
||
return this; |
||
}; |
||
|
||
/** |
||
To stop the operation. |
||
This option will tell the plugin to disable all event bindings and hide the gadget scrollbar from the UI. |
||
@method stop |
||
@chainable |
||
@example |
||
$(".nano").nanoScroller({ stop: true }); |
||
*/ |
||
|
||
|
||
NanoScroll.prototype.stop = function() { |
||
if (cAF) { |
||
cAF(this.scrollRAF); |
||
} |
||
this.stopped = true; |
||
this.removeEvents(); |
||
if (!this.iOSNativeScrolling) { |
||
this.pane.hide(); |
||
} |
||
return this; |
||
}; |
||
|
||
/** |
||
Destroys nanoScroller and restores browser's native scrollbar. |
||
@method destroy |
||
@chainable |
||
@example |
||
$(".nano").nanoScroller({ destroy: true }); |
||
*/ |
||
|
||
|
||
NanoScroll.prototype.destroy = function() { |
||
if (!this.stopped) { |
||
this.stop(); |
||
} |
||
if (!this.iOSNativeScrolling && this.pane.length) { |
||
this.pane.remove(); |
||
} |
||
if (BROWSER_IS_IE7) { |
||
this.$content.height(''); |
||
} |
||
this.$content.removeAttr('tabindex'); |
||
if (this.$el.hasClass('has-scrollbar')) { |
||
this.$el.removeClass('has-scrollbar'); |
||
this.$content.css({ |
||
right: '' |
||
}); |
||
} |
||
return this; |
||
}; |
||
|
||
/** |
||
To flash the scrollbar gadget for an amount of time defined in plugin settings (defaults to 1,5s). |
||
Useful if you want to show the user (e.g. on pageload) that there is more content waiting for him. |
||
@method flash |
||
@chainable |
||
@example |
||
$(".nano").nanoScroller({ flash: true }); |
||
*/ |
||
|
||
|
||
NanoScroll.prototype.flash = function() { |
||
var _this = this; |
||
if (this.iOSNativeScrolling) { |
||
return; |
||
} |
||
if (!this.isActive) { |
||
return; |
||
} |
||
this.reset(); |
||
this.pane.addClass('flashed'); |
||
setTimeout(function() { |
||
_this.pane.removeClass('flashed'); |
||
}, this.options.flashDelay); |
||
return this; |
||
}; |
||
|
||
return NanoScroll; |
||
|
||
})(); |
||
$.fn.nanoScroller = function(settings) { |
||
return this.each(function() { |
||
var options, scrollbar; |
||
if (!(scrollbar = this.nanoscroller)) { |
||
options = $.extend({}, defaults, settings); |
||
this.nanoscroller = scrollbar = new NanoScroll(this, options); |
||
} |
||
if (settings && typeof settings === "object") { |
||
$.extend(scrollbar.options, settings); |
||
if (settings.scrollBottom != null) { |
||
return scrollbar.scrollBottom(settings.scrollBottom); |
||
} |
||
if (settings.scrollTop != null) { |
||
return scrollbar.scrollTop(settings.scrollTop); |
||
} |
||
if (settings.scrollTo) { |
||
return scrollbar.scrollTo(settings.scrollTo); |
||
} |
||
if (settings.scroll === 'bottom') { |
||
return scrollbar.scrollBottom(0); |
||
} |
||
if (settings.scroll === 'top') { |
||
return scrollbar.scrollTop(0); |
||
} |
||
if (settings.scroll && settings.scroll instanceof $) { |
||
return scrollbar.scrollTo(settings.scroll); |
||
} |
||
if (settings.stop) { |
||
return scrollbar.stop(); |
||
} |
||
if (settings.destroy) { |
||
return scrollbar.destroy(); |
||
} |
||
if (settings.flash) { |
||
return scrollbar.flash(); |
||
} |
||
} |
||
return scrollbar.reset(); |
||
}); |
||
}; |
||
$.fn.nanoScroller.Constructor = NanoScroll; |
||
})(jQuery, window, document); |
||
|
||
/** |
||
* emojiarea - A rich textarea control that supports emojis, WYSIWYG-style. |
||
* Copyright (c) 2012 DIY Co |
||
* |
||
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this |
||
* file except in compliance with the License. You may obtain a copy of the License at: |
||
* http://www.apache.org/licenses/LICENSE-2.0 |
||
* |
||
* Unless required by applicable law or agreed to in writing, software distributed under |
||
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF |
||
* ANY KIND, either express or implied. See the License for the specific language |
||
* governing permissions and limitations under the License. |
||
* |
||
* @author Brian Reavis <[email protected]> |
||
*/ |
||
|
||
/** |
||
* This file also contains some modifications by Igor Zhukov in order to add custom scrollbars to EmojiMenu |
||
* See keyword `MODIFICATION` in source code. |
||
*/ |
||
|
||
(function($, window, document) { |
||
|
||
var ELEMENT_NODE = 1; |
||
var TEXT_NODE = 3; |
||
var TAGS_BLOCK = ['p', 'div', 'pre', 'form']; |
||
var KEY_ESC = 27; |
||
var KEY_TAB = 9; |
||
|
||
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
||
|
||
/*! MODIFICATION START |
||
Options 'spritesheetPath', 'spritesheetDimens', 'iconSize' added by Andre Staltz. |
||
*/ |
||
$.emojiarea = { |
||
path: '', |
||
spritesheetPath: '', |
||
spritesheetDimens: [], |
||
iconSize: 20, |
||
icons: {}, |
||
defaults: { |
||
button: null, |
||
buttonLabel: 'Emojis', |
||
buttonPosition: 'after' |
||
} |
||
}; |
||
/*! MODIFICATION END */ |
||
|
||
$.fn.emojiarea = function(options) { |
||
options = $.extend({}, $.emojiarea.defaults, options); |
||
return this.each(function() { |
||
var $textarea = $(this); |
||
if ('contentEditable' in document.body && options.wysiwyg !== false) { |
||
new EmojiArea_WYSIWYG($textarea, options); |
||
} else { |
||
new EmojiArea_Plain($textarea, options); |
||
} |
||
}); |
||
}; |
||
|
||
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
||
|
||
var util = {}; |
||
|
||
util.restoreSelection = (function() { |
||
if (window.getSelection) { |
||
return function(savedSelection) { |
||
var sel = window.getSelection(); |
||
sel.removeAllRanges(); |
||
for (var i = 0, len = savedSelection.length; i < len; ++i) { |
||
sel.addRange(savedSelection[i]); |
||
} |
||
}; |
||
} else if (document.selection && document.selection.createRange) { |
||
return function(savedSelection) { |
||
if (savedSelection) { |
||
savedSelection.select(); |
||
} |
||
}; |
||
} |
||
})(); |
||
|
||
util.saveSelection = (function() { |
||
if (window.getSelection) { |
||
return function() { |
||
var sel = window.getSelection(), ranges = []; |
||
if (sel.rangeCount) { |
||
for (var i = 0, len = sel.rangeCount; i < len; ++i) { |
||
ranges.push(sel.getRangeAt(i)); |
||
} |
||
} |
||
return ranges; |
||
}; |
||
} else if (document.selection && document.selection.createRange) { |
||
return function() { |
||
var sel = document.selection; |
||
return (sel.type.toLowerCase() !== 'none') ? sel.createRange() : null; |
||
}; |
||
} |
||
})(); |
||
|
||
util.replaceSelection = (function() { |
||
if (window.getSelection) { |
||
return function(content) { |
||
var range, sel = window.getSelection(); |
||
var node = typeof content === 'string' ? document.createTextNode(content) : content; |
||
if (sel.getRangeAt && sel.rangeCount) { |
||
range = sel.getRangeAt(0); |
||
range.deleteContents(); |
||
range.insertNode(document.createTextNode(' ')); |
||
range.insertNode(node); |
||
range.setStart(node, 0); |
||
|
||
window.setTimeout(function() { |
||
range = document.createRange(); |
||
range.setStartAfter(node); |
||
range.collapse(true); |
||
sel.removeAllRanges(); |
||
sel.addRange(range); |
||
}, 0); |
||
} |
||
} |
||
} else if (document.selection && document.selection.createRange) { |
||
return function(content) { |
||
var range = document.selection.createRange(); |
||
if (typeof content === 'string') { |
||
range.text = content; |
||
} else { |
||
range.pasteHTML(content.outerHTML); |
||
} |
||
} |
||
} |
||
})(); |
||
|
||
util.insertAtCursor = function(text, el) { |
||
text = ' ' + text; |
||
var val = el.value, endIndex, startIndex, range; |
||
if (typeof el.selectionStart != 'undefined' && typeof el.selectionEnd != 'undefined') { |
||
startIndex = el.selectionStart; |
||
endIndex = el.selectionEnd; |
||
el.value = val.substring(0, startIndex) + text + val.substring(el.selectionEnd); |
||
el.selectionStart = el.selectionEnd = startIndex + text.length; |
||
} else if (typeof document.selection != 'undefined' && typeof document.selection.createRange != 'undefined') { |
||
el.focus(); |
||
range = document.selection.createRange(); |
||
range.text = text; |
||
range.select(); |
||
} |
||
}; |
||
|
||
util.extend = function(a, b) { |
||
if (typeof a === 'undefined' || !a) { a = {}; } |
||
if (typeof b === 'object') { |
||
for (var key in b) { |
||
if (b.hasOwnProperty(key)) { |
||
a[key] = b[key]; |
||
} |
||
} |
||
} |
||
return a; |
||
}; |
||
|
||
util.escapeRegex = function(str) { |
||
return (str + '').replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1'); |
||
}; |
||
|
||
util.htmlEntities = function(str) { |
||
return String(str).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"'); |
||
}; |
||
|
||
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
||
|
||
var EmojiArea = function() {}; |
||
|
||
EmojiArea.prototype.setup = function() { |
||
var self = this; |
||
|
||
this.$editor.on('focus', function() { self.hasFocus = true; }); |
||
this.$editor.on('blur', function() { self.hasFocus = false; }); |
||
|
||
this.setupButton(); |
||
}; |
||
|
||
EmojiArea.prototype.setupButton = function() { |
||
var self = this; |
||
var $button; |
||
|
||
if (this.options.button) { |
||
$button = $(this.options.button); |
||
} else if (this.options.button !== false) { |
||
$button = $('<a href="javascript:void(0)">'); |
||
$button.html(this.options.buttonLabel); |
||
$button.addClass('emoji-button'); |
||
$button.attr({title: this.options.buttonLabel}); |
||
this.$editor[this.options.buttonPosition]($button); |
||
} else { |
||
$button = $(''); |
||
} |
||
|
||
$button.on('click', function(e) { |
||
EmojiMenu.show(self); |
||
e.stopPropagation(); |
||
}); |
||
|
||
this.$button = $button; |
||
}; |
||
|
||
/*! MODIFICATION START |
||
This function was modified by Andre Staltz so that the icon is created from a spritesheet. |
||
*/ |
||
EmojiArea.createIcon = function(emoji) { |
||
var category = emoji[0]; |
||
var row = emoji[1]; |
||
var column = emoji[2]; |
||
var name = emoji[3]; |
||
var filename = $.emojiarea.spritesheetPath; |
||
var xoffset = -($.emojiarea.iconSize * column); |
||
var yoffset = -($.emojiarea.iconSize * row); |
||
var scaledWidth = ($.emojiarea.spritesheetDimens[category][1] * $.emojiarea.iconSize); |
||
var scaledHeight = ($.emojiarea.spritesheetDimens[category][0] * $.emojiarea.iconSize); |
||
|
||
var style = 'display:inline-block;'; |
||
style += 'width:' + $.emojiarea.iconSize + 'px;'; |
||
style += 'height:' + $.emojiarea.iconSize + 'px;'; |
||
style += 'background:url(\'' + filename.replace('!',category) + '\') ' + xoffset + 'px ' + yoffset + 'px no-repeat;'; |
||
style += 'background-size:' + scaledWidth + 'px ' + scaledHeight + 'px;'; |
||
return '<img src="img/blank.gif" class="img" style="'+ style +'" alt="' + util.htmlEntities(name) + '">'; |
||
}; |
||
/*! MODIFICATION END */ |
||
|
||
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
||
|
||
/** |
||
* Editor (plain-text) |
||
* |
||
* @constructor |
||
* @param {object} $textarea |
||
* @param {object} options |
||
*/ |
||
|
||
var EmojiArea_Plain = function($textarea, options) { |
||
this.options = options; |
||
this.$textarea = $textarea; |
||
this.$editor = $textarea; |
||
this.setup(); |
||
}; |
||
|
||
EmojiArea_Plain.prototype.insert = function(emoji) { |
||
if (!$.emojiarea.icons.hasOwnProperty(emoji)) return; |
||
util.insertAtCursor(emoji, this.$textarea[0]); |
||
this.$textarea.trigger('change'); |
||
}; |
||
|
||
EmojiArea_Plain.prototype.val = function() { |
||
return this.$textarea.val(); |
||
}; |
||
|
||
util.extend(EmojiArea_Plain.prototype, EmojiArea.prototype); |
||
|
||
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
||
|
||
/** |
||
* Editor (rich) |
||
* |
||
* @constructor |
||
* @param {object} $textarea |
||
* @param {object} options |
||
*/ |
||
|
||
var EmojiArea_WYSIWYG = function($textarea, options) { |
||
var self = this; |
||
|
||
this.options = options || {}; |
||
this.$textarea = $textarea; |
||
this.$editor = $('<div>').addClass('emoji-wysiwyg-editor'); |
||
this.$editor.text($textarea.val()); |
||
this.$editor.attr({contenteditable: 'true'}); |
||
/*! MODIFICATION START |
||
Following code was modified by Igor Zhukov, in order to improve rich text paste |
||
*/ |
||
var changeEvents = 'blur change'; |
||
if (!this.options.norealTime) { |
||
changeEvents += ' keyup'; |
||
} |
||
this.$editor.on(changeEvents, function(e) { return self.onChange.apply(self, [e]); }); |
||
this.$editor.on('paste', function(e) { return self.onPaste.apply(self, [e]); }); |
||
/*! MODIFICATION END */ |
||
|
||
this.$editor.on('mousedown focus', function() { document.execCommand('enableObjectResizing', false, false); }); |
||
this.$editor.on('blur', function() { document.execCommand('enableObjectResizing', true, true); }); |
||
|
||
var html = this.$editor.text(); |
||
var emojis = $.emojiarea.icons; |
||
for (var key in emojis) { |
||
if (emojis.hasOwnProperty(key)) { |
||
/* MODIFICATION: Following line was modified by Andre Staltz, to use new implementation of createIcon function.*/ |
||
html = html.replace(new RegExp(util.escapeRegex(key), 'g'), EmojiArea.createIcon(emojis[key])); |
||
} |
||
} |
||
this.$editor.html(html); |
||
|
||
$textarea.hide().after(this.$editor); |
||
|
||
this.setup(); |
||
|
||
/* MODIFICATION: Following line was modified by Igor Zhukov, in order to improve emoji insert behaviour */ |
||
$(document.body).on('mousedown', function() { |
||
if (self.hasFocus) { |
||
self.selection = util.saveSelection(); |
||
} |
||
}); |
||
}; |
||
|
||
/*! MODIFICATION START |
||
Following code was modified by Igor Zhukov, in order to improve rich text paste |
||
*/ |
||
EmojiArea_WYSIWYG.prototype.onPaste = function(e) { |
||
var cData = (e.originalEvent || e).clipboardData, |
||
items = cData && cData.items || [], |
||
i; |
||
for (i = 0; i < items.length; i++) { |
||
if (items[i].kind == 'file') { |
||
e.preventDefault(); |
||
return true; |
||
} |
||
} |
||
|
||
var text = (e.originalEvent || e).clipboardData.getData('text/plain'), |
||
self = this; |
||
setTimeout(function () { |
||
self.onChange(); |
||
}, 0); |
||
if (text.length) { |
||
document.execCommand('insertText', false, text); |
||
return cancelEvent(e); |
||
} |
||
return true; |
||
}; |
||
/*! MODIFICATION END */ |
||
|
||
EmojiArea_WYSIWYG.prototype.onChange = function(e) { |
||
this.$textarea.val(this.val()).trigger('change'); |
||
}; |
||
|
||
EmojiArea_WYSIWYG.prototype.insert = function(emoji) { |
||
var content; |
||
/* MODIFICATION: Following line was modified by Andre Staltz, to use new implementation of createIcon function.*/ |
||
var $img = $(EmojiArea.createIcon($.emojiarea.icons[emoji])); |
||
if ($img[0].attachEvent) { |
||
$img[0].attachEvent('onresizestart', function(e) { e.returnValue = false; }, false); |
||
} |
||
|
||
this.$editor.trigger('focus'); |
||
if (this.selection) { |
||
util.restoreSelection(this.selection); |
||
} |
||
try { util.replaceSelection($img[0]); } catch (e) {} |
||
|
||
/*! MODIFICATION START |
||
Following code was modified by Igor Zhukov, in order to improve selection handling |
||
*/ |
||
var self = this; |
||
setTimeout(function () { |
||
self.selection = util.saveSelection(); |
||
}, 100); |
||
/*! MODIFICATION END */ |
||
|
||
this.onChange(); |
||
}; |
||
|
||
EmojiArea_WYSIWYG.prototype.val = function() { |
||
var lines = []; |
||
var line = []; |
||
|
||
var flush = function() { |
||
lines.push(line.join('')); |
||
line = []; |
||
}; |
||
|
||
var sanitizeNode = function(node) { |
||
if (node.nodeType === TEXT_NODE) { |
||
line.push(node.nodeValue); |
||
} else if (node.nodeType === ELEMENT_NODE) { |
||
var tagName = node.tagName.toLowerCase(); |
||
var isBlock = TAGS_BLOCK.indexOf(tagName) !== -1; |
||
|
||
if (isBlock && line.length) flush(); |
||
|
||
if (tagName === 'img') { |
||
var alt = node.getAttribute('alt') || ''; |
||
if (alt) line.push(alt); |
||
return; |
||
} else if (tagName === 'br') { |
||
flush(); |
||
} |
||
|
||
var children = node.childNodes; |
||
for (var i = 0; i < children.length; i++) { |
||
sanitizeNode(children[i]); |
||
} |
||
|
||
if (isBlock && line.length) flush(); |
||
} |
||
}; |
||
|
||
var children = this.$editor[0].childNodes; |
||
for (var i = 0; i < children.length; i++) { |
||
sanitizeNode(children[i]); |
||
} |
||
|
||
if (line.length) flush(); |
||
|
||
return lines.join('\n'); |
||
}; |
||
|
||
util.extend(EmojiArea_WYSIWYG.prototype, EmojiArea.prototype); |
||
|
||
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
||
|
||
/** |
||
* Emoji Dropdown Menu |
||
* |
||
* @constructor |
||
* @param {object} emojiarea |
||
*/ |
||
var EmojiMenu = function() { |
||
var self = this; |
||
var $body = $(document.body); |
||
var $window = $(window); |
||
|
||
this.visible = false; |
||
this.emojiarea = null; |
||
this.$menu = $('<div>'); |
||
this.$menu.addClass('emoji-menu'); |
||
this.$menu.hide(); |
||
|
||
/*! MODIFICATION START |
||
Following code was modified by Igor Zhukov, in order to add scrollbars and tail to EmojiMenu |
||
Also modified by Andre Staltz, to include tabs for categories, on the menu header. |
||
*/ |
||
this.$itemsTailWrap = $('<div class="emoji-items-wrap1"></div>').appendTo(this.$menu); |
||
this.$categoryTabs = $('<table class="emoji-menu-tabs"><tr>' + |
||
'<td><a class="emoji-menu-tab icon-smile" ></a></td>' + |
||
'<td><a class="emoji-menu-tab icon-flower"></a></td>' + |
||
'<td><a class="emoji-menu-tab icon-bell"></a></td>' + |
||
'<td><a class="emoji-menu-tab icon-car"></a></td>' + |
||
'<td><a class="emoji-menu-tab icon-grid"></a></td>' + |
||
'</tr></table>').appendTo(this.$itemsTailWrap); |
||
this.$itemsWrap = $('<div class="emoji-items-wrap nano"></div>').appendTo(this.$itemsTailWrap); |
||
this.$items = $('<div class="emoji-items content">').appendTo(this.$itemsWrap); |
||
$('<div class="emoji-menu-tail">').appendTo(this.$menu); |
||
/*! MODIFICATION END */ |
||
|
||
$body.append(this.$menu); |
||
|
||
/*! MODIFICATION: Following line is added by Igor Zhukov, in order to add scrollbars to EmojiMenu */ |
||
this.$itemsWrap.nanoScroller({preventPageScrolling: true, tabIndex: -1}); |
||
|
||
$body.on('keydown', function(e) { |
||
if (e.keyCode === KEY_ESC || e.keyCode === KEY_TAB) { |
||
self.hide(); |
||
} |
||
}); |
||
|
||
$body.on('mouseup', function(e) { |
||
/*! MODIFICATION START |
||
Following code was added by Igor Zhukov, in order to prevent close on click on EmojiMenu scrollbar |
||
*/ |
||
e = e.originalEvent || e; |
||
var target = e.originalTarget || e.target || window; |
||
while (target && target != window) { |
||
target = target.parentNode; |
||
if (target == self.$menu[0] || self.emojiarea && target == self.emojiarea.$button[0]) { |
||
return; |
||
} |
||
} |
||
/*! MODIFICATION END */ |
||
self.hide(); |
||
}); |
||
|
||
$window.on('resize', function() { |
||
if (self.visible) self.reposition(); |
||
}); |
||
|
||
this.$menu.on('mouseup', 'a', function(e) { |
||
e.stopPropagation(); |
||
return false; |
||
}); |
||
|
||
this.$menu.on('click', 'a', function(e) { |
||
/*! MODIFICATION START |
||
Following code was modified by Andre Staltz, to capture clicks on category tabs and change the category selection. |
||
*/ |
||
if ($(this).hasClass('emoji-menu-tab')) { |
||
if (self.getTabIndex(this) !== self.currentCategory) { |
||
self.selectCategory(self.getTabIndex(this)); |
||
} |
||
return false; |
||
} |
||
/*! MODIFICATION END */ |
||
var emoji = $('.label', $(this)).text(); |
||
window.setTimeout(function() { |
||
self.onItemSelected(emoji); |
||
/*! MODIFICATION START |
||
Following code was modified by Igor Zhukov, in order to close only on ctrl-, alt- emoji select |
||
*/ |
||
if (e.ctrlKey || e.metaKey) { |
||
self.hide(); |
||
} |
||
/*! MODIFICATION END */ |
||
}, 0); |
||
e.stopPropagation(); |
||
return false; |
||
}); |
||
|
||
/* MODIFICATION: Following line was modified by Andre Staltz, in order to select a default category. */ |
||
this.selectCategory(0); |
||
}; |
||
|
||
/*! MODIFICATION START |
||
Following code was added by Andre Staltz, to implement category selection. |
||
*/ |
||
EmojiMenu.prototype.getTabIndex = function(tab) { |
||
return this.$categoryTabs.find('.emoji-menu-tab').index(tab); |
||
}; |
||
|
||
EmojiMenu.prototype.selectCategory = function(category) { |
||
var self = this; |
||
this.$categoryTabs.find('.emoji-menu-tab').each(function(index) { |
||
if (index === category) { |
||
this.className += '-selected'; |
||
} |
||
else { |
||
this.className = this.className.replace('-selected', ''); |
||
} |
||
}); |
||
this.currentCategory = category; |
||
this.load(category); |
||
this.$itemsWrap.nanoScroller({ scroll: 'top' }); |
||
}; |
||
/*! MODIFICATION END */ |
||
|
||
EmojiMenu.prototype.onItemSelected = function(emoji) { |
||
this.emojiarea.insert(emoji); |
||
}; |
||
|
||
/* MODIFICATION: The following function argument was modified by Andre Staltz, in order to load only icons from a category. */ |
||
EmojiMenu.prototype.load = function(category) { |
||
var html = []; |
||
var options = $.emojiarea.icons; |
||
var path = $.emojiarea.path; |
||
if (path.length && path.charAt(path.length - 1) !== '/') { |
||
path += '/'; |
||
} |
||
|
||
for (var key in options) { |
||
/* MODIFICATION: The following 2 lines were modified by Andre Staltz, in order to load only icons from the specified category. */ |
||
if (options.hasOwnProperty(key) && options[key][0] === category) { |
||
html.push('<a href="javascript:void(0)" title="' + util.htmlEntities(key) + '">' + EmojiArea.createIcon(options[key]) + '<span class="label">' + util.htmlEntities(key) + '</span></a>'); |
||
} |
||
} |
||
|
||
this.$items.html(html.join('')); |
||
|
||
/*! MODIFICATION: Following 4 lines were added by Igor Zhukov, in order to add scrollbars to EmojiMenu */ |
||
var self = this; |
||
setTimeout(function () { |
||
self.$itemsWrap.nanoScroller(); |
||
}, 100); |
||
}; |
||
|
||
EmojiMenu.prototype.reposition = function() { |
||
var $button = this.emojiarea.$button; |
||
var offset = $button.offset(); |
||
offset.top += $button.outerHeight(); |
||
offset.left += Math.round($button.outerWidth() / 2); |
||
|
||
this.$menu.css({ |
||
top: offset.top, |
||
left: offset.left |
||
}); |
||
}; |
||
|
||
EmojiMenu.prototype.hide = function(callback) { |
||
if (this.emojiarea) { |
||
this.emojiarea.menu = null; |
||
this.emojiarea.$button.removeClass('on'); |
||
this.emojiarea = null; |
||
} |
||
|
||
|
||
this.visible = false; |
||
this.$menu.hide(); |
||
}; |
||
|
||
EmojiMenu.prototype.show = function(emojiarea) { |
||
/* MODIFICATION: Following line was modified by Igor Zhukov, in order to improve EmojiMenu behaviour */ |
||
if (this.emojiarea && this.emojiarea === emojiarea) return this.hide(); |
||
emojiarea.$button.addClass('on'); |
||
this.emojiarea = emojiarea; |
||
this.emojiarea.menu = this; |
||
|
||
this.reposition(); |
||
this.$menu.show(); |
||
this.visible = true; |
||
}; |
||
|
||
EmojiMenu.show = (function() { |
||
var menu = null; |
||
return function(emojiarea) { |
||
menu = menu || new EmojiMenu(); |
||
menu.show(emojiarea); |
||
}; |
||
})(); |
||
|
||
})(jQuery, window, document); |
||
/** |
||
* @license AngularJS v1.2.9 |
||
* (c) 2010-2014 Google, Inc. http://angularjs.org |
||
* License: MIT |
||
*/ |
||
(function(window, document, undefined) {'use strict'; |
||
|
||
/** |
||
* @description |
||
* |
||
* This object provides a utility for producing rich Error messages within |
||
* Angular. It can be called as follows: |
||
* |
||
* var exampleMinErr = minErr('example'); |
||
* throw exampleMinErr('one', 'This {0} is {1}', foo, bar); |
||
* |
||
* The above creates an instance of minErr in the example namespace. The |
||
* resulting error will have a namespaced error code of example.one. The |
||
* resulting error will replace {0} with the value of foo, and {1} with the |
||
* value of bar. The object is not restricted in the number of arguments it can |
||
* take. |
||
* |
||
* If fewer arguments are specified than necessary for interpolation, the extra |
||
* interpolation markers will be preserved in the final string. |
||
* |
||
* Since data will be parsed statically during a build step, some restrictions |
||
* are applied with respect to how minErr instances are created and called. |
||
* Instances should have names of the form namespaceMinErr for a minErr created |
||
* using minErr('namespace') . Error codes, namespaces and template strings |
||
* should all be static strings, not variables or general expressions. |
||
* |
||
* @param {string} module The namespace to use for the new minErr instance. |
||
* @returns {function(string, string, ...): Error} instance |
||
*/ |
||
|
||
function minErr(module) { |
||
return function () { |
||
var code = arguments[0], |
||
prefix = '[' + (module ? module + ':' : '') + code + '] ', |
||
template = arguments[1], |
||
templateArgs = arguments, |
||
stringify = function (obj) { |
||
if (typeof obj === 'function') { |
||
return obj.toString().replace(/ \{[\s\S]*$/, ''); |
||
} else if (typeof obj === 'undefined') { |
||
return 'undefined'; |
||
} else if (typeof obj !== 'string') { |
||
return JSON.stringify(obj); |
||
} |
||
return obj; |
||
}, |
||
message, i; |
||
|
||
message = prefix + template.replace(/\{\d+\}/g, function (match) { |
||
var index = +match.slice(1, -1), arg; |
||
|
||
if (index + 2 < templateArgs.length) { |
||
arg = templateArgs[index + 2]; |
||
if (typeof arg === 'function') { |
||
return arg.toString().replace(/ ?\{[\s\S]*$/, ''); |
||
} else if (typeof arg === 'undefined') { |
||
return 'undefined'; |
||
} else if (typeof arg !== 'string') { |
||
return toJson(arg); |
||
} |
||
return arg; |
||
} |
||
return match; |
||
}); |
||
|
||
message = message + '\nhttp://errors.angularjs.org/1.2.9/' + |
||
(module ? module + '/' : '') + code; |
||
for (i = 2; i < arguments.length; i++) { |
||
message = message + (i == 2 ? '?' : '&') + 'p' + (i-2) + '=' + |
||
encodeURIComponent(stringify(arguments[i])); |
||
} |
||
|
||
return new Error(message); |
||
}; |
||
} |
||
|
||
/* We need to tell jshint what variables are being exported */ |
||
/* global |
||
-angular, |
||
-msie, |
||
-jqLite, |
||
-jQuery, |
||
-slice, |
||
-push, |
||
-toString, |
||
-ngMinErr, |
||
-_angular, |
||
-angularModule, |
||
-nodeName_, |
||
-uid, |
||
|
||
-lowercase, |
||
-uppercase, |
||
-manualLowercase, |
||
-manualUppercase, |
||
-nodeName_, |
||
-isArrayLike, |
||
-forEach, |
||
-sortedKeys, |
||
-forEachSorted, |
||
-reverseParams, |
||
-nextUid, |
||
-setHashKey, |
||
-extend, |
||
-int, |
||
-inherit, |
||
-noop, |
||
-identity, |
||
-valueFn, |
||
-isUndefined, |
||
-isDefined, |
||
-isObject, |
||
-isString, |
||
-isNumber, |
||
-isDate, |
||
-isArray, |
||
-isFunction, |
||
-isRegExp, |
||
-isWindow, |
||
-isScope, |
||
-isFile, |
||
-isBoolean, |
||
-trim, |
||
-isElement, |
||
-makeMap, |
||
-map, |
||
-size, |
||
-includes, |
||
-indexOf, |
||
-arrayRemove, |
||
-isLeafNode, |
||
-copy, |
||
-shallowCopy, |
||
-equals, |
||
-csp, |
||
-concat, |
||
-sliceArgs, |
||
-bind, |
||
-toJsonReplacer, |
||
-toJson, |
||
-fromJson, |
||
-toBoolean, |
||
-startingTag, |
||
-tryDecodeURIComponent, |
||
-parseKeyValue, |
||
-toKeyValue, |
||
-encodeUriSegment, |
||
-encodeUriQuery, |
||
-angularInit, |
||
-bootstrap, |
||
-snake_case, |
||
-bindJQuery, |
||
-assertArg, |
||
-assertArgFn, |
||
-assertNotHasOwnProperty, |
||
-getter, |
||
-getBlockElements, |
||
|
||
*/ |
||
|
||
//////////////////////////////////// |
||
|
||
/** |
||
* @ngdoc function |
||
* @name angular.lowercase |
||
* @function |
||
* |
||
* @description Converts the specified string to lowercase. |
||
* @param {string} string String to be converted to lowercase. |
||
* @returns {string} Lowercased string. |
||
*/ |
||
var lowercase = function(string){return isString(string) ? string.toLowerCase() : string;}; |
||
|
||
|
||
/** |
||
* @ngdoc function |
||
* @name angular.uppercase |
||
* @function |
||
* |
||
* @description Converts the specified string to uppercase. |
||
* @param {string} string String to be converted to uppercase. |
||
* @returns {string} Uppercased string. |
||
*/ |
||
var uppercase = function(string){return isString(string) ? string.toUpperCase() : string;}; |
||
|
||
|
||
var manualLowercase = function(s) { |
||
/* jshint bitwise: false */ |
||
return isString(s) |
||
? s.replace(/[A-Z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) | 32);}) |
||
: s; |
||
}; |
||
var manualUppercase = function(s) { |
||
/* jshint bitwise: false */ |
||
return isString(s) |
||
? s.replace(/[a-z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) & ~32);}) |
||
: s; |
||
}; |
||
|
||
|
||
// String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish |
||
// locale, for this reason we need to detect this case and redefine lowercase/uppercase methods |
||
// with correct but slower alternatives. |
||
if ('i' !== 'I'.toLowerCase()) { |
||
lowercase = manualLowercase; |
||
uppercase = manualUppercase; |
||
} |
||
|
||
|
||
var /** holds major version number for IE or NaN for real browsers */ |
||
msie, |
||
jqLite, // delay binding since jQuery could be loaded after us. |
||
jQuery, // delay binding |
||
slice = [].slice, |
||
push = [].push, |
||
toString = Object.prototype.toString, |
||
ngMinErr = minErr('ng'), |
||
|
||
|
||
_angular = window.angular, |
||
/** @name angular */ |
||
angular = window.angular || (window.angular = {}), |
||
angularModule, |
||
nodeName_, |
||
uid = ['0', '0', '0']; |
||
|
||
/** |
||
* IE 11 changed the format of the UserAgent string. |
||
* See http://msdn.microsoft.com/en-us/library/ms537503.aspx |
||
*/ |
||
msie = int((/msie (\d+)/.exec(lowercase(navigator.userAgent)) || [])[1]); |
||
if (isNaN(msie)) { |
||
msie = int((/trident\/.*; rv:(\d+)/.exec(lowercase(navigator.userAgent)) || [])[1]); |
||
} |
||
|
||
|
||
/** |
||
* @private |
||
* @param {*} obj |
||
* @return {boolean} Returns true if `obj` is an array or array-like object (NodeList, Arguments, |
||
* String ...) |
||
*/ |
||
function isArrayLike(obj) { |
||
if (obj == null || isWindow(obj)) { |
||
return false; |
||
} |
||
|
||
var length = obj.length; |
||
|
||
if (obj.nodeType === 1 && length) { |
||
return true; |
||
} |
||
|
||
return isString(obj) || isArray(obj) || length === 0 || |
||
typeof length === 'number' && length > 0 && (length - 1) in obj; |
||
} |
||
|
||
/** |
||
* @ngdoc function |
||
* @name angular.forEach |
||
* @function |
||
* |
||
* @description |
||
* Invokes the `iterator` function once for each item in `obj` collection, which can be either an |
||
* object or an array. The `iterator` function is invoked with `iterator(value, key)`, where `value` |
||
* is the value of an object property or an array element and `key` is the object property key or |
||
* array element index. Specifying a `context` for the function is optional. |
||
* |
||
* It is worth nothing that `.forEach` does not iterate over inherited properties because it filters |
||
* using the `hasOwnProperty` method. |
||
* |
||
<pre> |
||
var values = {name: 'misko', gender: 'male'}; |
||
var log = []; |
||
angular.forEach(values, function(value, key){ |
||
this.push(key + ': ' + value); |
||
}, log); |
||
expect(log).toEqual(['name: misko', 'gender:male']); |
||
</pre> |
||
* |
||
* @param {Object|Array} obj Object to iterate over. |
||
* @param {Function} iterator Iterator function. |
||
* @param {Object=} context Object to become context (`this`) for the iterator function. |
||
* @returns {Object|Array} Reference to `obj`. |
||
*/ |
||
function forEach(obj, iterator, context) { |
||
var key; |
||
if (obj) { |
||
if (isFunction(obj)){ |
||
for (key in obj) { |
||
// Need to check if hasOwnProperty exists, |
||
// as on IE8 the result of querySelectorAll is an object without a hasOwnProperty function |
||
if (key != 'prototype' && key != 'length' && key != 'name' && (!obj.hasOwnProperty || obj.hasOwnProperty(key))) { |
||
iterator.call(context, obj[key], key); |
||
} |
||
} |
||
} else if (obj.forEach && obj.forEach !== forEach) { |
||
obj.forEach(iterator, context); |
||
} else if (isArrayLike(obj)) { |
||
for (key = 0; key < obj.length; key++) |
||
iterator.call(context, obj[key], key); |
||
} else { |
||
for (key in obj) { |
||
if (obj.hasOwnProperty(key)) { |
||
iterator.call(context, obj[key], key); |
||
} |
||
} |
||
} |
||
} |
||
return obj; |
||
} |
||
|
||
function sortedKeys(obj) { |
||
var keys = []; |
||
for (var key in obj) { |
||
if (obj.hasOwnProperty(key)) { |
||
keys.push(key); |
||
} |
||
} |
||
return keys.sort(); |
||
} |
||
|
||
function forEachSorted(obj, iterator, context) { |
||
var keys = sortedKeys(obj); |
||
for ( var i = 0; i < keys.length; i++) { |
||
iterator.call(context, obj[keys[i]], keys[i]); |
||
} |
||
return keys; |
||
} |
||
|
||
|
||
/** |
||
* when using forEach the params are value, key, but it is often useful to have key, value. |
||
* @param {function(string, *)} iteratorFn |
||
* @returns {function(*, string)} |
||
*/ |
||
function reverseParams(iteratorFn) { |
||
return function(value, key) { iteratorFn(key, value); }; |
||
} |
||
|
||
/** |
||
* A consistent way of creating unique IDs in angular. The ID is a sequence of alpha numeric |
||
* characters such as '012ABC'. The reason why we are not using simply a number counter is that |
||
* the number string gets longer over time, and it can also overflow, where as the nextId |
||
* will grow much slower, it is a string, and it will never overflow. |
||
* |
||
* @returns an unique alpha-numeric string |
||
*/ |
||
function nextUid() { |
||
var index = uid.length; |
||
var digit; |
||
|
||
while(index) { |
||
index--; |
||
digit = uid[index].charCodeAt(0); |
||
if (digit == 57 /*'9'*/) { |
||
uid[index] = 'A'; |
||
return uid.join(''); |
||
} |
||
if (digit == 90 /*'Z'*/) { |
||
uid[index] = '0'; |
||
} else { |
||
uid[index] = String.fromCharCode(digit + 1); |
||
return uid.join(''); |
||
} |
||
} |
||
uid.unshift('0'); |
||
return uid.join(''); |
||
} |
||
|
||
|
||
/** |
||
* Set or clear the hashkey for an object. |
||
* @param obj object |
||
* @param h the hashkey (!truthy to delete the hashkey) |
||
*/ |
||
function setHashKey(obj, h) { |
||
if (h) { |
||
obj.$$hashKey = h; |
||
} |
||
else { |
||
delete obj.$$hashKey; |
||
} |
||
} |
||
|
||
/** |
||
* @ngdoc function |
||
* @name angular.extend |
||
* @function |
||
* |
||
* @description |
||
* Extends the destination object `dst` by copying all of the properties from the `src` object(s) |
||
* to `dst`. You can specify multiple `src` objects. |
||
* |
||
* @param {Object} dst Destination object. |
||
* @param {...Object} src Source object(s). |
||
* @returns {Object} Reference to `dst`. |
||
*/ |
||
function extend(dst) { |
||
var h = dst.$$hashKey; |
||
forEach(arguments, function(obj){ |
||
if (obj !== dst) { |
||
forEach(obj, function(value, key){ |
||
dst[key] = value; |
||
}); |
||
} |
||
}); |
||
|
||
setHashKey(dst,h); |
||
return dst; |
||
} |
||
|
||
function int(str) { |
||
return parseInt(str, 10); |
||
} |
||
|
||
|
||
function inherit(parent, extra) { |
||
return extend(new (extend(function() {}, {prototype:parent}))(), extra); |
||
} |
||
|
||
/** |
||
* @ngdoc function |
||
* @name angular.noop |
||
* @function |
||
* |
||
* @description |
||
* A function that performs no operations. This function can be useful when writing code in the |
||
* functional style. |
||
<pre> |
||
function foo(callback) { |
||
var result = calculateResult(); |
||
(callback || angular.noop)(result); |
||
} |
||
</pre> |
||
*/ |
||
function noop() {} |
||
noop.$inject = []; |
||
|
||
|
||
/** |
||
* @ngdoc function |
||
* @name angular.identity |
||
* @function |
||
* |
||
* @description |
||
* A function that returns its first argument. This function is useful when writing code in the |
||
* functional style. |
||
* |
||
<pre> |
||
function transformer(transformationFn, value) { |
||
return (transformationFn || angular.identity)(value); |
||
}; |
||
</pre> |
||
*/ |
||
function identity($) {return $;} |
||
identity.$inject = []; |
||
|
||
|
||
function valueFn(value) {return function() {return value;};} |
||
|
||
/** |
||
* @ngdoc function |
||
* @name angular.isUndefined |
||
* @function |
||
* |
||
* @description |
||
* Determines if a reference is undefined. |
||
* |
||
* @param {*} value Reference to check. |
||
* @returns {boolean} True if `value` is undefined. |
||
*/ |
||
function isUndefined(value){return typeof value === 'undefined';} |
||
|
||
|
||
/** |
||
* @ngdoc function |
||
* @name angular.isDefined |
||
* @function |
||
* |
||
* @description |
||
* Determines if a reference is defined. |
||
* |
||
* @param {*} value Reference to check. |
||
* @returns {boolean} True if `value` is defined. |
||
*/ |
||
function isDefined(value){return typeof value !== 'undefined';} |
||
|
||
|
||
/** |
||
* @ngdoc function |
||
* @name angular.isObject |
||
* @function |
||
* |
||
* @description |
||
* Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not |
||
* considered to be objects. |
||
* |
||
* @param {*} value Reference to check. |
||
* @returns {boolean} True if `value` is an `Object` but not `null`. |
||
*/ |
||
function isObject(value){return value != null && typeof value === 'object';} |
||
|
||
|
||
/** |
||
* @ngdoc function |
||
* @name angular.isString |
||
* @function |
||
* |
||
* @description |
||
* Determines if a reference is a `String`. |
||
* |
||
* @param {*} value Reference to check. |
||
* @returns {boolean} True if `value` is a `String`. |
||
*/ |
||
function isString(value){return typeof value === 'string';} |
||
|
||
|
||
/** |
||
* @ngdoc function |
||
* @name angular.isNumber |
||
* @function |
||
* |
||
* @description |
||
* Determines if a reference is a `Number`. |
||
* |
||
* @param {*} value Reference to check. |
||
* @returns {boolean} True if `value` is a `Number`. |
||
*/ |
||
function isNumber(value){return typeof value === 'number';} |
||
|
||
|
||
/** |
||
* @ngdoc function |
||
* @name angular.isDate |
||
* @function |
||
* |
||
* @description |
||
* Determines if a value is a date. |
||
* |
||
* @param {*} value Reference to check. |
||
* @returns {boolean} True if `value` is a `Date`. |
||
*/ |
||
function isDate(value){ |
||
return toString.call(value) === '[object Date]'; |
||
} |
||
|
||
|
||
/** |
||
* @ngdoc function |
||
* @name angular.isArray |
||
* @function |
||
* |
||
* @description |
||
* Determines if a reference is an `Array`. |
||
* |
||
* @param {*} value Reference to check. |
||
* @returns {boolean} True if `value` is an `Array`. |
||
*/ |
||
function isArray(value) { |
||
return toString.call(value) === '[object Array]'; |
||
} |
||
|
||
|
||
/** |
||
* @ngdoc function |
||
* @name angular.isFunction |
||
* @function |
||
* |
||
* @description |
||
* Determines if a reference is a `Function`. |
||
* |
||
* @param {*} value Reference to check. |
||
* @returns {boolean} True if `value` is a `Function`. |
||
*/ |
||
function isFunction(value){return typeof value === 'function';} |
||
|
||
|
||
/** |
||
* Determines if a value is a regular expression object. |
||
* |
||
* @private |
||
* @param {*} value Reference to check. |
||
* @returns {boolean} True if `value` is a `RegExp`. |
||
*/ |
||
function isRegExp(value) { |
||
return toString.call(value) === '[object RegExp]'; |
||
} |
||
|
||
|
||
/** |
||
* Checks if `obj` is a window object. |
||
* |
||
* @private |
||
* @param {*} obj Object to check |
||
* @returns {boolean} True if `obj` is a window obj. |
||
*/ |
||
function isWindow(obj) { |
||
return obj && obj.document && obj.location && obj.alert && obj.setInterval; |
||
} |
||
|
||
|
||
function isScope(obj) { |
||
return obj && obj.$evalAsync && obj.$watch; |
||
} |
||
|
||
|
||
function isFile(obj) { |
||
return toString.call(obj) === '[object File]'; |
||
} |
||
|
||
|
||
function isBoolean(value) { |
||
return typeof value === 'boolean'; |
||
} |
||
|
||
|
||
var trim = (function() { |
||
// native trim is way faster: http://jsperf.com/angular-trim-test |
||
// but IE doesn't have it... :-( |
||
// TODO: we should move this into IE/ES5 polyfill |
||
if (!String.prototype.trim) { |
||
return function(value) { |
||
return isString(value) ? value.replace(/^\s\s*/, '').replace(/\s\s*$/, '') : value; |
||
}; |
||
} |
||
return function(value) { |
||
return isString(value) ? value.trim() : value; |
||
}; |
||
})(); |
||
|
||
|
||
/** |
||
* @ngdoc function |
||
* @name angular.isElement |
||
* @function |
||
* |
||
* @description |
||
* Determines if a reference is a DOM element (or wrapped jQuery element). |
||
* |
||
* @param {*} value Reference to check. |
||
* @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element). |
||
*/ |
||
function isElement(node) { |
||
return !!(node && |
||
(node.nodeName // we are a direct element |
||
|| (node.on && node.find))); // we have an on and find method part of jQuery API |
||
} |
||
|
||
/** |
||
* @param str 'key1,key2,...' |
||
* @returns {object} in the form of {key1:true, key2:true, ...} |
||
*/ |
||
function makeMap(str){ |
||
var obj = {}, items = str.split(","), i; |
||
for ( i = 0; i < items.length; i++ ) |
||
obj[ items[i] ] = true; |
||
return obj; |
||
} |
||
|
||
|
||
if (msie < 9) { |
||
nodeName_ = function(element) { |
||
element = element.nodeName ? element : element[0]; |
||
return (element.scopeName && element.scopeName != 'HTML') |
||
? uppercase(element.scopeName + ':' + element.nodeName) : element.nodeName; |
||
}; |
||
} else { |
||
nodeName_ = function(element) { |
||
return element.nodeName ? element.nodeName : element[0].nodeName; |
||
}; |
||
} |
||
|
||
|
||
function map(obj, iterator, context) { |
||
var results = []; |
||
forEach(obj, function(value, index, list) { |
||
results.push(iterator.call(context, value, index, list)); |
||
}); |
||
return results; |
||
} |
||
|
||
|
||
/** |
||
* @description |
||
* Determines the number of elements in an array, the number of properties an object has, or |
||
* the length of a string. |
||
* |
||
* Note: This function is used to augment the Object type in Angular expressions. See |
||
* {@link angular.Object} for more information about Angular arrays. |
||
* |
||
* @param {Object|Array|string} obj Object, array, or string to inspect. |
||
* @param {boolean} [ownPropsOnly=false] Count only "own" properties in an object |
||
* @returns {number} The size of `obj` or `0` if `obj` is neither an object nor an array. |
||
*/ |
||
function size(obj, ownPropsOnly) { |
||
var count = 0, key; |
||
|
||
if (isArray(obj) || isString(obj)) { |
||
return obj.length; |
||
} else if (isObject(obj)){ |
||
for (key in obj) |
||
if (!ownPropsOnly || obj.hasOwnProperty(key)) |
||
count++; |
||
} |
||
|
||
return count; |
||
} |
||
|
||
|
||
function includes(array, obj) { |
||
return indexOf(array, obj) != -1; |
||
} |
||
|
||
function indexOf(array, obj) { |
||
if (array.indexOf) return array.indexOf(obj); |
||
|
||
for (var i = 0; i < array.length; i++) { |
||
if (obj === array[i]) return i; |
||
} |
||
return -1; |
||
} |
||
|
||
function arrayRemove(array, value) { |
||
var index = indexOf(array, value); |
||
if (index >=0) |
||
array.splice(index, 1); |
||
return value; |
||
} |
||
|
||
function isLeafNode (node) { |
||
if (node) { |
||
switch (node.nodeName) { |
||
case "OPTION": |
||
case "PRE": |
||
case "TITLE": |
||
return true; |
||
} |
||
} |
||
return false; |
||
} |
||
|
||
/** |
||
* @ngdoc function |
||
* @name angular.copy |
||
* @function |
||
* |
||
* @description |
||
* Creates a deep copy of `source`, which should be an object or an array. |
||
* |
||
* * If no destination is supplied, a copy of the object or array is created. |
||
* * If a destination is provided, all of its elements (for array) or properties (for objects) |
||
* are deleted and then all elements/properties from the source are copied to it. |
||
* * If `source` is not an object or array (inc. `null` and `undefined`), `source` is returned. |
||
* * If `source` is identical to 'destination' an exception will be thrown. |
||
* |
||
* @param {*} source The source that will be used to make a copy. |
||
* Can be any type, including primitives, `null`, and `undefined`. |
||
* @param {(Object|Array)=} destination Destination into which the source is copied. If |
||
* provided, must be of the same type as `source`. |
||
* @returns {*} The copy or updated `destination`, if `destination` was specified. |
||
* |
||
* @example |
||
<doc:example> |
||
<doc:source> |
||
<div ng-controller="Controller"> |
||
<form novalidate class="simple-form"> |
||
Name: <input type="text" ng-model="user.name" /><br /> |
||
E-mail: <input type="email" ng-model="user.email" /><br /> |
||
Gender: <input type="radio" ng-model="user.gender" value="male" />male |
||
<input type="radio" ng-model="user.gender" value="female" />female<br /> |
||
<button ng-click="reset()">RESET</button> |
||
<button ng-click="update(user)">SAVE</button> |
||
</form> |
||
<pre>form = {{user | json}}</pre> |
||
<pre>master = {{master | json}}</pre> |
||
</div> |
||
|
||
<script> |
||
function Controller($scope) { |
||
$scope.master= {}; |
||
|
||
$scope.update = function(user) { |
||
// Example with 1 argument |
||
$scope.master= angular.copy(user); |
||
}; |
||
|
||
$scope.reset = function() { |
||
// Example with 2 arguments |
||
angular.copy($scope.master, $scope.user); |
||
}; |
||
|
||
$scope.reset(); |
||
} |
||
</script> |
||
</doc:source> |
||
</doc:example> |
||
*/ |
||
function copy(source, destination){ |
||
if (isWindow(source) || isScope(source)) { |
||
throw ngMinErr('cpws', |
||
"Can't copy! Making copies of Window or Scope instances is not supported."); |
||
} |
||
|
||
if (!destination) { |
||
destination = source; |
||
if (source) { |
||
if (isArray(source)) { |
||
destination = copy(source, []); |
||
} else if (isDate(source)) { |
||
destination = new Date(source.getTime()); |
||
} else if (isRegExp(source)) { |
||
destination = new RegExp(source.source); |
||
} else if (isObject(source)) { |
||
destination = copy(source, {}); |
||
} |
||
} |
||
} else { |
||
if (source === destination) throw ngMinErr('cpi', |
||
"Can't copy! Source and destination are identical."); |
||
if (isArray(source)) { |
||
destination.length = 0; |
||
for ( var i = 0; i < source.length; i++) { |
||
destination.push(copy(source[i])); |
||
} |
||
} else { |
||
var h = destination.$$hashKey; |
||
forEach(destination, function(value, key){ |
||
delete destination[key]; |
||
}); |
||
for ( var key in source) { |
||
destination[key] = copy(source[key]); |
||
} |
||
setHashKey(destination,h); |
||
} |
||
} |
||
return destination; |
||
} |
||
|
||
/** |
||
* Create a shallow copy of an object |
||
*/ |
||
function shallowCopy(src, dst) { |
||
dst = dst || {}; |
||
|
||
for(var key in src) { |
||
// shallowCopy is only ever called by $compile nodeLinkFn, which has control over src |
||
// so we don't need to worry about using our custom hasOwnProperty here |
||
if (src.hasOwnProperty(key) && key.charAt(0) !== '$' && key.charAt(1) !== '$') { |
||
dst[key] = src[key]; |
||
} |
||
} |
||
|
||
return dst; |
||
} |
||
|
||
|
||
/** |
||
* @ngdoc function |
||
* @name angular.equals |
||
* @function |
||
* |
||
* @description |
||
* Determines if two objects or two values are equivalent. Supports value types, regular |
||
* expressions, arrays and objects. |
||
* |
||
* Two objects or values are considered equivalent if at least one of the following is true: |
||
* |
||
* * Both objects or values pass `===` comparison. |
||
* * Both objects or values are of the same type and all of their properties are equal by |
||
* comparing them with `angular.equals`. |
||
* * Both values are NaN. (In JavaScript, NaN == NaN => false. But we consider two NaN as equal) |
||
* * Both values represent the same regular expression (In JavasScript, |
||
* /abc/ == /abc/ => false. But we consider two regular expressions as equal when their textual |
||
* representation matches). |
||
* |
||
* During a property comparison, properties of `function` type and properties with names |
||
* that begin with `$` are ignored. |
||
* |
||
* Scope and DOMWindow objects are being compared only by identify (`===`). |
||
* |
||
* @param {*} o1 Object or value to compare. |
||
* @param {*} o2 Object or value to compare. |
||
* @returns {boolean} True if arguments are equal. |
||
*/ |
||
function equals(o1, o2) { |
||
if (o1 === o2) return true; |
||
if (o1 === null || o2 === null) return false; |
||
if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN |
||
var t1 = typeof o1, t2 = typeof o2, length, key, keySet; |
||
if (t1 == t2) { |
||
if (t1 == 'object') { |
||
if (isArray(o1)) { |
||
if (!isArray(o2)) return false; |
||
if ((length = o1.length) == o2.length) { |
||
for(key=0; key<length; key++) { |
||
if (!equals(o1[key], o2[key])) return false; |
||
} |
||
return true; |
||
} |
||
} else if (isDate(o1)) { |
||
return isDate(o2) && o1.getTime() == o2.getTime(); |
||
} else if (isRegExp(o1) && isRegExp(o2)) { |
||
return o1.toString() == o2.toString(); |
||
} else { |
||
if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2) || isArray(o2)) return false; |
||
keySet = {}; |
||
for(key in o1) { |
||
if (key.charAt(0) === '$' || isFunction(o1[key])) continue; |
||
if (!equals(o1[key], o2[key])) return false; |
||
keySet[key] = true; |
||
} |
||
for(key in o2) { |
||
if (!keySet.hasOwnProperty(key) && |
||
key.charAt(0) !== '$' && |
||
o2[key] !== undefined && |
||
!isFunction(o2[key])) return false; |
||
} |
||
return true; |
||
} |
||
} |
||
} |
||
return false; |
||
} |
||
|
||
|
||
function csp() { |
||
return (document.securityPolicy && document.securityPolicy.isActive) || |
||
(document.querySelector && |
||
!!(document.querySelector('[ng-csp]') || document.querySelector('[data-ng-csp]'))); |
||
} |
||
|
||
|
||
function concat(array1, array2, index) { |
||
return array1.concat(slice.call(array2, index)); |
||
} |
||
|
||
function sliceArgs(args, startIndex) { |
||
return slice.call(args, startIndex || 0); |
||
} |
||
|
||
|
||
/* jshint -W101 */ |
||
/** |
||
* @ngdoc function |
||
* @name angular.bind |
||
* @function |
||
* |
||
* @description |
||
* Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for |
||
* `fn`). You can supply optional `args` that are prebound to the function. This feature is also |
||
* known as [partial application](http://en.wikipedia.org/wiki/Partial_application), as |
||
* distinguished from [function currying](http://en.wikipedia.org/wiki/Currying#Contrast_with_partial_function_application). |
||
* |
||
* @param {Object} self Context which `fn` should be evaluated in. |
||
* @param {function()} fn Function to be bound. |
||
* @param {...*} args Optional arguments to be prebound to the `fn` function call. |
||
* @returns {function()} Function that wraps the `fn` with all the specified bindings. |
||
*/ |
||
/* jshint +W101 */ |
||
function bind(self, fn) { |
||
var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : []; |
||
if (isFunction(fn) && !(fn instanceof RegExp)) { |
||
return curryArgs.length |
||
? function() { |
||
return arguments.length |
||
? fn.apply(self, curryArgs.concat(slice.call(arguments, 0))) |
||
: fn.apply(self, curryArgs); |
||
} |
||
: function() { |
||
return arguments.length |
||
? fn.apply(self, arguments) |
||
: fn.call(self); |
||
}; |
||
} else { |
||
// in IE, native methods are not functions so they cannot be bound (note: they don't need to be) |
||
return fn; |
||
} |
||
} |
||
|
||
|
||
function toJsonReplacer(key, value) { |
||
var val = value; |
||
|
||
if (typeof key === 'string' && key.charAt(0) === '$') { |
||
val = undefined; |
||
} else if (isWindow(value)) { |
||
val = '$WINDOW'; |
||
} else if (value && document === value) { |
||
val = '$DOCUMENT'; |
||
} else if (isScope(value)) { |
||
val = '$SCOPE'; |
||
} |
||
|
||
return val; |
||
} |
||
|
||
|
||
/** |
||
* @ngdoc function |
||
* @name angular.toJson |
||
* @function |
||
* |
||
* @description |
||
* Serializes input into a JSON-formatted string. Properties with leading $ characters will be |
||
* stripped since angular uses this notation internally. |
||
* |
||
* @param {Object|Array|Date|string|number} obj Input to be serialized into JSON. |
||
* @param {boolean=} pretty If set to true, the JSON output will contain newlines and whitespace. |
||
* @returns {string|undefined} JSON-ified string representing `obj`. |
||
*/ |
||
function toJson(obj, pretty) { |
||
if (typeof obj === 'undefined') return undefined; |
||
return JSON.stringify(obj, toJsonReplacer, pretty ? ' ' : null); |
||
} |
||
|
||
|
||
/** |
||
* @ngdoc function |
||
* @name angular.fromJson |
||
* @function |
||
* |
||
* @description |
||
* Deserializes a JSON string. |
||
* |
||
* @param {string} json JSON string to deserialize. |
||
* @returns {Object|Array|Date|string|number} Deserialized thingy. |
||
*/ |
||
function fromJson(json) { |
||
return isString(json) |
||
? JSON.parse(json) |
||
: json; |
||
} |
||
|
||
|
||
function toBoolean(value) { |
||
if (typeof value === 'function') { |
||
value = true; |
||
} else if (value && value.length !== 0) { |
||
var v = lowercase("" + value); |
||
value = !(v == 'f' || v == '0' || v == 'false' || v == 'no' || v == 'n' || v == '[]'); |
||
} else { |
||
value = false; |
||
} |
||
return value; |
||
} |
||
|
||
/** |
||
* @returns {string} Returns the string representation of the element. |
||
*/ |
||
function startingTag(element) { |
||
element = jqLite(element).clone(); |
||
try { |
||
// turns out IE does not let you set .html() on elements which |
||
// are not allowed to have children. So we just ignore it. |
||
element.empty(); |
||
} catch(e) {} |
||
// As Per DOM Standards |
||
var TEXT_NODE = 3; |
||
var elemHtml = jqLite('<div>').append(element).html(); |
||
try { |
||
return element[0].nodeType === TEXT_NODE ? lowercase(elemHtml) : |
||
elemHtml. |
||
match(/^(<[^>]+>)/)[1]. |
||
replace(/^<([\w\-]+)/, function(match, nodeName) { return '<' + lowercase(nodeName); }); |
||
} catch(e) { |
||
return lowercase(elemHtml); |
||
} |
||
|
||
} |
||
|
||
|
||
///////////////////////////////////////////////// |
||
|
||
/** |
||
* Tries to decode the URI component without throwing an exception. |
||
* |
||
* @private |
||
* @param str value potential URI component to check. |
||
* @returns {boolean} True if `value` can be decoded |
||
* with the decodeURIComponent function. |
||
*/ |
||
function tryDecodeURIComponent(value) { |
||
try { |
||
return decodeURIComponent(value); |
||
} catch(e) { |
||
// Ignore any invalid uri component |
||
} |
||
} |
||
|
||
|
||
/** |
||
* Parses an escaped url query string into key-value pairs. |
||
* @returns Object.<(string|boolean)> |
||
*/ |
||
function parseKeyValue(/**string*/keyValue) { |
||
var obj = {}, key_value, key; |
||
forEach((keyValue || "").split('&'), function(keyValue){ |
||
if ( keyValue ) { |
||
key_value = keyValue.split('='); |
||
key = tryDecodeURIComponent(key_value[0]); |
||
if ( isDefined(key) ) { |
||
var val = isDefined(key_value[1]) ? tryDecodeURIComponent(key_value[1]) : true; |
||
if (!obj[key]) { |
||
obj[key] = val; |
||
} else if(isArray(obj[key])) { |
||
obj[key].push(val); |
||
} else { |
||
obj[key] = [obj[key],val]; |
||
} |
||
} |
||
} |
||
}); |
||
return obj; |
||
} |
||
|
||
function toKeyValue(obj) { |
||
var parts = []; |
||
forEach(obj, function(value, key) { |
||
if (isArray(value)) { |
||
forEach(value, function(arrayValue) { |
||
parts.push(encodeUriQuery(key, true) + |
||
(arrayValue === true ? '' : '=' + encodeUriQuery(arrayValue, true))); |
||
}); |
||
} else { |
||
parts.push(encodeUriQuery(key, true) + |
||
(value === true ? '' : '=' + encodeUriQuery(value, true))); |
||
} |
||
}); |
||
return parts.length ? parts.join('&') : ''; |
||
} |
||
|
||
|
||
/** |
||
* We need our custom method because encodeURIComponent is too aggressive and doesn't follow |
||
* http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path |
||
* segments: |
||
* segment = *pchar |
||
* pchar = unreserved / pct-encoded / sub-delims / ":" / "@" |
||
* pct-encoded = "%" HEXDIG HEXDIG |
||
* unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" |
||
* sub-delims = "!" / "$" / "&" / "'" / "(" / ")" |
||
* / "*" / "+" / "," / ";" / "=" |
||
*/ |
||
function encodeUriSegment(val) { |
||
return encodeUriQuery(val, true). |
||
replace(/%26/gi, '&'). |
||
replace(/%3D/gi, '='). |
||
replace(/%2B/gi, '+'); |
||
} |
||
|
||
|
||
/** |
||
* This method is intended for encoding *key* or *value* parts of query component. We need a custom |
||
* method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be |
||
* encoded per http://tools.ietf.org/html/rfc3986: |
||
* query = *( pchar / "/" / "?" ) |
||
* pchar = unreserved / pct-encoded / sub-delims / ":" / "@" |
||
* unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" |
||
* pct-encoded = "%" HEXDIG HEXDIG |
||
* sub-delims = "!" / "$" / "&" / "'" / "(" / ")" |
||
* / "*" / "+" / "," / ";" / "=" |
||
*/ |
||
function encodeUriQuery(val, pctEncodeSpaces) { |
||
return encodeURIComponent(val). |
||
replace(/%40/gi, '@'). |
||
replace(/%3A/gi, ':'). |
||
replace(/%24/g, '$'). |
||
replace(/%2C/gi, ','). |
||
replace(/%20/g, (pctEncodeSpaces ? '%20' : '+')); |
||
} |
||
|
||
|
||
/** |
||
* @ngdoc directive |
||
* @name ng.directive:ngApp |
||
* |
||
* @element ANY |
||
* @param {angular.Module} ngApp an optional application |
||
* {@link angular.module module} name to load. |
||
* |
||
* @description |
||
* |
||
* Use this directive to **auto-bootstrap** an AngularJS application. The `ngApp` directive |
||
* designates the **root element** of the application and is typically placed near the root element |
||
* of the page - e.g. on the `<body>` or `<html>` tags. |
||
* |
||
* Only one AngularJS application can be auto-bootstrapped per HTML document. The first `ngApp` |
||
* found in the document will be used to define the root element to auto-bootstrap as an |
||
* application. To run multiple applications in an HTML document you must manually bootstrap them using |
||
* {@link angular.bootstrap} instead. AngularJS applications cannot be nested within each other. |
||
* |
||
* You can specify an **AngularJS module** to be used as the root module for the application. This |
||
* module will be loaded into the {@link AUTO.$injector} when the application is bootstrapped and |
||
* should contain the application code needed or have dependencies on other modules that will |
||
* contain the code. See {@link angular.module} for more information. |
||
* |
||
* In the example below if the `ngApp` directive were not placed on the `html` element then the |
||
* document would not be compiled, the `AppController` would not be instantiated and the `{{ a+b }}` |
||
* would not be resolved to `3`. |
||
* |
||
* `ngApp` is the easiest, and most common, way to bootstrap an application. |
||
* |
||
<example module="ngAppDemo"> |
||
<file name="index.html"> |
||
<div ng-controller="ngAppDemoController"> |
||
I can add: {{a}} + {{b}} = {{ a+b }} |
||
</file> |
||
<file name="script.js"> |
||
angular.module('ngAppDemo', []).controller('ngAppDemoController', function($scope) { |
||
$scope.a = 1; |
||
$scope.b = 2; |
||
}); |
||
</file> |
||
</example> |
||
* |
||
*/ |
||
function angularInit(element, bootstrap) { |
||
var elements = [element], |
||
appElement, |
||
module, |
||
names = ['ng:app', 'ng-app', 'x-ng-app', 'data-ng-app'], |
||
NG_APP_CLASS_REGEXP = /\sng[:\-]app(:\s*([\w\d_]+);?)?\s/; |
||
|
||
function append(element) { |
||
element && elements.push(element); |
||
} |
||
|
||
forEach(names, function(name) { |
||
names[name] = true; |
||
append(document.getElementById(name)); |
||
name = name.replace(':', '\\:'); |
||
if (element.querySelectorAll) { |
||
forEach(element.querySelectorAll('.' + name), append); |
||
forEach(element.querySelectorAll('.' + name + '\\:'), append); |
||
forEach(element.querySelectorAll('[' + name + ']'), append); |
||
} |
||
}); |
||
|
||
forEach(elements, function(element) { |
||
if (!appElement) { |
||
var className = ' ' + element.className + ' '; |
||
var match = NG_APP_CLASS_REGEXP.exec(className); |
||
if (match) { |
||
appElement = element; |
||
module = (match[2] || '').replace(/\s+/g, ','); |
||
} else { |
||
forEach(element.attributes, function(attr) { |
||
if (!appElement && names[attr.name]) { |
||
appElement = element; |
||
module = attr.value; |
||
} |
||
}); |
||
} |
||
} |
||
}); |
||
if (appElement) { |
||
bootstrap(appElement, module ? [module] : []); |
||
} |
||
} |
||
|
||
/** |
||
* @ngdoc function |
||
* @name angular.bootstrap |
||
* @description |
||
* Use this function to manually start up angular application. |
||
* |
||
* See: {@link guide/bootstrap Bootstrap} |
||
* |
||
* Note that ngScenario-based end-to-end tests cannot use this function to bootstrap manually. |
||
* They must use {@link api/ng.directive:ngApp ngApp}. |
||
* |
||
* @param {Element} element DOM element which is the root of angular application. |
||
* @param {Array<String|Function|Array>=} modules an array of modules to load into the application. |
||
* Each item in the array should be the name of a predefined module or a (DI annotated) |
||
* function that will be invoked by the injector as a run block. |
||
* See: {@link angular.module modules} |
||
* @returns {AUTO.$injector} Returns the newly created injector for this app. |
||
*/ |
||
function bootstrap(element, modules) { |
||
var doBootstrap = function() { |
||
element = jqLite(element); |
||
|
||
if (element.injector()) { |
||
var tag = (element[0] === document) ? 'document' : startingTag(element); |
||
throw ngMinErr('btstrpd', "App Already Bootstrapped with this Element '{0}'", tag); |
||
} |
||
|
||
modules = modules || []; |
||
modules.unshift(['$provide', function($provide) { |
||
$provide.value('$rootElement', element); |
||
}]); |
||
modules.unshift('ng'); |
||
var injector = createInjector(modules); |
||
injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector', '$animate', |
||
function(scope, element, compile, injector, animate) { |
||
scope.$apply(function() { |
||
element.data('$injector', injector); |
||
compile(element)(scope); |
||
}); |
||
}] |
||
); |
||
return injector; |
||
}; |
||
|
||
var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/; |
||
|
||
if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) { |
||
return doBootstrap(); |
||
} |
||
|
||
window.name = window.name.replace(NG_DEFER_BOOTSTRAP, ''); |
||
angular.resumeBootstrap = function(extraModules) { |
||
forEach(extraModules, function(module) { |
||
modules.push(module); |
||
}); |
||
doBootstrap(); |
||
}; |
||
} |
||
|
||
var SNAKE_CASE_REGEXP = /[A-Z]/g; |
||
function snake_case(name, separator){ |
||
separator = separator || '_'; |
||
return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) { |
||
return (pos ? separator : '') + letter.toLowerCase(); |
||
}); |
||
} |
||
|
||
function bindJQuery() { |
||
// bind to jQuery if present; |
||
jQuery = window.jQuery; |
||
// reset to jQuery or default to us. |
||
if (jQuery) { |
||
jqLite = jQuery; |
||
extend(jQuery.fn, { |
||
scope: JQLitePrototype.scope, |
||
isolateScope: JQLitePrototype.isolateScope, |
||
controller: JQLitePrototype.controller, |
||
injector: JQLitePrototype.injector, |
||
inheritedData: JQLitePrototype.inheritedData |
||
}); |
||
// Method signature: |
||
// jqLitePatchJQueryRemove(name, dispatchThis, filterElems, getterIfNoArguments) |
||
jqLitePatchJQueryRemove('remove', true, true, false); |
||
jqLitePatchJQueryRemove('empty', false, false, false); |
||
jqLitePatchJQueryRemove('html', false, false, true); |
||
} else { |
||
jqLite = JQLite; |
||
} |
||
angular.element = jqLite; |
||
} |
||
|
||
/** |
||
* throw error if the argument is falsy. |
||
*/ |
||
function assertArg(arg, name, reason) { |
||
if (!arg) { |
||
throw ngMinErr('areq', "Argument '{0}' is {1}", (name || '?'), (reason || "required")); |
||
} |
||
return arg; |
||
} |
||
|
||
function assertArgFn(arg, name, acceptArrayAnnotation) { |
||
if (acceptArrayAnnotation && isArray(arg)) { |
||
arg = arg[arg.length - 1]; |
||
} |
||
|
||
assertArg(isFunction(arg), name, 'not a function, got ' + |
||
(arg && typeof arg == 'object' ? arg.constructor.name || 'Object' : typeof arg)); |
||
return arg; |
||
} |
||
|
||
/** |
||
* throw error if the name given is hasOwnProperty |
||
* @param {String} name the name to test |
||
* @param {String} context the context in which the name is used, such as module or directive |
||
*/ |
||
function assertNotHasOwnProperty(name, context) { |
||
if (name === 'hasOwnProperty') { |
||
throw ngMinErr('badname', "hasOwnProperty is not a valid {0} name", context); |
||
} |
||
} |
||
|
||
/** |
||
* Return the value accessible from the object by path. Any undefined traversals are ignored |
||
* @param {Object} obj starting object |
||
* @param {string} path path to traverse |
||
* @param {boolean=true} bindFnToScope |
||
* @returns value as accessible by path |
||
*/ |
||
//TODO(misko): this function needs to be removed |
||
function getter(obj, path, bindFnToScope) { |
||
if (!path) return obj; |
||
var keys = path.split('.'); |
||
var key; |
||
var lastInstance = obj; |
||
var len = keys.length; |
||
|
||
for (var i = 0; i < len; i++) { |
||
key = keys[i]; |
||
if (obj) { |
||
obj = (lastInstance = obj)[key]; |
||
} |
||
} |
||
if (!bindFnToScope && isFunction(obj)) { |
||
return bind(lastInstance, obj); |
||
} |
||
return obj; |
||
} |
||
|
||
/** |
||
* Return the DOM siblings between the first and last node in the given array. |
||
* @param {Array} array like object |
||
* @returns jQlite object containing the elements |
||
*/ |
||
function getBlockElements(nodes) { |
||
var startNode = nodes[0], |
||
endNode = nodes[nodes.length - 1]; |
||
if (startNode === endNode) { |
||
return jqLite(startNode); |
||
} |
||
|
||
var element = startNode; |
||
var elements = [element]; |
||
|
||
do { |
||
element = element.nextSibling; |
||
if (!element) break; |
||
elements.push(element); |
||
} while (element !== endNode); |
||
|
||
return jqLite(elements); |
||
} |
||
|
||
/** |
||
* @ngdoc interface |
||
* @name angular.Module |
||
* @description |
||
* |
||
* Interface for configuring angular {@link angular.module modules}. |
||
*/ |
||
|
||
function setupModuleLoader(window) { |
||
|
||
var $injectorMinErr = minErr('$injector'); |
||
var ngMinErr = minErr('ng'); |
||
|
||
function ensure(obj, name, factory) { |
||
return obj[name] || (obj[name] = factory()); |
||
} |
||
|
||
var angular = ensure(window, 'angular', Object); |
||
|
||
// We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap |
||
angular.$$minErr = angular.$$minErr || minErr; |
||
|
||
return ensure(angular, 'module', function() { |
||
/** @type {Object.<string, angular.Module>} */ |
||
var modules = {}; |
||
|
||
/** |
||
* @ngdoc function |
||
* @name angular.module |
||
* @description |
||
* |
||
* The `angular.module` is a global place for creating, registering and retrieving Angular |
||
* modules. |
||
* All modules (angular core or 3rd party) that should be available to an application must be |
||
* registered using this mechanism. |
||
* |
||
* When passed two or more arguments, a new module is created. If passed only one argument, an |
||
* existing module (the name passed as the first argument to `module`) is retrieved. |
||
* |
||
* |
||
* # Module |
||
* |
||
* A module is a collection of services, directives, filters, and configuration information. |
||
* `angular.module` is used to configure the {@link AUTO.$injector $injector}. |
||
* |
||
* <pre> |
||
* // Create a new module |
||
* var myModule = angular.module('myModule', []); |
||
* |
||
* // register a new service |
||
* myModule.value('appName', 'MyCoolApp'); |
||
* |
||
* // configure existing services inside initialization blocks. |
||
* myModule.config(function($locationProvider) { |
||
* // Configure existing providers |
||
* $locationProvider.hashPrefix('!'); |
||
* }); |
||
* </pre> |
||
* |
||
* Then you can create an injector and load your modules like this: |
||
* |
||
* <pre> |
||
* var injector = angular.injector(['ng', 'MyModule']) |
||
* </pre> |
||
* |
||
* However it's more likely that you'll just use |
||
* {@link ng.directive:ngApp ngApp} or |
||
* {@link angular.bootstrap} to simplify this process for you. |
||
* |
||
* @param {!string} name The name of the module to create or retrieve. |
||
* @param {Array.<string>=} requires If specified then new module is being created. If |
||
* unspecified then the the module is being retrieved for further configuration. |
||
* @param {Function} configFn Optional configuration function for the module. Same as |
||
* {@link angular.Module#methods_config Module#config()}. |
||
* @returns {module} new module with the {@link angular.Module} api. |
||
*/ |
||
return function module(name, requires, configFn) { |
||
var assertNotHasOwnProperty = function(name, context) { |
||
if (name === 'hasOwnProperty') { |
||
throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context); |
||
} |
||
}; |
||
|
||
assertNotHasOwnProperty(name, 'module'); |
||
if (requires && modules.hasOwnProperty(name)) { |
||
modules[name] = null; |
||
} |
||
return ensure(modules, name, function() { |
||
if (!requires) { |
||
throw $injectorMinErr('nomod', "Module '{0}' is not available! You either misspelled " + |
||
"the module name or forgot to load it. If registering a module ensure that you " + |
||
"specify the dependencies as the second argument.", name); |
||
} |
||
|
||
/** @type {!Array.<Array.<*>>} */ |
||
var invokeQueue = []; |
||
|
||
/** @type {!Array.<Function>} */ |
||
var runBlocks = []; |
||
|
||
var config = invokeLater('$injector', 'invoke'); |
||
|
||
/** @type {angular.Module} */ |
||
var moduleInstance = { |
||
// Private state |
||
_invokeQueue: invokeQueue, |
||
_runBlocks: runBlocks, |
||
|
||
/** |
||
* @ngdoc property |
||
* @name angular.Module#requires |
||
* @propertyOf angular.Module |
||
* @returns {Array.<string>} List of module names which must be loaded before this module. |
||
* @description |
||
* Holds the list of modules which the injector will load before the current module is |
||
* loaded. |
||
*/ |
||
requires: requires, |
||
|
||
/** |
||
* @ngdoc property |
||
* @name angular.Module#name |
||
* @propertyOf angular.Module |
||
* @returns {string} Name of the module. |
||
* @description |
||
*/ |
||
name: name, |
||
|
||
|
||
/** |
||
* @ngdoc method |
||
* @name angular.Module#provider |
||
* @methodOf angular.Module |
||
* @param {string} name service name |
||
* @param {Function} providerType Construction function for creating new instance of the |
||
* service. |
||
* @description |
||
* See {@link AUTO.$provide#provider $provide.provider()}. |
||
*/ |
||
provider: invokeLater('$provide', 'provider'), |
||
|
||
/** |
||
* @ngdoc method |
||
* @name angular.Module#factory |
||
* @methodOf angular.Module |
||
* @param {string} name service name |
||
* @param {Function} providerFunction Function for creating new instance of the service. |
||
* @description |
||
* See {@link AUTO.$provide#factory $provide.factory()}. |
||
*/ |
||
factory: invokeLater('$provide', 'factory'), |
||
|
||
/** |
||
* @ngdoc method |
||
* @name angular.Module#service |
||
* @methodOf angular.Module |
||
* @param {string} name service name |
||
* @param {Function} constructor A constructor function that will be instantiated. |
||
* @description |
||
* See {@link AUTO.$provide#service $provide.service()}. |
||
*/ |
||
service: invokeLater('$provide', 'service'), |
||
|
||
/** |
||
* @ngdoc method |
||
* @name angular.Module#value |
||
* @methodOf angular.Module |
||
* @param {string} name service name |
||
* @param {*} object Service instance object. |
||
* @description |
||
* See {@link AUTO.$provide#value $provide.value()}. |
||
*/ |
||
value: invokeLater('$provide', 'value'), |
||
|
||
/** |
||
* @ngdoc method |
||
* @name angular.Module#constant |
||
* @methodOf angular.Module |
||
* @param {string} name constant name |
||
* @param {*} object Constant value. |
||
* @description |
||
* Because the constant are fixed, they get applied before other provide methods. |
||
* See {@link AUTO.$provide#constant $provide.constant()}. |
||
*/ |
||
constant: invokeLater('$provide', 'constant', 'unshift'), |
||
|
||
/** |
||
* @ngdoc method |
||
* @name angular.Module#animation |
||
* @methodOf angular.Module |
||
* @param {string} name animation name |
||
* @param {Function} animationFactory Factory function for creating new instance of an |
||
* animation. |
||
* @description |
||
* |
||
* **NOTE**: animations take effect only if the **ngAnimate** module is loaded. |
||
* |
||
* |
||
* Defines an animation hook that can be later used with |
||
* {@link ngAnimate.$animate $animate} service and directives that use this service. |
||
* |
||
* <pre> |
||
* module.animation('.animation-name', function($inject1, $inject2) { |
||
* return { |
||
* eventName : function(element, done) { |
||
* //code to run the animation |
||
* //once complete, then run done() |
||
* return function cancellationFunction(element) { |
||
* //code to cancel the animation |
||
* } |
||
* } |
||
* } |
||
* }) |
||
* </pre> |
||
* |
||
* See {@link ngAnimate.$animateProvider#register $animateProvider.register()} and |
||
* {@link ngAnimate ngAnimate module} for more information. |
||
*/ |
||
animation: invokeLater('$animateProvider', 'register'), |
||
|
||
/** |
||
* @ngdoc method |
||
* @name angular.Module#filter |
||
* @methodOf angular.Module |
||
* @param {string} name Filter name. |
||
* @param {Function} filterFactory Factory function for creating new instance of filter. |
||
* @description |
||
* See {@link ng.$filterProvider#register $filterProvider.register()}. |
||
*/ |
||
filter: invokeLater('$filterProvider', 'register'), |
||
|
||
/** |
||
* @ngdoc method |
||
* @name angular.Module#controller |
||
* @methodOf angular.Module |
||
* @param {string|Object} name Controller name, or an object map of controllers where the |
||
* keys are the names and the values are the constructors. |
||
* @param {Function} constructor Controller constructor function. |
||
* @description |
||
* See {@link ng.$controllerProvider#register $controllerProvider.register()}. |
||
*/ |
||
controller: invokeLater('$controllerProvider', 'register'), |
||
|
||
/** |
||
* @ngdoc method |
||
* @name angular.Module#directive |
||
* @methodOf angular.Module |
||
* @param {string|Object} name Directive name, or an object map of directives where the |
||
* keys are the names and the values are the factories. |
||
* @param {Function} directiveFactory Factory function for creating new instance of |
||
* directives. |
||
* @description |
||
* See {@link ng.$compileProvider#methods_directive $compileProvider.directive()}. |
||
*/ |
||
directive: invokeLater('$compileProvider', 'directive'), |
||
|
||
/** |
||
* @ngdoc method |
||
* @name angular.Module#config |
||
* @methodOf angular.Module |
||
* @param {Function} configFn Execute this function on module load. Useful for service |
||
* configuration. |
||
* @description |
||
* Use this method to register work which needs to be performed on module loading. |
||
*/ |
||
config: config, |
||
|
||
/** |
||
* @ngdoc method |
||
* @name angular.Module#run |
||
* @methodOf angular.Module |
||
* @param {Function} initializationFn Execute this function after injector creation. |
||
* Useful for application initialization. |
||
* @description |
||
* Use this method to register work which should be performed when the injector is done |
||
* loading all modules. |
||
*/ |
||
run: function(block) { |
||
runBlocks.push(block); |
||
return this; |
||
} |
||
}; |
||
|
||
if (configFn) { |
||
config(configFn); |
||
} |
||
|
||
return moduleInstance; |
||
|
||
/** |
||
* @param {string} provider |
||
* @param {string} method |
||
* @param {String=} insertMethod |
||
* @returns {angular.Module} |
||
*/ |
||
function invokeLater(provider, method, insertMethod) { |
||
return function() { |
||
invokeQueue[insertMethod || 'push']([provider, method, arguments]); |
||
return moduleInstance; |
||
}; |
||
} |
||
}); |
||
}; |
||
}); |
||
|
||
} |
||
|
||
/* global |
||
angularModule: true, |
||
version: true, |
||
|
||
$LocaleProvider, |
||
$CompileProvider, |
||
|
||
htmlAnchorDirective, |
||
inputDirective, |
||
inputDirective, |
||
formDirective, |
||
scriptDirective, |
||
selectDirective, |
||
styleDirective, |
||
optionDirective, |
||
ngBindDirective, |
||
ngBindHtmlDirective, |
||
ngBindTemplateDirective, |
||
ngClassDirective, |
||
ngClassEvenDirective, |
||
ngClassOddDirective, |
||
ngCspDirective, |
||
ngCloakDirective, |
||
ngControllerDirective, |
||
ngFormDirective, |
||
ngHideDirective, |
||
ngIfDirective, |
||
ngIncludeDirective, |
||
ngIncludeFillContentDirective, |
||
ngInitDirective, |
||
ngNonBindableDirective, |
||
ngPluralizeDirective, |
||
ngRepeatDirective, |
||
ngShowDirective, |
||
ngStyleDirective, |
||
ngSwitchDirective, |
||
ngSwitchWhenDirective, |
||
ngSwitchDefaultDirective, |
||
ngOptionsDirective, |
||
ngTranscludeDirective, |
||
ngModelDirective, |
||
ngListDirective, |
||
ngChangeDirective, |
||
requiredDirective, |
||
requiredDirective, |
||
ngValueDirective, |
||
ngAttributeAliasDirectives, |
||
ngEventDirectives, |
||
|
||
$AnchorScrollProvider, |
||
$AnimateProvider, |
||
$BrowserProvider, |
||
$CacheFactoryProvider, |
||
$ControllerProvider, |
||
$DocumentProvider, |
||
$ExceptionHandlerProvider, |
||
$FilterProvider, |
||
$InterpolateProvider, |
||
$IntervalProvider, |
||
$HttpProvider, |
||
$HttpBackendProvider, |
||
$LocationProvider, |
||
$LogProvider, |
||
$ParseProvider, |
||
$RootScopeProvider, |
||
$QProvider, |
||
$$SanitizeUriProvider, |
||
$SceProvider, |
||
$SceDelegateProvider, |
||
$SnifferProvider, |
||
$TemplateCacheProvider, |
||
$TimeoutProvider, |
||
$WindowProvider |
||
*/ |
||
|
||
|
||
/** |
||
* @ngdoc property |
||
* @name angular.version |
||
* @description |
||
* An object that contains information about the current AngularJS version. This object has the |
||
* following properties: |
||
* |
||
* - `full` – `{string}` – Full version string, such as "0.9.18". |
||
* - `major` – `{number}` – Major version number, such as "0". |
||
* - `minor` – `{number}` – Minor version number, such as "9". |
||
* - `dot` – `{number}` – Dot version number, such as "18". |
||
* - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat". |
||
*/ |
||
var version = { |
||
full: '1.2.9', // all of these placeholder strings will be replaced by grunt's |
||
major: 1, // package task |
||
minor: 2, |
||
dot: 9, |
||
codeName: 'enchanted-articulacy' |
||
}; |
||
|
||
|
||
function publishExternalAPI(angular){ |
||
extend(angular, { |
||
'bootstrap': bootstrap, |
||
'copy': copy, |
||
'extend': extend, |
||
'equals': equals, |
||
'element': jqLite, |
||
'forEach': forEach, |
||
'injector': createInjector, |
||
'noop':noop, |
||
'bind':bind, |
||
'toJson': toJson, |
||
'fromJson': fromJson, |
||
'identity':identity, |
||
'isUndefined': isUndefined, |
||
'isDefined': isDefined, |
||
'isString': isString, |
||
'isFunction': isFunction, |
||
'isObject': isObject, |
||
'isNumber': isNumber, |
||
'isElement': isElement, |
||
'isArray': isArray, |
||
'version': version, |
||
'isDate': isDate, |
||
'lowercase': lowercase, |
||
'uppercase': uppercase, |
||
'callbacks': {counter: 0}, |
||
'$$minErr': minErr, |
||
'$$csp': csp |
||
}); |
||
|
||
angularModule = setupModuleLoader(window); |
||
try { |
||
angularModule('ngLocale'); |
||
} catch (e) { |
||
angularModule('ngLocale', []).provider('$locale', $LocaleProvider); |
||
} |
||
|
||
angularModule('ng', ['ngLocale'], ['$provide', |
||
function ngModule($provide) { |
||
// $$sanitizeUriProvider needs to be before $compileProvider as it is used by it. |
||
$provide.provider({ |
||
$$sanitizeUri: $$SanitizeUriProvider |
||
}); |
||
$provide.provider('$compile', $CompileProvider). |
||
directive({ |
||
a: htmlAnchorDirective, |
||
input: inputDirective, |
||
textarea: inputDirective, |
||
form: formDirective, |
||
script: scriptDirective, |
||
select: selectDirective, |
||
style: styleDirective, |
||
option: optionDirective, |
||
ngBind: ngBindDirective, |
||
ngBindHtml: ngBindHtmlDirective, |
||
ngBindTemplate: ngBindTemplateDirective, |
||
ngClass: ngClassDirective, |
||
ngClassEven: ngClassEvenDirective, |
||
ngClassOdd: ngClassOddDirective, |
||
ngCloak: ngCloakDirective, |
||
ngController: ngControllerDirective, |
||
ngForm: ngFormDirective, |
||
ngHide: ngHideDirective, |
||
ngIf: ngIfDirective, |
||
ngInclude: ngIncludeDirective, |
||
ngInit: ngInitDirective, |
||
ngNonBindable: ngNonBindableDirective, |
||
ngPluralize: ngPluralizeDirective, |
||
ngRepeat: ngRepeatDirective, |
||
ngShow: ngShowDirective, |
||
ngStyle: ngStyleDirective, |
||
ngSwitch: ngSwitchDirective, |
||
ngSwitchWhen: ngSwitchWhenDirective, |
||
ngSwitchDefault: ngSwitchDefaultDirective, |
||
ngOptions: ngOptionsDirective, |
||
ngTransclude: ngTranscludeDirective, |
||
ngModel: ngModelDirective, |
||
ngList: ngListDirective, |
||
ngChange: ngChangeDirective, |
||
required: requiredDirective, |
||
ngRequired: requiredDirective, |
||
ngValue: ngValueDirective |
||
}). |
||
directive({ |
||
ngInclude: ngIncludeFillContentDirective |
||
}). |
||
directive(ngAttributeAliasDirectives). |
||
directive(ngEventDirectives); |
||
$provide.provider({ |
||
$anchorScroll: $AnchorScrollProvider, |
||
$animate: $AnimateProvider, |
||
$browser: $BrowserProvider, |
||
$cacheFactory: $CacheFactoryProvider, |
||
$controller: $ControllerProvider, |
||
$document: $DocumentProvider, |
||
$exceptionHandler: $ExceptionHandlerProvider, |
||
$filter: $FilterProvider, |
||
$interpolate: $InterpolateProvider, |
||
$interval: $IntervalProvider, |
||
$http: $HttpProvider, |
||
$httpBackend: $HttpBackendProvider, |
||
$location: $LocationProvider, |
||
$log: $LogProvider, |
||
$parse: $ParseProvider, |
||
$rootScope: $RootScopeProvider, |
||
$q: $QProvider, |
||
$sce: $SceProvider, |
||
$sceDelegate: $SceDelegateProvider, |
||
$sniffer: $SnifferProvider, |
||
$templateCache: $TemplateCacheProvider, |
||
$timeout: $TimeoutProvider, |
||
$window: $WindowProvider |
||
}); |
||
} |
||
]); |
||
} |
||
|
||
/* global |
||
|
||
-JQLitePrototype, |
||
-addEventListenerFn, |
||
-removeEventListenerFn, |
||
-BOOLEAN_ATTR |
||
*/ |
||
|
||
////////////////////////////////// |
||
//JQLite |
||
////////////////////////////////// |
||
|
||
/** |
||
* @ngdoc function |
||
* @name angular.element |
||
* @function |
||
* |
||
* @description |
||
* Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element. |
||
* |
||
* If jQuery is available, `angular.element` is an alias for the |
||
* [jQuery](http://api.jquery.com/jQuery/) function. If jQuery is not available, `angular.element` |
||
* delegates to Angular's built-in subset of jQuery, called "jQuery lite" or "jqLite." |
||
* |
||
* <div class="alert alert-success">jqLite is a tiny, API-compatible subset of jQuery that allows |
||
* Angular to manipulate the DOM in a cross-browser compatible way. **jqLite** implements only the most |
||
* commonly needed functionality with the goal of having a very small footprint.</div> |
||
* |
||
* To use jQuery, simply load it before `DOMContentLoaded` event fired. |
||
* |
||
* <div class="alert">**Note:** all element references in Angular are always wrapped with jQuery or |
||
* jqLite; they are never raw DOM references.</div> |
||
* |
||
* ## Angular's jqLite |
||
* jqLite provides only the following jQuery methods: |
||
* |
||
* - [`addClass()`](http://api.jquery.com/addClass/) |
||
* - [`after()`](http://api.jquery.com/after/) |
||
* - [`append()`](http://api.jquery.com/append/) |
||
* - [`attr()`](http://api.jquery.com/attr/) |
||
* - [`bind()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData |
||
* - [`children()`](http://api.jquery.com/children/) - Does not support selectors |
||
* - [`clone()`](http://api.jquery.com/clone/) |
||
* - [`contents()`](http://api.jquery.com/contents/) |
||
* - [`css()`](http://api.jquery.com/css/) |
||
* - [`data()`](http://api.jquery.com/data/) |
||
* - [`empty()`](http://api.jquery.com/empty/) |
||
* - [`eq()`](http://api.jquery.com/eq/) |
||
* - [`find()`](http://api.jquery.com/find/) - Limited to lookups by tag name |
||
* - [`hasClass()`](http://api.jquery.com/hasClass/) |
||
* - [`html()`](http://api.jquery.com/html/) |
||
* - [`next()`](http://api.jquery.com/next/) - Does not support selectors |
||
* - [`on()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData |
||
* - [`off()`](http://api.jquery.com/off/) - Does not support namespaces or selectors |
||
* - [`one()`](http://api.jquery.com/one/) - Does not support namespaces or selectors |
||
* - [`parent()`](http://api.jquery.com/parent/) - Does not support selectors |
||
* - [`prepend()`](http://api.jquery.com/prepend/) |
||
* - [`prop()`](http://api.jquery.com/prop/) |
||
* - [`ready()`](http://api.jquery.com/ready/) |
||
* - [`remove()`](http://api.jquery.com/remove/) |
||
* - [`removeAttr()`](http://api.jquery.com/removeAttr/) |
||
* - [`removeClass()`](http://api.jquery.com/removeClass/) |
||
* - [`removeData()`](http://api.jquery.com/removeData/) |
||
* - [`replaceWith()`](http://api.jquery.com/replaceWith/) |
||
* - [`text()`](http://api.jquery.com/text/) |
||
* - [`toggleClass()`](http://api.jquery.com/toggleClass/) |
||
* - [`triggerHandler()`](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers. |
||
* - [`unbind()`](http://api.jquery.com/off/) - Does not support namespaces |
||
* - [`val()`](http://api.jquery.com/val/) |
||
* - [`wrap()`](http://api.jquery.com/wrap/) |
||
* |
||
* ## jQuery/jqLite Extras |
||
* Angular also provides the following additional methods and events to both jQuery and jqLite: |
||
* |
||
* ### Events |
||
* - `$destroy` - AngularJS intercepts all jqLite/jQuery's DOM destruction apis and fires this event |
||
* on all DOM nodes being removed. This can be used to clean up any 3rd party bindings to the DOM |
||
* element before it is removed. |
||
* |
||
* ### Methods |
||
* - `controller(name)` - retrieves the controller of the current element or its parent. By default |
||
* retrieves controller associated with the `ngController` directive. If `name` is provided as |
||
* camelCase directive name, then the controller for this directive will be retrieved (e.g. |
||
* `'ngModel'`). |
||
* - `injector()` - retrieves the injector of the current element or its parent. |
||
* - `scope()` - retrieves the {@link api/ng.$rootScope.Scope scope} of the current |
||
* element or its parent. |
||
* - `isolateScope()` - retrieves an isolate {@link api/ng.$rootScope.Scope scope} if one is attached directly to the |
||
* current element. This getter should be used only on elements that contain a directive which starts a new isolate |
||
* scope. Calling `scope()` on this element always returns the original non-isolate scope. |
||
* - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top |
||
* parent element is reached. |
||
* |
||
* @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery. |
||
* @returns {Object} jQuery object. |
||
*/ |
||
|
||
var jqCache = JQLite.cache = {}, |
||
jqName = JQLite.expando = 'ng-' + new Date().getTime(), |
||
jqId = 1, |
||
addEventListenerFn = (window.document.addEventListener |
||
? function(element, type, fn) {element.addEventListener(type, fn, false);} |
||
: function(element, type, fn) {element.attachEvent('on' + type, fn);}), |
||
removeEventListenerFn = (window.document.removeEventListener |
||
? function(element, type, fn) {element.removeEventListener(type, fn, false); } |
||
: function(element, type, fn) {element.detachEvent('on' + type, fn); }); |
||
|
||
function jqNextId() { return ++jqId; } |
||
|
||
|
||
var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g; |
||
var MOZ_HACK_REGEXP = /^moz([A-Z])/; |
||
var jqLiteMinErr = minErr('jqLite'); |
||
|
||
/** |
||
* Converts snake_case to camelCase. |
||
* Also there is special case for Moz prefix starting with upper case letter. |
||
* @param name Name to normalize |
||
*/ |
||
function camelCase(name) { |
||
return name. |
||
replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) { |
||
return offset ? letter.toUpperCase() : letter; |
||
}). |
||
replace(MOZ_HACK_REGEXP, 'Moz$1'); |
||
} |
||
|
||
///////////////////////////////////////////// |
||
// jQuery mutation patch |
||
// |
||
// In conjunction with bindJQuery intercepts all jQuery's DOM destruction apis and fires a |
||
// $destroy event on all DOM nodes being removed. |
||
// |
||
///////////////////////////////////////////// |
||
|
||
function jqLitePatchJQueryRemove(name, dispatchThis, filterElems, getterIfNoArguments) { |
||
var originalJqFn = jQuery.fn[name]; |
||
originalJqFn = originalJqFn.$original || originalJqFn; |
||
removePatch.$original = originalJqFn; |
||
jQuery.fn[name] = removePatch; |
||
|
||
function removePatch(param) { |
||
// jshint -W040 |
||
var list = filterElems && param ? [this.filter(param)] : [this], |
||
fireEvent = dispatchThis, |
||
set, setIndex, setLength, |
||
element, childIndex, childLength, children; |
||
|
||
if (!getterIfNoArguments || param != null) { |
||
while(list.length) { |
||
set = list.shift(); |
||
for(setIndex = 0, setLength = set.length; setIndex < setLength; setIndex++) { |
||
element = jqLite(set[setIndex]); |
||
if (fireEvent) { |
||
element.triggerHandler('$destroy'); |
||
} else { |
||
fireEvent = !fireEvent; |
||
} |
||
for(childIndex = 0, childLength = (children = element.children()).length; |
||
childIndex < childLength; |
||
childIndex++) { |
||
list.push(jQuery(children[childIndex])); |
||
} |
||
} |
||
} |
||
} |
||
return originalJqFn.apply(this, arguments); |
||
} |
||
} |
||
|
||
///////////////////////////////////////////// |
||
function JQLite(element) { |
||
if (element instanceof JQLite) { |
||
return element; |
||
} |
||
if (!(this instanceof JQLite)) { |
||
if (isString(element) && element.charAt(0) != '<') { |
||
throw jqLiteMinErr('nosel', 'Looking up elements via selectors is not supported by jqLite! See: http://docs.angularjs.org/api/angular.element'); |
||
} |
||
return new JQLite(element); |
||
} |
||
|
||
if (isString(element)) { |
||
var div = document.createElement('div'); |
||
// Read about the NoScope elements here: |
||
// http://msdn.microsoft.com/en-us/library/ms533897(VS.85).aspx |
||
div.innerHTML = '<div> </div>' + element; // IE insanity to make NoScope elements work! |
||
div.removeChild(div.firstChild); // remove the superfluous div |
||
jqLiteAddNodes(this, div.childNodes); |
||
var fragment = jqLite(document.createDocumentFragment()); |
||
fragment.append(this); // detach the elements from the temporary DOM div. |
||
} else { |
||
jqLiteAddNodes(this, element); |
||
} |
||
} |
||
|
||
function jqLiteClone(element) { |
||
return element.cloneNode(true); |
||
} |
||
|
||
function jqLiteDealoc(element){ |
||
jqLiteRemoveData(element); |
||
for ( var i = 0, children = element.childNodes || []; i < children.length; i++) { |
||
jqLiteDealoc(children[i]); |
||
} |
||
} |
||
|
||
function jqLiteOff(element, type, fn, unsupported) { |
||
if (isDefined(unsupported)) throw jqLiteMinErr('offargs', 'jqLite#off() does not support the `selector` argument'); |
||
|
||
var events = jqLiteExpandoStore(element, 'events'), |
||
handle = jqLiteExpandoStore(element, 'handle'); |
||
|
||
if (!handle) return; //no listeners registered |
||
|
||
if (isUndefined(type)) { |
||
forEach(events, function(eventHandler, type) { |
||
removeEventListenerFn(element, type, eventHandler); |
||
delete events[type]; |
||
}); |
||
} else { |
||
forEach(type.split(' '), function(type) { |
||
if (isUndefined(fn)) { |
||
removeEventListenerFn(element, type, events[type]); |
||
delete events[type]; |
||
} else { |
||
arrayRemove(events[type] || [], fn); |
||
} |
||
}); |
||
} |
||
} |
||
|
||
function jqLiteRemoveData(element, name) { |
||
var expandoId = element[jqName], |
||
expandoStore = jqCache[expandoId]; |
||
|
||
if (expandoStore) { |
||
if (name) { |
||
delete jqCache[expandoId].data[name]; |
||
return; |
||
} |
||
|
||
if (expandoStore.handle) { |
||
expandoStore.events.$destroy && expandoStore.handle({}, '$destroy'); |
||
jqLiteOff(element); |
||
} |
||
delete jqCache[expandoId]; |
||
element[jqName] = undefined; // ie does not allow deletion of attributes on elements. |
||
} |
||
} |
||
|
||
function jqLiteExpandoStore(element, key, value) { |
||
var expandoId = element[jqName], |
||
expandoStore = jqCache[expandoId || -1]; |
||
|
||
if (isDefined(value)) { |
||
if (!expandoStore) { |
||
element[jqName] = expandoId = jqNextId(); |
||
expandoStore = jqCache[expandoId] = {}; |
||
} |
||
expandoStore[key] = value; |
||
} else { |
||
return expandoStore && expandoStore[key]; |
||
} |
||
} |
||
|
||
function jqLiteData(element, key, value) { |
||
var data = jqLiteExpandoStore(element, 'data'), |
||
isSetter = isDefined(value), |
||
keyDefined = !isSetter && isDefined(key), |
||
isSimpleGetter = keyDefined && !isObject(key); |
||
|
||
if (!data && !isSimpleGetter) { |
||
jqLiteExpandoStore(element, 'data', data = {}); |
||
} |
||
|
||
if (isSetter) { |
||
data[key] = value; |
||
} else { |
||
if (keyDefined) { |
||
if (isSimpleGetter) { |
||
// don't create data in this case. |
||
return data && data[key]; |
||
} else { |
||
extend(data, key); |
||
} |
||
} else { |
||
return data; |
||
} |
||
} |
||
} |
||
|
||
function jqLiteHasClass(element, selector) { |
||
if (!element.getAttribute) return false; |
||
return ((" " + (element.getAttribute('class') || '') + " ").replace(/[\n\t]/g, " "). |
||
indexOf( " " + selector + " " ) > -1); |
||
} |
||
|
||
function jqLiteRemoveClass(element, cssClasses) { |
||
if (cssClasses && element.setAttribute) { |
||
forEach(cssClasses.split(' '), function(cssClass) { |
||
element.setAttribute('class', trim( |
||
(" " + (element.getAttribute('class') || '') + " ") |
||
.replace(/[\n\t]/g, " ") |
||
.replace(" " + trim(cssClass) + " ", " ")) |
||
); |
||
}); |
||
} |
||
} |
||
|
||
function jqLiteAddClass(element, cssClasses) { |
||
if (cssClasses && element.setAttribute) { |
||
var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ') |
||
.replace(/[\n\t]/g, " "); |
||
|
||
forEach(cssClasses.split(' '), function(cssClass) { |
||
cssClass = trim(cssClass); |
||
if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) { |
||
existingClasses += cssClass + ' '; |
||
} |
||
}); |
||
|
||
element.setAttribute('class', trim(existingClasses)); |
||
} |
||
} |
||
|
||
function jqLiteAddNodes(root, elements) { |
||
if (elements) { |
||
elements = (!elements.nodeName && isDefined(elements.length) && !isWindow(elements)) |
||
? elements |
||
: [ elements ]; |
||
for(var i=0; i < elements.length; i++) { |
||
root.push(elements[i]); |
||
} |
||
} |
||
} |
||
|
||
function jqLiteController(element, name) { |
||
return jqLiteInheritedData(element, '$' + (name || 'ngController' ) + 'Controller'); |
||
} |
||
|
||
function jqLiteInheritedData(element, name, value) { |
||
element = jqLite(element); |
||
|
||
// if element is the document object work with the html element instead |
||
// this makes $(document).scope() possible |
||
if(element[0].nodeType == 9) { |
||
element = element.find('html'); |
||
} |
||
var names = isArray(name) ? name : [name]; |
||
|
||
while (element.length) { |
||
|
||
for (var i = 0, ii = names.length; i < ii; i++) { |
||
if ((value = element.data(names[i])) !== undefined) return value; |
||
} |
||
element = element.parent(); |
||
} |
||
} |
||
|
||
function jqLiteEmpty(element) { |
||
for (var i = 0, childNodes = element.childNodes; i < childNodes.length; i++) { |
||
jqLiteDealoc(childNodes[i]); |
||
} |
||
while (element.firstChild) { |
||
element.removeChild(element.firstChild); |
||
} |
||
} |
||
|
||
////////////////////////////////////////// |
||
// Functions which are declared directly. |
||
////////////////////////////////////////// |
||
var JQLitePrototype = JQLite.prototype = { |
||
ready: function(fn) { |
||
var fired = false; |
||
|
||
function trigger() { |
||
if (fired) return; |
||
fired = true; |
||
fn(); |
||
} |
||
|
||
// check if document already is loaded |
||
if (document.readyState === 'complete'){ |
||
setTimeout(trigger); |
||
} else { |
||
this.on('DOMContentLoaded', trigger); // works for modern browsers and IE9 |
||
// we can not use jqLite since we are not done loading and jQuery could be loaded later. |
||
// jshint -W064 |
||
JQLite(window).on('load', trigger); // fallback to window.onload for others |
||
// jshint +W064 |
||
} |
||
}, |
||
toString: function() { |
||
var value = []; |
||
forEach(this, function(e){ value.push('' + e);}); |
||
return '[' + value.join(', ') + ']'; |
||
}, |
||
|
||
eq: function(index) { |
||
return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]); |
||
}, |
||
|
||
length: 0, |
||
push: push, |
||
sort: [].sort, |
||
splice: [].splice |
||
}; |
||
|
||
////////////////////////////////////////// |
||
// Functions iterating getter/setters. |
||
// these functions return self on setter and |
||
// value on get. |
||
////////////////////////////////////////// |
||
var BOOLEAN_ATTR = {}; |
||
forEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), function(value) { |
||
BOOLEAN_ATTR[lowercase(value)] = value; |
||
}); |
||
var BOOLEAN_ELEMENTS = {}; |
||
forEach('input,select,option,textarea,button,form,details'.split(','), function(value) { |
||
BOOLEAN_ELEMENTS[uppercase(value)] = true; |
||
}); |
||
|
||
function getBooleanAttrName(element, name) { |
||
// check dom last since we will most likely fail on name |
||
var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()]; |
||
|
||
// booleanAttr is here twice to minimize DOM access |
||
return booleanAttr && BOOLEAN_ELEMENTS[element.nodeName] && booleanAttr; |
||
} |
||
|
||
forEach({ |
||
data: jqLiteData, |
||
inheritedData: jqLiteInheritedData, |
||
|
||
scope: function(element) { |
||
// Can't use jqLiteData here directly so we stay compatible with jQuery! |
||
return jqLite(element).data('$scope') || jqLiteInheritedData(element.parentNode || element, ['$isolateScope', '$scope']); |
||
}, |
||
|
||
isolateScope: function(element) { |
||
// Can't use jqLiteData here directly so we stay compatible with jQuery! |
||
return jqLite(element).data('$isolateScope') || jqLite(element).data('$isolateScopeNoTemplate'); |
||
}, |
||
|
||
controller: jqLiteController , |
||
|
||
injector: function(element) { |
||
return jqLiteInheritedData(element, '$injector'); |
||
}, |
||
|
||
removeAttr: function(element,name) { |
||
element.removeAttribute(name); |
||
}, |
||
|
||
hasClass: jqLiteHasClass, |
||
|
||
css: function(element, name, value) { |
||
name = camelCase(name); |
||
|
||
if (isDefined(value)) { |
||
element.style[name] = value; |
||
} else { |
||
var val; |
||
|
||
if (msie <= 8) { |
||
// this is some IE specific weirdness that jQuery 1.6.4 does not sure why |
||
val = element.currentStyle && element.currentStyle[name]; |
||
if (val === '') val = 'auto'; |
||
} |
||
|
||
val = val || element.style[name]; |
||
|
||
if (msie <= 8) { |
||
// jquery weirdness :-/ |
||
val = (val === '') ? undefined : val; |
||
} |
||
|
||
return val; |
||
} |
||
}, |
||
|
||
attr: function(element, name, value){ |
||
var lowercasedName = lowercase(name); |
||
if (BOOLEAN_ATTR[lowercasedName]) { |
||
if (isDefined(value)) { |
||
if (!!value) { |
||
element[name] = true; |
||
element.setAttribute(name, lowercasedName); |
||
} else { |
||
element[name] = false; |
||
element.removeAttribute(lowercasedName); |
||
} |
||
} else { |
||
return (element[name] || |
||
(element.attributes.getNamedItem(name)|| noop).specified) |
||
? lowercasedName |
||
: undefined; |
||
} |
||
} else if (isDefined(value)) { |
||
element.setAttribute(name, value); |
||
} else if (element.getAttribute) { |
||
// the extra argument "2" is to get the right thing for a.href in IE, see jQuery code |
||
// some elements (e.g. Document) don't have get attribute, so return undefined |
||
var ret = element.getAttribute(name, 2); |
||
// normalize non-existing attributes to undefined (as jQuery) |
||
return ret === null ? undefined : ret; |
||
} |
||
}, |
||
|
||
prop: function(element, name, value) { |
||
if (isDefined(value)) { |
||
element[name] = value; |
||
} else { |
||
return element[name]; |
||
} |
||
}, |
||
|
||
text: (function() { |
||
var NODE_TYPE_TEXT_PROPERTY = []; |
||
if (msie < 9) { |
||
NODE_TYPE_TEXT_PROPERTY[1] = 'innerText'; /** Element **/ |
||
NODE_TYPE_TEXT_PROPERTY[3] = 'nodeValue'; /** Text **/ |
||
} else { |
||
NODE_TYPE_TEXT_PROPERTY[1] = /** Element **/ |
||
NODE_TYPE_TEXT_PROPERTY[3] = 'textContent'; /** Text **/ |
||
} |
||
getText.$dv = ''; |
||
return getText; |
||
|
||
function getText(element, value) { |
||
var textProp = NODE_TYPE_TEXT_PROPERTY[element.nodeType]; |
||
if (isUndefined(value)) { |
||
return textProp ? element[textProp] : ''; |
||
} |
||
element[textProp] = value; |
||
} |
||
})(), |
||
|
||
val: function(element, value) { |
||
if (isUndefined(value)) { |
||
if (nodeName_(element) === 'SELECT' && element.multiple) { |
||
var result = []; |
||
forEach(element.options, function (option) { |
||
if (option.selected) { |
||
result.push(option.value || option.text); |
||
} |
||
}); |
||
return result.length === 0 ? null : result; |
||
} |
||
return element.value; |
||
} |
||
element.value = value; |
||
}, |
||
|
||
html: function(element, value) { |
||
if (isUndefined(value)) { |
||
return element.innerHTML; |
||
} |
||
for (var i = 0, childNodes = element.childNodes; i < childNodes.length; i++) { |
||
jqLiteDealoc(childNodes[i]); |
||
} |
||
element.innerHTML = value; |
||
}, |
||
|
||
empty: jqLiteEmpty |
||
}, function(fn, name){ |
||
/** |
||
* Properties: writes return selection, reads return first value |
||
*/ |
||
JQLite.prototype[name] = function(arg1, arg2) { |
||
var i, key; |
||
|
||
// jqLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it |
||
// in a way that survives minification. |
||
// jqLiteEmpty takes no arguments but is a setter. |
||
if (fn !== jqLiteEmpty && |
||
(((fn.length == 2 && (fn !== jqLiteHasClass && fn !== jqLiteController)) ? arg1 : arg2) === undefined)) { |
||
if (isObject(arg1)) { |
||
|
||
// we are a write, but the object properties are the key/values |
||
for (i = 0; i < this.length; i++) { |
||
if (fn === jqLiteData) { |
||
// data() takes the whole object in jQuery |
||
fn(this[i], arg1); |
||
} else { |
||
for (key in arg1) { |
||
fn(this[i], key, arg1[key]); |
||
} |
||
} |
||
} |
||
// return self for chaining |
||
return this; |
||
} else { |
||
// we are a read, so read the first child. |
||
var value = fn.$dv; |
||
// Only if we have $dv do we iterate over all, otherwise it is just the first element. |
||
var jj = (value === undefined) ? Math.min(this.length, 1) : this.length; |
||
for (var j = 0; j < jj; j++) { |
||
var nodeValue = fn(this[j], arg1, arg2); |
||
value = value ? value + nodeValue : nodeValue; |
||
} |
||
return value; |
||
} |
||
} else { |
||
// we are a write, so apply to all children |
||
for (i = 0; i < this.length; i++) { |
||
fn(this[i], arg1, arg2); |
||
} |
||
// return self for chaining |
||
return this; |
||
} |
||
}; |
||
}); |
||
|
||
function createEventHandler(element, events) { |
||
var eventHandler = function (event, type) { |
||
if (!event.preventDefault) { |
||
event.preventDefault = function() { |
||
event.returnValue = false; //ie |
||
}; |
||
} |
||
|
||
if (!event.stopPropagation) { |
||
event.stopPropagation = function() { |
||
event.cancelBubble = true; //ie |
||
}; |
||
} |
||
|
||
if (!event.target) { |
||
event.target = event.srcElement || document; |
||
} |
||
|
||
if (isUndefined(event.defaultPrevented)) { |
||
var prevent = event.preventDefault; |
||
event.preventDefault = function() { |
||
event.defaultPrevented = true; |
||
prevent.call(event); |
||
}; |
||
event.defaultPrevented = false; |
||
} |
||
|
||
event.isDefaultPrevented = function() { |
||
return event.defaultPrevented || event.returnValue === false; |
||
}; |
||
|
||
// Copy event handlers in case event handlers array is modified during execution. |
||
var eventHandlersCopy = shallowCopy(events[type || event.type] || []); |
||
|
||
forEach(eventHandlersCopy, function(fn) { |
||
fn.call(element, event); |
||
}); |
||
|
||
// Remove monkey-patched methods (IE), |
||
// as they would cause memory leaks in IE8. |
||
if (msie <= 8) { |
||
// IE7/8 does not allow to delete property on native object |
||
event.preventDefault = null; |
||
event.stopPropagation = null; |
||
event.isDefaultPrevented = null; |
||
} else { |
||
// It shouldn't affect normal browsers (native methods are defined on prototype). |
||
delete event.preventDefault; |
||
delete event.stopPropagation; |
||
delete event.isDefaultPrevented; |
||
} |
||
}; |
||
eventHandler.elem = element; |
||
return eventHandler; |
||
} |
||
|
||
////////////////////////////////////////// |
||
// Functions iterating traversal. |
||
// These functions chain results into a single |
||
// selector. |
||
////////////////////////////////////////// |
||
forEach({ |
||
removeData: jqLiteRemoveData, |
||
|
||
dealoc: jqLiteDealoc, |
||
|
||
on: function onFn(element, type, fn, unsupported){ |
||
if (isDefined(unsupported)) throw jqLiteMinErr('onargs', 'jqLite#on() does not support the `selector` or `eventData` parameters'); |
||
|
||
var events = jqLiteExpandoStore(element, 'events'), |
||
handle = jqLiteExpandoStore(element, 'handle'); |
||
|
||
if (!events) jqLiteExpandoStore(element, 'events', events = {}); |
||
if (!handle) jqLiteExpandoStore(element, 'handle', handle = createEventHandler(element, events)); |
||
|
||
forEach(type.split(' '), function(type){ |
||
var eventFns = events[type]; |
||
|
||
if (!eventFns) { |
||
if (type == 'mouseenter' || type == 'mouseleave') { |
||
var contains = document.body.contains || document.body.compareDocumentPosition ? |
||
function( a, b ) { |
||
// jshint bitwise: false |
||
var adown = a.nodeType === 9 ? a.documentElement : a, |
||
bup = b && b.parentNode; |
||
return a === bup || !!( bup && bup.nodeType === 1 && ( |
||
adown.contains ? |
||
adown.contains( bup ) : |
||
a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 |
||
)); |
||
} : |
||
function( a, b ) { |
||
if ( b ) { |
||
while ( (b = b.parentNode) ) { |
||
if ( b === a ) { |
||
return true; |
||
} |
||
} |
||
} |
||
return false; |
||
}; |
||
|
||
events[type] = []; |
||
|
||
// Refer to jQuery's implementation of mouseenter & mouseleave |
||
// Read about mouseenter and mouseleave: |
||
// http://www.quirksmode.org/js/events_mouse.html#link8 |
||
var eventmap = { mouseleave : "mouseout", mouseenter : "mouseover"}; |
||
|
||
onFn(element, eventmap[type], function(event) { |
||
var target = this, related = event.relatedTarget; |
||
// For mousenter/leave call the handler if related is outside the target. |
||
// NB: No relatedTarget if the mouse left/entered the browser window |
||
if ( !related || (related !== target && !contains(target, related)) ){ |
||
handle(event, type); |
||
} |
||
}); |
||
|
||
} else { |
||
addEventListenerFn(element, type, handle); |
||
events[type] = []; |
||
} |
||
eventFns = events[type]; |
||
} |
||
eventFns.push(fn); |
||
}); |
||
}, |
||
|
||
off: jqLiteOff, |
||
|
||
one: function(element, type, fn) { |
||
element = jqLite(element); |
||
|
||
//add the listener twice so that when it is called |
||
//you can remove the original function and still be |
||
//able to call element.off(ev, fn) normally |
||
element.on(type, function onFn() { |
||
element.off(type, fn); |
||
element.off(type, onFn); |
||
}); |
||
element.on(type, fn); |
||
}, |
||
|
||
replaceWith: function(element, replaceNode) { |
||
var index, parent = element.parentNode; |
||
jqLiteDealoc(element); |
||
forEach(new JQLite(replaceNode), function(node){ |
||
if (index) { |
||
parent.insertBefore(node, index.nextSibling); |
||
} else { |
||
parent.replaceChild(node, element); |
||
} |
||
index = node; |
||
}); |
||
}, |
||
|
||
children: function(element) { |
||
var children = []; |
||
forEach(element.childNodes, function(element){ |
||
if (element.nodeType === 1) |
||
children.push(element); |
||
}); |
||
return children; |
||
}, |
||
|
||
contents: function(element) { |
||
return element.childNodes || []; |
||
}, |
||
|
||
append: function(element, node) { |
||
forEach(new JQLite(node), function(child){ |
||
if (element.nodeType === 1 || element.nodeType === 11) { |
||
element.appendChild(child); |
||
} |
||
}); |
||
}, |
||
|
||
prepend: function(element, node) { |
||
if (element.nodeType === 1) { |
||
var index = element.firstChild; |
||
forEach(new JQLite(node), function(child){ |
||
element.insertBefore(child, index); |
||
}); |
||
} |
||
}, |
||
|
||
wrap: function(element, wrapNode) { |
||
wrapNode = jqLite(wrapNode)[0]; |
||
var parent = element.parentNode; |
||
if (parent) { |
||
parent.replaceChild(wrapNode, element); |
||
} |
||
wrapNode.appendChild(element); |
||
}, |
||
|
||
remove: function(element) { |
||
jqLiteDealoc(element); |
||
var parent = element.parentNode; |
||
if (parent) parent.removeChild(element); |
||
}, |
||
|
||
after: function(element, newElement) { |
||
var index = element, parent = element.parentNode; |
||
forEach(new JQLite(newElement), function(node){ |
||
parent.insertBefore(node, index.nextSibling); |
||
index = node; |
||
}); |
||
}, |
||
|
||
addClass: jqLiteAddClass, |
||
removeClass: jqLiteRemoveClass, |
||
|
||
toggleClass: function(element, selector, condition) { |
||
if (isUndefined(condition)) { |
||
condition = !jqLiteHasClass(element, selector); |
||
} |
||
(condition ? jqLiteAddClass : jqLiteRemoveClass)(element, selector); |
||
}, |
||
|
||
parent: function(element) { |
||
var parent = element.parentNode; |
||
return parent && parent.nodeType !== 11 ? parent : null; |
||
}, |
||
|
||
next: function(element) { |
||
if (element.nextElementSibling) { |
||
return element.nextElementSibling; |
||
} |
||
|
||
// IE8 doesn't have nextElementSibling |
||
var elm = element.nextSibling; |
||
while (elm != null && elm.nodeType !== 1) { |
||
elm = elm.nextSibling; |
||
} |
||
return elm; |
||
}, |
||
|
||
find: function(element, selector) { |
||
if (element.getElementsByTagName) { |
||
return element.getElementsByTagName(selector); |
||
} else { |
||
return []; |
||
} |
||
}, |
||
|
||
clone: jqLiteClone, |
||
|
||
triggerHandler: function(element, eventName, eventData) { |
||
var eventFns = (jqLiteExpandoStore(element, 'events') || {})[eventName]; |
||
|
||
eventData = eventData || []; |
||
|
||
var event = [{ |
||
preventDefault: noop, |
||
stopPropagation: noop |
||
}]; |
||
|
||
forEach(eventFns, function(fn) { |
||
fn.apply(element, event.concat(eventData)); |
||
}); |
||
} |
||
}, function(fn, name){ |
||
/** |
||
* chaining functions |
||
*/ |
||
JQLite.prototype[name] = function(arg1, arg2, arg3) { |
||
var value; |
||
for(var i=0; i < this.length; i++) { |
||
if (isUndefined(value)) { |
||
value = fn(this[i], arg1, arg2, arg3); |
||
if (isDefined(value)) { |
||
// any function which returns a value needs to be wrapped |
||
value = jqLite(value); |
||
} |
||
} else { |
||
jqLiteAddNodes(value, fn(this[i], arg1, arg2, arg3)); |
||
} |
||
} |
||
return isDefined(value) ? value : this; |
||
}; |
||
|
||
// bind legacy bind/unbind to on/off |
||
JQLite.prototype.bind = JQLite.prototype.on; |
||
JQLite.prototype.unbind = JQLite.prototype.off; |
||
}); |
||
|
||
/** |
||
* Computes a hash of an 'obj'. |
||
* Hash of a: |
||
* string is string |
||
* number is number as string |
||
* object is either result of calling $$hashKey function on the object or uniquely generated id, |
||
* that is also assigned to the $$hashKey property of the object. |
||
* |
||
* @param obj |
||
* @returns {string} hash string such that the same input will have the same hash string. |
||
* The resulting string key is in 'type:hashKey' format. |
||
*/ |
||
function hashKey(obj) { |
||
var objType = typeof obj, |
||
key; |
||
|
||
if (objType == 'object' && obj !== null) { |
||
if (typeof (key = obj.$$hashKey) == 'function') { |
||
// must invoke on object to keep the right this |
||
key = obj.$$hashKey(); |
||
} else if (key === undefined) { |
||
key = obj.$$hashKey = nextUid(); |
||
} |
||
} else { |
||
key = obj; |
||
} |
||
|
||
return objType + ':' + key; |
||
} |
||
|
||
/** |
||
* HashMap which can use objects as keys |
||
*/ |
||
function HashMap(array){ |
||
forEach(array, this.put, this); |
||
} |
||
HashMap.prototype = { |
||
/** |
||
* Store key value pair |
||
* @param key key to store can be any type |
||
* @param value value to store can be any type |
||
*/ |
||
put: function(key, value) { |
||
this[hashKey(key)] = value; |
||
}, |
||
|
||
/** |
||
* @param key |
||
* @returns the value for the key |
||
*/ |
||
get: function(key) { |
||
return this[hashKey(key)]; |
||
}, |
||
|
||
/** |
||
* Remove the key/value pair |
||
* @param key |
||
*/ |
||
remove: function(key) { |
||
var value = this[key = hashKey(key)]; |
||
delete this[key]; |
||
return value; |
||
} |
||
}; |
||
|
||
/** |
||
* @ngdoc function |
||
* @name angular.injector |
||
* @function |
||
* |
||
* @description |
||
* Creates an injector function that can be used for retrieving services as well as for |
||
* dependency injection (see {@link guide/di dependency injection}). |
||
* |
||
|
||
* @param {Array.<string|Function>} modules A list of module functions or their aliases. See |
||
* {@link angular.module}. The `ng` module must be explicitly added. |
||
* @returns {function()} Injector function. See {@link AUTO.$injector $injector}. |
||
* |
||
* @example |
||
* Typical usage |
||
* <pre> |
||
* // create an injector |
||
* var $injector = angular.injector(['ng']); |
||
* |
||
* // use the injector to kick off your application |
||
* // use the type inference to auto inject arguments, or use implicit injection |
||
* $injector.invoke(function($rootScope, $compile, $document){ |
||
* $compile($document)($rootScope); |
||
* $rootScope.$digest(); |
||
* }); |
||
* </pre> |
||
* |
||
* Sometimes you want to get access to the injector of a currently running Angular app |
||
* from outside Angular. Perhaps, you want to inject and compile some markup after the |
||
* application has been bootstrapped. You can do this using extra `injector()` added |
||
* to JQuery/jqLite elements. See {@link angular.element}. |
||
* |
||
* *This is fairly rare but could be the case if a third party library is injecting the |
||
* markup.* |
||
* |
||
* In the following example a new block of HTML containing a `ng-controller` |
||
* directive is added to the end of the document body by JQuery. We then compile and link |
||
* it into the current AngularJS scope. |
||
* |
||
* <pre> |
||
* var $div = $('<div ng-controller="MyCtrl">{{content.label}}</div>'); |
||
* $(document.body).append($div); |
||
* |
||
* angular.element(document).injector().invoke(function($compile) { |
||
* var scope = angular.element($div).scope(); |
||
* $compile($div)(scope); |
||
* }); |
||
* </pre> |
||
*/ |
||
|
||
|
||
/** |
||
* @ngdoc overview |
||
* @name AUTO |
||
* @description |
||
* |
||
* Implicit module which gets automatically added to each {@link AUTO.$injector $injector}. |
||
*/ |
||
|
||
var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m; |
||
var FN_ARG_SPLIT = /,/; |
||
var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/; |
||
var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg; |
||
var $injectorMinErr = minErr('$injector'); |
||
function annotate(fn) { |
||
var $inject, |
||
fnText, |
||
argDecl, |
||
last; |
||
|
||
if (typeof fn == 'function') { |
||
if (!($inject = fn.$inject)) { |
||
$inject = []; |
||
if (fn.length) { |
||
fnText = fn.toString().replace(STRIP_COMMENTS, ''); |
||
argDecl = fnText.match(FN_ARGS); |
||
forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg){ |
||
arg.replace(FN_ARG, function(all, underscore, name){ |
||
$inject.push(name); |
||
}); |
||
}); |
||
} |
||
fn.$inject = $inject; |
||
} |
||
} else if (isArray(fn)) { |
||
last = fn.length - 1; |
||
assertArgFn(fn[last], 'fn'); |
||
$inject = fn.slice(0, last); |
||
} else { |
||
assertArgFn(fn, 'fn', true); |
||
} |
||
return $inject; |
||
} |
||
|
||
/////////////////////////////////////// |
||
|
||
/** |
||
* @ngdoc object |
||
* @name AUTO.$injector |
||
* @function |
||
* |
||
* @description |
||
* |
||
* `$injector` is used to retrieve object instances as defined by |
||
* {@link AUTO.$provide provider}, instantiate types, invoke methods, |
||
* and load modules. |
||
* |
||
* The following always holds true: |
||
* |
||
* <pre> |
||
* var $injector = angular.injector(); |
||
* expect($injector.get('$injector')).toBe($injector); |
||
* expect($injector.invoke(function($injector){ |
||
* return $injector; |
||
* }).toBe($injector); |
||
* </pre> |
||
* |
||
* # Injection Function Annotation |
||
* |
||
* JavaScript does not have annotations, and annotations are needed for dependency injection. The |
||
* following are all valid ways of annotating function with injection arguments and are equivalent. |
||
* |
||
* <pre> |
||
* // inferred (only works if code not minified/obfuscated) |
||
* $injector.invoke(function(serviceA){}); |
||
* |
||
* // annotated |
||
* function explicit(serviceA) {}; |
||
* explicit.$inject = ['serviceA']; |
||
* $injector.invoke(explicit); |
||
* |
||
* // inline |
||
* $injector.invoke(['serviceA', function(serviceA){}]); |
||
* </pre> |
||
* |
||
* ## Inference |
||
* |
||
* In JavaScript calling `toString()` on a function returns the function definition. The definition |
||
* can then be parsed and the function arguments can be extracted. *NOTE:* This does not work with |
||
* minification, and obfuscation tools since these tools change the argument names. |
||
* |
||
* ## `$inject` Annotation |
||
* By adding a `$inject` property onto a function the injection parameters can be specified. |
||
* |
||
* ## Inline |
||
* As an array of injection names, where the last item in the array is the function to call. |
||
*/ |
||
|
||
/** |
||
* @ngdoc method |
||
* @name AUTO.$injector#get |
||
* @methodOf AUTO.$injector |
||
* |
||
* @description |
||
* Return an instance of the service. |
||
* |
||
* @param {string} name The name of the instance to retrieve. |
||
* @return {*} The instance. |
||
*/ |
||
|
||
/** |
||
* @ngdoc method |
||
* @name AUTO.$injector#invoke |
||
* @methodOf AUTO.$injector |
||
* |
||
* @description |
||
* Invoke the method and supply the method arguments from the `$injector`. |
||
* |
||
* @param {!function} fn The function to invoke. Function parameters are injected according to the |
||
* {@link guide/di $inject Annotation} rules. |
||
* @param {Object=} self The `this` for the invoked method. |
||
* @param {Object=} locals Optional object. If preset then any argument names are read from this |
||
* object first, before the `$injector` is consulted. |
||
* @returns {*} the value returned by the invoked `fn` function. |
||
*/ |
||
|
||
/** |
||
* @ngdoc method |
||
* @name AUTO.$injector#has |
||
* @methodOf AUTO.$injector |
||
* |
||
* @description |
||
* Allows the user to query if the particular service exist. |
||
* |
||
* @param {string} Name of the service to query. |
||
* @returns {boolean} returns true if injector has given service. |
||
*/ |
||
|
||
/** |
||
* @ngdoc method |
||
* @name AUTO.$injector#instantiate |
||
* @methodOf AUTO.$injector |
||
* @description |
||
* Create a new instance of JS type. The method takes a constructor function invokes the new |
||
* operator and supplies all of the arguments to the constructor function as specified by the |
||
* constructor annotation. |
||
* |
||
* @param {function} Type Annotated constructor function. |
||
* @param {Object=} locals Optional object. If preset then any argument names are read from this |
||
* object first, before the `$injector` is consulted. |
||
* @returns {Object} new instance of `Type`. |
||
*/ |
||
|
||
/** |
||
* @ngdoc method |
||
* @name AUTO.$injector#annotate |
||
* @methodOf AUTO.$injector |
||
* |
||
* @description |
||
* Returns an array of service names which the function is requesting for injection. This API is |
||
* used by the injector to determine which services need to be injected into the function when the |
||
* function is invoked. There are three ways in which the function can be annotated with the needed |
||
* dependencies. |
||
* |
||
* # Argument names |
||
* |
||
* The simplest form is to extract the dependencies from the arguments of the function. This is done |
||
* by converting the function into a string using `toString()` method and extracting the argument |
||
* names. |
||
* <pre> |
||
* // Given |
||
* function MyController($scope, $route) { |
||
* // ... |
||
* } |
||
* |
||
* // Then |
||
* expect(injector.annotate(MyController)).toEqual(['$scope', '$route']); |
||
* </pre> |
||
* |
||
* This method does not work with code minification / obfuscation. For this reason the following |
||
* annotation strategies are supported. |
||
* |
||
* # The `$inject` property |
||
* |
||
* If a function has an `$inject` property and its value is an array of strings, then the strings |
||
* represent names of services to be injected into the function. |
||
* <pre> |
||
* // Given |
||
* var MyController = function(obfuscatedScope, obfuscatedRoute) { |
||
* // ... |
||
* } |
||
* // Define function dependencies |
||
* MyController['$inject'] = ['$scope', '$route']; |
||
* |
||
* // Then |
||
* expect(injector.annotate(MyController)).toEqual(['$scope', '$route']); |
||
* </pre> |
||
* |
||
* # The array notation |
||
* |
||
* It is often desirable to inline Injected functions and that's when setting the `$inject` property |
||
* is very inconvenient. In these situations using the array notation to specify the dependencies in |
||
* a way that survives minification is a better choice: |
||
* |
||
* <pre> |
||
* // We wish to write this (not minification / obfuscation safe) |
||
* injector.invoke(function($compile, $rootScope) { |
||
* // ... |
||
* }); |
||
* |
||
* // We are forced to write break inlining |
||
* var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) { |
||
* // ... |
||
* }; |
||
* tmpFn.$inject = ['$compile', '$rootScope']; |
||
* injector.invoke(tmpFn); |
||
* |
||
* // To better support inline function the inline annotation is supported |
||
* injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) { |
||
* // ... |
||
* }]); |
||
* |
||
* // Therefore |
||
* expect(injector.annotate( |
||
* ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}]) |
||
* ).toEqual(['$compile', '$rootScope']); |
||
* </pre> |
||
* |
||
* @param {function|Array.<string|Function>} fn Function for which dependent service names need to |
||
* be retrieved as described above. |
||
* |
||
* @returns {Array.<string>} The names of the services which the function requires. |
||
*/ |
||
|
||
|
||
|
||
|
||
/** |
||
* @ngdoc object |
||
* @name AUTO.$provide |
||
* |
||
* @description |
||
* |
||
* The {@link AUTO.$provide $provide} service has a number of methods for registering components |
||
* with the {@link AUTO.$injector $injector}. Many of these functions are also exposed on |
||
* {@link angular.Module}. |
||
* |
||
* An Angular **service** is a singleton object created by a **service factory**. These **service |
||
* factories** are functions which, in turn, are created by a **service provider**. |
||
* The **service providers** are constructor functions. When instantiated they must contain a |
||
* property called `$get`, which holds the **service factory** function. |
||
* |
||
* When you request a service, the {@link AUTO.$injector $injector} is responsible for finding the |
||
* correct **service provider**, instantiating it and then calling its `$get` **service factory** |
||
* function to get the instance of the **service**. |
||
* |
||
* Often services have no configuration options and there is no need to add methods to the service |
||
* provider. The provider will be no more than a constructor function with a `$get` property. For |
||
* these cases the {@link AUTO.$provide $provide} service has additional helper methods to register |
||
* services without specifying a provider. |
||
* |
||
* * {@link AUTO.$provide#methods_provider provider(provider)} - registers a **service provider** with the |
||
* {@link AUTO.$injector $injector} |
||
* * {@link AUTO.$provide#methods_constant constant(obj)} - registers a value/object that can be accessed by |
||
* providers and services. |
||
* * {@link AUTO.$provide#methods_value value(obj)} - registers a value/object that can only be accessed by |
||
* services, not providers. |
||
* * {@link AUTO.$provide#methods_factory factory(fn)} - registers a service **factory function**, `fn`, |
||
* that will be wrapped in a **service provider** object, whose `$get` property will contain the |
||
* given factory function. |
||
* * {@link AUTO.$provide#methods_service service(class)} - registers a **constructor function**, `class` that |
||
* that will be wrapped in a **service provider** object, whose `$get` property will instantiate |
||
* a new object using the given constructor function. |
||
* |
||
* See the individual methods for more information and examples. |
||
*/ |
||
|
||
/** |
||
* @ngdoc method |
||
* @name AUTO.$provide#provider |
||
* @methodOf AUTO.$provide |
||
* @description |
||
* |
||
* Register a **provider function** with the {@link AUTO.$injector $injector}. Provider functions |
||
* are constructor functions, whose instances are responsible for "providing" a factory for a |
||
* service. |
||
* |
||
* Service provider names start with the name of the service they provide followed by `Provider`. |
||
* For example, the {@link ng.$log $log} service has a provider called |
||
* {@link ng.$logProvider $logProvider}. |
||
* |
||
* Service provider objects can have additional methods which allow configuration of the provider |
||
* and its service. Importantly, you can configure what kind of service is created by the `$get` |
||
* method, or how that service will act. For example, the {@link ng.$logProvider $logProvider} has a |
||
* method {@link ng.$logProvider#debugEnabled debugEnabled} |
||
* which lets you specify whether the {@link ng.$log $log} service will log debug messages to the |
||
* console or not. |
||
* |
||
* @param {string} name The name of the instance. NOTE: the provider will be available under `name + |
||
'Provider'` key. |
||
* @param {(Object|function())} provider If the provider is: |
||
* |
||
* - `Object`: then it should have a `$get` method. The `$get` method will be invoked using |
||
* {@link AUTO.$injector#invoke $injector.invoke()} when an instance needs to be |
||
* created. |
||
* - `Constructor`: a new instance of the provider will be created using |
||
* {@link AUTO.$injector#instantiate $injector.instantiate()}, then treated as |
||
* `object`. |
||
* |
||
* @returns {Object} registered provider instance |
||
|
||
* @example |
||
* |
||
* The following example shows how to create a simple event tracking service and register it using |
||
* {@link AUTO.$provide#methods_provider $provide.provider()}. |
||
* |
||
* <pre> |
||
* // Define the eventTracker provider |
||
* function EventTrackerProvider() { |
||
* var trackingUrl = '/track'; |
||
* |
||
* // A provider method for configuring where the tracked events should been saved |
||
* this.setTrackingUrl = function(url) { |
||
* trackingUrl = url; |
||
* }; |
||
* |
||
* // The service factory function |
||
* this.$get = ['$http', function($http) { |
||
* var trackedEvents = {}; |
||
* return { |
||
* // Call this to track an event |
||
* event: function(event) { |
||
* var count = trackedEvents[event] || 0; |
||
* count += 1; |
||
* trackedEvents[event] = count; |
||
* return count; |
||
* }, |
||
* // Call this to save the tracked events to the trackingUrl |
||
* save: function() { |
||
* $http.post(trackingUrl, trackedEvents); |
||
* } |
||
* }; |
||
* }]; |
||
* } |
||
* |
||
* describe('eventTracker', function() { |
||
* var postSpy; |
||
* |
||
* beforeEach(module(function($provide) { |
||
* // Register the eventTracker provider |
||
* $provide.provider('eventTracker', EventTrackerProvider); |
||
* })); |
||
* |
||
* beforeEach(module(function(eventTrackerProvider) { |
||
* // Configure eventTracker provider |
||
* eventTrackerProvider.setTrackingUrl('/custom-track'); |
||
* })); |
||
* |
||
* it('tracks events', inject(function(eventTracker) { |
||
* expect(eventTracker.event('login')).toEqual(1); |
||
* expect(eventTracker.event('login')).toEqual(2); |
||
* })); |
||
* |
||
* it('saves to the tracking url', inject(function(eventTracker, $http) { |
||
* postSpy = spyOn($http, 'post'); |
||
* eventTracker.event('login'); |
||
* eventTracker.save(); |
||
* expect(postSpy).toHaveBeenCalled(); |
||
* expect(postSpy.mostRecentCall.args[0]).not.toEqual('/track'); |
||
* expect(postSpy.mostRecentCall.args[0]).toEqual('/custom-track'); |
||
* expect(postSpy.mostRecentCall.args[1]).toEqual({ 'login': 1 }); |
||
* })); |
||
* }); |
||
* </pre> |
||
*/ |
||
|
||
/** |
||
* @ngdoc method |
||
* @name AUTO.$provide#factory |
||
* @methodOf AUTO.$provide |
||
* @description |
||
* |
||
* Register a **service factory**, which will be called to return the service instance. |
||
* This is short for registering a service where its provider consists of only a `$get` property, |
||
* which is the given service factory function. |
||
* You should use {@link AUTO.$provide#factory $provide.factory(getFn)} if you do not need to |
||
* configure your service in a provider. |
||
* |
||
* @param {string} name The name of the instance. |
||
* @param {function()} $getFn The $getFn for the instance creation. Internally this is a short hand |
||
* for `$provide.provider(name, {$get: $getFn})`. |
||
* @returns {Object} registered provider instance |
||
* |
||
* @example |
||
* Here is an example of registering a service |
||
* <pre> |
||
* $provide.factory('ping', ['$http', function($http) { |
||
* return function ping() { |
||
* return $http.send('/ping'); |
||
* }; |
||
* }]); |
||
* </pre> |
||
* You would then inject and use this service like this: |
||
* <pre> |
||
* someModule.controller('Ctrl', ['ping', function(ping) { |
||
* ping(); |
||
* }]); |
||
* </pre> |
||
*/ |
||
|
||
|
||
/** |
||
* @ngdoc method |
||
* @name AUTO.$provide#service |
||
* @methodOf AUTO.$provide |
||
* @description |
||
* |
||
* Register a **service constructor**, which will be invoked with `new` to create the service |
||
* instance. |
||
* This is short for registering a service where its provider's `$get` property is the service |
||
* constructor function that will be used to instantiate the service instance. |
||
* |
||
* You should use {@link AUTO.$provide#methods_service $provide.service(class)} if you define your service |
||
* as a type/class. |
||
* |
||
* @param {string} name The name of the instance. |
||
* @param {Function} constructor A class (constructor function) that will be instantiated. |
||
* @returns {Object} registered provider instance |
||
* |
||
* @example |
||
* Here is an example of registering a service using |
||
* {@link AUTO.$provide#methods_service $provide.service(class)}. |
||
* <pre> |
||
* $provide.service('ping', ['$http', function($http) { |
||
* var Ping = function() { |
||
* this.$http = $http; |
||
* }; |
||
* |
||
* Ping.prototype.send = function() { |
||
* return this.$http.get('/ping'); |
||
* }; |
||
* |
||
* return Ping; |
||
* }]); |
||
* </pre> |
||
* You would then inject and use this service like this: |
||
* <pre> |
||
* someModule.controller('Ctrl', ['ping', function(ping) { |
||
* ping.send(); |
||
* }]); |
||
* </pre> |
||
*/ |
||
|
||
|
||
/** |
||
* @ngdoc method |
||
* @name AUTO.$provide#value |
||
* @methodOf AUTO.$provide |
||
* @description |
||
* |
||
* Register a **value service** with the {@link AUTO.$injector $injector}, such as a string, a |
||
* number, an array, an object or a function. This is short for registering a service where its |
||
* provider's `$get` property is a factory function that takes no arguments and returns the **value |
||
* service**. |
||
* |
||
* Value services are similar to constant services, except that they cannot be injected into a |
||
* module configuration function (see {@link angular.Module#config}) but they can be overridden by |
||
* an Angular |
||
* {@link AUTO.$provide#decorator decorator}. |
||
* |
||
* @param {string} name The name of the instance. |
||
* @param {*} value The value. |
||
* @returns {Object} registered provider instance |
||
* |
||
* @example |
||
* Here are some examples of creating value services. |
||
* <pre> |
||
* $provide.value('ADMIN_USER', 'admin'); |
||
* |
||
* $provide.value('RoleLookup', { admin: 0, writer: 1, reader: 2 }); |
||
* |
||
* $provide.value('halfOf', function(value) { |
||
* return value / 2; |
||
* }); |
||
* </pre> |
||
*/ |
||
|
||
|
||
/** |
||
* @ngdoc method |
||
* @name AUTO.$provide#constant |
||
* @methodOf AUTO.$provide |
||
* @description |
||
* |
||
* Register a **constant service**, such as a string, a number, an array, an object or a function, |
||
* with the {@link AUTO.$injector $injector}. Unlike {@link AUTO.$provide#value value} it can be |
||
* injected into a module configuration function (see {@link angular.Module#config}) and it cannot |
||
* be overridden by an Angular {@link AUTO.$provide#decorator decorator}. |
||
* |
||
* @param {string} name The name of the constant. |
||
* @param {*} value The constant value. |
||
* @returns {Object} registered instance |
||
* |
||
* @example |
||
* Here a some examples of creating constants: |
||
* <pre> |
||
* $provide.constant('SHARD_HEIGHT', 306); |
||
* |
||
* $provide.constant('MY_COLOURS', ['red', 'blue', 'grey']); |
||
* |
||
* $provide.constant('double', function(value) { |
||
* return value * 2; |
||
* }); |
||
* </pre> |
||
*/ |
||
|
||
|
||
/** |
||
* @ngdoc method |
||
* @name AUTO.$provide#decorator |
||
* @methodOf AUTO.$provide |
||
* @description |
||
* |
||
* Register a **service decorator** with the {@link AUTO.$injector $injector}. A service decorator |
||
* intercepts the creation of a service, allowing it to override or modify the behaviour of the |
||
* service. The object returned by the decorator may be the original service, or a new service |
||
* object which replaces or wraps and delegates to the original service. |
||
* |
||
* @param {string} name The name of the service to decorate. |
||
* @param {function()} decorator This function will be invoked when the service needs to be |
||
* instantiated and should return the decorated service instance. The function is called using |
||
* the {@link AUTO.$injector#invoke injector.invoke} method and is therefore fully injectable. |
||
* Local injection arguments: |
||
* |
||
* * `$delegate` - The original service instance, which can be monkey patched, configured, |
||
* decorated or delegated to. |
||
* |
||
* @example |
||
* Here we decorate the {@link ng.$log $log} service to convert warnings to errors by intercepting |
||
* calls to {@link ng.$log#error $log.warn()}. |
||
* <pre> |
||
* $provider.decorator('$log', ['$delegate', function($delegate) { |
||
* $delegate.warn = $delegate.error; |
||
* return $delegate; |
||
* }]); |
||
* </pre> |
||
*/ |
||
|
||
|
||
function createInjector(modulesToLoad) { |
||
var INSTANTIATING = {}, |
||
providerSuffix = 'Provider', |
||
path = [], |
||
loadedModules = new HashMap(), |
||
providerCache = { |
||
$provide: { |
||
provider: supportObject(provider), |
||
factory: supportObject(factory), |
||
service: supportObject(service), |
||
value: supportObject(value), |
||
constant: supportObject(constant), |
||
decorator: decorator |
||
} |
||
}, |
||
providerInjector = (providerCache.$injector = |
||
createInternalInjector(providerCache, function() { |
||
throw $injectorMinErr('unpr', "Unknown provider: {0}", path.join(' <- ')); |
||
})), |
||
instanceCache = {}, |
||
instanceInjector = (instanceCache.$injector = |
||
createInternalInjector(instanceCache, function(servicename) { |
||
var provider = providerInjector.get(servicename + providerSuffix); |
||
return instanceInjector.invoke(provider.$get, provider); |
||
})); |
||
|
||
|
||
forEach(loadModules(modulesToLoad), function(fn) { instanceInjector.invoke(fn || noop); }); |
||
|
||
return instanceInjector; |
||
|
||
//////////////////////////////////// |
||
// $provider |
||
//////////////////////////////////// |
||
|
||
function supportObject(delegate) { |
||
return function(key, value) { |
||
if (isObject(key)) { |
||
forEach(key, reverseParams(delegate)); |
||
} else { |
||
return delegate(key, value); |
||
} |
||
}; |
||
} |
||
|
||
function provider(name, provider_) { |
||
assertNotHasOwnProperty(name, 'service'); |
||
if (isFunction(provider_) || isArray(provider_)) { |
||
provider_ = providerInjector.instantiate(provider_); |
||
} |
||
if (!provider_.$get) { |
||
throw $injectorMinErr('pget', "Provider '{0}' must define $get factory method.", name); |
||
} |
||
return providerCache[name + providerSuffix] = provider_; |
||
} |
||
|
||
function factory(name, factoryFn) { return provider(name, { $get: factoryFn }); } |
||
|
||
function service(name, constructor) { |
||
return factory(name, ['$injector', function($injector) { |
||
return $injector.instantiate(constructor); |
||
}]); |
||
} |
||
|
||
function value(name, val) { return factory(name, valueFn(val)); } |
||
|
||
function constant(name, value) { |
||
assertNotHasOwnProperty(name, 'constant'); |
||
providerCache[name] = value; |
||
instanceCache[name] = value; |
||
} |
||
|
||
function decorator(serviceName, decorFn) { |
||
var origProvider = providerInjector.get(serviceName + providerSuffix), |
||
orig$get = origProvider.$get; |
||
|
||
origProvider.$get = function() { |
||
var origInstance = instanceInjector.invoke(orig$get, origProvider); |
||
return instanceInjector.invoke(decorFn, null, {$delegate: origInstance}); |
||
}; |
||
} |
||
|
||
//////////////////////////////////// |
||
// Module Loading |
||
//////////////////////////////////// |
||
function loadModules(modulesToLoad){ |
||
var runBlocks = [], moduleFn, invokeQueue, i, ii; |
||
forEach(modulesToLoad, function(module) { |
||
if (loadedModules.get(module)) return; |
||
loadedModules.put(module, true); |
||
|
||
try { |
||
if (isString(module)) { |
||
moduleFn = angularModule(module); |
||
runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks); |
||
|
||
for(invokeQueue = moduleFn._invokeQueue, i = 0, ii = invokeQueue.length; i < ii; i++) { |
||
var invokeArgs = invokeQueue[i], |
||
provider = providerInjector.get(invokeArgs[0]); |
||
|
||
provider[invokeArgs[1]].apply(provider, invokeArgs[2]); |
||
} |
||
} else if (isFunction(module)) { |
||
runBlocks.push(providerInjector.invoke(module)); |
||
} else if (isArray(module)) { |
||
runBlocks.push(providerInjector.invoke(module)); |
||
} else { |
||
assertArgFn(module, 'module'); |
||
} |
||
} catch (e) { |
||
if (isArray(module)) { |
||
module = module[module.length - 1]; |
||
} |
||
if (e.message && e.stack && e.stack.indexOf(e.message) == -1) { |
||
// Safari & FF's stack traces don't contain error.message content |
||
// unlike those of Chrome and IE |
||
// So if stack doesn't contain message, we create a new string that contains both. |
||
// Since error.stack is read-only in Safari, I'm overriding e and not e.stack here. |
||
/* jshint -W022 */ |
||
e = e.message + '\n' + e.stack; |
||
} |
||
throw $injectorMinErr('modulerr', "Failed to instantiate module {0} due to:\n{1}", |
||
module, e.stack || e.message || e); |
||
} |
||
}); |
||
return runBlocks; |
||
} |
||
|
||
//////////////////////////////////// |
||
// internal Injector |
||
//////////////////////////////////// |
||
|
||
function createInternalInjector(cache, factory) { |
||
|
||
function getService(serviceName) { |
||
if (cache.hasOwnProperty(serviceName)) { |
||
if (cache[serviceName] === INSTANTIATING) { |
||
throw $injectorMinErr('cdep', 'Circular dependency found: {0}', path.join(' <- ')); |
||
} |
||
return cache[serviceName]; |
||
} else { |
||
try { |
||
path.unshift(serviceName); |
||
cache[serviceName] = INSTANTIATING; |
||
return cache[serviceName] = factory(serviceName); |
||
} catch (err) { |
||
if (cache[serviceName] === INSTANTIATING) { |
||
delete cache[serviceName]; |
||
} |
||
throw err; |
||
} finally { |
||
path.shift(); |
||
} |
||
} |
||
} |
||
|
||
function invoke(fn, self, locals){ |
||
var args = [], |
||
$inject = annotate(fn), |
||
length, i, |
||
key; |
||
|
||
for(i = 0, length = $inject.length; i < length; i++) { |
||
key = $inject[i]; |
||
if (typeof key !== 'string') { |
||
throw $injectorMinErr('itkn', |
||
'Incorrect injection token! Expected service name as string, got {0}', key); |
||
} |
||
args.push( |
||
locals && locals.hasOwnProperty(key) |
||
? locals[key] |
||
: getService(key) |
||
); |
||
} |
||
if (!fn.$inject) { |
||
// this means that we must be an array. |
||
fn = fn[length]; |
||
} |
||
|
||
// http://jsperf.com/angularjs-invoke-apply-vs-switch |
||
// #5388 |
||
return fn.apply(self, args); |
||
} |
||
|
||
function instantiate(Type, locals) { |
||
var Constructor = function() {}, |
||
instance, returnedValue; |
||
|
||
// Check if Type is annotated and use just the given function at n-1 as parameter |
||
// e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]); |
||
Constructor.prototype = (isArray(Type) ? Type[Type.length - 1] : Type).prototype; |
||
instance = new Constructor(); |
||
returnedValue = invoke(Type, instance, locals); |
||
|
||
return isObject(returnedValue) || isFunction(returnedValue) ? returnedValue : instance; |
||
} |
||
|
||
return { |
||
invoke: invoke, |
||
instantiate: instantiate, |
||
get: getService, |
||
annotate: annotate, |
||
has: function(name) { |
||
return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name); |
||
} |
||
}; |
||
} |
||
} |
||
|
||
/** |
||
* @ngdoc function |
||
* @name ng.$anchorScroll |
||
* @requires $window |
||
* @requires $location |
||
* @requires $rootScope |
||
* |
||
* @description |
||
* When called, it checks current value of `$location.hash()` and scroll to related element, |
||
* according to rules specified in |
||
* {@link http://dev.w3.org/html5/spec/Overview.html#the-indicated-part-of-the-document Html5 spec}. |
||
* |
||
* It also watches the `$location.hash()` and scrolls whenever it changes to match any anchor. |
||
* This can be disabled by calling `$anchorScrollProvider.disableAutoScrolling()`. |
||
* |
||
* @example |
||
<example> |
||
<file name="index.html"> |
||
<div id="scrollArea" ng-controller="ScrollCtrl"> |
||
<a ng-click="gotoBottom()">Go to bottom</a> |
||
<a id="bottom"></a> You're at the bottom! |
||
</div> |
||
</file> |
||
<file name="script.js"> |
||
function ScrollCtrl($scope, $location, $anchorScroll) { |
||
$scope.gotoBottom = function (){ |
||
// set the location.hash to the id of |
||
// the element you wish to scroll to. |
||
$location.hash('bottom'); |
||
|
||
// call $anchorScroll() |
||
$anchorScroll(); |
||
} |
||
} |
||
</file> |
||
<file name="style.css"> |
||
#scrollArea { |
||
height: 350px; |
||
overflow: auto; |
||
} |
||
|
||
#bottom { |
||
display: block; |
||
margin-top: 2000px; |
||
} |
||
</file> |
||
</example> |
||
*/ |
||
function $AnchorScrollProvider() { |
||
|
||
var autoScrollingEnabled = true; |
||
|
||
this.disableAutoScrolling = function() { |
||
autoScrollingEnabled = false; |
||
}; |
||
|
||
this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) { |
||
var document = $window.document; |
||
|
||
// helper function to get first anchor from a NodeList |
||
// can't use filter.filter, as it accepts only instances of Array |
||
// and IE can't convert NodeList to an array using [].slice |
||
// TODO(vojta): use filter if we change it to accept lists as well |
||
function getFirstAnchor(list) { |
||
var result = null; |
||
forEach(list, function(element) { |
||
if (!result && lowercase(element.nodeName) === 'a') result = element; |
||
}); |
||
return result; |
||
} |
||
|
||
function scroll() { |
||
var hash = $location.hash(), elm; |
||
|
||
// empty hash, scroll to the top of the page |
||
if (!hash) $window.scrollTo(0, 0); |
||
|
||
// element with given id |
||
else if ((elm = document.getElementById(hash))) elm.scrollIntoView(); |
||
|
||
// first anchor with given name :-D |
||
else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) elm.scrollIntoView(); |
||
|
||
// no element and hash == 'top', scroll to the top of the page |
||
else if (hash === 'top') $window.scrollTo(0, 0); |
||
} |
||
|
||
// does not scroll when user clicks on anchor link that is currently on |
||
// (no url change, no $location.hash() change), browser native does scroll |
||
if (autoScrollingEnabled) { |
||
$rootScope.$watch(function autoScrollWatch() {return $location.hash();}, |
||
function autoScrollWatchAction() { |
||
$rootScope.$evalAsync(scroll); |
||
}); |
||
} |
||
|
||
return scroll; |
||
}]; |
||
} |
||
|
||
var $animateMinErr = minErr('$animate'); |
||
|
||
/** |
||
* @ngdoc object |
||
* @name ng.$animateProvider |
||
* |
||
* @description |
||
* Default implementation of $animate that doesn't perform any animations, instead just |
||
* synchronously performs DOM |
||
* updates and calls done() callbacks. |
||
* |
||
* In order to enable animations the ngAnimate module has to be loaded. |
||
* |
||
* To see the functional implementation check out src/ngAnimate/animate.js |
||
*/ |
||
var $AnimateProvider = ['$provide', function($provide) { |
||
|
||
|
||
this.$$selectors = {}; |
||
|
||
|
||
/** |
||
* @ngdoc function |
||
* @name ng.$animateProvider#register |
||
* @methodOf ng.$animateProvider |
||
* |
||
* @description |
||
* Registers a new injectable animation factory function. The factory function produces the |
||
* animation object which contains callback functions for each event that is expected to be |
||
* animated. |
||
* |
||
* * `eventFn`: `function(Element, doneFunction)` The element to animate, the `doneFunction` |
||
* must be called once the element animation is complete. If a function is returned then the |
||
* animation service will use this function to cancel the animation whenever a cancel event is |
||
* triggered. |
||
* |
||
* |
||
*<pre> |
||
* return { |
||
* eventFn : function(element, done) { |
||
* //code to run the animation |
||
* //once complete, then run done() |
||
* return function cancellationFunction() { |
||
* //code to cancel the animation |
||
* } |
||
* } |
||
* } |
||
*</pre> |
||
* |
||
* @param {string} name The name of the animation. |
||
* @param {function} factory The factory function that will be executed to return the animation |
||
* object. |
||
*/ |
||
this.register = function(name, factory) { |
||
var key = name + '-animation'; |
||
if (name && name.charAt(0) != '.') throw $animateMinErr('notcsel', |
||
"Expecting class selector starting with '.' got '{0}'.", name); |
||
this.$$selectors[name.substr(1)] = key; |
||
$provide.factory(key, factory); |
||
}; |
||
|
||
/** |
||
* @ngdoc function |
||
* @name ng.$animateProvider#classNameFilter |
||
* @methodOf ng.$animateProvider |
||
* |
||
* @description |
||
* Sets and/or returns the CSS class regular expression that is checked when performing |
||
* an animation. Upon bootstrap the classNameFilter value is not set at all and will |
||
* therefore enable $animate to attempt to perform an animation on any element. |
||
* When setting the classNameFilter value, animations will only be performed on elements |
||
* that successfully match the filter expression. This in turn can boost performance |
||
* for low-powered devices as well as applications containing a lot of structural operations. |
||
* @param {RegExp=} expression The className expression which will be checked against all animations |
||
* @return {RegExp} The current CSS className expression value. If null then there is no expression value |
||
*/ |
||
this.classNameFilter = function(expression) { |
||
if(arguments.length === 1) { |
||
this.$$classNameFilter = (expression instanceof RegExp) ? expression : null; |
||
} |
||
return this.$$classNameFilter; |
||
}; |
||
|
||
this.$get = ['$timeout', function($timeout) { |
||
|
||
/** |
||
* |
||
* @ngdoc object |
||
* @name ng.$animate |
||
* @description The $animate service provides rudimentary DOM manipulation functions to |
||
* insert, remove and move elements within the DOM, as well as adding and removing classes. |
||
* This service is the core service used by the ngAnimate $animator service which provides |
||
* high-level animation hooks for CSS and JavaScript. |
||
* |
||
* $animate is available in the AngularJS core, however, the ngAnimate module must be included |
||
* to enable full out animation support. Otherwise, $animate will only perform simple DOM |
||
* manipulation operations. |
||
* |
||
* To learn more about enabling animation support, click here to visit the {@link ngAnimate |
||
* ngAnimate module page} as well as the {@link ngAnimate.$animate ngAnimate $animate service |
||
* page}. |
||
*/ |
||
return { |
||
|
||
/** |
||
* |
||
* @ngdoc function |
||
* @name ng.$animate#enter |
||
* @methodOf ng.$animate |
||
* @function |
||
* @description Inserts the element into the DOM either after the `after` element or within |
||
* the `parent` element. Once complete, the done() callback will be fired (if provided). |
||
* @param {jQuery/jqLite element} element the element which will be inserted into the DOM |
||
* @param {jQuery/jqLite element} parent the parent element which will append the element as |
||
* a child (if the after element is not present) |
||
* @param {jQuery/jqLite element} after the sibling element which will append the element |
||
* after itself |
||
* @param {function=} done callback function that will be called after the element has been |
||
* inserted into the DOM |
||
*/ |
||
enter : function(element, parent, after, done) { |
||
if (after) { |
||
after.after(element); |
||
} else { |
||
if (!parent || !parent[0]) { |
||
parent = after.parent(); |
||
} |
||
parent.append(element); |
||
} |
||
done && $timeout(done, 0, false); |
||
}, |
||
|
||
/** |
||
* |
||
* @ngdoc function |
||
* @name ng.$animate#leave |
||
* @methodOf ng.$animate |
||
* @function |
||
* @description Removes the element from the DOM. Once complete, the done() callback will be |
||
* fired (if provided). |
||
* @param {jQuery/jqLite element} element the element which will be removed from the DOM |
||
* @param {function=} done callback function that will be called after the element has been |
||
* removed from the DOM |
||
*/ |
||
leave : function(element, done) { |
||
element.remove(); |
||
done && $timeout(done, 0, false); |
||
}, |
||
|
||
/** |
||
* |
||
* @ngdoc function |
||
* @name ng.$animate#move |
||
* @methodOf ng.$animate |
||
* @function |
||
* @description Moves the position of the provided element within the DOM to be placed |
||
* either after the `after` element or inside of the `parent` element. Once complete, the |
||
* done() callback will be fired (if provided). |
||
* |
||
* @param {jQuery/jqLite element} element the element which will be moved around within the |
||
* DOM |
||
* @param {jQuery/jqLite element} parent the parent element where the element will be |
||
* inserted into (if the after element is not present) |
||
* @param {jQuery/jqLite element} after the sibling element where the element will be |
||
* positioned next to |
||
* @param {function=} done the callback function (if provided) that will be fired after the |
||
* element has been moved to its new position |
||
*/ |
||
move : function(element, parent, after, done) { |
||
// Do not remove element before insert. Removing will cause data associated with the |
||
// element to be dropped. Insert will implicitly do the remove. |
||
this.enter(element, parent, after, done); |
||
}, |
||
|
||
/** |
||
* |
||
* @ngdoc function |
||
* @name ng.$animate#addClass |
||
* @methodOf ng.$animate |
||
* @function |
||
* @description Adds the provided className CSS class value to the provided element. Once |
||
* complete, the done() callback will be fired (if provided). |
||
* @param {jQuery/jqLite element} element the element which will have the className value |
||
* added to it |
||
* @param {string} className the CSS class which will be added to the element |
||
* @param {function=} done the callback function (if provided) that will be fired after the |
||
* className value has been added to the element |
||
*/ |
||
addClass : function(element, className, done) { |
||
className = isString(className) ? |
||
className : |
||
isArray(className) ? className.join(' ') : ''; |
||
forEach(element, function (element) { |
||
jqLiteAddClass(element, className); |
||
}); |
||
done && $timeout(done, 0, false); |
||
}, |
||
|
||
/** |
||
* |
||
* @ngdoc function |
||
* @name ng.$animate#removeClass |
||
* @methodOf ng.$animate |
||
* @function |
||
* @description Removes the provided className CSS class value from the provided element. |
||
* Once complete, the done() callback will be fired (if provided). |
||
* @param {jQuery/jqLite element} element the element which will have the className value |
||
* removed from it |
||
* @param {string} className the CSS class which will be removed from the element |
||
* @param {function=} done the callback function (if provided) that will be fired after the |
||
* className value has been removed from the element |
||
*/ |
||
removeClass : function(element, className, done) { |
||
className = isString(className) ? |
||
className : |
||
isArray(className) ? className.join(' ') : ''; |
||
forEach(element, function (element) { |
||
jqLiteRemoveClass(element, className); |
||
}); |
||
done && $timeout(done, 0, false); |
||
}, |
||
|
||
enabled : noop |
||
}; |
||
}]; |
||
}]; |
||
|
||
/** |
||
* ! This is a private undocumented service ! |
||
* |
||
* @name ng.$browser |
||
* @requires $log |
||
* @description |
||
* This object has two goals: |
||
* |
||
* - hide all the global state in the browser caused by the window object |
||
* - abstract away all the browser specific features and inconsistencies |
||
* |
||
* For tests we provide {@link ngMock.$browser mock implementation} of the `$browser` |
||
* service, which can be used for convenient testing of the application without the interaction with |
||
* the real browser apis. |
||
*/ |
||
/** |
||
* @param {object} window The global window object. |
||
* @param {object} document jQuery wrapped document. |
||
* @param {function()} XHR XMLHttpRequest constructor. |
||
* @param {object} $log console.log or an object with the same interface. |
||
* @param {object} $sniffer $sniffer service |
||
*/ |
||
function Browser(window, document, $log, $sniffer) { |
||
var self = this, |
||
rawDocument = document[0], |
||
location = window.location, |
||
history = window.history, |
||
setTimeout = window.setTimeout, |
||
clearTimeout = window.clearTimeout, |
||
pendingDeferIds = {}; |
||
|
||
self.isMock = false; |
||
|
||
var outstandingRequestCount = 0; |
||
var outstandingRequestCallbacks = []; |
||
|
||
// TODO(vojta): remove this temporary api |
||
self.$$completeOutstandingRequest = completeOutstandingRequest; |
||
self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; }; |
||
|
||
/** |
||
* Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks` |
||
* counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed. |
||
*/ |
||
function completeOutstandingRequest(fn) { |
||
try { |
||
fn.apply(null, sliceArgs(arguments, 1)); |
||
} finally { |
||
outstandingRequestCount--; |
||
if (outstandingRequestCount === 0) { |
||
while(outstandingRequestCallbacks.length) { |
||
try { |
||
outstandingRequestCallbacks.pop()(); |
||
} catch (e) { |
||
$log.error(e); |
||
} |
||
} |
||
} |
||
} |
||
} |
||
|
||
/** |
||
* @private |
||
* Note: this method is used only by scenario runner |
||
* TODO(vojta): prefix this method with $$ ? |
||
* @param {function()} callback Function that will be called when no outstanding request |
||
*/ |
||
self.notifyWhenNoOutstandingRequests = function(callback) { |
||
// force browser to execute all pollFns - this is needed so that cookies and other pollers fire |
||
// at some deterministic time in respect to the test runner's actions. Leaving things up to the |
||
// regular poller would result in flaky tests. |
||
forEach(pollFns, function(pollFn){ pollFn(); }); |
||
|
||
if (outstandingRequestCount === 0) { |
||
callback(); |
||
} else { |
||
outstandingRequestCallbacks.push(callback); |
||
} |
||
}; |
||
|
||
////////////////////////////////////////////////////////////// |
||
// Poll Watcher API |
||
////////////////////////////////////////////////////////////// |
||
var pollFns = [], |
||
pollTimeout; |
||
|
||
/** |
||
* @name ng.$browser#addPollFn |
||
* @methodOf ng.$browser |
||
* |
||
* @param {function()} fn Poll function to add |
||
* |
||
* @description |
||
* Adds a function to the list of functions that poller periodically executes, |
||
* and starts polling if not started yet. |
||
* |
||
* @returns {function()} the added function |
||
*/ |
||
self.addPollFn = function(fn) { |
||
if (isUndefined(pollTimeout)) startPoller(100, setTimeout); |
||
pollFns.push(fn); |
||
return fn; |
||
}; |
||
|
||
/** |
||
* @param {number} interval How often should browser call poll functions (ms) |
||
* @param {function()} setTimeout Reference to a real or fake `setTimeout` function. |
||
* |
||
* @description |
||
* Configures the poller to run in the specified intervals, using the specified |
||
* setTimeout fn and kicks it off. |
||
*/ |
||
function startPoller(interval, setTimeout) { |
||
(function check() { |
||
forEach(pollFns, function(pollFn){ pollFn(); }); |
||
pollTimeout = setTimeout(check, interval); |
||
})(); |
||
} |
||
|
||
////////////////////////////////////////////////////////////// |
||
// URL API |
||
////////////////////////////////////////////////////////////// |
||
|
||
var lastBrowserUrl = location.href, |
||
baseElement = document.find('base'), |
||
newLocation = null; |
||
|
||
/** |
||
* @name ng.$browser#url |
||
* @methodOf ng.$browser |
||
* |
||
* @description |
||
* GETTER: |
||
* Without any argument, this method just returns current value of location.href. |
||
* |
||
* SETTER: |
||
* With at least one argument, this method sets url to new value. |
||
* If html5 history api supported, pushState/replaceState is used, otherwise |
||
* location.href/location.replace is used. |
||
* Returns its own instance to allow chaining |
||
* |
||
* NOTE: this api is intended for use only by the $location service. Please use the |
||
* {@link ng.$location $location service} to change url. |
||
* |
||
* @param {string} url New url (when used as setter) |
||
* @param {boolean=} replace Should new url replace current history record ? |
||
*/ |
||
self.url = function(url, replace) { |
||
// Android Browser BFCache causes location, history reference to become stale. |
||
if (location !== window.location) location = window.location; |
||
if (history !== window.history) history = window.history; |
||
|
||
// setter |
||
if (url) { |
||
if (lastBrowserUrl == url) return; |
||
lastBrowserUrl = url; |
||
if ($sniffer.history) { |
||
if (replace) history.replaceState(null, '', url); |
||
else { |
||
history.pushState(null, '', url); |
||
// Crazy Opera Bug: http://my.opera.com/community/forums/topic.dml?id=1185462 |
||
baseElement.attr('href', baseElement.attr('href')); |
||
} |
||
} else { |
||
newLocation = url; |
||
if (replace) { |
||
location.replace(url); |
||
} else { |
||
location.href = url; |
||
} |
||
} |
||
return self; |
||
// getter |
||
} else { |
||
// - newLocation is a workaround for an IE7-9 issue with location.replace and location.href |
||
// methods not updating location.href synchronously. |
||
// - the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172 |
||
return newLocation || location.href.replace(/%27/g,"'"); |
||
} |
||
}; |
||
|
||
var urlChangeListeners = [], |
||
urlChangeInit = false; |
||
|
||
function fireUrlChange() { |
||
newLocation = null; |
||
if (lastBrowserUrl == self.url()) return; |
||
|
||
lastBrowserUrl = self.url(); |
||
forEach(urlChangeListeners, function(listener) { |
||
listener(self.url()); |
||
}); |
||
} |
||
|
||
/** |
||
* @name ng.$browser#onUrlChange |
||
* @methodOf ng.$browser |
||
* @TODO(vojta): refactor to use node's syntax for events |
||
* |
||
* @description |
||
* Register callback function that will be called, when url changes. |
||
* |
||
* It's only called when the url is changed from outside of angular: |
||
* - user types different url into address bar |
||
* - user clicks on history (forward/back) button |
||
* - user clicks on a link |
||
* |
||
* It's not called when url is changed by $browser.url() method |
||
* |
||
* The listener gets called with new url as parameter. |
||
* |
||
* NOTE: this api is intended for use only by the $location service. Please use the |
||
* {@link ng.$location $location service} to monitor url changes in angular apps. |
||
* |
||
* @param {function(string)} listener Listener function to be called when url changes. |
||
* @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous. |
||
*/ |
||
self.onUrlChange = function(callback) { |
||
if (!urlChangeInit) { |
||
// We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera) |
||
// don't fire popstate when user change the address bar and don't fire hashchange when url |
||
// changed by push/replaceState |
||
|
||
// html5 history api - popstate event |
||
if ($sniffer.history) jqLite(window).on('popstate', fireUrlChange); |
||
// hashchange event |
||
if ($sniffer.hashchange) jqLite(window).on('hashchange', fireUrlChange); |
||
// polling |
||
else self.addPollFn(fireUrlChange); |
||
|
||
urlChangeInit = true; |
||
} |
||
|
||
urlChangeListeners.push(callback); |
||
return callback; |
||
}; |
||
|
||
////////////////////////////////////////////////////////////// |
||
// Misc API |
||
////////////////////////////////////////////////////////////// |
||
|
||
/** |
||
* @name ng.$browser#baseHref |
||
* @methodOf ng.$browser |
||
* |
||
* @description |
||
* Returns current <base href> |
||
* (always relative - without domain) |
||
* |
||
* @returns {string=} current <base href> |
||
*/ |
||
self.baseHref = function() { |
||
var href = baseElement.attr('href'); |
||
return href ? href.replace(/^(https?\:)?\/\/[^\/]*/, '') : ''; |
||
}; |
||
|
||
////////////////////////////////////////////////////////////// |
||
// Cookies API |
||
////////////////////////////////////////////////////////////// |
||
var lastCookies = {}; |
||
var lastCookieString = ''; |
||
var cookiePath = self.baseHref(); |
||
|
||
/** |
||
* @name ng.$browser#cookies |
||
* @methodOf ng.$browser |
||
* |
||
* @param {string=} name Cookie name |
||
* @param {string=} value Cookie value |
||
* |
||
* @description |
||
* The cookies method provides a 'private' low level access to browser cookies. |
||
* It is not meant to be used directly, use the $cookie service instead. |
||
* |
||
* The return values vary depending on the arguments that the method was called with as follows: |
||
* |
||
* - cookies() -> hash of all cookies, this is NOT a copy of the internal state, so do not modify |
||
* it |
||
* - cookies(name, value) -> set name to value, if value is undefined delete the cookie |
||
* - cookies(name) -> the same as (name, undefined) == DELETES (no one calls it right now that |
||
* way) |
||
* |
||
* @returns {Object} Hash of all cookies (if called without any parameter) |
||
*/ |
||
self.cookies = function(name, value) { |
||
/* global escape: false, unescape: false */ |
||
var cookieLength, cookieArray, cookie, i, index; |
||
|
||
if (name) { |
||
if (value === undefined) { |
||
rawDocument.cookie = escape(name) + "=;path=" + cookiePath + |
||
";expires=Thu, 01 Jan 1970 00:00:00 GMT"; |
||
} else { |
||
if (isString(value)) { |
||
cookieLength = (rawDocument.cookie = escape(name) + '=' + escape(value) + |
||
';path=' + cookiePath).length + 1; |
||
|
||
// per http://www.ietf.org/rfc/rfc2109.txt browser must allow at minimum: |
||
// - 300 cookies |
||
// - 20 cookies per unique domain |
||
// - 4096 bytes per cookie |
||
if (cookieLength > 4096) { |
||
$log.warn("Cookie '"+ name + |
||
"' possibly not set or overflowed because it was too large ("+ |
||
cookieLength + " > 4096 bytes)!"); |
||
} |
||
} |
||
} |
||
} else { |
||
if (rawDocument.cookie !== lastCookieString) { |
||
lastCookieString = rawDocument.cookie; |
||
cookieArray = lastCookieString.split("; "); |
||
lastCookies = {}; |
||
|
||
for (i = 0; i < cookieArray.length; i++) { |
||
cookie = cookieArray[i]; |
||
index = cookie.indexOf('='); |
||
if (index > 0) { //ignore nameless cookies |
||
name = unescape(cookie.substring(0, index)); |
||
// the first value that is seen for a cookie is the most |
||
// specific one. values for the same cookie name that |
||
// follow are for less specific paths. |
||
if (lastCookies[name] === undefined) { |
||
lastCookies[name] = unescape(cookie.substring(index + 1)); |
||
} |
||
} |
||
} |
||
} |
||
return lastCookies; |
||
} |
||
}; |
||
|
||
|
||
/** |
||
* @name ng.$browser#defer |
||
* @methodOf ng.$browser |
||
* @param {function()} fn A function, who's execution should be deferred. |
||
* @param {number=} [delay=0] of milliseconds to defer the function execution. |
||
* @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`. |
||
* |
||
* @description |
||
* Executes a fn asynchronously via `setTimeout(fn, delay)`. |
||
* |
||
* Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using |
||
* `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed |
||
* via `$browser.defer.flush()`. |
||
* |
||
*/ |
||
self.defer = function(fn, delay) { |
||
var timeoutId; |
||
outstandingRequestCount++; |
||
timeoutId = setTimeout(function() { |
||
delete pendingDeferIds[timeoutId]; |
||
completeOutstandingRequest(fn); |
||
}, delay || 0); |
||
pendingDeferIds[timeoutId] = true; |
||
return timeoutId; |
||
}; |
||
|
||
|
||
/** |
||
* @name ng.$browser#defer.cancel |
||
* @methodOf ng.$browser.defer |
||
* |
||
* @description |
||
* Cancels a deferred task identified with `deferId`. |
||
* |
||
* @param {*} deferId Token returned by the `$browser.defer` function. |
||
* @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully |
||
* canceled. |
||
*/ |
||
self.defer.cancel = function(deferId) { |
||
if (pendingDeferIds[deferId]) { |
||
delete pendingDeferIds[deferId]; |
||
clearTimeout(deferId); |
||
completeOutstandingRequest(noop); |
||
return true; |
||
} |
||
return false; |
||
}; |
||
|
||
} |
||
|
||
function $BrowserProvider(){ |
||
this.$get = ['$window', '$log', '$sniffer', '$document', |
||
function( $window, $log, $sniffer, $document){ |
||
return new Browser($window, $document, $log, $sniffer); |
||
}]; |
||
} |
||
|
||
/** |
||
* @ngdoc object |
||
* @name ng.$cacheFactory |
||
* |
||
* @description |
||
* Factory that constructs cache objects and gives access to them. |
||
* |
||
* <pre> |
||
* |
||
* var cache = $cacheFactory('cacheId'); |
||
* expect($cacheFactory.get('cacheId')).toBe(cache); |
||
* expect($cacheFactory.get('noSuchCacheId')).not.toBeDefined(); |
||
* |
||
* cache.put("key", "value"); |
||
* cache.put("another key", "another value"); |
||
* |
||
* // We've specified no options on creation |
||
* expect(cache.info()).toEqual({id: 'cacheId', size: 2}); |
||
* |
||
* </pre> |
||
* |
||
* |
||
* @param {string} cacheId Name or id of the newly created cache. |
||
* @param {object=} options Options object that specifies the cache behavior. Properties: |
||
* |
||
* - `{number=}` `capacity` — turns the cache into LRU cache. |
||
* |
||
* @returns {object} Newly created cache object with the following set of methods: |
||
* |
||
* - `{object}` `info()` — Returns id, size, and options of cache. |
||
* - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns |
||
* it. |
||
* - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss. |
||
* - `{void}` `remove({string} key)` — Removes a key-value pair from the cache. |
||
* - `{void}` `removeAll()` — Removes all cached values. |
||
* - `{void}` `destroy()` — Removes references to this cache from $cacheFactory. |
||
* |
||
*/ |
||
function $CacheFactoryProvider() { |
||
|
||
this.$get = function() { |
||
var caches = {}; |
||
|
||
function cacheFactory(cacheId, options) { |
||
if (cacheId in caches) { |
||
throw minErr('$cacheFactory')('iid', "CacheId '{0}' is already taken!", cacheId); |
||
} |
||
|
||
var size = 0, |
||
stats = extend({}, options, {id: cacheId}), |
||
data = {}, |
||
capacity = (options && options.capacity) || Number.MAX_VALUE, |
||
lruHash = {}, |
||
freshEnd = null, |
||
staleEnd = null; |
||
|
||
return caches[cacheId] = { |
||
|
||
put: function(key, value) { |
||
var lruEntry = lruHash[key] || (lruHash[key] = {key: key}); |
||
|
||
refresh(lruEntry); |
||
|
||
if (isUndefined(value)) return; |
||
if (!(key in data)) size++; |
||
data[key] = value; |
||
|
||
if (size > capacity) { |
||
this.remove(staleEnd.key); |
||
} |
||
|
||
return value; |
||
}, |
||
|
||
|
||
get: function(key) { |
||
var lruEntry = lruHash[key]; |
||
|
||
if (!lruEntry) return; |
||
|
||
refresh(lruEntry); |
||
|
||
return data[key]; |
||
}, |
||
|
||
|
||
remove: function(key) { |
||
var lruEntry = lruHash[key]; |
||
|
||
if (!lruEntry) return; |
||
|
||
if (lruEntry == freshEnd) freshEnd = lruEntry.p; |
||
if (lruEntry == staleEnd) staleEnd = lruEntry.n; |
||
link(lruEntry.n,lruEntry.p); |
||
|
||
delete lruHash[key]; |
||
delete data[key]; |
||
size--; |
||
}, |
||
|
||
|
||
removeAll: function() { |
||
data = {}; |
||
size = 0; |
||
lruHash = {}; |
||
freshEnd = staleEnd = null; |
||
}, |
||
|
||
|
||
destroy: function() { |
||
data = null; |
||
stats = null; |
||
lruHash = null; |
||
delete caches[cacheId]; |
||
}, |
||
|
||
|
||
info: function() { |
||
return extend({}, stats, {size: size}); |
||
} |
||
}; |
||
|
||
|
||
/** |
||
* makes the `entry` the freshEnd of the LRU linked list |
||
*/ |
||
function refresh(entry) { |
||
if (entry != freshEnd) { |
||
if (!staleEnd) { |
||
staleEnd = entry; |
||
} else if (staleEnd == entry) { |
||
staleEnd = entry.n; |
||
} |
||
|
||
link(entry.n, entry.p); |
||
link(entry, freshEnd); |
||
freshEnd = entry; |
||
freshEnd.n = null; |
||
} |
||
} |
||
|
||
|
||
/** |
||
* bidirectionally links two entries of the LRU linked list |
||
*/ |
||
function link(nextEntry, prevEntry) { |
||
if (nextEntry != prevEntry) { |
||
if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify |
||
if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify |
||
} |
||
} |
||
} |
||
|
||
|
||
/** |
||
* @ngdoc method |
||
* @name ng.$cacheFactory#info |
||
* @methodOf ng.$cacheFactory |
||
* |
||
* @description |
||
* Get information about all the of the caches that have been created |
||
* |
||
* @returns {Object} - key-value map of `cacheId` to the result of calling `cache#info` |
||
*/ |
||
cacheFactory.info = function() { |
||
var info = {}; |
||
forEach(caches, function(cache, cacheId) { |
||
info[cacheId] = cache.info(); |
||
}); |
||
return info; |
||
}; |
||
|
||
|
||
/** |
||
* @ngdoc method |
||
* @name ng.$cacheFactory#get |
||
* @methodOf ng.$cacheFactory |
||
* |
||
* @description |
||
* Get access to a cache object by the `cacheId` used when it was created. |
||
* |
||
* @param {string} cacheId Name or id of a cache to access. |
||
* @returns {object} Cache object identified by the cacheId or undefined if no such cache. |
||
*/ |
||
cacheFactory.get = function(cacheId) { |
||
return caches[cacheId]; |
||
}; |
||
|
||
|
||
return cacheFactory; |
||
}; |
||
} |
||
|
||
/** |
||
* @ngdoc object |
||
* @name ng.$templateCache |
||
* |
||
* @description |
||
* The first time a template is used, it is loaded in the template cache for quick retrieval. You |
||
* can load templates directly into the cache in a `script` tag, or by consuming the |
||
* `$templateCache` service directly. |
||
* |
||
* Adding via the `script` tag: |
||
* <pre> |
||
* <html ng-app> |
||
* <head> |
||
* <script type="text/ng-template" id="templateId.html"> |
||
* This is the content of the template |
||
* </script> |
||
* </head> |
||
* ... |
||
* </html> |
||
* </pre> |
||
* |
||
* **Note:** the `script` tag containing the template does not need to be included in the `head` of |
||
* the document, but it must be below the `ng-app` definition. |
||
* |
||
* Adding via the $templateCache service: |
||
* |
||
* <pre> |
||
* var myApp = angular.module('myApp', []); |
||
* myApp.run(function($templateCache) { |
||
* $templateCache.put('templateId.html', 'This is the content of the template'); |
||
* }); |
||
* </pre> |
||
* |
||
* To retrieve the template later, simply use it in your HTML: |
||
* <pre> |
||
* <div ng-include=" 'templateId.html' "></div> |
||
* </pre> |
||
* |
||
* or get it via Javascript: |
||
* <pre> |
||
* $templateCache.get('templateId.html') |
||
* </pre> |
||
* |
||
* See {@link ng.$cacheFactory $cacheFactory}. |
||
* |
||
*/ |
||
function $TemplateCacheProvider() { |
||
this.$get = ['$cacheFactory', function($cacheFactory) { |
||
return $cacheFactory('templates'); |
||
}]; |
||
} |
||
|
||
/* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE! |
||
* |
||
* DOM-related variables: |
||
* |
||
* - "node" - DOM Node |
||
* - "element" - DOM Element or Node |
||
* - "$node" or "$element" - jqLite-wrapped node or element |
||
* |
||
* |
||
* Compiler related stuff: |
||
* |
||
* - "linkFn" - linking fn of a single directive |
||
* - "nodeLinkFn" - function that aggregates all linking fns for a particular node |
||
* - "childLinkFn" - function that aggregates all linking fns for child nodes of a particular node |
||
* - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList) |
||
*/ |
||
|
||
|
||
/** |
||
* @ngdoc function |
||
* @name ng.$compile |
||
* @function |
||
* |
||
* @description |
||
* Compiles an HTML string or DOM into a template and produces a template function, which |
||
* can then be used to link {@link ng.$rootScope.Scope `scope`} and the template together. |
||
* |
||
* The compilation is a process of walking the DOM tree and matching DOM elements to |
||
* {@link ng.$compileProvider#methods_directive directives}. |
||
* |
||
* <div class="alert alert-warning"> |
||
* **Note:** This document is an in-depth reference of all directive options. |
||
* For a gentle introduction to directives with examples of common use cases, |
||
* see the {@link guide/directive directive guide}. |
||
* </div> |
||
* |
||
* ## Comprehensive Directive API |
||
* |
||
* There are many different options for a directive. |
||
* |
||
* The difference resides in the return value of the factory function. |
||
* You can either return a "Directive Definition Object" (see below) that defines the directive properties, |
||
* or just the `postLink` function (all other properties will have the default values). |
||
* |
||
* <div class="alert alert-success"> |
||
* **Best Practice:** It's recommended to use the "directive definition object" form. |
||
* </div> |
||
* |
||
* Here's an example directive declared with a Directive Definition Object: |
||
* |
||
* <pre> |
||
* var myModule = angular.module(...); |
||
* |
||
* myModule.directive('directiveName', function factory(injectables) { |
||
* var directiveDefinitionObject = { |
||
* priority: 0, |
||
* template: '<div></div>', // or // function(tElement, tAttrs) { ... }, |
||
* // or |
||
* // templateUrl: 'directive.html', // or // function(tElement, tAttrs) { ... }, |
||
* replace: false, |
||
* transclude: false, |
||
* restrict: 'A', |
||
* scope: false, |
||
* controller: function($scope, $element, $attrs, $transclude, otherInjectables) { ... }, |
||
* require: 'siblingDirectiveName', // or // ['^parentDirectiveName', '?optionalDirectiveName', '?^optionalParent'], |
||
* compile: function compile(tElement, tAttrs, transclude) { |
||
* return { |
||
* pre: function preLink(scope, iElement, iAttrs, controller) { ... }, |
||
* post: function postLink(scope, iElement, iAttrs, controller) { ... } |
||
* } |
||
* // or |
||
* // return function postLink( ... ) { ... } |
||
* }, |
||
* // or |
||
* // link: { |
||
* // pre: function preLink(scope, iElement, iAttrs, controller) { ... }, |
||
* // post: function postLink(scope, iElement, iAttrs, controller) { ... } |
||
* // } |
||
* // or |
||
* // link: function postLink( ... ) { ... } |
||
* }; |
||
* return directiveDefinitionObject; |
||
* }); |
||
* </pre> |
||
* |
||
* <div class="alert alert-warning"> |
||
* **Note:** Any unspecified options will use the default value. You can see the default values below. |
||
* </div> |
||
* |
||
* Therefore the above can be simplified as: |
||
* |
||
* <pre> |
||
* var myModule = angular.module(...); |
||
* |
||
* myModule.directive('directiveName', function factory(injectables) { |
||
* var directiveDefinitionObject = { |
||
* link: function postLink(scope, iElement, iAttrs) { ... } |
||
* }; |
||
* return directiveDefinitionObject; |
||
* // or |
||
* // return function postLink(scope, iElement, iAttrs) { ... } |
||
* }); |
||
* </pre> |
||
* |
||
* |
||
* |
||
* ### Directive Definition Object |
||
* |
||
* The directive definition object provides instructions to the {@link api/ng.$compile |
||
* compiler}. The attributes are: |
||
* |
||
* #### `priority` |
||
* When there are multiple directives defined on a single DOM element, sometimes it |
||
* is necessary to specify the order in which the directives are applied. The `priority` is used |
||
* to sort the directives before their `compile` functions get called. Priority is defined as a |
||
* number. Directives with greater numerical `priority` are compiled first. Pre-link functions |
||
* are also run in priority order, but post-link functions are run in reverse order. The order |
||
* of directives with the same priority is undefined. The default priority is `0`. |
||
* |
||
* #### `terminal` |
||
* If set to true then the current `priority` will be the last set of directives |
||
* which will execute (any directives at the current priority will still execute |
||
* as the order of execution on same `priority` is undefined). |
||
* |
||
* #### `scope` |
||
* **If set to `true`,** then a new scope will be created for this directive. If multiple directives on the |
||
* same element request a new scope, only one new scope is created. The new scope rule does not |
||
* apply for the root of the template since the root of the template always gets a new scope. |
||
* |
||
* **If set to `{}` (object hash),** then a new "isolate" scope is created. The 'isolate' scope differs from |
||
* normal scope in that it does not prototypically inherit from the parent scope. This is useful |
||
* when creating reusable components, which should not accidentally read or modify data in the |
||
* parent scope. |
||
* |
||
* The 'isolate' scope takes an object hash which defines a set of local scope properties |
||
* derived from the parent scope. These local properties are useful for aliasing values for |
||
* templates. Locals definition is a hash of local scope property to its source: |
||
* |
||
* * `@` or `@attr` - bind a local scope property to the value of DOM attribute. The result is |
||
* always a string since DOM attributes are strings. If no `attr` name is specified then the |
||
* attribute name is assumed to be the same as the local name. |
||
* Given `<widget my-attr="hello {{name}}">` and widget definition |
||
* of `scope: { localName:'@myAttr' }`, then widget scope property `localName` will reflect |
||
* the interpolated value of `hello {{name}}`. As the `name` attribute changes so will the |
||
* `localName` property on the widget scope. The `name` is read from the parent scope (not |
||
* component scope). |
||
* |
||
* * `=` or `=attr` - set up bi-directional binding between a local scope property and the |
||
* parent scope property of name defined via the value of the `attr` attribute. If no `attr` |
||
* name is specified then the attribute name is assumed to be the same as the local name. |
||
* Given `<widget my-attr="parentModel">` and widget definition of |
||
* `scope: { localModel:'=myAttr' }`, then widget scope property `localModel` will reflect the |
||
* value of `parentModel` on the parent scope. Any changes to `parentModel` will be reflected |
||
* in `localModel` and any changes in `localModel` will reflect in `parentModel`. If the parent |
||
* scope property doesn't exist, it will throw a NON_ASSIGNABLE_MODEL_EXPRESSION exception. You |
||
* can avoid this behavior using `=?` or `=?attr` in order to flag the property as optional. |
||
* |
||
* * `&` or `&attr` - provides a way to execute an expression in the context of the parent scope. |
||
* If no `attr` name is specified then the attribute name is assumed to be the same as the |
||
* local name. Given `<widget my-attr="count = count + value">` and widget definition of |
||
* `scope: { localFn:'&myAttr' }`, then isolate scope property `localFn` will point to |
||
* a function wrapper for the `count = count + value` expression. Often it's desirable to |
||
* pass data from the isolated scope via an expression and to the parent scope, this can be |
||
* done by passing a map of local variable names and values into the expression wrapper fn. |
||
* For example, if the expression is `increment(amount)` then we can specify the amount value |
||
* by calling the `localFn` as `localFn({amount: 22})`. |
||
* |
||
* |
||
* |
||
* #### `controller` |
||
* Controller constructor function. The controller is instantiated before the |
||
* pre-linking phase and it is shared with other directives (see |
||
* `require` attribute). This allows the directives to communicate with each other and augment |
||
* each other's behavior. The controller is injectable (and supports bracket notation) with the following locals: |
||
* |
||
* * `$scope` - Current scope associated with the element |
||
* * `$element` - Current element |
||
* * `$attrs` - Current attributes object for the element |
||
* * `$transclude` - A transclude linking function pre-bound to the correct transclusion scope. |
||
* The scope can be overridden by an optional first argument. |
||
* `function([scope], cloneLinkingFn)`. |
||
* |
||
* |
||
* #### `require` |
||
* Require another directive and inject its controller as the fourth argument to the linking function. The |
||
* `require` takes a string name (or array of strings) of the directive(s) to pass in. If an array is used, the |
||
* injected argument will be an array in corresponding order. If no such directive can be |
||
* found, or if the directive does not have a controller, then an error is raised. The name can be prefixed with: |
||
* |
||
* * (no prefix) - Locate the required controller on the current element. Throw an error if not found. |
||
* * `?` - Attempt to locate the required controller or pass `null` to the `link` fn if not found. |
||
* * `^` - Locate the required controller by searching the element's parents. Throw an error if not found. |
||
* * `?^` - Attempt to locate the required controller by searching the element's parents or pass `null` to the |
||
* `link` fn if not found. |
||
* |
||
* |
||
* #### `controllerAs` |
||
* Controller alias at the directive scope. An alias for the controller so it |
||
* can be referenced at the directive template. The directive needs to define a scope for this |
||
* configuration to be used. Useful in the case when directive is used as component. |
||
* |
||
* |
||
* #### `restrict` |
||
* String of subset of `EACM` which restricts the directive to a specific directive |
||
* declaration style. If omitted, the default (attributes only) is used. |
||
* |
||
* * `E` - Element name: `<my-directive></my-directive>` |
||
* * `A` - Attribute (default): `<div my-directive="exp"></div>` |
||
* * `C` - Class: `<div class="my-directive: exp;"></div>` |
||
* * `M` - Comment: `<!-- directive: my-directive exp -->` |
||
* |
||
* |
||
* #### `template` |
||
* replace the current element with the contents of the HTML. The replacement process |
||
* migrates all of the attributes / classes from the old element to the new one. See the |
||
* {@link guide/directive#creating-custom-directives_creating-directives_template-expanding-directive |
||
* Directives Guide} for an example. |
||
* |
||
* You can specify `template` as a string representing the template or as a function which takes |
||
* two arguments `tElement` and `tAttrs` (described in the `compile` function api below) and |
||
* returns a string value representing the template. |
||
* |
||
* |
||
* #### `templateUrl` |
||
* Same as `template` but the template is loaded from the specified URL. Because |
||
* the template loading is asynchronous the compilation/linking is suspended until the template |
||
* is loaded. |
||
* |
||
* You can specify `templateUrl` as a string representing the URL or as a function which takes two |
||
* arguments `tElement` and `tAttrs` (described in the `compile` function api below) and returns |
||
* a string value representing the url. In either case, the template URL is passed through {@link |
||
* api/ng.$sce#methods_getTrustedResourceUrl $sce.getTrustedResourceUrl}. |
||
* |
||
* |
||
* #### `replace` |
||
* specify where the template should be inserted. Defaults to `false`. |
||
* |
||
* * `true` - the template will replace the current element. |
||
* * `false` - the template will replace the contents of the current element. |
||
* |
||
* |
||
* #### `transclude` |
||
* compile the content of the element and make it available to the directive. |
||
* Typically used with {@link api/ng.directive:ngTransclude |
||
* ngTransclude}. The advantage of transclusion is that the linking function receives a |
||
* transclusion function which is pre-bound to the correct scope. In a typical setup the widget |
||
* creates an `isolate` scope, but the transclusion is not a child, but a sibling of the `isolate` |
||
* scope. This makes it possible for the widget to have private state, and the transclusion to |
||
* be bound to the parent (pre-`isolate`) scope. |
||
* |
||
* * `true` - transclude the content of the directive. |
||
* * `'element'` - transclude the whole element including any directives defined at lower priority. |
||
* |
||
* |
||
* #### `compile` |
||
* |
||
* <pre> |
||
* function compile(tElement, tAttrs, transclude) { ... } |
||
* </pre> |
||
* |
||
* The compile function deals with transforming the template DOM. Since most directives do not do |
||
* template transformation, it is not used often. Examples that require compile functions are |
||
* directives that transform template DOM, such as {@link |
||
* api/ng.directive:ngRepeat ngRepeat}, or load the contents |
||
* asynchronously, such as {@link api/ngRoute.directive:ngView ngView}. The |
||
* compile function takes the following arguments. |
||
* |
||
* * `tElement` - template element - The element where the directive has been declared. It is |
||
* safe to do template transformation on the element and child elements only. |
||
* |
||
* * `tAttrs` - template attributes - Normalized list of attributes declared on this element shared |
||
* between all directive compile functions. |
||
* |
||
* * `transclude` - [*DEPRECATED*!] A transclude linking function: `function(scope, cloneLinkingFn)` |
||
* |
||
* <div class="alert alert-warning"> |
||
* **Note:** The template instance and the link instance may be different objects if the template has |
||
* been cloned. For this reason it is **not** safe to do anything other than DOM transformations that |
||
* apply to all cloned DOM nodes within the compile function. Specifically, DOM listener registration |
||
* should be done in a linking function rather than in a compile function. |
||
* </div> |
||
* |
||
* <div class="alert alert-error"> |
||
* **Note:** The `transclude` function that is passed to the compile function is deprecated, as it |
||
* e.g. does not know about the right outer scope. Please use the transclude function that is passed |
||
* to the link function instead. |
||
* </div> |
||
|
||
* A compile function can have a return value which can be either a function or an object. |
||
* |
||
* * returning a (post-link) function - is equivalent to registering the linking function via the |
||
* `link` property of the config object when the compile function is empty. |
||
* |
||
* * returning an object with function(s) registered via `pre` and `post` properties - allows you to |
||
* control when a linking function should be called during the linking phase. See info about |
||
* pre-linking and post-linking functions below. |
||
* |
||
* |
||
* #### `link` |
||
* This property is used only if the `compile` property is not defined. |
||
* |
||
* <pre> |
||
* function link(scope, iElement, iAttrs, controller, transcludeFn) { ... } |
||
* </pre> |
||
* |
||
* The link function is responsible for registering DOM listeners as well as updating the DOM. It is |
||
* executed after the template has been cloned. This is where most of the directive logic will be |
||
* put. |
||
* |
||
* * `scope` - {@link api/ng.$rootScope.Scope Scope} - The scope to be used by the |
||
* directive for registering {@link api/ng.$rootScope.Scope#methods_$watch watches}. |
||
* |
||
* * `iElement` - instance element - The element where the directive is to be used. It is safe to |
||
* manipulate the children of the element only in `postLink` function since the children have |
||
* already been linked. |
||
* |
||
* * `iAttrs` - instance attributes - Normalized list of attributes declared on this element shared |
||
* between all directive linking functions. |
||
* |
||
* * `controller` - a controller instance - A controller instance if at least one directive on the |
||
* element defines a controller. The controller is shared among all the directives, which allows |
||
* the directives to use the controllers as a communication channel. |
||
* |
||
* * `transcludeFn` - A transclude linking function pre-bound to the correct transclusion scope. |
||
* The scope can be overridden by an optional first argument. This is the same as the `$transclude` |
||
* parameter of directive controllers. |
||
* `function([scope], cloneLinkingFn)`. |
||
* |
||
* |
||
* #### Pre-linking function |
||
* |
||
* Executed before the child elements are linked. Not safe to do DOM transformation since the |
||
* compiler linking function will fail to locate the correct elements for linking. |
||
* |
||
* #### Post-linking function |
||
* |
||
* Executed after the child elements are linked. It is safe to do DOM transformation in the post-linking function. |
||
* |
||
* <a name="Attributes"></a> |
||
* ### Attributes |
||
* |
||
* The {@link api/ng.$compile.directive.Attributes Attributes} object - passed as a parameter in the |
||
* `link()` or `compile()` functions. It has a variety of uses. |
||
* |
||
* accessing *Normalized attribute names:* |
||
* Directives like 'ngBind' can be expressed in many ways: 'ng:bind', `data-ng-bind`, or 'x-ng-bind'. |
||
* the attributes object allows for normalized access to |
||
* the attributes. |
||
* |
||
* * *Directive inter-communication:* All directives share the same instance of the attributes |
||
* object which allows the directives to use the attributes object as inter directive |
||
* communication. |
||
* |
||
* * *Supports interpolation:* Interpolation attributes are assigned to the attribute object |
||
* allowing other directives to read the interpolated value. |
||
* |
||
* * *Observing interpolated attributes:* Use `$observe` to observe the value changes of attributes |
||
* that contain interpolation (e.g. `src="{{bar}}"`). Not only is this very efficient but it's also |
||
* the only way to easily get the actual value because during the linking phase the interpolation |
||
* hasn't been evaluated yet and so the value is at this time set to `undefined`. |
||
* |
||
* <pre> |
||
* function linkingFn(scope, elm, attrs, ctrl) { |
||
* // get the attribute value |
||
* console.log(attrs.ngModel); |
||
* |
||
* // change the attribute |
||
* attrs.$set('ngModel', 'new value'); |
||
* |
||
* // observe changes to interpolated attribute |
||
* attrs.$observe('ngModel', function(value) { |
||
* console.log('ngModel has changed value to ' + value); |
||
* }); |
||
* } |
||
* </pre> |
||
* |
||
* Below is an example using `$compileProvider`. |
||
* |
||
* <div class="alert alert-warning"> |
||
* **Note**: Typically directives are registered with `module.directive`. The example below is |
||
* to illustrate how `$compile` works. |
||
* </div> |
||
* |
||
<doc:example module="compile"> |
||
<doc:source> |
||
<script> |
||
angular.module('compile', [], function($compileProvider) { |
||
// configure new 'compile' directive by passing a directive |
||
// factory function. The factory function injects the '$compile' |
||
$compileProvider.directive('compile', function($compile) { |
||
// directive factory creates a link function |
||
return function(scope, element, attrs) { |
||
scope.$watch( |
||
function(scope) { |
||
// watch the 'compile' expression for changes |
||
return scope.$eval(attrs.compile); |
||
}, |
||
function(value) { |
||
// when the 'compile' expression changes |
||
// assign it into the current DOM |
||
element.html(value); |
||
|
||
// compile the new DOM and link it to the current |
||
// scope. |
||
// NOTE: we only compile .childNodes so that |
||
// we don't get into infinite loop compiling ourselves |
||
$compile(element.contents())(scope); |
||
} |
||
); |
||
}; |
||
}) |
||
}); |
||
|
||
function Ctrl($scope) { |
||
$scope.name = 'Angular'; |
||
$scope.html = 'Hello {{name}}'; |
||
} |
||
</script> |
||
<div ng-controller="Ctrl"> |
||
<input ng-model="name"> <br> |
||
<textarea ng-model="html"></textarea> <br> |
||
<div compile="html"></div> |
||
</div> |
||
</doc:source> |
||
<doc:scenario> |
||
it('should auto compile', function() { |
||
expect(element('div[compile]').text()).toBe('Hello Angular'); |
||
input('html').enter('{{name}}!'); |
||
expect(element('div[compile]').text()).toBe('Angular!'); |
||
}); |
||
</doc:scenario> |
||
</doc:example> |
||
|
||
* |
||
* |
||
* @param {string|DOMElement} element Element or HTML string to compile into a template function. |
||
* @param {function(angular.Scope[, cloneAttachFn]} transclude function available to directives. |
||
* @param {number} maxPriority only apply directives lower then given priority (Only effects the |
||
* root element(s), not their children) |
||
* @returns {function(scope[, cloneAttachFn])} a link function which is used to bind template |
||
* (a DOM element/tree) to a scope. Where: |
||
* |
||
* * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to. |
||
* * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the |
||
* `template` and call the `cloneAttachFn` function allowing the caller to attach the |
||
* cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is |
||
* called as: <br> `cloneAttachFn(clonedElement, scope)` where: |
||
* |
||
* * `clonedElement` - is a clone of the original `element` passed into the compiler. |
||
* * `scope` - is the current scope with which the linking function is working with. |
||
* |
||
* Calling the linking function returns the element of the template. It is either the original |
||
* element passed in, or the clone of the element if the `cloneAttachFn` is provided. |
||
* |
||
* After linking the view is not updated until after a call to $digest which typically is done by |
||
* Angular automatically. |
||
* |
||
* If you need access to the bound view, there are two ways to do it: |
||
* |
||
* - If you are not asking the linking function to clone the template, create the DOM element(s) |
||
* before you send them to the compiler and keep this reference around. |
||
* <pre> |
||
* var element = $compile('<p>{{total}}</p>')(scope); |
||
* </pre> |
||
* |
||
* - if on the other hand, you need the element to be cloned, the view reference from the original |
||
* example would not point to the clone, but rather to the original template that was cloned. In |
||
* this case, you can access the clone via the cloneAttachFn: |
||
* <pre> |
||
* var templateElement = angular.element('<p>{{total}}</p>'), |
||
* scope = ....; |
||
* |
||
* var clonedElement = $compile(templateElement)(scope, function(clonedElement, scope) { |
||
* //attach the clone to DOM document at the right place |
||
* }); |
||
* |
||
* //now we have reference to the cloned DOM via `clonedElement` |
||
* </pre> |
||
* |
||
* |
||
* For information on how the compiler works, see the |
||
* {@link guide/compiler Angular HTML Compiler} section of the Developer Guide. |
||
*/ |
||
|
||
var $compileMinErr = minErr('$compile'); |
||
|
||
/** |
||
* @ngdoc service |
||
* @name ng.$compileProvider |
||
* @function |
||
* |
||
* @description |
||
*/ |
||
$CompileProvider.$inject = ['$provide', '$$sanitizeUriProvider']; |
||
function $CompileProvider($provide, $$sanitizeUriProvider) { |
||
var hasDirectives = {}, |
||
Suffix = 'Directive', |
||
COMMENT_DIRECTIVE_REGEXP = /^\s*directive\:\s*([\d\w\-_]+)\s+(.*)$/, |
||
CLASS_DIRECTIVE_REGEXP = /(([\d\w\-_]+)(?:\:([^;]+))?;?)/; |
||
|
||
// Ref: http://developers.whatwg.org/webappapis.html#event-handler-idl-attributes |
||
// The assumption is that future DOM event attribute names will begin with |
||
// 'on' and be composed of only English letters. |
||
var EVENT_HANDLER_ATTR_REGEXP = /^(on[a-z]+|formaction)$/; |
||
|
||
/** |
||
* @ngdoc function |
||
* @name ng.$compileProvider#directive |
||
* @methodOf ng.$compileProvider |
||
* @function |
||
* |
||
* @description |
||
* Register a new directive with the compiler. |
||
* |
||
* @param {string|Object} name Name of the directive in camel-case (i.e. <code>ngBind</code> which |
||
* will match as <code>ng-bind</code>), or an object map of directives where the keys are the |
||
* names and the values are the factories. |
||
* @param {function|Array} directiveFactory An injectable directive factory function. See |
||
* {@link guide/directive} for more info. |
||
* @returns {ng.$compileProvider} Self for chaining. |
||
*/ |
||
this.directive = function registerDirective(name, directiveFactory) { |
||
assertNotHasOwnProperty(name, 'directive'); |
||
if (isString(name)) { |
||
assertArg(directiveFactory, 'directiveFactory'); |
||
if (!hasDirectives.hasOwnProperty(name)) { |
||
hasDirectives[name] = []; |
||
$provide.factory(name + Suffix, ['$injector', '$exceptionHandler', |
||
function($injector, $exceptionHandler) { |
||
var directives = []; |
||
forEach(hasDirectives[name], function(directiveFactory, index) { |
||
try { |
||
var directive = $injector.invoke(directiveFactory); |
||
if (isFunction(directive)) { |
||
directive = { compile: valueFn(directive) }; |
||
} else if (!directive.compile && directive.link) { |
||
directive.compile = valueFn(directive.link); |
||
} |
||
directive.priority = directive.priority || 0; |
||
directive.index = index; |
||
directive.name = directive.name || name; |
||
directive.require = directive.require || (directive.controller && directive.name); |
||
directive.restrict = directive.restrict || 'A'; |
||
directives.push(directive); |
||
} catch (e) { |
||
$exceptionHandler(e); |
||
} |
||
}); |
||
return directives; |
||
}]); |
||
} |
||
hasDirectives[name].push(directiveFactory); |
||
} else { |
||
forEach(name, reverseParams(registerDirective)); |
||
} |
||
return this; |
||
}; |
||
|
||
|
||
/** |
||
* @ngdoc function |
||
* @name ng.$compileProvider#aHrefSanitizationWhitelist |
||
* @methodOf ng.$compileProvider |
||
* @function |
||
* |
||
* @description |
||
* Retrieves or overrides the default regular expression that is used for whitelisting of safe |
||
* urls during a[href] sanitization. |
||
* |
||
* The sanitization is a security measure aimed at prevent XSS attacks via html links. |
||
* |
||
* Any url about to be assigned to a[href] via data-binding is first normalized and turned into |
||
* an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist` |
||
* regular expression. If a match is found, the original url is written into the dom. Otherwise, |
||
* the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM. |
||
* |
||
* @param {RegExp=} regexp New regexp to whitelist urls with. |
||
* @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for |
||
* chaining otherwise. |
||
*/ |
||
this.aHrefSanitizationWhitelist = function(regexp) { |
||
if (isDefined(regexp)) { |
||
$$sanitizeUriProvider.aHrefSanitizationWhitelist(regexp); |
||
return this; |
||
} else { |
||
return $$sanitizeUriProvider.aHrefSanitizationWhitelist(); |
||
} |
||
}; |
||
|
||
|
||
/** |
||
* @ngdoc function |
||
* @name ng.$compileProvider#imgSrcSanitizationWhitelist |
||
* @methodOf ng.$compileProvider |
||
* @function |
||
* |
||
* @description |
||
* Retrieves or overrides the default regular expression that is used for whitelisting of safe |
||
* urls during img[src] sanitization. |
||
* |
||
* The sanitization is a security measure aimed at prevent XSS attacks via html links. |
||
* |
||
* Any url about to be assigned to img[src] via data-binding is first normalized and turned into |
||
* an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist` |
||
* regular expression. If a match is found, the original url is written into the dom. Otherwise, |
||
* the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM. |
||
* |
||
* @param {RegExp=} regexp New regexp to whitelist urls with. |
||
* @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for |
||
* chaining otherwise. |
||
*/ |
||
this.imgSrcSanitizationWhitelist = function(regexp) { |
||
if (isDefined(regexp)) { |
||
$$sanitizeUriProvider.imgSrcSanitizationWhitelist(regexp); |
||
return this; |
||
} else { |
||
return $$sanitizeUriProvider.imgSrcSanitizationWhitelist(); |
||
} |
||
}; |
||
|
||
this.$get = [ |
||
'$injector', '$interpolate', '$exceptionHandler', '$http', '$templateCache', '$parse', |
||
'$controller', '$rootScope', '$document', '$sce', '$animate', '$$sanitizeUri', |
||
function($injector, $interpolate, $exceptionHandler, $http, $templateCache, $parse, |
||
$controller, $rootScope, $document, $sce, $animate, $$sanitizeUri) { |
||
|
||
var Attributes = function(element, attr) { |
||
this.$$element = element; |
||
this.$attr = attr || {}; |
||
}; |
||
|
||
Attributes.prototype = { |
||
$normalize: directiveNormalize, |
||
|
||
|
||
/** |
||
* @ngdoc function |
||
* @name ng.$compile.directive.Attributes#$addClass |
||
* @methodOf ng.$compile.directive.Attributes |
||
* @function |
||
* |
||
* @description |
||
* Adds the CSS class value specified by the classVal parameter to the element. If animations |
||
* are enabled then an animation will be triggered for the class addition. |
||
* |
||
* @param {string} classVal The className value that will be added to the element |
||
*/ |
||
$addClass : function(classVal) { |
||
if(classVal && classVal.length > 0) { |
||
$animate.addClass(this.$$element, classVal); |
||
} |
||
}, |
||
|
||
/** |
||
* @ngdoc function |
||
* @name ng.$compile.directive.Attributes#$removeClass |
||
* @methodOf ng.$compile.directive.Attributes |
||
* @function |
||
* |
||
* @description |
||
* Removes the CSS class value specified by the classVal parameter from the element. If |
||
* animations are enabled then an animation will be triggered for the class removal. |
||
* |
||
* @param {string} classVal The className value that will be removed from the element |
||
*/ |
||
$removeClass : function(classVal) { |
||
if(classVal && classVal.length > 0) { |
||
$animate.removeClass(this.$$element, classVal); |
||
} |
||
}, |
||
|
||
/** |
||
* @ngdoc function |
||
* @name ng.$compile.directive.Attributes#$updateClass |
||
* @methodOf ng.$compile.directive.Attributes |
||
* @function |
||
* |
||
* @description |
||
* Adds and removes the appropriate CSS class values to the element based on the difference |
||
* between the new and old CSS class values (specified as newClasses and oldClasses). |
||
* |
||
* @param {string} newClasses The current CSS className value |
||
* @param {string} oldClasses The former CSS className value |
||
*/ |
||
$updateClass : function(newClasses, oldClasses) { |
||
this.$removeClass(tokenDifference(oldClasses, newClasses)); |
||
this.$addClass(tokenDifference(newClasses, oldClasses)); |
||
}, |
||
|
||
/** |
||
* Set a normalized attribute on the element in a way such that all directives |
||
* can share the attribute. This function properly handles boolean attributes. |
||
* @param {string} key Normalized key. (ie ngAttribute) |
||
* @param {string|boolean} value The value to set. If `null` attribute will be deleted. |
||
* @param {boolean=} writeAttr If false, does not write the value to DOM element attribute. |
||
* Defaults to true. |
||
* @param {string=} attrName Optional none normalized name. Defaults to key. |
||
*/ |
||
$set: function(key, value, writeAttr, attrName) { |
||
// TODO: decide whether or not to throw an error if "class" |
||
//is set through this function since it may cause $updateClass to |
||
//become unstable. |
||
|
||
var booleanKey = getBooleanAttrName(this.$$element[0], key), |
||
normalizedVal, |
||
nodeName; |
||
|
||
if (booleanKey) { |
||
this.$$element.prop(key, value); |
||
attrName = booleanKey; |
||
} |
||
|
||
this[key] = value; |
||
|
||
// translate normalized key to actual key |
||
if (attrName) { |
||
this.$attr[key] = attrName; |
||
} else { |
||
attrName = this.$attr[key]; |
||
if (!attrName) { |
||
this.$attr[key] = attrName = snake_case(key, '-'); |
||
} |
||
} |
||
|
||
nodeName = nodeName_(this.$$element); |
||
|
||
// sanitize a[href] and img[src] values |
||
if ((nodeName === 'A' && key === 'href') || |
||
(nodeName === 'IMG' && key === 'src')) { |
||
this[key] = value = $$sanitizeUri(value, key === 'src'); |
||
} |
||
|
||
if (writeAttr !== false) { |
||
if (value === null || value === undefined) { |
||
this.$$element.removeAttr(attrName); |
||
} else { |
||
this.$$element.attr(attrName, value); |
||
} |
||
} |
||
|
||
// fire observers |
||
var $$observers = this.$$observers; |
||
$$observers && forEach($$observers[key], function(fn) { |
||
try { |
||
fn(value); |
||
} catch (e) { |
||
$exceptionHandler(e); |
||
} |
||
}); |
||
}, |
||
|
||
|
||
/** |
||
* @ngdoc function |
||
* @name ng.$compile.directive.Attributes#$observe |
||
* @methodOf ng.$compile.directive.Attributes |
||
* @function |
||
* |
||
* @description |
||
* Observes an interpolated attribute. |
||
* |
||
* The observer function will be invoked once during the next `$digest` following |
||
* compilation. The observer is then invoked whenever the interpolated value |
||
* changes. |
||
* |
||
* @param {string} key Normalized key. (ie ngAttribute) . |
||
* @param {function(interpolatedValue)} fn Function that will be called whenever |
||
the interpolated value of the attribute changes. |
||
* See the {@link guide/directive#Attributes Directives} guide for more info. |
||
* @returns {function()} the `fn` parameter. |
||
*/ |
||
$observe: function(key, fn) { |
||
var attrs = this, |
||
$$observers = (attrs.$$observers || (attrs.$$observers = {})), |
||
listeners = ($$observers[key] || ($$observers[key] = [])); |
||
|
||
listeners.push(fn); |
||
$rootScope.$evalAsync(function() { |
||
if (!listeners.$$inter) { |
||
// no one registered attribute interpolation function, so lets call it manually |
||
fn(attrs[key]); |
||
} |
||
}); |
||
return fn; |
||
} |
||
}; |
||
|
||
var startSymbol = $interpolate.startSymbol(), |
||
endSymbol = $interpolate.endSymbol(), |
||
denormalizeTemplate = (startSymbol == '{{' || endSymbol == '}}') |
||
? identity |
||
: function denormalizeTemplate(template) { |
||
return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol); |
||
}, |
||
NG_ATTR_BINDING = /^ngAttr[A-Z]/; |
||
|
||
|
||
return compile; |
||
|
||
//================================ |
||
|
||
function compile($compileNodes, transcludeFn, maxPriority, ignoreDirective, |
||
previousCompileContext) { |
||
if (!($compileNodes instanceof jqLite)) { |
||
// jquery always rewraps, whereas we need to preserve the original selector so that we can |
||
// modify it. |
||
$compileNodes = jqLite($compileNodes); |
||
} |
||
// We can not compile top level text elements since text nodes can be merged and we will |
||
// not be able to attach scope data to them, so we will wrap them in <span> |
||
forEach($compileNodes, function(node, index){ |
||
if (node.nodeType == 3 /* text node */ && node.nodeValue.match(/\S+/) /* non-empty */ ) { |
||
$compileNodes[index] = node = jqLite(node).wrap('<span></span>').parent()[0]; |
||
} |
||
}); |
||
var compositeLinkFn = |
||
compileNodes($compileNodes, transcludeFn, $compileNodes, |
||
maxPriority, ignoreDirective, previousCompileContext); |
||
safeAddClass($compileNodes, 'ng-scope'); |
||
return function publicLinkFn(scope, cloneConnectFn, transcludeControllers){ |
||
assertArg(scope, 'scope'); |
||
// important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart |
||
// and sometimes changes the structure of the DOM. |
||
var $linkNode = cloneConnectFn |
||
? JQLitePrototype.clone.call($compileNodes) // IMPORTANT!!! |
||
: $compileNodes; |
||
|
||
forEach(transcludeControllers, function(instance, name) { |
||
$linkNode.data('$' + name + 'Controller', instance); |
||
}); |
||
|
||
// Attach scope only to non-text nodes. |
||
for(var i = 0, ii = $linkNode.length; i<ii; i++) { |
||
var node = $linkNode[i], |
||
nodeType = node.nodeType; |
||
if (nodeType === 1 /* element */ || nodeType === 9 /* document */) { |
||
$linkNode.eq(i).data('$scope', scope); |
||
} |
||
} |
||
|
||
if (cloneConnectFn) cloneConnectFn($linkNode, scope); |
||
if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode); |
||
return $linkNode; |
||
}; |
||
} |
||
|
||
function safeAddClass($element, className) { |
||
try { |
||
$element.addClass(className); |
||
} catch(e) { |
||
// ignore, since it means that we are trying to set class on |
||
// SVG element, where class name is read-only. |
||
} |
||
} |
||
|
||
/** |
||
* Compile function matches each node in nodeList against the directives. Once all directives |
||
* for a particular node are collected their compile functions are executed. The compile |
||
* functions return values - the linking functions - are combined into a composite linking |
||
* function, which is the a linking function for the node. |
||
* |
||
* @param {NodeList} nodeList an array of nodes or NodeList to compile |
||
* @param {function(angular.Scope[, cloneAttachFn]} transcludeFn A linking function, where the |
||
* scope argument is auto-generated to the new child of the transcluded parent scope. |
||
* @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then |
||
* the rootElement must be set the jqLite collection of the compile root. This is |
||
* needed so that the jqLite collection items can be replaced with widgets. |
||
* @param {number=} maxPriority Max directive priority. |
||
* @returns {?function} A composite linking function of all of the matched directives or null. |
||
*/ |
||
function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority, ignoreDirective, |
||
previousCompileContext) { |
||
var linkFns = [], |
||
attrs, directives, nodeLinkFn, childNodes, childLinkFn, linkFnFound; |
||
|
||
for (var i = 0; i < nodeList.length; i++) { |
||
attrs = new Attributes(); |
||
|
||
// we must always refer to nodeList[i] since the nodes can be replaced underneath us. |
||
directives = collectDirectives(nodeList[i], [], attrs, i === 0 ? maxPriority : undefined, |
||
ignoreDirective); |
||
|
||
nodeLinkFn = (directives.length) |
||
? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement, |
||
null, [], [], previousCompileContext) |
||
: null; |
||
|
||
if (nodeLinkFn && nodeLinkFn.scope) { |
||
safeAddClass(jqLite(nodeList[i]), 'ng-scope'); |
||
} |
||
|
||
childLinkFn = (nodeLinkFn && nodeLinkFn.terminal || |
||
!(childNodes = nodeList[i].childNodes) || |
||
!childNodes.length) |
||
? null |
||
: compileNodes(childNodes, |
||
nodeLinkFn ? nodeLinkFn.transclude : transcludeFn); |
||
|
||
linkFns.push(nodeLinkFn, childLinkFn); |
||
linkFnFound = linkFnFound || nodeLinkFn || childLinkFn; |
||
//use the previous context only for the first element in the virtual group |
||
previousCompileContext = null; |
||
} |
||
|
||
// return a linking function if we have found anything, null otherwise |
||
return linkFnFound ? compositeLinkFn : null; |
||
|
||
function compositeLinkFn(scope, nodeList, $rootElement, boundTranscludeFn) { |
||
var nodeLinkFn, childLinkFn, node, $node, childScope, childTranscludeFn, i, ii, n; |
||
|
||
// copy nodeList so that linking doesn't break due to live list updates. |
||
var nodeListLength = nodeList.length, |
||
stableNodeList = new Array(nodeListLength); |
||
for (i = 0; i < nodeListLength; i++) { |
||
stableNodeList[i] = nodeList[i]; |
||
} |
||
|
||
for(i = 0, n = 0, ii = linkFns.length; i < ii; n++) { |
||
node = stableNodeList[n]; |
||
nodeLinkFn = linkFns[i++]; |
||
childLinkFn = linkFns[i++]; |
||
$node = jqLite(node); |
||
|
||
if (nodeLinkFn) { |
||
if (nodeLinkFn.scope) { |
||
childScope = scope.$new(); |
||
$node.data('$scope', childScope); |
||
} else { |
||
childScope = scope; |
||
} |
||
childTranscludeFn = nodeLinkFn.transclude; |
||
if (childTranscludeFn || (!boundTranscludeFn && transcludeFn)) { |
||
nodeLinkFn(childLinkFn, childScope, node, $rootElement, |
||
createBoundTranscludeFn(scope, childTranscludeFn || transcludeFn) |
||
); |
||
} else { |
||
nodeLinkFn(childLinkFn, childScope, node, $rootElement, boundTranscludeFn); |
||
} |
||
} else if (childLinkFn) { |
||
childLinkFn(scope, node.childNodes, undefined, boundTranscludeFn); |
||
} |
||
} |
||
} |
||
} |
||
|
||
function createBoundTranscludeFn(scope, transcludeFn) { |
||
return function boundTranscludeFn(transcludedScope, cloneFn, controllers) { |
||
var scopeCreated = false; |
||
|
||
if (!transcludedScope) { |
||
transcludedScope = scope.$new(); |
||
transcludedScope.$$transcluded = true; |
||
scopeCreated = true; |
||
} |
||
|
||
var clone = transcludeFn(transcludedScope, cloneFn, controllers); |
||
if (scopeCreated) { |
||
clone.on('$destroy', bind(transcludedScope, transcludedScope.$destroy)); |
||
} |
||
return clone; |
||
}; |
||
} |
||
|
||
/** |
||
* Looks for directives on the given node and adds them to the directive collection which is |
||
* sorted. |
||
* |
||
* @param node Node to search. |
||
* @param directives An array to which the directives are added to. This array is sorted before |
||
* the function returns. |
||
* @param attrs The shared attrs object which is used to populate the normalized attributes. |
||
* @param {number=} maxPriority Max directive priority. |
||
*/ |
||
function collectDirectives(node, directives, attrs, maxPriority, ignoreDirective) { |
||
var nodeType = node.nodeType, |
||
attrsMap = attrs.$attr, |
||
match, |
||
className; |
||
|
||
switch(nodeType) { |
||
case 1: /* Element */ |
||
// use the node name: <directive> |
||
addDirective(directives, |
||
directiveNormalize(nodeName_(node).toLowerCase()), 'E', maxPriority, ignoreDirective); |
||
|
||
// iterate over the attributes |
||
for (var attr, name, nName, ngAttrName, value, nAttrs = node.attributes, |
||
j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) { |
||
var attrStartName = false; |
||
var attrEndName = false; |
||
|
||
attr = nAttrs[j]; |
||
if (!msie || msie >= 8 || attr.specified) { |
||
name = attr.name; |
||
// support ngAttr attribute binding |
||
ngAttrName = directiveNormalize(name); |
||
if (NG_ATTR_BINDING.test(ngAttrName)) { |
||
name = snake_case(ngAttrName.substr(6), '-'); |
||
} |
||
|
||
var directiveNName = ngAttrName.replace(/(Start|End)$/, ''); |
||
if (ngAttrName === directiveNName + 'Start') { |
||
attrStartName = name; |
||
attrEndName = name.substr(0, name.length - 5) + 'end'; |
||
name = name.substr(0, name.length - 6); |
||
} |
||
|
||
nName = directiveNormalize(name.toLowerCase()); |
||
attrsMap[nName] = name; |
||
attrs[nName] = value = trim(attr.value); |
||
if (getBooleanAttrName(node, nName)) { |
||
attrs[nName] = true; // presence means true |
||
} |
||
addAttrInterpolateDirective(node, directives, value, nName); |
||
addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName, |
||
attrEndName); |
||
} |
||
} |
||
|
||
// use class as directive |
||
className = node.className; |
||
if (isString(className) && className !== '') { |
||
while (match = CLASS_DIRECTIVE_REGEXP.exec(className)) { |
||
nName = directiveNormalize(match[2]); |
||
if (addDirective(directives, nName, 'C', maxPriority, ignoreDirective)) { |
||
attrs[nName] = trim(match[3]); |
||
} |
||
className = className.substr(match.index + match[0].length); |
||
} |
||
} |
||
break; |
||
case 3: /* Text Node */ |
||
addTextInterpolateDirective(directives, node.nodeValue); |
||
break; |
||
case 8: /* Comment */ |
||
try { |
||
match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue); |
||
if (match) { |
||
nName = directiveNormalize(match[1]); |
||
if (addDirective(directives, nName, 'M', maxPriority, ignoreDirective)) { |
||
attrs[nName] = trim(match[2]); |
||
} |
||
} |
||
} catch (e) { |
||
// turns out that under some circumstances IE9 throws errors when one attempts to read |
||
// comment's node value. |
||
// Just ignore it and continue. (Can't seem to reproduce in test case.) |
||
} |
||
break; |
||
} |
||
|
||
directives.sort(byPriority); |
||
return directives; |
||
} |
||
|
||
/** |
||
* Given a node with an directive-start it collects all of the siblings until it finds |
||
* directive-end. |
||
* @param node |
||
* @param attrStart |
||
* @param attrEnd |
||
* @returns {*} |
||
*/ |
||
function groupScan(node, attrStart, attrEnd) { |
||
var nodes = []; |
||
var depth = 0; |
||
if (attrStart && node.hasAttribute && node.hasAttribute(attrStart)) { |
||
var startNode = node; |
||
do { |
||
if (!node) { |
||
throw $compileMinErr('uterdir', |
||
"Unterminated attribute, found '{0}' but no matching '{1}' found.", |
||
attrStart, attrEnd); |
||
} |
||
if (node.nodeType == 1 /** Element **/) { |
||
if (node.hasAttribute(attrStart)) depth++; |
||
if (node.hasAttribute(attrEnd)) depth--; |
||
} |
||
nodes.push(node); |
||
node = node.nextSibling; |
||
} while (depth > 0); |
||
} else { |
||
nodes.push(node); |
||
} |
||
|
||
return jqLite(nodes); |
||
} |
||
|
||
/** |
||
* Wrapper for linking function which converts normal linking function into a grouped |
||
* linking function. |
||
* @param linkFn |
||
* @param attrStart |
||
* @param attrEnd |
||
* @returns {Function} |
||
*/ |
||
function groupElementsLinkFnWrapper(linkFn, attrStart, attrEnd) { |
||
return function(scope, element, attrs, controllers, transcludeFn) { |
||
element = groupScan(element[0], attrStart, attrEnd); |
||
return linkFn(scope, element, attrs, controllers, transcludeFn); |
||
}; |
||
} |
||
|
||
/** |
||
* Once the directives have been collected, their compile functions are executed. This method |
||
* is responsible for inlining directive templates as well as terminating the application |
||
* of the directives if the terminal directive has been reached. |
||
* |
||
* @param {Array} directives Array of collected directives to execute their compile function. |
||
* this needs to be pre-sorted by priority order. |
||
* @param {Node} compileNode The raw DOM node to apply the compile functions to |
||
* @param {Object} templateAttrs The shared attribute function |
||
* @param {function(angular.Scope[, cloneAttachFn]} transcludeFn A linking function, where the |
||
* scope argument is auto-generated to the new |
||
* child of the transcluded parent scope. |
||
* @param {JQLite} jqCollection If we are working on the root of the compile tree then this |
||
* argument has the root jqLite array so that we can replace nodes |
||
* on it. |
||
* @param {Object=} originalReplaceDirective An optional directive that will be ignored when |
||
* compiling the transclusion. |
||
* @param {Array.<Function>} preLinkFns |
||
* @param {Array.<Function>} postLinkFns |
||
* @param {Object} previousCompileContext Context used for previous compilation of the current |
||
* node |
||
* @returns linkFn |
||
*/ |
||
function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn, |
||
jqCollection, originalReplaceDirective, preLinkFns, postLinkFns, |
||
previousCompileContext) { |
||
previousCompileContext = previousCompileContext || {}; |
||
|
||
var terminalPriority = -Number.MAX_VALUE, |
||
newScopeDirective, |
||
controllerDirectives = previousCompileContext.controllerDirectives, |
||
newIsolateScopeDirective = previousCompileContext.newIsolateScopeDirective, |
||
templateDirective = previousCompileContext.templateDirective, |
||
nonTlbTranscludeDirective = previousCompileContext.nonTlbTranscludeDirective, |
||
hasTranscludeDirective = false, |
||
hasElementTranscludeDirective = false, |
||
$compileNode = templateAttrs.$$element = jqLite(compileNode), |
||
directive, |
||
directiveName, |
||
$template, |
||
replaceDirective = originalReplaceDirective, |
||
childTranscludeFn = transcludeFn, |
||
linkFn, |
||
directiveValue; |
||
|
||
// executes all directives on the current element |
||
for(var i = 0, ii = directives.length; i < ii; i++) { |
||
directive = directives[i]; |
||
var attrStart = directive.$$start; |
||
var attrEnd = directive.$$end; |
||
|
||
// collect multiblock sections |
||
if (attrStart) { |
||
$compileNode = groupScan(compileNode, attrStart, attrEnd); |
||
} |
||
$template = undefined; |
||
|
||
if (terminalPriority > directive.priority) { |
||
break; // prevent further processing of directives |
||
} |
||
|
||
if (directiveValue = directive.scope) { |
||
newScopeDirective = newScopeDirective || directive; |
||
|
||
// skip the check for directives with async templates, we'll check the derived sync |
||
// directive when the template arrives |
||
if (!directive.templateUrl) { |
||
assertNoDuplicate('new/isolated scope', newIsolateScopeDirective, directive, |
||
$compileNode); |
||
if (isObject(directiveValue)) { |
||
newIsolateScopeDirective = directive; |
||
} |
||
} |
||
} |
||
|
||
directiveName = directive.name; |
||
|
||
if (!directive.templateUrl && directive.controller) { |
||
directiveValue = directive.controller; |
||
controllerDirectives = controllerDirectives || {}; |
||
assertNoDuplicate("'" + directiveName + "' controller", |
||
controllerDirectives[directiveName], directive, $compileNode); |
||
controllerDirectives[directiveName] = directive; |
||
} |
||
|
||
if (directiveValue = directive.transclude) { |
||
hasTranscludeDirective = true; |
||
|
||
// Special case ngIf and ngRepeat so that we don't complain about duplicate transclusion. |
||
// This option should only be used by directives that know how to how to safely handle element transclusion, |
||
// where the transcluded nodes are added or replaced after linking. |
||
if (!directive.$$tlb) { |
||
assertNoDuplicate('transclusion', nonTlbTranscludeDirective, directive, $compileNode); |
||
nonTlbTranscludeDirective = directive; |
||
} |
||
|
||
if (directiveValue == 'element') { |
||
hasElementTranscludeDirective = true; |
||
terminalPriority = directive.priority; |
||
$template = groupScan(compileNode, attrStart, attrEnd); |
||
$compileNode = templateAttrs.$$element = |
||
jqLite(document.createComment(' ' + directiveName + ': ' + |
||
templateAttrs[directiveName] + ' ')); |
||
compileNode = $compileNode[0]; |
||
replaceWith(jqCollection, jqLite(sliceArgs($template)), compileNode); |
||
|
||
childTranscludeFn = compile($template, transcludeFn, terminalPriority, |
||
replaceDirective && replaceDirective.name, { |
||
// Don't pass in: |
||
// - controllerDirectives - otherwise we'll create duplicates controllers |
||
// - newIsolateScopeDirective or templateDirective - combining templates with |
||
// element transclusion doesn't make sense. |
||
// |
||
// We need only nonTlbTranscludeDirective so that we prevent putting transclusion |
||
// on the same element more than once. |
||
nonTlbTranscludeDirective: nonTlbTranscludeDirective |
||
}); |
||
} else { |
||
$template = jqLite(jqLiteClone(compileNode)).contents(); |
||
$compileNode.empty(); // clear contents |
||
childTranscludeFn = compile($template, transcludeFn); |
||
} |
||
} |
||
|
||
if (directive.template) { |
||
assertNoDuplicate('template', templateDirective, directive, $compileNode); |
||
templateDirective = directive; |
||
|
||
directiveValue = (isFunction(directive.template)) |
||
? directive.template($compileNode, templateAttrs) |
||
: directive.template; |
||
|
||
directiveValue = denormalizeTemplate(directiveValue); |
||
|
||
if (directive.replace) { |
||
replaceDirective = directive; |
||
$template = jqLite('<div>' + |
||
trim(directiveValue) + |
||
'</div>').contents(); |
||
compileNode = $template[0]; |
||
|
||
if ($template.length != 1 || compileNode.nodeType !== 1) { |
||
throw $compileMinErr('tplrt', |
||
"Template for directive '{0}' must have exactly one root element. {1}", |
||
directiveName, ''); |
||
} |
||
|
||
replaceWith(jqCollection, $compileNode, compileNode); |
||
|
||
var newTemplateAttrs = {$attr: {}}; |
||
|
||
// combine directives from the original node and from the template: |
||
// - take the array of directives for this element |
||
// - split it into two parts, those that already applied (processed) and those that weren't (unprocessed) |
||
// - collect directives from the template and sort them by priority |
||
// - combine directives as: processed + template + unprocessed |
||
var templateDirectives = collectDirectives(compileNode, [], newTemplateAttrs); |
||
var unprocessedDirectives = directives.splice(i + 1, directives.length - (i + 1)); |
||
|
||
if (newIsolateScopeDirective) { |
||
markDirectivesAsIsolate(templateDirectives); |
||
} |
||
directives = directives.concat(templateDirectives).concat(unprocessedDirectives); |
||
mergeTemplateAttributes(templateAttrs, newTemplateAttrs); |
||
|
||
ii = directives.length; |
||
} else { |
||
$compileNode.html(directiveValue); |
||
} |
||
} |
||
|
||
if (directive.templateUrl) { |
||
assertNoDuplicate('template', templateDirective, directive, $compileNode); |
||
templateDirective = directive; |
||
|
||
if (directive.replace) { |
||
replaceDirective = directive; |
||
} |
||
|
||
nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), $compileNode, |
||
templateAttrs, jqCollection, childTranscludeFn, preLinkFns, postLinkFns, { |
||
controllerDirectives: controllerDirectives, |
||
newIsolateScopeDirective: newIsolateScopeDirective, |
||
templateDirective: templateDirective, |
||
nonTlbTranscludeDirective: nonTlbTranscludeDirective |
||
}); |
||
ii = directives.length; |
||
} else if (directive.compile) { |
||
try { |
||
linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn); |
||
if (isFunction(linkFn)) { |
||
addLinkFns(null, linkFn, attrStart, attrEnd); |
||
} else if (linkFn) { |
||
addLinkFns(linkFn.pre, linkFn.post, attrStart, attrEnd); |
||
} |
||
} catch (e) { |
||
$exceptionHandler(e, startingTag($compileNode)); |
||
} |
||
} |
||
|
||
if (directive.terminal) { |
||
nodeLinkFn.terminal = true; |
||
terminalPriority = Math.max(terminalPriority, directive.priority); |
||
} |
||
|
||
} |
||
|
||
nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope === true; |
||
nodeLinkFn.transclude = hasTranscludeDirective && childTranscludeFn; |
||
|
||
// might be normal or delayed nodeLinkFn depending on if templateUrl is present |
||
return nodeLinkFn; |
||
|
||
//////////////////// |
||
|
||
function addLinkFns(pre, post, attrStart, attrEnd) { |
||
if (pre) { |
||
if (attrStart) pre = groupElementsLinkFnWrapper(pre, attrStart, attrEnd); |
||
pre.require = directive.require; |
||
if (newIsolateScopeDirective === directive || directive.$$isolateScope) { |
||
pre = cloneAndAnnotateFn(pre, {isolateScope: true}); |
||
} |
||
preLinkFns.push(pre); |
||
} |
||
if (post) { |
||
if (attrStart) post = groupElementsLinkFnWrapper(post, attrStart, attrEnd); |
||
post.require = directive.require; |
||
if (newIsolateScopeDirective === directive || directive.$$isolateScope) { |
||
post = cloneAndAnnotateFn(post, {isolateScope: true}); |
||
} |
||
postLinkFns.push(post); |
||
} |
||
} |
||
|
||
|
||
function getControllers(require, $element, elementControllers) { |
||
var value, retrievalMethod = 'data', optional = false; |
||
if (isString(require)) { |
||
while((value = require.charAt(0)) == '^' || value == '?') { |
||
require = require.substr(1); |
||
if (value == '^') { |
||
retrievalMethod = 'inheritedData'; |
||
} |
||
optional = optional || value == '?'; |
||
} |
||
value = null; |
||
|
||
if (elementControllers && retrievalMethod === 'data') { |
||
value = elementControllers[require]; |
||
} |
||
value = value || $element[retrievalMethod]('$' + require + 'Controller'); |
||
|
||
if (!value && !optional) { |
||
throw $compileMinErr('ctreq', |
||
"Controller '{0}', required by directive '{1}', can't be found!", |
||
require, directiveName); |
||
} |
||
return value; |
||
} else if (isArray(require)) { |
||
value = []; |
||
forEach(require, function(require) { |
||
value.push(getControllers(require, $element, elementControllers)); |
||
}); |
||
} |
||
return value; |
||
} |
||
|
||
|
||
function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) { |
||
var attrs, $element, i, ii, linkFn, controller, isolateScope, elementControllers = {}, transcludeFn; |
||
|
||
if (compileNode === linkNode) { |
||
attrs = templateAttrs; |
||
} else { |
||
attrs = shallowCopy(templateAttrs, new Attributes(jqLite(linkNode), templateAttrs.$attr)); |
||
} |
||
$element = attrs.$$element; |
||
|
||
if (newIsolateScopeDirective) { |
||
var LOCAL_REGEXP = /^\s*([@=&])(\??)\s*(\w*)\s*$/; |
||
var $linkNode = jqLite(linkNode); |
||
|
||
isolateScope = scope.$new(true); |
||
|
||
if (templateDirective && (templateDirective === newIsolateScopeDirective.$$originalDirective)) { |
||
$linkNode.data('$isolateScope', isolateScope) ; |
||
} else { |
||
$linkNode.data('$isolateScopeNoTemplate', isolateScope); |
||
} |
||
|
||
|
||
|
||
safeAddClass($linkNode, 'ng-isolate-scope'); |
||
|
||
forEach(newIsolateScopeDirective.scope, function(definition, scopeName) { |
||
var match = definition.match(LOCAL_REGEXP) || [], |
||
attrName = match[3] || scopeName, |
||
optional = (match[2] == '?'), |
||
mode = match[1], // @, =, or & |
||
lastValue, |
||
parentGet, parentSet, compare; |
||
|
||
isolateScope.$$isolateBindings[scopeName] = mode + attrName; |
||
|
||
switch (mode) { |
||
|
||
case '@': |
||
attrs.$observe(attrName, function(value) { |
||
isolateScope[scopeName] = value; |
||
}); |
||
attrs.$$observers[attrName].$$scope = scope; |
||
if( attrs[attrName] ) { |
||
// If the attribute has been provided then we trigger an interpolation to ensure |
||
// the value is there for use in the link fn |
||
isolateScope[scopeName] = $interpolate(attrs[attrName])(scope); |
||
} |
||
break; |
||
|
||
case '=': |
||
if (optional && !attrs[attrName]) { |
||
return; |
||
} |
||
parentGet = $parse(attrs[attrName]); |
||
if (parentGet.literal) { |
||
compare = equals; |
||
} else { |
||
compare = function(a,b) { return a === b; }; |
||
} |
||
parentSet = parentGet.assign || function() { |
||
// reset the change, or we will throw this exception on every $digest |
||
lastValue = isolateScope[scopeName] = parentGet(scope); |
||
throw $compileMinErr('nonassign', |
||
"Expression '{0}' used with directive '{1}' is non-assignable!", |
||
attrs[attrName], newIsolateScopeDirective.name); |
||
}; |
||
lastValue = isolateScope[scopeName] = parentGet(scope); |
||
isolateScope.$watch(function parentValueWatch() { |
||
var parentValue = parentGet(scope); |
||
if (!compare(parentValue, isolateScope[scopeName])) { |
||
// we are out of sync and need to copy |
||
if (!compare(parentValue, lastValue)) { |
||
// parent changed and it has precedence |
||
isolateScope[scopeName] = parentValue; |
||
} else { |
||
// if the parent can be assigned then do so |
||
parentSet(scope, parentValue = isolateScope[scopeName]); |
||
} |
||
} |
||
return lastValue = parentValue; |
||
}, null, parentGet.literal); |
||
break; |
||
|
||
case '&': |
||
parentGet = $parse(attrs[attrName]); |
||
isolateScope[scopeName] = function(locals) { |
||
return parentGet(scope, locals); |
||
}; |
||
break; |
||
|
||
default: |
||
throw $compileMinErr('iscp', |
||
"Invalid isolate scope definition for directive '{0}'." + |
||
" Definition: {... {1}: '{2}' ...}", |
||
newIsolateScopeDirective.name, scopeName, definition); |
||
} |
||
}); |
||
} |
||
transcludeFn = boundTranscludeFn && controllersBoundTransclude; |
||
if (controllerDirectives) { |
||
forEach(controllerDirectives, function(directive) { |
||
var locals = { |
||
$scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope, |
||
$element: $element, |
||
$attrs: attrs, |
||
$transclude: transcludeFn |
||
}, controllerInstance; |
||
|
||
controller = directive.controller; |
||
if (controller == '@') { |
||
controller = attrs[directive.name]; |
||
} |
||
|
||
controllerInstance = $controller(controller, locals); |
||
// For directives with element transclusion the element is a comment, |
||
// but jQuery .data doesn't support attaching data to comment nodes as it's hard to |
||
// clean up (http://bugs.jquery.com/ticket/8335). |
||
// Instead, we save the controllers for the element in a local hash and attach to .data |
||
// later, once we have the actual element. |
||
elementControllers[directive.name] = controllerInstance; |
||
if (!hasElementTranscludeDirective) { |
||
$element.data('$' + directive.name + 'Controller', controllerInstance); |
||
} |
||
|
||
if (directive.controllerAs) { |
||
locals.$scope[directive.controllerAs] = controllerInstance; |
||
} |
||
}); |
||
} |
||
|
||
// PRELINKING |
||
for(i = 0, ii = preLinkFns.length; i < ii; i++) { |
||
try { |
||
linkFn = preLinkFns[i]; |
||
linkFn(linkFn.isolateScope ? isolateScope : scope, $element, attrs, |
||
linkFn.require && getControllers(linkFn.require, $element, elementControllers), transcludeFn); |
||
} catch (e) { |
||
$exceptionHandler(e, startingTag($element)); |
||
} |
||
} |
||
|
||
// RECURSION |
||
// We only pass the isolate scope, if the isolate directive has a template, |
||
// otherwise the child elements do not belong to the isolate directive. |
||
var scopeToChild = scope; |
||
if (newIsolateScopeDirective && (newIsolateScopeDirective.template || newIsolateScopeDirective.templateUrl === null)) { |
||
scopeToChild = isolateScope; |
||
} |
||
childLinkFn && childLinkFn(scopeToChild, linkNode.childNodes, undefined, boundTranscludeFn); |
||
|
||
// POSTLINKING |
||
for(i = postLinkFns.length - 1; i >= 0; i--) { |
||
try { |
||
linkFn = postLinkFns[i]; |
||
linkFn(linkFn.isolateScope ? isolateScope : scope, $element, attrs, |
||
linkFn.require && getControllers(linkFn.require, $element, elementControllers), transcludeFn); |
||
} catch (e) { |
||
$exceptionHandler(e, startingTag($element)); |
||
} |
||
} |
||
|
||
// This is the function that is injected as `$transclude`. |
||
function controllersBoundTransclude(scope, cloneAttachFn) { |
||
var transcludeControllers; |
||
|
||
// no scope passed |
||
if (arguments.length < 2) { |
||
cloneAttachFn = scope; |
||
scope = undefined; |
||
} |
||
|
||
if (hasElementTranscludeDirective) { |
||
transcludeControllers = elementControllers; |
||
} |
||
|
||
return boundTranscludeFn(scope, cloneAttachFn, transcludeControllers); |
||
} |
||
} |
||
} |
||
|
||
function markDirectivesAsIsolate(directives) { |
||
// mark all directives as needing isolate scope. |
||
for (var j = 0, jj = directives.length; j < jj; j++) { |
||
directives[j] = inherit(directives[j], {$$isolateScope: true}); |
||
} |
||
} |
||
|
||
/** |
||
* looks up the directive and decorates it with exception handling and proper parameters. We |
||
* call this the boundDirective. |
||
* |
||
* @param {string} name name of the directive to look up. |
||
* @param {string} location The directive must be found in specific format. |
||
* String containing any of theses characters: |
||
* |
||
* * `E`: element name |
||
* * `A': attribute |
||
* * `C`: class |
||
* * `M`: comment |
||
* @returns true if directive was added. |
||
*/ |
||
function addDirective(tDirectives, name, location, maxPriority, ignoreDirective, startAttrName, |
||
endAttrName) { |
||
if (name === ignoreDirective) return null; |
||
var match = null; |
||
if (hasDirectives.hasOwnProperty(name)) { |
||
for(var directive, directives = $injector.get(name + Suffix), |
||
i = 0, ii = directives.length; i<ii; i++) { |
||
try { |
||
directive = directives[i]; |
||
if ( (maxPriority === undefined || maxPriority > directive.priority) && |
||
directive.restrict.indexOf(location) != -1) { |
||
if (startAttrName) { |
||
directive = inherit(directive, {$$start: startAttrName, $$end: endAttrName}); |
||
} |
||
tDirectives.push(directive); |
||
match = directive; |
||
} |
||
} catch(e) { $exceptionHandler(e); } |
||
} |
||
} |
||
return match; |
||
} |
||
|
||
|
||
/** |
||
* When the element is replaced with HTML template then the new attributes |
||
* on the template need to be merged with the existing attributes in the DOM. |
||
* The desired effect is to have both of the attributes present. |
||
* |
||
* @param {object} dst destination attributes (original DOM) |
||
* @param {object} src source attributes (from the directive template) |
||
*/ |
||
function mergeTemplateAttributes(dst, src) { |
||
var srcAttr = src.$attr, |
||
dstAttr = dst.$attr, |
||
$element = dst.$$element; |
||
|
||
// reapply the old attributes to the new element |
||
forEach(dst, function(value, key) { |
||
if (key.charAt(0) != '$') { |
||
if (src[key]) { |
||
value += (key === 'style' ? ';' : ' ') + src[key]; |
||
} |
||
dst.$set(key, value, true, srcAttr[key]); |
||
} |
||
}); |
||
|
||
// copy the new attributes on the old attrs object |
||
forEach(src, function(value, key) { |
||
if (key == 'class') { |
||
safeAddClass($element, value); |
||
dst['class'] = (dst['class'] ? dst['class'] + ' ' : '') + value; |
||
} else if (key == 'style') { |
||
$element.attr('style', $element.attr('style') + ';' + value); |
||
dst['style'] = (dst['style'] ? dst['style'] + ';' : '') + value; |
||
// `dst` will never contain hasOwnProperty as DOM parser won't let it. |
||
// You will get an "InvalidCharacterError: DOM Exception 5" error if you |
||
// have an attribute like "has-own-property" or "data-has-own-property", etc. |
||
} else if (key.charAt(0) != '$' && !dst.hasOwnProperty(key)) { |
||
dst[key] = value; |
||
dstAttr[key] = srcAttr[key]; |
||
} |
||
}); |
||
} |
||
|
||
|
||
function compileTemplateUrl(directives, $compileNode, tAttrs, |
||
$rootElement, childTranscludeFn, preLinkFns, postLinkFns, previousCompileContext) { |
||
var linkQueue = [], |
||
afterTemplateNodeLinkFn, |
||
afterTemplateChildLinkFn, |
||
beforeTemplateCompileNode = $compileNode[0], |
||
origAsyncDirective = directives.shift(), |
||
// The fact that we have to copy and patch the directive seems wrong! |
||
derivedSyncDirective = extend({}, origAsyncDirective, { |
||
templateUrl: null, transclude: null, replace: null, $$originalDirective: origAsyncDirective |
||
}), |
||
templateUrl = (isFunction(origAsyncDirective.templateUrl)) |
||
? origAsyncDirective.templateUrl($compileNode, tAttrs) |
||
: origAsyncDirective.templateUrl; |
||
|
||
$compileNode.empty(); |
||
|
||
$http.get($sce.getTrustedResourceUrl(templateUrl), {cache: $templateCache}). |
||
success(function(content) { |
||
var compileNode, tempTemplateAttrs, $template, childBoundTranscludeFn; |
||
|
||
content = denormalizeTemplate(content); |
||
|
||
if (origAsyncDirective.replace) { |
||
$template = jqLite('<div>' + trim(content) + '</div>').contents(); |
||
compileNode = $template[0]; |
||
|
||
if ($template.length != 1 || compileNode.nodeType !== 1) { |
||
throw $compileMinErr('tplrt', |
||
"Template for directive '{0}' must have exactly one root element. {1}", |
||
origAsyncDirective.name, templateUrl); |
||
} |
||
|
||
tempTemplateAttrs = {$attr: {}}; |
||
replaceWith($rootElement, $compileNode, compileNode); |
||
var templateDirectives = collectDirectives(compileNode, [], tempTemplateAttrs); |
||
|
||
if (isObject(origAsyncDirective.scope)) { |
||
markDirectivesAsIsolate(templateDirectives); |
||
} |
||
directives = templateDirectives.concat(directives); |
||
mergeTemplateAttributes(tAttrs, tempTemplateAttrs); |
||
} else { |
||
compileNode = beforeTemplateCompileNode; |
||
$compileNode.html(content); |
||
} |
||
|
||
directives.unshift(derivedSyncDirective); |
||
|
||
afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs, |
||
childTranscludeFn, $compileNode, origAsyncDirective, preLinkFns, postLinkFns, |
||
previousCompileContext); |
||
forEach($rootElement, function(node, i) { |
||
if (node == compileNode) { |
||
$rootElement[i] = $compileNode[0]; |
||
} |
||
}); |
||
afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn); |
||
|
||
|
||
while(linkQueue.length) { |
||
var scope = linkQueue.shift(), |
||
beforeTemplateLinkNode = linkQueue.shift(), |
||
linkRootElement = linkQueue.shift(), |
||
boundTranscludeFn = linkQueue.shift(), |
||
linkNode = $compileNode[0]; |
||
|
||
if (beforeTemplateLinkNode !== beforeTemplateCompileNode) { |
||
// it was cloned therefore we have to clone as well. |
||
linkNode = jqLiteClone(compileNode); |
||
replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode); |
||
} |
||
if (afterTemplateNodeLinkFn.transclude) { |
||
childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude); |
||
} else { |
||
childBoundTranscludeFn = boundTranscludeFn; |
||
} |
||
afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement, |
||
childBoundTranscludeFn); |
||
} |
||
linkQueue = null; |
||
}). |
||
error(function(response, code, headers, config) { |
||
throw $compileMinErr('tpload', 'Failed to load template: {0}', config.url); |
||
}); |
||
|
||
return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, boundTranscludeFn) { |
||
if (linkQueue) { |
||
linkQueue.push(scope); |
||
linkQueue.push(node); |
||
linkQueue.push(rootElement); |
||
linkQueue.push(boundTranscludeFn); |
||
} else { |
||
afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, boundTranscludeFn); |
||
} |
||
}; |
||
} |
||
|
||
|
||
/** |
||
* Sorting function for bound directives. |
||
*/ |
||
function byPriority(a, b) { |
||
var diff = b.priority - a.priority; |
||
if (diff !== 0) return diff; |
||
if (a.name !== b.name) return (a.name < b.name) ? -1 : 1; |
||
return a.index - b.index; |
||
} |
||
|
||
|
||
function assertNoDuplicate(what, previousDirective, directive, element) { |
||
if (previousDirective) { |
||
throw $compileMinErr('multidir', 'Multiple directives [{0}, {1}] asking for {2} on: {3}', |
||
previousDirective.name, directive.name, what, startingTag(element)); |
||
} |
||
} |
||
|
||
|
||
function addTextInterpolateDirective(directives, text) { |
||
var interpolateFn = $interpolate(text, true); |
||
if (interpolateFn) { |
||
directives.push({ |
||
priority: 0, |
||
compile: valueFn(function textInterpolateLinkFn(scope, node) { |
||
var parent = node.parent(), |
||
bindings = parent.data('$binding') || []; |
||
bindings.push(interpolateFn); |
||
safeAddClass(parent.data('$binding', bindings), 'ng-binding'); |
||
scope.$watch(interpolateFn, function interpolateFnWatchAction(value) { |
||
node[0].nodeValue = value; |
||
}); |
||
}) |
||
}); |
||
} |
||
} |
||
|
||
|
||
function getTrustedContext(node, attrNormalizedName) { |
||
if (attrNormalizedName == "srcdoc") { |
||
return $sce.HTML; |
||
} |
||
var tag = nodeName_(node); |
||
// maction[xlink:href] can source SVG. It's not limited to <maction>. |
||
if (attrNormalizedName == "xlinkHref" || |
||
(tag == "FORM" && attrNormalizedName == "action") || |
||
(tag != "IMG" && (attrNormalizedName == "src" || |
||
attrNormalizedName == "ngSrc"))) { |
||
return $sce.RESOURCE_URL; |
||
} |
||
} |
||
|
||
|
||
function addAttrInterpolateDirective(node, directives, value, name) { |
||
var interpolateFn = $interpolate(value, true); |
||
|
||
// no interpolation found -> ignore |
||
if (!interpolateFn) return; |
||
|
||
|
||
if (name === "multiple" && nodeName_(node) === "SELECT") { |
||
throw $compileMinErr("selmulti", |
||
"Binding to the 'multiple' attribute is not supported. Element: {0}", |
||
startingTag(node)); |
||
} |
||
|
||
directives.push({ |
||
priority: 100, |
||
compile: function() { |
||
return { |
||
pre: function attrInterpolatePreLinkFn(scope, element, attr) { |
||
var $$observers = (attr.$$observers || (attr.$$observers = {})); |
||
|
||
if (EVENT_HANDLER_ATTR_REGEXP.test(name)) { |
||
throw $compileMinErr('nodomevents', |
||
"Interpolations for HTML DOM event attributes are disallowed. Please use the " + |
||
"ng- versions (such as ng-click instead of onclick) instead."); |
||
} |
||
|
||
// we need to interpolate again, in case the attribute value has been updated |
||
// (e.g. by another directive's compile function) |
||
interpolateFn = $interpolate(attr[name], true, getTrustedContext(node, name)); |
||
|
||
// if attribute was updated so that there is no interpolation going on we don't want to |
||
// register any observers |
||
if (!interpolateFn) return; |
||
|
||
// TODO(i): this should likely be attr.$set(name, iterpolateFn(scope) so that we reset the |
||
// actual attr value |
||
attr[name] = interpolateFn(scope); |
||
($$observers[name] || ($$observers[name] = [])).$$inter = true; |
||
(attr.$$observers && attr.$$observers[name].$$scope || scope). |
||
$watch(interpolateFn, function interpolateFnWatchAction(newValue, oldValue) { |
||
//special case for class attribute addition + removal |
||
//so that class changes can tap into the animation |
||
//hooks provided by the $animate service. Be sure to |
||
//skip animations when the first digest occurs (when |
||
//both the new and the old values are the same) since |
||
//the CSS classes are the non-interpolated values |
||
if(name === 'class' && newValue != oldValue) { |
||
attr.$updateClass(newValue, oldValue); |
||
} else { |
||
attr.$set(name, newValue); |
||
} |
||
}); |
||
} |
||
}; |
||
} |
||
}); |
||
} |
||
|
||
|
||
/** |
||
* This is a special jqLite.replaceWith, which can replace items which |
||
* have no parents, provided that the containing jqLite collection is provided. |
||
* |
||
* @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes |
||
* in the root of the tree. |
||
* @param {JqLite} elementsToRemove The jqLite element which we are going to replace. We keep |
||
* the shell, but replace its DOM node reference. |
||
* @param {Node} newNode The new DOM node. |
||
*/ |
||
function replaceWith($rootElement, elementsToRemove, newNode) { |
||
var firstElementToRemove = elementsToRemove[0], |
||
removeCount = elementsToRemove.length, |
||
parent = firstElementToRemove.parentNode, |
||
i, ii; |
||
|
||
if ($rootElement) { |
||
for(i = 0, ii = $rootElement.length; i < ii; i++) { |
||
if ($rootElement[i] == firstElementToRemove) { |
||
$rootElement[i++] = newNode; |
||
for (var j = i, j2 = j + removeCount - 1, |
||
jj = $rootElement.length; |
||
j < jj; j++, j2++) { |
||
if (j2 < jj) { |
||
$rootElement[j] = $rootElement[j2]; |
||
} else { |
||
delete $rootElement[j]; |
||
} |
||
} |
||
$rootElement.length -= removeCount - 1; |
||
break; |
||
} |
||
} |
||
} |
||
|
||
if (parent) { |
||
parent.replaceChild(newNode, firstElementToRemove); |
||
} |
||
var fragment = document.createDocumentFragment(); |
||
fragment.appendChild(firstElementToRemove); |
||
newNode[jqLite.expando] = firstElementToRemove[jqLite.expando]; |
||
for (var k = 1, kk = elementsToRemove.length; k < kk; k++) { |
||
var element = elementsToRemove[k]; |
||
jqLite(element).remove(); // must do this way to clean up expando |
||
fragment.appendChild(element); |
||
delete elementsToRemove[k]; |
||
} |
||
|
||
elementsToRemove[0] = newNode; |
||
elementsToRemove.length = 1; |
||
} |
||
|
||
|
||
function cloneAndAnnotateFn(fn, annotation) { |
||
return extend(function() { return fn.apply(null, arguments); }, fn, annotation); |
||
} |
||
}]; |
||
} |
||
|
||
var PREFIX_REGEXP = /^(x[\:\-_]|data[\:\-_])/i; |
||
/** |
||
* Converts all accepted directives format into proper directive name. |
||
* All of these will become 'myDirective': |
||
* my:Directive |
||
* my-directive |
||
* x-my-directive |
||
* data-my:directive |
||
* |
||
* Also there is special case for Moz prefix starting with upper case letter. |
||
* @param name Name to normalize |
||
*/ |
||
function directiveNormalize(name) { |
||
return camelCase(name.replace(PREFIX_REGEXP, '')); |
||
} |
||
|
||
/** |
||
* @ngdoc object |
||
* @name ng.$compile.directive.Attributes |
||
* |
||
* @description |
||
* A shared object between directive compile / linking functions which contains normalized DOM |
||
* element attributes. The values reflect current binding state `{{ }}`. The normalization is |
||
* needed since all of these are treated as equivalent in Angular: |
||
* |
||
* <span ng:bind="a" ng-bind="a" data-ng-bind="a" x-ng-bind="a"> |
||
*/ |
||
|
||
/** |
||
* @ngdoc property |
||
* @name ng.$compile.directive.Attributes#$attr |
||
* @propertyOf ng.$compile.directive.Attributes |
||
* @returns {object} A map of DOM element attribute names to the normalized name. This is |
||
* needed to do reverse lookup from normalized name back to actual name. |
||
*/ |
||
|
||
|
||
/** |
||
* @ngdoc function |
||
* @name ng.$compile.directive.Attributes#$set |
||
* @methodOf ng.$compile.directive.Attributes |
||
* @function |
||
* |
||
* @description |
||
* Set DOM element attribute value. |
||
* |
||
* |
||
* @param {string} name Normalized element attribute name of the property to modify. The name is |
||
* reverse-translated using the {@link ng.$compile.directive.Attributes#$attr $attr} |
||
* property to the original name. |
||
* @param {string} value Value to set the attribute to. The value can be an interpolated string. |
||
*/ |
||
|
||
|
||
|
||
/** |
||
* Closure compiler type information |
||
*/ |
||
|
||
function nodesetLinkingFn( |
||
/* angular.Scope */ scope, |
||
/* NodeList */ nodeList, |
||
/* Element */ rootElement, |
||
/* function(Function) */ boundTranscludeFn |
||
){} |
||
|
||
function directiveLinkingFn( |
||
/* nodesetLinkingFn */ nodesetLinkingFn, |
||
/* angular.Scope */ scope, |
||
/* Node */ node, |
||
/* Element */ rootElement, |
||
/* function(Function) */ boundTranscludeFn |
||
){} |
||
|
||
function tokenDifference(str1, str2) { |
||
var values = '', |
||
tokens1 = str1.split(/\s+/), |
||
tokens2 = str2.split(/\s+/); |
||
|
||
outer: |
||
for(var i = 0; i < tokens1.length; i++) { |
||
var token = tokens1[i]; |
||
for(var j = 0; j < tokens2.length; j++) { |
||
if(token == tokens2[j]) continue outer; |
||
} |
||
values += (values.length > 0 ? ' ' : '') + token; |
||
} |
||
return values; |
||
} |
||
|
||
/** |
||
* @ngdoc object |
||
* @name ng.$controllerProvider |
||
* @description |
||
* The {@link ng.$controller $controller service} is used by Angular to create new |
||
* controllers. |
||
* |
||
* This provider allows controller registration via the |
||
* {@link ng.$controllerProvider#methods_register register} method. |
||
*/ |
||
function $ControllerProvider() { |
||
var controllers = {}, |
||
CNTRL_REG = /^(\S+)(\s+as\s+(\w+))?$/; |
||
|
||
|
||
/** |
||
* @ngdoc function |
||
* @name ng.$controllerProvider#register |
||
* @methodOf ng.$controllerProvider |
||
* @param {string|Object} name Controller name, or an object map of controllers where the keys are |
||
* the names and the values are the constructors. |
||
* @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI |
||
* annotations in the array notation). |
||
*/ |
||
this.register = function(name, constructor) { |
||
assertNotHasOwnProperty(name, 'controller'); |
||
if (isObject(name)) { |
||
extend(controllers, name); |
||
} else { |
||
controllers[name] = constructor; |
||
} |
||
}; |
||
|
||
|
||
this.$get = ['$injector', '$window', function($injector, $window) { |
||
|
||
/** |
||
* @ngdoc function |
||
* @name ng.$controller |
||
* @requires $injector |
||
* |
||
* @param {Function|string} constructor If called with a function then it's considered to be the |
||
* controller constructor function. Otherwise it's considered to be a string which is used |
||
* to retrieve the controller constructor using the following steps: |
||
* |
||
* * check if a controller with given name is registered via `$controllerProvider` |
||
* * check if evaluating the string on the current scope returns a constructor |
||
* * check `window[constructor]` on the global `window` object |
||
* |
||
* @param {Object} locals Injection locals for Controller. |
||
* @return {Object} Instance of given controller. |
||
* |
||
* @description |
||
* `$controller` service is responsible for instantiating controllers. |
||
* |
||
* It's just a simple call to {@link AUTO.$injector $injector}, but extracted into |
||
* a service, so that one can override this service with {@link https://gist.github.com/1649788 |
||
* BC version}. |
||
*/ |
||
return function(expression, locals) { |
||
var instance, match, constructor, identifier; |
||
|
||
if(isString(expression)) { |
||
match = expression.match(CNTRL_REG), |
||
constructor = match[1], |
||
identifier = match[3]; |
||
expression = controllers.hasOwnProperty(constructor) |
||
? controllers[constructor] |
||
: getter(locals.$scope, constructor, true) || getter($window, constructor, true); |
||
|
||
assertArgFn(expression, constructor, true); |
||
} |
||
|
||
instance = $injector.instantiate(expression, locals); |
||
|
||
if (identifier) { |
||
if (!(locals && typeof locals.$scope == 'object')) { |
||
throw minErr('$controller')('noscp', |
||
"Cannot export controller '{0}' as '{1}'! No $scope object provided via `locals`.", |
||
constructor || expression.name, identifier); |
||
} |
||
|
||
locals.$scope[identifier] = instance; |
||
} |
||
|
||
return instance; |
||
}; |
||
}]; |
||
} |
||
|
||
/** |
||
* @ngdoc object |
||
* @name ng.$document |
||
* @requires $window |
||
* |
||
* @description |
||
* A {@link angular.element jQuery or jqLite} wrapper for the browser's `window.document` object. |
||
*/ |
||
function $DocumentProvider(){ |
||
this.$get = ['$window', function(window){ |
||
return jqLite(window.document); |
||
}]; |
||
} |
||
|
||
/** |
||
* @ngdoc function |
||
* @name ng.$exceptionHandler |
||
* @requires $log |
||
* |
||
* @description |
||
* Any uncaught exception in angular expressions is delegated to this service. |
||
* The default implementation simply delegates to `$log.error` which logs it into |
||
* the browser console. |
||
* |
||
* In unit tests, if `angular-mocks.js` is loaded, this service is overridden by |
||
* {@link ngMock.$exceptionHandler mock $exceptionHandler} which aids in testing. |
||
* |
||
* ## Example: |
||
* |
||
* <pre> |
||
* angular.module('exceptionOverride', []).factory('$exceptionHandler', function () { |
||
* return function (exception, cause) { |
||
* exception.message += ' (caused by "' + cause + '")'; |
||
* throw exception; |
||
* }; |
||
* }); |
||
* </pre> |
||
* |
||
* This example will override the normal action of `$exceptionHandler`, to make angular |
||
* exceptions fail hard when they happen, instead of just logging to the console. |
||
* |
||
* @param {Error} exception Exception associated with the error. |
||
* @param {string=} cause optional information about the context in which |
||
* the error was thrown. |
||
* |
||
*/ |
||
function $ExceptionHandlerProvider() { |
||
this.$get = ['$log', function($log) { |
||
return function(exception, cause) { |
||
$log.error.apply($log, arguments); |
||
}; |
||
}]; |
||
} |
||
|
||
/** |
||
* Parse headers into key value object |
||
* |
||
* @param {string} headers Raw headers as a string |
||
* @returns {Object} Parsed headers as key value object |
||
*/ |
||
function parseHeaders(headers) { |
||
var parsed = {}, key, val, i; |
||
|
||
if (!headers) return parsed; |
||
|
||
forEach(headers.split('\n'), function(line) { |
||
i = line.indexOf(':'); |
||
key = lowercase(trim(line.substr(0, i))); |
||
val = trim(line.substr(i + 1)); |
||
|
||
if (key) { |
||
if (parsed[key]) { |
||
parsed[key] += ', ' + val; |
||
} else { |
||
parsed[key] = val; |
||
} |
||
} |
||
}); |
||
|
||
return parsed; |
||
} |
||
|
||
|
||
/** |
||
* Returns a function that provides access to parsed headers. |
||
* |
||
* Headers are lazy parsed when first requested. |
||
* @see parseHeaders |
||
* |
||
* @param {(string|Object)} headers Headers to provide access to. |
||
* @returns {function(string=)} Returns a getter function which if called with: |
||
* |
||
* - if called with single an argument returns a single header value or null |
||
* - if called with no arguments returns an object containing all headers. |
||
*/ |
||
function headersGetter(headers) { |
||
var headersObj = isObject(headers) ? headers : undefined; |
||
|
||
return function(name) { |
||
if (!headersObj) headersObj = parseHeaders(headers); |
||
|
||
if (name) { |
||
return headersObj[lowercase(name)] || null; |
||
} |
||
|
||
return headersObj; |
||
}; |
||
} |
||
|
||
|
||
/** |
||
* Chain all given functions |
||
* |
||
* This function is used for both request and response transforming |
||
* |
||
* @param {*} data Data to transform. |
||
* @param {function(string=)} headers Http headers getter fn. |
||
* @param {(function|Array.<function>)} fns Function or an array of functions. |
||
* @returns {*} Transformed data. |
||
*/ |
||
function transformData(data, headers, fns) { |
||
if (isFunction(fns)) |
||
return fns(data, headers); |
||
|
||
forEach(fns, function(fn) { |
||
data = fn(data, headers); |
||
}); |
||
|
||
return data; |
||
} |
||
|
||
|
||
function isSuccess(status) { |
||
return 200 <= status && status < 300; |
||
} |
||
|
||
|
||
function $HttpProvider() { |
||
var JSON_START = /^\s*(\[|\{[^\{])/, |
||
JSON_END = /[\}\]]\s*$/, |
||
PROTECTION_PREFIX = /^\)\]\}',?\n/, |
||
CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': 'application/json;charset=utf-8'}; |
||
|
||
var defaults = this.defaults = { |
||
// transform incoming response data |
||
transformResponse: [function(data) { |
||
if (isString(data)) { |
||
// strip json vulnerability protection prefix |
||
data = data.replace(PROTECTION_PREFIX, ''); |
||
if (JSON_START.test(data) && JSON_END.test(data)) |
||
data = fromJson(data); |
||
} |
||
return data; |
||
}], |
||
|
||
// transform outgoing request data |
||
transformRequest: [function(d) { |
||
return isObject(d) && !isFile(d) ? toJson(d) : d; |
||
}], |
||
|
||
// default headers |
||
headers: { |
||
common: { |
||
'Accept': 'application/json, text/plain, */*' |
||
}, |
||
post: copy(CONTENT_TYPE_APPLICATION_JSON), |
||
put: copy(CONTENT_TYPE_APPLICATION_JSON), |
||
patch: copy(CONTENT_TYPE_APPLICATION_JSON) |
||
}, |
||
|
||
xsrfCookieName: 'XSRF-TOKEN', |
||
xsrfHeaderName: 'X-XSRF-TOKEN' |
||
}; |
||
|
||
/** |
||
* Are ordered by request, i.e. they are applied in the same order as the |
||
* array, on request, but reverse order, on response. |
||
*/ |
||
var interceptorFactories = this.interceptors = []; |
||
|
||
/** |
||
* For historical reasons, response interceptors are ordered by the order in which |
||
* they are applied to the response. (This is the opposite of interceptorFactories) |
||
*/ |
||
var responseInterceptorFactories = this.responseInterceptors = []; |
||
|
||
this.$get = ['$httpBackend', '$browser', '$cacheFactory', '$rootScope', '$q', '$injector', |
||
function($httpBackend, $browser, $cacheFactory, $rootScope, $q, $injector) { |
||
|
||
var defaultCache = $cacheFactory('$http'); |
||
|
||
/** |
||
* Interceptors stored in reverse order. Inner interceptors before outer interceptors. |
||
* The reversal is needed so that we can build up the interception chain around the |
||
* server request. |
||
*/ |
||
var reversedInterceptors = []; |
||
|
||
forEach(interceptorFactories, function(interceptorFactory) { |
||
reversedInterceptors.unshift(isString(interceptorFactory) |
||
? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory)); |
||
}); |
||
|
||
forEach(responseInterceptorFactories, function(interceptorFactory, index) { |
||
var responseFn = isString(interceptorFactory) |
||
? $injector.get(interceptorFactory) |
||
: $injector.invoke(interceptorFactory); |
||
|
||
/** |
||
* Response interceptors go before "around" interceptors (no real reason, just |
||
* had to pick one.) But they are already reversed, so we can't use unshift, hence |
||
* the splice. |
||
*/ |
||
reversedInterceptors.splice(index, 0, { |
||
response: function(response) { |
||
return responseFn($q.when(response)); |
||
}, |
||
responseError: function(response) { |
||
return responseFn($q.reject(response)); |
||
} |
||
}); |
||
}); |
||
|
||
|
||
/** |
||
* @ngdoc function |
||
* @name ng.$http |
||
* @requires $httpBackend |
||
* @requires $browser |
||
* @requires $cacheFactory |
||
* @requires $rootScope |
||
* @requires $q |
||
* @requires $injector |
||
* |
||
* @description |
||
* The `$http` service is a core Angular service that facilitates communication with the remote |
||
* HTTP servers via the browser's {@link https://developer.mozilla.org/en/xmlhttprequest |
||
* XMLHttpRequest} object or via {@link http://en.wikipedia.org/wiki/JSONP JSONP}. |
||
* |
||
* For unit testing applications that use `$http` service, see |
||
* {@link ngMock.$httpBackend $httpBackend mock}. |
||
* |
||
* For a higher level of abstraction, please check out the {@link ngResource.$resource |
||
* $resource} service. |
||
* |
||
* The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by |
||
* the $q service. While for simple usage patterns this doesn't matter much, for advanced usage |
||
* it is important to familiarize yourself with these APIs and the guarantees they provide. |
||
* |
||
* |
||
* # General usage |
||
* The `$http` service is a function which takes a single argument — a configuration object — |
||
* that is used to generate an HTTP request and returns a {@link ng.$q promise} |
||
* with two $http specific methods: `success` and `error`. |
||
* |
||
* <pre> |
||
* $http({method: 'GET', url: '/someUrl'}). |
||
* success(function(data, status, headers, config) { |
||
* // this callback will be called asynchronously |
||
* // when the response is available |
||
* }). |
||
* error(function(data, status, headers, config) { |
||
* // called asynchronously if an error occurs |
||
* // or server returns response with an error status. |
||
* }); |
||
* </pre> |
||
* |
||
* Since the returned value of calling the $http function is a `promise`, you can also use |
||
* the `then` method to register callbacks, and these callbacks will receive a single argument – |
||
* an object representing the response. See the API signature and type info below for more |
||
* details. |
||
* |
||
* A response status code between 200 and 299 is considered a success status and |
||
* will result in the success callback being called. Note that if the response is a redirect, |
||
* XMLHttpRequest will transparently follow it, meaning that the error callback will not be |
||
* called for such responses. |
||
* |
||
* # Calling $http from outside AngularJS |
||
* The `$http` service will not actually send the request until the next `$digest()` is |
||
* executed. Normally this is not an issue, since almost all the time your call to `$http` will |
||
* be from within a `$apply()` block. |
||
* If you are calling `$http` from outside Angular, then you should wrap it in a call to |
||
* `$apply` to cause a $digest to occur and also to handle errors in the block correctly. |
||
* |
||
* ``` |
||
* $scope.$apply(function() { |
||
* $http(...); |
||
* }); |
||
* ``` |
||
* |
||
* # Writing Unit Tests that use $http |
||
* When unit testing you are mostly responsible for scheduling the `$digest` cycle. If you do |
||
* not trigger a `$digest` before calling `$httpBackend.flush()` then the request will not have |
||
* been made and `$httpBackend.expect(...)` expectations will fail. The solution is to run the |
||
* code that calls the `$http()` method inside a $apply block as explained in the previous |
||
* section. |
||
* |
||
* ``` |
||
* $httpBackend.expectGET(...); |
||
* $scope.$apply(function() { |
||
* $http.get(...); |
||
* }); |
||
* $httpBackend.flush(); |
||
* ``` |
||
* |
||
* # Shortcut methods |
||
* |
||
* Since all invocations of the $http service require passing in an HTTP method and URL, and |
||
* POST/PUT requests require request data to be provided as well, shortcut methods |
||
* were created: |
||
* |
||
* <pre> |
||
* $http.get('/someUrl').success(successCallback); |
||
* $http.post('/someUrl', data).success(successCallback); |
||
* </pre> |
||
* |
||
* Complete list of shortcut methods: |
||
* |
||
* - {@link ng.$http#methods_get $http.get} |
||
* - {@link ng.$http#methods_head $http.head} |
||
* - {@link ng.$http#methods_post $http.post} |
||
* - {@link ng.$http#methods_put $http.put} |
||
* - {@link ng.$http#methods_delete $http.delete} |
||
* - {@link ng.$http#methods_jsonp $http.jsonp} |
||
* |
||
* |
||
* # Setting HTTP Headers |
||
* |
||
* The $http service will automatically add certain HTTP headers to all requests. These defaults |
||
* can be fully configured by accessing the `$httpProvider.defaults.headers` configuration |
||
* object, which currently contains this default configuration: |
||
* |
||
* - `$httpProvider.defaults.headers.common` (headers that are common for all requests): |
||
* - `Accept: application/json, text/plain, * / *` |
||
* - `$httpProvider.defaults.headers.post`: (header defaults for POST requests) |
||
* - `Content-Type: application/json` |
||
* - `$httpProvider.defaults.headers.put` (header defaults for PUT requests) |
||
* - `Content-Type: application/json` |
||
* |
||
* To add or overwrite these defaults, simply add or remove a property from these configuration |
||
* objects. To add headers for an HTTP method other than POST or PUT, simply add a new object |
||
* with the lowercased HTTP method name as the key, e.g. |
||
* `$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }. |
||
* |
||
* The defaults can also be set at runtime via the `$http.defaults` object in the same |
||
* fashion. For example: |
||
* |
||
* ``` |
||
* module.run(function($http) { |
||
* $http.defaults.headers.common.Authentication = 'Basic YmVlcDpib29w' |
||
* }); |
||
* ``` |
||
* |
||
* In addition, you can supply a `headers` property in the config object passed when |
||
* calling `$http(config)`, which overrides the defaults without changing them globally. |
||
* |
||
* |
||
* # Transforming Requests and Responses |
||
* |
||
* Both requests and responses can be transformed using transform functions. By default, Angular |
||
* applies these transformations: |
||
* |
||
* Request transformations: |
||
* |
||
* - If the `data` property of the request configuration object contains an object, serialize it |
||
* into JSON format. |
||
* |
||
* Response transformations: |
||
* |
||
* - If XSRF prefix is detected, strip it (see Security Considerations section below). |
||
* - If JSON response is detected, deserialize it using a JSON parser. |
||
* |
||
* To globally augment or override the default transforms, modify the |
||
* `$httpProvider.defaults.transformRequest` and `$httpProvider.defaults.transformResponse` |
||
* properties. These properties are by default an array of transform functions, which allows you |
||
* to `push` or `unshift` a new transformation function into the transformation chain. You can |
||
* also decide to completely override any default transformations by assigning your |
||
* transformation functions to these properties directly without the array wrapper. These defaults |
||
* are again available on the $http factory at run-time, which may be useful if you have run-time |
||
* services you wish to be involved in your transformations. |
||
* |
||
* Similarly, to locally override the request/response transforms, augment the |
||
* `transformRequest` and/or `transformResponse` properties of the configuration object passed |
||
* into `$http`. |
||
* |
||
* |
||
* # Caching |
||
* |
||
* To enable caching, set the request configuration `cache` property to `true` (to use default |
||
* cache) or to a custom cache object (built with {@link ng.$cacheFactory `$cacheFactory`}). |
||
* When the cache is enabled, `$http` stores the response from the server in the specified |
||
* cache. The next time the same request is made, the response is served from the cache without |
||
* sending a request to the server. |
||
* |
||
* Note that even if the response is served from cache, delivery of the data is asynchronous in |
||
* the same way that real requests are. |
||
* |
||
* If there are multiple GET requests for the same URL that should be cached using the same |
||
* cache, but the cache is not populated yet, only one request to the server will be made and |
||
* the remaining requests will be fulfilled using the response from the first request. |
||
* |
||
* You can change the default cache to a new object (built with |
||
* {@link ng.$cacheFactory `$cacheFactory`}) by updating the |
||
* {@link ng.$http#properties_defaults `$http.defaults.cache`} property. All requests who set |
||
* their `cache` property to `true` will now use this cache object. |
||
* |
||
* If you set the default cache to `false` then only requests that specify their own custom |
||
* cache object will be cached. |
||
* |
||
* # Interceptors |
||
* |
||
* Before you start creating interceptors, be sure to understand the |
||
* {@link ng.$q $q and deferred/promise APIs}. |
||
* |
||
* For purposes of global error handling, authentication, or any kind of synchronous or |
||
* asynchronous pre-processing of request or postprocessing of responses, it is desirable to be |
||
* able to intercept requests before they are handed to the server and |
||
* responses before they are handed over to the application code that |
||
* initiated these requests. The interceptors leverage the {@link ng.$q |
||
* promise APIs} to fulfill this need for both synchronous and asynchronous pre-processing. |
||
* |
||
* The interceptors are service factories that are registered with the `$httpProvider` by |
||
* adding them to the `$httpProvider.interceptors` array. The factory is called and |
||
* injected with dependencies (if specified) and returns the interceptor. |
||
* |
||
* There are two kinds of interceptors (and two kinds of rejection interceptors): |
||
* |
||
* * `request`: interceptors get called with http `config` object. The function is free to |
||
* modify the `config` or create a new one. The function needs to return the `config` |
||
* directly or as a promise. |
||
* * `requestError`: interceptor gets called when a previous interceptor threw an error or |
||
* resolved with a rejection. |
||
* * `response`: interceptors get called with http `response` object. The function is free to |
||
* modify the `response` or create a new one. The function needs to return the `response` |
||
* directly or as a promise. |
||
* * `responseError`: interceptor gets called when a previous interceptor threw an error or |
||
* resolved with a rejection. |
||
* |
||
* |
||
* <pre> |
||
* // register the interceptor as a service |
||
* $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) { |
||
* return { |
||
* // optional method |
||
* 'request': function(config) { |
||
* // do something on success |
||
* return config || $q.when(config); |
||
* }, |
||
* |
||
* // optional method |
||
* 'requestError': function(rejection) { |
||
* // do something on error |
||
* if (canRecover(rejection)) { |
||
* return responseOrNewPromise |
||
* } |
||
* return $q.reject(rejection); |
||
* }, |
||
* |
||
* |
||
* |
||
* // optional method |
||
* 'response': function(response) { |
||
* // do something on success |
||
* return response || $q.when(response); |
||
* }, |
||
* |
||
* // optional method |
||
* 'responseError': function(rejection) { |
||
* // do something on error |
||
* if (canRecover(rejection)) { |
||
* return responseOrNewPromise |
||
* } |
||
* return $q.reject(rejection); |
||
* } |
||
* }; |
||
* }); |
||
* |
||
* $httpProvider.interceptors.push('myHttpInterceptor'); |
||
* |
||
* |
||
* // alternatively, register the interceptor via an anonymous factory |
||
* $httpProvider.interceptors.push(function($q, dependency1, dependency2) { |
||
* return { |
||
* 'request': function(config) { |
||
* // same as above |
||
* }, |
||
* |
||
* 'response': function(response) { |
||
* // same as above |
||
* } |
||
* }; |
||
* }); |
||
* </pre> |
||
* |
||
* # Response interceptors (DEPRECATED) |
||
* |
||
* Before you start creating interceptors, be sure to understand the |
||
* {@link ng.$q $q and deferred/promise APIs}. |
||
* |
||
* For purposes of global error handling, authentication or any kind of synchronous or |
||
* asynchronous preprocessing of received responses, it is desirable to be able to intercept |
||
* responses for http requests before they are handed over to the application code that |
||
* initiated these requests. The response interceptors leverage the {@link ng.$q |
||
* promise apis} to fulfil this need for both synchronous and asynchronous preprocessing. |
||
* |
||
* The interceptors are service factories that are registered with the $httpProvider by |
||
* adding them to the `$httpProvider.responseInterceptors` array. The factory is called and |
||
* injected with dependencies (if specified) and returns the interceptor — a function that |
||
* takes a {@link ng.$q promise} and returns the original or a new promise. |
||
* |
||
* <pre> |
||
* // register the interceptor as a service |
||
* $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) { |
||
* return function(promise) { |
||
* return promise.then(function(response) { |
||
* // do something on success |
||
* return response; |
||
* }, function(response) { |
||
* // do something on error |
||
* if (canRecover(response)) { |
||
* return responseOrNewPromise |
||
* } |
||
* return $q.reject(response); |
||
* }); |
||
* } |
||
* }); |
||
* |
||
* $httpProvider.responseInterceptors.push('myHttpInterceptor'); |
||
* |
||
* |
||
* // register the interceptor via an anonymous factory |
||
* $httpProvider.responseInterceptors.push(function($q, dependency1, dependency2) { |
||
* return function(promise) { |
||
* // same as above |
||
* } |
||
* }); |
||
* </pre> |
||
* |
||
* |
||
* # Security Considerations |
||
* |
||
* When designing web applications, consider security threats from: |
||
* |
||
* - {@link http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx |
||
* JSON vulnerability} |
||
* - {@link http://en.wikipedia.org/wiki/Cross-site_request_forgery XSRF} |
||
* |
||
* Both server and the client must cooperate in order to eliminate these threats. Angular comes |
||
* pre-configured with strategies that address these issues, but for this to work backend server |
||
* cooperation is required. |
||
* |
||
* ## JSON Vulnerability Protection |
||
* |
||
* A {@link http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx |
||
* JSON vulnerability} allows third party website to turn your JSON resource URL into |
||
* {@link http://en.wikipedia.org/wiki/JSONP JSONP} request under some conditions. To |
||
* counter this your server can prefix all JSON requests with following string `")]}',\n"`. |
||
* Angular will automatically strip the prefix before processing it as JSON. |
||
* |
||
* For example if your server needs to return: |
||
* <pre> |
||
* ['one','two'] |
||
* </pre> |
||
* |
||
* which is vulnerable to attack, your server can return: |
||
* <pre> |
||
* )]}', |
||
* ['one','two'] |
||
* </pre> |
||
* |
||
* Angular will strip the prefix, before processing the JSON. |
||
* |
||
* |
||
* ## Cross Site Request Forgery (XSRF) Protection |
||
* |
||
* {@link http://en.wikipedia.org/wiki/Cross-site_request_forgery XSRF} is a technique by which |
||
* an unauthorized site can gain your user's private data. Angular provides a mechanism |
||
* to counter XSRF. When performing XHR requests, the $http service reads a token from a cookie |
||
* (by default, `XSRF-TOKEN`) and sets it as an HTTP header (`X-XSRF-TOKEN`). Since only |
||
* JavaScript that runs on your domain could read the cookie, your server can be assured that |
||
* the XHR came from JavaScript running on your domain. The header will not be set for |
||
* cross-domain requests. |
||
* |
||
* To take advantage of this, your server needs to set a token in a JavaScript readable session |
||
* cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the |
||
* server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure |
||
* that only JavaScript running on your domain could have sent the request. The token must be |
||
* unique for each user and must be verifiable by the server (to prevent the JavaScript from |
||
* making up its own tokens). We recommend that the token is a digest of your site's |
||
* authentication cookie with a {@link https://en.wikipedia.org/wiki/Salt_(cryptography) salt} |
||
* for added security. |
||
* |
||
* The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName |
||
* properties of either $httpProvider.defaults at config-time, $http.defaults at run-time, |
||
* or the per-request config object. |
||
* |
||
* |
||
* @param {object} config Object describing the request to be made and how it should be |
||
* processed. The object has following properties: |
||
* |
||
* - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc) |
||
* - **url** – `{string}` – Absolute or relative URL of the resource that is being requested. |
||
* - **params** – `{Object.<string|Object>}` – Map of strings or objects which will be turned |
||
* to `?key1=value1&key2=value2` after the url. If the value is not a string, it will be |
||
* JSONified. |
||
* - **data** – `{string|Object}` – Data to be sent as the request message data. |
||
* - **headers** – `{Object}` – Map of strings or functions which return strings representing |
||
* HTTP headers to send to the server. If the return value of a function is null, the |
||
* header will not be sent. |
||
* - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token. |
||
* - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token. |
||
* - **transformRequest** – |
||
* `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` – |
||
* transform function or an array of such functions. The transform function takes the http |
||
* request body and headers and returns its transformed (typically serialized) version. |
||
* - **transformResponse** – |
||
* `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` – |
||
* transform function or an array of such functions. The transform function takes the http |
||
* response body and headers and returns its transformed (typically deserialized) version. |
||
* - **cache** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the |
||
* GET request, otherwise if a cache instance built with |
||
* {@link ng.$cacheFactory $cacheFactory}, this cache will be used for |
||
* caching. |
||
* - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise} |
||
* that should abort the request when resolved. |
||
* - **withCredentials** - `{boolean}` - whether to to set the `withCredentials` flag on the |
||
* XHR object. See {@link https://developer.mozilla.org/en/http_access_control#section_5 |
||
* requests with credentials} for more information. |
||
* - **responseType** - `{string}` - see {@link |
||
* https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#responseType requestType}. |
||
* |
||
* @returns {HttpPromise} Returns a {@link ng.$q promise} object with the |
||
* standard `then` method and two http specific methods: `success` and `error`. The `then` |
||
* method takes two arguments a success and an error callback which will be called with a |
||
* response object. The `success` and `error` methods take a single argument - a function that |
||
* will be called when the request succeeds or fails respectively. The arguments passed into |
||
* these functions are destructured representation of the response object passed into the |
||
* `then` method. The response object has these properties: |
||
* |
||
* - **data** – `{string|Object}` – The response body transformed with the transform |
||
* functions. |
||
* - **status** – `{number}` – HTTP status code of the response. |
||
* - **headers** – `{function([headerName])}` – Header getter function. |
||
* - **config** – `{Object}` – The configuration object that was used to generate the request. |
||
* |
||
* @property {Array.<Object>} pendingRequests Array of config objects for currently pending |
||
* requests. This is primarily meant to be used for debugging purposes. |
||
* |
||
* |
||
* @example |
||
<example> |
||
<file name="index.html"> |
||
<div ng-controller="FetchCtrl"> |
||
<select ng-model="method"> |
||
<option>GET</option> |
||
<option>JSONP</option> |
||
</select> |
||
<input type="text" ng-model="url" size="80"/> |
||
<button ng-click="fetch()">fetch</button><br> |
||
<button ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button> |
||
<button |
||
ng-click="updateModel('JSONP', |
||
'http://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero')"> |
||
Sample JSONP |
||
</button> |
||
<button |
||
ng-click="updateModel('JSONP', 'http://angularjs.org/doesntexist&callback=JSON_CALLBACK')"> |
||
Invalid JSONP |
||
</button> |
||
<pre>http status code: {{status}}</pre> |
||
<pre>http response data: {{data}}</pre> |
||
</div> |
||
</file> |
||
<file name="script.js"> |
||
function FetchCtrl($scope, $http, $templateCache) { |
||
$scope.method = 'GET'; |
||
$scope.url = 'http-hello.html'; |
||
|
||
$scope.fetch = function() { |
||
$scope.code = null; |
||
$scope.response = null; |
||
|
||
$http({method: $scope.method, url: $scope.url, cache: $templateCache}). |
||
success(function(data, status) { |
||
$scope.status = status; |
||
$scope.data = data; |
||
}). |
||
error(function(data, status) { |
||
$scope.data = data || "Request failed"; |
||
$scope.status = status; |
||
}); |
||
}; |
||
|
||
$scope.updateModel = function(method, url) { |
||
$scope.method = method; |
||
$scope.url = url; |
||
}; |
||
} |
||
</file> |
||
<file name="http-hello.html"> |
||
Hello, $http! |
||
</file> |
||
<file name="scenario.js"> |
||
it('should make an xhr GET request', function() { |
||
element(':button:contains("Sample GET")').click(); |
||
element(':button:contains("fetch")').click(); |
||
expect(binding('status')).toBe('200'); |
||
expect(binding('data')).toMatch(/Hello, \$http!/); |
||
}); |
||
|
||
it('should make a JSONP request to angularjs.org', function() { |
||
element(':button:contains("Sample JSONP")').click(); |
||
element(':button:contains("fetch")').click(); |
||
expect(binding('status')).toBe('200'); |
||
expect(binding('data')).toMatch(/Super Hero!/); |
||
}); |
||
|
||
it('should make JSONP request to invalid URL and invoke the error handler', |
||
function() { |
||
element(':button:contains("Invalid JSONP")').click(); |
||
element(':button:contains("fetch")').click(); |
||
expect(binding('status')).toBe('0'); |
||
expect(binding('data')).toBe('Request failed'); |
||
}); |
||
</file> |
||
</example> |
||
*/ |
||
function $http(requestConfig) { |
||
var config = { |
||
transformRequest: defaults.transformRequest, |
||
transformResponse: defaults.transformResponse |
||
}; |
||
var headers = mergeHeaders(requestConfig); |
||
|
||
extend(config, requestConfig); |
||
config.headers = headers; |
||
config.method = uppercase(config.method); |
||
|
||
var xsrfValue = urlIsSameOrigin(config.url) |
||
? $browser.cookies()[config.xsrfCookieName || defaults.xsrfCookieName] |
||
: undefined; |
||
if (xsrfValue) { |
||
headers[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue; |
||
} |
||
|
||
|
||
var serverRequest = function(config) { |
||
headers = config.headers; |
||
var reqData = transformData(config.data, headersGetter(headers), config.transformRequest); |
||
|
||
// strip content-type if data is undefined |
||
if (isUndefined(config.data)) { |
||
forEach(headers, function(value, header) { |
||
if (lowercase(header) === 'content-type') { |
||
delete headers[header]; |
||
} |
||
}); |
||
} |
||
|
||
if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) { |
||
config.withCredentials = defaults.withCredentials; |
||
} |
||
|
||
// send request |
||
return sendReq(config, reqData, headers).then(transformResponse, transformResponse); |
||
}; |
||
|
||
var chain = [serverRequest, undefined]; |
||
var promise = $q.when(config); |
||
|
||
// apply interceptors |
||
forEach(reversedInterceptors, function(interceptor) { |
||
if (interceptor.request || interceptor.requestError) { |
||
chain.unshift(interceptor.request, interceptor.requestError); |
||
} |
||
if (interceptor.response || interceptor.responseError) { |
||
chain.push(interceptor.response, interceptor.responseError); |
||
} |
||
}); |
||
|
||
while(chain.length) { |
||
var thenFn = chain.shift(); |
||
var rejectFn = chain.shift(); |
||
|
||
promise = promise.then(thenFn, rejectFn); |
||
} |
||
|
||
promise.success = function(fn) { |
||
promise.then(function(response) { |
||
fn(response.data, response.status, response.headers, config); |
||
}); |
||
return promise; |
||
}; |
||
|
||
promise.error = function(fn) { |
||
promise.then(null, function(response) { |
||
fn(response.data, response.status, response.headers, config); |
||
}); |
||
return promise; |
||
}; |
||
|
||
return promise; |
||
|
||
function transformResponse(response) { |
||
// make a copy since the response must be cacheable |
||
var resp = extend({}, response, { |
||
data: transformData(response.data, response.headers, config.transformResponse) |
||
}); |
||
return (isSuccess(response.status)) |
||
? resp |
||
: $q.reject(resp); |
||
} |
||
|
||
function mergeHeaders(config) { |
||
var defHeaders = defaults.headers, |
||
reqHeaders = extend({}, config.headers), |
||
defHeaderName, lowercaseDefHeaderName, reqHeaderName; |
||
|
||
defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]); |
||
|
||
// execute if header value is function |
||
execHeaders(defHeaders); |
||
execHeaders(reqHeaders); |
||
|
||
// using for-in instead of forEach to avoid unecessary iteration after header has been found |
||
defaultHeadersIteration: |
||
for (defHeaderName in defHeaders) { |
||
lowercaseDefHeaderName = lowercase(defHeaderName); |
||
|
||
for (reqHeaderName in reqHeaders) { |
||
if (lowercase(reqHeaderName) === lowercaseDefHeaderName) { |
||
continue defaultHeadersIteration; |
||
} |
||
} |
||
|
||
reqHeaders[defHeaderName] = defHeaders[defHeaderName]; |
||
} |
||
|
||
return reqHeaders; |
||
|
||
function execHeaders(headers) { |
||
var headerContent; |
||
|
||
forEach(headers, function(headerFn, header) { |
||
if (isFunction(headerFn)) { |
||
headerContent = headerFn(); |
||
if (headerContent != null) { |
||
headers[header] = headerContent; |
||
} else { |
||
delete headers[header]; |
||
} |
||
} |
||
}); |
||
} |
||
} |
||
} |
||
|
||
$http.pendingRequests = []; |
||
|
||
/** |
||
* @ngdoc method |
||
* @name ng.$http#get |
||
* @methodOf ng.$http |
||
* |
||
* @description |
||
* Shortcut method to perform `GET` request. |
||
* |
||
* @param {string} url Relative or absolute URL specifying the destination of the request |
||
* @param {Object=} config Optional configuration object |
||
* @returns {HttpPromise} Future object |
||
*/ |
||
|
||
/** |
||
* @ngdoc method |
||
* @name ng.$http#delete |
||
* @methodOf ng.$http |
||
* |
||
* @description |
||
* Shortcut method to perform `DELETE` request. |
||
* |
||
* @param {string} url Relative or absolute URL specifying the destination of the request |
||
* @param {Object=} config Optional configuration object |
||
* @returns {HttpPromise} Future object |
||
*/ |
||
|
||
/** |
||
* @ngdoc method |
||
* @name ng.$http#head |
||
* @methodOf ng.$http |
||
* |
||
* @description |
||
* Shortcut method to perform `HEAD` request. |
||
* |
||
* @param {string} url Relative or absolute URL specifying the destination of the request |
||
* @param {Object=} config Optional configuration object |
||
* @returns {HttpPromise} Future object |
||
*/ |
||
|
||
/** |
||
* @ngdoc method |
||
* @name ng.$http#jsonp |
||
* @methodOf ng.$http |
||
* |
||
* @description |
||
* Shortcut method to perform `JSONP` request. |
||
* |
||
* @param {string} url Relative or absolute URL specifying the destination of the request. |
||
* Should contain `JSON_CALLBACK` string. |
||
* @param {Object=} config Optional configuration object |
||
* @returns {HttpPromise} Future object |
||
*/ |
||
createShortMethods('get', 'delete', 'head', 'jsonp'); |
||
|
||
/** |
||
* @ngdoc method |
||
* @name ng.$http#post |
||
* @methodOf ng.$http |
||
* |
||
* @description |
||
* Shortcut method to perform `POST` request. |
||
* |
||
* @param {string} url Relative or absolute URL specifying the destination of the request |
||
* @param {*} data Request content |
||
* @param {Object=} config Optional configuration object |
||
* @returns {HttpPromise} Future object |
||
*/ |
||
|
||
/** |
||
* @ngdoc method |
||
* @name ng.$http#put |
||
* @methodOf ng.$http |
||
* |
||
* @description |
||
* Shortcut method to perform `PUT` request. |
||
* |
||
* @param {string} url Relative or absolute URL specifying the destination of the request |
||
* @param {*} data Request content |
||
* @param {Object=} config Optional configuration object |
||
* @returns {HttpPromise} Future object |
||
*/ |
||
createShortMethodsWithData('post', 'put'); |
||
|
||
/** |
||
* @ngdoc property |
||
* @name ng.$http#defaults |
||
* @propertyOf ng.$http |
||
* |
||
* @description |
||
* Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of |
||
* default headers, withCredentials as well as request and response transformations. |
||
* |
||
* See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above. |
||
*/ |
||
$http.defaults = defaults; |
||
|
||
|
||
return $http; |
||
|
||
|
||
function createShortMethods(names) { |
||
forEach(arguments, function(name) { |
||
$http[name] = function(url, config) { |
||
return $http(extend(config || {}, { |
||
method: name, |
||
url: url |
||
})); |
||
}; |
||
}); |
||
} |
||
|
||
|
||
function createShortMethodsWithData(name) { |
||
forEach(arguments, function(name) { |
||
$http[name] = function(url, data, config) { |
||
return $http(extend(config || {}, { |
||
method: name, |
||
url: url, |
||
data: data |
||
})); |
||
}; |
||
}); |
||
} |
||
|
||
|
||
/** |
||
* Makes the request. |
||
* |
||
* !!! ACCESSES CLOSURE VARS: |
||
* $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests |
||
*/ |
||
function sendReq(config, reqData, reqHeaders) { |
||
var deferred = $q.defer(), |
||
promise = deferred.promise, |
||
cache, |
||
cachedResp, |
||
url = buildUrl(config.url, config.params); |
||
|
||
$http.pendingRequests.push(config); |
||
promise.then(removePendingReq, removePendingReq); |
||
|
||
|
||
if ((config.cache || defaults.cache) && config.cache !== false && config.method == 'GET') { |
||
cache = isObject(config.cache) ? config.cache |
||
: isObject(defaults.cache) ? defaults.cache |
||
: defaultCache; |
||
} |
||
|
||
if (cache) { |
||
cachedResp = cache.get(url); |
||
if (isDefined(cachedResp)) { |
||
if (cachedResp.then) { |
||
// cached request has already been sent, but there is no response yet |
||
cachedResp.then(removePendingReq, removePendingReq); |
||
return cachedResp; |
||
} else { |
||
// serving from cache |
||
if (isArray(cachedResp)) { |
||
resolvePromise(cachedResp[1], cachedResp[0], copy(cachedResp[2])); |
||
} else { |
||
resolvePromise(cachedResp, 200, {}); |
||
} |
||
} |
||
} else { |
||
// put the promise for the non-transformed response into cache as a placeholder |
||
cache.put(url, promise); |
||
} |
||
} |
||
|
||
// if we won't have the response in cache, send the request to the backend |
||
if (isUndefined(cachedResp)) { |
||
$httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout, |
||
config.withCredentials, config.responseType); |
||
} |
||
|
||
return promise; |
||
|
||
|
||
/** |
||
* Callback registered to $httpBackend(): |
||
* - caches the response if desired |
||
* - resolves the raw $http promise |
||
* - calls $apply |
||
*/ |
||
function done(status, response, headersString) { |
||
if (cache) { |
||
if (isSuccess(status)) { |
||
cache.put(url, [status, response, parseHeaders(headersString)]); |
||
} else { |
||
// remove promise from the cache |
||
cache.remove(url); |
||
} |
||
} |
||
|
||
resolvePromise(response, status, headersString); |
||
if (!$rootScope.$$phase) $rootScope.$apply(); |
||
} |
||
|
||
|
||
/** |
||
* Resolves the raw $http promise. |
||
*/ |
||
function resolvePromise(response, status, headers) { |
||
// normalize internal statuses to 0 |
||
status = Math.max(status, 0); |
||
|
||
(isSuccess(status) ? deferred.resolve : deferred.reject)({ |
||
data: response, |
||
status: status, |
||
headers: headersGetter(headers), |
||
config: config |
||
}); |
||
} |
||
|
||
|
||
function removePendingReq() { |
||
var idx = indexOf($http.pendingRequests, config); |
||
if (idx !== -1) $http.pendingRequests.splice(idx, 1); |
||
} |
||
} |
||
|
||
|
||
function buildUrl(url, params) { |
||
if (!params) return url; |
||
var parts = []; |
||
forEachSorted(params, function(value, key) { |
||
if (value === null || isUndefined(value)) return; |
||
if (!isArray(value)) value = [value]; |
||
|
||
forEach(value, function(v) { |
||
if (isObject(v)) { |
||
v = toJson(v); |
||
} |
||
parts.push(encodeUriQuery(key) + '=' + |
||
encodeUriQuery(v)); |
||
}); |
||
}); |
||
return url + ((url.indexOf('?') == -1) ? '?' : '&') + parts.join('&'); |
||
} |
||
|
||
|
||
}]; |
||
} |
||
|
||
function createXhr(method) { |
||
// IE8 doesn't support PATCH method, but the ActiveX object does |
||
/* global ActiveXObject */ |
||
return (msie <= 8 && lowercase(method) === 'patch') |
||
? new ActiveXObject('Microsoft.XMLHTTP') |
||
: new window.XMLHttpRequest(); |
||
} |
||
|
||
|
||
/** |
||
* @ngdoc object |
||
* @name ng.$httpBackend |
||
* @requires $browser |
||
* @requires $window |
||
* @requires $document |
||
* |
||
* @description |
||
* HTTP backend used by the {@link ng.$http service} that delegates to |
||
* XMLHttpRequest object or JSONP and deals with browser incompatibilities. |
||
* |
||
* You should never need to use this service directly, instead use the higher-level abstractions: |
||
* {@link ng.$http $http} or {@link ngResource.$resource $resource}. |
||
* |
||
* During testing this implementation is swapped with {@link ngMock.$httpBackend mock |
||
* $httpBackend} which can be trained with responses. |
||
*/ |
||
function $HttpBackendProvider() { |
||
this.$get = ['$browser', '$window', '$document', function($browser, $window, $document) { |
||
return createHttpBackend($browser, createXhr, $browser.defer, $window.angular.callbacks, $document[0]); |
||
}]; |
||
} |
||
|
||
function createHttpBackend($browser, createXhr, $browserDefer, callbacks, rawDocument) { |
||
var ABORTED = -1; |
||
|
||
// TODO(vojta): fix the signature |
||
return function(method, url, post, callback, headers, timeout, withCredentials, responseType) { |
||
var status; |
||
$browser.$$incOutstandingRequestCount(); |
||
url = url || $browser.url(); |
||
|
||
if (lowercase(method) == 'jsonp') { |
||
var callbackId = '_' + (callbacks.counter++).toString(36); |
||
callbacks[callbackId] = function(data) { |
||
callbacks[callbackId].data = data; |
||
}; |
||
|
||
var jsonpDone = jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId), |
||
function() { |
||
if (callbacks[callbackId].data) { |
||
completeRequest(callback, 200, callbacks[callbackId].data); |
||
} else { |
||
completeRequest(callback, status || -2); |
||
} |
||
callbacks[callbackId] = angular.noop; |
||
}); |
||
} else { |
||
|
||
var xhr = createXhr(method); |
||
|
||
xhr.open(method, url, true); |
||
forEach(headers, function(value, key) { |
||
if (isDefined(value)) { |
||
xhr.setRequestHeader(key, value); |
||
} |
||
}); |
||
|
||
// In IE6 and 7, this might be called synchronously when xhr.send below is called and the |
||
// response is in the cache. the promise api will ensure that to the app code the api is |
||
// always async |
||
xhr.onreadystatechange = function() { |
||
// onreadystatechange might get called multiple times with readyState === 4 on mobile webkit caused by |
||
// xhrs that are resolved while the app is in the background (see #5426). |
||
// since calling completeRequest sets the `xhr` variable to null, we just check if it's not null before |
||
// continuing |
||
// |
||
// we can't set xhr.onreadystatechange to undefined or delete it because that breaks IE8 (method=PATCH) and |
||
// Safari respectively. |
||
if (xhr && xhr.readyState == 4) { |
||
var responseHeaders = null, |
||
response = null; |
||
|
||
if(status !== ABORTED) { |
||
responseHeaders = xhr.getAllResponseHeaders(); |
||
|
||
// responseText is the old-school way of retrieving response (supported by IE8 & 9) |
||
// response/responseType properties were introduced in XHR Level2 spec (supported by IE10) |
||
response = ('response' in xhr) ? xhr.response : xhr.responseText; |
||
} |
||
|
||
completeRequest(callback, |
||
status || xhr.status, |
||
response, |
||
responseHeaders); |
||
} |
||
}; |
||
|
||
if (withCredentials) { |
||
xhr.withCredentials = true; |
||
} |
||
|
||
if (responseType) { |
||
xhr.responseType = responseType; |
||
} |
||
|
||
xhr.send(post || null); |
||
} |
||
|
||
if (timeout > 0) { |
||
var timeoutId = $browserDefer(timeoutRequest, timeout); |
||
} else if (timeout && timeout.then) { |
||
timeout.then(timeoutRequest); |
||
} |
||
|
||
|
||
function timeoutRequest() { |
||
status = ABORTED; |
||
jsonpDone && jsonpDone(); |
||
xhr && xhr.abort(); |
||
} |
||
|
||
function completeRequest(callback, status, response, headersString) { |
||
// cancel timeout and subsequent timeout promise resolution |
||
timeoutId && $browserDefer.cancel(timeoutId); |
||
jsonpDone = xhr = null; |
||
|
||
// fix status code when it is 0 (0 status is undocumented). |
||
// Occurs when accessing file resources. |
||
// On Android 4.1 stock browser it occurs while retrieving files from application cache. |
||
status = (status === 0) ? (response ? 200 : 404) : status; |
||
|
||
// normalize IE bug (http://bugs.jquery.com/ticket/1450) |
||
status = status == 1223 ? 204 : status; |
||
|
||
callback(status, response, headersString); |
||
$browser.$$completeOutstandingRequest(noop); |
||
} |
||
}; |
||
|
||
function jsonpReq(url, done) { |
||
// we can't use jQuery/jqLite here because jQuery does crazy shit with script elements, e.g.: |
||
// - fetches local scripts via XHR and evals them |
||
// - adds and immediately removes script elements from the document |
||
var script = rawDocument.createElement('script'), |
||
doneWrapper = function() { |
||
script.onreadystatechange = script.onload = script.onerror = null; |
||
rawDocument.body.removeChild(script); |
||
if (done) done(); |
||
}; |
||
|
||
script.type = 'text/javascript'; |
||
script.src = url; |
||
|
||
if (msie && msie <= 8) { |
||
script.onreadystatechange = function() { |
||
if (/loaded|complete/.test(script.readyState)) { |
||
doneWrapper(); |
||
} |
||
}; |
||
} else { |
||
script.onload = script.onerror = function() { |
||
doneWrapper(); |
||
}; |
||
} |
||
|
||
rawDocument.body.appendChild(script); |
||
return doneWrapper; |
||
} |
||
} |
||
|
||
var $interpolateMinErr = minErr('$interpolate'); |
||
|
||
/** |
||
* @ngdoc object |
||
* @name ng.$interpolateProvider |
||
* @function |
||
* |
||
* @description |
||
* |
||
* Used for configuring the interpolation markup. Defaults to `{{` and `}}`. |
||
* |
||
* @example |
||
<doc:example module="customInterpolationApp"> |
||
<doc:source> |
||
<script> |
||
var customInterpolationApp = angular.module('customInterpolationApp', []); |
||
|
||
customInterpolationApp.config(function($interpolateProvider) { |
||
$interpolateProvider.startSymbol('//'); |
||
$interpolateProvider.endSymbol('//'); |
||
}); |
||
|
||
|
||
customInterpolationApp.controller('DemoController', function DemoController() { |
||
this.label = "This binding is brought you by // interpolation symbols."; |
||
}); |
||
</script> |
||
<div ng-app="App" ng-controller="DemoController as demo"> |
||
//demo.label// |
||
</div> |
||
</doc:source> |
||
<doc:scenario> |
||
it('should interpolate binding with custom symbols', function() { |
||
expect(binding('demo.label')).toBe('This binding is brought you by // interpolation symbols.'); |
||
}); |
||
</doc:scenario> |
||
</doc:example> |
||
*/ |
||
function $InterpolateProvider() { |
||
var startSymbol = '{{'; |
||
var endSymbol = '}}'; |
||
|
||
/** |
||
* @ngdoc method |
||
* @name ng.$interpolateProvider#startSymbol |
||
* @methodOf ng.$interpolateProvider |
||
* @description |
||
* Symbol to denote start of expression in the interpolated string. Defaults to `{{`. |
||
* |
||
* @param {string=} value new value to set the starting symbol to. |
||
* @returns {string|self} Returns the symbol when used as getter and self if used as setter. |
||
*/ |
||
this.startSymbol = function(value){ |
||
if (value) { |
||
startSymbol = value; |
||
return this; |
||
} else { |
||
return startSymbol; |
||
} |
||
}; |
||
|
||
/** |
||
* @ngdoc method |
||
* @name ng.$interpolateProvider#endSymbol |
||
* @methodOf ng.$interpolateProvider |
||
* @description |
||
* Symbol to denote the end of expression in the interpolated string. Defaults to `}}`. |
||
* |
||
* @param {string=} value new value to set the ending symbol to. |
||
* @returns {string|self} Returns the symbol when used as getter and self if used as setter. |
||
*/ |
||
this.endSymbol = function(value){ |
||
if (value) { |
||
endSymbol = value; |
||
return this; |
||
} else { |
||
return endSymbol; |
||
} |
||
}; |
||
|
||
|
||
this.$get = ['$parse', '$exceptionHandler', '$sce', function($parse, $exceptionHandler, $sce) { |
||
var startSymbolLength = startSymbol.length, |
||
endSymbolLength = endSymbol.length; |
||
|
||
/** |
||
* @ngdoc function |
||
* @name ng.$interpolate |
||
* @function |
||
* |
||
* @requires $parse |
||
* @requires $sce |
||
* |
||
* @description |
||
* |
||
* Compiles a string with markup into an interpolation function. This service is used by the |
||
* HTML {@link ng.$compile $compile} service for data binding. See |
||
* {@link ng.$interpolateProvider $interpolateProvider} for configuring the |
||
* interpolation markup. |
||
* |
||
* |
||
<pre> |
||
var $interpolate = ...; // injected |
||
var exp = $interpolate('Hello {{name | uppercase}}!'); |
||
expect(exp({name:'Angular'}).toEqual('Hello ANGULAR!'); |
||
</pre> |
||
* |
||
* |
||
* @param {string} text The text with markup to interpolate. |
||
* @param {boolean=} mustHaveExpression if set to true then the interpolation string must have |
||
* embedded expression in order to return an interpolation function. Strings with no |
||
* embedded expression will return null for the interpolation function. |
||
* @param {string=} trustedContext when provided, the returned function passes the interpolated |
||
* result through {@link ng.$sce#methods_getTrusted $sce.getTrusted(interpolatedResult, |
||
* trustedContext)} before returning it. Refer to the {@link ng.$sce $sce} service that |
||
* provides Strict Contextual Escaping for details. |
||
* @returns {function(context)} an interpolation function which is used to compute the |
||
* interpolated string. The function has these parameters: |
||
* |
||
* * `context`: an object against which any expressions embedded in the strings are evaluated |
||
* against. |
||
* |
||
*/ |
||
function $interpolate(text, mustHaveExpression, trustedContext) { |
||
var startIndex, |
||
endIndex, |
||
index = 0, |
||
parts = [], |
||
length = text.length, |
||
hasInterpolation = false, |
||
fn, |
||
exp, |
||
concat = []; |
||
|
||
while(index < length) { |
||
if ( ((startIndex = text.indexOf(startSymbol, index)) != -1) && |
||
((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) != -1) ) { |
||
(index != startIndex) && parts.push(text.substring(index, startIndex)); |
||
parts.push(fn = $parse(exp = text.substring(startIndex + startSymbolLength, endIndex))); |
||
fn.exp = exp; |
||
index = endIndex + endSymbolLength; |
||
hasInterpolation = true; |
||
} else { |
||
// we did not find anything, so we have to add the remainder to the parts array |
||
(index != length) && parts.push(text.substring(index)); |
||
index = length; |
||
} |
||
} |
||
|
||
if (!(length = parts.length)) { |
||
// we added, nothing, must have been an empty string. |
||
parts.push(''); |
||
length = 1; |
||
} |
||
|
||
// Concatenating expressions makes it hard to reason about whether some combination of |
||
// concatenated values are unsafe to use and could easily lead to XSS. By requiring that a |
||
// single expression be used for iframe[src], object[src], etc., we ensure that the value |
||
// that's used is assigned or constructed by some JS code somewhere that is more testable or |
||
// make it obvious that you bound the value to some user controlled value. This helps reduce |
||
// the load when auditing for XSS issues. |
||
if (trustedContext && parts.length > 1) { |
||
throw $interpolateMinErr('noconcat', |
||
"Error while interpolating: {0}\nStrict Contextual Escaping disallows " + |
||
"interpolations that concatenate multiple expressions when a trusted value is " + |
||
"required. See http://docs.angularjs.org/api/ng.$sce", text); |
||
} |
||
|
||
if (!mustHaveExpression || hasInterpolation) { |
||
concat.length = length; |
||
fn = function(context) { |
||
try { |
||
for(var i = 0, ii = length, part; i<ii; i++) { |
||
if (typeof (part = parts[i]) == 'function') { |
||
part = part(context); |
||
if (trustedContext) { |
||
part = $sce.getTrusted(trustedContext, part); |
||
} else { |
||
part = $sce.valueOf(part); |
||
} |
||
if (part === null || isUndefined(part)) { |
||
part = ''; |
||
} else if (typeof part != 'string') { |
||
part = toJson(part); |
||
} |
||
} |
||
concat[i] = part; |
||
} |
||
return concat.join(''); |
||
} |
||
catch(err) { |
||
var newErr = $interpolateMinErr('interr', "Can't interpolate: {0}\n{1}", text, |
||
err.toString()); |
||
$exceptionHandler(newErr); |
||
} |
||
}; |
||
fn.exp = text; |
||
fn.parts = parts; |
||
return fn; |
||
} |
||
} |
||
|
||
|
||
/** |
||
* @ngdoc method |
||
* @name ng.$interpolate#startSymbol |
||
* @methodOf ng.$interpolate |
||
* @description |
||
* Symbol to denote the start of expression in the interpolated string. Defaults to `{{`. |
||
* |
||
* Use {@link ng.$interpolateProvider#startSymbol $interpolateProvider#startSymbol} to change |
||
* the symbol. |
||
* |
||
* @returns {string} start symbol. |
||
*/ |
||
$interpolate.startSymbol = function() { |
||
return startSymbol; |
||
}; |
||
|
||
|
||
/** |
||
* @ngdoc method |
||
* @name ng.$interpolate#endSymbol |
||
* @methodOf ng.$interpolate |
||
* @description |
||
* Symbol to denote the end of expression in the interpolated string. Defaults to `}}`. |
||
* |
||
* Use {@link ng.$interpolateProvider#endSymbol $interpolateProvider#endSymbol} to change |
||
* the symbol. |
||
* |
||
* @returns {string} start symbol. |
||
*/ |
||
$interpolate.endSymbol = function() { |
||
return endSymbol; |
||
}; |
||
|
||
return $interpolate; |
||
}]; |
||
} |
||
|
||
function $IntervalProvider() { |
||
this.$get = ['$rootScope', '$window', '$q', |
||
function($rootScope, $window, $q) { |
||
var intervals = {}; |
||
|
||
|
||
/** |
||
* @ngdoc function |
||
* @name ng.$interval |
||
* |
||
* @description |
||
* Angular's wrapper for `window.setInterval`. The `fn` function is executed every `delay` |
||
* milliseconds. |
||
* |
||
* The return value of registering an interval function is a promise. This promise will be |
||
* notified upon each tick of the interval, and will be resolved after `count` iterations, or |
||
* run indefinitely if `count` is not defined. The value of the notification will be the |
||
* number of iterations that have run. |
||
* To cancel an interval, call `$interval.cancel(promise)`. |
||
* |
||
* In tests you can use {@link ngMock.$interval#methods_flush `$interval.flush(millis)`} to |
||
* move forward by `millis` milliseconds and trigger any functions scheduled to run in that |
||
* time. |
||
* |
||
* <div class="alert alert-warning"> |
||
* **Note**: Intervals created by this service must be explicitly destroyed when you are finished |
||
* with them. In particular they are not automatically destroyed when a controller's scope or a |
||
* directive's element are destroyed. |
||
* You should take this into consideration and make sure to always cancel the interval at the |
||
* appropriate moment. See the example below for more details on how and when to do this. |
||
* </div> |
||
* |
||
* @param {function()} fn A function that should be called repeatedly. |
||
* @param {number} delay Number of milliseconds between each function call. |
||
* @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat |
||
* indefinitely. |
||
* @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise |
||
* will invoke `fn` within the {@link ng.$rootScope.Scope#methods_$apply $apply} block. |
||
* @returns {promise} A promise which will be notified on each iteration. |
||
* |
||
* @example |
||
<doc:example module="time"> |
||
<doc:source> |
||
<script> |
||
function Ctrl2($scope,$interval) { |
||
$scope.format = 'M/d/yy h:mm:ss a'; |
||
$scope.blood_1 = 100; |
||
$scope.blood_2 = 120; |
||
|
||
var stop; |
||
$scope.fight = function() { |
||
// Don't start a new fight if we are already fighting |
||
if ( angular.isDefined(stop) ) return; |
||
|
||
stop = $interval(function() { |
||
if ($scope.blood_1 > 0 && $scope.blood_2 > 0) { |
||
$scope.blood_1 = $scope.blood_1 - 3; |
||
$scope.blood_2 = $scope.blood_2 - 4; |
||
} else { |
||
$scope.stopFight(); |
||
} |
||
}, 100); |
||
}; |
||
|
||
$scope.stopFight = function() { |
||
if (angular.isDefined(stop)) { |
||
$interval.cancel(stop); |
||
stop = undefined; |
||
} |
||
}; |
||
|
||
$scope.resetFight = function() { |
||
$scope.blood_1 = 100; |
||
$scope.blood_2 = 120; |
||
} |
||
|
||
$scope.$on('$destroy', function() { |
||
// Make sure that the interval is destroyed too |
||
$scope.stopFight(); |
||
}); |
||
} |
||
|
||
angular.module('time', []) |
||
// Register the 'myCurrentTime' directive factory method. |
||
// We inject $interval and dateFilter service since the factory method is DI. |
||
.directive('myCurrentTime', function($interval, dateFilter) { |
||
// return the directive link function. (compile function not needed) |
||
return function(scope, element, attrs) { |
||
var format, // date format |
||
stopTime; // so that we can cancel the time updates |
||
|
||
// used to update the UI |
||
function updateTime() { |
||
element.text(dateFilter(new Date(), format)); |
||
} |
||
|
||
// watch the expression, and update the UI on change. |
||
scope.$watch(attrs.myCurrentTime, function(value) { |
||
format = value; |
||
updateTime(); |
||
}); |
||
|
||
stopTime = $interval(updateTime, 1000); |
||
|
||
// listen on DOM destroy (removal) event, and cancel the next UI update |
||
// to prevent updating time ofter the DOM element was removed. |
||
element.bind('$destroy', function() { |
||
$interval.cancel(stopTime); |
||
}); |
||
} |
||
}); |
||
</script> |
||
|
||
<div> |
||
<div ng-controller="Ctrl2"> |
||
Date format: <input ng-model="format"> <hr/> |
||
Current time is: <span my-current-time="format"></span> |
||
<hr/> |
||
Blood 1 : <font color='red'>{{blood_1}}</font> |
||
Blood 2 : <font color='red'>{{blood_2}}</font> |
||
<button type="button" data-ng-click="fight()">Fight</button> |
||
<button type="button" data-ng-click="stopFight()">StopFight</button> |
||
<button type="button" data-ng-click="resetFight()">resetFight</button> |
||
</div> |
||
</div> |
||
|
||
</doc:source> |
||
</doc:example> |
||
*/ |
||
function interval(fn, delay, count, invokeApply) { |
||
var setInterval = $window.setInterval, |
||
clearInterval = $window.clearInterval, |
||
deferred = $q.defer(), |
||
promise = deferred.promise, |
||
iteration = 0, |
||
skipApply = (isDefined(invokeApply) && !invokeApply); |
||
|
||
count = isDefined(count) ? count : 0, |
||
|
||
promise.then(null, null, fn); |
||
|
||
promise.$$intervalId = setInterval(function tick() { |
||
deferred.notify(iteration++); |
||
|
||
if (count > 0 && iteration >= count) { |
||
deferred.resolve(iteration); |
||
clearInterval(promise.$$intervalId); |
||
delete intervals[promise.$$intervalId]; |
||
} |
||
|
||
if (!skipApply) $rootScope.$apply(); |
||
|
||
}, delay); |
||
|
||
intervals[promise.$$intervalId] = deferred; |
||
|
||
return promise; |
||
} |
||
|
||
|
||
/** |
||
* @ngdoc function |
||
* @name ng.$interval#cancel |
||
* @methodOf ng.$interval |
||
* |
||
* @description |
||
* Cancels a task associated with the `promise`. |
||
* |
||
* @param {number} promise Promise returned by the `$interval` function. |
||
* @returns {boolean} Returns `true` if the task was successfully canceled. |
||
*/ |
||
interval.cancel = function(promise) { |
||
if (promise && promise.$$intervalId in intervals) { |
||
intervals[promise.$$intervalId].reject('canceled'); |
||
clearInterval(promise.$$intervalId); |
||
delete intervals[promise.$$intervalId]; |
||
return true; |
||
} |
||
return false; |
||
}; |
||
|
||
return interval; |
||
}]; |
||
} |
||
|
||
/** |
||
* @ngdoc object |
||
* @name ng.$locale |
||
* |
||
* @description |
||
* $locale service provides localization rules for various Angular components. As of right now the |
||
* only public api is: |
||
* |
||
* * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`) |
||
*/ |
||
function $LocaleProvider(){ |
||
this.$get = function() { |
||
return { |
||
id: 'en-us', |
||
|
||
NUMBER_FORMATS: { |
||
DECIMAL_SEP: '.', |
||
GROUP_SEP: ',', |
||
PATTERNS: [ |
||
{ // Decimal Pattern |
||
minInt: 1, |
||
minFrac: 0, |
||
maxFrac: 3, |
||
posPre: '', |
||
posSuf: '', |
||
negPre: '-', |
||
negSuf: '', |
||
gSize: 3, |
||
lgSize: 3 |
||
},{ //Currency Pattern |
||
minInt: 1, |
||
minFrac: 2, |
||
maxFrac: 2, |
||
posPre: '\u00A4', |
||
posSuf: '', |
||
negPre: '(\u00A4', |
||
negSuf: ')', |
||
gSize: 3, |
||
lgSize: 3 |
||
} |
||
], |
||
CURRENCY_SYM: '$' |
||
}, |
||
|
||
DATETIME_FORMATS: { |
||
MONTH: |
||
'January,February,March,April,May,June,July,August,September,October,November,December' |
||
.split(','), |
||
SHORTMONTH: 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(','), |
||
DAY: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'.split(','), |
||
SHORTDAY: 'Sun,Mon,Tue,Wed,Thu,Fri,Sat'.split(','), |
||
AMPMS: ['AM','PM'], |
||
medium: 'MMM d, y h:mm:ss a', |
||
short: 'M/d/yy h:mm a', |
||
fullDate: 'EEEE, MMMM d, y', |
||
longDate: 'MMMM d, y', |
||
mediumDate: 'MMM d, y', |
||
shortDate: 'M/d/yy', |
||
mediumTime: 'h:mm:ss a', |
||
shortTime: 'h:mm a' |
||
}, |
||
|
||
pluralCat: function(num) { |
||
if (num === 1) { |
||
return 'one'; |
||
} |
||
return 'other'; |
||
} |
||
}; |
||
}; |
||
} |
||
|
||
var PATH_MATCH = /^([^\?#]*)(\?([^#]*))?(#(.*))?$/, |
||
DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21}; |
||
var $locationMinErr = minErr('$location'); |
||
|
||
|
||
/** |
||
* Encode path using encodeUriSegment, ignoring forward slashes |
||
* |
||
* @param {string} path Path to encode |
||
* @returns {string} |
||
*/ |
||
function encodePath(path) { |
||
var segments = path.split('/'), |
||
i = segments.length; |
||
|
||
while (i--) { |
||
segments[i] = encodeUriSegment(segments[i]); |
||
} |
||
|
||
return segments.join('/'); |
||
} |
||
|
||
function parseAbsoluteUrl(absoluteUrl, locationObj, appBase) { |
||
var parsedUrl = urlResolve(absoluteUrl, appBase); |
||
|
||
locationObj.$$protocol = parsedUrl.protocol; |
||
locationObj.$$host = parsedUrl.hostname; |
||
locationObj.$$port = int(parsedUrl.port) || DEFAULT_PORTS[parsedUrl.protocol] || null; |
||
} |
||
|
||
|
||
function parseAppUrl(relativeUrl, locationObj, appBase) { |
||
var prefixed = (relativeUrl.charAt(0) !== '/'); |
||
if (prefixed) { |
||
relativeUrl = '/' + relativeUrl; |
||
} |
||
var match = urlResolve(relativeUrl, appBase); |
||
locationObj.$$path = decodeURIComponent(prefixed && match.pathname.charAt(0) === '/' ? |
||
match.pathname.substring(1) : match.pathname); |
||
locationObj.$$search = parseKeyValue(match.search); |
||
locationObj.$$hash = decodeURIComponent(match.hash); |
||
|
||
// make sure path starts with '/'; |
||
if (locationObj.$$path && locationObj.$$path.charAt(0) != '/') { |
||
locationObj.$$path = '/' + locationObj.$$path; |
||
} |
||
} |
||
|
||
|
||
/** |
||
* |
||
* @param {string} begin |
||
* @param {string} whole |
||
* @returns {string} returns text from whole after begin or undefined if it does not begin with |
||
* expected string. |
||
*/ |
||
function beginsWith(begin, whole) { |
||
if (whole.indexOf(begin) === 0) { |
||
return whole.substr(begin.length); |
||
} |
||
} |
||
|
||
|
||
function stripHash(url) { |
||
var index = url.indexOf('#'); |
||
return index == -1 ? url : url.substr(0, index); |
||
} |
||
|
||
|
||
function stripFile(url) { |
||
return url.substr(0, stripHash(url).lastIndexOf('/') + 1); |
||
} |
||
|
||
/* return the server only (scheme://host:port) */ |
||
function serverBase(url) { |
||
return url.substring(0, url.indexOf('/', url.indexOf('//') + 2)); |
||
} |
||
|
||
|
||
/** |
||
* LocationHtml5Url represents an url |
||
* This object is exposed as $location service when HTML5 mode is enabled and supported |
||
* |
||
* @constructor |
||
* @param {string} appBase application base URL |
||
* @param {string} basePrefix url path prefix |
||
*/ |
||
function LocationHtml5Url(appBase, basePrefix) { |
||
this.$$html5 = true; |
||
basePrefix = basePrefix || ''; |
||
var appBaseNoFile = stripFile(appBase); |
||
parseAbsoluteUrl(appBase, this, appBase); |
||
|
||
|
||
/** |
||
* Parse given html5 (regular) url string into properties |
||
* @param {string} newAbsoluteUrl HTML5 url |
||
* @private |
||
*/ |
||
this.$$parse = function(url) { |
||
var pathUrl = beginsWith(appBaseNoFile, url); |
||
if (!isString(pathUrl)) { |
||
throw $locationMinErr('ipthprfx', 'Invalid url "{0}", missing path prefix "{1}".', url, |
||
appBaseNoFile); |
||
} |
||
|
||
parseAppUrl(pathUrl, this, appBase); |
||
|
||
if (!this.$$path) { |
||
this.$$path = '/'; |
||
} |
||
|
||
this.$$compose(); |
||
}; |
||
|
||
/** |
||
* Compose url and update `absUrl` property |
||
* @private |
||
*/ |
||
this.$$compose = function() { |
||
var search = toKeyValue(this.$$search), |
||
hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : ''; |
||
|
||
this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash; |
||
this.$$absUrl = appBaseNoFile + this.$$url.substr(1); // first char is always '/' |
||
}; |
||
|
||
this.$$rewrite = function(url) { |
||
var appUrl, prevAppUrl; |
||
|
||
if ( (appUrl = beginsWith(appBase, url)) !== undefined ) { |
||
prevAppUrl = appUrl; |
||
if ( (appUrl = beginsWith(basePrefix, appUrl)) !== undefined ) { |
||
return appBaseNoFile + (beginsWith('/', appUrl) || appUrl); |
||
} else { |
||
return appBase + prevAppUrl; |
||
} |
||
} else if ( (appUrl = beginsWith(appBaseNoFile, url)) !== undefined ) { |
||
return appBaseNoFile + appUrl; |
||
} else if (appBaseNoFile == url + '/') { |
||
return appBaseNoFile; |
||
} |
||
}; |
||
} |
||
|
||
|
||
/** |
||
* LocationHashbangUrl represents url |
||
* This object is exposed as $location service when developer doesn't opt into html5 mode. |
||
* It also serves as the base class for html5 mode fallback on legacy browsers. |
||
* |
||
* @constructor |
||
* @param {string} appBase application base URL |
||
* @param {string} hashPrefix hashbang prefix |
||
*/ |
||
function LocationHashbangUrl(appBase, hashPrefix) { |
||
var appBaseNoFile = stripFile(appBase); |
||
|
||
parseAbsoluteUrl(appBase, this, appBase); |
||
|
||
|
||
/** |
||
* Parse given hashbang url into properties |
||
* @param {string} url Hashbang url |
||
* @private |
||
*/ |
||
this.$$parse = function(url) { |
||
var withoutBaseUrl = beginsWith(appBase, url) || beginsWith(appBaseNoFile, url); |
||
var withoutHashUrl = withoutBaseUrl.charAt(0) == '#' |
||
? beginsWith(hashPrefix, withoutBaseUrl) |
||
: (this.$$html5) |
||
? withoutBaseUrl |
||
: ''; |
||
|
||
if (!isString(withoutHashUrl)) { |
||
throw $locationMinErr('ihshprfx', 'Invalid url "{0}", missing hash prefix "{1}".', url, |
||
hashPrefix); |
||
} |
||
parseAppUrl(withoutHashUrl, this, appBase); |
||
|
||
this.$$path = removeWindowsDriveName(this.$$path, withoutHashUrl, appBase); |
||
|
||
this.$$compose(); |
||
|
||
/* |
||
* In Windows, on an anchor node on documents loaded from |
||
* the filesystem, the browser will return a pathname |
||
* prefixed with the drive name ('/C:/path') when a |
||
* pathname without a drive is set: |
||
* * a.setAttribute('href', '/foo') |
||
* * a.pathname === '/C:/foo' //true |
||
* |
||
* Inside of Angular, we're always using pathnames that |
||
* do not include drive names for routing. |
||
*/ |
||
function removeWindowsDriveName (path, url, base) { |
||
/* |
||
Matches paths for file protocol on windows, |
||
such as /C:/foo/bar, and captures only /foo/bar. |
||
*/ |
||
var windowsFilePathExp = /^\/?.*?:(\/.*)/; |
||
|
||
var firstPathSegmentMatch; |
||
|
||
//Get the relative path from the input URL. |
||
if (url.indexOf(base) === 0) { |
||
url = url.replace(base, ''); |
||
} |
||
|
||
/* |
||
* The input URL intentionally contains a |
||
* first path segment that ends with a colon. |
||
*/ |
||
if (windowsFilePathExp.exec(url)) { |
||
return path; |
||
} |
||
|
||
firstPathSegmentMatch = windowsFilePathExp.exec(path); |
||
return firstPathSegmentMatch ? firstPathSegmentMatch[1] : path; |
||
} |
||
}; |
||
|
||
/** |
||
* Compose hashbang url and update `absUrl` property |
||
* @private |
||
*/ |
||
this.$$compose = function() { |
||
var search = toKeyValue(this.$$search), |
||
hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : ''; |
||
|
||
this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash; |
||
this.$$absUrl = appBase + (this.$$url ? hashPrefix + this.$$url : ''); |
||
}; |
||
|
||
this.$$rewrite = function(url) { |
||
if(stripHash(appBase) == stripHash(url)) { |
||
return url; |
||
} |
||
}; |
||
} |
||
|
||
|
||
/** |
||
* LocationHashbangUrl represents url |
||
* This object is exposed as $location service when html5 history api is enabled but the browser |
||
* does not support it. |
||
* |
||
* @constructor |
||
* @param {string} appBase application base URL |
||
* @param {string} hashPrefix hashbang prefix |
||
*/ |
||
function LocationHashbangInHtml5Url(appBase, hashPrefix) { |
||
this.$$html5 = true; |
||
LocationHashbangUrl.apply(this, arguments); |
||
|
||
var appBaseNoFile = stripFile(appBase); |
||
|
||
this.$$rewrite = function(url) { |
||
var appUrl; |
||
|
||
if ( appBase == stripHash(url) ) { |
||
return url; |
||
} else if ( (appUrl = beginsWith(appBaseNoFile, url)) ) { |
||
return appBase + hashPrefix + appUrl; |
||
} else if ( appBaseNoFile === url + '/') { |
||
return appBaseNoFile; |
||
} |
||
}; |
||
} |
||
|
||
|
||
LocationHashbangInHtml5Url.prototype = |
||
LocationHashbangUrl.prototype = |
||
LocationHtml5Url.prototype = { |
||
|
||
/** |
||
* Are we in html5 mode? |
||
* @private |
||
*/ |
||
$$html5: false, |
||
|
||
/** |
||
* Has any change been replacing ? |
||
* @private |
||
*/ |
||
$$replace: false, |
||
|
||
/** |
||
* @ngdoc method |
||
* @name ng.$location#absUrl |
||
* @methodOf ng.$location |
||
* |
||
* @description |
||
* This method is getter only. |
||
* |
||
* Return full url representation with all segments encoded according to rules specified in |
||
* {@link http://www.ietf.org/rfc/rfc3986.txt RFC 3986}. |
||
* |
||
* @return {string} full url |
||
*/ |
||
absUrl: locationGetter('$$absUrl'), |
||
|
||
/** |
||
* @ngdoc method |
||
* @name ng.$location#url |
||
* @methodOf ng.$location |
||
* |
||
* @description |
||
* This method is getter / setter. |
||
* |
||
* Return url (e.g. `/path?a=b#hash`) when called without any parameter. |
||
* |
||
* Change path, search and hash, when called with parameter and return `$location`. |
||
* |
||
* @param {string=} url New url without base prefix (e.g. `/path?a=b#hash`) |
||
* @param {string=} replace The path that will be changed |
||
* @return {string} url |
||
*/ |
||
url: function(url, replace) { |
||
if (isUndefined(url)) |
||
return this.$$url; |
||
|
||
var match = PATH_MATCH.exec(url); |
||
if (match[1]) this.path(decodeURIComponent(match[1])); |
||
if (match[2] || match[1]) this.search(match[3] || ''); |
||
this.hash(match[5] || '', replace); |
||
|
||
return this; |
||
}, |
||
|
||
/** |
||
* @ngdoc method |
||
* @name ng.$location#protocol |
||
* @methodOf ng.$location |
||
* |
||
* @description |
||
* This method is getter only. |
||
* |
||
* Return protocol of current url. |
||
* |
||
* @return {string} protocol of current url |
||
*/ |
||
protocol: locationGetter('$$protocol'), |
||
|
||
/** |
||
* @ngdoc method |
||
* @name ng.$location#host |
||
* @methodOf ng.$location |
||
* |
||
* @description |
||
* This method is getter only. |
||
* |
||
* Return host of current url. |
||
* |
||
* @return {string} host of current url. |
||
*/ |
||
host: locationGetter('$$host'), |
||
|
||
/** |
||
* @ngdoc method |
||
* @name ng.$location#port |
||
* @methodOf ng.$location |
||
* |
||
* @description |
||
* This method is getter only. |
||
* |
||
* Return port of current url. |
||
* |
||
* @return {Number} port |
||
*/ |
||
port: locationGetter('$$port'), |
||
|
||
/** |
||
* @ngdoc method |
||
* @name ng.$location#path |
||
* @methodOf ng.$location |
||
* |
||
* @description |
||
* This method is getter / setter. |
||
* |
||
* Return path of current url when called without any parameter. |
||
* |
||
* Change path when called with parameter and return `$location`. |
||
* |
||
* Note: Path should always begin with forward slash (/), this method will add the forward slash |
||
* if it is missing. |
||
* |
||
* @param {string=} path New path |
||
* @return {string} path |
||
*/ |
||
path: locationGetterSetter('$$path', function(path) { |
||
return path.charAt(0) == '/' ? path : '/' + path; |
||
}), |
||
|
||
/** |
||
* @ngdoc method |
||
* @name ng.$location#search |
||
* @methodOf ng.$location |
||
* |
||
* @description |
||
* This method is getter / setter. |
||
* |
||
* Return search part (as object) of current url when called without any parameter. |
||
* |
||
* Change search part when called with parameter and return `$location`. |
||
* |
||
* @param {string|Object.<string>|Object.<Array.<string>>} search New search params - string or |
||
* hash object. Hash object may contain an array of values, which will be decoded as duplicates in |
||
* the url. |
||
* |
||
* @param {(string|Array<string>)=} paramValue If `search` is a string, then `paramValue` will override only a |
||
* single search parameter. If `paramValue` is an array, it will set the parameter as a |
||
* comma-separated value. If `paramValue` is `null`, the parameter will be deleted. |
||
* |
||
* @return {string} search |
||
*/ |
||
search: function(search, paramValue) { |
||
switch (arguments.length) { |
||
case 0: |
||
return this.$$search; |
||
case 1: |
||
if (isString(search)) { |
||
this.$$search = parseKeyValue(search); |
||
} else if (isObject(search)) { |
||
this.$$search = search; |
||
} else { |
||
throw $locationMinErr('isrcharg', |
||
'The first argument of the `$location#search()` call must be a string or an object.'); |
||
} |
||
break; |
||
default: |
||
if (isUndefined(paramValue) || paramValue === null) { |
||
delete this.$$search[search]; |
||
} else { |
||
this.$$search[search] = paramValue; |
||
} |
||
} |
||
|
||
this.$$compose(); |
||
return this; |
||
}, |
||
|
||
/** |
||
* @ngdoc method |
||
* @name ng.$location#hash |
||
* @methodOf ng.$location |
||
* |
||
* @description |
||
* This method is getter / setter. |
||
* |
||
* Return hash fragment when called without any parameter. |
||
* |
||
* Change hash fragment when called with parameter and return `$location`. |
||
* |
||
* @param {string=} hash New hash fragment |
||
* @return {string} hash |
||
*/ |
||
hash: locationGetterSetter('$$hash', identity), |
||
|
||
/** |
||
* @ngdoc method |
||
* @name ng.$location#replace |
||
* @methodOf ng.$location |
||
* |
||
* @description |
||
* If called, all changes to $location during current `$digest` will be replacing current history |
||
* record, instead of adding new one. |
||
*/ |
||
replace: function() { |
||
this.$$replace = true; |
||
return this; |
||
} |
||
}; |
||
|
||
function locationGetter(property) { |
||
return function() { |
||
return this[property]; |
||
}; |
||
} |
||
|
||
|
||
function locationGetterSetter(property, preprocess) { |
||
return function(value) { |
||
if (isUndefined(value)) |
||
return this[property]; |
||
|
||
this[property] = preprocess(value); |
||
this.$$compose(); |
||
|
||
return this; |
||
}; |
||
} |
||
|
||
|
||
/** |
||
* @ngdoc object |
||
* @name ng.$location |
||
* |
||
* @requires $browser |
||
* @requires $sniffer |
||
* @requires $rootElement |
||
* |
||
* @description |
||
* The $location service parses the URL in the browser address bar (based on the |
||
* {@link https://developer.mozilla.org/en/window.location window.location}) and makes the URL |
||
* available to your application. Changes to the URL in the address bar are reflected into |
||
* $location service and changes to $location are reflected into the browser address bar. |
||
* |
||
* **The $location service:** |
||
* |
||
* - Exposes the current URL in the browser address bar, so you can |
||
* - Watch and observe the URL. |
||
* - Change the URL. |
||
* - Synchronizes the URL with the browser when the user |
||
* - Changes the address bar. |
||
* - Clicks the back or forward button (or clicks a History link). |
||
* - Clicks on a link. |
||
* - Represents the URL object as a set of methods (protocol, host, port, path, search, hash). |
||
* |
||
* For more information see {@link guide/dev_guide.services.$location Developer Guide: Angular |
||
* Services: Using $location} |
||
*/ |
||
|
||
/** |
||
* @ngdoc object |
||
* @name ng.$locationProvider |
||
* @description |
||
* Use the `$locationProvider` to configure how the application deep linking paths are stored. |
||
*/ |
||
function $LocationProvider(){ |
||
var hashPrefix = '', |
||
html5Mode = false; |
||
|
||
/** |
||
* @ngdoc property |
||
* @name ng.$locationProvider#hashPrefix |
||
* @methodOf ng.$locationProvider |
||
* @description |
||
* @param {string=} prefix Prefix for hash part (containing path and search) |
||
* @returns {*} current value if used as getter or itself (chaining) if used as setter |
||
*/ |
||
this.hashPrefix = function(prefix) { |
||
if (isDefined(prefix)) { |
||
hashPrefix = prefix; |
||
return this; |
||
} else { |
||
return hashPrefix; |
||
} |
||
}; |
||
|
||
/** |
||
* @ngdoc property |
||
* @name ng.$locationProvider#html5Mode |
||
* @methodOf ng.$locationProvider |
||
* @description |
||
* @param {boolean=} mode Use HTML5 strategy if available. |
||
* @returns {*} current value if used as getter or itself (chaining) if used as setter |
||
*/ |
||
this.html5Mode = function(mode) { |
||
if (isDefined(mode)) { |
||
html5Mode = mode; |
||
return this; |
||
} else { |
||
return html5Mode; |
||
} |
||
}; |
||
|
||
/** |
||
* @ngdoc event |
||
* @name ng.$location#$locationChangeStart |
||
* @eventOf ng.$location |
||
* @eventType broadcast on root scope |
||
* @description |
||
* Broadcasted before a URL will change. This change can be prevented by calling |
||
* `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on} for more |
||
* details about event object. Upon successful change |
||
* {@link ng.$location#events_$locationChangeSuccess $locationChangeSuccess} is fired. |
||
* |
||
* @param {Object} angularEvent Synthetic event object. |
||
* @param {string} newUrl New URL |
||
* @param {string=} oldUrl URL that was before it was changed. |
||
*/ |
||
|
||
/** |
||
* @ngdoc event |
||
* @name ng.$location#$locationChangeSuccess |
||
* @eventOf ng.$location |
||
* @eventType broadcast on root scope |
||
* @description |
||
* Broadcasted after a URL was changed. |
||
* |
||
* @param {Object} angularEvent Synthetic event object. |
||
* @param {string} newUrl New URL |
||
* @param {string=} oldUrl URL that was before it was changed. |
||
*/ |
||
|
||
this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement', |
||
function( $rootScope, $browser, $sniffer, $rootElement) { |
||
var $location, |
||
LocationMode, |
||
baseHref = $browser.baseHref(), // if base[href] is undefined, it defaults to '' |
||
initialUrl = $browser.url(), |
||
appBase; |
||
|
||
if (html5Mode) { |
||
appBase = serverBase(initialUrl) + (baseHref || '/'); |
||
LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url; |
||
} else { |
||
appBase = stripHash(initialUrl); |
||
LocationMode = LocationHashbangUrl; |
||
} |
||
$location = new LocationMode(appBase, '#' + hashPrefix); |
||
$location.$$parse($location.$$rewrite(initialUrl)); |
||
|
||
$rootElement.on('click', function(event) { |
||
// TODO(vojta): rewrite link when opening in new tab/window (in legacy browser) |
||
// currently we open nice url link and redirect then |
||
|
||
if (event.ctrlKey || event.metaKey || event.which == 2) return; |
||
|
||
var elm = jqLite(event.target); |
||
|
||
// traverse the DOM up to find first A tag |
||
while (lowercase(elm[0].nodeName) !== 'a') { |
||
// ignore rewriting if no A tag (reached root element, or no parent - removed from document) |
||
if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return; |
||
} |
||
|
||
var absHref = elm.prop('href'); |
||
|
||
if (isObject(absHref) && absHref.toString() === '[object SVGAnimatedString]') { |
||
// SVGAnimatedString.animVal should be identical to SVGAnimatedString.baseVal, unless during |
||
// an animation. |
||
absHref = urlResolve(absHref.animVal).href; |
||
} |
||
|
||
var rewrittenUrl = $location.$$rewrite(absHref); |
||
|
||
if (absHref && !elm.attr('target') && rewrittenUrl && !event.isDefaultPrevented()) { |
||
event.preventDefault(); |
||
if (rewrittenUrl != $browser.url()) { |
||
// update location manually |
||
$location.$$parse(rewrittenUrl); |
||
$rootScope.$apply(); |
||
// hack to work around FF6 bug 684208 when scenario runner clicks on links |
||
window.angular['ff-684208-preventDefault'] = true; |
||
} |
||
} |
||
}); |
||
|
||
|
||
// rewrite hashbang url <> html5 url |
||
if ($location.absUrl() != initialUrl) { |
||
$browser.url($location.absUrl(), true); |
||
} |
||
|
||
// update $location when $browser url changes |
||
$browser.onUrlChange(function(newUrl) { |
||
if ($location.absUrl() != newUrl) { |
||
$rootScope.$evalAsync(function() { |
||
var oldUrl = $location.absUrl(); |
||
|
||
$location.$$parse(newUrl); |
||
if ($rootScope.$broadcast('$locationChangeStart', newUrl, |
||
oldUrl).defaultPrevented) { |
||
$location.$$parse(oldUrl); |
||
$browser.url(oldUrl); |
||
} else { |
||
afterLocationChange(oldUrl); |
||
} |
||
}); |
||
if (!$rootScope.$$phase) $rootScope.$digest(); |
||
} |
||
}); |
||
|
||
// update browser |
||
var changeCounter = 0; |
||
$rootScope.$watch(function $locationWatch() { |
||
var oldUrl = $browser.url(); |
||
var currentReplace = $location.$$replace; |
||
|
||
if (!changeCounter || oldUrl != $location.absUrl()) { |
||
changeCounter++; |
||
$rootScope.$evalAsync(function() { |
||
if ($rootScope.$broadcast('$locationChangeStart', $location.absUrl(), oldUrl). |
||
defaultPrevented) { |
||
$location.$$parse(oldUrl); |
||
} else { |
||
$browser.url($location.absUrl(), currentReplace); |
||
afterLocationChange(oldUrl); |
||
} |
||
}); |
||
} |
||
$location.$$replace = false; |
||
|
||
return changeCounter; |
||
}); |
||
|
||
return $location; |
||
|
||
function afterLocationChange(oldUrl) { |
||
$rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl); |
||
} |
||
}]; |
||
} |
||
|
||
/** |
||
* @ngdoc object |
||
* @name ng.$log |
||
* @requires $window |
||
* |
||
* @description |
||
* Simple service for logging. Default implementation safely writes the message |
||
* into the browser's console (if present). |
||
* |
||
* The main purpose of this service is to simplify debugging and troubleshooting. |
||
* |
||
* The default is to log `debug` messages. You can use |
||
* {@link ng.$logProvider ng.$logProvider#debugEnabled} to change this. |
||
* |
||
* @example |
||
<example> |
||
<file name="script.js"> |
||
function LogCtrl($scope, $log) { |
||
$scope.$log = $log; |
||
$scope.message = 'Hello World!'; |
||
} |
||
</file> |
||
<file name="index.html"> |
||
<div ng-controller="LogCtrl"> |
||
<p>Reload this page with open console, enter text and hit the log button...</p> |
||
Message: |
||
<input type="text" ng-model="message"/> |
||
<button ng-click="$log.log(message)">log</button> |
||
<button ng-click="$log.warn(message)">warn</button> |
||
<button ng-click="$log.info(message)">info</button> |
||
<button ng-click="$log.error(message)">error</button> |
||
</div> |
||
</file> |
||
</example> |
||
*/ |
||
|
||
/** |
||
* @ngdoc object |
||
* @name ng.$logProvider |
||
* @description |
||
* Use the `$logProvider` to configure how the application logs messages |
||
*/ |
||
function $LogProvider(){ |
||
var debug = true, |
||
self = this; |
||
|
||
/** |
||
* @ngdoc property |
||
* @name ng.$logProvider#debugEnabled |
||
* @methodOf ng.$logProvider |
||
* @description |
||
* @param {string=} flag enable or disable debug level messages |
||
* @returns {*} current value if used as getter or itself (chaining) if used as setter |
||
*/ |
||
this.debugEnabled = function(flag) { |
||
if (isDefined(flag)) { |
||
debug = flag; |
||
return this; |
||
} else { |
||
return debug; |
||
} |
||
}; |
||
|
||
this.$get = ['$window', function($window){ |
||
return { |
||
/** |
||
* @ngdoc method |
||
* @name ng.$log#log |
||
* @methodOf ng.$log |
||
* |
||
* @description |
||
* Write a log message |
||
*/ |
||
log: consoleLog('log'), |
||
|
||
/** |
||
* @ngdoc method |
||
* @name ng.$log#info |
||
* @methodOf ng.$log |
||
* |
||
* @description |
||
* Write an information message |
||
*/ |
||
info: consoleLog('info'), |
||
|
||
/** |
||
* @ngdoc method |
||
* @name ng.$log#warn |
||
* @methodOf ng.$log |
||
* |
||
* @description |
||
* Write a warning message |
||
*/ |
||
warn: consoleLog('warn'), |
||
|
||
/** |
||
* @ngdoc method |
||
* @name ng.$log#error |
||
* @methodOf ng.$log |
||
* |
||
* @description |
||
* Write an error message |
||
*/ |
||
error: consoleLog('error'), |
||
|
||
/** |
||
* @ngdoc method |
||
* @name ng.$log#debug |
||
* @methodOf ng.$log |
||
* |
||
* @description |
||
* Write a debug message |
||
*/ |
||
debug: (function () { |
||
var fn = consoleLog('debug'); |
||
|
||
return function() { |
||
if (debug) { |
||
fn.apply(self, arguments); |
||
} |
||
}; |
||
}()) |
||
}; |
||
|
||
function formatError(arg) { |
||
if (arg instanceof Error) { |
||
if (arg.stack) { |
||
arg = (arg.message && arg.stack.indexOf(arg.message) === -1) |
||
? 'Error: ' + arg.message + '\n' + arg.stack |
||
: arg.stack; |
||
} else if (arg.sourceURL) { |
||
arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line; |
||
} |
||
} |
||
return arg; |
||
} |
||
|
||
function consoleLog(type) { |
||
var console = $window.console || {}, |
||
logFn = console[type] || console.log || noop, |
||
hasApply = false; |
||
|
||
// Note: reading logFn.apply throws an error in IE11 in IE8 document mode. |
||
// The reason behind this is that console.log has type "object" in IE8... |
||
try { |
||
hasApply = !! logFn.apply; |
||
} catch (e) {} |
||
|
||
if (hasApply) { |
||
return function() { |
||
var args = []; |
||
forEach(arguments, function(arg) { |
||
args.push(formatError(arg)); |
||
}); |
||
return logFn.apply(console, args); |
||
}; |
||
} |
||
|
||
// we are IE which either doesn't have window.console => this is noop and we do nothing, |
||
// or we are IE where console.log doesn't have apply so we log at least first 2 args |
||
return function(arg1, arg2) { |
||
logFn(arg1, arg2 == null ? '' : arg2); |
||
}; |
||
} |
||
}]; |
||
} |
||
|
||
var $parseMinErr = minErr('$parse'); |
||
var promiseWarningCache = {}; |
||
var promiseWarning; |
||
|
||
// Sandboxing Angular Expressions |
||
// ------------------------------ |
||
// Angular expressions are generally considered safe because these expressions only have direct |
||
// access to $scope and locals. However, one can obtain the ability to execute arbitrary JS code by |
||
// obtaining a reference to native JS functions such as the Function constructor. |
||
// |
||
// As an example, consider the following Angular expression: |
||
// |
||
// {}.toString.constructor(alert("evil JS code")) |
||
// |
||
// We want to prevent this type of access. For the sake of performance, during the lexing phase we |
||
// disallow any "dotted" access to any member named "constructor". |
||
// |
||
// For reflective calls (a[b]) we check that the value of the lookup is not the Function constructor |
||
// while evaluating the expression, which is a stronger but more expensive test. Since reflective |
||
// calls are expensive anyway, this is not such a big deal compared to static dereferencing. |
||
// |
||
// This sandboxing technique is not perfect and doesn't aim to be. The goal is to prevent exploits |
||
// against the expression language, but not to prevent exploits that were enabled by exposing |
||
// sensitive JavaScript or browser apis on Scope. Exposing such objects on a Scope is never a good |
||
// practice and therefore we are not even trying to protect against interaction with an object |
||
// explicitly exposed in this way. |
||
// |
||
// A developer could foil the name check by aliasing the Function constructor under a different |
||
// name on the scope. |
||
// |
||
// In general, it is not possible to access a Window object from an angular expression unless a |
||
// window or some DOM object that has a reference to window is published onto a Scope. |
||
|
||
function ensureSafeMemberName(name, fullExpression) { |
||
if (name === "constructor") { |
||
throw $parseMinErr('isecfld', |
||
'Referencing "constructor" field in Angular expressions is disallowed! Expression: {0}', |
||
fullExpression); |
||
} |
||
return name; |
||
} |
||
|
||
function ensureSafeObject(obj, fullExpression) { |
||
// nifty check if obj is Function that is fast and works across iframes and other contexts |
||
if (obj) { |
||
if (obj.constructor === obj) { |
||
throw $parseMinErr('isecfn', |
||
'Referencing Function in Angular expressions is disallowed! Expression: {0}', |
||
fullExpression); |
||
} else if (// isWindow(obj) |
||
obj.document && obj.location && obj.alert && obj.setInterval) { |
||
throw $parseMinErr('isecwindow', |
||
'Referencing the Window in Angular expressions is disallowed! Expression: {0}', |
||
fullExpression); |
||
} else if (// isElement(obj) |
||
obj.children && (obj.nodeName || (obj.on && obj.find))) { |
||
throw $parseMinErr('isecdom', |
||
'Referencing DOM nodes in Angular expressions is disallowed! Expression: {0}', |
||
fullExpression); |
||
} |
||
} |
||
return obj; |
||
} |
||
|
||
var OPERATORS = { |
||
/* jshint bitwise : false */ |
||
'null':function(){return null;}, |
||
'true':function(){return true;}, |
||
'false':function(){return false;}, |
||
undefined:noop, |
||
'+':function(self, locals, a,b){ |
||
a=a(self, locals); b=b(self, locals); |
||
if (isDefined(a)) { |
||
if (isDefined(b)) { |
||
return a + b; |
||
} |
||
return a; |
||
} |
||
return isDefined(b)?b:undefined;}, |
||
'-':function(self, locals, a,b){ |
||
a=a(self, locals); b=b(self, locals); |
||
return (isDefined(a)?a:0)-(isDefined(b)?b:0); |
||
}, |
||
'*':function(self, locals, a,b){return a(self, locals)*b(self, locals);}, |
||
'/':function(self, locals, a,b){return a(self, locals)/b(self, locals);}, |
||
'%':function(self, locals, a,b){return a(self, locals)%b(self, locals);}, |
||
'^':function(self, locals, a,b){return a(self, locals)^b(self, locals);}, |
||
'=':noop, |
||
'===':function(self, locals, a, b){return a(self, locals)===b(self, locals);}, |
||
'!==':function(self, locals, a, b){return a(self, locals)!==b(self, locals);}, |
||
'==':function(self, locals, a,b){return a(self, locals)==b(self, locals);}, |
||
'!=':function(self, locals, a,b){return a(self, locals)!=b(self, locals);}, |
||
'<':function(self, locals, a,b){return a(self, locals)<b(self, locals);}, |
||
'>':function(self, locals, a,b){return a(self, locals)>b(self, locals);}, |
||
'<=':function(self, locals, a,b){return a(self, locals)<=b(self, locals);}, |
||
'>=':function(self, locals, a,b){return a(self, locals)>=b(self, locals);}, |
||
'&&':function(self, locals, a,b){return a(self, locals)&&b(self, locals);}, |
||
'||':function(self, locals, a,b){return a(self, locals)||b(self, locals);}, |
||
'&':function(self, locals, a,b){return a(self, locals)&b(self, locals);}, |
||
// '|':function(self, locals, a,b){return a|b;}, |
||
'|':function(self, locals, a,b){return b(self, locals)(self, locals, a(self, locals));}, |
||
'!':function(self, locals, a){return !a(self, locals);} |
||
}; |
||
/* jshint bitwise: true */ |
||
var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'}; |
||
|
||
|
||
///////////////////////////////////////// |
||
|
||
|
||
/** |
||
* @constructor |
||
*/ |
||
var Lexer = function (options) { |
||
this.options = options; |
||
}; |
||
|
||
Lexer.prototype = { |
||
constructor: Lexer, |
||
|
||
lex: function (text) { |
||
this.text = text; |
||
|
||
this.index = 0; |
||
this.ch = undefined; |
||
this.lastCh = ':'; // can start regexp |
||
|
||
this.tokens = []; |
||
|
||
var token; |
||
var json = []; |
||
|
||
while (this.index < this.text.length) { |
||
this.ch = this.text.charAt(this.index); |
||
if (this.is('"\'')) { |
||
this.readString(this.ch); |
||
} else if (this.isNumber(this.ch) || this.is('.') && this.isNumber(this.peek())) { |
||
this.readNumber(); |
||
} else if (this.isIdent(this.ch)) { |
||
this.readIdent(); |
||
// identifiers can only be if the preceding char was a { or , |
||
if (this.was('{,') && json[0] === '{' && |
||
(token = this.tokens[this.tokens.length - 1])) { |
||
token.json = token.text.indexOf('.') === -1; |
||
} |
||
} else if (this.is('(){}[].,;:?')) { |
||
this.tokens.push({ |
||
index: this.index, |
||
text: this.ch, |
||
json: (this.was(':[,') && this.is('{[')) || this.is('}]:,') |
||
}); |
||
if (this.is('{[')) json.unshift(this.ch); |
||
if (this.is('}]')) json.shift(); |
||
this.index++; |
||
} else if (this.isWhitespace(this.ch)) { |
||
this.index++; |
||
continue; |
||
} else { |
||
var ch2 = this.ch + this.peek(); |
||
var ch3 = ch2 + this.peek(2); |
||
var fn = OPERATORS[this.ch]; |
||
var fn2 = OPERATORS[ch2]; |
||
var fn3 = OPERATORS[ch3]; |
||
if (fn3) { |
||
this.tokens.push({index: this.index, text: ch3, fn: fn3}); |
||
this.index += 3; |
||
} else if (fn2) { |
||
this.tokens.push({index: this.index, text: ch2, fn: fn2}); |
||
this.index += 2; |
||
} else if (fn) { |
||
this.tokens.push({ |
||
index: this.index, |
||
text: this.ch, |
||
fn: fn, |
||
json: (this.was('[,:') && this.is('+-')) |
||
}); |
||
this.index += 1; |
||
} else { |
||
this.throwError('Unexpected next character ', this.index, this.index + 1); |
||
} |
||
} |
||
this.lastCh = this.ch; |
||
} |
||
return this.tokens; |
||
}, |
||
|
||
is: function(chars) { |
||
return chars.indexOf(this.ch) !== -1; |
||
}, |
||
|
||
was: function(chars) { |
||
return chars.indexOf(this.lastCh) !== -1; |
||
}, |
||
|
||
peek: function(i) { |
||
var num = i || 1; |
||
return (this.index + num < this.text.length) ? this.text.charAt(this.index + num) : false; |
||
}, |
||
|
||
isNumber: function(ch) { |
||
return ('0' <= ch && ch <= '9'); |
||
}, |
||
|
||
isWhitespace: function(ch) { |
||
// IE treats non-breaking space as \u00A0 |
||
return (ch === ' ' || ch === '\r' || ch === '\t' || |
||
ch === '\n' || ch === '\v' || ch === '\u00A0'); |
||
}, |
||
|
||
isIdent: function(ch) { |
||
return ('a' <= ch && ch <= 'z' || |
||
'A' <= ch && ch <= 'Z' || |
||
'_' === ch || ch === '$'); |
||
}, |
||
|
||
isExpOperator: function(ch) { |
||
return (ch === '-' || ch === '+' || this.isNumber(ch)); |
||
}, |
||
|
||
throwError: function(error, start, end) { |
||
end = end || this.index; |
||
var colStr = (isDefined(start) |
||
? 's ' + start + '-' + this.index + ' [' + this.text.substring(start, end) + ']' |
||
: ' ' + end); |
||
throw $parseMinErr('lexerr', 'Lexer Error: {0} at column{1} in expression [{2}].', |
||
error, colStr, this.text); |
||
}, |
||
|
||
readNumber: function() { |
||
var number = ''; |
||
var start = this.index; |
||
while (this.index < this.text.length) { |
||
var ch = lowercase(this.text.charAt(this.index)); |
||
if (ch == '.' || this.isNumber(ch)) { |
||
number += ch; |
||
} else { |
||
var peekCh = this.peek(); |
||
if (ch == 'e' && this.isExpOperator(peekCh)) { |
||
number += ch; |
||
} else if (this.isExpOperator(ch) && |
||
peekCh && this.isNumber(peekCh) && |
||
number.charAt(number.length - 1) == 'e') { |
||
number += ch; |
||
} else if (this.isExpOperator(ch) && |
||
(!peekCh || !this.isNumber(peekCh)) && |
||
number.charAt(number.length - 1) == 'e') { |
||
this.throwError('Invalid exponent'); |
||
} else { |
||
break; |
||
} |
||
} |
||
this.index++; |
||
} |
||
number = 1 * number; |
||
this.tokens.push({ |
||
index: start, |
||
text: number, |
||
json: true, |
||
fn: function() { return number; } |
||
}); |
||
}, |
||
|
||
readIdent: function() { |
||
var parser = this; |
||
|
||
var ident = ''; |
||
var start = this.index; |
||
|
||
var lastDot, peekIndex, methodName, ch; |
||
|
||
while (this.index < this.text.length) { |
||
ch = this.text.charAt(this.index); |
||
if (ch === '.' || this.isIdent(ch) || this.isNumber(ch)) { |
||
if (ch === '.') lastDot = this.index; |
||
ident += ch; |
||
} else { |
||
break; |
||
} |
||
this.index++; |
||
} |
||
|
||
//check if this is not a method invocation and if it is back out to last dot |
||
if (lastDot) { |
||
peekIndex = this.index; |
||
while (peekIndex < this.text.length) { |
||
ch = this.text.charAt(peekIndex); |
||
if (ch === '(') { |
||
methodName = ident.substr(lastDot - start + 1); |
||
ident = ident.substr(0, lastDot - start); |
||
this.index = peekIndex; |
||
break; |
||
} |
||
if (this.isWhitespace(ch)) { |
||
peekIndex++; |
||
} else { |
||
break; |
||
} |
||
} |
||
} |
||
|
||
|
||
var token = { |
||
index: start, |
||
text: ident |
||
}; |
||
|
||
// OPERATORS is our own object so we don't need to use special hasOwnPropertyFn |
||
if (OPERATORS.hasOwnProperty(ident)) { |
||
token.fn = OPERATORS[ident]; |
||
token.json = OPERATORS[ident]; |
||
} else { |
||
var getter = getterFn(ident, this.options, this.text); |
||
token.fn = extend(function(self, locals) { |
||
return (getter(self, locals)); |
||
}, { |
||
assign: function(self, value) { |
||
return setter(self, ident, value, parser.text, parser.options); |
||
} |
||
}); |
||
} |
||
|
||
this.tokens.push(token); |
||
|
||
if (methodName) { |
||
this.tokens.push({ |
||
index:lastDot, |
||
text: '.', |
||
json: false |
||
}); |
||
this.tokens.push({ |
||
index: lastDot + 1, |
||
text: methodName, |
||
json: false |
||
}); |
||
} |
||
}, |
||
|
||
readString: function(quote) { |
||
var start = this.index; |
||
this.index++; |
||
var string = ''; |
||
var rawString = quote; |
||
var escape = false; |
||
while (this.index < this.text.length) { |
||
var ch = this.text.charAt(this.index); |
||
rawString += ch; |
||
if (escape) { |
||
if (ch === 'u') { |
||
var hex = this.text.substring(this.index + 1, this.index + 5); |
||
if (!hex.match(/[\da-f]{4}/i)) |
||
this.throwError('Invalid unicode escape [\\u' + hex + ']'); |
||
this.index += 4; |
||
string += String.fromCharCode(parseInt(hex, 16)); |
||
} else { |
||
var rep = ESCAPE[ch]; |
||
if (rep) { |
||
string += rep; |
||
} else { |
||
string += ch; |
||
} |
||
} |
||
escape = false; |
||
} else if (ch === '\\') { |
||
escape = true; |
||
} else if (ch === quote) { |
||
this.index++; |
||
this.tokens.push({ |
||
index: start, |
||
text: rawString, |
||
string: string, |
||
json: true, |
||
fn: function() { return string; } |
||
}); |
||
return; |
||
} else { |
||
string += ch; |
||
} |
||
this.index++; |
||
} |
||
this.throwError('Unterminated quote', start); |
||
} |
||
}; |
||
|
||
|
||
/** |
||
* @constructor |
||
*/ |
||
var Parser = function (lexer, $filter, options) { |
||
this.lexer = lexer; |
||
this.$filter = $filter; |
||
this.options = options; |
||
}; |
||
|
||
Parser.ZERO = function () { return 0; }; |
||
|
||
Parser.prototype = { |
||
constructor: Parser, |
||
|
||
parse: function (text, json) { |
||
this.text = text; |
||
|
||
//TODO(i): strip all the obsolte json stuff from this file |
||
this.json = json; |
||
|
||
this.tokens = this.lexer.lex(text); |
||
|
||
if (json) { |
||
// The extra level of aliasing is here, just in case the lexer misses something, so that |
||
// we prevent any accidental execution in JSON. |
||
this.assignment = this.logicalOR; |
||
|
||
this.functionCall = |
||
this.fieldAccess = |
||
this.objectIndex = |
||
this.filterChain = function() { |
||
this.throwError('is not valid json', {text: text, index: 0}); |
||
}; |
||
} |
||
|
||
var value = json ? this.primary() : this.statements(); |
||
|
||
if (this.tokens.length !== 0) { |
||
this.throwError('is an unexpected token', this.tokens[0]); |
||
} |
||
|
||
value.literal = !!value.literal; |
||
value.constant = !!value.constant; |
||
|
||
return value; |
||
}, |
||
|
||
primary: function () { |
||
var primary; |
||
if (this.expect('(')) { |
||
primary = this.filterChain(); |
||
this.consume(')'); |
||
} else if (this.expect('[')) { |
||
primary = this.arrayDeclaration(); |
||
} else if (this.expect('{')) { |
||
primary = this.object(); |
||
} else { |
||
var token = this.expect(); |
||
primary = token.fn; |
||
if (!primary) { |
||
this.throwError('not a primary expression', token); |
||
} |
||
if (token.json) { |
||
primary.constant = true; |
||
primary.literal = true; |
||
} |
||
} |
||
|
||
var next, context; |
||
while ((next = this.expect('(', '[', '.'))) { |
||
if (next.text === '(') { |
||
primary = this.functionCall(primary, context); |
||
context = null; |
||
} else if (next.text === '[') { |
||
context = primary; |
||
primary = this.objectIndex(primary); |
||
} else if (next.text === '.') { |
||
context = primary; |
||
primary = this.fieldAccess(primary); |
||
} else { |
||
this.throwError('IMPOSSIBLE'); |
||
} |
||
} |
||
return primary; |
||
}, |
||
|
||
throwError: function(msg, token) { |
||
throw $parseMinErr('syntax', |
||
'Syntax Error: Token \'{0}\' {1} at column {2} of the expression [{3}] starting at [{4}].', |
||
token.text, msg, (token.index + 1), this.text, this.text.substring(token.index)); |
||
}, |
||
|
||
peekToken: function() { |
||
if (this.tokens.length === 0) |
||
throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text); |
||
return this.tokens[0]; |
||
}, |
||
|
||
peek: function(e1, e2, e3, e4) { |
||
if (this.tokens.length > 0) { |
||
var token = this.tokens[0]; |
||
var t = token.text; |
||
if (t === e1 || t === e2 || t === e3 || t === e4 || |
||
(!e1 && !e2 && !e3 && !e4)) { |
||
return token; |
||
} |
||
} |
||
return false; |
||
}, |
||
|
||
expect: function(e1, e2, e3, e4){ |
||
var token = this.peek(e1, e2, e3, e4); |
||
if (token) { |
||
if (this.json && !token.json) { |
||
this.throwError('is not valid json', token); |
||
} |
||
this.tokens.shift(); |
||
return token; |
||
} |
||
return false; |
||
}, |
||
|
||
consume: function(e1){ |
||
if (!this.expect(e1)) { |
||
this.throwError('is unexpected, expecting [' + e1 + ']', this.peek()); |
||
} |
||
}, |
||
|
||
unaryFn: function(fn, right) { |
||
return extend(function(self, locals) { |
||
return fn(self, locals, right); |
||
}, { |
||
constant:right.constant |
||
}); |
||
}, |
||
|
||
ternaryFn: function(left, middle, right){ |
||
return extend(function(self, locals){ |
||
return left(self, locals) ? middle(self, locals) : right(self, locals); |
||
}, { |
||
constant: left.constant && middle.constant && right.constant |
||
}); |
||
}, |
||
|
||
binaryFn: function(left, fn, right) { |
||
return extend(function(self, locals) { |
||
return fn(self, locals, left, right); |
||
}, { |
||
constant:left.constant && right.constant |
||
}); |
||
}, |
||
|
||
statements: function() { |
||
var statements = []; |
||
while (true) { |
||
if (this.tokens.length > 0 && !this.peek('}', ')', ';', ']')) |
||
statements.push(this.filterChain()); |
||
if (!this.expect(';')) { |
||
// optimize for the common case where there is only one statement. |
||
// TODO(size): maybe we should not support multiple statements? |
||
return (statements.length === 1) |
||
? statements[0] |
||
: function(self, locals) { |
||
var value; |
||
for (var i = 0; i < statements.length; i++) { |
||
var statement = statements[i]; |
||
if (statement) { |
||
value = statement(self, locals); |
||
} |
||
} |
||
return value; |
||
}; |
||
} |
||
} |
||
}, |
||
|
||
filterChain: function() { |
||
var left = this.expression(); |
||
var token; |
||
while (true) { |
||
if ((token = this.expect('|'))) { |
||
left = this.binaryFn(left, token.fn, this.filter()); |
||
} else { |
||
return left; |
||
} |
||
} |
||
}, |
||
|
||
filter: function() { |
||
var token = this.expect(); |
||
var fn = this.$filter(token.text); |
||
var argsFn = []; |
||
while (true) { |
||
if ((token = this.expect(':'))) { |
||
argsFn.push(this.expression()); |
||
} else { |
||
var fnInvoke = function(self, locals, input) { |
||
var args = [input]; |
||
for (var i = 0; i < argsFn.length; i++) { |
||
args.push(argsFn[i](self, locals)); |
||
} |
||
return fn.apply(self, args); |
||
}; |
||
return function() { |
||
return fnInvoke; |
||
}; |
||
} |
||
} |
||
}, |
||
|
||
expression: function() { |
||
return this.assignment(); |
||
}, |
||
|
||
assignment: function() { |
||
var left = this.ternary(); |
||
var right; |
||
var token; |
||
if ((token = this.expect('='))) { |
||
if (!left.assign) { |
||
this.throwError('implies assignment but [' + |
||
this.text.substring(0, token.index) + '] can not be assigned to', token); |
||
} |
||
right = this.ternary(); |
||
return function(scope, locals) { |
||
return left.assign(scope, right(scope, locals), locals); |
||
}; |
||
} |
||
return left; |
||
}, |
||
|
||
ternary: function() { |
||
var left = this.logicalOR(); |
||
var middle; |
||
var token; |
||
if ((token = this.expect('?'))) { |
||
middle = this.ternary(); |
||
if ((token = this.expect(':'))) { |
||
return this.ternaryFn(left, middle, this.ternary()); |
||
} else { |
||
this.throwError('expected :', token); |
||
} |
||
} else { |
||
return left; |
||
} |
||
}, |
||
|
||
logicalOR: function() { |
||
var left = this.logicalAND(); |
||
var token; |
||
while (true) { |
||
if ((token = this.expect('||'))) { |
||
left = this.binaryFn(left, token.fn, this.logicalAND()); |
||
} else { |
||
return left; |
||
} |
||
} |
||
}, |
||
|
||
logicalAND: function() { |
||
var left = this.equality(); |
||
var token; |
||
if ((token = this.expect('&&'))) { |
||
left = this.binaryFn(left, token.fn, this.logicalAND()); |
||
} |
||
return left; |
||
}, |
||
|
||
equality: function() { |
||
var left = this.relational(); |
||
var token; |
||
if ((token = this.expect('==','!=','===','!=='))) { |
||
left = this.binaryFn(left, token.fn, this.equality()); |
||
} |
||
return left; |
||
}, |
||
|
||
relational: function() { |
||
var left = this.additive(); |
||
var token; |
||
if ((token = this.expect('<', '>', '<=', '>='))) { |
||
left = this.binaryFn(left, token.fn, this.relational()); |
||
} |
||
return left; |
||
}, |
||
|
||
additive: function() { |
||
var left = this.multiplicative(); |
||
var token; |
||
while ((token = this.expect('+','-'))) { |
||
left = this.binaryFn(left, token.fn, this.multiplicative()); |
||
} |
||
return left; |
||
}, |
||
|
||
multiplicative: function() { |
||
var left = this.unary(); |
||
var token; |
||
while ((token = this.expect('*','/','%'))) { |
||
left = this.binaryFn(left, token.fn, this.unary()); |
||
} |
||
return left; |
||
}, |
||
|
||
unary: function() { |
||
var token; |
||
if (this.expect('+')) { |
||
return this.primary(); |
||
} else if ((token = this.expect('-'))) { |
||
return this.binaryFn(Parser.ZERO, token.fn, this.unary()); |
||
} else if ((token = this.expect('!'))) { |
||
return this.unaryFn(token.fn, this.unary()); |
||
} else { |
||
return this.primary(); |
||
} |
||
}, |
||
|
||
fieldAccess: function(object) { |
||
var parser = this; |
||
var field = this.expect().text; |
||
var getter = getterFn(field, this.options, this.text); |
||
|
||
return extend(function(scope, locals, self) { |
||
return getter(self || object(scope, locals), locals); |
||
}, { |
||
assign: function(scope, value, locals) { |
||
return setter(object(scope, locals), field, value, parser.text, parser.options); |
||
} |
||
}); |
||
}, |
||
|
||
objectIndex: function(obj) { |
||
var parser = this; |
||
|
||
var indexFn = this.expression(); |
||
this.consume(']'); |
||
|
||
return extend(function(self, locals) { |
||
var o = obj(self, locals), |
||
i = indexFn(self, locals), |
||
v, p; |
||
|
||
if (!o) return undefined; |
||
v = ensureSafeObject(o[i], parser.text); |
||
if (v && v.then && parser.options.unwrapPromises) { |
||
p = v; |
||
if (!('$$v' in v)) { |
||
p.$$v = undefined; |
||
p.then(function(val) { p.$$v = val; }); |
||
} |
||
v = v.$$v; |
||
} |
||
return v; |
||
}, { |
||
assign: function(self, value, locals) { |
||
var key = indexFn(self, locals); |
||
// prevent overwriting of Function.constructor which would break ensureSafeObject check |
||
var safe = ensureSafeObject(obj(self, locals), parser.text); |
||
return safe[key] = value; |
||
} |
||
}); |
||
}, |
||
|
||
functionCall: function(fn, contextGetter) { |
||
var argsFn = []; |
||
if (this.peekToken().text !== ')') { |
||
do { |
||
argsFn.push(this.expression()); |
||
} while (this.expect(',')); |
||
} |
||
this.consume(')'); |
||
|
||
var parser = this; |
||
|
||
return function(scope, locals) { |
||
var args = []; |
||
var context = contextGetter ? contextGetter(scope, locals) : scope; |
||
|
||
for (var i = 0; i < argsFn.length; i++) { |
||
args.push(argsFn[i](scope, locals)); |
||
} |
||
var fnPtr = fn(scope, locals, context) || noop; |
||
|
||
ensureSafeObject(context, parser.text); |
||
ensureSafeObject(fnPtr, parser.text); |
||
|
||
// IE stupidity! (IE doesn't have apply for some native functions) |
||
var v = fnPtr.apply |
||
? fnPtr.apply(context, args) |
||
: fnPtr(args[0], args[1], args[2], args[3], args[4]); |
||
|
||
return ensureSafeObject(v, parser.text); |
||
}; |
||
}, |
||
|
||
// This is used with json array declaration |
||
arrayDeclaration: function () { |
||
var elementFns = []; |
||
var allConstant = true; |
||
if (this.peekToken().text !== ']') { |
||
do { |
||
var elementFn = this.expression(); |
||
elementFns.push(elementFn); |
||
if (!elementFn.constant) { |
||
allConstant = false; |
||
} |
||
} while (this.expect(',')); |
||
} |
||
this.consume(']'); |
||
|
||
return extend(function(self, locals) { |
||
var array = []; |
||
for (var i = 0; i < elementFns.length; i++) { |
||
array.push(elementFns[i](self, locals)); |
||
} |
||
return array; |
||
}, { |
||
literal: true, |
||
constant: allConstant |
||
}); |
||
}, |
||
|
||
object: function () { |
||
var keyValues = []; |
||
var allConstant = true; |
||
if (this.peekToken().text !== '}') { |
||
do { |
||
var token = this.expect(), |
||
key = token.string || token.text; |
||
this.consume(':'); |
||
var value = this.expression(); |
||
keyValues.push({key: key, value: value}); |
||
if (!value.constant) { |
||
allConstant = false; |
||
} |
||
} while (this.expect(',')); |
||
} |
||
this.consume('}'); |
||
|
||
return extend(function(self, locals) { |
||
var object = {}; |
||
for (var i = 0; i < keyValues.length; i++) { |
||
var keyValue = keyValues[i]; |
||
object[keyValue.key] = keyValue.value(self, locals); |
||
} |
||
return object; |
||
}, { |
||
literal: true, |
||
constant: allConstant |
||
}); |
||
} |
||
}; |
||
|
||
|
||
////////////////////////////////////////////////// |
||
// Parser helper functions |
||
////////////////////////////////////////////////// |
||
|
||
function setter(obj, path, setValue, fullExp, options) { |
||
//needed? |
||
options = options || {}; |
||
|
||
var element = path.split('.'), key; |
||
for (var i = 0; element.length > 1; i++) { |
||
key = ensureSafeMemberName(element.shift(), fullExp); |
||
var propertyObj = obj[key]; |
||
if (!propertyObj) { |
||
propertyObj = {}; |
||
obj[key] = propertyObj; |
||
} |
||
obj = propertyObj; |
||
if (obj.then && options.unwrapPromises) { |
||
promiseWarning(fullExp); |
||
if (!("$$v" in obj)) { |
||
(function(promise) { |
||
promise.then(function(val) { promise.$$v = val; }); } |
||
)(obj); |
||
} |
||
if (obj.$$v === undefined) { |
||
obj.$$v = {}; |
||
} |
||
obj = obj.$$v; |
||
} |
||
} |
||
key = ensureSafeMemberName(element.shift(), fullExp); |
||
obj[key] = setValue; |
||
return setValue; |
||
} |
||
|
||
var getterFnCache = {}; |
||
|
||
/** |
||
* Implementation of the "Black Hole" variant from: |
||
* - http://jsperf.com/angularjs-parse-getter/4 |
||
* - http://jsperf.com/path-evaluation-simplified/7 |
||
*/ |
||
function cspSafeGetterFn(key0, key1, key2, key3, key4, fullExp, options) { |
||
ensureSafeMemberName(key0, fullExp); |
||
ensureSafeMemberName(key1, fullExp); |
||
ensureSafeMemberName(key2, fullExp); |
||
ensureSafeMemberName(key3, fullExp); |
||
ensureSafeMemberName(key4, fullExp); |
||
|
||
return !options.unwrapPromises |
||
? function cspSafeGetter(scope, locals) { |
||
var pathVal = (locals && locals.hasOwnProperty(key0)) ? locals : scope; |
||
|
||
if (pathVal == null) return pathVal; |
||
pathVal = pathVal[key0]; |
||
|
||
if (!key1) return pathVal; |
||
if (pathVal == null) return undefined; |
||
pathVal = pathVal[key1]; |
||
|
||
if (!key2) return pathVal; |
||
if (pathVal == null) return undefined; |
||
pathVal = pathVal[key2]; |
||
|
||
if (!key3) return pathVal; |
||
if (pathVal == null) return undefined; |
||
pathVal = pathVal[key3]; |
||
|
||
if (!key4) return pathVal; |
||
if (pathVal == null) return undefined; |
||
pathVal = pathVal[key4]; |
||
|
||
return pathVal; |
||
} |
||
: function cspSafePromiseEnabledGetter(scope, locals) { |
||
var pathVal = (locals && locals.hasOwnProperty(key0)) ? locals : scope, |
||
promise; |
||
|
||
if (pathVal == null) return pathVal; |
||
|
||
pathVal = pathVal[key0]; |
||
if (pathVal && pathVal.then) { |
||
promiseWarning(fullExp); |
||
if (!("$$v" in pathVal)) { |
||
promise = pathVal; |
||
promise.$$v = undefined; |
||
promise.then(function(val) { promise.$$v = val; }); |
||
} |
||
pathVal = pathVal.$$v; |
||
} |
||
|
||
if (!key1) return pathVal; |
||
if (pathVal == null) return undefined; |
||
pathVal = pathVal[key1]; |
||
if (pathVal && pathVal.then) { |
||
promiseWarning(fullExp); |
||
if (!("$$v" in pathVal)) { |
||
promise = pathVal; |
||
promise.$$v = undefined; |
||
promise.then(function(val) { promise.$$v = val; }); |
||
} |
||
pathVal = pathVal.$$v; |
||
} |
||
|
||
if (!key2) return pathVal; |
||
if (pathVal == null) return undefined; |
||
pathVal = pathVal[key2]; |
||
if (pathVal && pathVal.then) { |
||
promiseWarning(fullExp); |
||
if (!("$$v" in pathVal)) { |
||
promise = pathVal; |
||
promise.$$v = undefined; |
||
promise.then(function(val) { promise.$$v = val; }); |
||
} |
||
pathVal = pathVal.$$v; |
||
} |
||
|
||
if (!key3) return pathVal; |
||
if (pathVal == null) return undefined; |
||
pathVal = pathVal[key3]; |
||
if (pathVal && pathVal.then) { |
||
promiseWarning(fullExp); |
||
if (!("$$v" in pathVal)) { |
||
promise = pathVal; |
||
promise.$$v = undefined; |
||
promise.then(function(val) { promise.$$v = val; }); |
||
} |
||
pathVal = pathVal.$$v; |
||
} |
||
|
||
if (!key4) return pathVal; |
||
if (pathVal == null) return undefined; |
||
pathVal = pathVal[key4]; |
||
if (pathVal && pathVal.then) { |
||
promiseWarning(fullExp); |
||
if (!("$$v" in pathVal)) { |
||
promise = pathVal; |
||
promise.$$v = undefined; |
||
promise.then(function(val) { promise.$$v = val; }); |
||
} |
||
pathVal = pathVal.$$v; |
||
} |
||
return pathVal; |
||
}; |
||
} |
||
|
||
function simpleGetterFn1(key0, fullExp) { |
||
ensureSafeMemberName(key0, fullExp); |
||
|
||
return function simpleGetterFn1(scope, locals) { |
||
if (scope == null) return undefined; |
||
return ((locals && locals.hasOwnProperty(key0)) ? locals : scope)[key0]; |
||
}; |
||
} |
||
|
||
function simpleGetterFn2(key0, key1, fullExp) { |
||
ensureSafeMemberName(key0, fullExp); |
||
ensureSafeMemberName(key1, fullExp); |
||
|
||
return function simpleGetterFn2(scope, locals) { |
||
if (scope == null) return undefined; |
||
scope = ((locals && locals.hasOwnProperty(key0)) ? locals : scope)[key0]; |
||
return scope == null ? undefined : scope[key1]; |
||
}; |
||
} |
||
|
||
function getterFn(path, options, fullExp) { |
||
// Check whether the cache has this getter already. |
||
// We can use hasOwnProperty directly on the cache because we ensure, |
||
// see below, that the cache never stores a path called 'hasOwnProperty' |
||
if (getterFnCache.hasOwnProperty(path)) { |
||
return getterFnCache[path]; |
||
} |
||
|
||
var pathKeys = path.split('.'), |
||
pathKeysLength = pathKeys.length, |
||
fn; |
||
|
||
// When we have only 1 or 2 tokens, use optimized special case closures. |
||
// http://jsperf.com/angularjs-parse-getter/6 |
||
if (!options.unwrapPromises && pathKeysLength === 1) { |
||
fn = simpleGetterFn1(pathKeys[0], fullExp); |
||
} else if (!options.unwrapPromises && pathKeysLength === 2) { |
||
fn = simpleGetterFn2(pathKeys[0], pathKeys[1], fullExp); |
||
} else if (options.csp) { |
||
if (pathKeysLength < 6) { |
||
fn = cspSafeGetterFn(pathKeys[0], pathKeys[1], pathKeys[2], pathKeys[3], pathKeys[4], fullExp, |
||
options); |
||
} else { |
||
fn = function(scope, locals) { |
||
var i = 0, val; |
||
do { |
||
val = cspSafeGetterFn(pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++], |
||
pathKeys[i++], fullExp, options)(scope, locals); |
||
|
||
locals = undefined; // clear after first iteration |
||
scope = val; |
||
} while (i < pathKeysLength); |
||
return val; |
||
}; |
||
} |
||
} else { |
||
var code = 'var p;\n'; |
||
forEach(pathKeys, function(key, index) { |
||
ensureSafeMemberName(key, fullExp); |
||
code += 'if(s == null) return undefined;\n' + |
||
's='+ (index |
||
// we simply dereference 's' on any .dot notation |
||
? 's' |
||
// but if we are first then we check locals first, and if so read it first |
||
: '((k&&k.hasOwnProperty("' + key + '"))?k:s)') + '["' + key + '"]' + ';\n' + |
||
(options.unwrapPromises |
||
? 'if (s && s.then) {\n' + |
||
' pw("' + fullExp.replace(/(["\r\n])/g, '\\$1') + '");\n' + |
||
' if (!("$$v" in s)) {\n' + |
||
' p=s;\n' + |
||
' p.$$v = undefined;\n' + |
||
' p.then(function(v) {p.$$v=v;});\n' + |
||
'}\n' + |
||
' s=s.$$v\n' + |
||
'}\n' |
||
: ''); |
||
}); |
||
code += 'return s;'; |
||
|
||
/* jshint -W054 */ |
||
var evaledFnGetter = new Function('s', 'k', 'pw', code); // s=scope, k=locals, pw=promiseWarning |
||
/* jshint +W054 */ |
||
evaledFnGetter.toString = valueFn(code); |
||
fn = options.unwrapPromises ? function(scope, locals) { |
||
return evaledFnGetter(scope, locals, promiseWarning); |
||
} : evaledFnGetter; |
||
} |
||
|
||
// Only cache the value if it's not going to mess up the cache object |
||
// This is more performant that using Object.prototype.hasOwnProperty.call |
||
if (path !== 'hasOwnProperty') { |
||
getterFnCache[path] = fn; |
||
} |
||
return fn; |
||
} |
||
|
||
/////////////////////////////////// |
||
|
||
/** |
||
* @ngdoc function |
||
* @name ng.$parse |
||
* @function |
||
* |
||
* @description |
||
* |
||
* Converts Angular {@link guide/expression expression} into a function. |
||
* |
||
* <pre> |
||
* var getter = $parse('user.name'); |
||
* var setter = getter.assign; |
||
* var context = {user:{name:'angular'}}; |
||
* var locals = {user:{name:'local'}}; |
||
* |
||
* expect(getter(context)).toEqual('angular'); |
||
* setter(context, 'newValue'); |
||
* expect(context.user.name).toEqual('newValue'); |
||
* expect(getter(context, locals)).toEqual('local'); |
||
* </pre> |
||
* |
||
* |
||
* @param {string} expression String expression to compile. |
||
* @returns {function(context, locals)} a function which represents the compiled expression: |
||
* |
||
* * `context` – `{object}` – an object against which any expressions embedded in the strings |
||
* are evaluated against (typically a scope object). |
||
* * `locals` – `{object=}` – local variables context object, useful for overriding values in |
||
* `context`. |
||
* |
||
* The returned function also has the following properties: |
||
* * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript |
||
* literal. |
||
* * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript |
||
* constant literals. |
||
* * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be |
||
* set to a function to change its value on the given context. |
||
* |
||
*/ |
||
|
||
|
||
/** |
||
* @ngdoc object |
||
* @name ng.$parseProvider |
||
* @function |
||
* |
||
* @description |
||
* `$parseProvider` can be used for configuring the default behavior of the {@link ng.$parse $parse} |
||
* service. |
||
*/ |
||
function $ParseProvider() { |
||
var cache = {}; |
||
|
||
var $parseOptions = { |
||
csp: false, |
||
unwrapPromises: false, |
||
logPromiseWarnings: true |
||
}; |
||
|
||
|
||
/** |
||
* @deprecated Promise unwrapping via $parse is deprecated and will be removed in the future. |
||
* |
||
* @ngdoc method |
||
* @name ng.$parseProvider#unwrapPromises |
||
* @methodOf ng.$parseProvider |
||
* @description |
||
* |
||
* **This feature is deprecated, see deprecation notes below for more info** |
||
* |
||
* If set to true (default is false), $parse will unwrap promises automatically when a promise is |
||
* found at any part of the expression. In other words, if set to true, the expression will always |
||
* result in a non-promise value. |
||
* |
||
* While the promise is unresolved, it's treated as undefined, but once resolved and fulfilled, |
||
* the fulfillment value is used in place of the promise while evaluating the expression. |
||
* |
||
* **Deprecation notice** |
||
* |
||
* This is a feature that didn't prove to be wildly useful or popular, primarily because of the |
||
* dichotomy between data access in templates (accessed as raw values) and controller code |
||
* (accessed as promises). |
||
* |
||
* In most code we ended up resolving promises manually in controllers anyway and thus unifying |
||
* the model access there. |
||
* |
||
* Other downsides of automatic promise unwrapping: |
||
* |
||
* - when building components it's often desirable to receive the raw promises |
||
* - adds complexity and slows down expression evaluation |
||
* - makes expression code pre-generation unattractive due to the amount of code that needs to be |
||
* generated |
||
* - makes IDE auto-completion and tool support hard |
||
* |
||
* **Warning Logs** |
||
* |
||
* If the unwrapping is enabled, Angular will log a warning about each expression that unwraps a |
||
* promise (to reduce the noise, each expression is logged only once). To disable this logging use |
||
* `$parseProvider.logPromiseWarnings(false)` api. |
||
* |
||
* |
||
* @param {boolean=} value New value. |
||
* @returns {boolean|self} Returns the current setting when used as getter and self if used as |
||
* setter. |
||
*/ |
||
this.unwrapPromises = function(value) { |
||
if (isDefined(value)) { |
||
$parseOptions.unwrapPromises = !!value; |
||
return this; |
||
} else { |
||
return $parseOptions.unwrapPromises; |
||
} |
||
}; |
||
|
||
|
||
/** |
||
* @deprecated Promise unwrapping via $parse is deprecated and will be removed in the future. |
||
* |
||
* @ngdoc method |
||
* @name ng.$parseProvider#logPromiseWarnings |
||
* @methodOf ng.$parseProvider |
||
* @description |
||
* |
||
* Controls whether Angular should log a warning on any encounter of a promise in an expression. |
||
* |
||
* The default is set to `true`. |
||
* |
||
* This setting applies only if `$parseProvider.unwrapPromises` setting is set to true as well. |
||
* |
||
* @param {boolean=} value New value. |
||
* @returns {boolean|self} Returns the current setting when used as getter and self if used as |
||
* setter. |
||
*/ |
||
this.logPromiseWarnings = function(value) { |
||
if (isDefined(value)) { |
||
$parseOptions.logPromiseWarnings = value; |
||
return this; |
||
} else { |
||
return $parseOptions.logPromiseWarnings; |
||
} |
||
}; |
||
|
||
|
||
this.$get = ['$filter', '$sniffer', '$log', function($filter, $sniffer, $log) { |
||
$parseOptions.csp = $sniffer.csp; |
||
|
||
promiseWarning = function promiseWarningFn(fullExp) { |
||
if (!$parseOptions.logPromiseWarnings || promiseWarningCache.hasOwnProperty(fullExp)) return; |
||
promiseWarningCache[fullExp] = true; |
||
$log.warn('[$parse] Promise found in the expression `' + fullExp + '`. ' + |
||
'Automatic unwrapping of promises in Angular expressions is deprecated.'); |
||
}; |
||
|
||
return function(exp) { |
||
var parsedExpression; |
||
|
||
switch (typeof exp) { |
||
case 'string': |
||
|
||
if (cache.hasOwnProperty(exp)) { |
||
return cache[exp]; |
||
} |
||
|
||
var lexer = new Lexer($parseOptions); |
||
var parser = new Parser(lexer, $filter, $parseOptions); |
||
parsedExpression = parser.parse(exp, false); |
||
|
||
if (exp !== 'hasOwnProperty') { |
||
// Only cache the value if it's not going to mess up the cache object |
||
// This is more performant that using Object.prototype.hasOwnProperty.call |
||
cache[exp] = parsedExpression; |
||
} |
||
|
||
return parsedExpression; |
||
|
||
case 'function': |
||
return exp; |
||
|
||
default: |
||
return noop; |
||
} |
||
}; |
||
}]; |
||
} |
||
|
||
/** |
||
* @ngdoc service |
||
* @name ng.$q |
||
* @requires $rootScope |
||
* |
||
* @description |
||
* A promise/deferred implementation inspired by [Kris Kowal's Q](https://github.com/kriskowal/q). |
||
* |
||
* [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an |
||
* interface for interacting with an object that represents the result of an action that is |
||
* performed asynchronously, and may or may not be finished at any given point in time. |
||
* |
||
* From the perspective of dealing with error handling, deferred and promise APIs are to |
||
* asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming. |
||
* |
||
* <pre> |
||
* // for the purpose of this example let's assume that variables `$q` and `scope` are |
||
* // available in the current lexical scope (they could have been injected or passed in). |
||
* |
||
* function asyncGreet(name) { |
||
* var deferred = $q.defer(); |
||
* |
||
* setTimeout(function() { |
||
* // since this fn executes async in a future turn of the event loop, we need to wrap |
||
* // our code into an $apply call so that the model changes are properly observed. |
||
* scope.$apply(function() { |
||
* deferred.notify('About to greet ' + name + '.'); |
||
* |
||
* if (okToGreet(name)) { |
||
* deferred.resolve('Hello, ' + name + '!'); |
||
* } else { |
||
* deferred.reject('Greeting ' + name + ' is not allowed.'); |
||
* } |
||
* }); |
||
* }, 1000); |
||
* |
||
* return deferred.promise; |
||
* } |
||
* |
||
* var promise = asyncGreet('Robin Hood'); |
||
* promise.then(function(greeting) { |
||
* alert('Success: ' + greeting); |
||
* }, function(reason) { |
||
* alert('Failed: ' + reason); |
||
* }, function(update) { |
||
* alert('Got notification: ' + update); |
||
* }); |
||
* </pre> |
||
* |
||
* At first it might not be obvious why this extra complexity is worth the trouble. The payoff |
||
* comes in the way of guarantees that promise and deferred APIs make, see |
||
* https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md. |
||
* |
||
* Additionally the promise api allows for composition that is very hard to do with the |
||
* traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach. |
||
* For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the |
||
* section on serial or parallel joining of promises. |
||
* |
||
* |
||
* # The Deferred API |
||
* |
||
* A new instance of deferred is constructed by calling `$q.defer()`. |
||
* |
||
* The purpose of the deferred object is to expose the associated Promise instance as well as APIs |
||
* that can be used for signaling the successful or unsuccessful completion, as well as the status |
||
* of the task. |
||
* |
||
* **Methods** |
||
* |
||
* - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection |
||
* constructed via `$q.reject`, the promise will be rejected instead. |
||
* - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to |
||
* resolving it with a rejection constructed via `$q.reject`. |
||
* - `notify(value)` - provides updates on the status of the promises execution. This may be called |
||
* multiple times before the promise is either resolved or rejected. |
||
* |
||
* **Properties** |
||
* |
||
* - promise – `{Promise}` – promise object associated with this deferred. |
||
* |
||
* |
||
* # The Promise API |
||
* |
||
* A new promise instance is created when a deferred instance is created and can be retrieved by |
||
* calling `deferred.promise`. |
||
* |
||
* The purpose of the promise object is to allow for interested parties to get access to the result |
||
* of the deferred task when it completes. |
||
* |
||
* **Methods** |
||
* |
||
* - `then(successCallback, errorCallback, notifyCallback)` – regardless of when the promise was or |
||
* will be resolved or rejected, `then` calls one of the success or error callbacks asynchronously |
||
* as soon as the result is available. The callbacks are called with a single argument: the result |
||
* or rejection reason. Additionally, the notify callback may be called zero or more times to |
||
* provide a progress indication, before the promise is resolved or rejected. |
||
* |
||
* This method *returns a new promise* which is resolved or rejected via the return value of the |
||
* `successCallback`, `errorCallback`. It also notifies via the return value of the |
||
* `notifyCallback` method. The promise can not be resolved or rejected from the notifyCallback |
||
* method. |
||
* |
||
* - `catch(errorCallback)` – shorthand for `promise.then(null, errorCallback)` |
||
* |
||
* - `finally(callback)` – allows you to observe either the fulfillment or rejection of a promise, |
||
* but to do so without modifying the final value. This is useful to release resources or do some |
||
* clean-up that needs to be done whether the promise was rejected or resolved. See the [full |
||
* specification](https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback) for |
||
* more information. |
||
* |
||
* Because `finally` is a reserved word in JavaScript and reserved keywords are not supported as |
||
* property names by ES3, you'll need to invoke the method like `promise['finally'](callback)` to |
||
* make your code IE8 compatible. |
||
* |
||
* # Chaining promises |
||
* |
||
* Because calling the `then` method of a promise returns a new derived promise, it is easily |
||
* possible to create a chain of promises: |
||
* |
||
* <pre> |
||
* promiseB = promiseA.then(function(result) { |
||
* return result + 1; |
||
* }); |
||
* |
||
* // promiseB will be resolved immediately after promiseA is resolved and its value |
||
* // will be the result of promiseA incremented by 1 |
||
* </pre> |
||
* |
||
* It is possible to create chains of any length and since a promise can be resolved with another |
||
* promise (which will defer its resolution further), it is possible to pause/defer resolution of |
||
* the promises at any point in the chain. This makes it possible to implement powerful APIs like |
||
* $http's response interceptors. |
||
* |
||
* |
||
* # Differences between Kris Kowal's Q and $q |
||
* |
||
* There are two main differences: |
||
* |
||
* - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation |
||
* mechanism in angular, which means faster propagation of resolution or rejection into your |
||
* models and avoiding unnecessary browser repaints, which would result in flickering UI. |
||
* - Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains |
||
* all the important functionality needed for common async tasks. |
||
* |
||
* # Testing |
||
* |
||
* <pre> |
||
* it('should simulate promise', inject(function($q, $rootScope) { |
||
* var deferred = $q.defer(); |
||
* var promise = deferred.promise; |
||
* var resolvedValue; |
||
* |
||
* promise.then(function(value) { resolvedValue = value; }); |
||
* expect(resolvedValue).toBeUndefined(); |
||
* |
||
* // Simulate resolving of promise |
||
* deferred.resolve(123); |
||
* // Note that the 'then' function does not get called synchronously. |
||
* // This is because we want the promise API to always be async, whether or not |
||
* // it got called synchronously or asynchronously. |
||
* expect(resolvedValue).toBeUndefined(); |
||
* |
||
* // Propagate promise resolution to 'then' functions using $apply(). |
||
* $rootScope.$apply(); |
||
* expect(resolvedValue).toEqual(123); |
||
* })); |
||
* </pre> |
||
*/ |
||
function $QProvider() { |
||
|
||
this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) { |
||
return qFactory(function(callback) { |
||
$rootScope.$evalAsync(callback); |
||
}, $exceptionHandler); |
||
}]; |
||
} |
||
|
||
|
||
/** |
||
* Constructs a promise manager. |
||
* |
||
* @param {function(function)} nextTick Function for executing functions in the next turn. |
||
* @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for |
||
* debugging purposes. |
||
* @returns {object} Promise manager. |
||
*/ |
||
function qFactory(nextTick, exceptionHandler) { |
||
|
||
/** |
||
* @ngdoc |
||
* @name ng.$q#defer |
||
* @methodOf ng.$q |
||
* @description |
||
* Creates a `Deferred` object which represents a task which will finish in the future. |
||
* |
||
* @returns {Deferred} Returns a new instance of deferred. |
||
*/ |
||
var defer = function() { |
||
var pending = [], |
||
value, deferred; |
||
|
||
deferred = { |
||
|
||
resolve: function(val) { |
||
if (pending) { |
||
var callbacks = pending; |
||
pending = undefined; |
||
value = ref(val); |
||
|
||
if (callbacks.length) { |
||
nextTick(function() { |
||
var callback; |
||
for (var i = 0, ii = callbacks.length; i < ii; i++) { |
||
callback = callbacks[i]; |
||
value.then(callback[0], callback[1], callback[2]); |
||
} |
||
}); |
||
} |
||
} |
||
}, |
||
|
||
|
||
reject: function(reason) { |
||
deferred.resolve(reject(reason)); |
||
}, |
||
|
||
|
||
notify: function(progress) { |
||
if (pending) { |
||
var callbacks = pending; |
||
|
||
if (pending.length) { |
||
nextTick(function() { |
||
var callback; |
||
for (var i = 0, ii = callbacks.length; i < ii; i++) { |
||
callback = callbacks[i]; |
||
callback[2](progress); |
||
} |
||
}); |
||
} |
||
} |
||
}, |
||
|
||
|
||
promise: { |
||
then: function(callback, errback, progressback) { |
||
var result = defer(); |
||
|
||
var wrappedCallback = function(value) { |
||
try { |
||
result.resolve((isFunction(callback) ? callback : defaultCallback)(value)); |
||
} catch(e) { |
||
result.reject(e); |
||
exceptionHandler(e); |
||
} |
||
}; |
||
|
||
var wrappedErrback = function(reason) { |
||
try { |
||
result.resolve((isFunction(errback) ? errback : defaultErrback)(reason)); |
||
} catch(e) { |
||
result.reject(e); |
||
exceptionHandler(e); |
||
} |
||
}; |
||
|
||
var wrappedProgressback = function(progress) { |
||
try { |
||
result.notify((isFunction(progressback) ? progressback : defaultCallback)(progress)); |
||
} catch(e) { |
||
exceptionHandler(e); |
||
} |
||
}; |
||
|
||
if (pending) { |
||
pending.push([wrappedCallback, wrappedErrback, wrappedProgressback]); |
||
} else { |
||
value.then(wrappedCallback, wrappedErrback, wrappedProgressback); |
||
} |
||
|
||
return result.promise; |
||
}, |
||
|
||
"catch": function(callback) { |
||
return this.then(null, callback); |
||
}, |
||
|
||
"finally": function(callback) { |
||
|
||
function makePromise(value, resolved) { |
||
var result = defer(); |
||
if (resolved) { |
||
result.resolve(value); |
||
} else { |
||
result.reject(value); |
||
} |
||
return result.promise; |
||
} |
||
|
||
function handleCallback(value, isResolved) { |
||
var callbackOutput = null; |
||
try { |
||
callbackOutput = (callback ||defaultCallback)(); |
||
} catch(e) { |
||
return makePromise(e, false); |
||
} |
||
if (callbackOutput && isFunction(callbackOutput.then)) { |
||
return callbackOutput.then(function() { |
||
return makePromise(value, isResolved); |
||
}, function(error) { |
||
return makePromise(error, false); |
||
}); |
||
} else { |
||
return makePromise(value, isResolved); |
||
} |
||
} |
||
|
||
return this.then(function(value) { |
||
return handleCallback(value, true); |
||
}, function(error) { |
||
return handleCallback(error, false); |
||
}); |
||
} |
||
} |
||
}; |
||
|
||
return deferred; |
||
}; |
||
|
||
|
||
var ref = function(value) { |
||
if (value && isFunction(value.then)) return value; |
||
return { |
||
then: function(callback) { |
||
var result = defer(); |
||
nextTick(function() { |
||
result.resolve(callback(value)); |
||
}); |
||
return result.promise; |
||
} |
||
}; |
||
}; |
||
|
||
|
||
/** |
||
* @ngdoc |
||
* @name ng.$q#reject |
||
* @methodOf ng.$q |
||
* @description |
||
* Creates a promise that is resolved as rejected with the specified `reason`. This api should be |
||
* used to forward rejection in a chain of promises. If you are dealing with the last promise in |
||
* a promise chain, you don't need to worry about it. |
||
* |
||
* When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of |
||
* `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via |
||
* a promise error callback and you want to forward the error to the promise derived from the |
||
* current promise, you have to "rethrow" the error by returning a rejection constructed via |
||
* `reject`. |
||
* |
||
* <pre> |
||
* promiseB = promiseA.then(function(result) { |
||
* // success: do something and resolve promiseB |
||
* // with the old or a new result |
||
* return result; |
||
* }, function(reason) { |
||
* // error: handle the error if possible and |
||
* // resolve promiseB with newPromiseOrValue, |
||
* // otherwise forward the rejection to promiseB |
||
* if (canHandle(reason)) { |
||
* // handle the error and recover |
||
* return newPromiseOrValue; |
||
* } |
||
* return $q.reject(reason); |
||
* }); |
||
* </pre> |
||
* |
||
* @param {*} reason Constant, message, exception or an object representing the rejection reason. |
||
* @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`. |
||
*/ |
||
var reject = function(reason) { |
||
return { |
||
then: function(callback, errback) { |
||
var result = defer(); |
||
nextTick(function() { |
||
try { |
||
result.resolve((isFunction(errback) ? errback : defaultErrback)(reason)); |
||
} catch(e) { |
||
result.reject(e); |
||
exceptionHandler(e); |
||
} |
||
}); |
||
return result.promise; |
||
} |
||
}; |
||
}; |
||
|
||
|
||
/** |
||
* @ngdoc |
||
* @name ng.$q#when |
||
* @methodOf ng.$q |
||
* @description |
||
* Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. |
||
* This is useful when you are dealing with an object that might or might not be a promise, or if |
||
* the promise comes from a source that can't be trusted. |
||
* |
||
* @param {*} value Value or a promise |
||
* @returns {Promise} Returns a promise of the passed value or promise |
||
*/ |
||
var when = function(value, callback, errback, progressback) { |
||
var result = defer(), |
||
done; |
||
|
||
var wrappedCallback = function(value) { |
||
try { |
||
return (isFunction(callback) ? callback : defaultCallback)(value); |
||
} catch (e) { |
||
exceptionHandler(e); |
||
return reject(e); |
||
} |
||
}; |
||
|
||
var wrappedErrback = function(reason) { |
||
try { |
||
return (isFunction(errback) ? errback : defaultErrback)(reason); |
||
} catch (e) { |
||
exceptionHandler(e); |
||
return reject(e); |
||
} |
||
}; |
||
|
||
var wrappedProgressback = function(progress) { |
||
try { |
||
return (isFunction(progressback) ? progressback : defaultCallback)(progress); |
||
} catch (e) { |
||
exceptionHandler(e); |
||
} |
||
}; |
||
|
||
nextTick(function() { |
||
ref(value).then(function(value) { |
||
if (done) return; |
||
done = true; |
||
result.resolve(ref(value).then(wrappedCallback, wrappedErrback, wrappedProgressback)); |
||
}, function(reason) { |
||
if (done) return; |
||
done = true; |
||
result.resolve(wrappedErrback(reason)); |
||
}, function(progress) { |
||
if (done) return; |
||
result.notify(wrappedProgressback(progress)); |
||
}); |
||
}); |
||
|
||
return result.promise; |
||
}; |
||
|
||
|
||
function defaultCallback(value) { |
||
return value; |
||
} |
||
|
||
|
||
function defaultErrback(reason) { |
||
return reject(reason); |
||
} |
||
|
||
|
||
/** |
||
* @ngdoc |
||
* @name ng.$q#all |
||
* @methodOf ng.$q |
||
* @description |
||
* Combines multiple promises into a single promise that is resolved when all of the input |
||
* promises are resolved. |
||
* |
||
* @param {Array.<Promise>|Object.<Promise>} promises An array or hash of promises. |
||
* @returns {Promise} Returns a single promise that will be resolved with an array/hash of values, |
||
* each value corresponding to the promise at the same index/key in the `promises` array/hash. |
||
* If any of the promises is resolved with a rejection, this resulting promise will be rejected |
||
* with the same rejection value. |
||
*/ |
||
function all(promises) { |
||
var deferred = defer(), |
||
counter = 0, |
||
results = isArray(promises) ? [] : {}; |
||
|
||
forEach(promises, function(promise, key) { |
||
counter++; |
||
ref(promise).then(function(value) { |
||
if (results.hasOwnProperty(key)) return; |
||
results[key] = value; |
||
if (!(--counter)) deferred.resolve(results); |
||
}, function(reason) { |
||
if (results.hasOwnProperty(key)) return; |
||
deferred.reject(reason); |
||
}); |
||
}); |
||
|
||
if (counter === 0) { |
||
deferred.resolve(results); |
||
} |
||
|
||
return deferred.promise; |
||
} |
||
|
||
return { |
||
defer: defer, |
||
reject: reject, |
||
when: when, |
||
all: all |
||
}; |
||
} |
||
|
||
/** |
||
* DESIGN NOTES |
||
* |
||
* The design decisions behind the scope are heavily favored for speed and memory consumption. |
||
* |
||
* The typical use of scope is to watch the expressions, which most of the time return the same |
||
* value as last time so we optimize the operation. |
||
* |
||
* Closures construction is expensive in terms of speed as well as memory: |
||
* - No closures, instead use prototypical inheritance for API |
||
* - Internal state needs to be stored on scope directly, which means that private state is |
||
* exposed as $$____ properties |
||
* |
||
* Loop operations are optimized by using while(count--) { ... } |
||
* - this means that in order to keep the same order of execution as addition we have to add |
||
* items to the array at the beginning (shift) instead of at the end (push) |
||
* |
||
* Child scopes are created and removed often |
||
* - Using an array would be slow since inserts in middle are expensive so we use linked list |
||
* |
||
* There are few watches then a lot of observers. This is why you don't want the observer to be |
||
* implemented in the same way as watch. Watch requires return of initialization function which |
||
* are expensive to construct. |
||
*/ |
||
|
||
|
||
/** |
||
* @ngdoc object |
||
* @name ng.$rootScopeProvider |
||
* @description |
||
* |
||
* Provider for the $rootScope service. |
||
*/ |
||
|
||
/** |
||
* @ngdoc function |
||
* @name ng.$rootScopeProvider#digestTtl |
||
* @methodOf ng.$rootScopeProvider |
||
* @description |
||
* |
||
* Sets the number of `$digest` iterations the scope should attempt to execute before giving up and |
||
* assuming that the model is unstable. |
||
* |
||
* The current default is 10 iterations. |
||
* |
||
* In complex applications it's possible that the dependencies between `$watch`s will result in |
||
* several digest iterations. However if an application needs more than the default 10 digest |
||
* iterations for its model to stabilize then you should investigate what is causing the model to |
||
* continuously change during the digest. |
||
* |
||
* Increasing the TTL could have performance implications, so you should not change it without |
||
* proper justification. |
||
* |
||
* @param {number} limit The number of digest iterations. |
||
*/ |
||
|
||
|
||
/** |
||
* @ngdoc object |
||
* @name ng.$rootScope |
||
* @description |
||
* |
||
* Every application has a single root {@link ng.$rootScope.Scope scope}. |
||
* All other scopes are descendant scopes of the root scope. Scopes provide separation |
||
* between the model and the view, via a mechanism for watching the model for changes. |
||
* They also provide an event emission/broadcast and subscription facility. See the |
||
* {@link guide/scope developer guide on scopes}. |
||
*/ |
||
function $RootScopeProvider(){ |
||
var TTL = 10; |
||
var $rootScopeMinErr = minErr('$rootScope'); |
||
var lastDirtyWatch = null; |
||
|
||
this.digestTtl = function(value) { |
||
if (arguments.length) { |
||
TTL = value; |
||
} |
||
return TTL; |
||
}; |
||
|
||
this.$get = ['$injector', '$exceptionHandler', '$parse', '$browser', |
||
function( $injector, $exceptionHandler, $parse, $browser) { |
||
|
||
/** |
||
* @ngdoc function |
||
* @name ng.$rootScope.Scope |
||
* |
||
* @description |
||
* A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the |
||
* {@link AUTO.$injector $injector}. Child scopes are created using the |
||
* {@link ng.$rootScope.Scope#methods_$new $new()} method. (Most scopes are created automatically when |
||
* compiled HTML template is executed.) |
||
* |
||
* Here is a simple scope snippet to show how you can interact with the scope. |
||
* <pre> |
||
* <file src="./test/ng/rootScopeSpec.js" tag="docs1" /> |
||
* </pre> |
||
* |
||
* # Inheritance |
||
* A scope can inherit from a parent scope, as in this example: |
||
* <pre> |
||
var parent = $rootScope; |
||
var child = parent.$new(); |
||
|
||
parent.salutation = "Hello"; |
||
child.name = "World"; |
||
expect(child.salutation).toEqual('Hello'); |
||
|
||
child.salutation = "Welcome"; |
||
expect(child.salutation).toEqual('Welcome'); |
||
expect(parent.salutation).toEqual('Hello'); |
||
* </pre> |
||
* |
||
* |
||
* @param {Object.<string, function()>=} providers Map of service factory which need to be |
||
* provided for the current scope. Defaults to {@link ng}. |
||
* @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should |
||
* append/override services provided by `providers`. This is handy |
||
* when unit-testing and having the need to override a default |
||
* service. |
||
* @returns {Object} Newly created scope. |
||
* |
||
*/ |
||
function Scope() { |
||
this.$id = nextUid(); |
||
this.$$phase = this.$parent = this.$$watchers = |
||
this.$$nextSibling = this.$$prevSibling = |
||
this.$$childHead = this.$$childTail = null; |
||
this['this'] = this.$root = this; |
||
this.$$destroyed = false; |
||
this.$$asyncQueue = []; |
||
this.$$postDigestQueue = []; |
||
this.$$listeners = {}; |
||
this.$$listenerCount = {}; |
||
this.$$isolateBindings = {}; |
||
} |
||
|
||
/** |
||
* @ngdoc property |
||
* @name ng.$rootScope.Scope#$id |
||
* @propertyOf ng.$rootScope.Scope |
||
* @returns {number} Unique scope ID (monotonically increasing alphanumeric sequence) useful for |
||
* debugging. |
||
*/ |
||
|
||
|
||
Scope.prototype = { |
||
constructor: Scope, |
||
/** |
||
* @ngdoc function |
||
* @name ng.$rootScope.Scope#$new |
||
* @methodOf ng.$rootScope.Scope |
||
* @function |
||
* |
||
* @description |
||
* Creates a new child {@link ng.$rootScope.Scope scope}. |
||
* |
||
* The parent scope will propagate the {@link ng.$rootScope.Scope#methods_$digest $digest()} and |
||
* {@link ng.$rootScope.Scope#methods_$digest $digest()} events. The scope can be removed from the |
||
* scope hierarchy using {@link ng.$rootScope.Scope#methods_$destroy $destroy()}. |
||
* |
||
* {@link ng.$rootScope.Scope#methods_$destroy $destroy()} must be called on a scope when it is |
||
* desired for the scope and its child scopes to be permanently detached from the parent and |
||
* thus stop participating in model change detection and listener notification by invoking. |
||
* |
||
* @param {boolean} isolate If true, then the scope does not prototypically inherit from the |
||
* parent scope. The scope is isolated, as it can not see parent scope properties. |
||
* When creating widgets, it is useful for the widget to not accidentally read parent |
||
* state. |
||
* |
||
* @returns {Object} The newly created child scope. |
||
* |
||
*/ |
||
$new: function(isolate) { |
||
var ChildScope, |
||
child; |
||
|
||
if (isolate) { |
||
child = new Scope(); |
||
child.$root = this.$root; |
||
// ensure that there is just one async queue per $rootScope and its children |
||
child.$$asyncQueue = this.$$asyncQueue; |
||
child.$$postDigestQueue = this.$$postDigestQueue; |
||
} else { |
||
ChildScope = function() {}; // should be anonymous; This is so that when the minifier munges |
||
// the name it does not become random set of chars. This will then show up as class |
||
// name in the web inspector. |
||
ChildScope.prototype = this; |
||
child = new ChildScope(); |
||
child.$id = nextUid(); |
||
} |
||
child['this'] = child; |
||
child.$$listeners = {}; |
||
child.$$listenerCount = {}; |
||
child.$parent = this; |
||
child.$$watchers = child.$$nextSibling = child.$$childHead = child.$$childTail = null; |
||
child.$$prevSibling = this.$$childTail; |
||
if (this.$$childHead) { |
||
this.$$childTail.$$nextSibling = child; |
||
this.$$childTail = child; |
||
} else { |
||
this.$$childHead = this.$$childTail = child; |
||
} |
||
return child; |
||
}, |
||
|
||
/** |
||
* @ngdoc function |
||
* @name ng.$rootScope.Scope#$watch |
||
* @methodOf ng.$rootScope.Scope |
||
* @function |
||
* |
||
* @description |
||
* Registers a `listener` callback to be executed whenever the `watchExpression` changes. |
||
* |
||
* - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#methods_$digest |
||
* $digest()} and should return the value that will be watched. (Since |
||
* {@link ng.$rootScope.Scope#methods_$digest $digest()} reruns when it detects changes the |
||
* `watchExpression` can execute multiple times per |
||
* {@link ng.$rootScope.Scope#methods_$digest $digest()} and should be idempotent.) |
||
* - The `listener` is called only when the value from the current `watchExpression` and the |
||
* previous call to `watchExpression` are not equal (with the exception of the initial run, |
||
* see below). The inequality is determined according to |
||
* {@link angular.equals} function. To save the value of the object for later comparison, |
||
* the {@link angular.copy} function is used. It also means that watching complex options |
||
* will have adverse memory and performance implications. |
||
* - The watch `listener` may change the model, which may trigger other `listener`s to fire. |
||
* This is achieved by rerunning the watchers until no changes are detected. The rerun |
||
* iteration limit is 10 to prevent an infinite loop deadlock. |
||
* |
||
* |
||
* If you want to be notified whenever {@link ng.$rootScope.Scope#methods_$digest $digest} is called, |
||
* you can register a `watchExpression` function with no `listener`. (Since `watchExpression` |
||
* can execute multiple times per {@link ng.$rootScope.Scope#methods_$digest $digest} cycle when a |
||
* change is detected, be prepared for multiple calls to your listener.) |
||
* |
||
* After a watcher is registered with the scope, the `listener` fn is called asynchronously |
||
* (via {@link ng.$rootScope.Scope#methods_$evalAsync $evalAsync}) to initialize the |
||
* watcher. In rare cases, this is undesirable because the listener is called when the result |
||
* of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you |
||
* can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the |
||
* listener was called due to initialization. |
||
* |
||
* The example below contains an illustration of using a function as your $watch listener |
||
* |
||
* |
||
* # Example |
||
* <pre> |
||
// let's assume that scope was dependency injected as the $rootScope |
||
var scope = $rootScope; |
||
scope.name = 'misko'; |
||
scope.counter = 0; |
||
|
||
expect(scope.counter).toEqual(0); |
||
scope.$watch('name', function(newValue, oldValue) { |
||
scope.counter = scope.counter + 1; |
||
}); |
||
expect(scope.counter).toEqual(0); |
||
|
||
scope.$digest(); |
||
// no variable change |
||
expect(scope.counter).toEqual(0); |
||
|
||
scope.name = 'adam'; |
||
scope.$digest(); |
||
expect(scope.counter).toEqual(1); |
||
|
||
|
||
|
||
// Using a listener function |
||
var food; |
||
scope.foodCounter = 0; |
||
expect(scope.foodCounter).toEqual(0); |
||
scope.$watch( |
||
// This is the listener function |
||
function() { return food; }, |
||
// This is the change handler |
||
function(newValue, oldValue) { |
||
if ( newValue !== oldValue ) { |
||
// Only increment the counter if the value changed |
||
scope.foodCounter = scope.foodCounter + 1; |
||
} |
||
} |
||
); |
||
// No digest has been run so the counter will be zero |
||
expect(scope.foodCounter).toEqual(0); |
||
|
||
// Run the digest but since food has not changed count will still be zero |
||
scope.$digest(); |
||
expect(scope.foodCounter).toEqual(0); |
||
|
||
// Update food and run digest. Now the counter will increment |
||
food = 'cheeseburger'; |
||
scope.$digest(); |
||
expect(scope.foodCounter).toEqual(1); |
||
|
||
* </pre> |
||
* |
||
* |
||
* |
||
* @param {(function()|string)} watchExpression Expression that is evaluated on each |
||
* {@link ng.$rootScope.Scope#methods_$digest $digest} cycle. A change in the return value triggers |
||
* a call to the `listener`. |
||
* |
||
* - `string`: Evaluated as {@link guide/expression expression} |
||
* - `function(scope)`: called with current `scope` as a parameter. |
||
* @param {(function()|string)=} listener Callback called whenever the return value of |
||
* the `watchExpression` changes. |
||
* |
||
* - `string`: Evaluated as {@link guide/expression expression} |
||
* - `function(newValue, oldValue, scope)`: called with current and previous values as |
||
* parameters. |
||
* |
||
* @param {boolean=} objectEquality Compare object for equality rather than for reference. |
||
* @returns {function()} Returns a deregistration function for this listener. |
||
*/ |
||
$watch: function(watchExp, listener, objectEquality) { |
||
var scope = this, |
||
get = compileToFn(watchExp, 'watch'), |
||
array = scope.$$watchers, |
||
watcher = { |
||
fn: listener, |
||
last: initWatchVal, |
||
get: get, |
||
exp: watchExp, |
||
eq: !!objectEquality |
||
}; |
||
|
||
lastDirtyWatch = null; |
||
|
||
// in the case user pass string, we need to compile it, do we really need this ? |
||
if (!isFunction(listener)) { |
||
var listenFn = compileToFn(listener || noop, 'listener'); |
||
watcher.fn = function(newVal, oldVal, scope) {listenFn(scope);}; |
||
} |
||
|
||
if (typeof watchExp == 'string' && get.constant) { |
||
var originalFn = watcher.fn; |
||
watcher.fn = function(newVal, oldVal, scope) { |
||
originalFn.call(this, newVal, oldVal, scope); |
||
arrayRemove(array, watcher); |
||
}; |
||
} |
||
|
||
if (!array) { |
||
array = scope.$$watchers = []; |
||
} |
||
// we use unshift since we use a while loop in $digest for speed. |
||
// the while loop reads in reverse order. |
||
array.unshift(watcher); |
||
|
||
return function() { |
||
arrayRemove(array, watcher); |
||
lastDirtyWatch = null; |
||
}; |
||
}, |
||
|
||
|
||
/** |
||
* @ngdoc function |
||
* @name ng.$rootScope.Scope#$watchCollection |
||
* @methodOf ng.$rootScope.Scope |
||
* @function |
||
* |
||
* @description |
||
* Shallow watches the properties of an object and fires whenever any of the properties change |
||
* (for arrays, this implies watching the array items; for object maps, this implies watching |
||
* the properties). If a change is detected, the `listener` callback is fired. |
||
* |
||
* - The `obj` collection is observed via standard $watch operation and is examined on every |
||
* call to $digest() to see if any items have been added, removed, or moved. |
||
* - The `listener` is called whenever anything within the `obj` has changed. Examples include |
||
* adding, removing, and moving items belonging to an object or array. |
||
* |
||
* |
||
* # Example |
||
* <pre> |
||
$scope.names = ['igor', 'matias', 'misko', 'james']; |
||
$scope.dataCount = 4; |
||
|
||
$scope.$watchCollection('names', function(newNames, oldNames) { |
||
$scope.dataCount = newNames.length; |
||
}); |
||
|
||
expect($scope.dataCount).toEqual(4); |
||
$scope.$digest(); |
||
|
||
//still at 4 ... no changes |
||
expect($scope.dataCount).toEqual(4); |
||
|
||
$scope.names.pop(); |
||
$scope.$digest(); |
||
|
||
//now there's been a change |
||
expect($scope.dataCount).toEqual(3); |
||
* </pre> |
||
* |
||
* |
||
* @param {string|Function(scope)} obj Evaluated as {@link guide/expression expression}. The |
||
* expression value should evaluate to an object or an array which is observed on each |
||
* {@link ng.$rootScope.Scope#methods_$digest $digest} cycle. Any shallow change within the |
||
* collection will trigger a call to the `listener`. |
||
* |
||
* @param {function(newCollection, oldCollection, scope)} listener a callback function that is |
||
* fired with both the `newCollection` and `oldCollection` as parameters. |
||
* The `newCollection` object is the newly modified data obtained from the `obj` expression |
||
* and the `oldCollection` object is a copy of the former collection data. |
||
* The `scope` refers to the current scope. |
||
* |
||
* @returns {function()} Returns a de-registration function for this listener. When the |
||
* de-registration function is executed, the internal watch operation is terminated. |
||
*/ |
||
$watchCollection: function(obj, listener) { |
||
var self = this; |
||
var oldValue; |
||
var newValue; |
||
var changeDetected = 0; |
||
var objGetter = $parse(obj); |
||
var internalArray = []; |
||
var internalObject = {}; |
||
var oldLength = 0; |
||
|
||
function $watchCollectionWatch() { |
||
newValue = objGetter(self); |
||
var newLength, key; |
||
|
||
if (!isObject(newValue)) { |
||
if (oldValue !== newValue) { |
||
oldValue = newValue; |
||
changeDetected++; |
||
} |
||
} else if (isArrayLike(newValue)) { |
||
if (oldValue !== internalArray) { |
||
// we are transitioning from something which was not an array into array. |
||
oldValue = internalArray; |
||
oldLength = oldValue.length = 0; |
||
changeDetected++; |
||
} |
||
|
||
newLength = newValue.length; |
||
|
||
if (oldLength !== newLength) { |
||
// if lengths do not match we need to trigger change notification |
||
changeDetected++; |
||
oldValue.length = oldLength = newLength; |
||
} |
||
// copy the items to oldValue and look for changes. |
||
for (var i = 0; i < newLength; i++) { |
||
if (oldValue[i] !== newValue[i]) { |
||
changeDetected++; |
||
oldValue[i] = newValue[i]; |
||
} |
||
} |
||
} else { |
||
if (oldValue !== internalObject) { |
||
// we are transitioning from something which was not an object into object. |
||
oldValue = internalObject = {}; |
||
oldLength = 0; |
||
changeDetected++; |
||
} |
||
// copy the items to oldValue and look for changes. |
||
newLength = 0; |
||
for (key in newValue) { |
||
if (newValue.hasOwnProperty(key)) { |
||
newLength++; |
||
if (oldValue.hasOwnProperty(key)) { |
||
if (oldValue[key] !== newValue[key]) { |
||
changeDetected++; |
||
oldValue[key] = newValue[key]; |
||
} |
||
} else { |
||
oldLength++; |
||
oldValue[key] = newValue[key]; |
||
changeDetected++; |
||
} |
||
} |
||
} |
||
if (oldLength > newLength) { |
||
// we used to have more keys, need to find them and destroy them. |
||
changeDetected++; |
||
for(key in oldValue) { |
||
if (oldValue.hasOwnProperty(key) && !newValue.hasOwnProperty(key)) { |
||
oldLength--; |
||
delete oldValue[key]; |
||
} |
||
} |
||
} |
||
} |
||
return changeDetected; |
||
} |
||
|
||
function $watchCollectionAction() { |
||
listener(newValue, oldValue, self); |
||
} |
||
|
||
return this.$watch($watchCollectionWatch, $watchCollectionAction); |
||
}, |
||
|
||
/** |
||
* @ngdoc function |
||
* @name ng.$rootScope.Scope#$digest |
||
* @methodOf ng.$rootScope.Scope |
||
* @function |
||
* |
||
* @description |
||
* Processes all of the {@link ng.$rootScope.Scope#methods_$watch watchers} of the current scope and |
||
* its children. Because a {@link ng.$rootScope.Scope#methods_$watch watcher}'s listener can change |
||
* the model, the `$digest()` keeps calling the {@link ng.$rootScope.Scope#methods_$watch watchers} |
||
* until no more listeners are firing. This means that it is possible to get into an infinite |
||
* loop. This function will throw `'Maximum iteration limit exceeded.'` if the number of |
||
* iterations exceeds 10. |
||
* |
||
* Usually, you don't call `$digest()` directly in |
||
* {@link ng.directive:ngController controllers} or in |
||
* {@link ng.$compileProvider#methods_directive directives}. |
||
* Instead, you should call {@link ng.$rootScope.Scope#methods_$apply $apply()} (typically from within |
||
* a {@link ng.$compileProvider#methods_directive directives}), which will force a `$digest()`. |
||
* |
||
* If you want to be notified whenever `$digest()` is called, |
||
* you can register a `watchExpression` function with |
||
* {@link ng.$rootScope.Scope#methods_$watch $watch()} with no `listener`. |
||
* |
||
* In unit tests, you may need to call `$digest()` to simulate the scope life cycle. |
||
* |
||
* # Example |
||
* <pre> |
||
var scope = ...; |
||
scope.name = 'misko'; |
||
scope.counter = 0; |
||
|
||
expect(scope.counter).toEqual(0); |
||
scope.$watch('name', function(newValue, oldValue) { |
||
scope.counter = scope.counter + 1; |
||
}); |
||
expect(scope.counter).toEqual(0); |
||
|
||
scope.$digest(); |
||
// no variable change |
||
expect(scope.counter).toEqual(0); |
||
|
||
scope.name = 'adam'; |
||
scope.$digest(); |
||
expect(scope.counter).toEqual(1); |
||
* </pre> |
||
* |
||
*/ |
||
$digest: function() { |
||
var watch, value, last, |
||
watchers, |
||
asyncQueue = this.$$asyncQueue, |
||
postDigestQueue = this.$$postDigestQueue, |
||
length, |
||
dirty, ttl = TTL, |
||
next, current, target = this, |
||
watchLog = [], |
||
logIdx, logMsg, asyncTask; |
||
|
||
beginPhase('$digest'); |
||
|
||
lastDirtyWatch = null; |
||
|
||
do { // "while dirty" loop |
||
dirty = false; |
||
current = target; |
||
|
||
while(asyncQueue.length) { |
||
try { |
||
asyncTask = asyncQueue.shift(); |
||
asyncTask.scope.$eval(asyncTask.expression); |
||
} catch (e) { |
||
clearPhase(); |
||
$exceptionHandler(e); |
||
} |
||
lastDirtyWatch = null; |
||
} |
||
|
||
traverseScopesLoop: |
||
do { // "traverse the scopes" loop |
||
if ((watchers = current.$$watchers)) { |
||
// process our watches |
||
length = watchers.length; |
||
while (length--) { |
||
try { |
||
watch = watchers[length]; |
||
// Most common watches are on primitives, in which case we can short |
||
// circuit it with === operator, only when === fails do we use .equals |
||
if (watch) { |
||
if ((value = watch.get(current)) !== (last = watch.last) && |
||
!(watch.eq |
||
? equals(value, last) |
||
: (typeof value == 'number' && typeof last == 'number' |
||
&& isNaN(value) && isNaN(last)))) { |
||
dirty = true; |
||
lastDirtyWatch = watch; |
||
watch.last = watch.eq ? copy(value) : value; |
||
watch.fn(value, ((last === initWatchVal) ? value : last), current); |
||
if (ttl < 5) { |
||
logIdx = 4 - ttl; |
||
if (!watchLog[logIdx]) watchLog[logIdx] = []; |
||
logMsg = (isFunction(watch.exp)) |
||
? 'fn: ' + (watch.exp.name || watch.exp.toString()) |
||
: watch.exp; |
||
logMsg += '; newVal: ' + toJson(value) + '; oldVal: ' + toJson(last); |
||
watchLog[logIdx].push(logMsg); |
||
} |
||
} else if (watch === lastDirtyWatch) { |
||
// If the most recently dirty watcher is now clean, short circuit since the remaining watchers |
||
// have already been tested. |
||
dirty = false; |
||
break traverseScopesLoop; |
||
} |
||
} |
||
} catch (e) { |
||
clearPhase(); |
||
$exceptionHandler(e); |
||
} |
||
} |
||
} |
||
|
||
// Insanity Warning: scope depth-first traversal |
||
// yes, this code is a bit crazy, but it works and we have tests to prove it! |
||
// this piece should be kept in sync with the traversal in $broadcast |
||
if (!(next = (current.$$childHead || |
||
(current !== target && current.$$nextSibling)))) { |
||
while(current !== target && !(next = current.$$nextSibling)) { |
||
current = current.$parent; |
||
} |
||
} |
||
} while ((current = next)); |
||
|
||
// `break traverseScopesLoop;` takes us to here |
||
|
||
if((dirty || asyncQueue.length) && !(ttl--)) { |
||
clearPhase(); |
||
throw $rootScopeMinErr('infdig', |
||
'{0} $digest() iterations reached. Aborting!\n' + |
||
'Watchers fired in the last 5 iterations: {1}', |
||
TTL, toJson(watchLog)); |
||
} |
||
|
||
} while (dirty || asyncQueue.length); |
||
|
||
clearPhase(); |
||
|
||
while(postDigestQueue.length) { |
||
try { |
||
postDigestQueue.shift()(); |
||
} catch (e) { |
||
$exceptionHandler(e); |
||
} |
||
} |
||
}, |
||
|
||
|
||
/** |
||
* @ngdoc event |
||
* @name ng.$rootScope.Scope#$destroy |
||
* @eventOf ng.$rootScope.Scope |
||
* @eventType broadcast on scope being destroyed |
||
* |
||
* @description |
||
* Broadcasted when a scope and its children are being destroyed. |
||
* |
||
* Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to |
||
* clean up DOM bindings before an element is removed from the DOM. |
||
*/ |
||
|
||
/** |
||
* @ngdoc function |
||
* @name ng.$rootScope.Scope#$destroy |
||
* @methodOf ng.$rootScope.Scope |
||
* @function |
||
* |
||
* @description |
||
* Removes the current scope (and all of its children) from the parent scope. Removal implies |
||
* that calls to {@link ng.$rootScope.Scope#methods_$digest $digest()} will no longer |
||
* propagate to the current scope and its children. Removal also implies that the current |
||
* scope is eligible for garbage collection. |
||
* |
||
* The `$destroy()` is usually used by directives such as |
||
* {@link ng.directive:ngRepeat ngRepeat} for managing the |
||
* unrolling of the loop. |
||
* |
||
* Just before a scope is destroyed, a `$destroy` event is broadcasted on this scope. |
||
* Application code can register a `$destroy` event handler that will give it a chance to |
||
* perform any necessary cleanup. |
||
* |
||
* Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to |
||
* clean up DOM bindings before an element is removed from the DOM. |
||
*/ |
||
$destroy: function() { |
||
// we can't destroy the root scope or a scope that has been already destroyed |
||
if (this.$$destroyed) return; |
||
var parent = this.$parent; |
||
|
||
this.$broadcast('$destroy'); |
||
this.$$destroyed = true; |
||
if (this === $rootScope) return; |
||
|
||
forEach(this.$$listenerCount, bind(null, decrementListenerCount, this)); |
||
|
||
if (parent.$$childHead == this) parent.$$childHead = this.$$nextSibling; |
||
if (parent.$$childTail == this) parent.$$childTail = this.$$prevSibling; |
||
if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling; |
||
if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling; |
||
|
||
// This is bogus code that works around Chrome's GC leak |
||
// see: https://github.com/angular/angular.js/issues/1313#issuecomment-10378451 |
||
this.$parent = this.$$nextSibling = this.$$prevSibling = this.$$childHead = |
||
this.$$childTail = null; |
||
}, |
||
|
||
/** |
||
* @ngdoc function |
||
* @name ng.$rootScope.Scope#$eval |
||
* @methodOf ng.$rootScope.Scope |
||
* @function |
||
* |
||
* @description |
||
* Executes the `expression` on the current scope and returns the result. Any exceptions in |
||
* the expression are propagated (uncaught). This is useful when evaluating Angular |
||
* expressions. |
||
* |
||
* # Example |
||
* <pre> |
||
var scope = ng.$rootScope.Scope(); |
||
scope.a = 1; |
||
scope.b = 2; |
||
|
||
expect(scope.$eval('a+b')).toEqual(3); |
||
expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3); |
||
* </pre> |
||
* |
||
* @param {(string|function())=} expression An angular expression to be executed. |
||
* |
||
* - `string`: execute using the rules as defined in {@link guide/expression expression}. |
||
* - `function(scope)`: execute the function with the current `scope` parameter. |
||
* |
||
* @param {(object)=} locals Local variables object, useful for overriding values in scope. |
||
* @returns {*} The result of evaluating the expression. |
||
*/ |
||
$eval: function(expr, locals) { |
||
return $parse(expr)(this, locals); |
||
}, |
||
|
||
/** |
||
* @ngdoc function |
||
* @name ng.$rootScope.Scope#$evalAsync |
||
* @methodOf ng.$rootScope.Scope |
||
* @function |
||
* |
||
* @description |
||
* Executes the expression on the current scope at a later point in time. |
||
* |
||
* The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only |
||
* that: |
||
* |
||
* - it will execute after the function that scheduled the evaluation (preferably before DOM |
||
* rendering). |
||
* - at least one {@link ng.$rootScope.Scope#methods_$digest $digest cycle} will be performed after |
||
* `expression` execution. |
||
* |
||
* Any exceptions from the execution of the expression are forwarded to the |
||
* {@link ng.$exceptionHandler $exceptionHandler} service. |
||
* |
||
* __Note:__ if this function is called outside of a `$digest` cycle, a new `$digest` cycle |
||
* will be scheduled. However, it is encouraged to always call code that changes the model |
||
* from within an `$apply` call. That includes code evaluated via `$evalAsync`. |
||
* |
||
* @param {(string|function())=} expression An angular expression to be executed. |
||
* |
||
* - `string`: execute using the rules as defined in {@link guide/expression expression}. |
||
* - `function(scope)`: execute the function with the current `scope` parameter. |
||
* |
||
*/ |
||
$evalAsync: function(expr) { |
||
// if we are outside of an $digest loop and this is the first time we are scheduling async |
||
// task also schedule async auto-flush |
||
if (!$rootScope.$$phase && !$rootScope.$$asyncQueue.length) { |
||
$browser.defer(function() { |
||
if ($rootScope.$$asyncQueue.length) { |
||
$rootScope.$digest(); |
||
} |
||
}); |
||
} |
||
|
||
this.$$asyncQueue.push({scope: this, expression: expr}); |
||
}, |
||
|
||
$$postDigest : function(fn) { |
||
this.$$postDigestQueue.push(fn); |
||
}, |
||
|
||
/** |
||
* @ngdoc function |
||
* @name ng.$rootScope.Scope#$apply |
||
* @methodOf ng.$rootScope.Scope |
||
* @function |
||
* |
||
* @description |
||
* `$apply()` is used to execute an expression in angular from outside of the angular |
||
* framework. (For example from browser DOM events, setTimeout, XHR or third party libraries). |
||
* Because we are calling into the angular framework we need to perform proper scope life |
||
* cycle of {@link ng.$exceptionHandler exception handling}, |
||
* {@link ng.$rootScope.Scope#methods_$digest executing watches}. |
||
* |
||
* ## Life cycle |
||
* |
||
* # Pseudo-Code of `$apply()` |
||
* <pre> |
||
function $apply(expr) { |
||
try { |
||
return $eval(expr); |
||
} catch (e) { |
||
$exceptionHandler(e); |
||
} finally { |
||
$root.$digest(); |
||
} |
||
} |
||
* </pre> |
||
* |
||
* |
||
* Scope's `$apply()` method transitions through the following stages: |
||
* |
||
* 1. The {@link guide/expression expression} is executed using the |
||
* {@link ng.$rootScope.Scope#methods_$eval $eval()} method. |
||
* 2. Any exceptions from the execution of the expression are forwarded to the |
||
* {@link ng.$exceptionHandler $exceptionHandler} service. |
||
* 3. The {@link ng.$rootScope.Scope#methods_$watch watch} listeners are fired immediately after the |
||
* expression was executed using the {@link ng.$rootScope.Scope#methods_$digest $digest()} method. |
||
* |
||
* |
||
* @param {(string|function())=} exp An angular expression to be executed. |
||
* |
||
* - `string`: execute using the rules as defined in {@link guide/expression expression}. |
||
* - `function(scope)`: execute the function with current `scope` parameter. |
||
* |
||
* @returns {*} The result of evaluating the expression. |
||
*/ |
||
$apply: function(expr) { |
||
try { |
||
beginPhase('$apply'); |
||
return this.$eval(expr); |
||
} catch (e) { |
||
$exceptionHandler(e); |
||
} finally { |
||
clearPhase(); |
||
try { |
||
$rootScope.$digest(); |
||
} catch (e) { |
||
$exceptionHandler(e); |
||
throw e; |
||
} |
||
} |
||
}, |
||
|
||
/** |
||
* @ngdoc function |
||
* @name ng.$rootScope.Scope#$on |
||
* @methodOf ng.$rootScope.Scope |
||
* @function |
||
* |
||
* @description |
||
* Listens on events of a given type. See {@link ng.$rootScope.Scope#methods_$emit $emit} for |
||
* discussion of event life cycle. |
||
* |
||
* The event listener function format is: `function(event, args...)`. The `event` object |
||
* passed into the listener has the following attributes: |
||
* |
||
* - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or |
||
* `$broadcast`-ed. |
||
* - `currentScope` - `{Scope}`: the current scope which is handling the event. |
||
* - `name` - `{string}`: name of the event. |
||
* - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel |
||
* further event propagation (available only for events that were `$emit`-ed). |
||
* - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag |
||
* to true. |
||
* - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called. |
||
* |
||
* @param {string} name Event name to listen on. |
||
* @param {function(event, args...)} listener Function to call when the event is emitted. |
||
* @returns {function()} Returns a deregistration function for this listener. |
||
*/ |
||
$on: function(name, listener) { |
||
var namedListeners = this.$$listeners[name]; |
||
if (!namedListeners) { |
||
this.$$listeners[name] = namedListeners = []; |
||
} |
||
namedListeners.push(listener); |
||
|
||
var current = this; |
||
do { |
||
if (!current.$$listenerCount[name]) { |
||
current.$$listenerCount[name] = 0; |
||
} |
||
current.$$listenerCount[name]++; |
||
} while ((current = current.$parent)); |
||
|
||
var self = this; |
||
return function() { |
||
namedListeners[indexOf(namedListeners, listener)] = null; |
||
decrementListenerCount(self, 1, name); |
||
}; |
||
}, |
||
|
||
|
||
/** |
||
* @ngdoc function |
||
* @name ng.$rootScope.Scope#$emit |
||
* @methodOf ng.$rootScope.Scope |
||
* @function |
||
* |
||
* @description |
||
* Dispatches an event `name` upwards through the scope hierarchy notifying the |
||
* registered {@link ng.$rootScope.Scope#methods_$on} listeners. |
||
* |
||
* The event life cycle starts at the scope on which `$emit` was called. All |
||
* {@link ng.$rootScope.Scope#methods_$on listeners} listening for `name` event on this scope get |
||
* notified. Afterwards, the event traverses upwards toward the root scope and calls all |
||
* registered listeners along the way. The event will stop propagating if one of the listeners |
||
* cancels it. |
||
* |
||
* Any exception emitted from the {@link ng.$rootScope.Scope#methods_$on listeners} will be passed |
||
* onto the {@link ng.$exceptionHandler $exceptionHandler} service. |
||
* |
||
* @param {string} name Event name to emit. |
||
* @param {...*} args Optional set of arguments which will be passed onto the event listeners. |
||
* @return {Object} Event object (see {@link ng.$rootScope.Scope#methods_$on}). |
||
*/ |
||
$emit: function(name, args) { |
||
var empty = [], |
||
namedListeners, |
||
scope = this, |
||
stopPropagation = false, |
||
event = { |
||
name: name, |
||
targetScope: scope, |
||
stopPropagation: function() {stopPropagation = true;}, |
||
preventDefault: function() { |
||
event.defaultPrevented = true; |
||
}, |
||
defaultPrevented: false |
||
}, |
||
listenerArgs = concat([event], arguments, 1), |
||
i, length; |
||
|
||
do { |
||
namedListeners = scope.$$listeners[name] || empty; |
||
event.currentScope = scope; |
||
for (i=0, length=namedListeners.length; i<length; i++) { |
||
|
||
// if listeners were deregistered, defragment the array |
||
if (!namedListeners[i]) { |
||
namedListeners.splice(i, 1); |
||
i--; |
||
length--; |
||
continue; |
||
} |
||
try { |
||
//allow all listeners attached to the current scope to run |
||
namedListeners[i].apply(null, listenerArgs); |
||
} catch (e) { |
||
$exceptionHandler(e); |
||
} |
||
} |
||
//if any listener on the current scope stops propagation, prevent bubbling |
||
if (stopPropagation) return event; |
||
//traverse upwards |
||
scope = scope.$parent; |
||
} while (scope); |
||
|
||
return event; |
||
}, |
||
|
||
|
||
/** |
||
* @ngdoc function |
||
* @name ng.$rootScope.Scope#$broadcast |
||
* @methodOf ng.$rootScope.Scope |
||
* @function |
||
* |
||
* @description |
||
* Dispatches an event `name` downwards to all child scopes (and their children) notifying the |
||
* registered {@link ng.$rootScope.Scope#methods_$on} listeners. |
||
* |
||
* The event life cycle starts at the scope on which `$broadcast` was called. All |
||
* {@link ng.$rootScope.Scope#methods_$on listeners} listening for `name` event on this scope get |
||
* notified. Afterwards, the event propagates to all direct and indirect scopes of the current |
||
* scope and calls all registered listeners along the way. The event cannot be canceled. |
||
* |
||
* Any exception emitted from the {@link ng.$rootScope.Scope#methods_$on listeners} will be passed |
||
* onto the {@link ng.$exceptionHandler $exceptionHandler} service. |
||
* |
||
* @param {string} name Event name to broadcast. |
||
* @param {...*} args Optional set of arguments which will be passed onto the event listeners. |
||
* @return {Object} Event object, see {@link ng.$rootScope.Scope#methods_$on} |
||
*/ |
||
$broadcast: function(name, args) { |
||
var target = this, |
||
current = target, |
||
next = target, |
||
event = { |
||
name: name, |
||
targetScope: target, |
||
preventDefault: function() { |
||
event.defaultPrevented = true; |
||
}, |
||
defaultPrevented: false |
||
}, |
||
listenerArgs = concat([event], arguments, 1), |
||
listeners, i, length; |
||
|
||
//down while you can, then up and next sibling or up and next sibling until back at root |
||
while ((current = next)) { |
||
event.currentScope = current; |
||
listeners = current.$$listeners[name] || []; |
||
for (i=0, length = listeners.length; i<length; i++) { |
||
// if listeners were deregistered, defragment the array |
||
if (!listeners[i]) { |
||
listeners.splice(i, 1); |
||
i--; |
||
length--; |
||
continue; |
||
} |
||
|
||
try { |
||
listeners[i].apply(null, listenerArgs); |
||
} catch(e) { |
||
$exceptionHandler(e); |
||
} |
||
} |
||
|
||
// Insanity Warning: scope depth-first traversal |
||
// yes, this code is a bit crazy, but it works and we have tests to prove it! |
||
// this piece should be kept in sync with the traversal in $digest |
||
// (though it differs due to having the extra check for $$listenerCount) |
||
if (!(next = ((current.$$listenerCount[name] && current.$$childHead) || |
||
(current !== target && current.$$nextSibling)))) { |
||
while(current !== target && !(next = current.$$nextSibling)) { |
||
current = current.$parent; |
||
} |
||
} |
||
} |
||
|
||
return event; |
||
} |
||
}; |
||
|
||
var $rootScope = new Scope(); |
||
|
||
return $rootScope; |
||
|
||
|
||
function beginPhase(phase) { |
||
if ($rootScope.$$phase) { |
||
throw $rootScopeMinErr('inprog', '{0} already in progress', $rootScope.$$phase); |
||
} |
||
|
||
$rootScope.$$phase = phase; |
||
} |
||
|
||
function clearPhase() { |
||
$rootScope.$$phase = null; |
||
} |
||
|
||
function compileToFn(exp, name) { |
||
var fn = $parse(exp); |
||
assertArgFn(fn, name); |
||
return fn; |
||
} |
||
|
||
function decrementListenerCount(current, count, name) { |
||
do { |
||
current.$$listenerCount[name] -= count; |
||
|
||
if (current.$$listenerCount[name] === 0) { |
||
delete current.$$listenerCount[name]; |
||
} |
||
} while ((current = current.$parent)); |
||
} |
||
|
||
/** |
||
* function used as an initial value for watchers. |
||
* because it's unique we can easily tell it apart from other values |
||
*/ |
||
function initWatchVal() {} |
||
}]; |
||
} |
||
|
||
/** |
||
* @description |
||
* Private service to sanitize uris for links and images. Used by $compile and $sanitize. |
||
*/ |
||
function $$SanitizeUriProvider() { |
||
var aHrefSanitizationWhitelist = /^\s*(https?|ftp|mailto|tel|file):/, |
||
imgSrcSanitizationWhitelist = /^\s*(https?|ftp|file):|data:image\//; |
||
|
||
/** |
||
* @description |
||
* Retrieves or overrides the default regular expression that is used for whitelisting of safe |
||
* urls during a[href] sanitization. |
||
* |
||
* The sanitization is a security measure aimed at prevent XSS attacks via html links. |
||
* |
||
* Any url about to be assigned to a[href] via data-binding is first normalized and turned into |
||
* an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist` |
||
* regular expression. If a match is found, the original url is written into the dom. Otherwise, |
||
* the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM. |
||
* |
||
* @param {RegExp=} regexp New regexp to whitelist urls with. |
||
* @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for |
||
* chaining otherwise. |
||
*/ |
||
this.aHrefSanitizationWhitelist = function(regexp) { |
||
if (isDefined(regexp)) { |
||
aHrefSanitizationWhitelist = regexp; |
||
return this; |
||
} |
||
return aHrefSanitizationWhitelist; |
||
}; |
||
|
||
|
||
/** |
||
* @description |
||
* Retrieves or overrides the default regular expression that is used for whitelisting of safe |
||
* urls during img[src] sanitization. |
||
* |
||
* The sanitization is a security measure aimed at prevent XSS attacks via html links. |
||
* |
||
* Any url about to be assigned to img[src] via data-binding is first normalized and turned into |
||
* an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist` |
||
* regular expression. If a match is found, the original url is written into the dom. Otherwise, |
||
* the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM. |
||
* |
||
* @param {RegExp=} regexp New regexp to whitelist urls with. |
||
* @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for |
||
* chaining otherwise. |
||
*/ |
||
this.imgSrcSanitizationWhitelist = function(regexp) { |
||
if (isDefined(regexp)) { |
||
imgSrcSanitizationWhitelist = regexp; |
||
return this; |
||
} |
||
return imgSrcSanitizationWhitelist; |
||
}; |
||
|
||
this.$get = function() { |
||
return function sanitizeUri(uri, isImage) { |
||
var regex = isImage ? imgSrcSanitizationWhitelist : aHrefSanitizationWhitelist; |
||
var normalizedVal; |
||
// NOTE: urlResolve() doesn't support IE < 8 so we don't sanitize for that case. |
||
if (!msie || msie >= 8 ) { |
||
normalizedVal = urlResolve(uri).href; |
||
if (normalizedVal !== '' && !normalizedVal.match(regex)) { |
||
return 'unsafe:'+normalizedVal; |
||
} |
||
} |
||
return uri; |
||
}; |
||
}; |
||
} |
||
|
||
var $sceMinErr = minErr('$sce'); |
||
|
||
var SCE_CONTEXTS = { |
||
HTML: 'html', |
||
CSS: 'css', |
||
URL: 'url', |
||
// RESOURCE_URL is a subtype of URL used in contexts where a privileged resource is sourced from a |
||
// url. (e.g. ng-include, script src, templateUrl) |
||
RESOURCE_URL: 'resourceUrl', |
||
JS: 'js' |
||
}; |
||
|
||
// Helper functions follow. |
||
|
||
// Copied from: |
||
// http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962 |
||
// Prereq: s is a string. |
||
function escapeForRegexp(s) { |
||
return s.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g, '\\$1'). |
||
replace(/\x08/g, '\\x08'); |
||
} |
||
|
||
|
||
function adjustMatcher(matcher) { |
||
if (matcher === 'self') { |
||
return matcher; |
||
} else if (isString(matcher)) { |
||
// Strings match exactly except for 2 wildcards - '*' and '**'. |
||
// '*' matches any character except those from the set ':/.?&'. |
||
// '**' matches any character (like .* in a RegExp). |
||
// More than 2 *'s raises an error as it's ill defined. |
||
if (matcher.indexOf('***') > -1) { |
||
throw $sceMinErr('iwcard', |
||
'Illegal sequence *** in string matcher. String: {0}', matcher); |
||
} |
||
matcher = escapeForRegexp(matcher). |
||
replace('\\*\\*', '.*'). |
||
replace('\\*', '[^:/.?&;]*'); |
||
return new RegExp('^' + matcher + '$'); |
||
} else if (isRegExp(matcher)) { |
||
// The only other type of matcher allowed is a Regexp. |
||
// Match entire URL / disallow partial matches. |
||
// Flags are reset (i.e. no global, ignoreCase or multiline) |
||
return new RegExp('^' + matcher.source + '$'); |
||
} else { |
||
throw $sceMinErr('imatcher', |
||
'Matchers may only be "self", string patterns or RegExp objects'); |
||
} |
||
} |
||
|
||
|
||
function adjustMatchers(matchers) { |
||
var adjustedMatchers = []; |
||
if (isDefined(matchers)) { |
||
forEach(matchers, function(matcher) { |
||
adjustedMatchers.push(adjustMatcher(matcher)); |
||
}); |
||
} |
||
return adjustedMatchers; |
||
} |
||
|
||
|
||
/** |
||
* @ngdoc service |
||
* @name ng.$sceDelegate |
||
* @function |
||
* |
||
* @description |
||
* |
||
* `$sceDelegate` is a service that is used by the `$sce` service to provide {@link ng.$sce Strict |
||
* Contextual Escaping (SCE)} services to AngularJS. |
||
* |
||
* Typically, you would configure or override the {@link ng.$sceDelegate $sceDelegate} instead of |
||
* the `$sce` service to customize the way Strict Contextual Escaping works in AngularJS. This is |
||
* because, while the `$sce` provides numerous shorthand methods, etc., you really only need to |
||
* override 3 core functions (`trustAs`, `getTrusted` and `valueOf`) to replace the way things |
||
* work because `$sce` delegates to `$sceDelegate` for these operations. |
||
* |
||
* Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} to configure this service. |
||
* |
||
* The default instance of `$sceDelegate` should work out of the box with little pain. While you |
||
* can override it completely to change the behavior of `$sce`, the common case would |
||
* involve configuring the {@link ng.$sceDelegateProvider $sceDelegateProvider} instead by setting |
||
* your own whitelists and blacklists for trusting URLs used for loading AngularJS resources such as |
||
* templates. Refer {@link ng.$sceDelegateProvider#methods_resourceUrlWhitelist |
||
* $sceDelegateProvider.resourceUrlWhitelist} and {@link |
||
* ng.$sceDelegateProvider#methods_resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist} |
||
*/ |
||
|
||
/** |
||
* @ngdoc object |
||
* @name ng.$sceDelegateProvider |
||
* @description |
||
* |
||
* The `$sceDelegateProvider` provider allows developers to configure the {@link ng.$sceDelegate |
||
* $sceDelegate} service. This allows one to get/set the whitelists and blacklists used to ensure |
||
* that the URLs used for sourcing Angular templates are safe. Refer {@link |
||
* ng.$sceDelegateProvider#methods_resourceUrlWhitelist $sceDelegateProvider.resourceUrlWhitelist} and |
||
* {@link ng.$sceDelegateProvider#methods_resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist} |
||
* |
||
* For the general details about this service in Angular, read the main page for {@link ng.$sce |
||
* Strict Contextual Escaping (SCE)}. |
||
* |
||
* **Example**: Consider the following case. <a name="example"></a> |
||
* |
||
* - your app is hosted at url `http://myapp.example.com/` |
||
* - but some of your templates are hosted on other domains you control such as |
||
* `http://srv01.assets.example.com/`, `http://srv02.assets.example.com/`, etc. |
||
* - and you have an open redirect at `http://myapp.example.com/clickThru?...`. |
||
* |
||
* Here is what a secure configuration for this scenario might look like: |
||
* |
||
* <pre class="prettyprint"> |
||
* angular.module('myApp', []).config(function($sceDelegateProvider) { |
||
* $sceDelegateProvider.resourceUrlWhitelist([ |
||
* // Allow same origin resource loads. |
||
* 'self', |
||
* // Allow loading from our assets domain. Notice the difference between * and **. |
||
* 'http://srv*.assets.example.com/**']); |
||
* |
||
* // The blacklist overrides the whitelist so the open redirect here is blocked. |
||
* $sceDelegateProvider.resourceUrlBlacklist([ |
||
* 'http://myapp.example.com/clickThru**']); |
||
* }); |
||
* </pre> |
||
*/ |
||
|
||
function $SceDelegateProvider() { |
||
this.SCE_CONTEXTS = SCE_CONTEXTS; |
||
|
||
// Resource URLs can also be trusted by policy. |
||
var resourceUrlWhitelist = ['self'], |
||
resourceUrlBlacklist = []; |
||
|
||
/** |
||
* @ngdoc function |
||
* @name ng.sceDelegateProvider#resourceUrlWhitelist |
||
* @methodOf ng.$sceDelegateProvider |
||
* @function |
||
* |
||
* @param {Array=} whitelist When provided, replaces the resourceUrlWhitelist with the value |
||
* provided. This must be an array or null. A snapshot of this array is used so further |
||
* changes to the array are ignored. |
||
* |
||
* Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items |
||
* allowed in this array. |
||
* |
||
* Note: **an empty whitelist array will block all URLs**! |
||
* |
||
* @return {Array} the currently set whitelist array. |
||
* |
||
* The **default value** when no whitelist has been explicitly set is `['self']` allowing only |
||
* same origin resource requests. |
||
* |
||
* @description |
||
* Sets/Gets the whitelist of trusted resource URLs. |
||
*/ |
||
this.resourceUrlWhitelist = function (value) { |
||
if (arguments.length) { |
||
resourceUrlWhitelist = adjustMatchers(value); |
||
} |
||
return resourceUrlWhitelist; |
||
}; |
||
|
||
/** |
||
* @ngdoc function |
||
* @name ng.sceDelegateProvider#resourceUrlBlacklist |
||
* @methodOf ng.$sceDelegateProvider |
||
* @function |
||
* |
||
* @param {Array=} blacklist When provided, replaces the resourceUrlBlacklist with the value |
||
* provided. This must be an array or null. A snapshot of this array is used so further |
||
* changes to the array are ignored. |
||
* |
||
* Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items |
||
* allowed in this array. |
||
* |
||
* The typical usage for the blacklist is to **block |
||
* [open redirects](http://cwe.mitre.org/data/definitions/601.html)** served by your domain as |
||
* these would otherwise be trusted but actually return content from the redirected domain. |
||
* |
||
* Finally, **the blacklist overrides the whitelist** and has the final say. |
||
* |
||
* @return {Array} the currently set blacklist array. |
||
* |
||
* The **default value** when no whitelist has been explicitly set is the empty array (i.e. there |
||
* is no blacklist.) |
||
* |
||
* @description |
||
* Sets/Gets the blacklist of trusted resource URLs. |
||
*/ |
||
|
||
this.resourceUrlBlacklist = function (value) { |
||
if (arguments.length) { |
||
resourceUrlBlacklist = adjustMatchers(value); |
||
} |
||
return resourceUrlBlacklist; |
||
}; |
||
|
||
this.$get = ['$injector', function($injector) { |
||
|
||
var htmlSanitizer = function htmlSanitizer(html) { |
||
throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.'); |
||
}; |
||
|
||
if ($injector.has('$sanitize')) { |
||
htmlSanitizer = $injector.get('$sanitize'); |
||
} |
||
|
||
|
||
function matchUrl(matcher, parsedUrl) { |
||
if (matcher === 'self') { |
||
return urlIsSameOrigin(parsedUrl); |
||
} else { |
||
// definitely a regex. See adjustMatchers() |
||
return !!matcher.exec(parsedUrl.href); |
||
} |
||
} |
||
|
||
function isResourceUrlAllowedByPolicy(url) { |
||
var parsedUrl = urlResolve(url.toString()); |
||
var i, n, allowed = false; |
||
// Ensure that at least one item from the whitelist allows this url. |
||
for (i = 0, n = resourceUrlWhitelist.length; i < n; i++) { |
||
if (matchUrl(resourceUrlWhitelist[i], parsedUrl)) { |
||
allowed = true; |
||
break; |
||
} |
||
} |
||
if (allowed) { |
||
// Ensure that no item from the blacklist blocked this url. |
||
for (i = 0, n = resourceUrlBlacklist.length; i < n; i++) { |
||
if (matchUrl(resourceUrlBlacklist[i], parsedUrl)) { |
||
allowed = false; |
||
break; |
||
} |
||
} |
||
} |
||
return allowed; |
||
} |
||
|
||
function generateHolderType(Base) { |
||
var holderType = function TrustedValueHolderType(trustedValue) { |
||
this.$$unwrapTrustedValue = function() { |
||
return trustedValue; |
||
}; |
||
}; |
||
if (Base) { |
||
holderType.prototype = new Base(); |
||
} |
||
holderType.prototype.valueOf = function sceValueOf() { |
||
return this.$$unwrapTrustedValue(); |
||
}; |
||
holderType.prototype.toString = function sceToString() { |
||
return this.$$unwrapTrustedValue().toString(); |
||
}; |
||
return holderType; |
||
} |
||
|
||
var trustedValueHolderBase = generateHolderType(), |
||
byType = {}; |
||
|
||
byType[SCE_CONTEXTS.HTML] = generateHolderType(trustedValueHolderBase); |
||
byType[SCE_CONTEXTS.CSS] = generateHolderType(trustedValueHolderBase); |
||
byType[SCE_CONTEXTS.URL] = generateHolderType(trustedValueHolderBase); |
||
byType[SCE_CONTEXTS.JS] = generateHolderType(trustedValueHolderBase); |
||
byType[SCE_CONTEXTS.RESOURCE_URL] = generateHolderType(byType[SCE_CONTEXTS.URL]); |
||
|
||
/** |
||
* @ngdoc method |
||
* @name ng.$sceDelegate#trustAs |
||
* @methodOf ng.$sceDelegate |
||
* |
||
* @description |
||
* Returns an object that is trusted by angular for use in specified strict |
||
* contextual escaping contexts (such as ng-html-bind-unsafe, ng-include, any src |
||
* attribute interpolation, any dom event binding attribute interpolation |
||
* such as for onclick, etc.) that uses the provided value. |
||
* See {@link ng.$sce $sce} for enabling strict contextual escaping. |
||
* |
||
* @param {string} type The kind of context in which this value is safe for use. e.g. url, |
||
* resourceUrl, html, js and css. |
||
* @param {*} value The value that that should be considered trusted/safe. |
||
* @returns {*} A value that can be used to stand in for the provided `value` in places |
||
* where Angular expects a $sce.trustAs() return value. |
||
*/ |
||
function trustAs(type, trustedValue) { |
||
var Constructor = (byType.hasOwnProperty(type) ? byType[type] : null); |
||
if (!Constructor) { |
||
throw $sceMinErr('icontext', |
||
'Attempted to trust a value in invalid context. Context: {0}; Value: {1}', |
||
type, trustedValue); |
||
} |
||
if (trustedValue === null || trustedValue === undefined || trustedValue === '') { |
||
return trustedValue; |
||
} |
||
// All the current contexts in SCE_CONTEXTS happen to be strings. In order to avoid trusting |
||
// mutable objects, we ensure here that the value passed in is actually a string. |
||
if (typeof trustedValue !== 'string') { |
||
throw $sceMinErr('itype', |
||
'Attempted to trust a non-string value in a content requiring a string: Context: {0}', |
||
type); |
||
} |
||
return new Constructor(trustedValue); |
||
} |
||
|
||
/** |
||
* @ngdoc method |
||
* @name ng.$sceDelegate#valueOf |
||
* @methodOf ng.$sceDelegate |
||
* |
||
* @description |
||
* If the passed parameter had been returned by a prior call to {@link ng.$sceDelegate#methods_trustAs |
||
* `$sceDelegate.trustAs`}, returns the value that had been passed to {@link |
||
* ng.$sceDelegate#methods_trustAs `$sceDelegate.trustAs`}. |
||
* |
||
* If the passed parameter is not a value that had been returned by {@link |
||
* ng.$sceDelegate#methods_trustAs `$sceDelegate.trustAs`}, returns it as-is. |
||
* |
||
* @param {*} value The result of a prior {@link ng.$sceDelegate#methods_trustAs `$sceDelegate.trustAs`} |
||
* call or anything else. |
||
* @returns {*} The `value` that was originally provided to {@link ng.$sceDelegate#methods_trustAs |
||
* `$sceDelegate.trustAs`} if `value` is the result of such a call. Otherwise, returns |
||
* `value` unchanged. |
||
*/ |
||
function valueOf(maybeTrusted) { |
||
if (maybeTrusted instanceof trustedValueHolderBase) { |
||
return maybeTrusted.$$unwrapTrustedValue(); |
||
} else { |
||
return maybeTrusted; |
||
} |
||
} |
||
|
||
/** |
||
* @ngdoc method |
||
* @name ng.$sceDelegate#getTrusted |
||
* @methodOf ng.$sceDelegate |
||
* |
||
* @description |
||
* Takes the result of a {@link ng.$sceDelegate#methods_trustAs `$sceDelegate.trustAs`} call and |
||
* returns the originally supplied value if the queried context type is a supertype of the |
||
* created type. If this condition isn't satisfied, throws an exception. |
||
* |
||
* @param {string} type The kind of context in which this value is to be used. |
||
* @param {*} maybeTrusted The result of a prior {@link ng.$sceDelegate#methods_trustAs |
||
* `$sceDelegate.trustAs`} call. |
||
* @returns {*} The value the was originally provided to {@link ng.$sceDelegate#methods_trustAs |
||
* `$sceDelegate.trustAs`} if valid in this context. Otherwise, throws an exception. |
||
*/ |
||
function getTrusted(type, maybeTrusted) { |
||
if (maybeTrusted === null || maybeTrusted === undefined || maybeTrusted === '') { |
||
return maybeTrusted; |
||
} |
||
var constructor = (byType.hasOwnProperty(type) ? byType[type] : null); |
||
if (constructor && maybeTrusted instanceof constructor) { |
||
return maybeTrusted.$$unwrapTrustedValue(); |
||
} |
||
// If we get here, then we may only take one of two actions. |
||
// 1. sanitize the value for the requested type, or |
||
// 2. throw an exception. |
||
if (type === SCE_CONTEXTS.RESOURCE_URL) { |
||
if (isResourceUrlAllowedByPolicy(maybeTrusted)) { |
||
return maybeTrusted; |
||
} else { |
||
throw $sceMinErr('insecurl', |
||
'Blocked loading resource from url not allowed by $sceDelegate policy. URL: {0}', |
||
maybeTrusted.toString()); |
||
} |
||
} else if (type === SCE_CONTEXTS.HTML) { |
||
return htmlSanitizer(maybeTrusted); |
||
} |
||
throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.'); |
||
} |
||
|
||
return { trustAs: trustAs, |
||
getTrusted: getTrusted, |
||
valueOf: valueOf }; |
||
}]; |
||
} |
||
|
||
|
||
/** |
||
* @ngdoc object |
||
* @name ng.$sceProvider |
||
* @description |
||
* |
||
* The $sceProvider provider allows developers to configure the {@link ng.$sce $sce} service. |
||
* - enable/disable Strict Contextual Escaping (SCE) in a module |
||
* - override the default implementation with a custom delegate |
||
* |
||
* Read more about {@link ng.$sce Strict Contextual Escaping (SCE)}. |
||
*/ |
||
|
||
/* jshint maxlen: false*/ |
||
|
||
/** |
||
* @ngdoc service |
||
* @name ng.$sce |
||
* @function |
||
* |
||
* @description |
||
* |
||
* `$sce` is a service that provides Strict Contextual Escaping services to AngularJS. |
||
* |
||
* # Strict Contextual Escaping |
||
* |
||
* Strict Contextual Escaping (SCE) is a mode in which AngularJS requires bindings in certain |
||
* contexts to result in a value that is marked as safe to use for that context. One example of |
||
* such a context is binding arbitrary html controlled by the user via `ng-bind-html`. We refer |
||
* to these contexts as privileged or SCE contexts. |
||
* |
||
* As of version 1.2, Angular ships with SCE enabled by default. |
||
* |
||
* Note: When enabled (the default), IE8 in quirks mode is not supported. In this mode, IE8 allows |
||
* one to execute arbitrary javascript by the use of the expression() syntax. Refer |
||
* <http://blogs.msdn.com/b/ie/archive/2008/10/16/ending-expressions.aspx> to learn more about them. |
||
* You can ensure your document is in standards mode and not quirks mode by adding `<!doctype html>` |
||
* to the top of your HTML document. |
||
* |
||
* SCE assists in writing code in way that (a) is secure by default and (b) makes auditing for |
||
* security vulnerabilities such as XSS, clickjacking, etc. a lot easier. |
||
* |
||
* Here's an example of a binding in a privileged context: |
||
* |
||
* <pre class="prettyprint"> |
||
* <input ng-model="userHtml"> |
||
* <div ng-bind-html="userHtml"> |
||
* </pre> |
||
* |
||
* Notice that `ng-bind-html` is bound to `userHtml` controlled by the user. With SCE |
||
* disabled, this application allows the user to render arbitrary HTML into the DIV. |
||
* In a more realistic example, one may be rendering user comments, blog articles, etc. via |
||
* bindings. (HTML is just one example of a context where rendering user controlled input creates |
||
* security vulnerabilities.) |
||
* |
||
* For the case of HTML, you might use a library, either on the client side, or on the server side, |
||
* to sanitize unsafe HTML before binding to the value and rendering it in the document. |
||
* |
||
* How would you ensure that every place that used these types of bindings was bound to a value that |
||
* was sanitized by your library (or returned as safe for rendering by your server?) How can you |
||
* ensure that you didn't accidentally delete the line that sanitized the value, or renamed some |
||
* properties/fields and forgot to update the binding to the sanitized value? |
||
* |
||
* To be secure by default, you want to ensure that any such bindings are disallowed unless you can |
||
* determine that something explicitly says it's safe to use a value for binding in that |
||
* context. You can then audit your code (a simple grep would do) to ensure that this is only done |
||
* for those values that you can easily tell are safe - because they were received from your server, |
||
* sanitized by your library, etc. You can organize your codebase to help with this - perhaps |
||
* allowing only the files in a specific directory to do this. Ensuring that the internal API |
||
* exposed by that code doesn't markup arbitrary values as safe then becomes a more manageable task. |
||
* |
||
* In the case of AngularJS' SCE service, one uses {@link ng.$sce#methods_trustAs $sce.trustAs} |
||
* (and shorthand methods such as {@link ng.$sce#methods_trustAsHtml $sce.trustAsHtml}, etc.) to |
||
* obtain values that will be accepted by SCE / privileged contexts. |
||
* |
||
* |
||
* ## How does it work? |
||
* |
||
* In privileged contexts, directives and code will bind to the result of {@link ng.$sce#methods_getTrusted |
||
* $sce.getTrusted(context, value)} rather than to the value directly. Directives use {@link |
||
* ng.$sce#methods_parse $sce.parseAs} rather than `$parse` to watch attribute bindings, which performs the |
||
* {@link ng.$sce#methods_getTrusted $sce.getTrusted} behind the scenes on non-constant literals. |
||
* |
||
* As an example, {@link ng.directive:ngBindHtml ngBindHtml} uses {@link |
||
* ng.$sce#methods_parseAsHtml $sce.parseAsHtml(binding expression)}. Here's the actual code (slightly |
||
* simplified): |
||
* |
||
* <pre class="prettyprint"> |
||
* var ngBindHtmlDirective = ['$sce', function($sce) { |
||
* return function(scope, element, attr) { |
||
* scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function(value) { |
||
* element.html(value || ''); |
||
* }); |
||
* }; |
||
* }]; |
||
* </pre> |
||
* |
||
* ## Impact on loading templates |
||
* |
||
* This applies both to the {@link ng.directive:ngInclude `ng-include`} directive as well as |
||
* `templateUrl`'s specified by {@link guide/directive directives}. |
||
* |
||
* By default, Angular only loads templates from the same domain and protocol as the application |
||
* document. This is done by calling {@link ng.$sce#methods_getTrustedResourceUrl |
||
* $sce.getTrustedResourceUrl} on the template URL. To load templates from other domains and/or |
||
* protocols, you may either either {@link ng.$sceDelegateProvider#methods_resourceUrlWhitelist whitelist |
||
* them} or {@link ng.$sce#methods_trustAsResourceUrl wrap it} into a trusted value. |
||
* |
||
* *Please note*: |
||
* The browser's |
||
* {@link https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest |
||
* Same Origin Policy} and {@link http://www.w3.org/TR/cors/ Cross-Origin Resource Sharing (CORS)} |
||
* policy apply in addition to this and may further restrict whether the template is successfully |
||
* loaded. This means that without the right CORS policy, loading templates from a different domain |
||
* won't work on all browsers. Also, loading templates from `file://` URL does not work on some |
||
* browsers. |
||
* |
||
* ## This feels like too much overhead for the developer? |
||
* |
||
* It's important to remember that SCE only applies to interpolation expressions. |
||
* |
||
* If your expressions are constant literals, they're automatically trusted and you don't need to |
||
* call `$sce.trustAs` on them. (e.g. |
||
* `<div ng-html-bind-unsafe="'<b>implicitly trusted</b>'"></div>`) just works. |
||
* |
||
* Additionally, `a[href]` and `img[src]` automatically sanitize their URLs and do not pass them |
||
* through {@link ng.$sce#methods_getTrusted $sce.getTrusted}. SCE doesn't play a role here. |
||
* |
||
* The included {@link ng.$sceDelegate $sceDelegate} comes with sane defaults to allow you to load |
||
* templates in `ng-include` from your application's domain without having to even know about SCE. |
||
* It blocks loading templates from other domains or loading templates over http from an https |
||
* served document. You can change these by setting your own custom {@link |
||
* ng.$sceDelegateProvider#methods_resourceUrlWhitelist whitelists} and {@link |
||
* ng.$sceDelegateProvider#methods_resourceUrlBlacklist blacklists} for matching such URLs. |
||
* |
||
* This significantly reduces the overhead. It is far easier to pay the small overhead and have an |
||
* application that's secure and can be audited to verify that with much more ease than bolting |
||
* security onto an application later. |
||
* |
||
* <a name="contexts"></a> |
||
* ## What trusted context types are supported? |
||
* |
||
* | Context | Notes | |
||
* |---------------------|----------------| |
||
* | `$sce.HTML` | For HTML that's safe to source into the application. The {@link ng.directive:ngBindHtml ngBindHtml} directive uses this context for bindings. | |
||
* | `$sce.CSS` | For CSS that's safe to source into the application. Currently unused. Feel free to use it in your own directives. | |
||
* | `$sce.URL` | For URLs that are safe to follow as links. Currently unused (`<a href=` and `<img src=` sanitize their urls and don't consititute an SCE context. | |
||
* | `$sce.RESOURCE_URL` | For URLs that are not only safe to follow as links, but whose contens are also safe to include in your application. Examples include `ng-include`, `src` / `ngSrc` bindings for tags other than `IMG` (e.g. `IFRAME`, `OBJECT`, etc.) <br><br>Note that `$sce.RESOURCE_URL` makes a stronger statement about the URL than `$sce.URL` does and therefore contexts requiring values trusted for `$sce.RESOURCE_URL` can be used anywhere that values trusted for `$sce.URL` are required. | |
||
* | `$sce.JS` | For JavaScript that is safe to execute in your application's context. Currently unused. Feel free to use it in your own directives. | |
||
* |
||
* ## Format of items in {@link ng.$sceDelegateProvider#methods_resourceUrlWhitelist resourceUrlWhitelist}/{@link ng.$sceDelegateProvider#methods_resourceUrlBlacklist Blacklist} <a name="resourceUrlPatternItem"></a> |
||
* |
||
* Each element in these arrays must be one of the following: |
||
* |
||
* - **'self'** |
||
* - The special **string**, `'self'`, can be used to match against all URLs of the **same |
||
* domain** as the application document using the **same protocol**. |
||
* - **String** (except the special value `'self'`) |
||
* - The string is matched against the full *normalized / absolute URL* of the resource |
||
* being tested (substring matches are not good enough.) |
||
* - There are exactly **two wildcard sequences** - `*` and `**`. All other characters |
||
* match themselves. |
||
* - `*`: matches zero or more occurances of any character other than one of the following 6 |
||
* characters: '`:`', '`/`', '`.`', '`?`', '`&`' and ';'. It's a useful wildcard for use |
||
* in a whitelist. |
||
* - `**`: matches zero or more occurances of *any* character. As such, it's not |
||
* not appropriate to use in for a scheme, domain, etc. as it would match too much. (e.g. |
||
* http://**.example.com/ would match http://evil.com/?ignore=.example.com/ and that might |
||
* not have been the intention.) It's usage at the very end of the path is ok. (e.g. |
||
* http://foo.example.com/templates/**). |
||
* - **RegExp** (*see caveat below*) |
||
* - *Caveat*: While regular expressions are powerful and offer great flexibility, their syntax |
||
* (and all the inevitable escaping) makes them *harder to maintain*. It's easy to |
||
* accidentally introduce a bug when one updates a complex expression (imho, all regexes should |
||
* have good test coverage.). For instance, the use of `.` in the regex is correct only in a |
||
* small number of cases. A `.` character in the regex used when matching the scheme or a |
||
* subdomain could be matched against a `:` or literal `.` that was likely not intended. It |
||
* is highly recommended to use the string patterns and only fall back to regular expressions |
||
* if they as a last resort. |
||
* - The regular expression must be an instance of RegExp (i.e. not a string.) It is |
||
* matched against the **entire** *normalized / absolute URL* of the resource being tested |
||
* (even when the RegExp did not have the `^` and `$` codes.) In addition, any flags |
||
* present on the RegExp (such as multiline, global, ignoreCase) are ignored. |
||
* - If you are generating your Javascript from some other templating engine (not |
||
* recommended, e.g. in issue [#4006](https://github.com/angular/angular.js/issues/4006)), |
||
* remember to escape your regular expression (and be aware that you might need more than |
||
* one level of escaping depending on your templating engine and the way you interpolated |
||
* the value.) Do make use of your platform's escaping mechanism as it might be good |
||
* enough before coding your own. e.g. Ruby has |
||
* [Regexp.escape(str)](http://www.ruby-doc.org/core-2.0.0/Regexp.html#method-c-escape) |
||
* and Python has [re.escape](http://docs.python.org/library/re.html#re.escape). |
||
* Javascript lacks a similar built in function for escaping. Take a look at Google |
||
* Closure library's [goog.string.regExpEscape(s)]( |
||
* http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962). |
||
* |
||
* Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} for an example. |
||
* |
||
* ## Show me an example using SCE. |
||
* |
||
* @example |
||
<example module="mySceApp"> |
||
<file name="index.html"> |
||
<div ng-controller="myAppController as myCtrl"> |
||
<i ng-bind-html="myCtrl.explicitlyTrustedHtml" id="explicitlyTrustedHtml"></i><br><br> |
||
<b>User comments</b><br> |
||
By default, HTML that isn't explicitly trusted (e.g. Alice's comment) is sanitized when |
||
$sanitize is available. If $sanitize isn't available, this results in an error instead of an |
||
exploit. |
||
<div class="well"> |
||
<div ng-repeat="userComment in myCtrl.userComments"> |
||
<b>{{userComment.name}}</b>: |
||
<span ng-bind-html="userComment.htmlComment" class="htmlComment"></span> |
||
<br> |
||
</div> |
||
</div> |
||
</div> |
||
</file> |
||
|
||
<file name="script.js"> |
||
var mySceApp = angular.module('mySceApp', ['ngSanitize']); |
||
|
||
mySceApp.controller("myAppController", function myAppController($http, $templateCache, $sce) { |
||
var self = this; |
||
$http.get("test_data.json", {cache: $templateCache}).success(function(userComments) { |
||
self.userComments = userComments; |
||
}); |
||
self.explicitlyTrustedHtml = $sce.trustAsHtml( |
||
'<span onmouseover="this.textContent="Explicitly trusted HTML bypasses ' + |
||
'sanitization."">Hover over this text.</span>'); |
||
}); |
||
</file> |
||
|
||
<file name="test_data.json"> |
||
[ |
||
{ "name": "Alice", |
||
"htmlComment": |
||
"<span onmouseover='this.textContent=\"PWN3D!\"'>Is <i>anyone</i> reading this?</span>" |
||
}, |
||
{ "name": "Bob", |
||
"htmlComment": "<i>Yes!</i> Am I the only other one?" |
||
} |
||
] |
||
</file> |
||
|
||
<file name="scenario.js"> |
||
describe('SCE doc demo', function() { |
||
it('should sanitize untrusted values', function() { |
||
expect(element('.htmlComment').html()).toBe('<span>Is <i>anyone</i> reading this?</span>'); |
||
}); |
||
it('should NOT sanitize explicitly trusted values', function() { |
||
expect(element('#explicitlyTrustedHtml').html()).toBe( |
||
'<span onmouseover="this.textContent="Explicitly trusted HTML bypasses ' + |
||
'sanitization."">Hover over this text.</span>'); |
||
}); |
||
}); |
||
</file> |
||
</example> |
||
* |
||
* |
||
* |
||
* ## Can I disable SCE completely? |
||
* |
||
* Yes, you can. However, this is strongly discouraged. SCE gives you a lot of security benefits |
||
* for little coding overhead. It will be much harder to take an SCE disabled application and |
||
* either secure it on your own or enable SCE at a later stage. It might make sense to disable SCE |
||
* for cases where you have a lot of existing code that was written before SCE was introduced and |
||
* you're migrating them a module at a time. |
||
* |
||
* That said, here's how you can completely disable SCE: |
||
* |
||
* <pre class="prettyprint"> |
||
* angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) { |
||
* // Completely disable SCE. For demonstration purposes only! |
||
* // Do not use in new projects. |
||
* $sceProvider.enabled(false); |
||
* }); |
||
* </pre> |
||
* |
||
*/ |
||
/* jshint maxlen: 100 */ |
||
|
||
function $SceProvider() { |
||
var enabled = true; |
||
|
||
/** |
||
* @ngdoc function |
||
* @name ng.sceProvider#enabled |
||
* @methodOf ng.$sceProvider |
||
* @function |
||
* |
||
* @param {boolean=} value If provided, then enables/disables SCE. |
||
* @return {boolean} true if SCE is enabled, false otherwise. |
||
* |
||
* @description |
||
* Enables/disables SCE and returns the current value. |
||
*/ |
||
this.enabled = function (value) { |
||
if (arguments.length) { |
||
enabled = !!value; |
||
} |
||
return enabled; |
||
}; |
||
|
||
|
||
/* Design notes on the default implementation for SCE. |
||
* |
||
* The API contract for the SCE delegate |
||
* ------------------------------------- |
||
* The SCE delegate object must provide the following 3 methods: |
||
* |
||
* - trustAs(contextEnum, value) |
||
* This method is used to tell the SCE service that the provided value is OK to use in the |
||
* contexts specified by contextEnum. It must return an object that will be accepted by |
||
* getTrusted() for a compatible contextEnum and return this value. |
||
* |
||
* - valueOf(value) |
||
* For values that were not produced by trustAs(), return them as is. For values that were |
||
* produced by trustAs(), return the corresponding input value to trustAs. Basically, if |
||
* trustAs is wrapping the given values into some type, this operation unwraps it when given |
||
* such a value. |
||
* |
||
* - getTrusted(contextEnum, value) |
||
* This function should return the a value that is safe to use in the context specified by |
||
* contextEnum or throw and exception otherwise. |
||
* |
||
* NOTE: This contract deliberately does NOT state that values returned by trustAs() must be |
||
* opaque or wrapped in some holder object. That happens to be an implementation detail. For |
||
* instance, an implementation could maintain a registry of all trusted objects by context. In |
||
* such a case, trustAs() would return the same object that was passed in. getTrusted() would |
||
* return the same object passed in if it was found in the registry under a compatible context or |
||
* throw an exception otherwise. An implementation might only wrap values some of the time based |
||
* on some criteria. getTrusted() might return a value and not throw an exception for special |
||
* constants or objects even if not wrapped. All such implementations fulfill this contract. |
||
* |
||
* |
||
* A note on the inheritance model for SCE contexts |
||
* ------------------------------------------------ |
||
* I've used inheritance and made RESOURCE_URL wrapped types a subtype of URL wrapped types. This |
||
* is purely an implementation details. |
||
* |
||
* The contract is simply this: |
||
* |
||
* getTrusted($sce.RESOURCE_URL, value) succeeding implies that getTrusted($sce.URL, value) |
||
* will also succeed. |
||
* |
||
* Inheritance happens to capture this in a natural way. In some future, we |
||
* may not use inheritance anymore. That is OK because no code outside of |
||
* sce.js and sceSpecs.js would need to be aware of this detail. |
||
*/ |
||
|
||
this.$get = ['$parse', '$sniffer', '$sceDelegate', function( |
||
$parse, $sniffer, $sceDelegate) { |
||
// Prereq: Ensure that we're not running in IE8 quirks mode. In that mode, IE allows |
||
// the "expression(javascript expression)" syntax which is insecure. |
||
if (enabled && $sniffer.msie && $sniffer.msieDocumentMode < 8) { |
||
throw $sceMinErr('iequirks', |
||
'Strict Contextual Escaping does not support Internet Explorer version < 9 in quirks ' + |
||
'mode. You can fix this by adding the text <!doctype html> to the top of your HTML ' + |
||
'document. See http://docs.angularjs.org/api/ng.$sce for more information.'); |
||
} |
||
|
||
var sce = copy(SCE_CONTEXTS); |
||
|
||
/** |
||
* @ngdoc function |
||
* @name ng.sce#isEnabled |
||
* @methodOf ng.$sce |
||
* @function |
||
* |
||
* @return {Boolean} true if SCE is enabled, false otherwise. If you want to set the value, you |
||
* have to do it at module config time on {@link ng.$sceProvider $sceProvider}. |
||
* |
||
* @description |
||
* Returns a boolean indicating if SCE is enabled. |
||
*/ |
||
sce.isEnabled = function () { |
||
return enabled; |
||
}; |
||
sce.trustAs = $sceDelegate.trustAs; |
||
sce.getTrusted = $sceDelegate.getTrusted; |
||
sce.valueOf = $sceDelegate.valueOf; |
||
|
||
if (!enabled) { |
||
sce.trustAs = sce.getTrusted = function(type, value) { return value; }; |
||
sce.valueOf = identity; |
||
} |
||
|
||
/** |
||
* @ngdoc method |
||
* @name ng.$sce#parse |
||
* @methodOf ng.$sce |
||
* |
||
* @description |
||
* Converts Angular {@link guide/expression expression} into a function. This is like {@link |
||
* ng.$parse $parse} and is identical when the expression is a literal constant. Otherwise, it |
||
* wraps the expression in a call to {@link ng.$sce#methods_getTrusted $sce.getTrusted(*type*, |
||
* *result*)} |
||
* |
||
* @param {string} type The kind of SCE context in which this result will be used. |
||
* @param {string} expression String expression to compile. |
||
* @returns {function(context, locals)} a function which represents the compiled expression: |
||
* |
||
* * `context` – `{object}` – an object against which any expressions embedded in the strings |
||
* are evaluated against (typically a scope object). |
||
* * `locals` – `{object=}` – local variables context object, useful for overriding values in |
||
* `context`. |
||
*/ |
||
sce.parseAs = function sceParseAs(type, expr) { |
||
var parsed = $parse(expr); |
||
if (parsed.literal && parsed.constant) { |
||
return parsed; |
||
} else { |
||
return function sceParseAsTrusted(self, locals) { |
||
return sce.getTrusted(type, parsed(self, locals)); |
||
}; |
||
} |
||
}; |
||
|
||
/** |
||
* @ngdoc method |
||
* @name ng.$sce#trustAs |
||
* @methodOf ng.$sce |
||
* |
||
* @description |
||
* Delegates to {@link ng.$sceDelegate#methods_trustAs `$sceDelegate.trustAs`}. As such, |
||
* returns an objectthat is trusted by angular for use in specified strict contextual |
||
* escaping contexts (such as ng-html-bind-unsafe, ng-include, any src attribute |
||
* interpolation, any dom event binding attribute interpolation such as for onclick, etc.) |
||
* that uses the provided value. See * {@link ng.$sce $sce} for enabling strict contextual |
||
* escaping. |
||
* |
||
* @param {string} type The kind of context in which this value is safe for use. e.g. url, |
||
* resource_url, html, js and css. |
||
* @param {*} value The value that that should be considered trusted/safe. |
||
* @returns {*} A value that can be used to stand in for the provided `value` in places |
||
* where Angular expects a $sce.trustAs() return value. |
||
*/ |
||
|
||
/** |
||
* @ngdoc method |
||
* @name ng.$sce#trustAsHtml |
||
* @methodOf ng.$sce |
||
* |
||
* @description |
||
* Shorthand method. `$sce.trustAsHtml(value)` → |
||
* {@link ng.$sceDelegate#methods_trustAs `$sceDelegate.trustAs($sce.HTML, value)`} |
||
* |
||
* @param {*} value The value to trustAs. |
||
* @returns {*} An object that can be passed to {@link ng.$sce#methods_getTrustedHtml |
||
* $sce.getTrustedHtml(value)} to obtain the original value. (privileged directives |
||
* only accept expressions that are either literal constants or are the |
||
* return value of {@link ng.$sce#methods_trustAs $sce.trustAs}.) |
||
*/ |
||
|
||
/** |
||
* @ngdoc method |
||
* @name ng.$sce#trustAsUrl |
||
* @methodOf ng.$sce |
||
* |
||
* @description |
||
* Shorthand method. `$sce.trustAsUrl(value)` → |
||
* {@link ng.$sceDelegate#methods_trustAs `$sceDelegate.trustAs($sce.URL, value)`} |
||
* |
||
* @param {*} value The value to trustAs. |
||
* @returns {*} An object that can be passed to {@link ng.$sce#methods_getTrustedUrl |
||
* $sce.getTrustedUrl(value)} to obtain the original value. (privileged directives |
||
* only accept expressions that are either literal constants or are the |
||
* return value of {@link ng.$sce#methods_trustAs $sce.trustAs}.) |
||
*/ |
||
|
||
/** |
||
* @ngdoc method |
||
* @name ng.$sce#trustAsResourceUrl |
||
* @methodOf ng.$sce |
||
* |
||
* @description |
||
* Shorthand method. `$sce.trustAsResourceUrl(value)` → |
||
* {@link ng.$sceDelegate#methods_trustAs `$sceDelegate.trustAs($sce.RESOURCE_URL, value)`} |
||
* |
||
* @param {*} value The value to trustAs. |
||
* @returns {*} An object that can be passed to {@link ng.$sce#methods_getTrustedResourceUrl |
||
* $sce.getTrustedResourceUrl(value)} to obtain the original value. (privileged directives |
||
* only accept expressions that are either literal constants or are the return |
||
* value of {@link ng.$sce#methods_trustAs $sce.trustAs}.) |
||
*/ |
||
|
||
/** |
||
* @ngdoc method |
||
* @name ng.$sce#trustAsJs |
||
* @methodOf ng.$sce |
||
* |
||
* @description |
||
* Shorthand method. `$sce.trustAsJs(value)` → |
||
* {@link ng.$sceDelegate#methods_trustAs `$sceDelegate.trustAs($sce.JS, value)`} |
||
* |
||
* @param {*} value The value to trustAs. |
||
* @returns {*} An object that can be passed to {@link ng.$sce#methods_getTrustedJs |
||
* $sce.getTrustedJs(value)} to obtain the original value. (privileged directives |
||
* only accept expressions that are either literal constants or are the |
||
* return value of {@link ng.$sce#methods_trustAs $sce.trustAs}.) |
||
*/ |
||
|
||
/** |
||
* @ngdoc method |
||
* @name ng.$sce#getTrusted |
||
* @methodOf ng.$sce |
||
* |
||
* @description |
||
* Delegates to {@link ng.$sceDelegate#methods_getTrusted `$sceDelegate.getTrusted`}. As such, |
||
* takes the result of a {@link ng.$sce#methods_trustAs `$sce.trustAs`}() call and returns the |
||
* originally supplied value if the queried context type is a supertype of the created type. |
||
* If this condition isn't satisfied, throws an exception. |
||
* |
||
* @param {string} type The kind of context in which this value is to be used. |
||
* @param {*} maybeTrusted The result of a prior {@link ng.$sce#methods_trustAs `$sce.trustAs`} |
||
* call. |
||
* @returns {*} The value the was originally provided to |
||
* {@link ng.$sce#methods_trustAs `$sce.trustAs`} if valid in this context. |
||
* Otherwise, throws an exception. |
||
*/ |
||
|
||
/** |
||
* @ngdoc method |
||
* @name ng.$sce#getTrustedHtml |
||
* @methodOf ng.$sce |
||
* |
||
* @description |
||
* Shorthand method. `$sce.getTrustedHtml(value)` → |
||
* {@link ng.$sceDelegate#methods_getTrusted `$sceDelegate.getTrusted($sce.HTML, value)`} |
||
* |
||
* @param {*} value The value to pass to `$sce.getTrusted`. |
||
* @returns {*} The return value of `$sce.getTrusted($sce.HTML, value)` |
||
*/ |
||
|
||
/** |
||
* @ngdoc method |
||
* @name ng.$sce#getTrustedCss |
||
* @methodOf ng.$sce |
||
* |
||
* @description |
||
* Shorthand method. `$sce.getTrustedCss(value)` → |
||
* {@link ng.$sceDelegate#methods_getTrusted `$sceDelegate.getTrusted($sce.CSS, value)`} |
||
* |
||
* @param {*} value The value to pass to `$sce.getTrusted`. |
||
* @returns {*} The return value of `$sce.getTrusted($sce.CSS, value)` |
||
*/ |
||
|
||
/** |
||
* @ngdoc method |
||
* @name ng.$sce#getTrustedUrl |
||
* @methodOf ng.$sce |
||
* |
||
* @description |
||
* Shorthand method. `$sce.getTrustedUrl(value)` → |
||
* {@link ng.$sceDelegate#methods_getTrusted `$sceDelegate.getTrusted($sce.URL, value)`} |
||
* |
||
* @param {*} value The value to pass to `$sce.getTrusted`. |
||
* @returns {*} The return value of `$sce.getTrusted($sce.URL, value)` |
||
*/ |
||
|
||
/** |
||
* @ngdoc method |
||
* @name ng.$sce#getTrustedResourceUrl |
||
* @methodOf ng.$sce |
||
* |
||
* @description |
||
* Shorthand method. `$sce.getTrustedResourceUrl(value)` → |
||
* {@link ng.$sceDelegate#methods_getTrusted `$sceDelegate.getTrusted($sce.RESOURCE_URL, value)`} |
||
* |
||
* @param {*} value The value to pass to `$sceDelegate.getTrusted`. |
||
* @returns {*} The return value of `$sce.getTrusted($sce.RESOURCE_URL, value)` |
||
*/ |
||
|
||
/** |
||
* @ngdoc method |
||
* @name ng.$sce#getTrustedJs |
||
* @methodOf ng.$sce |
||
* |
||
* @description |
||
* Shorthand method. `$sce.getTrustedJs(value)` → |
||
* {@link ng.$sceDelegate#methods_getTrusted `$sceDelegate.getTrusted($sce.JS, value)`} |
||
* |
||
* @param {*} value The value to pass to `$sce.getTrusted`. |
||
* @returns {*} The return value of `$sce.getTrusted($sce.JS, value)` |
||
*/ |
||
|
||
/** |
||
* @ngdoc method |
||
* @name ng.$sce#parseAsHtml |
||
* @methodOf ng.$sce |
||
* |
||
* @description |
||
* Shorthand method. `$sce.parseAsHtml(expression string)` → |
||
* {@link ng.$sce#methods_parse `$sce.parseAs($sce.HTML, value)`} |
||
* |
||
* @param {string} expression String expression to compile. |
||
* @returns {function(context, locals)} a function which represents the compiled expression: |
||
* |
||
* * `context` – `{object}` – an object against which any expressions embedded in the strings |
||
* are evaluated against (typically a scope object). |
||
* * `locals` – `{object=}` – local variables context object, useful for overriding values in |
||
* `context`. |
||
*/ |
||
|
||
/** |
||
* @ngdoc method |
||
* @name ng.$sce#parseAsCss |
||
* @methodOf ng.$sce |
||
* |
||
* @description |
||
* Shorthand method. `$sce.parseAsCss(value)` → |
||
* {@link ng.$sce#methods_parse `$sce.parseAs($sce.CSS, value)`} |
||
* |
||
* @param {string} expression String expression to compile. |
||
* @returns {function(context, locals)} a function which represents the compiled expression: |
||
* |
||
* * `context` – `{object}` – an object against which any expressions embedded in the strings |
||
* are evaluated against (typically a scope object). |
||
* * `locals` – `{object=}` – local variables context object, useful for overriding values in |
||
* `context`. |
||
*/ |
||
|
||
/** |
||
* @ngdoc method |
||
* @name ng.$sce#parseAsUrl |
||
* @methodOf ng.$sce |
||
* |
||
* @description |
||
* Shorthand method. `$sce.parseAsUrl(value)` → |
||
* {@link ng.$sce#methods_parse `$sce.parseAs($sce.URL, value)`} |
||
* |
||
* @param {string} expression String expression to compile. |
||
* @returns {function(context, locals)} a function which represents the compiled expression: |
||
* |
||
* * `context` – `{object}` – an object against which any expressions embedded in the strings |
||
* are evaluated against (typically a scope object). |
||
* * `locals` – `{object=}` – local variables context object, useful for overriding values in |
||
* `context`. |
||
*/ |
||
|
||
/** |
||
* @ngdoc method |
||
* @name ng.$sce#parseAsResourceUrl |
||
* @methodOf ng.$sce |
||
* |
||
* @description |
||
* Shorthand method. `$sce.parseAsResourceUrl(value)` → |
||
* {@link ng.$sce#methods_parse `$sce.parseAs($sce.RESOURCE_URL, value)`} |
||
* |
||
* @param {string} expression String expression to compile. |
||
* @returns {function(context, locals)} a function which represents the compiled expression: |
||
* |
||
* * `context` – `{object}` – an object against which any expressions embedded in the strings |
||
* are evaluated against (typically a scope object). |
||
* * `locals` – `{object=}` – local variables context object, useful for overriding values in |
||
* `context`. |
||
*/ |
||
|
||
/** |
||
* @ngdoc method |
||
* @name ng.$sce#parseAsJs |
||
* @methodOf ng.$sce |
||
* |
||
* @description |
||
* Shorthand method. `$sce.parseAsJs(value)` → |
||
* {@link ng.$sce#methods_parse `$sce.parseAs($sce.JS, value)`} |
||
* |
||
* @param {string} expression String expression to compile. |
||
* @returns {function(context, locals)} a function which represents the compiled expression: |
||
* |
||
* * `context` – `{object}` – an object against which any expressions embedded in the strings |
||
* are evaluated against (typically a scope object). |
||
* * `locals` – `{object=}` – local variables context object, useful for overriding values in |
||
* `context`. |
||
*/ |
||
|
||
// Shorthand delegations. |
||
var parse = sce.parseAs, |
||
getTrusted = sce.getTrusted, |
||
trustAs = sce.trustAs; |
||
|
||
forEach(SCE_CONTEXTS, function (enumValue, name) { |
||
var lName = lowercase(name); |
||
sce[camelCase("parse_as_" + lName)] = function (expr) { |
||
return parse(enumValue, expr); |
||
}; |
||
sce[camelCase("get_trusted_" + lName)] = function (value) { |
||
return getTrusted(enumValue, value); |
||
}; |
||
sce[camelCase("trust_as_" + lName)] = function (value) { |
||
return trustAs(enumValue, value); |
||
}; |
||
}); |
||
|
||
return sce; |
||
}]; |
||
} |
||
|
||
/** |
||
* !!! This is an undocumented "private" service !!! |
||
* |
||
* @name ng.$sniffer |
||
* @requires $window |
||
* @requires $document |
||
* |
||
* @property {boolean} history Does the browser support html5 history api ? |
||
* @property {boolean} hashchange Does the browser support hashchange event ? |
||
* @property {boolean} transitions Does the browser support CSS transition events ? |
||
* @property {boolean} animations Does the browser support CSS animation events ? |
||
* |
||
* @description |
||
* This is very simple implementation of testing browser's features. |
||
*/ |
||
function $SnifferProvider() { |
||
this.$get = ['$window', '$document', function($window, $document) { |
||
var eventSupport = {}, |
||
android = |
||
int((/android (\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]), |
||
boxee = /Boxee/i.test(($window.navigator || {}).userAgent), |
||
document = $document[0] || {}, |
||
documentMode = document.documentMode, |
||
vendorPrefix, |
||
vendorRegex = /^(Moz|webkit|O|ms)(?=[A-Z])/, |
||
bodyStyle = document.body && document.body.style, |
||
transitions = false, |
||
animations = false, |
||
match; |
||
|
||
if (bodyStyle) { |
||
for(var prop in bodyStyle) { |
||
if(match = vendorRegex.exec(prop)) { |
||
vendorPrefix = match[0]; |
||
vendorPrefix = vendorPrefix.substr(0, 1).toUpperCase() + vendorPrefix.substr(1); |
||
break; |
||
} |
||
} |
||
|
||
if(!vendorPrefix) { |
||
vendorPrefix = ('WebkitOpacity' in bodyStyle) && 'webkit'; |
||
} |
||
|
||
transitions = !!(('transition' in bodyStyle) || (vendorPrefix + 'Transition' in bodyStyle)); |
||
animations = !!(('animation' in bodyStyle) || (vendorPrefix + 'Animation' in bodyStyle)); |
||
|
||
if (android && (!transitions||!animations)) { |
||
transitions = isString(document.body.style.webkitTransition); |
||
animations = isString(document.body.style.webkitAnimation); |
||
} |
||
} |
||
|
||
|
||
return { |
||
// Android has history.pushState, but it does not update location correctly |
||
// so let's not use the history API at all. |
||
// http://code.google.com/p/android/issues/detail?id=17471 |
||
// https://github.com/angular/angular.js/issues/904 |
||
|
||
// older webkit browser (533.9) on Boxee box has exactly the same problem as Android has |
||
// so let's not use the history API also |
||
// We are purposefully using `!(android < 4)` to cover the case when `android` is undefined |
||
// jshint -W018 |
||
history: !!($window.history && $window.history.pushState && !(android < 4) && !boxee), |
||
// jshint +W018 |
||
hashchange: 'onhashchange' in $window && |
||
// IE8 compatible mode lies |
||
(!documentMode || documentMode > 7), |
||
hasEvent: function(event) { |
||
// IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have |
||
// it. In particular the event is not fired when backspace or delete key are pressed or |
||
// when cut operation is performed. |
||
if (event == 'input' && msie == 9) return false; |
||
|
||
if (isUndefined(eventSupport[event])) { |
||
var divElm = document.createElement('div'); |
||
eventSupport[event] = 'on' + event in divElm; |
||
} |
||
|
||
return eventSupport[event]; |
||
}, |
||
csp: csp(), |
||
vendorPrefix: vendorPrefix, |
||
transitions : transitions, |
||
animations : animations, |
||
android: android, |
||
msie : msie, |
||
msieDocumentMode: documentMode |
||
}; |
||
}]; |
||
} |
||
|
||
function $TimeoutProvider() { |
||
this.$get = ['$rootScope', '$browser', '$q', '$exceptionHandler', |
||
function($rootScope, $browser, $q, $exceptionHandler) { |
||
var deferreds = {}; |
||
|
||
|
||
/** |
||
* @ngdoc function |
||
* @name ng.$timeout |
||
* @requires $browser |
||
* |
||
* @description |
||
* Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch |
||
* block and delegates any exceptions to |
||
* {@link ng.$exceptionHandler $exceptionHandler} service. |
||
* |
||
* The return value of registering a timeout function is a promise, which will be resolved when |
||
* the timeout is reached and the timeout function is executed. |
||
* |
||
* To cancel a timeout request, call `$timeout.cancel(promise)`. |
||
* |
||
* In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to |
||
* synchronously flush the queue of deferred functions. |
||
* |
||
* @param {function()} fn A function, whose execution should be delayed. |
||
* @param {number=} [delay=0] Delay in milliseconds. |
||
* @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise |
||
* will invoke `fn` within the {@link ng.$rootScope.Scope#methods_$apply $apply} block. |
||
* @returns {Promise} Promise that will be resolved when the timeout is reached. The value this |
||
* promise will be resolved with is the return value of the `fn` function. |
||
* |
||
*/ |
||
function timeout(fn, delay, invokeApply) { |
||
var deferred = $q.defer(), |
||
promise = deferred.promise, |
||
skipApply = (isDefined(invokeApply) && !invokeApply), |
||
timeoutId; |
||
|
||
timeoutId = $browser.defer(function() { |
||
try { |
||
deferred.resolve(fn()); |
||
} catch(e) { |
||
deferred.reject(e); |
||
$exceptionHandler(e); |
||
} |
||
finally { |
||
delete deferreds[promise.$$timeoutId]; |
||
} |
||
|
||
if (!skipApply) $rootScope.$apply(); |
||
}, delay); |
||
|
||
promise.$$timeoutId = timeoutId; |
||
deferreds[timeoutId] = deferred; |
||
|
||
return promise; |
||
} |
||
|
||
|
||
/** |
||
* @ngdoc function |
||
* @name ng.$timeout#cancel |
||
* @methodOf ng.$timeout |
||
* |
||
* @description |
||
* Cancels a task associated with the `promise`. As a result of this, the promise will be |
||
* resolved with a rejection. |
||
* |
||
* @param {Promise=} promise Promise returned by the `$timeout` function. |
||
* @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully |
||
* canceled. |
||
*/ |
||
timeout.cancel = function(promise) { |
||
if (promise && promise.$$timeoutId in deferreds) { |
||
deferreds[promise.$$timeoutId].reject('canceled'); |
||
delete deferreds[promise.$$timeoutId]; |
||
return $browser.defer.cancel(promise.$$timeoutId); |
||
} |
||
return false; |
||
}; |
||
|
||
return timeout; |
||
}]; |
||
} |
||
|
||
// NOTE: The usage of window and document instead of $window and $document here is |
||
// deliberate. This service depends on the specific behavior of anchor nodes created by the |
||
// browser (resolving and parsing URLs) that is unlikely to be provided by mock objects and |
||
// cause us to break tests. In addition, when the browser resolves a URL for XHR, it |
||
// doesn't know about mocked locations and resolves URLs to the real document - which is |
||
// exactly the behavior needed here. There is little value is mocking these out for this |
||
// service. |
||
var urlParsingNode = document.createElement("a"); |
||
var originUrl = urlResolve(window.location.href, true); |
||
|
||
|
||
/** |
||
* |
||
* Implementation Notes for non-IE browsers |
||
* ---------------------------------------- |
||
* Assigning a URL to the href property of an anchor DOM node, even one attached to the DOM, |
||
* results both in the normalizing and parsing of the URL. Normalizing means that a relative |
||
* URL will be resolved into an absolute URL in the context of the application document. |
||
* Parsing means that the anchor node's host, hostname, protocol, port, pathname and related |
||
* properties are all populated to reflect the normalized URL. This approach has wide |
||
* compatibility - Safari 1+, Mozilla 1+, Opera 7+,e etc. See |
||
* http://www.aptana.com/reference/html/api/HTMLAnchorElement.html |
||
* |
||
* Implementation Notes for IE |
||
* --------------------------- |
||
* IE >= 8 and <= 10 normalizes the URL when assigned to the anchor node similar to the other |
||
* browsers. However, the parsed components will not be set if the URL assigned did not specify |
||
* them. (e.g. if you assign a.href = "foo", then a.protocol, a.host, etc. will be empty.) We |
||
* work around that by performing the parsing in a 2nd step by taking a previously normalized |
||
* URL (e.g. by assigning to a.href) and assigning it a.href again. This correctly populates the |
||
* properties such as protocol, hostname, port, etc. |
||
* |
||
* IE7 does not normalize the URL when assigned to an anchor node. (Apparently, it does, if one |
||
* uses the inner HTML approach to assign the URL as part of an HTML snippet - |
||
* http://stackoverflow.com/a/472729) However, setting img[src] does normalize the URL. |
||
* Unfortunately, setting img[src] to something like "javascript:foo" on IE throws an exception. |
||
* Since the primary usage for normalizing URLs is to sanitize such URLs, we can't use that |
||
* method and IE < 8 is unsupported. |
||
* |
||
* References: |
||
* http://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement |
||
* http://www.aptana.com/reference/html/api/HTMLAnchorElement.html |
||
* http://url.spec.whatwg.org/#urlutils |
||
* https://github.com/angular/angular.js/pull/2902 |
||
* http://james.padolsey.com/javascript/parsing-urls-with-the-dom/ |
||
* |
||
* @function |
||
* @param {string} url The URL to be parsed. |
||
* @description Normalizes and parses a URL. |
||
* @returns {object} Returns the normalized URL as a dictionary. |
||
* |
||
* | member name | Description | |
||
* |---------------|----------------| |
||
* | href | A normalized version of the provided URL if it was not an absolute URL | |
||
* | protocol | The protocol including the trailing colon | |
||
* | host | The host and port (if the port is non-default) of the normalizedUrl | |
||
* | search | The search params, minus the question mark | |
||
* | hash | The hash string, minus the hash symbol |
||
* | hostname | The hostname |
||
* | port | The port, without ":" |
||
* | pathname | The pathname, beginning with "/" |
||
* |
||
*/ |
||
function urlResolve(url, base) { |
||
var href = url; |
||
|
||
if (msie) { |
||
// Normalize before parse. Refer Implementation Notes on why this is |
||
// done in two steps on IE. |
||
urlParsingNode.setAttribute("href", href); |
||
href = urlParsingNode.href; |
||
} |
||
|
||
urlParsingNode.setAttribute('href', href); |
||
|
||
// urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils |
||
return { |
||
href: urlParsingNode.href, |
||
protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '', |
||
host: urlParsingNode.host, |
||
search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '', |
||
hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '', |
||
hostname: urlParsingNode.hostname, |
||
port: urlParsingNode.port, |
||
pathname: (urlParsingNode.pathname.charAt(0) === '/') |
||
? urlParsingNode.pathname |
||
: '/' + urlParsingNode.pathname |
||
}; |
||
} |
||
|
||
/** |
||
* Parse a request URL and determine whether this is a same-origin request as the application document. |
||
* |
||
* @param {string|object} requestUrl The url of the request as a string that will be resolved |
||
* or a parsed URL object. |
||
* @returns {boolean} Whether the request is for the same origin as the application document. |
||
*/ |
||
function urlIsSameOrigin(requestUrl) { |
||
var parsed = (isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl; |
||
return (parsed.protocol === originUrl.protocol && |
||
parsed.host === originUrl.host); |
||
} |
||
|
||
/** |
||
* @ngdoc object |
||
* @name ng.$window |
||
* |
||
* @description |
||
* A reference to the browser's `window` object. While `window` |
||
* is globally available in JavaScript, it causes testability problems, because |
||
* it is a global variable. In angular we always refer to it through the |
||
* `$window` service, so it may be overridden, removed or mocked for testing. |
||
* |
||
* Expressions, like the one defined for the `ngClick` directive in the example |
||
* below, are evaluated with respect to the current scope. Therefore, there is |
||
* no risk of inadvertently coding in a dependency on a global value in such an |
||
* expression. |
||
* |
||
* @example |
||
<doc:example> |
||
<doc:source> |
||
<script> |
||
function Ctrl($scope, $window) { |
||
$scope.greeting = 'Hello, World!'; |
||
$scope.doGreeting = function(greeting) { |
||
$window.alert(greeting); |
||
}; |
||
} |
||
</script> |
||
<div ng-controller="Ctrl"> |
||
<input type="text" ng-model="greeting" /> |
||
<button ng-click="doGreeting(greeting)">ALERT</button> |
||
</div> |
||
</doc:source> |
||
<doc:scenario> |
||
it('should display the greeting in the input box', function() { |
||
input('greeting').enter('Hello, E2E Tests'); |
||
// If we click the button it will block the test runner |
||
// element(':button').click(); |
||
}); |
||
</doc:scenario> |
||
</doc:example> |
||
*/ |
||
function $WindowProvider(){ |
||
this.$get = valueFn(window); |
||
} |
||
|
||
/** |
||
* @ngdoc object |
||
* @name ng.$filterProvider |
||
* @description |
||
* |
||
* Filters are just functions which transform input to an output. However filters need to be |
||
* Dependency Injected. To achieve this a filter definition consists of a factory function which is |
||
* annotated with dependencies and is responsible for creating a filter function. |
||
* |
||
* <pre> |
||
* // Filter registration |
||
* function MyModule($provide, $filterProvider) { |
||
* // create a service to demonstrate injection (not always needed) |
||
* $provide.value('greet', function(name){ |
||
* return 'Hello ' + name + '!'; |
||
* }); |
||
* |
||
* // register a filter factory which uses the |
||
* // greet service to demonstrate DI. |
||
* $filterProvider.register('greet', function(greet){ |
||
* // return the filter function which uses the greet service |
||
* // to generate salutation |
||
* return function(text) { |
||
* // filters need to be forgiving so check input validity |
||
* return text && greet(text) || text; |
||
* }; |
||
* }); |
||
* } |
||
* </pre> |
||
* |
||
* The filter function is registered with the `$injector` under the filter name suffix with |
||
* `Filter`. |
||
* |
||
* <pre> |
||
* it('should be the same instance', inject( |
||
* function($filterProvider) { |
||
* $filterProvider.register('reverse', function(){ |
||
* return ...; |
||
* }); |
||
* }, |
||
* function($filter, reverseFilter) { |
||
* expect($filter('reverse')).toBe(reverseFilter); |
||
* }); |
||
* </pre> |
||
* |
||
* |
||
* For more information about how angular filters work, and how to create your own filters, see |
||
* {@link guide/filter Filters} in the Angular Developer Guide. |
||
*/ |
||
/** |
||
* @ngdoc method |
||
* @name ng.$filterProvider#register |
||
* @methodOf ng.$filterProvider |
||
* @description |
||
* Register filter factory function. |
||
* |
||
* @param {String} name Name of the filter. |
||
* @param {function} fn The filter factory function which is injectable. |
||
*/ |
||
|
||
|
||
/** |
||
* @ngdoc function |
||
* @name ng.$filter |
||
* @function |
||
* @description |
||
* Filters are used for formatting data displayed to the user. |
||
* |
||
* The general syntax in templates is as follows: |
||
* |
||
* {{ expression [| filter_name[:parameter_value] ... ] }} |
||
* |
||
* @param {String} name Name of the filter function to retrieve |
||
* @return {Function} the filter function |
||
*/ |
||
$FilterProvider.$inject = ['$provide']; |
||
function $FilterProvider($provide) { |
||
var suffix = 'Filter'; |
||
|
||
/** |
||
* @ngdoc function |
||
* @name ng.$controllerProvider#register |
||
* @methodOf ng.$controllerProvider |
||
* @param {string|Object} name Name of the filter function, or an object map of filters where |
||
* the keys are the filter names and the values are the filter factories. |
||
* @returns {Object} Registered filter instance, or if a map of filters was provided then a map |
||
* of the registered filter instances. |
||
*/ |
||
function register(name, factory) { |
||
if(isObject(name)) { |
||
var filters = {}; |
||
forEach(name, function(filter, key) { |
||
filters[key] = register(key, filter); |
||
}); |
||
return filters; |
||
} else { |
||
return $provide.factory(name + suffix, factory); |
||
} |
||
} |
||
this.register = register; |
||
|
||
this.$get = ['$injector', function($injector) { |
||
return function(name) { |
||
return $injector.get(name + suffix); |
||
}; |
||
}]; |
||
|
||
//////////////////////////////////////// |
||
|
||
/* global |
||
currencyFilter: false, |
||
dateFilter: false, |
||
filterFilter: false, |
||
jsonFilter: false, |
||
limitToFilter: false, |
||
lowercaseFilter: false, |
||
numberFilter: false, |
||
orderByFilter: false, |
||
uppercaseFilter: false, |
||
*/ |
||
|
||
register('currency', currencyFilter); |
||
register('date', dateFilter); |
||
register('filter', filterFilter); |
||
register('json', jsonFilter); |
||
register('limitTo', limitToFilter); |
||
register('lowercase', lowercaseFilter); |
||
register('number', numberFilter); |
||
register('orderBy', orderByFilter); |
||
register('uppercase', uppercaseFilter); |
||
} |
||
|
||
/** |
||
* @ngdoc filter |
||
* @name ng.filter:filter |
||
* @function |
||
* |
||
* @description |
||
* Selects a subset of items from `array` and returns it as a new array. |
||
* |
||
* @param {Array} array The source array. |
||
* @param {string|Object|function()} expression The predicate to be used for selecting items from |
||
* `array`. |
||
* |
||
* Can be one of: |
||
* |
||
* - `string`: The string is evaluated as an expression and the resulting value is used for substring match against |
||
* the contents of the `array`. All strings or objects with string properties in `array` that contain this string |
||
* will be returned. The predicate can be negated by prefixing the string with `!`. |
||
* |
||
* - `Object`: A pattern object can be used to filter specific properties on objects contained |
||
* by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items |
||
* which have property `name` containing "M" and property `phone` containing "1". A special |
||
* property name `$` can be used (as in `{$:"text"}`) to accept a match against any |
||
* property of the object. That's equivalent to the simple substring match with a `string` |
||
* as described above. |
||
* |
||
* - `function(value)`: A predicate function can be used to write arbitrary filters. The function is |
||
* called for each element of `array`. The final result is an array of those elements that |
||
* the predicate returned true for. |
||
* |
||
* @param {function(actual, expected)|true|undefined} comparator Comparator which is used in |
||
* determining if the expected value (from the filter expression) and actual value (from |
||
* the object in the array) should be considered a match. |
||
* |
||
* Can be one of: |
||
* |
||
* - `function(actual, expected)`: |
||
* The function will be given the object value and the predicate value to compare and |
||
* should return true if the item should be included in filtered result. |
||
* |
||
* - `true`: A shorthand for `function(actual, expected) { return angular.equals(expected, actual)}`. |
||
* this is essentially strict comparison of expected and actual. |
||
* |
||
* - `false|undefined`: A short hand for a function which will look for a substring match in case |
||
* insensitive way. |
||
* |
||
* @example |
||
<doc:example> |
||
<doc:source> |
||
<div ng-init="friends = [{name:'John', phone:'555-1276'}, |
||
{name:'Mary', phone:'800-BIG-MARY'}, |
||
{name:'Mike', phone:'555-4321'}, |
||
{name:'Adam', phone:'555-5678'}, |
||
{name:'Julie', phone:'555-8765'}, |
||
{name:'Juliette', phone:'555-5678'}]"></div> |
||
|
||
Search: <input ng-model="searchText"> |
||
<table id="searchTextResults"> |
||
<tr><th>Name</th><th>Phone</th></tr> |
||
<tr ng-repeat="friend in friends | filter:searchText"> |
||
<td>{{friend.name}}</td> |
||
<td>{{friend.phone}}</td> |
||
</tr> |
||
</table> |
||
<hr> |
||
Any: <input ng-model="search.$"> <br> |
||
Name only <input ng-model="search.name"><br> |
||
Phone only <input ng-model="search.phone"><br> |
||
Equality <input type="checkbox" ng-model="strict"><br> |
||
<table id="searchObjResults"> |
||
<tr><th>Name</th><th>Phone</th></tr> |
||
<tr ng-repeat="friend in friends | filter:search:strict"> |
||
<td>{{friend.name}}</td> |
||
<td>{{friend.phone}}</td> |
||
</tr> |
||
</table> |
||
</doc:source> |
||
<doc:scenario> |
||
it('should search across all fields when filtering with a string', function() { |
||
input('searchText').enter('m'); |
||
expect(repeater('#searchTextResults tr', 'friend in friends').column('friend.name')). |
||
toEqual(['Mary', 'Mike', 'Adam']); |
||
|
||
input('searchText').enter('76'); |
||
expect(repeater('#searchTextResults tr', 'friend in friends').column('friend.name')). |
||
toEqual(['John', 'Julie']); |
||
}); |
||
|
||
it('should search in specific fields when filtering with a predicate object', function() { |
||
input('search.$').enter('i'); |
||
expect(repeater('#searchObjResults tr', 'friend in friends').column('friend.name')). |
||
toEqual(['Mary', 'Mike', 'Julie', 'Juliette']); |
||
}); |
||
it('should use a equal comparison when comparator is true', function() { |
||
input('search.name').enter('Julie'); |
||
input('strict').check(); |
||
expect(repeater('#searchObjResults tr', 'friend in friends').column('friend.name')). |
||
toEqual(['Julie']); |
||
}); |
||
</doc:scenario> |
||
</doc:example> |
||
*/ |
||
function filterFilter() { |
||
return function(array, expression, comparator) { |
||
if (!isArray(array)) return array; |
||
|
||
var comparatorType = typeof(comparator), |
||
predicates = []; |
||
|
||
predicates.check = function(value) { |
||
for (var j = 0; j < predicates.length; j++) { |
||
if(!predicates[j](value)) { |
||
return false; |
||
} |
||
} |
||
return true; |
||
}; |
||
|
||
if (comparatorType !== 'function') { |
||
if (comparatorType === 'boolean' && comparator) { |
||
comparator = function(obj, text) { |
||
return angular.equals(obj, text); |
||
}; |
||
} else { |
||
comparator = function(obj, text) { |
||
text = (''+text).toLowerCase(); |
||
return (''+obj).toLowerCase().indexOf(text) > -1; |
||
}; |
||
} |
||
} |
||
|
||
var search = function(obj, text){ |
||
if (typeof text == 'string' && text.charAt(0) === '!') { |
||
return !search(obj, text.substr(1)); |
||
} |
||
switch (typeof obj) { |
||
case "boolean": |
||
case "number": |
||
case "string": |
||
return comparator(obj, text); |
||
case "object": |
||
switch (typeof text) { |
||
case "object": |
||
return comparator(obj, text); |
||
default: |
||
for ( var objKey in obj) { |
||
if (objKey.charAt(0) !== '$' && search(obj[objKey], text)) { |
||
return true; |
||
} |
||
} |
||
break; |
||
} |
||
return false; |
||
case "array": |
||
for ( var i = 0; i < obj.length; i++) { |
||
if (search(obj[i], text)) { |
||
return true; |
||
} |
||
} |
||
return false; |
||
default: |
||
return false; |
||
} |
||
}; |
||
switch (typeof expression) { |
||
case "boolean": |
||
case "number": |
||
case "string": |
||
// Set up expression object and fall through |
||
expression = {$:expression}; |
||
// jshint -W086 |
||
case "object": |
||
// jshint +W086 |
||
for (var key in expression) { |
||
(function(path) { |
||
if (typeof expression[path] == 'undefined') return; |
||
predicates.push(function(value) { |
||
return search(path == '$' ? value : getter(value, path), expression[path]); |
||
}); |
||
})(key); |
||
} |
||
break; |
||
case 'function': |
||
predicates.push(expression); |
||
break; |
||
default: |
||
return array; |
||
} |
||
var filtered = []; |
||
for ( var j = 0; j < array.length; j++) { |
||
var value = array[j]; |
||
if (predicates.check(value)) { |
||
filtered.push(value); |
||
} |
||
} |
||
return filtered; |
||
}; |
||
} |
||
|
||
/** |
||
* @ngdoc filter |
||
* @name ng.filter:currency |
||
* @function |
||
* |
||
* @description |
||
* Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default |
||
* symbol for current locale is used. |
||
* |
||
* @param {number} amount Input to filter. |
||
* @param {string=} symbol Currency symbol or identifier to be displayed. |
||
* @returns {string} Formatted number. |
||
* |
||
* |
||
* @example |
||
<doc:example> |
||
<doc:source> |
||
<script> |
||
function Ctrl($scope) { |
||
$scope.amount = 1234.56; |
||
} |
||
</script> |
||
<div ng-controller="Ctrl"> |
||
<input type="number" ng-model="amount"> <br> |
||
default currency symbol ($): {{amount | currency}}<br> |
||
custom currency identifier (USD$): {{amount | currency:"USD$"}} |
||
</div> |
||
</doc:source> |
||
<doc:scenario> |
||
it('should init with 1234.56', function() { |
||
expect(binding('amount | currency')).toBe('$1,234.56'); |
||
expect(binding('amount | currency:"USD$"')).toBe('USD$1,234.56'); |
||
}); |
||
it('should update', function() { |
||
input('amount').enter('-1234'); |
||
expect(binding('amount | currency')).toBe('($1,234.00)'); |
||
expect(binding('amount | currency:"USD$"')).toBe('(USD$1,234.00)'); |
||
}); |
||
</doc:scenario> |
||
</doc:example> |
||
*/ |
||
currencyFilter.$inject = ['$locale']; |
||
function currencyFilter($locale) { |
||
var formats = $locale.NUMBER_FORMATS; |
||
return function(amount, currencySymbol){ |
||
if (isUndefined(currencySymbol)) currencySymbol = formats.CURRENCY_SYM; |
||
return formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, 2). |
||
replace(/\u00A4/g, currencySymbol); |
||
}; |
||
} |
||
|
||
/** |
||
* @ngdoc filter |
||
* @name ng.filter:number |
||
* @function |
||
* |
||
* @description |
||
* Formats a number as text. |
||
* |
||
* If the input is not a number an empty string is returned. |
||
* |
||
* @param {number|string} number Number to format. |
||
* @param {(number|string)=} fractionSize Number of decimal places to round the number to. |
||
* If this is not provided then the fraction size is computed from the current locale's number |
||
* formatting pattern. In the case of the default locale, it will be 3. |
||
* @returns {string} Number rounded to decimalPlaces and places a “,” after each third digit. |
||
* |
||
* @example |
||
<doc:example> |
||
<doc:source> |
||
<script> |
||
function Ctrl($scope) { |
||
$scope.val = 1234.56789; |
||
} |
||
</script> |
||
<div ng-controller="Ctrl"> |
||
Enter number: <input ng-model='val'><br> |
||
Default formatting: {{val | number}}<br> |
||
No fractions: {{val | number:0}}<br> |
||
Negative number: {{-val | number:4}} |
||
</div> |
||
</doc:source> |
||
<doc:scenario> |
||
it('should format numbers', function() { |
||
expect(binding('val | number')).toBe('1,234.568'); |
||
expect(binding('val | number:0')).toBe('1,235'); |
||
expect(binding('-val | number:4')).toBe('-1,234.5679'); |
||
}); |
||
|
||
it('should update', function() { |
||
input('val').enter('3374.333'); |
||
expect(binding('val | number')).toBe('3,374.333'); |
||
expect(binding('val | number:0')).toBe('3,374'); |
||
expect(binding('-val | number:4')).toBe('-3,374.3330'); |
||
}); |
||
</doc:scenario> |
||
</doc:example> |
||
*/ |
||
|
||
|
||
numberFilter.$inject = ['$locale']; |
||
function numberFilter($locale) { |
||
var formats = $locale.NUMBER_FORMATS; |
||
return function(number, fractionSize) { |
||
return formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP, |
||
fractionSize); |
||
}; |
||
} |
||
|
||
var DECIMAL_SEP = '.'; |
||
function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) { |
||
if (isNaN(number) || !isFinite(number)) return ''; |
||
|
||
var isNegative = number < 0; |
||
number = Math.abs(number); |
||
var numStr = number + '', |
||
formatedText = '', |
||
parts = []; |
||
|
||
var hasExponent = false; |
||
if (numStr.indexOf('e') !== -1) { |
||
var match = numStr.match(/([\d\.]+)e(-?)(\d+)/); |
||
if (match && match[2] == '-' && match[3] > fractionSize + 1) { |
||
numStr = '0'; |
||
} else { |
||
formatedText = numStr; |
||
hasExponent = true; |
||
} |
||
} |
||
|
||
if (!hasExponent) { |
||
var fractionLen = (numStr.split(DECIMAL_SEP)[1] || '').length; |
||
|
||
// determine fractionSize if it is not specified |
||
if (isUndefined(fractionSize)) { |
||
fractionSize = Math.min(Math.max(pattern.minFrac, fractionLen), pattern.maxFrac); |
||
} |
||
|
||
var pow = Math.pow(10, fractionSize); |
||
number = Math.round(number * pow) / pow; |
||
var fraction = ('' + number).split(DECIMAL_SEP); |
||
var whole = fraction[0]; |
||
fraction = fraction[1] || ''; |
||
|
||
var i, pos = 0, |
||
lgroup = pattern.lgSize, |
||
group = pattern.gSize; |
||
|
||
if (whole.length >= (lgroup + group)) { |
||
pos = whole.length - lgroup; |
||
for (i = 0; i < pos; i++) { |
||
if ((pos - i)%group === 0 && i !== 0) { |
||
formatedText += groupSep; |
||
} |
||
formatedText += whole.charAt(i); |
||
} |
||
} |
||
|
||
for (i = pos; i < whole.length; i++) { |
||
if ((whole.length - i)%lgroup === 0 && i !== 0) { |
||
formatedText += groupSep; |
||
} |
||
formatedText += whole.charAt(i); |
||
} |
||
|
||
// format fraction part. |
||
while(fraction.length < fractionSize) { |
||
fraction += '0'; |
||
} |
||
|
||
if (fractionSize && fractionSize !== "0") formatedText += decimalSep + fraction.substr(0, fractionSize); |
||
} else { |
||
|
||
if (fractionSize > 0 && number > -1 && number < 1) { |
||
formatedText = number.toFixed(fractionSize); |
||
} |
||
} |
||
|
||
parts.push(isNegative ? pattern.negPre : pattern.posPre); |
||
parts.push(formatedText); |
||
parts.push(isNegative ? pattern.negSuf : pattern.posSuf); |
||
return parts.join(''); |
||
} |
||
|
||
function padNumber(num, digits, trim) { |
||
var neg = ''; |
||
if (num < 0) { |
||
neg = '-'; |
||
num = -num; |
||
} |
||
num = '' + num; |
||
while(num.length < digits) num = '0' + num; |
||
if (trim) |
||
num = num.substr(num.length - digits); |
||
return neg + num; |
||
} |
||
|
||
|
||
function dateGetter(name, size, offset, trim) { |
||
offset = offset || 0; |
||
return function(date) { |
||
var value = date['get' + name](); |
||
if (offset > 0 || value > -offset) |
||
value += offset; |
||
if (value === 0 && offset == -12 ) value = 12; |
||
return padNumber(value, size, trim); |
||
}; |
||
} |
||
|
||
function dateStrGetter(name, shortForm) { |
||
return function(date, formats) { |
||
var value = date['get' + name](); |
||
var get = uppercase(shortForm ? ('SHORT' + name) : name); |
||
|
||
return formats[get][value]; |
||
}; |
||
} |
||
|
||
function timeZoneGetter(date) { |
||
var zone = -1 * date.getTimezoneOffset(); |
||
var paddedZone = (zone >= 0) ? "+" : ""; |
||
|
||
paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) + |
||
padNumber(Math.abs(zone % 60), 2); |
||
|
||
return paddedZone; |
||
} |
||
|
||
function ampmGetter(date, formats) { |
||
return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1]; |
||
} |
||
|
||
var DATE_FORMATS = { |
||
yyyy: dateGetter('FullYear', 4), |
||
yy: dateGetter('FullYear', 2, 0, true), |
||
y: dateGetter('FullYear', 1), |
||
MMMM: dateStrGetter('Month'), |
||
MMM: dateStrGetter('Month', true), |
||
MM: dateGetter('Month', 2, 1), |
||
M: dateGetter('Month', 1, 1), |
||
dd: dateGetter('Date', 2), |
||
d: dateGetter('Date', 1), |
||
HH: dateGetter('Hours', 2), |
||
H: dateGetter('Hours', 1), |
||
hh: dateGetter('Hours', 2, -12), |
||
h: dateGetter('Hours', 1, -12), |
||
mm: dateGetter('Minutes', 2), |
||
m: dateGetter('Minutes', 1), |
||
ss: dateGetter('Seconds', 2), |
||
s: dateGetter('Seconds', 1), |
||
// while ISO 8601 requires fractions to be prefixed with `.` or `,` |
||
// we can be just safely rely on using `sss` since we currently don't support single or two digit fractions |
||
sss: dateGetter('Milliseconds', 3), |
||
EEEE: dateStrGetter('Day'), |
||
EEE: dateStrGetter('Day', true), |
||
a: ampmGetter, |
||
Z: timeZoneGetter |
||
}; |
||
|
||
var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZE']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z))(.*)/, |
||
NUMBER_STRING = /^\-?\d+$/; |
||
|
||
/** |
||
* @ngdoc filter |
||
* @name ng.filter:date |
||
* @function |
||
* |
||
* @description |
||
* Formats `date` to a string based on the requested `format`. |
||
* |
||
* `format` string can be composed of the following elements: |
||
* |
||
* * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010) |
||
* * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10) |
||
* * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199) |
||
* * `'MMMM'`: Month in year (January-December) |
||
* * `'MMM'`: Month in year (Jan-Dec) |
||
* * `'MM'`: Month in year, padded (01-12) |
||
* * `'M'`: Month in year (1-12) |
||
* * `'dd'`: Day in month, padded (01-31) |
||
* * `'d'`: Day in month (1-31) |
||
* * `'EEEE'`: Day in Week,(Sunday-Saturday) |
||
* * `'EEE'`: Day in Week, (Sun-Sat) |
||
* * `'HH'`: Hour in day, padded (00-23) |
||
* * `'H'`: Hour in day (0-23) |
||
* * `'hh'`: Hour in am/pm, padded (01-12) |
||
* * `'h'`: Hour in am/pm, (1-12) |
||
* * `'mm'`: Minute in hour, padded (00-59) |
||
* * `'m'`: Minute in hour (0-59) |
||
* * `'ss'`: Second in minute, padded (00-59) |
||
* * `'s'`: Second in minute (0-59) |
||
* * `'.sss' or ',sss'`: Millisecond in second, padded (000-999) |
||
* * `'a'`: am/pm marker |
||
* * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200) |
||
* |
||
* `format` string can also be one of the following predefined |
||
* {@link guide/i18n localizable formats}: |
||
* |
||
* * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale |
||
* (e.g. Sep 3, 2010 12:05:08 pm) |
||
* * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 pm) |
||
* * `'fullDate'`: equivalent to `'EEEE, MMMM d,y'` for en_US locale |
||
* (e.g. Friday, September 3, 2010) |
||
* * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010) |
||
* * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010) |
||
* * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10) |
||
* * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 pm) |
||
* * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 pm) |
||
* |
||
* `format` string can contain literal values. These need to be quoted with single quotes (e.g. |
||
* `"h 'in the morning'"`). In order to output single quote, use two single quotes in a sequence |
||
* (e.g. `"h 'o''clock'"`). |
||
* |
||
* @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or |
||
* number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.SSSZ and its |
||
* shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is |
||
* specified in the string input, the time is considered to be in the local timezone. |
||
* @param {string=} format Formatting rules (see Description). If not specified, |
||
* `mediumDate` is used. |
||
* @returns {string} Formatted string or the input if input is not recognized as date/millis. |
||
* |
||
* @example |
||
<doc:example> |
||
<doc:source> |
||
<span ng-non-bindable>{{1288323623006 | date:'medium'}}</span>: |
||
{{1288323623006 | date:'medium'}}<br> |
||
<span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>: |
||
{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}<br> |
||
<span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>: |
||
{{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}<br> |
||
</doc:source> |
||
<doc:scenario> |
||
it('should format date', function() { |
||
expect(binding("1288323623006 | date:'medium'")). |
||
toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/); |
||
expect(binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")). |
||
toMatch(/2010\-10\-2\d \d{2}:\d{2}:\d{2} (\-|\+)?\d{4}/); |
||
expect(binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")). |
||
toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/); |
||
}); |
||
</doc:scenario> |
||
</doc:example> |
||
*/ |
||
dateFilter.$inject = ['$locale']; |
||
function dateFilter($locale) { |
||
|
||
|
||
var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/; |
||
// 1 2 3 4 5 6 7 8 9 10 11 |
||
function jsonStringToDate(string) { |
||
var match; |
||
if (match = string.match(R_ISO8601_STR)) { |
||
var date = new Date(0), |
||
tzHour = 0, |
||
tzMin = 0, |
||
dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear, |
||
timeSetter = match[8] ? date.setUTCHours : date.setHours; |
||
|
||
if (match[9]) { |
||
tzHour = int(match[9] + match[10]); |
||
tzMin = int(match[9] + match[11]); |
||
} |
||
dateSetter.call(date, int(match[1]), int(match[2]) - 1, int(match[3])); |
||
var h = int(match[4]||0) - tzHour; |
||
var m = int(match[5]||0) - tzMin; |
||
var s = int(match[6]||0); |
||
var ms = Math.round(parseFloat('0.' + (match[7]||0)) * 1000); |
||
timeSetter.call(date, h, m, s, ms); |
||
return date; |
||
} |
||
return string; |
||
} |
||
|
||
|
||
return function(date, format) { |
||
var text = '', |
||
parts = [], |
||
fn, match; |
||
|
||
format = format || 'mediumDate'; |
||
format = $locale.DATETIME_FORMATS[format] || format; |
||
if (isString(date)) { |
||
if (NUMBER_STRING.test(date)) { |
||
date = int(date); |
||
} else { |
||
date = jsonStringToDate(date); |
||
} |
||
} |
||
|
||
if (isNumber(date)) { |
||
date = new Date(date); |
||
} |
||
|
||
if (!isDate(date)) { |
||
return date; |
||
} |
||
|
||
while(format) { |
||
match = DATE_FORMATS_SPLIT.exec(format); |
||
if (match) { |
||
parts = concat(parts, match, 1); |
||
format = parts.pop(); |
||
} else { |
||
parts.push(format); |
||
format = null; |
||
} |
||
} |
||
|
||
forEach(parts, function(value){ |
||
fn = DATE_FORMATS[value]; |
||
text += fn ? fn(date, $locale.DATETIME_FORMATS) |
||
: value.replace(/(^'|'$)/g, '').replace(/''/g, "'"); |
||
}); |
||
|
||
return text; |
||
}; |
||
} |
||
|
||
|
||
/** |
||
* @ngdoc filter |
||
* @name ng.filter:json |
||
* @function |
||
* |
||
* @description |
||
* Allows you to convert a JavaScript object into JSON string. |
||
* |
||
* This filter is mostly useful for debugging. When using the double curly {{value}} notation |
||
* the binding is automatically converted to JSON. |
||
* |
||
* @param {*} object Any JavaScript object (including arrays and primitive types) to filter. |
||
* @returns {string} JSON string. |
||
* |
||
* |
||
* @example: |
||
<doc:example> |
||
<doc:source> |
||
<pre>{{ {'name':'value'} | json }}</pre> |
||
</doc:source> |
||
<doc:scenario> |
||
it('should jsonify filtered objects', function() { |
||
expect(binding("{'name':'value'}")).toMatch(/\{\n "name": ?"value"\n}/); |
||
}); |
||
</doc:scenario> |
||
</doc:example> |
||
* |
||
*/ |
||
function jsonFilter() { |
||
return function(object) { |
||
return toJson(object, true); |
||
}; |
||
} |
||
|
||
|
||
/** |
||
* @ngdoc filter |
||
* @name ng.filter:lowercase |
||
* @function |
||
* @description |
||
* Converts string to lowercase. |
||
* @see angular.lowercase |
||
*/ |
||
var lowercaseFilter = valueFn(lowercase); |
||
|
||
|
||
/** |
||
* @ngdoc filter |
||
* @name ng.filter:uppercase |
||
* @function |
||
* @description |
||
* Converts string to uppercase. |
||
* @see angular.uppercase |
||
*/ |
||
var uppercaseFilter = valueFn(uppercase); |
||
|
||
/** |
||
* @ngdoc function |
||
* @name ng.filter:limitTo |
||
* @function |
||
* |
||
* @description |
||
* Creates a new array or string containing only a specified number of elements. The elements |
||
* are taken from either the beginning or the end of the source array or string, as specified by |
||
* the value and sign (positive or negative) of `limit`. |
||
* |
||
* @param {Array|string} input Source array or string to be limited. |
||
* @param {string|number} limit The length of the returned array or string. If the `limit` number |
||
* is positive, `limit` number of items from the beginning of the source array/string are copied. |
||
* If the number is negative, `limit` number of items from the end of the source array/string |
||
* are copied. The `limit` will be trimmed if it exceeds `array.length` |
||
* @returns {Array|string} A new sub-array or substring of length `limit` or less if input array |
||
* had less than `limit` elements. |
||
* |
||
* @example |
||
<doc:example> |
||
<doc:source> |
||
<script> |
||
function Ctrl($scope) { |
||
$scope.numbers = [1,2,3,4,5,6,7,8,9]; |
||
$scope.letters = "abcdefghi"; |
||
$scope.numLimit = 3; |
||
$scope.letterLimit = 3; |
||
} |
||
</script> |
||
<div ng-controller="Ctrl"> |
||
Limit {{numbers}} to: <input type="integer" ng-model="numLimit"> |
||
<p>Output numbers: {{ numbers | limitTo:numLimit }}</p> |
||
Limit {{letters}} to: <input type="integer" ng-model="letterLimit"> |
||
<p>Output letters: {{ letters | limitTo:letterLimit }}</p> |
||
</div> |
||
</doc:source> |
||
<doc:scenario> |
||
it('should limit the number array to first three items', function() { |
||
expect(element('.doc-example-live input[ng-model=numLimit]').val()).toBe('3'); |
||
expect(element('.doc-example-live input[ng-model=letterLimit]').val()).toBe('3'); |
||
expect(binding('numbers | limitTo:numLimit')).toEqual('[1,2,3]'); |
||
expect(binding('letters | limitTo:letterLimit')).toEqual('abc'); |
||
}); |
||
|
||
it('should update the output when -3 is entered', function() { |
||
input('numLimit').enter(-3); |
||
input('letterLimit').enter(-3); |
||
expect(binding('numbers | limitTo:numLimit')).toEqual('[7,8,9]'); |
||
expect(binding('letters | limitTo:letterLimit')).toEqual('ghi'); |
||
}); |
||
|
||
it('should not exceed the maximum size of input array', function() { |
||
input('numLimit').enter(100); |
||
input('letterLimit').enter(100); |
||
expect(binding('numbers | limitTo:numLimit')).toEqual('[1,2,3,4,5,6,7,8,9]'); |
||
expect(binding('letters | limitTo:letterLimit')).toEqual('abcdefghi'); |
||
}); |
||
</doc:scenario> |
||
</doc:example> |
||
*/ |
||
function limitToFilter(){ |
||
return function(input, limit) { |
||
if (!isArray(input) && !isString(input)) return input; |
||
|
||
limit = int(limit); |
||
|
||
if (isString(input)) { |
||
//NaN check on limit |
||
if (limit) { |
||
return limit >= 0 ? input.slice(0, limit) : input.slice(limit, input.length); |
||
} else { |
||
return ""; |
||
} |
||
} |
||
|
||
var out = [], |
||
i, n; |
||
|
||
// if abs(limit) exceeds maximum length, trim it |
||
if (limit > input.length) |
||
limit = input.length; |
||
else if (limit < -input.length) |
||
limit = -input.length; |
||
|
||
if (limit > 0) { |
||
i = 0; |
||
n = limit; |
||
} else { |
||
i = input.length + limit; |
||
n = input.length; |
||
} |
||
|
||
for (; i<n; i++) { |
||
out.push(input[i]); |
||
} |
||
|
||
return out; |
||
}; |
||
} |
||
|
||
/** |
||
* @ngdoc function |
||
* @name ng.filter:orderBy |
||
* @function |
||
* |
||
* @description |
||
* Orders a specified `array` by the `expression` predicate. |
||
* |
||
* @param {Array} array The array to sort. |
||
* @param {function(*)|string|Array.<(function(*)|string)>} expression A predicate to be |
||
* used by the comparator to determine the order of elements. |
||
* |
||
* Can be one of: |
||
* |
||
* - `function`: Getter function. The result of this function will be sorted using the |
||
* `<`, `=`, `>` operator. |
||
* - `string`: An Angular expression which evaluates to an object to order by, such as 'name' |
||
* to sort by a property called 'name'. Optionally prefixed with `+` or `-` to control |
||
* ascending or descending sort order (for example, +name or -name). |
||
* - `Array`: An array of function or string predicates. The first predicate in the array |
||
* is used for sorting, but when two items are equivalent, the next predicate is used. |
||
* |
||
* @param {boolean=} reverse Reverse the order the array. |
||
* @returns {Array} Sorted copy of the source array. |
||
* |
||
* @example |
||
<doc:example> |
||
<doc:source> |
||
<script> |
||
function Ctrl($scope) { |
||
$scope.friends = |
||
[{name:'John', phone:'555-1212', age:10}, |
||
{name:'Mary', phone:'555-9876', age:19}, |
||
{name:'Mike', phone:'555-4321', age:21}, |
||
{name:'Adam', phone:'555-5678', age:35}, |
||
{name:'Julie', phone:'555-8765', age:29}] |
||
$scope.predicate = '-age'; |
||
} |
||
</script> |
||
<div ng-controller="Ctrl"> |
||
<pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre> |
||
<hr/> |
||
[ <a href="" ng-click="predicate=''">unsorted</a> ] |
||
<table class="friend"> |
||
<tr> |
||
<th><a href="" ng-click="predicate = 'name'; reverse=false">Name</a> |
||
(<a href="" ng-click="predicate = '-name'; reverse=false">^</a>)</th> |
||
<th><a href="" ng-click="predicate = 'phone'; reverse=!reverse">Phone Number</a></th> |
||
<th><a href="" ng-click="predicate = 'age'; reverse=!reverse">Age</a></th> |
||
</tr> |
||
<tr ng-repeat="friend in friends | orderBy:predicate:reverse"> |
||
<td>{{friend.name}}</td> |
||
<td>{{friend.phone}}</td> |
||
<td>{{friend.age}}</td> |
||
</tr> |
||
</table> |
||
</div> |
||
</doc:source> |
||
<doc:scenario> |
||
it('should be reverse ordered by aged', function() { |
||
expect(binding('predicate')).toBe('-age'); |
||
expect(repeater('table.friend', 'friend in friends').column('friend.age')). |
||
toEqual(['35', '29', '21', '19', '10']); |
||
expect(repeater('table.friend', 'friend in friends').column('friend.name')). |
||
toEqual(['Adam', 'Julie', 'Mike', 'Mary', 'John']); |
||
}); |
||
|
||
it('should reorder the table when user selects different predicate', function() { |
||
element('.doc-example-live a:contains("Name")').click(); |
||
expect(repeater('table.friend', 'friend in friends').column('friend.name')). |
||
toEqual(['Adam', 'John', 'Julie', 'Mary', 'Mike']); |
||
expect(repeater('table.friend', 'friend in friends').column('friend.age')). |
||
toEqual(['35', '10', '29', '19', '21']); |
||
|
||
element('.doc-example-live a:contains("Phone")').click(); |
||
expect(repeater('table.friend', 'friend in friends').column('friend.phone')). |
||
toEqual(['555-9876', '555-8765', '555-5678', '555-4321', '555-1212']); |
||
expect(repeater('table.friend', 'friend in friends').column('friend.name')). |
||
toEqual(['Mary', 'Julie', 'Adam', 'Mike', 'John']); |
||
}); |
||
</doc:scenario> |
||
</doc:example> |
||
*/ |
||
orderByFilter.$inject = ['$parse']; |
||
function orderByFilter($parse){ |
||
return function(array, sortPredicate, reverseOrder) { |
||
if (!isArray(array)) return array; |
||
if (!sortPredicate) return array; |
||
sortPredicate = isArray(sortPredicate) ? sortPredicate: [sortPredicate]; |
||
sortPredicate = map(sortPredicate, function(predicate){ |
||
var descending = false, get = predicate || identity; |
||
if (isString(predicate)) { |
||
if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) { |
||
descending = predicate.charAt(0) == '-'; |
||
predicate = predicate.substring(1); |
||
} |
||
get = $parse(predicate); |
||
} |
||
return reverseComparator(function(a,b){ |
||
return compare(get(a),get(b)); |
||
}, descending); |
||
}); |
||
var arrayCopy = []; |
||
for ( var i = 0; i < array.length; i++) { arrayCopy.push(array[i]); } |
||
return arrayCopy.sort(reverseComparator(comparator, reverseOrder)); |
||
|
||
function comparator(o1, o2){ |
||
for ( var i = 0; i < sortPredicate.length; i++) { |
||
var comp = sortPredicate[i](o1, o2); |
||
if (comp !== 0) return comp; |
||
} |
||
return 0; |
||
} |
||
function reverseComparator(comp, descending) { |
||
return toBoolean(descending) |
||
? function(a,b){return comp(b,a);} |
||
: comp; |
||
} |
||
function compare(v1, v2){ |
||
var t1 = typeof v1; |
||
var t2 = typeof v2; |
||
if (t1 == t2) { |
||
if (t1 == "string") { |
||
v1 = v1.toLowerCase(); |
||
v2 = v2.toLowerCase(); |
||
} |
||
if (v1 === v2) return 0; |
||
return v1 < v2 ? -1 : 1; |
||
} else { |
||
return t1 < t2 ? -1 : 1; |
||
} |
||
} |
||
}; |
||
} |
||
|
||
function ngDirective(directive) { |
||
if (isFunction(directive)) { |
||
directive = { |
||
link: directive |
||
}; |
||
} |
||
directive.restrict = directive.restrict || 'AC'; |
||
return valueFn(directive); |
||
} |
||
|
||
/** |
||
* @ngdoc directive |
||
* @name ng.directive:a |
||
* @restrict E |
||
* |
||
* @description |
||
* Modifies the default behavior of the html A tag so that the default action is prevented when |
||
* the href attribute is empty. |
||
* |
||
* This change permits the easy creation of action links with the `ngClick` directive |
||
* without changing the location or causing page reloads, e.g.: |
||
* `<a href="" ng-click="list.addItem()">Add Item</a>` |
||
*/ |
||
var htmlAnchorDirective = valueFn({ |
||
restrict: 'E', |
||
compile: function(element, attr) { |
||
|
||
if (msie <= 8) { |
||
|
||
// turn <a href ng-click="..">link</a> into a stylable link in IE |
||
// but only if it doesn't have name attribute, in which case it's an anchor |
||
if (!attr.href && !attr.name) { |
||
attr.$set('href', ''); |
||
} |
||
|
||
// add a comment node to anchors to workaround IE bug that causes element content to be reset |
||
// to new attribute content if attribute is updated with value containing @ and element also |
||
// contains value with @ |
||
// see issue #1949 |
||
element.append(document.createComment('IE fix')); |
||
} |
||
|
||
if (!attr.href && !attr.name) { |
||
return function(scope, element) { |
||
element.on('click', function(event){ |
||
// if we have no href url, then don't navigate anywhere. |
||
if (!element.attr('href')) { |
||
event.preventDefault(); |
||
} |
||
}); |
||
}; |
||
} |
||
} |
||
}); |
||
|
||
/** |
||
* @ngdoc directive |
||
* @name ng.directive:ngHref |
||
* @restrict A |
||
* @priority 99 |
||
* |
||
* @description |
||
* Using Angular markup like `{{hash}}` in an href attribute will |
||
* make the link go to the wrong URL if the user clicks it before |
||
* Angular has a chance to replace the `{{hash}}` markup with its |
||
* value. Until Angular replaces the markup the link will be broken |
||
* and will most likely return a 404 error. |
||
* |
||
* The `ngHref` directive solves this problem. |
||
* |
||
* The wrong way to write it: |
||
* <pre> |
||
* <a href="http://www.gravatar.com/avatar/{{hash}}"/> |
||
* </pre> |
||
* |
||
* The correct way to write it: |
||
* <pre> |
||
* <a ng-href="http://www.gravatar.com/avatar/{{hash}}"/> |
||
* </pre> |
||
* |
||
* @element A |
||
* @param {template} ngHref any string which can contain `{{}}` markup. |
||
* |
||
* @example |
||
* This example shows various combinations of `href`, `ng-href` and `ng-click` attributes |
||
* in links and their different behaviors: |
||
<doc:example> |
||
<doc:source> |
||
<input ng-model="value" /><br /> |
||
<a id="link-1" href ng-click="value = 1">link 1</a> (link, don't reload)<br /> |
||
<a id="link-2" href="" ng-click="value = 2">link 2</a> (link, don't reload)<br /> |
||
<a id="link-3" ng-href="/{{'123'}}">link 3</a> (link, reload!)<br /> |
||
<a id="link-4" href="" name="xx" ng-click="value = 4">anchor</a> (link, don't reload)<br /> |
||
<a id="link-5" name="xxx" ng-click="value = 5">anchor</a> (no link)<br /> |
||
<a id="link-6" ng-href="{{value}}">link</a> (link, change location) |
||
</doc:source> |
||
<doc:scenario> |
||
it('should execute ng-click but not reload when href without value', function() { |
||
element('#link-1').click(); |
||
expect(input('value').val()).toEqual('1'); |
||
expect(element('#link-1').attr('href')).toBe(""); |
||
}); |
||
|
||
it('should execute ng-click but not reload when href empty string', function() { |
||
element('#link-2').click(); |
||
expect(input('value').val()).toEqual('2'); |
||
expect(element('#link-2').attr('href')).toBe(""); |
||
}); |
||
|
||
it('should execute ng-click and change url when ng-href specified', function() { |
||
expect(element('#link-3').attr('href')).toBe("/123"); |
||
|
||
element('#link-3').click(); |
||
expect(browser().window().path()).toEqual('/123'); |
||
}); |
||
|
||
it('should execute ng-click but not reload when href empty string and name specified', function() { |
||
element('#link-4').click(); |
||
expect(input('value').val()).toEqual('4'); |
||
expect(element('#link-4').attr('href')).toBe(''); |
||
}); |
||
|
||
it('should execute ng-click but not reload when no href but name specified', function() { |
||
element('#link-5').click(); |
||
expect(input('value').val()).toEqual('5'); |
||
expect(element('#link-5').attr('href')).toBe(undefined); |
||
}); |
||
|
||
it('should only change url when only ng-href', function() { |
||
input('value').enter('6'); |
||
expect(element('#link-6').attr('href')).toBe('6'); |
||
|
||
element('#link-6').click(); |
||
expect(browser().location().url()).toEqual('/6'); |
||
}); |
||
</doc:scenario> |
||
</doc:example> |
||
*/ |
||
|
||
/** |
||
* @ngdoc directive |
||
* @name ng.directive:ngSrc |
||
* @restrict A |
||
* @priority 99 |
||
* |
||
* @description |
||
* Using Angular markup like `{{hash}}` in a `src` attribute doesn't |
||
* work right: The browser will fetch from the URL with the literal |
||
* text `{{hash}}` until Angular replaces the expression inside |
||
* `{{hash}}`. The `ngSrc` directive solves this problem. |
||
* |
||
* The buggy way to write it: |
||
* <pre> |
||
* <img src="http://www.gravatar.com/avatar/{{hash}}"/> |
||
* </pre> |
||
* |
||
* The correct way to write it: |
||
* <pre> |
||
* <img ng-src="http://www.gravatar.com/avatar/{{hash}}"/> |
||
* </pre> |
||
* |
||
* @element IMG |
||
* @param {template} ngSrc any string which can contain `{{}}` markup. |
||
*/ |
||
|
||
/** |
||
* @ngdoc directive |
||
* @name ng.directive:ngSrcset |
||
* @restrict A |
||
* @priority 99 |
||
* |
||
* @description |
||
* Using Angular markup like `{{hash}}` in a `srcset` attribute doesn't |
||
* work right: The browser will fetch from the URL with the literal |
||
* text `{{hash}}` until Angular replaces the expression inside |
||
* `{{hash}}`. The `ngSrcset` directive solves this problem. |
||
* |
||
* The buggy way to write it: |
||
* <pre> |
||
* <img srcset="http://www.gravatar.com/avatar/{{hash}} 2x"/> |
||
* </pre> |
||
* |
||
* The correct way to write it: |
||
* <pre> |
||
* <img ng-srcset="http://www.gravatar.com/avatar/{{hash}} 2x"/> |
||
* </pre> |
||
* |
||
* @element IMG |
||
* @param {template} ngSrcset any string which can contain `{{}}` markup. |
||
*/ |
||
|
||
/** |
||
* @ngdoc directive |
||
* @name ng.directive:ngDisabled |
||
* @restrict A |
||
* @priority 100 |
||
* |
||
* @description |
||
* |
||
* The following markup will make the button enabled on Chrome/Firefox but not on IE8 and older IEs: |
||
* <pre> |
||
* <div ng-init="scope = { isDisabled: false }"> |
||
* <button disabled="{{scope.isDisabled}}">Disabled</button> |
||
* </div> |
||
* </pre> |
||
* |
||
* The HTML specification does not require browsers to preserve the values of boolean attributes |
||
* such as disabled. (Their presence means true and their absence means false.) |
||
* If we put an Angular interpolation expression into such an attribute then the |
||
* binding information would be lost when the browser removes the attribute. |
||
* The `ngDisabled` directive solves this problem for the `disabled` attribute. |
||
* This complementary directive is not removed by the browser and so provides |
||
* a permanent reliable place to store the binding information. |
||
* |
||
* @example |
||
<doc:example> |
||
<doc:source> |
||
Click me to toggle: <input type="checkbox" ng-model="checked"><br/> |
||
<button ng-model="button" ng-disabled="checked">Button</button> |
||
</doc:source> |
||
<doc:scenario> |
||
it('should toggle button', function() { |
||
expect(element('.doc-example-live :button').prop('disabled')).toBeFalsy(); |
||
input('checked').check(); |
||
expect(element('.doc-example-live :button').prop('disabled')).toBeTruthy(); |
||
}); |
||
</doc:scenario> |
||
</doc:example> |
||
* |
||
* @element INPUT |
||
* @param {expression} ngDisabled If the {@link guide/expression expression} is truthy, |
||
* then special attribute "disabled" will be set on the element |
||
*/ |
||
|
||
|
||
/** |
||
* @ngdoc directive |
||
* @name ng.directive:ngChecked |
||
* @restrict A |
||
* @priority 100 |
||
* |
||
* @description |
||
* The HTML specification does not require browsers to preserve the values of boolean attributes |
||
* such as checked. (Their presence means true and their absence means false.) |
||
* If we put an Angular interpolation expression into such an attribute then the |
||
* binding information would be lost when the browser removes the attribute. |
||
* The `ngChecked` directive solves this problem for the `checked` attribute. |
||
* This complementary directive is not removed by the browser and so provides |
||
* a permanent reliable place to store the binding information. |
||
* @example |
||
<doc:example> |
||
<doc:source> |
||
Check me to check both: <input type="checkbox" ng-model="master"><br/> |
||
<input id="checkSlave" type="checkbox" ng-checked="master"> |
||
</doc:source> |
||
<doc:scenario> |
||
it('should check both checkBoxes', function() { |
||
expect(element('.doc-example-live #checkSlave').prop('checked')).toBeFalsy(); |
||
input('master').check(); |
||
expect(element('.doc-example-live #checkSlave').prop('checked')).toBeTruthy(); |
||
}); |
||
</doc:scenario> |
||
</doc:example> |
||
* |
||
* @element INPUT |
||
* @param {expression} ngChecked If the {@link guide/expression expression} is truthy, |
||
* then special attribute "checked" will be set on the element |
||
*/ |
||
|
||
|
||
/** |
||
* @ngdoc directive |
||
* @name ng.directive:ngReadonly |
||
* @restrict A |
||
* @priority 100 |
||
* |
||
* @description |
||
* The HTML specification does not require browsers to preserve the values of boolean attributes |
||
* such as readonly. (Their presence means true and their absence means false.) |
||
* If we put an Angular interpolation expression into such an attribute then the |
||
* binding information would be lost when the browser removes the attribute. |
||
* The `ngReadonly` directive solves this problem for the `readonly` attribute. |
||
* This complementary directive is not removed by the browser and so provides |
||
* a permanent reliable place to store the binding information. |
||
* @example |
||
<doc:example> |
||
<doc:source> |
||
Check me to make text readonly: <input type="checkbox" ng-model="checked"><br/> |
||
<input type="text" ng-readonly="checked" value="I'm Angular"/> |
||
</doc:source> |
||
<doc:scenario> |
||
it('should toggle readonly attr', function() { |
||
expect(element('.doc-example-live :text').prop('readonly')).toBeFalsy(); |
||
input('checked').check(); |
||
expect(element('.doc-example-live :text').prop('readonly')).toBeTruthy(); |
||
}); |
||
</doc:scenario> |
||
</doc:example> |
||
* |
||
* @element INPUT |
||
* @param {expression} ngReadonly If the {@link guide/expression expression} is truthy, |
||
* then special attribute "readonly" will be set on the element |
||
*/ |
||
|
||
|
||
/** |
||
* @ngdoc directive |
||
* @name ng.directive:ngSelected |
||
* @restrict A |
||
* @priority 100 |
||
* |
||
* @description |
||
* The HTML specification does not require browsers to preserve the values of boolean attributes |
||
* such as selected. (Their presence means true and their absence means false.) |
||
* If we put an Angular interpolation expression into such an attribute then the |
||
* binding information would be lost when the browser removes the attribute. |
||
* The `ngSelected` directive solves this problem for the `selected` atttribute. |
||
* This complementary directive is not removed by the browser and so provides |
||
* a permanent reliable place to store the binding information. |
||
* |
||
* @example |
||
<doc:example> |
||
<doc:source> |
||
Check me to select: <input type="checkbox" ng-model="selected"><br/> |
||
<select> |
||
<option>Hello!</option> |
||
<option id="greet" ng-selected="selected">Greetings!</option> |
||
</select> |
||
</doc:source> |
||
<doc:scenario> |
||
it('should select Greetings!', function() { |
||
expect(element('.doc-example-live #greet').prop('selected')).toBeFalsy(); |
||
input('selected').check(); |
||
expect(element('.doc-example-live #greet').prop('selected')).toBeTruthy(); |
||
}); |
||
</doc:scenario> |
||
</doc:example> |
||
* |
||
* @element OPTION |
||
* @param {expression} ngSelected If the {@link guide/expression expression} is truthy, |
||
* then special attribute "selected" will be set on the element |
||
*/ |
||
|
||
/** |
||
* @ngdoc directive |
||
* @name ng.directive:ngOpen |
||
* @restrict A |
||
* @priority 100 |
||
* |
||
* @description |
||
* The HTML specification does not require browsers to preserve the values of boolean attributes |
||
* such as open. (Their presence means true and their absence means false.) |
||
* If we put an Angular interpolation expression into such an attribute then the |
||
* binding information would be lost when the browser removes the attribute. |
||
* The `ngOpen` directive solves this problem for the `open` attribute. |
||
* This complementary directive is not removed by the browser and so provides |
||
* a permanent reliable place to store the binding information. |
||
* @example |
||
<doc:example> |
||
<doc:source> |
||
Check me check multiple: <input type="checkbox" ng-model="open"><br/> |
||
<details id="details" ng-open="open"> |
||
<summary>Show/Hide me</summary> |
||
</details> |
||
</doc:source> |
||
<doc:scenario> |
||
it('should toggle open', function() { |
||
expect(element('#details').prop('open')).toBeFalsy(); |
||
input('open').check(); |
||
expect(element('#details').prop('open')).toBeTruthy(); |
||
}); |
||
</doc:scenario> |
||
</doc:example> |
||
* |
||
* @element DETAILS |
||
* @param {expression} ngOpen If the {@link guide/expression expression} is truthy, |
||
* then special attribute "open" will be set on the element |
||
*/ |
||
|
||
var ngAttributeAliasDirectives = {}; |
||
|
||
|
||
// boolean attrs are evaluated |
||
forEach(BOOLEAN_ATTR, function(propName, attrName) { |
||
// binding to multiple is not supported |
||
if (propName == "multiple") return; |
||
|
||
var normalized = directiveNormalize('ng-' + attrName); |
||
ngAttributeAliasDirectives[normalized] = function() { |
||
return { |
||
priority: 100, |
||
link: function(scope, element, attr) { |
||
scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) { |
||
attr.$set(attrName, !!value); |
||
}); |
||
} |
||
}; |
||
}; |
||
}); |
||
|
||
|
||
// ng-src, ng-srcset, ng-href are interpolated |
||
forEach(['src', 'srcset', 'href'], function(attrName) { |
||
var normalized = directiveNormalize('ng-' + attrName); |
||
ngAttributeAliasDirectives[normalized] = function() { |
||
return { |
||
priority: 99, // it needs to run after the attributes are interpolated |
||
link: function(scope, element, attr) { |
||
attr.$observe(normalized, function(value) { |
||
if (!value) |
||
return; |
||
|
||
attr.$set(attrName, value); |
||
|
||
// on IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist |
||
// then calling element.setAttribute('src', 'foo') doesn't do anything, so we need |
||
// to set the property as well to achieve the desired effect. |
||
// we use attr[attrName] value since $set can sanitize the url. |
||
if (msie) element.prop(attrName, attr[attrName]); |
||
}); |
||
} |
||
}; |
||
}; |
||
}); |
||
|
||
/* global -nullFormCtrl */ |
||
var nullFormCtrl = { |
||
$addControl: noop, |
||
$removeControl: noop, |
||
$setValidity: noop, |
||
$setDirty: noop, |
||
$setPristine: noop |
||
}; |
||
|
||
/** |
||
* @ngdoc object |
||
* @name ng.directive:form.FormController |
||
* |
||
* @property {boolean} $pristine True if user has not interacted with the form yet. |
||
* @property {boolean} $dirty True if user has already interacted with the form. |
||
* @property {boolean} $valid True if all of the containing forms and controls are valid. |
||
* @property {boolean} $invalid True if at least one containing control or form is invalid. |
||
* |
||
* @property {Object} $error Is an object hash, containing references to all invalid controls or |
||
* forms, where: |
||
* |
||
* - keys are validation tokens (error names), |
||
* - values are arrays of controls or forms that are invalid for given error name. |
||
* |
||
* |
||
* Built-in validation tokens: |
||
* |
||
* - `email` |
||
* - `max` |
||
* - `maxlength` |
||
* - `min` |
||
* - `minlength` |
||
* - `number` |
||
* - `pattern` |
||
* - `required` |
||
* - `url` |
||
* |
||
* @description |
||
* `FormController` keeps track of all its controls and nested forms as well as state of them, |
||
* such as being valid/invalid or dirty/pristine. |
||
* |
||
* Each {@link ng.directive:form form} directive creates an instance |
||
* of `FormController`. |
||
* |
||
*/ |
||
//asks for $scope to fool the BC controller module |
||
FormController.$inject = ['$element', '$attrs', '$scope']; |
||
function FormController(element, attrs) { |
||
var form = this, |
||
parentForm = element.parent().controller('form') || nullFormCtrl, |
||
invalidCount = 0, // used to easily determine if we are valid |
||
errors = form.$error = {}, |
||
controls = []; |
||
|
||
// init state |
||
form.$name = attrs.name || attrs.ngForm; |
||
form.$dirty = false; |
||
form.$pristine = true; |
||
form.$valid = true; |
||
form.$invalid = false; |
||
|
||
parentForm.$addControl(form); |
||
|
||
// Setup initial state of the control |
||
element.addClass(PRISTINE_CLASS); |
||
toggleValidCss(true); |
||
|
||
// convenience method for easy toggling of classes |
||
function toggleValidCss(isValid, validationErrorKey) { |
||
validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : ''; |
||
element. |
||
removeClass((isValid ? INVALID_CLASS : VALID_CLASS) + validationErrorKey). |
||
addClass((isValid ? VALID_CLASS : INVALID_CLASS) + validationErrorKey); |
||
} |
||
|
||
/** |
||
* @ngdoc function |
||
* @name ng.directive:form.FormController#$addControl |
||
* @methodOf ng.directive:form.FormController |
||
* |
||
* @description |
||
* Register a control with the form. |
||
* |
||
* Input elements using ngModelController do this automatically when they are linked. |
||
*/ |
||
form.$addControl = function(control) { |
||
// Breaking change - before, inputs whose name was "hasOwnProperty" were quietly ignored |
||
// and not added to the scope. Now we throw an error. |
||
assertNotHasOwnProperty(control.$name, 'input'); |
||
controls.push(control); |
||
|
||
if (control.$name) { |
||
form[control.$name] = control; |
||
} |
||
}; |
||
|
||
/** |
||
* @ngdoc function |
||
* @name ng.directive:form.FormController#$removeControl |
||
* @methodOf ng.directive:form.FormController |
||
* |
||
* @description |
||
* Deregister a control from the form. |
||
* |
||
* Input elements using ngModelController do this automatically when they are destroyed. |
||
*/ |
||
form.$removeControl = function(control) { |
||
if (control.$name && form[control.$name] === control) { |
||
delete form[control.$name]; |
||
} |
||
forEach(errors, function(queue, validationToken) { |
||
form.$setValidity(validationToken, true, control); |
||
}); |
||
|
||
arrayRemove(controls, control); |
||
}; |
||
|
||
/** |
||
* @ngdoc function |
||
* @name ng.directive:form.FormController#$setValidity |
||
* @methodOf ng.directive:form.FormController |
||
* |
||
* @description |
||
* Sets the validity of a form control. |
||
* |
||
* This method will also propagate to parent forms. |
||
*/ |
||
form.$setValidity = function(validationToken, isValid, control) { |
||
var queue = errors[validationToken]; |
||
|
||
if (isValid) { |
||
if (queue) { |
||
arrayRemove(queue, control); |
||
if (!queue.length) { |
||
invalidCount--; |
||
if (!invalidCount) { |
||
toggleValidCss(isValid); |
||
form.$valid = true; |
||
form.$invalid = false; |
||
} |
||
errors[validationToken] = false; |
||
toggleValidCss(true, validationToken); |
||
parentForm.$setValidity(validationToken, true, form); |
||
} |
||
} |
||
|
||
} else { |
||
if (!invalidCount) { |
||
toggleValidCss(isValid); |
||
} |
||
if (queue) { |
||
if (includes(queue, control)) return; |
||
} else { |
||
errors[validationToken] = queue = []; |
||
invalidCount++; |
||
toggleValidCss(false, validationToken); |
||
parentForm.$setValidity(validationToken, false, form); |
||
} |
||
queue.push(control); |
||
|
||
form.$valid = false; |
||
form.$invalid = true; |
||
} |
||
}; |
||
|
||
/** |
||
* @ngdoc function |
||
* @name ng.directive:form.FormController#$setDirty |
||
* @methodOf ng.directive:form.FormController |
||
* |
||
* @description |
||
* Sets the form to a dirty state. |
||
* |
||
* This method can be called to add the 'ng-dirty' class and set the form to a dirty |
||
* state (ng-dirty class). This method will also propagate to parent forms. |
||
*/ |
||
form.$setDirty = function() { |
||
element.removeClass(PRISTINE_CLASS).addClass(DIRTY_CLASS); |
||
form.$dirty = true; |
||
form.$pristine = false; |
||
parentForm.$setDirty(); |
||
}; |
||
|
||
/** |
||
* @ngdoc function |
||
* @name ng.directive:form.FormController#$setPristine |
||
* @methodOf ng.directive:form.FormController |
||
* |
||
* @description |
||
* Sets the form to its pristine state. |
||
* |
||
* This method can be called to remove the 'ng-dirty' class and set the form to its pristine |
||
* state (ng-pristine class). This method will also propagate to all the controls contained |
||
* in this form. |
||
* |
||
* Setting a form back to a pristine state is often useful when we want to 'reuse' a form after |
||
* saving or resetting it. |
||
*/ |
||
form.$setPristine = function () { |
||
element.removeClass(DIRTY_CLASS).addClass(PRISTINE_CLASS); |
||
form.$dirty = false; |
||
form.$pristine = true; |
||
forEach(controls, function(control) { |
||
control.$setPristine(); |
||
}); |
||
}; |
||
} |
||
|
||
|
||
/** |
||
* @ngdoc directive |
||
* @name ng.directive:ngForm |
||
* @restrict EAC |
||
* |
||
* @description |
||
* Nestable alias of {@link ng.directive:form `form`} directive. HTML |
||
* does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a |
||
* sub-group of controls needs to be determined. |
||
* |
||
* @param {string=} ngForm|name Name of the form. If specified, the form controller will be published into |
||
* related scope, under this name. |
||
* |
||
*/ |
||
|
||
/** |
||
* @ngdoc directive |
||
* @name ng.directive:form |
||
* @restrict E |
||
* |
||
* @description |
||
* Directive that instantiates |
||
* {@link ng.directive:form.FormController FormController}. |
||
* |
||
* If the `name` attribute is specified, the form controller is published onto the current scope under |
||
* this name. |
||
* |
||
* # Alias: {@link ng.directive:ngForm `ngForm`} |
||
* |
||
* In Angular forms can be nested. This means that the outer form is valid when all of the child |
||
* forms are valid as well. However, browsers do not allow nesting of `<form>` elements, so |
||
* Angular provides the {@link ng.directive:ngForm `ngForm`} directive which behaves identically to |
||
* `<form>` but can be nested. This allows you to have nested forms, which is very useful when |
||
* using Angular validation directives in forms that are dynamically generated using the |
||
* {@link ng.directive:ngRepeat `ngRepeat`} directive. Since you cannot dynamically generate the `name` |
||
* attribute of input elements using interpolation, you have to wrap each set of repeated inputs in an |
||
* `ngForm` directive and nest these in an outer `form` element. |
||
* |
||
* |
||
* # CSS classes |
||
* - `ng-valid` is set if the form is valid. |
||
* - `ng-invalid` is set if the form is invalid. |
||
* - `ng-pristine` is set if the form is pristine. |
||
* - `ng-dirty` is set if the form is dirty. |
||
* |
||
* |
||
* # Submitting a form and preventing the default action |
||
* |
||
* Since the role of forms in client-side Angular applications is different than in classical |
||
* roundtrip apps, it is desirable for the browser not to translate the form submission into a full |
||
* page reload that sends the data to the server. Instead some javascript logic should be triggered |
||
* to handle the form submission in an application-specific way. |
||
* |
||
* For this reason, Angular prevents the default action (form submission to the server) unless the |
||
* `<form>` element has an `action` attribute specified. |
||
* |
||
* You can use one of the following two ways to specify what javascript method should be called when |
||
* a form is submitted: |
||
* |
||
* - {@link ng.directive:ngSubmit ngSubmit} directive on the form element |
||
* - {@link ng.directive:ngClick ngClick} directive on the first |
||
* button or input field of type submit (input[type=submit]) |
||
* |
||
* To prevent double execution of the handler, use only one of the {@link ng.directive:ngSubmit ngSubmit} |
||
* or {@link ng.directive:ngClick ngClick} directives. |
||
* This is because of the following form submission rules in the HTML specification: |
||
* |
||
* - If a form has only one input field then hitting enter in this field triggers form submit |
||
* (`ngSubmit`) |
||
* - if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter |
||
* doesn't trigger submit |
||
* - if a form has one or more input fields and one or more buttons or input[type=submit] then |
||
* hitting enter in any of the input fields will trigger the click handler on the *first* button or |
||
* input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`) |
||
* |
||
* @param {string=} name Name of the form. If specified, the form controller will be published into |
||
* related scope, under this name. |
||
* |
||
* @example |
||
<doc:example> |
||
<doc:source> |
||
<script> |
||
function Ctrl($scope) { |
||
$scope.userType = 'guest'; |
||
} |
||
</script> |
||
<form name="myForm" ng-controller="Ctrl"> |
||
userType: <input name="input" ng-model="userType" required> |
||
<span class="error" ng-show="myForm.input.$error.required">Required!</span><br> |
||
<tt>userType = {{userType}}</tt><br> |
||
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br> |
||
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br> |
||
<tt>myForm.$valid = {{myForm.$valid}}</tt><br> |
||
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br> |
||
</form> |
||
</doc:source> |
||
<doc:scenario> |
||
it('should initialize to model', function() { |
||
expect(binding('userType')).toEqual('guest'); |
||
expect(binding('myForm.input.$valid')).toEqual('true'); |
||
}); |
||
|
||
it('should be invalid if empty', function() { |
||
input('userType').enter(''); |
||
expect(binding('userType')).toEqual(''); |
||
expect(binding('myForm.input.$valid')).toEqual('false'); |
||
}); |
||
</doc:scenario> |
||
</doc:example> |
||
*/ |
||
var formDirectiveFactory = function(isNgForm) { |
||
return ['$timeout', function($timeout) { |
||
var formDirective = { |
||
name: 'form', |
||
restrict: isNgForm ? 'EAC' : 'E', |
||
controller: FormController, |
||
compile: function() { |
||
return { |
||
pre: function(scope, formElement, attr, controller) { |
||
if (!attr.action) { |
||
// we can't use jq events because if a form is destroyed during submission the default |
||
// action is not prevented. see #1238 |
||
// |
||
// IE 9 is not affected because it doesn't fire a submit event and try to do a full |
||
// page reload if the form was destroyed by submission of the form via a click handler |
||
// on a button in the form. Looks like an IE9 specific bug. |
||
var preventDefaultListener = function(event) { |
||
event.preventDefault |
||
? event.preventDefault() |
||
: event.returnValue = false; // IE |
||
}; |
||
|
||
addEventListenerFn(formElement[0], 'submit', preventDefaultListener); |
||
|
||
// unregister the preventDefault listener so that we don't not leak memory but in a |
||
// way that will achieve the prevention of the default action. |
||
formElement.on('$destroy', function() { |
||
$timeout(function() { |
||
removeEventListenerFn(formElement[0], 'submit', preventDefaultListener); |
||
}, 0, false); |
||
}); |
||
} |
||
|
||
var parentFormCtrl = formElement.parent().controller('form'), |
||
alias = attr.name || attr.ngForm; |
||
|
||
if (alias) { |
||
setter(scope, alias, controller, alias); |
||
} |
||
if (parentFormCtrl) { |
||
formElement.on('$destroy', function() { |
||
parentFormCtrl.$removeControl(controller); |
||
if (alias) { |
||
setter(scope, alias, undefined, alias); |
||
} |
||
extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards |
||
}); |
||
} |
||
} |
||
}; |
||
} |
||
}; |
||
|
||
return formDirective; |
||
}]; |
||
}; |
||
|
||
var formDirective = formDirectiveFactory(); |
||
var ngFormDirective = formDirectiveFactory(true); |
||
|
||
/* global |
||
|
||
-VALID_CLASS, |
||
-INVALID_CLASS, |
||
-PRISTINE_CLASS, |
||
-DIRTY_CLASS |
||
*/ |
||
|
||
var URL_REGEXP = /^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/; |
||
var EMAIL_REGEXP = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,6}$/; |
||
var NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))\s*$/; |
||
|
||
var inputType = { |
||
|
||
/** |
||
* @ngdoc inputType |
||
* @name ng.directive:input.text |
||
* |
||
* @description |
||
* Standard HTML text input with angular data binding. |
||
* |
||
* @param {string} ngModel Assignable angular expression to data-bind to. |
||
* @param {string=} name Property name of the form under which the control is published. |
||
* @param {string=} required Adds `required` validation error key if the value is not entered. |
||
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to |
||
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of |
||
* `required` when you want to data-bind to the `required` attribute. |
||
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than |
||
* minlength. |
||
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than |
||
* maxlength. |
||
* @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the |
||
* RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for |
||
* patterns defined as scope expressions. |
||
* @param {string=} ngChange Angular expression to be executed when input changes due to user |
||
* interaction with the input element. |
||
* @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input. |
||
* |
||
* @example |
||
<doc:example> |
||
<doc:source> |
||
<script> |
||
function Ctrl($scope) { |
||
$scope.text = 'guest'; |
||
$scope.word = /^\s*\w*\s*$/; |
||
} |
||
</script> |
||
<form name="myForm" ng-controller="Ctrl"> |
||
Single word: <input type="text" name="input" ng-model="text" |
||
ng-pattern="word" required ng-trim="false"> |
||
<span class="error" ng-show="myForm.input.$error.required"> |
||
Required!</span> |
||
<span class="error" ng-show="myForm.input.$error.pattern"> |
||
Single word only!</span> |
||
|
||
<tt>text = {{text}}</tt><br/> |
||
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> |
||
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> |
||
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/> |
||
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> |
||
</form> |
||
</doc:source> |
||
<doc:scenario> |
||
it('should initialize to model', function() { |
||
expect(binding('text')).toEqual('guest'); |
||
expect(binding('myForm.input.$valid')).toEqual('true'); |
||
}); |
||
|
||
it('should be invalid if empty', function() { |
||
input('text').enter(''); |
||
expect(binding('text')).toEqual(''); |
||
expect(binding('myForm.input.$valid')).toEqual('false'); |
||
}); |
||
|
||
it('should be invalid if multi word', function() { |
||
input('text').enter('hello world'); |
||
expect(binding('myForm.input.$valid')).toEqual('false'); |
||
}); |
||
|
||
it('should not be trimmed', function() { |
||
input('text').enter('untrimmed '); |
||
expect(binding('text')).toEqual('untrimmed '); |
||
expect(binding('myForm.input.$valid')).toEqual('true'); |
||
}); |
||
</doc:scenario> |
||
</doc:example> |
||
*/ |
||
'text': textInputType, |
||
|
||
|
||
/** |
||
* @ngdoc inputType |
||
* @name ng.directive:input.number |
||
* |
||
* @description |
||
* Text input with number validation and transformation. Sets the `number` validation |
||
* error if not a valid number. |
||
* |
||
* @param {string} ngModel Assignable angular expression to data-bind to. |
||
* @param {string=} name Property name of the form under which the control is published. |
||
* @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. |
||
* @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. |
||
* @param {string=} required Sets `required` validation error key if the value is not entered. |
||
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to |
||
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of |
||
* `required` when you want to data-bind to the `required` attribute. |
||
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than |
||
* minlength. |
||
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than |
||
* maxlength. |
||
* @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the |
||
* RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for |
||
* patterns defined as scope expressions. |
||
* @param {string=} ngChange Angular expression to be executed when input changes due to user |
||
* interaction with the input element. |
||
* |
||
* @example |
||
<doc:example> |
||
<doc:source> |
||
<script> |
||
function Ctrl($scope) { |
||
$scope.value = 12; |
||
} |
||
</script> |
||
<form name="myForm" ng-controller="Ctrl"> |
||
Number: <input type="number" name="input" ng-model="value" |
||
min="0" max="99" required> |
||
<span class="error" ng-show="myForm.input.$error.required"> |
||
Required!</span> |
||
<span class="error" ng-show="myForm.input.$error.number"> |
||
Not valid number!</span> |
||
<tt>value = {{value}}</tt><br/> |
||
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> |
||
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> |
||
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/> |
||
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> |
||
</form> |
||
</doc:source> |
||
<doc:scenario> |
||
it('should initialize to model', function() { |
||
expect(binding('value')).toEqual('12'); |
||
expect(binding('myForm.input.$valid')).toEqual('true'); |
||
}); |
||
|
||
it('should be invalid if empty', function() { |
||
input('value').enter(''); |
||
expect(binding('value')).toEqual(''); |
||
expect(binding('myForm.input.$valid')).toEqual('false'); |
||
}); |
||
|
||
it('should be invalid if over max', function() { |
||
input('value').enter('123'); |
||
expect(binding('value')).toEqual(''); |
||
expect(binding('myForm.input.$valid')).toEqual('false'); |
||
}); |
||
</doc:scenario> |
||
</doc:example> |
||
*/ |
||
'number': numberInputType, |
||
|
||
|
||
/** |
||
* @ngdoc inputType |
||
* @name ng.directive:input.url |
||
* |
||
* @description |
||
* Text input with URL validation. Sets the `url` validation error key if the content is not a |
||
* valid URL. |
||
* |
||
* @param {string} ngModel Assignable angular expression to data-bind to. |
||
* @param {string=} name Property name of the form under which the control is published. |
||
* @param {string=} required Sets `required` validation error key if the value is not entered. |
||
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to |
||
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of |
||
* `required` when you want to data-bind to the `required` attribute. |
||
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than |
||
* minlength. |
||
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than |
||
* maxlength. |
||
* @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the |
||
* RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for |
||
* patterns defined as scope expressions. |
||
* @param {string=} ngChange Angular expression to be executed when input changes due to user |
||
* interaction with the input element. |
||
* |
||
* @example |
||
<doc:example> |
||
<doc:source> |
||
<script> |
||
function Ctrl($scope) { |
||
$scope.text = 'http://google.com'; |
||
} |
||
</script> |
||
<form name="myForm" ng-controller="Ctrl"> |
||
URL: <input type="url" name="input" ng-model="text" required> |
||
<span class="error" ng-show="myForm.input.$error.required"> |
||
Required!</span> |
||
<span class="error" ng-show="myForm.input.$error.url"> |
||
Not valid url!</span> |
||
<tt>text = {{text}}</tt><br/> |
||
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> |
||
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> |
||
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/> |
||
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> |
||
<tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/> |
||
</form> |
||
</doc:source> |
||
<doc:scenario> |
||
it('should initialize to model', function() { |
||
expect(binding('text')).toEqual('http://google.com'); |
||
expect(binding('myForm.input.$valid')).toEqual('true'); |
||
}); |
||
|
||
it('should be invalid if empty', function() { |
||
input('text').enter(''); |
||
expect(binding('text')).toEqual(''); |
||
expect(binding('myForm.input.$valid')).toEqual('false'); |
||
}); |
||
|
||
it('should be invalid if not url', function() { |
||
input('text').enter('xxx'); |
||
expect(binding('myForm.input.$valid')).toEqual('false'); |
||
}); |
||
</doc:scenario> |
||
</doc:example> |
||
*/ |
||
'url': urlInputType, |
||
|
||
|
||
/** |
||
* @ngdoc inputType |
||
* @name ng.directive:input.email |
||
* |
||
* @description |
||
* Text input with email validation. Sets the `email` validation error key if not a valid email |
||
* address. |
||
* |
||
* @param {string} ngModel Assignable angular expression to data-bind to. |
||
* @param {string=} name Property name of the form under which the control is published. |
||
* @param {string=} required Sets `required` validation error key if the value is not entered. |
||
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to |
||
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of |
||
* `required` when you want to data-bind to the `required` attribute. |
||
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than |
||
* minlength. |
||
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than |
||
* maxlength. |
||
* @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the |
||
* RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for |
||
* patterns defined as scope expressions. |
||
* @param {string=} ngChange Angular expression to be executed when input changes due to user |
||
* interaction with the input element. |
||
* |
||
* @example |
||
<doc:example> |
||
<doc:source> |
||
<script> |
||
function Ctrl($scope) { |
||
$scope.text = '[email protected]'; |
||
} |
||
</script> |
||
<form name="myForm" ng-controller="Ctrl"> |
||
Email: <input type="email" name="input" ng-model="text" required> |
||
<span class="error" ng-show="myForm.input.$error.required"> |
||
Required!</span> |
||
<span class="error" ng-show="myForm.input.$error.email"> |
||
Not valid email!</span> |
||
<tt>text = {{text}}</tt><br/> |
||
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> |
||
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> |
||
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/> |
||
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> |
||
<tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/> |
||
</form> |
||
</doc:source> |
||
<doc:scenario> |
||
it('should initialize to model', function() { |
||
expect(binding('text')).toEqual('[email protected]'); |
||
expect(binding('myForm.input.$valid')).toEqual('true'); |
||
}); |
||
|
||
it('should be invalid if empty', function() { |
||
input('text').enter(''); |
||
expect(binding('text')).toEqual(''); |
||
expect(binding('myForm.input.$valid')).toEqual('false'); |
||
}); |
||
|
||
it('should be invalid if not email', function() { |
||
input('text').enter('xxx'); |
||
expect(binding('myForm.input.$valid')).toEqual('false'); |
||
}); |
||
</doc:scenario> |
||
</doc:example> |
||
*/ |
||
'email': emailInputType, |
||
|
||
|
||
/** |
||
* @ngdoc inputType |
||
* @name ng.directive:input.radio |
||
* |
||
* @description |
||
* HTML radio button. |
||
* |
||
* @param {string} ngModel Assignable angular expression to data-bind to. |
||
* @param {string} value The value to which the expression should be set when selected. |
||
* @param {string=} name Property name of the form under which the control is published. |
||
* @param {string=} ngChange Angular expression to be executed when input changes due to user |
||
* interaction with the input element. |
||
* |
||
* @example |
||
<doc:example> |
||
<doc:source> |
||
<script> |
||
function Ctrl($scope) { |
||
$scope.color = 'blue'; |
||
} |
||
</script> |
||
<form name="myForm" ng-controller="Ctrl"> |
||
<input type="radio" ng-model="color" value="red"> Red <br/> |
||
<input type="radio" ng-model="color" value="green"> Green <br/> |
||
<input type="radio" ng-model="color" value="blue"> Blue <br/> |
||
<tt>color = {{color}}</tt><br/> |
||
</form> |
||
</doc:source> |
||
<doc:scenario> |
||
it('should change state', function() { |
||
expect(binding('color')).toEqual('blue'); |
||
|
||
input('color').select('red'); |
||
expect(binding('color')).toEqual('red'); |
||
}); |
||
</doc:scenario> |
||
</doc:example> |
||
*/ |
||
'radio': radioInputType, |
||
|
||
|
||
/** |
||
* @ngdoc inputType |
||
* @name ng.directive:input.checkbox |
||
* |
||
* @description |
||
* HTML checkbox. |
||
* |
||
* @param {string} ngModel Assignable angular expression to data-bind to. |
||
* @param {string=} name Property name of the form under which the control is published. |
||
* @param {string=} ngTrueValue The value to which the expression should be set when selected. |
||
* @param {string=} ngFalseValue The value to which the expression should be set when not selected. |
||
* @param {string=} ngChange Angular expression to be executed when input changes due to user |
||
* interaction with the input element. |
||
* |
||
* @example |
||
<doc:example> |
||
<doc:source> |
||
<script> |
||
function Ctrl($scope) { |
||
$scope.value1 = true; |
||
$scope.value2 = 'YES' |
||
} |
||
</script> |
||
<form name="myForm" ng-controller="Ctrl"> |
||
Value1: <input type="checkbox" ng-model="value1"> <br/> |
||
Value2: <input type="checkbox" ng-model="value2" |
||
ng-true-value="YES" ng-false-value="NO"> <br/> |
||
<tt>value1 = {{value1}}</tt><br/> |
||
<tt>value2 = {{value2}}</tt><br/> |
||
</form> |
||
</doc:source> |
||
<doc:scenario> |
||
it('should change state', function() { |
||
expect(binding('value1')).toEqual('true'); |
||
expect(binding('value2')).toEqual('YES'); |
||
|
||
input('value1').check(); |
||
input('value2').check(); |
||
expect(binding('value1')).toEqual('false'); |
||
expect(binding('value2')).toEqual('NO'); |
||
}); |
||
</doc:scenario> |
||
</doc:example> |
||
*/ |
||
'checkbox': checkboxInputType, |
||
|
||
'hidden': noop, |
||
'button': noop, |
||
'submit': noop, |
||
'reset': noop |
||
}; |
||
|
||
// A helper function to call $setValidity and return the value / undefined, |
||
// a pattern that is repeated a lot in the input validation logic. |
||
function validate(ctrl, validatorName, validity, value){ |
||
ctrl.$setValidity(validatorName, validity); |
||
return validity ? value : undefined; |
||
} |
||
|
||
function textInputType(scope, element, attr, ctrl, $sniffer, $browser) { |
||
// In composition mode, users are still inputing intermediate text buffer, |
||
// hold the listener until composition is done. |
||
// More about composition events: https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent |
||
if (!$sniffer.android) { |
||
var composing = false; |
||
|
||
element.on('compositionstart', function(data) { |
||
composing = true; |
||
}); |
||
|
||
element.on('compositionend', function() { |
||
composing = false; |
||
}); |
||
} |
||
|
||
var listener = function() { |
||
if (composing) return; |
||
var value = element.val(); |
||
|
||
// By default we will trim the value |
||
// If the attribute ng-trim exists we will avoid trimming |
||
// e.g. <input ng-model="foo" ng-trim="false"> |
||
if (toBoolean(attr.ngTrim || 'T')) { |
||
value = trim(value); |
||
} |
||
|
||
if (ctrl.$viewValue !== value) { |
||
if (scope.$$phase) { |
||
ctrl.$setViewValue(value); |
||
} else { |
||
scope.$apply(function() { |
||
ctrl.$setViewValue(value); |
||
}); |
||
} |
||
} |
||
}; |
||
|
||
// if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the |
||
// input event on backspace, delete or cut |
||
if ($sniffer.hasEvent('input')) { |
||
element.on('input', listener); |
||
} else { |
||
var timeout; |
||
|
||
var deferListener = function() { |
||
if (!timeout) { |
||
timeout = $browser.defer(function() { |
||
listener(); |
||
timeout = null; |
||
}); |
||
} |
||
}; |
||
|
||
element.on('keydown', function(event) { |
||
var key = event.keyCode; |
||
|
||
// ignore |
||
// command modifiers arrows |
||
if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return; |
||
|
||
deferListener(); |
||
}); |
||
|
||
// if user modifies input value using context menu in IE, we need "paste" and "cut" events to catch it |
||
if ($sniffer.hasEvent('paste')) { |
||
element.on('paste cut', deferListener); |
||
} |
||
} |
||
|
||
// if user paste into input using mouse on older browser |
||
// or form autocomplete on newer browser, we need "change" event to catch it |
||
element.on('change', listener); |
||
|
||
ctrl.$render = function() { |
||
element.val(ctrl.$isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue); |
||
}; |
||
|
||
// pattern validator |
||
var pattern = attr.ngPattern, |
||
patternValidator, |
||
match; |
||
|
||
if (pattern) { |
||
var validateRegex = function(regexp, value) { |
||
return validate(ctrl, 'pattern', ctrl.$isEmpty(value) || regexp.test(value), value); |
||
}; |
||
match = pattern.match(/^\/(.*)\/([gim]*)$/); |
||
if (match) { |
||
pattern = new RegExp(match[1], match[2]); |
||
patternValidator = function(value) { |
||
return validateRegex(pattern, value); |
||
}; |
||
} else { |
||
patternValidator = function(value) { |
||
var patternObj = scope.$eval(pattern); |
||
|
||
if (!patternObj || !patternObj.test) { |
||
throw minErr('ngPattern')('noregexp', |
||
'Expected {0} to be a RegExp but was {1}. Element: {2}', pattern, |
||
patternObj, startingTag(element)); |
||
} |
||
return validateRegex(patternObj, value); |
||
}; |
||
} |
||
|
||
ctrl.$formatters.push(patternValidator); |
||
ctrl.$parsers.push(patternValidator); |
||
} |
||
|
||
// min length validator |
||
if (attr.ngMinlength) { |
||
var minlength = int(attr.ngMinlength); |
||
var minLengthValidator = function(value) { |
||
return validate(ctrl, 'minlength', ctrl.$isEmpty(value) || value.length >= minlength, value); |
||
}; |
||
|
||
ctrl.$parsers.push(minLengthValidator); |
||
ctrl.$formatters.push(minLengthValidator); |
||
} |
||
|
||
// max length validator |
||
if (attr.ngMaxlength) { |
||
var maxlength = int(attr.ngMaxlength); |
||
var maxLengthValidator = function(value) { |
||
return validate(ctrl, 'maxlength', ctrl.$isEmpty(value) || value.length <= maxlength, value); |
||
}; |
||
|
||
ctrl.$parsers.push(maxLengthValidator); |
||
ctrl.$formatters.push(maxLengthValidator); |
||
} |
||
} |
||
|
||
function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) { |
||
textInputType(scope, element, attr, ctrl, $sniffer, $browser); |
||
|
||
ctrl.$parsers.push(function(value) { |
||
var empty = ctrl.$isEmpty(value); |
||
if (empty || NUMBER_REGEXP.test(value)) { |
||
ctrl.$setValidity('number', true); |
||
return value === '' ? null : (empty ? value : parseFloat(value)); |
||
} else { |
||
ctrl.$setValidity('number', false); |
||
return undefined; |
||
} |
||
}); |
||
|
||
ctrl.$formatters.push(function(value) { |
||
return ctrl.$isEmpty(value) ? '' : '' + value; |
||
}); |
||
|
||
if (attr.min) { |
||
var minValidator = function(value) { |
||
var min = parseFloat(attr.min); |
||
return validate(ctrl, 'min', ctrl.$isEmpty(value) || value >= min, value); |
||
}; |
||
|
||
ctrl.$parsers.push(minValidator); |
||
ctrl.$formatters.push(minValidator); |
||
} |
||
|
||
if (attr.max) { |
||
var maxValidator = function(value) { |
||
var max = parseFloat(attr.max); |
||
return validate(ctrl, 'max', ctrl.$isEmpty(value) || value <= max, value); |
||
}; |
||
|
||
ctrl.$parsers.push(maxValidator); |
||
ctrl.$formatters.push(maxValidator); |
||
} |
||
|
||
ctrl.$formatters.push(function(value) { |
||
return validate(ctrl, 'number', ctrl.$isEmpty(value) || isNumber(value), value); |
||
}); |
||
} |
||
|
||
function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) { |
||
textInputType(scope, element, attr, ctrl, $sniffer, $browser); |
||
|
||
var urlValidator = function(value) { |
||
return validate(ctrl, 'url', ctrl.$isEmpty(value) || URL_REGEXP.test(value), value); |
||
}; |
||
|
||
ctrl.$formatters.push(urlValidator); |
||
ctrl.$parsers.push(urlValidator); |
||
} |
||
|
||
function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) { |
||
textInputType(scope, element, attr, ctrl, $sniffer, $browser); |
||
|
||
var emailValidator = function(value) { |
||
return validate(ctrl, 'email', ctrl.$isEmpty(value) || EMAIL_REGEXP.test(value), value); |
||
}; |
||
|
||
ctrl.$formatters.push(emailValidator); |
||
ctrl.$parsers.push(emailValidator); |
||
} |
||
|
||
function radioInputType(scope, element, attr, ctrl) { |
||
// make the name unique, if not defined |
||
if (isUndefined(attr.name)) { |
||
element.attr('name', nextUid()); |
||
} |
||
|
||
element.on('click', function() { |
||
if (element[0].checked) { |
||
scope.$apply(function() { |
||
ctrl.$setViewValue(attr.value); |
||
}); |
||
} |
||
}); |
||
|
||
ctrl.$render = function() { |
||
var value = attr.value; |
||
element[0].checked = (value == ctrl.$viewValue); |
||
}; |
||
|
||
attr.$observe('value', ctrl.$render); |
||
} |
||
|
||
function checkboxInputType(scope, element, attr, ctrl) { |
||
var trueValue = attr.ngTrueValue, |
||
falseValue = attr.ngFalseValue; |
||
|
||
if (!isString(trueValue)) trueValue = true; |
||
if (!isString(falseValue)) falseValue = false; |
||
|
||
element.on('click', function() { |
||
scope.$apply(function() { |
||
ctrl.$setViewValue(element[0].checked); |
||
}); |
||
}); |
||
|
||
ctrl.$render = function() { |
||
element[0].checked = ctrl.$viewValue; |
||
}; |
||
|
||
// Override the standard `$isEmpty` because a value of `false` means empty in a checkbox. |
||
ctrl.$isEmpty = function(value) { |
||
return value !== trueValue; |
||
}; |
||
|
||
ctrl.$formatters.push(function(value) { |
||
return value === trueValue; |
||
}); |
||
|
||
ctrl.$parsers.push(function(value) { |
||
return value ? trueValue : falseValue; |
||
}); |
||
} |
||
|
||
|
||
/** |
||
* @ngdoc directive |
||
* @name ng.directive:textarea |
||
* @restrict E |
||
* |
||
* @description |
||
* HTML textarea element control with angular data-binding. The data-binding and validation |
||
* properties of this element are exactly the same as those of the |
||
* {@link ng.directive:input input element}. |
||
* |
||
* @param {string} ngModel Assignable angular expression to data-bind to. |
||
* @param {string=} name Property name of the form under which the control is published. |
||
* @param {string=} required Sets `required` validation error key if the value is not entered. |
||
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to |
||
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of |
||
* `required` when you want to data-bind to the `required` attribute. |
||
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than |
||
* minlength. |
||
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than |
||
* maxlength. |
||
* @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the |
||
* RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for |
||
* patterns defined as scope expressions. |
||
* @param {string=} ngChange Angular expression to be executed when input changes due to user |
||
* interaction with the input element. |
||
*/ |
||
|
||
|
||
/** |
||
* @ngdoc directive |
||
* @name ng.directive:input |
||
* @restrict E |
||
* |
||
* @description |
||
* HTML input element control with angular data-binding. Input control follows HTML5 input types |
||
* and polyfills the HTML5 validation behavior for older browsers. |
||
* |
||
* @param {string} ngModel Assignable angular expression to data-bind to. |
||
* @param {string=} name Property name of the form under which the control is published. |
||
* @param {string=} required Sets `required` validation error key if the value is not entered. |
||
* @param {boolean=} ngRequired Sets `required` attribute if set to true |
||
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than |
||
* minlength. |
||
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than |
||
* maxlength. |
||
* @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the |
||
* RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for |
||
* patterns defined as scope expressions. |
||
* @param {string=} ngChange Angular expression to be executed when input changes due to user |
||
* interaction with the input element. |
||
* |
||
* @example |
||
<doc:example> |
||
<doc:source> |
||
<script> |
||
function Ctrl($scope) { |
||
$scope.user = {name: 'guest', last: 'visitor'}; |
||
} |
||
</script> |
||
<div ng-controller="Ctrl"> |
||
<form name="myForm"> |
||
User name: <input type="text" name="userName" ng-model="user.name" required> |
||
<span class="error" ng-show="myForm.userName.$error.required"> |
||
Required!</span><br> |
||
Last name: <input type="text" name="lastName" ng-model="user.last" |
||
ng-minlength="3" ng-maxlength="10"> |
||
<span class="error" ng-show="myForm.lastName.$error.minlength"> |
||
Too short!</span> |
||
<span class="error" ng-show="myForm.lastName.$error.maxlength"> |
||
Too long!</span><br> |
||
</form> |
||
<hr> |
||
<tt>user = {{user}}</tt><br/> |
||
<tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br> |
||
<tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br> |
||
<tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br> |
||
<tt>myForm.lastName.$error = {{myForm.lastName.$error}}</tt><br> |
||
<tt>myForm.$valid = {{myForm.$valid}}</tt><br> |
||
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br> |
||
<tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br> |
||
<tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br> |
||
</div> |
||
</doc:source> |
||
<doc:scenario> |
||
it('should initialize to model', function() { |
||
expect(binding('user')).toEqual('{"name":"guest","last":"visitor"}'); |
||
expect(binding('myForm.userName.$valid')).toEqual('true'); |
||
expect(binding('myForm.$valid')).toEqual('true'); |
||
}); |
||
|
||
it('should be invalid if empty when required', function() { |
||
input('user.name').enter(''); |
||
expect(binding('user')).toEqual('{"last":"visitor"}'); |
||
expect(binding('myForm.userName.$valid')).toEqual('false'); |
||
expect(binding('myForm.$valid')).toEqual('false'); |
||
}); |
||
|
||
it('should be valid if empty when min length is set', function() { |
||
input('user.last').enter(''); |
||
expect(binding('user')).toEqual('{"name":"guest","last":""}'); |
||
expect(binding('myForm.lastName.$valid')).toEqual('true'); |
||
expect(binding('myForm.$valid')).toEqual('true'); |
||
}); |
||
|
||
it('should be invalid if less than required min length', function() { |
||
input('user.last').enter('xx'); |
||
expect(binding('user')).toEqual('{"name":"guest"}'); |
||
expect(binding('myForm.lastName.$valid')).toEqual('false'); |
||
expect(binding('myForm.lastName.$error')).toMatch(/minlength/); |
||
expect(binding('myForm.$valid')).toEqual('false'); |
||
}); |
||
|
||
it('should be invalid if longer than max length', function() { |
||
input('user.last').enter('some ridiculously long name'); |
||
expect(binding('user')) |
||
.toEqual('{"name":"guest"}'); |
||
expect(binding('myForm.lastName.$valid')).toEqual('false'); |
||
expect(binding('myForm.lastName.$error')).toMatch(/maxlength/); |
||
expect(binding('myForm.$valid')).toEqual('false'); |
||
}); |
||
</doc:scenario> |
||
</doc:example> |
||
*/ |
||
var inputDirective = ['$browser', '$sniffer', function($browser, $sniffer) { |
||
return { |
||
restrict: 'E', |
||
require: '?ngModel', |
||
link: function(scope, element, attr, ctrl) { |
||
if (ctrl) { |
||
(inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrl, $sniffer, |
||
$browser); |
||
} |
||
} |
||
}; |
||
}]; |
||
|
||
var VALID_CLASS = 'ng-valid', |
||
INVALID_CLASS = 'ng-invalid', |
||
PRISTINE_CLASS = 'ng-pristine', |
||
DIRTY_CLASS = 'ng-dirty'; |
||
|
||
/** |
||
* @ngdoc object |
||
* @name ng.directive:ngModel.NgModelController |
||
* |
||
* @property {string} $viewValue Actual string value in the view. |
||
* @property {*} $modelValue The value in the model, that the control is bound to. |
||
* @property {Array.<Function>} $parsers Array of functions to execute, as a pipeline, whenever |
||
the control reads value from the DOM. Each function is called, in turn, passing the value |
||
through to the next. Used to sanitize / convert the value as well as validation. |
||
For validation, the parsers should update the validity state using |
||
{@link ng.directive:ngModel.NgModelController#methods_$setValidity $setValidity()}, |
||
and return `undefined` for invalid values. |
||
|
||
* |
||
* @property {Array.<Function>} $formatters Array of functions to execute, as a pipeline, whenever |
||
the model value changes. Each function is called, in turn, passing the value through to the |
||
next. Used to format / convert values for display in the control and validation. |
||
* <pre> |
||
* function formatter(value) { |
||
* if (value) { |
||
* return value.toUpperCase(); |
||
* } |
||
* } |
||
* ngModel.$formatters.push(formatter); |
||
* </pre> |
||
* |
||
* @property {Array.<Function>} $viewChangeListeners Array of functions to execute whenever the |
||
* view value has changed. It is called with no arguments, and its return value is ignored. |
||
* This can be used in place of additional $watches against the model value. |
||
* |
||
* @property {Object} $error An object hash with all errors as keys. |
||
* |
||
* @property {boolean} $pristine True if user has not interacted with the control yet. |
||
* @property {boolean} $dirty True if user has already interacted with the control. |
||
* @property {boolean} $valid True if there is no error. |
||
* @property {boolean} $invalid True if at least one error on the control. |
||
* |
||
* @description |
||
* |
||
* `NgModelController` provides API for the `ng-model` directive. The controller contains |
||
* services for data-binding, validation, CSS updates, and value formatting and parsing. It |
||
* purposefully does not contain any logic which deals with DOM rendering or listening to |
||
* DOM events. Such DOM related logic should be provided by other directives which make use of |
||
* `NgModelController` for data-binding. |
||
* |
||
* ## Custom Control Example |
||
* This example shows how to use `NgModelController` with a custom control to achieve |
||
* data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`) |
||
* collaborate together to achieve the desired result. |
||
* |
||
* Note that `contenteditable` is an HTML5 attribute, which tells the browser to let the element |
||
* contents be edited in place by the user. This will not work on older browsers. |
||
* |
||
* <example module="customControl"> |
||
<file name="style.css"> |
||
[contenteditable] { |
||
border: 1px solid black; |
||
background-color: white; |
||
min-height: 20px; |
||
} |
||
|
||
.ng-invalid { |
||
border: 1px solid red; |
||
} |
||
|
||
</file> |
||
<file name="script.js"> |
||
angular.module('customControl', []). |
||
directive('contenteditable', function() { |
||
return { |
||
restrict: 'A', // only activate on element attribute |
||
require: '?ngModel', // get a hold of NgModelController |
||
link: function(scope, element, attrs, ngModel) { |
||
if(!ngModel) return; // do nothing if no ng-model |
||
|
||
// Specify how UI should be updated |
||
ngModel.$render = function() { |
||
element.html(ngModel.$viewValue || ''); |
||
}; |
||
|
||
// Listen for change events to enable binding |
||
element.on('blur keyup change', function() { |
||
scope.$apply(read); |
||
}); |
||
read(); // initialize |
||
|
||
// Write data to the model |
||
function read() { |
||
var html = element.html(); |
||
// When we clear the content editable the browser leaves a <br> behind |
||
// If strip-br attribute is provided then we strip this out |
||
if( attrs.stripBr && html == '<br>' ) { |
||
html = ''; |
||
} |
||
ngModel.$setViewValue(html); |
||
} |
||
} |
||
}; |
||
}); |
||
</file> |
||
<file name="index.html"> |
||
<form name="myForm"> |
||
<div contenteditable |
||
name="myWidget" ng-model="userContent" |
||
strip-br="true" |
||
required>Change me!</div> |
||
<span ng-show="myForm.myWidget.$error.required">Required!</span> |
||
<hr> |
||
<textarea ng-model="userContent"></textarea> |
||
</form> |
||
</file> |
||
<file name="scenario.js"> |
||
it('should data-bind and become invalid', function() { |
||
var contentEditable = element('[contenteditable]'); |
||
|
||
expect(contentEditable.text()).toEqual('Change me!'); |
||
input('userContent').enter(''); |
||
expect(contentEditable.text()).toEqual(''); |
||
expect(contentEditable.prop('className')).toMatch(/ng-invalid-required/); |
||
}); |
||
</file> |
||
* </example> |
||
* |
||
* |
||
*/ |
||
var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse', |
||
function($scope, $exceptionHandler, $attr, $element, $parse) { |
||
this.$viewValue = Number.NaN; |
||
this.$modelValue = Number.NaN; |
||
this.$parsers = []; |
||
this.$formatters = []; |
||
this.$viewChangeListeners = []; |
||
this.$pristine = true; |
||
this.$dirty = false; |
||
this.$valid = true; |
||
this.$invalid = false; |
||
this.$name = $attr.name; |
||
|
||
var ngModelGet = $parse($attr.ngModel), |
||
ngModelSet = ngModelGet.assign; |
||
|
||
if (!ngModelSet) { |
||
throw minErr('ngModel')('nonassign', "Expression '{0}' is non-assignable. Element: {1}", |
||
$attr.ngModel, startingTag($element)); |
||
} |
||
|
||
/** |
||
* @ngdoc function |
||
* @name ng.directive:ngModel.NgModelController#$render |
||
* @methodOf ng.directive:ngModel.NgModelController |
||
* |
||
* @description |
||
* Called when the view needs to be updated. It is expected that the user of the ng-model |
||
* directive will implement this method. |
||
*/ |
||
this.$render = noop; |
||
|
||
/** |
||
* @ngdoc function |
||
* @name { ng.directive:ngModel.NgModelController#$isEmpty |
||
* @methodOf ng.directive:ngModel.NgModelController |
||
* |
||
* @description |
||
* This is called when we need to determine if the value of the input is empty. |
||
* |
||
* For instance, the required directive does this to work out if the input has data or not. |
||
* The default `$isEmpty` function checks whether the value is `undefined`, `''`, `null` or `NaN`. |
||
* |
||
* You can override this for input directives whose concept of being empty is different to the |
||
* default. The `checkboxInputType` directive does this because in its case a value of `false` |
||
* implies empty. |
||
*/ |
||
this.$isEmpty = function(value) { |
||
return isUndefined(value) || value === '' || value === null || value !== value; |
||
}; |
||
|
||
var parentForm = $element.inheritedData('$formController') || nullFormCtrl, |
||
invalidCount = 0, // used to easily determine if we are valid |
||
$error = this.$error = {}; // keep invalid keys here |
||
|
||
|
||
// Setup initial state of the control |
||
$element.addClass(PRISTINE_CLASS); |
||
toggleValidCss(true); |
||
|
||
// convenience method for easy toggling of classes |
||
function toggleValidCss(isValid, validationErrorKey) { |
||
validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : ''; |
||
$element. |
||
removeClass((isValid ? INVALID_CLASS : VALID_CLASS) + validationErrorKey). |
||
addClass((isValid ? VALID_CLASS : INVALID_CLASS) + validationErrorKey); |
||
} |
||
|
||
/** |
||
* @ngdoc function |
||
* @name ng.directive:ngModel.NgModelController#$setValidity |
||
* @methodOf ng.directive:ngModel.NgModelController |
||
* |
||
* @description |
||
* Change the validity state, and notifies the form when the control changes validity. (i.e. it |
||
* does not notify form if given validator is already marked as invalid). |
||
* |
||
* This method should be called by validators - i.e. the parser or formatter functions. |
||
* |
||
* @param {string} validationErrorKey Name of the validator. the `validationErrorKey` will assign |
||
* to `$error[validationErrorKey]=isValid` so that it is available for data-binding. |
||
* The `validationErrorKey` should be in camelCase and will get converted into dash-case |
||
* for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error` |
||
* class and can be bound to as `{{someForm.someControl.$error.myError}}` . |
||
* @param {boolean} isValid Whether the current state is valid (true) or invalid (false). |
||
*/ |
||
this.$setValidity = function(validationErrorKey, isValid) { |
||
// Purposeful use of ! here to cast isValid to boolean in case it is undefined |
||
// jshint -W018 |
||
if ($error[validationErrorKey] === !isValid) return; |
||
// jshint +W018 |
||
|
||
if (isValid) { |
||
if ($error[validationErrorKey]) invalidCount--; |
||
if (!invalidCount) { |
||
toggleValidCss(true); |
||
this.$valid = true; |
||
this.$invalid = false; |
||
} |
||
} else { |
||
toggleValidCss(false); |
||
this.$invalid = true; |
||
this.$valid = false; |
||
invalidCount++; |
||
} |
||
|
||
$error[validationErrorKey] = !isValid; |
||
toggleValidCss(isValid, validationErrorKey); |
||
|
||
parentForm.$setValidity(validationErrorKey, isValid, this); |
||
}; |
||
|
||
/** |
||
* @ngdoc function |
||
* @name ng.directive:ngModel.NgModelController#$setPristine |
||
* @methodOf ng.directive:ngModel.NgModelController |
||
* |
||
* @description |
||
* Sets the control to its pristine state. |
||
* |
||
* This method can be called to remove the 'ng-dirty' class and set the control to its pristine |
||
* state (ng-pristine class). |
||
*/ |
||
this.$setPristine = function () { |
||
this.$dirty = false; |
||
this.$pristine = true; |
||
$element.removeClass(DIRTY_CLASS).addClass(PRISTINE_CLASS); |
||
}; |
||
|
||
/** |
||
* @ngdoc function |
||
* @name ng.directive:ngModel.NgModelController#$setViewValue |
||
* @methodOf ng.directive:ngModel.NgModelController |
||
* |
||
* @description |
||
* Update the view value. |
||
* |
||
* This method should be called when the view value changes, typically from within a DOM event handler. |
||
* For example {@link ng.directive:input input} and |
||
* {@link ng.directive:select select} directives call it. |
||
* |
||
* It will update the $viewValue, then pass this value through each of the functions in `$parsers`, |
||
* which includes any validators. The value that comes out of this `$parsers` pipeline, be applied to |
||
* `$modelValue` and the **expression** specified in the `ng-model` attribute. |
||
* |
||
* Lastly, all the registered change listeners, in the `$viewChangeListeners` list, are called. |
||
* |
||
* Note that calling this function does not trigger a `$digest`. |
||
* |
||
* @param {string} value Value from the view. |
||
*/ |
||
this.$setViewValue = function(value) { |
||
this.$viewValue = value; |
||
|
||
// change to dirty |
||
if (this.$pristine) { |
||
this.$dirty = true; |
||
this.$pristine = false; |
||
$element.removeClass(PRISTINE_CLASS).addClass(DIRTY_CLASS); |
||
parentForm.$setDirty(); |
||
} |
||
|
||
forEach(this.$parsers, function(fn) { |
||
value = fn(value); |
||
}); |
||
|
||
if (this.$modelValue !== value) { |
||
this.$modelValue = value; |
||
ngModelSet($scope, value); |
||
forEach(this.$viewChangeListeners, function(listener) { |
||
try { |
||
listener(); |
||
} catch(e) { |
||
$exceptionHandler(e); |
||
} |
||
}); |
||
} |
||
}; |
||
|
||
// model -> value |
||
var ctrl = this; |
||
|
||
$scope.$watch(function ngModelWatch() { |
||
var value = ngModelGet($scope); |
||
|
||
// if scope model value and ngModel value are out of sync |
||
if (ctrl.$modelValue !== value) { |
||
|
||
var formatters = ctrl.$formatters, |
||
idx = formatters.length; |
||
|
||
ctrl.$modelValue = value; |
||
while(idx--) { |
||
value = formatters[idx](value); |
||
} |
||
|
||
if (ctrl.$viewValue !== value) { |
||
ctrl.$viewValue = value; |
||
ctrl.$render(); |
||
} |
||
} |
||
|
||
return value; |
||
}); |
||
}]; |
||
|
||
|
||
/** |
||
* @ngdoc directive |
||
* @name ng.directive:ngModel |
||
* |
||
* @element input |
||
* |
||
* @description |
||
* The `ngModel` directive binds an `input`,`select`, `textarea` (or custom form control) to a |
||
* property on the scope using {@link ng.directive:ngModel.NgModelController NgModelController}, |
||
* which is created and exposed by this directive. |
||
* |
||
* `ngModel` is responsible for: |
||
* |
||
* - Binding the view into the model, which other directives such as `input`, `textarea` or `select` |
||
* require. |
||
* - Providing validation behavior (i.e. required, number, email, url). |
||
* - Keeping the state of the control (valid/invalid, dirty/pristine, validation errors). |
||
* - Setting related css classes on the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`). |
||
* - Registering the control with its parent {@link ng.directive:form form}. |
||
* |
||
* Note: `ngModel` will try to bind to the property given by evaluating the expression on the |
||
* current scope. If the property doesn't already exist on this scope, it will be created |
||
* implicitly and added to the scope. |
||
* |
||
* For best practices on using `ngModel`, see: |
||
* |
||
* - {@link https://github.com/angular/angular.js/wiki/Understanding-Scopes} |
||
* |
||
* For basic examples, how to use `ngModel`, see: |
||
* |
||
* - {@link ng.directive:input input} |
||
* - {@link ng.directive:input.text text} |
||
* - {@link ng.directive:input.checkbox checkbox} |
||
* - {@link ng.directive:input.radio radio} |
||
* - {@link ng.directive:input.number number} |
||
* - {@link ng.directive:input.email email} |
||
* - {@link ng.directive:input.url url} |
||
* - {@link ng.directive:select select} |
||
* - {@link ng.directive:textarea textarea} |
||
* |
||
*/ |
||
var ngModelDirective = function() { |
||
return { |
||
require: ['ngModel', '^?form'], |
||
controller: NgModelController, |
||
link: function(scope, element, attr, ctrls) { |
||
// notify others, especially parent forms |
||
|
||
var modelCtrl = ctrls[0], |
||
formCtrl = ctrls[1] || nullFormCtrl; |
||
|
||
formCtrl.$addControl(modelCtrl); |
||
|
||
scope.$on('$destroy', function() { |
||
formCtrl.$removeControl(modelCtrl); |
||
}); |
||
} |
||
}; |
||
}; |
||
|
||
|
||
/** |
||
* @ngdoc directive |
||
* @name ng.directive:ngChange |
||
* |
||
* @description |
||
* Evaluate given expression when user changes the input. |
||
* The expression is not evaluated when the value change is coming from the model. |
||
* |
||
* Note, this directive requires `ngModel` to be present. |
||
* |
||
* @element input |
||
* @param {expression} ngChange {@link guide/expression Expression} to evaluate upon change |
||
* in input value. |
||
* |
||
* @example |
||
* <doc:example> |
||
* <doc:source> |
||
* <script> |
||
* function Controller($scope) { |
||
* $scope.counter = 0; |
||
* $scope.change = function() { |
||
* $scope.counter++; |
||
* }; |
||
* } |
||
* </script> |
||
* <div ng-controller="Controller"> |
||
* <input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" /> |
||
* <input type="checkbox" ng-model="confirmed" id="ng-change-example2" /> |
||
* <label for="ng-change-example2">Confirmed</label><br /> |
||
* debug = {{confirmed}}<br /> |
||
* counter = {{counter}} |
||
* </div> |
||
* </doc:source> |
||
* <doc:scenario> |
||
* it('should evaluate the expression if changing from view', function() { |
||
* expect(binding('counter')).toEqual('0'); |
||
* element('#ng-change-example1').click(); |
||
* expect(binding('counter')).toEqual('1'); |
||
* expect(binding('confirmed')).toEqual('true'); |
||
* }); |
||
* |
||
* it('should not evaluate the expression if changing from model', function() { |
||
* element('#ng-change-example2').click(); |
||
* expect(binding('counter')).toEqual('0'); |
||
* expect(binding('confirmed')).toEqual('true'); |
||
* }); |
||
* </doc:scenario> |
||
* </doc:example> |
||
*/ |
||
var ngChangeDirective = valueFn({ |
||
require: 'ngModel', |
||
link: function(scope, element, attr, ctrl) { |
||
ctrl.$viewChangeListeners.push(function() { |
||
scope.$eval(attr.ngChange); |
||
}); |
||
} |
||
}); |
||
|
||
|
||
var requiredDirective = function() { |
||
return { |
||
require: '?ngModel', |
||
link: function(scope, elm, attr, ctrl) { |
||
if (!ctrl) return; |
||
attr.required = true; // force truthy in case we are on non input element |
||
|
||
var validator = function(value) { |
||
if (attr.required && ctrl.$isEmpty(value)) { |
||
ctrl.$setValidity('required', false); |
||
return; |
||
} else { |
||
ctrl.$setValidity('required', true); |
||
return value; |
||
} |
||
}; |
||
|
||
ctrl.$formatters.push(validator); |
||
ctrl.$parsers.unshift(validator); |
||
|
||
attr.$observe('required', function() { |
||
validator(ctrl.$viewValue); |
||
}); |
||
} |
||
}; |
||
}; |
||
|
||
|
||
/** |
||
* @ngdoc directive |
||
* @name ng.directive:ngList |
||
* |
||
* @description |
||
* Text input that converts between a delimited string and an array of strings. The delimiter |
||
* can be a fixed string (by default a comma) or a regular expression. |
||
* |
||
* @element input |
||
* @param {string=} ngList optional delimiter that should be used to split the value. If |
||
* specified in form `/something/` then the value will be converted into a regular expression. |
||
* |
||
* @example |
||
<doc:example> |
||
<doc:source> |
||
<script> |
||
function Ctrl($scope) { |
||
$scope.names = ['igor', 'misko', 'vojta']; |
||
} |
||
</script> |
||
<form name="myForm" ng-controller="Ctrl"> |
||
List: <input name="namesInput" ng-model="names" ng-list required> |
||
<span class="error" ng-show="myForm.namesInput.$error.required"> |
||
Required!</span> |
||
<br> |
||
<tt>names = {{names}}</tt><br/> |
||
<tt>myForm.namesInput.$valid = {{myForm.namesInput.$valid}}</tt><br/> |
||
<tt>myForm.namesInput.$error = {{myForm.namesInput.$error}}</tt><br/> |
||
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/> |
||
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> |
||
</form> |
||
</doc:source> |
||
<doc:scenario> |
||
it('should initialize to model', function() { |
||
expect(binding('names')).toEqual('["igor","misko","vojta"]'); |
||
expect(binding('myForm.namesInput.$valid')).toEqual('true'); |
||
expect(element('span.error').css('display')).toBe('none'); |
||
}); |
||
|
||
it('should be invalid if empty', function() { |
||
input('names').enter(''); |
||
expect(binding('names')).toEqual(''); |
||
expect(binding('myForm.namesInput.$valid')).toEqual('false'); |
||
expect(element('span.error').css('display')).not().toBe('none'); |
||
}); |
||
</doc:scenario> |
||
</doc:example> |
||
*/ |
||
var ngListDirective = function() { |
||
return { |
||
require: 'ngModel', |
||
link: function(scope, element, attr, ctrl) { |
||
var match = /\/(.*)\//.exec(attr.ngList), |
||
separator = match && new RegExp(match[1]) || attr.ngList || ','; |
||
|
||
var parse = function(viewValue) { |
||
// If the viewValue is invalid (say required but empty) it will be `undefined` |
||
if (isUndefined(viewValue)) return; |
||
|
||
var list = []; |
||
|
||
if (viewValue) { |
||
forEach(viewValue.split(separator), function(value) { |
||
if (value) list.push(trim(value)); |
||
}); |
||
} |
||
|
||
return list; |
||
}; |
||
|
||
ctrl.$parsers.push(parse); |
||
ctrl.$formatters.push(function(value) { |
||
if (isArray(value)) { |
||
return value.join(', '); |
||
} |
||
|
||
return undefined; |
||
}); |
||
|
||
// Override the standard $isEmpty because an empty array means the input is empty. |
||
ctrl.$isEmpty = function(value) { |
||
return !value || !value.length; |
||
}; |
||
} |
||
}; |
||
}; |
||
|
||
|
||
var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/; |
||
/** |
||
* @ngdoc directive |
||
* @name ng.directive:ngValue |
||
* |
||
* @description |
||
* Binds the given expression to the value of `input[select]` or `input[radio]`, so |
||
* that when the element is selected, the `ngModel` of that element is set to the |
||
* bound value. |
||
* |
||
* `ngValue` is useful when dynamically generating lists of radio buttons using `ng-repeat`, as |
||
* shown below. |
||
* |
||
* @element input |
||
* @param {string=} ngValue angular expression, whose value will be bound to the `value` attribute |
||
* of the `input` element |
||
* |
||
* @example |
||
<doc:example> |
||
<doc:source> |
||
<script> |
||
function Ctrl($scope) { |
||
$scope.names = ['pizza', 'unicorns', 'robots']; |
||
$scope.my = { favorite: 'unicorns' }; |
||
} |
||
</script> |
||
<form ng-controller="Ctrl"> |
||
<h2>Which is your favorite?</h2> |
||
<label ng-repeat="name in names" for="{{name}}"> |
||
{{name}} |
||
<input type="radio" |
||
ng-model="my.favorite" |
||
ng-value="name" |
||
id="{{name}}" |
||
name="favorite"> |
||
</label> |
||
<div>You chose {{my.favorite}}</div> |
||
</form> |
||
</doc:source> |
||
<doc:scenario> |
||
it('should initialize to model', function() { |
||
expect(binding('my.favorite')).toEqual('unicorns'); |
||
}); |
||
it('should bind the values to the inputs', function() { |
||
input('my.favorite').select('pizza'); |
||
expect(binding('my.favorite')).toEqual('pizza'); |
||
}); |
||
</doc:scenario> |
||
</doc:example> |
||
*/ |
||
var ngValueDirective = function() { |
||
return { |
||
priority: 100, |
||
compile: function(tpl, tplAttr) { |
||
if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) { |
||
return function ngValueConstantLink(scope, elm, attr) { |
||
attr.$set('value', scope.$eval(attr.ngValue)); |
||
}; |
||
} else { |
||
return function ngValueLink(scope, elm, attr) { |
||
scope.$watch(attr.ngValue, function valueWatchAction(value) { |
||
attr.$set('value', value); |
||
}); |
||
}; |
||
} |
||
} |
||
}; |
||
}; |
||
|
||
/** |
||
* @ngdoc directive |
||
* @name ng.directive:ngBind |
||
* @restrict AC |
||
* |
||
* @description |
||
* The `ngBind` attribute tells Angular to replace the text content of the specified HTML element |
||
* with the value of a given expression, and to update the text content when the value of that |
||
* expression changes. |
||
* |
||
* Typically, you don't use `ngBind` directly, but instead you use the double curly markup like |
||
* `{{ expression }}` which is similar but less verbose. |
||
* |
||
* It is preferrable to use `ngBind` instead of `{{ expression }}` when a template is momentarily |
||
* displayed by the browser in its raw state before Angular compiles it. Since `ngBind` is an |
||
* element attribute, it makes the bindings invisible to the user while the page is loading. |
||
* |
||
* An alternative solution to this problem would be using the |
||
* {@link ng.directive:ngCloak ngCloak} directive. |
||
* |
||
* |
||
* @element ANY |
||
* @param {expression} ngBind {@link guide/expression Expression} to evaluate. |
||
* |
||
* @example |
||
* Enter a name in the Live Preview text box; the greeting below the text box changes instantly. |
||
<doc:example> |
||
<doc:source> |
||
<script> |
||
function Ctrl($scope) { |
||
$scope.name = 'Whirled'; |
||
} |
||
</script> |
||
<div ng-controller="Ctrl"> |
||
Enter name: <input type="text" ng-model="name"><br> |
||
Hello <span ng-bind="name"></span>! |
||
</div> |
||
</doc:source> |
||
<doc:scenario> |
||
it('should check ng-bind', function() { |
||
expect(using('.doc-example-live').binding('name')).toBe('Whirled'); |
||
using('.doc-example-live').input('name').enter('world'); |
||
expect(using('.doc-example-live').binding('name')).toBe('world'); |
||
}); |
||
</doc:scenario> |
||
</doc:example> |
||
*/ |
||
var ngBindDirective = ngDirective(function(scope, element, attr) { |
||
element.addClass('ng-binding').data('$binding', attr.ngBind); |
||
scope.$watch(attr.ngBind, function ngBindWatchAction(value) { |
||
// We are purposefully using == here rather than === because we want to |
||
// catch when value is "null or undefined" |
||
// jshint -W041 |
||
element.text(value == undefined ? '' : value); |
||
}); |
||
}); |
||
|
||
|
||
/** |
||
* @ngdoc directive |
||
* @name ng.directive:ngBindTemplate |
||
* |
||
* @description |
||
* The `ngBindTemplate` directive specifies that the element |
||
* text content should be replaced with the interpolation of the template |
||
* in the `ngBindTemplate` attribute. |
||
* Unlike `ngBind`, the `ngBindTemplate` can contain multiple `{{` `}}` |
||
* expressions. This directive is needed since some HTML elements |
||
* (such as TITLE and OPTION) cannot contain SPAN elements. |
||
* |
||
* @element ANY |
||
* @param {string} ngBindTemplate template of form |
||
* <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval. |
||
* |
||
* @example |
||
* Try it here: enter text in text box and watch the greeting change. |
||
<doc:example> |
||
<doc:source> |
||
<script> |
||
function Ctrl($scope) { |
||
$scope.salutation = 'Hello'; |
||
$scope.name = 'World'; |
||
} |
||
</script> |
||
<div ng-controller="Ctrl"> |
||
Salutation: <input type="text" ng-model="salutation"><br> |
||
Name: <input type="text" ng-model="name"><br> |
||
<pre ng-bind-template="{{salutation}} {{name}}!"></pre> |
||
</div> |
||
</doc:source> |
||
<doc:scenario> |
||
it('should check ng-bind', function() { |
||
expect(using('.doc-example-live').binding('salutation')). |
||
toBe('Hello'); |
||
expect(using('.doc-example-live').binding('name')). |
||
toBe('World'); |
||
using('.doc-example-live').input('salutation').enter('Greetings'); |
||
using('.doc-example-live').input('name').enter('user'); |
||
expect(using('.doc-example-live').binding('salutation')). |
||
toBe('Greetings'); |
||
expect(using('.doc-example-live').binding('name')). |
||
toBe('user'); |
||
}); |
||
</doc:scenario> |
||
</doc:example> |
||
*/ |
||
var ngBindTemplateDirective = ['$interpolate', function($interpolate) { |
||
return function(scope, element, attr) { |
||
// TODO: move this to scenario runner |
||
var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate)); |
||
element.addClass('ng-binding').data('$binding', interpolateFn); |
||
attr.$observe('ngBindTemplate', function(value) { |
||
element.text(value); |
||
}); |
||
}; |
||
}]; |
||
|
||
|
||
/** |
||
* @ngdoc directive |
||
* @name ng.directive:ngBindHtml |
||
* |
||
* @description |
||
* Creates a binding that will innerHTML the result of evaluating the `expression` into the current |
||
* element in a secure way. By default, the innerHTML-ed content will be sanitized using the {@link |
||
* ngSanitize.$sanitize $sanitize} service. To utilize this functionality, ensure that `$sanitize` |
||
* is available, for example, by including {@link ngSanitize} in your module's dependencies (not in |
||
* core Angular.) You may also bypass sanitization for values you know are safe. To do so, bind to |
||
* an explicitly trusted value via {@link ng.$sce#methods_trustAsHtml $sce.trustAsHtml}. See the example |
||
* under {@link ng.$sce#Example Strict Contextual Escaping (SCE)}. |
||
* |
||
* Note: If a `$sanitize` service is unavailable and the bound value isn't explicitly trusted, you |
||
* will have an exception (instead of an exploit.) |
||
* |
||
* @element ANY |
||
* @param {expression} ngBindHtml {@link guide/expression Expression} to evaluate. |
||
* |
||
* @example |
||
Try it here: enter text in text box and watch the greeting change. |
||
|
||
<example module="ngBindHtmlExample" deps="angular-sanitize.js"> |
||
<file name="index.html"> |
||
<div ng-controller="ngBindHtmlCtrl"> |
||
<p ng-bind-html="myHTML"></p> |
||
</div> |
||
</file> |
||
|
||
<file name="script.js"> |
||
angular.module('ngBindHtmlExample', ['ngSanitize']) |
||
|
||
.controller('ngBindHtmlCtrl', ['$scope', function ngBindHtmlCtrl($scope) { |
||
$scope.myHTML = |
||
'I am an <code>HTML</code>string with <a href="#">links!</a> and other <em>stuff</em>'; |
||
}]); |
||
</file> |
||
|
||
<file name="scenario.js"> |
||
it('should check ng-bind-html', function() { |
||
expect(using('.doc-example-live').binding('myHTML')). |
||
toBe( |
||
'I am an <code>HTML</code>string with <a href="#">links!</a> and other <em>stuff</em>' |
||
); |
||
}); |
||
</file> |
||
</example> |
||
*/ |
||
var ngBindHtmlDirective = ['$sce', '$parse', function($sce, $parse) { |
||
return function(scope, element, attr) { |
||
element.addClass('ng-binding').data('$binding', attr.ngBindHtml); |
||
|
||
var parsed = $parse(attr.ngBindHtml); |
||
function getStringValue() { return (parsed(scope) || '').toString(); } |
||
|
||
scope.$watch(getStringValue, function ngBindHtmlWatchAction(value) { |
||
element.html($sce.getTrustedHtml(parsed(scope)) || ''); |
||
}); |
||
}; |
||
}]; |
||
|
||
function classDirective(name, selector) { |
||
name = 'ngClass' + name; |
||
return function() { |
||
return { |
||
restrict: 'AC', |
||
link: function(scope, element, attr) { |
||
var oldVal; |
||
|
||
scope.$watch(attr[name], ngClassWatchAction, true); |
||
|
||
attr.$observe('class', function(value) { |
||
ngClassWatchAction(scope.$eval(attr[name])); |
||
}); |
||
|
||
|
||
if (name !== 'ngClass') { |
||
scope.$watch('$index', function($index, old$index) { |
||
// jshint bitwise: false |
||
var mod = $index & 1; |
||
if (mod !== old$index & 1) { |
||
var classes = flattenClasses(scope.$eval(attr[name])); |
||
mod === selector ? |
||
attr.$addClass(classes) : |
||
attr.$removeClass(classes); |
||
} |
||
}); |
||
} |
||
|
||
|
||
function ngClassWatchAction(newVal) { |
||
if (selector === true || scope.$index % 2 === selector) { |
||
var newClasses = flattenClasses(newVal || ''); |
||
if(!oldVal) { |
||
attr.$addClass(newClasses); |
||
} else if(!equals(newVal,oldVal)) { |
||
attr.$updateClass(newClasses, flattenClasses(oldVal)); |
||
} |
||
} |
||
oldVal = copy(newVal); |
||
} |
||
|
||
|
||
function flattenClasses(classVal) { |
||
if(isArray(classVal)) { |
||
return classVal.join(' '); |
||
} else if (isObject(classVal)) { |
||
var classes = [], i = 0; |
||
forEach(classVal, function(v, k) { |
||
if (v) { |
||
classes.push(k); |
||
} |
||
}); |
||
return classes.join(' '); |
||
} |
||
|
||
return classVal; |
||
} |
||
} |
||
}; |
||
}; |
||
} |
||
|
||
/** |
||
* @ngdoc directive |
||
* @name ng.directive:ngClass |
||
* @restrict AC |
||
* |
||
* @description |
||
* The `ngClass` directive allows you to dynamically set CSS classes on an HTML element by databinding |
||
* an expression that represents all classes to be added. |
||
* |
||
* The directive won't add duplicate classes if a particular class was already set. |
||
* |
||
* When the expression changes, the previously added classes are removed and only then the |
||
* new classes are added. |
||
* |
||
* @animations |
||
* add - happens just before the class is applied to the element |
||
* remove - happens just before the class is removed from the element |
||
* |
||
* @element ANY |
||
* @param {expression} ngClass {@link guide/expression Expression} to eval. The result |
||
* of the evaluation can be a string representing space delimited class |
||
* names, an array, or a map of class names to boolean values. In the case of a map, the |
||
* names of the properties whose values are truthy will be added as css classes to the |
||
* element. |
||
* |
||
* @example Example that demonstrates basic bindings via ngClass directive. |
||
<example> |
||
<file name="index.html"> |
||
<p ng-class="{strike: deleted, bold: important, red: error}">Map Syntax Example</p> |
||
<input type="checkbox" ng-model="deleted"> deleted (apply "strike" class)<br> |
||
<input type="checkbox" ng-model="important"> important (apply "bold" class)<br> |
||
<input type="checkbox" ng-model="error"> error (apply "red" class) |
||
<hr> |
||
<p ng-class="style">Using String Syntax</p> |
||
<input type="text" ng-model="style" placeholder="Type: bold strike red"> |
||
<hr> |
||
<p ng-class="[style1, style2, style3]">Using Array Syntax</p> |
||
<input ng-model="style1" placeholder="Type: bold, strike or red"><br> |
||
<input ng-model="style2" placeholder="Type: bold, strike or red"><br> |
||
<input ng-model="style3" placeholder="Type: bold, strike or red"><br> |
||
</file> |
||
<file name="style.css"> |
||
.strike { |
||
text-decoration: line-through; |
||
} |
||
.bold { |
||
font-weight: bold; |
||
} |
||
.red { |
||
color: red; |
||
} |
||
</file> |
||
<file name="scenario.js"> |
||
it('should let you toggle the class', function() { |
||
|
||
expect(element('.doc-example-live p:first').prop('className')).not().toMatch(/bold/); |
||
expect(element('.doc-example-live p:first').prop('className')).not().toMatch(/red/); |
||
|
||
input('important').check(); |
||
expect(element('.doc-example-live p:first').prop('className')).toMatch(/bold/); |
||
|
||
input('error').check(); |
||
expect(element('.doc-example-live p:first').prop('className')).toMatch(/red/); |
||
}); |
||
|
||
it('should let you toggle string example', function() { |
||
expect(element('.doc-example-live p:nth-of-type(2)').prop('className')).toBe(''); |
||
input('style').enter('red'); |
||
expect(element('.doc-example-live p:nth-of-type(2)').prop('className')).toBe('red'); |
||
}); |
||
|
||
it('array example should have 3 classes', function() { |
||
expect(element('.doc-example-live p:last').prop('className')).toBe(''); |
||
input('style1').enter('bold'); |
||
input('style2').enter('strike'); |
||
input('style3').enter('red'); |
||
expect(element('.doc-example-live p:last').prop('className')).toBe('bold strike red'); |
||
}); |
||
</file> |
||
</example> |
||
|
||
## Animations |
||
|
||
The example below demonstrates how to perform animations using ngClass. |
||
|
||
<example animations="true"> |
||
<file name="index.html"> |
||
<input type="button" value="set" ng-click="myVar='my-class'"> |
||
<input type="button" value="clear" ng-click="myVar=''"> |
||
<br> |
||
<span class="base-class" ng-class="myVar">Sample Text</span> |
||
</file> |
||
<file name="style.css"> |
||
.base-class { |
||
-webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; |
||
transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; |
||
} |
||
|
||
.base-class.my-class { |
||
color: red; |
||
font-size:3em; |
||
} |
||
</file> |
||
<file name="scenario.js"> |
||
it('should check ng-class', function() { |
||
expect(element('.doc-example-live span').prop('className')).not(). |
||
toMatch(/my-class/); |
||
|
||
using('.doc-example-live').element(':button:first').click(); |
||
|
||
expect(element('.doc-example-live span').prop('className')). |
||
toMatch(/my-class/); |
||
|
||
using('.doc-example-live').element(':button:last').click(); |
||
|
||
expect(element('.doc-example-live span').prop('className')).not(). |
||
toMatch(/my-class/); |
||
}); |
||
</file> |
||
</example> |
||
|
||
|
||
## ngClass and pre-existing CSS3 Transitions/Animations |
||
The ngClass directive still supports CSS3 Transitions/Animations even if they do not follow the ngAnimate CSS naming structure. |
||
Upon animation ngAnimate will apply supplementary CSS classes to track the start and end of an animation, but this will not hinder |
||
any pre-existing CSS transitions already on the element. To get an idea of what happens during a class-based animation, be sure |
||
to view the step by step details of {@link ngAnimate.$animate#methods_addclass $animate.addClass} and |
||
{@link ngAnimate.$animate#methods_removeclass $animate.removeClass}. |
||
*/ |
||
var ngClassDirective = classDirective('', true); |
||
|
||
/** |
||
* @ngdoc directive |
||
* @name ng.directive:ngClassOdd |
||
* @restrict AC |
||
* |
||
* @description |
||
* The `ngClassOdd` and `ngClassEven` directives work exactly as |
||
* {@link ng.directive:ngClass ngClass}, except they work in |
||
* conjunction with `ngRepeat` and take effect only on odd (even) rows. |
||
* |
||
* This directive can be applied only within the scope of an |
||
* {@link ng.directive:ngRepeat ngRepeat}. |
||
* |
||
* @element ANY |
||
* @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result |
||
* of the evaluation can be a string representing space delimited class names or an array. |
||
* |
||
* @example |
||
<example> |
||
<file name="index.html"> |
||
<ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']"> |
||
<li ng-repeat="name in names"> |
||
<span ng-class-odd="'odd'" ng-class-even="'even'"> |
||
{{name}} |
||
</span> |
||
</li> |
||
</ol> |
||
</file> |
||
<file name="style.css"> |
||
.odd { |
||
color: red; |
||
} |
||
.even { |
||
color: blue; |
||
} |
||
</file> |
||
<file name="scenario.js"> |
||
it('should check ng-class-odd and ng-class-even', function() { |
||
expect(element('.doc-example-live li:first span').prop('className')). |
||
toMatch(/odd/); |
||
expect(element('.doc-example-live li:last span').prop('className')). |
||
toMatch(/even/); |
||
}); |
||
</file> |
||
</example> |
||
*/ |
||
var ngClassOddDirective = classDirective('Odd', 0); |
||
|
||
/** |
||
* @ngdoc directive |
||
* @name ng.directive:ngClassEven |
||
* @restrict AC |
||
* |
||
* @description |
||
* The `ngClassOdd` and `ngClassEven` directives work exactly as |
||
* {@link ng.directive:ngClass ngClass}, except they work in |
||
* conjunction with `ngRepeat` and take effect only on odd (even) rows. |
||
* |
||
* This directive can be applied only within the scope of an |
||
* {@link ng.directive:ngRepeat ngRepeat}. |
||
* |
||
* @element ANY |
||
* @param {expression} ngClassEven {@link guide/expression Expression} to eval. The |
||
* result of the evaluation can be a string representing space delimited class names or an array. |
||
* |
||
* @example |
||
<example> |
||
<file name="index.html"> |
||
<ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']"> |
||
<li ng-repeat="name in names"> |
||
<span ng-class-odd="'odd'" ng-class-even="'even'"> |
||
{{name}} |
||
</span> |
||
</li> |
||
</ol> |
||
</file> |
||
<file name="style.css"> |
||
.odd { |
||
color: red; |
||
} |
||
.even { |
||
color: blue; |
||
} |
||
</file> |
||
<file name="scenario.js"> |
||
it('should check ng-class-odd and ng-class-even', function() { |
||
expect(element('.doc-example-live li:first span').prop('className')). |
||
toMatch(/odd/); |
||
expect(element('.doc-example-live li:last span').prop('className')). |
||
toMatch(/even/); |
||
}); |
||
</file> |
||
</example> |
||
*/ |
||
var ngClassEvenDirective = classDirective('Even', 1); |
||
|
||
/** |
||
* @ngdoc directive |
||
* @name ng.directive:ngCloak |
||
* @restrict AC |
||
* |
||
* @description |
||
* The `ngCloak` directive is used to prevent the Angular html template from being briefly |
||
* displayed by the browser in its raw (uncompiled) form while your application is loading. Use this |
||
* directive to avoid the undesirable flicker effect caused by the html template display. |
||
* |
||
* The directive can be applied to the `<body>` element, but the preferred usage is to apply |
||
* multiple `ngCloak` directives to small portions of the page to permit progressive rendering |
||
* of the browser view. |
||
* |
||
* `ngCloak` works in cooperation with the following css rule embedded within `angular.js` and |
||
* `angular.min.js`. |
||
* For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}). |
||
* |
||
* <pre> |
||
* [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak { |
||
* display: none !important; |
||
* } |
||
* </pre> |
||
* |
||
* When this css rule is loaded by the browser, all html elements (including their children) that |
||
* are tagged with the `ngCloak` directive are hidden. When Angular encounters this directive |
||
* during the compilation of the template it deletes the `ngCloak` element attribute, making |
||
* the compiled element visible. |
||
* |
||
* For the best result, the `angular.js` script must be loaded in the head section of the html |
||
* document; alternatively, the css rule above must be included in the external stylesheet of the |
||
* application. |
||
* |
||
* Legacy browsers, like IE7, do not provide attribute selector support (added in CSS 2.1) so they |
||
* cannot match the `[ng\:cloak]` selector. To work around this limitation, you must add the css |
||
* class `ng-cloak` in addition to the `ngCloak` directive as shown in the example below. |
||
* |
||
* @element ANY |
||
* |
||
* @example |
||
<doc:example> |
||
<doc:source> |
||
<div id="template1" ng-cloak>{{ 'hello' }}</div> |
||
<div id="template2" ng-cloak class="ng-cloak">{{ 'hello IE7' }}</div> |
||
</doc:source> |
||
<doc:scenario> |
||
it('should remove the template directive and css class', function() { |
||
expect(element('.doc-example-live #template1').attr('ng-cloak')). |
||
not().toBeDefined(); |
||
expect(element('.doc-example-live #template2').attr('ng-cloak')). |
||
not().toBeDefined(); |
||
}); |
||
</doc:scenario> |
||
</doc:example> |
||
* |
||
*/ |
||
var ngCloakDirective = ngDirective({ |
||
compile: function(element, attr) { |
||
attr.$set('ngCloak', undefined); |
||
element.removeClass('ng-cloak'); |
||
} |
||
}); |
||
|
||
/** |
||
* @ngdoc directive |
||
* @name ng.directive:ngController |
||
* |
||
* @description |
||
* The `ngController` directive attaches a controller class to the view. This is a key aspect of how angular |
||
* supports the principles behind the Model-View-Controller design pattern. |
||
* |
||
* MVC components in angular: |
||
* |
||
* * Model — The Model is scope properties; scopes are attached to the DOM where scope properties |
||
* are accessed through bindings. |
||
* * View — The template (HTML with data bindings) that is rendered into the View. |
||
* * Controller — The `ngController` directive specifies a Controller class; the class contains business |
||
* logic behind the application to decorate the scope with functions and values |
||
* |
||
* Note that you can also attach controllers to the DOM by declaring it in a route definition |
||
* via the {@link ngRoute.$route $route} service. A common mistake is to declare the controller |
||
* again using `ng-controller` in the template itself. This will cause the controller to be attached |
||
* and executed twice. |
||
* |
||
* @element ANY |
||
* @scope |
||
* @param {expression} ngController Name of a globally accessible constructor function or an |
||
* {@link guide/expression expression} that on the current scope evaluates to a |
||
* constructor function. The controller instance can be published into a scope property |
||
* by specifying `as propertyName`. |
||
* |
||
* @example |
||
* Here is a simple form for editing user contact information. Adding, removing, clearing, and |
||
* greeting are methods declared on the controller (see source tab). These methods can |
||
* easily be called from the angular markup. Notice that the scope becomes the `this` for the |
||
* controller's instance. This allows for easy access to the view data from the controller. Also |
||
* notice that any changes to the data are automatically reflected in the View without the need |
||
* for a manual update. The example is shown in two different declaration styles you may use |
||
* according to preference. |
||
<doc:example> |
||
<doc:source> |
||
<script> |
||
function SettingsController1() { |
||
this.name = "John Smith"; |
||
this.contacts = [ |
||
{type: 'phone', value: '408 555 1212'}, |
||
{type: 'email', value: '[email protected]'} ]; |
||
}; |
||
|
||
SettingsController1.prototype.greet = function() { |
||
alert(this.name); |
||
}; |
||
|
||
SettingsController1.prototype.addContact = function() { |
||
this.contacts.push({type: 'email', value: '[email protected]'}); |
||
}; |
||
|
||
SettingsController1.prototype.removeContact = function(contactToRemove) { |
||
var index = this.contacts.indexOf(contactToRemove); |
||
this.contacts.splice(index, 1); |
||
}; |
||
|
||
SettingsController1.prototype.clearContact = function(contact) { |
||
contact.type = 'phone'; |
||
contact.value = ''; |
||
}; |
||
</script> |
||
<div id="ctrl-as-exmpl" ng-controller="SettingsController1 as settings"> |
||
Name: <input type="text" ng-model="settings.name"/> |
||
[ <a href="" ng-click="settings.greet()">greet</a> ]<br/> |
||
Contact: |
||
<ul> |
||
<li ng-repeat="contact in settings.contacts"> |
||
<select ng-model="contact.type"> |
||
<option>phone</option> |
||
<option>email</option> |
||
</select> |
||
<input type="text" ng-model="contact.value"/> |
||
[ <a href="" ng-click="settings.clearContact(contact)">clear</a> |
||
| <a href="" ng-click="settings.removeContact(contact)">X</a> ] |
||
</li> |
||
<li>[ <a href="" ng-click="settings.addContact()">add</a> ]</li> |
||
</ul> |
||
</div> |
||
</doc:source> |
||
<doc:scenario> |
||
it('should check controller as', function() { |
||
expect(element('#ctrl-as-exmpl>:input').val()).toBe('John Smith'); |
||
expect(element('#ctrl-as-exmpl li:nth-child(1) input').val()) |
||
.toBe('408 555 1212'); |
||
expect(element('#ctrl-as-exmpl li:nth-child(2) input').val()) |
||
.toBe('[email protected]'); |
||
|
||
element('#ctrl-as-exmpl li:first a:contains("clear")').click(); |
||
expect(element('#ctrl-as-exmpl li:first input').val()).toBe(''); |
||
|
||
element('#ctrl-as-exmpl li:last a:contains("add")').click(); |
||
expect(element('#ctrl-as-exmpl li:nth-child(3) input').val()) |
||
.toBe('[email protected]'); |
||
}); |
||
</doc:scenario> |
||
</doc:example> |
||
<doc:example> |
||
<doc:source> |
||
<script> |
||
function SettingsController2($scope) { |
||
$scope.name = "John Smith"; |
||
$scope.contacts = [ |
||
{type:'phone', value:'408 555 1212'}, |
||
{type:'email', value:'[email protected]'} ]; |
||
|
||
$scope.greet = function() { |
||
alert(this.name); |
||
}; |
||
|
||
$scope.addContact = function() { |
||
this.contacts.push({type:'email', value:'[email protected]'}); |
||
}; |
||
|
||
$scope.removeContact = function(contactToRemove) { |
||
var index = this.contacts.indexOf(contactToRemove); |
||
this.contacts.splice(index, 1); |
||
}; |
||
|
||
$scope.clearContact = function(contact) { |
||
contact.type = 'phone'; |
||
contact.value = ''; |
||
}; |
||
} |
||
</script> |
||
<div id="ctrl-exmpl" ng-controller="SettingsController2"> |
||
Name: <input type="text" ng-model="name"/> |
||
[ <a href="" ng-click="greet()">greet</a> ]<br/> |
||
Contact: |
||
<ul> |
||
<li ng-repeat="contact in contacts"> |
||
<select ng-model="contact.type"> |
||
<option>phone</option> |
||
<option>email</option> |
||
</select> |
||
<input type="text" ng-model="contact.value"/> |
||
[ <a href="" ng-click="clearContact(contact)">clear</a> |
||
| <a href="" ng-click="removeContact(contact)">X</a> ] |
||
</li> |
||
<li>[ <a href="" ng-click="addContact()">add</a> ]</li> |
||
</ul> |
||
</div> |
||
</doc:source> |
||
<doc:scenario> |
||
it('should check controller', function() { |
||
expect(element('#ctrl-exmpl>:input').val()).toBe('John Smith'); |
||
expect(element('#ctrl-exmpl li:nth-child(1) input').val()) |
||
.toBe('408 555 1212'); |
||
expect(element('#ctrl-exmpl li:nth-child(2) input').val()) |
||
.toBe('[email protected]'); |
||
|
||
element('#ctrl-exmpl li:first a:contains("clear")').click(); |
||
expect(element('#ctrl-exmpl li:first input').val()).toBe(''); |
||
|
||
element('#ctrl-exmpl li:last a:contains("add")').click(); |
||
expect(element('#ctrl-exmpl li:nth-child(3) input').val()) |
||
.toBe('[email protected]'); |
||
}); |
||
</doc:scenario> |
||
</doc:example> |
||
|
||
*/ |
||
var ngControllerDirective = [function() { |
||
return { |
||
scope: true, |
||
controller: '@', |
||
priority: 500 |
||
}; |
||
}]; |
||
|
||
/** |
||
* @ngdoc directive |
||
* @name ng.directive:ngCsp |
||
* |
||
* @element html |
||
* @description |
||
* Enables [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) support. |
||
* |
||
* This is necessary when developing things like Google Chrome Extensions. |
||
* |
||
* CSP forbids apps to use `eval` or `Function(string)` generated functions (among other things). |
||
* For us to be compatible, we just need to implement the "getterFn" in $parse without violating |
||
* any of these restrictions. |
||
* |
||
* AngularJS uses `Function(string)` generated functions as a speed optimization. Applying the `ngCsp` |
||
* directive will cause Angular to use CSP compatibility mode. When this mode is on AngularJS will |
||
* evaluate all expressions up to 30% slower than in non-CSP mode, but no security violations will |
||
* be raised. |
||
* |
||
* CSP forbids JavaScript to inline stylesheet rules. In non CSP mode Angular automatically |
||
* includes some CSS rules (e.g. {@link ng.directive:ngCloak ngCloak}). |
||
* To make those directives work in CSP mode, include the `angular-csp.css` manually. |
||
* |
||
* In order to use this feature put the `ngCsp` directive on the root element of the application. |
||
* |
||
* *Note: This directive is only available in the `ng-csp` and `data-ng-csp` attribute form.* |
||
* |
||
* @example |
||
* This example shows how to apply the `ngCsp` directive to the `html` tag. |
||
<pre> |
||
<!doctype html> |
||
<html ng-app ng-csp> |
||
... |
||
... |
||
</html> |
||
</pre> |
||
*/ |
||
|
||
// ngCsp is not implemented as a proper directive any more, because we need it be processed while we bootstrap |
||
// the system (before $parse is instantiated), for this reason we just have a csp() fn that looks for ng-csp attribute |
||
// anywhere in the current doc |
||
|
||
/** |
||
* @ngdoc directive |
||
* @name ng.directive:ngClick |
||
* |
||
* @description |
||
* The ngClick directive allows you to specify custom behavior when |
||
* an element is clicked. |
||
* |
||
* @element ANY |
||
* @param {expression} ngClick {@link guide/expression Expression} to evaluate upon |
||
* click. (Event object is available as `$event`) |
||
* |
||
* @example |
||
<doc:example> |
||
<doc:source> |
||
<button ng-click="count = count + 1" ng-init="count=0"> |
||
Increment |
||
</button> |
||
count: {{count}} |
||
</doc:source> |
||
<doc:protractor> |
||
it('should check ng-click', function() { |
||
expect(element(by.binding('count')).getText()).toMatch('0'); |
||
element(by.css('.doc-example-live button')).click(); |
||
expect(element(by.binding('count')).getText()).toMatch('1'); |
||
}); |
||
</doc:protractor> |
||
</doc:example> |
||
*/ |
||
/* |
||
* A directive that allows creation of custom onclick handlers that are defined as angular |
||
* expressions and are compiled and executed within the current scope. |
||
* |
||
* Events that are handled via these handler are always configured not to propagate further. |
||
*/ |
||
var ngEventDirectives = {}; |
||
forEach( |
||
'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' '), |
||
function(name) { |
||
var directiveName = directiveNormalize('ng-' + name); |
||
ngEventDirectives[directiveName] = ['$parse', function($parse) { |
||
return { |
||
compile: function($element, attr) { |
||
var fn = $parse(attr[directiveName]); |
||
return function(scope, element, attr) { |
||
element.on(lowercase(name), function(event) { |
||
scope.$apply(function() { |
||
fn(scope, {$event:event}); |
||
}); |
||
}); |
||
}; |
||
} |
||
}; |
||
}]; |
||
} |
||
); |
||
|
||
/** |
||
* @ngdoc directive |
||
* @name ng.directive:ngDblclick |
||
* |
||
* @description |
||
* The `ngDblclick` directive allows you to specify custom behavior on a dblclick event. |
||
* |
||
* @element ANY |
||
* @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon |
||
* a dblclick. (The Event object is available as `$event`) |
||
* |
||
* @example |
||
<doc:example> |
||
<doc:source> |
||
<button ng-dblclick="count = count + 1" ng-init="count=0"> |
||
Increment (on double click) |
||
</button> |
||
count: {{count}} |
||
</doc:source> |
||
</doc:example> |
||
*/ |
||
|
||
|
||
/** |
||
* @ngdoc directive |
||
* @name ng.directive:ngMousedown |
||
* |
||
* @description |
||
* The ngMousedown directive allows you to specify custom behavior on mousedown event. |
||
* |
||
* @element ANY |
||
* @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon |
||
* mousedown. (Event object is available as `$event`) |
||
* |
||
* @example |
||
<doc:example> |
||
<doc:source> |
||
<button ng-mousedown="count = count + 1" ng-init="count=0"> |
||
Increment (on mouse down) |
||
</button> |
||
count: {{count}} |
||
</doc:source> |
||
</doc:example> |
||
*/ |
||
|
||
|
||
/** |
||
* @ngdoc directive |
||
* @name ng.directive:ngMouseup |
||
* |
||
* @description |
||
* Specify custom behavior on mouseup event. |
||
* |
||
* @element ANY |
||
* @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon |
||
* mouseup. (Event object is available as `$event`) |
||
* |
||
* @example |
||
<doc:example> |
||
<doc:source> |
||
<button ng-mouseup="count = count + 1" ng-init="count=0"> |
||
Increment (on mouse up) |
||
</button> |
||
count: {{count}} |
||
</doc:source> |
||
</doc:example> |
||
*/ |
||
|
||
/** |
||
* @ngdoc directive |
||
* @name ng.directive:ngMouseover |
||
* |
||
* @description |
||
* Specify custom behavior on mouseover event. |
||
* |
||
* @element ANY |
||
* @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon |
||
* mouseover. (Event object is available as `$event`) |
||
* |
||
* @example |
||
<doc:example> |
||
<doc:source> |
||
<button ng-mouseover="count = count + 1" ng-init="count=0"> |
||
Increment (when mouse is over) |
||
</button> |
||
count: {{count}} |
||
</doc:source> |
||
</doc:example> |
||
*/ |
||
|
||
|
||
/** |
||
* @ngdoc directive |
||
* @name ng.directive:ngMouseenter |
||
* |
||
* @description |
||
* Specify custom behavior on mouseenter event. |
||
* |
||
* @element ANY |
||
* @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon |
||
* mouseenter. (Event object is available as `$event`) |
||
* |
||
* @example |
||
<doc:example> |
||
<doc:source> |
||
<button ng-mouseenter="count = count + 1" ng-init="count=0"> |
||
Increment (when mouse enters) |
||
</button> |
||
count: {{count}} |
||
</doc:source> |
||
</doc:example> |
||
*/ |
||
|
||
|
||
/** |
||
* @ngdoc directive |
||
* @name ng.directive:ngMouseleave |
||
* |
||
* @description |
||
* Specify custom behavior on mouseleave event. |
||
* |
||
* @element ANY |
||
* @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon |
||
* mouseleave. (Event object is available as `$event`) |
||
* |
||
* @example |
||
<doc:example> |
||
<doc:source> |
||
<button ng-mouseleave="count = count + 1" ng-init="count=0"> |
||
Increment (when mouse leaves) |
||
</button> |
||
count: {{count}} |
||
</doc:source> |
||
</doc:example> |
||
*/ |
||
|
||
|
||
/** |
||
* @ngdoc directive |
||
* @name ng.directive:ngMousemove |
||
* |
||
* @description |
||
* Specify custom behavior on mousemove event. |
||
* |
||
* @element ANY |
||
* @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon |
||
* mousemove. (Event object is available as `$event`) |
||
* |
||
* @example |
||
<doc:example> |
||
<doc:source> |
||
<button ng-mousemove="count = count + 1" ng-init="count=0"> |
||
Increment (when mouse moves) |
||
</button> |
||
count: {{count}} |
||
</doc:source> |
||
</doc:example> |
||
*/ |
||
|
||
|
||
/** |
||
* @ngdoc directive |
||
* @name ng.directive:ngKeydown |
||
* |
||
* @description |
||
* Specify custom behavior on keydown event. |
||
* |
||
* @element ANY |
||
* @param {expression} ngKeydown {@link guide/expression Expression} to evaluate upon |
||
* keydown. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.) |
||
* |
||
* @example |
||
<doc:example> |
||
<doc:source> |
||
<input ng-keydown="count = count + 1" ng-init="count=0"> |
||
key down count: {{count}} |
||
</doc:source> |
||
</doc:example> |
||
*/ |
||
|
||
|
||
/** |
||
* @ngdoc directive |
||
* @name ng.directive:ngKeyup |
||
* |
||
* @description |
||
* Specify custom behavior on keyup event. |
||
* |
||
* @element ANY |
||
* @param {expression} ngKeyup {@link guide/expression Expression} to evaluate upon |
||
* keyup. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.) |
||
* |
||
* @example |
||
<doc:example> |
||
<doc:source> |
||
<input ng-keyup="count = count + 1" ng-init="count=0"> |
||
key up count: {{count}} |
||
</doc:source> |
||
</doc:example> |
||
*/ |
||
|
||
|
||
/** |
||
* @ngdoc directive |
||
* @name ng.directive:ngKeypress |
||
* |
||
* @description |
||
* Specify custom behavior on keypress event. |
||
* |
||
* @element ANY |
||
* @param {expression} ngKeypress {@link guide/expression Expression} to evaluate upon |
||
* keypress. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.) |
||
* |
||
* @example |
||
<doc:example> |
||
<doc:source> |
||
<input ng-keypress="count = count + 1" ng-init="count=0"> |
||
key press count: {{count}} |
||
</doc:source> |
||
</doc:example> |
||
*/ |
||
|
||
|
||
/** |
||
* @ngdoc directive |
||
* @name ng.directive:ngSubmit |
||
* |
||
* @description |
||
* Enables binding angular expressions to onsubmit events. |
||
* |
||
* Additionally it prevents the default action (which for form means sending the request to the |
||
* server and reloading the current page) **but only if the form does not contain an `action` |
||
* attribute**. |
||
* |
||
* @element form |
||
* @param {expression} ngSubmit {@link guide/expression Expression} to eval. (Event object is available as `$event`) |
||
* |
||
* @example |
||
<doc:example> |
||
<doc:source> |
||
<script> |
||
function Ctrl($scope) { |
||
$scope.list = []; |
||
$scope.text = 'hello'; |
||
$scope.submit = function() { |
||
if (this.text) { |
||
this.list.push(this.text); |
||
this.text = ''; |
||
} |
||
}; |
||
} |
||
</script> |
||
<form ng-submit="submit()" ng-controller="Ctrl"> |
||
Enter text and hit enter: |
||
<input type="text" ng-model="text" name="text" /> |
||
<input type="submit" id="submit" value="Submit" /> |
||
<pre>list={{list}}</pre> |
||
</form> |
||
</doc:source> |
||
<doc:scenario> |
||
it('should check ng-submit', function() { |
||
expect(binding('list')).toBe('[]'); |
||
element('.doc-example-live #submit').click(); |
||
expect(binding('list')).toBe('["hello"]'); |
||
expect(input('text').val()).toBe(''); |
||
}); |
||
it('should ignore empty strings', function() { |
||
expect(binding('list')).toBe('[]'); |
||
element('.doc-example-live #submit').click(); |
||
element('.doc-example-live #submit').click(); |
||
expect(binding('list')).toBe('["hello"]'); |
||
}); |
||
</doc:scenario> |
||
</doc:example> |
||
*/ |
||
|
||
/** |
||
* @ngdoc directive |
||
* @name ng.directive:ngFocus |
||
* |
||
* @description |
||
* Specify custom behavior on focus event. |
||
* |
||
* @element window, input, select, textarea, a |
||
* @param {expression} ngFocus {@link guide/expression Expression} to evaluate upon |
||
* focus. (Event object is available as `$event`) |
||
* |
||
* @example |
||
* See {@link ng.directive:ngClick ngClick} |
||
*/ |
||
|
||
/** |
||
* @ngdoc directive |
||
* @name ng.directive:ngBlur |
||
* |
||
* @description |
||
* Specify custom behavior on blur event. |
||
* |
||
* @element window, input, select, textarea, a |
||
* @param {expression} ngBlur {@link guide/expression Expression} to evaluate upon |
||
* blur. (Event object is available as `$event`) |
||
* |
||
* @example |
||
* See {@link ng.directive:ngClick ngClick} |
||
*/ |
||
|
||
/** |
||
* @ngdoc directive |
||
* @name ng.directive:ngCopy |
||
* |
||
* @description |
||
* Specify custom behavior on copy event. |
||
* |
||
* @element window, input, select, textarea, a |
||
* @param {expression} ngCopy {@link guide/expression Expression} to evaluate upon |
||
* copy. (Event object is available as `$event`) |
||
* |
||
* @example |
||
<doc:example> |
||
<doc:source> |
||
<input ng-copy="copied=true" ng-init="copied=false; value='copy me'" ng-model="value"> |
||
copied: {{copied}} |
||
</doc:source> |
||
</doc:example> |
||
*/ |
||
|
||
/** |
||
* @ngdoc directive |
||
* @name ng.directive:ngCut |
||
* |
||
* @description |
||
* Specify custom behavior on cut event. |
||
* |
||
* @element window, input, select, textarea, a |
||
* @param {expression} ngCut {@link guide/expression Expression} to evaluate upon |
||
* cut. (Event object is available as `$event`) |
||
* |
||
* @example |
||
<doc:example> |
||
<doc:source> |
||
<input ng-cut="cut=true" ng-init="cut=false; value='cut me'" ng-model="value"> |
||
cut: {{cut}} |
||
</doc:source> |
||
</doc:example> |
||
*/ |
||
|
||
/** |
||
* @ngdoc directive |
||
* @name ng.directive:ngPaste |
||
* |
||
* @description |
||
* Specify custom behavior on paste event. |
||
* |
||
* @element window, input, select, textarea, a |
||
* @param {expression} ngPaste {@link guide/expression Expression} to evaluate upon |
||
* paste. (Event object is available as `$event`) |
||
* |
||
* @example |
||
<doc:example> |
||
<doc:source> |
||
<input ng-paste="paste=true" ng-init="paste=false" placeholder='paste here'> |
||
pasted: {{paste}} |
||
</doc:source> |
||
</doc:example> |
||
*/ |
||
|
||
/** |
||
* @ngdoc directive |
||
* @name ng.directive:ngIf |
||
* @restrict A |
||
* |
||
* @description |
||
* The `ngIf` directive removes or recreates a portion of the DOM tree based on an |
||
* {expression}. If the expression assigned to `ngIf` evaluates to a false |
||
* value then the element is removed from the DOM, otherwise a clone of the |
||
* element is reinserted into the DOM. |
||
* |
||
* `ngIf` differs from `ngShow` and `ngHide` in that `ngIf` completely removes and recreates the |
||
* element in the DOM rather than changing its visibility via the `display` css property. A common |
||
* case when this difference is significant is when using css selectors that rely on an element's |
||
* position within the DOM, such as the `:first-child` or `:last-child` pseudo-classes. |
||
* |
||
* Note that when an element is removed using `ngIf` its scope is destroyed and a new scope |
||
* is created when the element is restored. The scope created within `ngIf` inherits from |
||
* its parent scope using |
||
* {@link https://github.com/angular/angular.js/wiki/The-Nuances-of-Scope-Prototypal-Inheritance prototypal inheritance}. |
||
* An important implication of this is if `ngModel` is used within `ngIf` to bind to |
||
* a javascript primitive defined in the parent scope. In this case any modifications made to the |
||
* variable within the child scope will override (hide) the value in the parent scope. |
||
* |
||
* Also, `ngIf` recreates elements using their compiled state. An example of this behavior |
||
* is if an element's class attribute is directly modified after it's compiled, using something like |
||
* jQuery's `.addClass()` method, and the element is later removed. When `ngIf` recreates the element |
||
* the added class will be lost because the original compiled state is used to regenerate the element. |
||
* |
||
* Additionally, you can provide animations via the `ngAnimate` module to animate the `enter` |
||
* and `leave` effects. |
||
* |
||
* @animations |
||
* enter - happens just after the ngIf contents change and a new DOM element is created and injected into the ngIf container |
||
* leave - happens just before the ngIf contents are removed from the DOM |
||
* |
||
* @element ANY |
||
* @scope |
||
* @priority 600 |
||
* @param {expression} ngIf If the {@link guide/expression expression} is falsy then |
||
* the element is removed from the DOM tree. If it is truthy a copy of the compiled |
||
* element is added to the DOM tree. |
||
* |
||
* @example |
||
<example animations="true"> |
||
<file name="index.html"> |
||
Click me: <input type="checkbox" ng-model="checked" ng-init="checked=true" /><br/> |
||
Show when checked: |
||
<span ng-if="checked" class="animate-if"> |
||
I'm removed when the checkbox is unchecked. |
||
</span> |
||
</file> |
||
<file name="animations.css"> |
||
.animate-if { |
||
background:white; |
||
border:1px solid black; |
||
padding:10px; |
||
} |
||
|
||
.animate-if.ng-enter, .animate-if.ng-leave { |
||
-webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; |
||
transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; |
||
} |
||
|
||
.animate-if.ng-enter, |
||
.animate-if.ng-leave.ng-leave-active { |
||
opacity:0; |
||
} |
||
|
||
.animate-if.ng-leave, |
||
.animate-if.ng-enter.ng-enter-active { |
||
opacity:1; |
||
} |
||
</file> |
||
</example> |
||
*/ |
||
var ngIfDirective = ['$animate', function($animate) { |
||
return { |
||
transclude: 'element', |
||
priority: 600, |
||
terminal: true, |
||
restrict: 'A', |
||
$$tlb: true, |
||
link: function ($scope, $element, $attr, ctrl, $transclude) { |
||
var block, childScope; |
||
$scope.$watch($attr.ngIf, function ngIfWatchAction(value) { |
||
|
||
if (toBoolean(value)) { |
||
if (!childScope) { |
||
childScope = $scope.$new(); |
||
$transclude(childScope, function (clone) { |
||
clone[clone.length++] = document.createComment(' end ngIf: ' + $attr.ngIf + ' '); |
||
// Note: We only need the first/last node of the cloned nodes. |
||
// However, we need to keep the reference to the jqlite wrapper as it might be changed later |
||
// by a directive with templateUrl when it's template arrives. |
||
block = { |
||
clone: clone |
||
}; |
||
$animate.enter(clone, $element.parent(), $element); |
||
}); |
||
} |
||
} else { |
||
|
||
if (childScope) { |
||
childScope.$destroy(); |
||
childScope = null; |
||
} |
||
|
||
if (block) { |
||
$animate.leave(getBlockElements(block.clone)); |
||
block = null; |
||
} |
||
} |
||
}); |
||
} |
||
}; |
||
}]; |
||
|
||
/** |
||
* @ngdoc directive |
||
* @name ng.directive:ngInclude |
||
* @restrict ECA |
||
* |
||
* @description |
||
* Fetches, compiles and includes an external HTML fragment. |
||
* |
||
* By default, the template URL is restricted to the same domain and protocol as the |
||
* application document. This is done by calling {@link ng.$sce#methods_getTrustedResourceUrl |
||
* $sce.getTrustedResourceUrl} on it. To load templates from other domains or protocols |
||
* you may either {@link ng.$sceDelegateProvider#methods_resourceUrlWhitelist whitelist them} or |
||
* {@link ng.$sce#methods_trustAsResourceUrl wrap them} as trusted values. Refer to Angular's {@link |
||
* ng.$sce Strict Contextual Escaping}. |
||
* |
||
* In addition, the browser's |
||
* {@link https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest |
||
* Same Origin Policy} and {@link http://www.w3.org/TR/cors/ Cross-Origin Resource Sharing |
||
* (CORS)} policy may further restrict whether the template is successfully loaded. |
||
* For example, `ngInclude` won't work for cross-domain requests on all browsers and for `file://` |
||
* access on some browsers. |
||
* |
||
* @animations |
||
* enter - animation is used to bring new content into the browser. |
||
* leave - animation is used to animate existing content away. |
||
* |
||
* The enter and leave animation occur concurrently. |
||
* |
||
* @scope |
||
* @priority 400 |
||
* |
||
* @param {string} ngInclude|src angular expression evaluating to URL. If the source is a string constant, |
||
* make sure you wrap it in quotes, e.g. `src="'myPartialTemplate.html'"`. |
||
* @param {string=} onload Expression to evaluate when a new partial is loaded. |
||
* |
||
* @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll |
||
* $anchorScroll} to scroll the viewport after the content is loaded. |
||
* |
||
* - If the attribute is not set, disable scrolling. |
||
* - If the attribute is set without value, enable scrolling. |
||
* - Otherwise enable scrolling only if the expression evaluates to truthy value. |
||
* |
||
* @example |
||
<example animations="true"> |
||
<file name="index.html"> |
||
<div ng-controller="Ctrl"> |
||
<select ng-model="template" ng-options="t.name for t in templates"> |
||
<option value="">(blank)</option> |
||
</select> |
||
url of the template: <tt>{{template.url}}</tt> |
||
<hr/> |
||
<div class="slide-animate-container"> |
||
<div class="slide-animate" ng-include="template.url"></div> |
||
</div> |
||
</div> |
||
</file> |
||
<file name="script.js"> |
||
function Ctrl($scope) { |
||
$scope.templates = |
||
[ { name: 'template1.html', url: 'template1.html'} |
||
, { name: 'template2.html', url: 'template2.html'} ]; |
||
$scope.template = $scope.templates[0]; |
||
} |
||
</file> |
||
<file name="template1.html"> |
||
Content of template1.html |
||
</file> |
||
<file name="template2.html"> |
||
Content of template2.html |
||
</file> |
||
<file name="animations.css"> |
||
.slide-animate-container { |
||
position:relative; |
||
background:white; |
||
border:1px solid black; |
||
height:40px; |
||
overflow:hidden; |
||
} |
||
|
||
.slide-animate { |
||
padding:10px; |
||
} |
||
|
||
.slide-animate.ng-enter, .slide-animate.ng-leave { |
||
-webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; |
||
transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; |
||
|
||
position:absolute; |
||
top:0; |
||
left:0; |
||
right:0; |
||
bottom:0; |
||
display:block; |
||
padding:10px; |
||
} |
||
|
||
.slide-animate.ng-enter { |
||
top:-50px; |
||
} |
||
.slide-animate.ng-enter.ng-enter-active { |
||
top:0; |
||
} |
||
|
||
.slide-animate.ng-leave { |
||
top:0; |
||
} |
||
.slide-animate.ng-leave.ng-leave-active { |
||
top:50px; |
||
} |
||
</file> |
||
<file name="scenario.js"> |
||
it('should load template1.html', function() { |
||
expect(element('.doc-example-live [ng-include]').text()). |
||
toMatch(/Content of template1.html/); |
||
}); |
||
it('should load template2.html', function() { |
||
select('template').option('1'); |
||
expect(element('.doc-example-live [ng-include]').text()). |
||
toMatch(/Content of template2.html/); |
||
}); |
||
it('should change to blank', function() { |
||
select('template').option(''); |
||
expect(element('.doc-example-live [ng-include]')).toBe(undefined); |
||
}); |
||
</file> |
||
</example> |
||
*/ |
||
|
||
|
||
/** |
||
* @ngdoc event |
||
* @name ng.directive:ngInclude#$includeContentRequested |
||
* @eventOf ng.directive:ngInclude |
||
* @eventType emit on the scope ngInclude was declared in |
||
* @description |
||
* Emitted every time the ngInclude content is requested. |
||
*/ |
||
|
||
|
||
/** |
||
* @ngdoc event |
||
* @name ng.directive:ngInclude#$includeContentLoaded |
||
* @eventOf ng.directive:ngInclude |
||
* @eventType emit on the current ngInclude scope |
||
* @description |
||
* Emitted every time the ngInclude content is reloaded. |
||
*/ |
||
var ngIncludeDirective = ['$http', '$templateCache', '$anchorScroll', '$animate', '$sce', |
||
function($http, $templateCache, $anchorScroll, $animate, $sce) { |
||
return { |
||
restrict: 'ECA', |
||
priority: 400, |
||
terminal: true, |
||
transclude: 'element', |
||
controller: angular.noop, |
||
compile: function(element, attr) { |
||
var srcExp = attr.ngInclude || attr.src, |
||
onloadExp = attr.onload || '', |
||
autoScrollExp = attr.autoscroll; |
||
|
||
return function(scope, $element, $attr, ctrl, $transclude) { |
||
var changeCounter = 0, |
||
currentScope, |
||
currentElement; |
||
|
||
var cleanupLastIncludeContent = function() { |
||
if (currentScope) { |
||
currentScope.$destroy(); |
||
currentScope = null; |
||
} |
||
if(currentElement) { |
||
$animate.leave(currentElement); |
||
currentElement = null; |
||
} |
||
}; |
||
|
||
scope.$watch($sce.parseAsResourceUrl(srcExp), function ngIncludeWatchAction(src) { |
||
var afterAnimation = function() { |
||
if (isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) { |
||
$anchorScroll(); |
||
} |
||
}; |
||
var thisChangeId = ++changeCounter; |
||
|
||
if (src) { |
||
$http.get(src, {cache: $templateCache}).success(function(response) { |
||
if (thisChangeId !== changeCounter) return; |
||
var newScope = scope.$new(); |
||
ctrl.template = response; |
||
|
||
// Note: This will also link all children of ng-include that were contained in the original |
||
// html. If that content contains controllers, ... they could pollute/change the scope. |
||
// However, using ng-include on an element with additional content does not make sense... |
||
// Note: We can't remove them in the cloneAttchFn of $transclude as that |
||
// function is called before linking the content, which would apply child |
||
// directives to non existing elements. |
||
var clone = $transclude(newScope, function(clone) { |
||
cleanupLastIncludeContent(); |
||
$animate.enter(clone, null, $element, afterAnimation); |
||
}); |
||
|
||
currentScope = newScope; |
||
currentElement = clone; |
||
|
||
currentScope.$emit('$includeContentLoaded'); |
||
scope.$eval(onloadExp); |
||
}).error(function() { |
||
if (thisChangeId === changeCounter) cleanupLastIncludeContent(); |
||
}); |
||
scope.$emit('$includeContentRequested'); |
||
} else { |
||
cleanupLastIncludeContent(); |
||
ctrl.template = null; |
||
} |
||
}); |
||
}; |
||
} |
||
}; |
||
}]; |
||
|
||
// This directive is called during the $transclude call of the first `ngInclude` directive. |
||
// It will replace and compile the content of the element with the loaded template. |
||
// We need this directive so that the element content is already filled when |
||
// the link function of another directive on the same element as ngInclude |
||
// is called. |
||
var ngIncludeFillContentDirective = ['$compile', |
||
function($compile) { |
||
return { |
||
restrict: 'ECA', |
||
priority: -400, |
||
require: 'ngInclude', |
||
link: function(scope, $element, $attr, ctrl) { |
||
$element.html(ctrl.template); |
||
$compile($element.contents())(scope); |
||
} |
||
}; |
||
}]; |
||
|
||
/** |
||
* @ngdoc directive |
||
* @name ng.directive:ngInit |
||
* @restrict AC |
||
* |
||
* @description |
||
* The `ngInit` directive allows you to evaluate an expression in the |
||
* current scope. |
||
* |
||
* <div class="alert alert-error"> |
||
* The only appropriate use of `ngInit` is for aliasing special properties of |
||
* {@link api/ng.directive:ngRepeat `ngRepeat`}, as seen in the demo below. Besides this case, you |
||
* should use {@link guide/controller controllers} rather than `ngInit` |
||
* to initialize values on a scope. |
||
* </div> |
||
* |
||
* @priority 450 |
||
* |
||
* @element ANY |
||
* @param {expression} ngInit {@link guide/expression Expression} to eval. |
||
* |
||
* @example |
||
<doc:example> |
||
<doc:source> |
||
<script> |
||
function Ctrl($scope) { |
||
$scope.list = [['a', 'b'], ['c', 'd']]; |
||
} |
||
</script> |
||
<div ng-controller="Ctrl"> |
||
<div ng-repeat="innerList in list" ng-init="outerIndex = $index"> |
||
<div ng-repeat="value in innerList" ng-init="innerIndex = $index"> |
||
<span class="example-init">list[ {{outerIndex}} ][ {{innerIndex}} ] = {{value}};</span> |
||
</div> |
||
</div> |
||
</div> |
||
</doc:source> |
||
<doc:scenario> |
||
it('should alias index positions', function() { |
||
expect(element('.example-init').text()) |
||
.toBe('list[ 0 ][ 0 ] = a;' + |
||
'list[ 0 ][ 1 ] = b;' + |
||
'list[ 1 ][ 0 ] = c;' + |
||
'list[ 1 ][ 1 ] = d;'); |
||
}); |
||
</doc:scenario> |
||
</doc:example> |
||
*/ |
||
var ngInitDirective = ngDirective({ |
||
priority: 450, |
||
compile: function() { |
||
return { |
||
pre: function(scope, element, attrs) { |
||
scope.$eval(attrs.ngInit); |
||
} |
||
}; |
||
} |
||
}); |
||
|
||
/** |
||
* @ngdoc directive |
||
* @name ng.directive:ngNonBindable |
||
* @restrict AC |
||
* @priority 1000 |
||
* |
||
* @description |
||
* The `ngNonBindable` directive tells Angular not to compile or bind the contents of the current |
||
* DOM element. This is useful if the element contains what appears to be Angular directives and |
||
* bindings but which should be ignored by Angular. This could be the case if you have a site that |
||
* displays snippets of code, for instance. |
||
* |
||
* @element ANY |
||
* |
||
* @example |
||
* In this example there are two locations where a simple interpolation binding (`{{}}`) is present, |
||
* but the one wrapped in `ngNonBindable` is left alone. |
||
* |
||
* @example |
||
<doc:example> |
||
<doc:source> |
||
<div>Normal: {{1 + 2}}</div> |
||
<div ng-non-bindable>Ignored: {{1 + 2}}</div> |
||
</doc:source> |
||
<doc:scenario> |
||
it('should check ng-non-bindable', function() { |
||
expect(using('.doc-example-live').binding('1 + 2')).toBe('3'); |
||
expect(using('.doc-example-live').element('div:last').text()). |
||
toMatch(/1 \+ 2/); |
||
}); |
||
</doc:scenario> |
||
</doc:example> |
||
*/ |
||
var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 }); |
||
|
||
/** |
||
* @ngdoc directive |
||
* @name ng.directive:ngPluralize |
||
* @restrict EA |
||
* |
||
* @description |
||
* # Overview |
||
* `ngPluralize` is a directive that displays messages according to en-US localization rules. |
||
* These rules are bundled with angular.js, but can be overridden |
||
* (see {@link guide/i18n Angular i18n} dev guide). You configure ngPluralize directive |
||
* by specifying the mappings between |
||
* {@link http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html |
||
* plural categories} and the strings to be displayed. |
||
* |
||
* # Plural categories and explicit number rules |
||
* There are two |
||
* {@link http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html |
||
* plural categories} in Angular's default en-US locale: "one" and "other". |
||
* |
||
* While a plural category may match many numbers (for example, in en-US locale, "other" can match |
||
* any number that is not 1), an explicit number rule can only match one number. For example, the |
||
* explicit number rule for "3" matches the number 3. There are examples of plural categories |
||
* and explicit number rules throughout the rest of this documentation. |
||
* |
||
* # Configuring ngPluralize |
||
* You configure ngPluralize by providing 2 attributes: `count` and `when`. |
||
* You can also provide an optional attribute, `offset`. |
||
* |
||
* The value of the `count` attribute can be either a string or an {@link guide/expression |
||
* Angular expression}; these are evaluated on the current scope for its bound value. |
||
* |
||
* The `when` attribute specifies the mappings between plural categories and the actual |
||
* string to be displayed. The value of the attribute should be a JSON object. |
||
* |
||
* The following example shows how to configure ngPluralize: |
||
* |
||
* <pre> |
||
* <ng-pluralize count="personCount" |
||
when="{'0': 'Nobody is viewing.', |
||
* 'one': '1 person is viewing.', |
||
* 'other': '{} people are viewing.'}"> |
||
* </ng-pluralize> |
||
*</pre> |
||
* |
||
* In the example, `"0: Nobody is viewing."` is an explicit number rule. If you did not |
||
* specify this rule, 0 would be matched to the "other" category and "0 people are viewing" |
||
* would be shown instead of "Nobody is viewing". You can specify an explicit number rule for |
||
* other numbers, for example 12, so that instead of showing "12 people are viewing", you can |
||
* show "a dozen people are viewing". |
||
* |
||
* You can use a set of closed braces (`{}`) as a placeholder for the number that you want substituted |
||
* into pluralized strings. In the previous example, Angular will replace `{}` with |
||
* <span ng-non-bindable>`{{personCount}}`</span>. The closed braces `{}` is a placeholder |
||
* for <span ng-non-bindable>{{numberExpression}}</span>. |
||
* |
||
* # Configuring ngPluralize with offset |
||
* The `offset` attribute allows further customization of pluralized text, which can result in |
||
* a better user experience. For example, instead of the message "4 people are viewing this document", |
||
* you might display "John, Kate and 2 others are viewing this document". |
||
* The offset attribute allows you to offset a number by any desired value. |
||
* Let's take a look at an example: |
||
* |
||
* <pre> |
||
* <ng-pluralize count="personCount" offset=2 |
||
* when="{'0': 'Nobody is viewing.', |
||
* '1': '{{person1}} is viewing.', |
||
* '2': '{{person1}} and {{person2}} are viewing.', |
||
* 'one': '{{person1}}, {{person2}} and one other person are viewing.', |
||
* 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}"> |
||
* </ng-pluralize> |
||
* </pre> |
||
* |
||
* Notice that we are still using two plural categories(one, other), but we added |
||
* three explicit number rules 0, 1 and 2. |
||
* When one person, perhaps John, views the document, "John is viewing" will be shown. |
||
* When three people view the document, no explicit number rule is found, so |
||
* an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category. |
||
* In this case, plural category 'one' is matched and "John, Marry and one other person are viewing" |
||
* is shown. |
||
* |
||
* Note that when you specify offsets, you must provide explicit number rules for |
||
* numbers from 0 up to and including the offset. If you use an offset of 3, for example, |
||
* you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for |
||
* plural categories "one" and "other". |
||
* |
||
* @param {string|expression} count The variable to be bounded to. |
||
* @param {string} when The mapping between plural category to its corresponding strings. |
||
* @param {number=} offset Offset to deduct from the total number. |
||
* |
||
* @example |
||
<doc:example> |
||
<doc:source> |
||
<script> |
||
function Ctrl($scope) { |
||
$scope.person1 = 'Igor'; |
||
$scope.person2 = 'Misko'; |
||
$scope.personCount = 1; |
||
} |
||
</script> |
||
<div ng-controller="Ctrl"> |
||
Person 1:<input type="text" ng-model="person1" value="Igor" /><br/> |
||
Person 2:<input type="text" ng-model="person2" value="Misko" /><br/> |
||
Number of People:<input type="text" ng-model="personCount" value="1" /><br/> |
||
|
||
<!--- Example with simple pluralization rules for en locale ---> |
||
Without Offset: |
||
<ng-pluralize count="personCount" |
||
when="{'0': 'Nobody is viewing.', |
||
'one': '1 person is viewing.', |
||
'other': '{} people are viewing.'}"> |
||
</ng-pluralize><br> |
||
|
||
<!--- Example with offset ---> |
||
With Offset(2): |
||
<ng-pluralize count="personCount" offset=2 |
||
when="{'0': 'Nobody is viewing.', |
||
'1': '{{person1}} is viewing.', |
||
'2': '{{person1}} and {{person2}} are viewing.', |
||
'one': '{{person1}}, {{person2}} and one other person are viewing.', |
||
'other': '{{person1}}, {{person2}} and {} other people are viewing.'}"> |
||
</ng-pluralize> |
||
</div> |
||
</doc:source> |
||
<doc:scenario> |
||
it('should show correct pluralized string', function() { |
||
expect(element('.doc-example-live ng-pluralize:first').text()). |
||
toBe('1 person is viewing.'); |
||
expect(element('.doc-example-live ng-pluralize:last').text()). |
||
toBe('Igor is viewing.'); |
||
|
||
using('.doc-example-live').input('personCount').enter('0'); |
||
expect(element('.doc-example-live ng-pluralize:first').text()). |
||
toBe('Nobody is viewing.'); |
||
expect(element('.doc-example-live ng-pluralize:last').text()). |
||
toBe('Nobody is viewing.'); |
||
|
||
using('.doc-example-live').input('personCount').enter('2'); |
||
expect(element('.doc-example-live ng-pluralize:first').text()). |
||
toBe('2 people are viewing.'); |
||
expect(element('.doc-example-live ng-pluralize:last').text()). |
||
toBe('Igor and Misko are viewing.'); |
||
|
||
using('.doc-example-live').input('personCount').enter('3'); |
||
expect(element('.doc-example-live ng-pluralize:first').text()). |
||
toBe('3 people are viewing.'); |
||
expect(element('.doc-example-live ng-pluralize:last').text()). |
||
toBe('Igor, Misko and one other person are viewing.'); |
||
|
||
using('.doc-example-live').input('personCount').enter('4'); |
||
expect(element('.doc-example-live ng-pluralize:first').text()). |
||
toBe('4 people are viewing.'); |
||
expect(element('.doc-example-live ng-pluralize:last').text()). |
||
toBe('Igor, Misko and 2 other people are viewing.'); |
||
}); |
||
|
||
it('should show data-binded names', function() { |
||
using('.doc-example-live').input('personCount').enter('4'); |
||
expect(element('.doc-example-live ng-pluralize:last').text()). |
||
toBe('Igor, Misko and 2 other people are viewing.'); |
||
|
||
using('.doc-example-live').input('person1').enter('Di'); |
||
using('.doc-example-live').input('person2').enter('Vojta'); |
||
expect(element('.doc-example-live ng-pluralize:last').text()). |
||
toBe('Di, Vojta and 2 other people are viewing.'); |
||
}); |
||
</doc:scenario> |
||
</doc:example> |
||
*/ |
||
var ngPluralizeDirective = ['$locale', '$interpolate', function($locale, $interpolate) { |
||
var BRACE = /{}/g; |
||
return { |
||
restrict: 'EA', |
||
link: function(scope, element, attr) { |
||
var numberExp = attr.count, |
||
whenExp = attr.$attr.when && element.attr(attr.$attr.when), // we have {{}} in attrs |
||
offset = attr.offset || 0, |
||
whens = scope.$eval(whenExp) || {}, |
||
whensExpFns = {}, |
||
startSymbol = $interpolate.startSymbol(), |
||
endSymbol = $interpolate.endSymbol(), |
||
isWhen = /^when(Minus)?(.+)$/; |
||
|
||
forEach(attr, function(expression, attributeName) { |
||
if (isWhen.test(attributeName)) { |
||
whens[lowercase(attributeName.replace('when', '').replace('Minus', '-'))] = |
||
element.attr(attr.$attr[attributeName]); |
||
} |
||
}); |
||
forEach(whens, function(expression, key) { |
||
whensExpFns[key] = |
||
$interpolate(expression.replace(BRACE, startSymbol + numberExp + '-' + |
||
offset + endSymbol)); |
||
}); |
||
|
||
scope.$watch(function ngPluralizeWatch() { |
||
var value = parseFloat(scope.$eval(numberExp)); |
||
|
||
if (!isNaN(value)) { |
||
//if explicit number rule such as 1, 2, 3... is defined, just use it. Otherwise, |
||
//check it against pluralization rules in $locale service |
||
if (!(value in whens)) value = $locale.pluralCat(value - offset); |
||
return whensExpFns[value](scope, element, true); |
||
} else { |
||
return ''; |
||
} |
||
}, function ngPluralizeWatchAction(newVal) { |
||
element.text(newVal); |
||
}); |
||
} |
||
}; |
||
}]; |
||
|
||
/** |
||
* @ngdoc directive |
||
* @name ng.directive:ngRepeat |
||
* |
||
* @description |
||
* The `ngRepeat` directive instantiates a template once per item from a collection. Each template |
||
* instance gets its own scope, where the given loop variable is set to the current collection item, |
||
* and `$index` is set to the item index or key. |
||
* |
||
* Special properties are exposed on the local scope of each template instance, including: |
||
* |
||
* | Variable | Type | Details | |
||
* |-----------|-----------------|-----------------------------------------------------------------------------| |
||
* | `$index` | {@type number} | iterator offset of the repeated element (0..length-1) | |
||
* | `$first` | {@type boolean} | true if the repeated element is first in the iterator. | |
||
* | `$middle` | {@type boolean} | true if the repeated element is between the first and last in the iterator. | |
||
* | `$last` | {@type boolean} | true if the repeated element is last in the iterator. | |
||
* | `$even` | {@type boolean} | true if the iterator position `$index` is even (otherwise false). | |
||
* | `$odd` | {@type boolean} | true if the iterator position `$index` is odd (otherwise false). | |
||
* |
||
* Creating aliases for these properties is possible with {@link api/ng.directive:ngInit `ngInit`}. |
||
* This may be useful when, for instance, nesting ngRepeats. |
||
* |
||
* # Special repeat start and end points |
||
* To repeat a series of elements instead of just one parent element, ngRepeat (as well as other ng directives) supports extending |
||
* the range of the repeater by defining explicit start and end points by using **ng-repeat-start** and **ng-repeat-end** respectively. |
||
* The **ng-repeat-start** directive works the same as **ng-repeat**, but will repeat all the HTML code (including the tag it's defined on) |
||
* up to and including the ending HTML tag where **ng-repeat-end** is placed. |
||
* |
||
* The example below makes use of this feature: |
||
* <pre> |
||
* <header ng-repeat-start="item in items"> |
||
* Header {{ item }} |
||
* </header> |
||
* <div class="body"> |
||
* Body {{ item }} |
||
* </div> |
||
* <footer ng-repeat-end> |
||
* Footer {{ item }} |
||
* </footer> |
||
* </pre> |
||
* |
||
* And with an input of {@type ['A','B']} for the items variable in the example above, the output will evaluate to: |
||
* <pre> |
||
* <header> |
||
* Header A |
||
* </header> |
||
* <div class="body"> |
||
* Body A |
||
* </div> |
||
* <footer> |
||
* Footer A |
||
* </footer> |
||
* <header> |
||
* Header B |
||
* </header> |
||
* <div class="body"> |
||
* Body B |
||
* </div> |
||
* <footer> |
||
* Footer B |
||
* </footer> |
||
* </pre> |
||
* |
||
* The custom start and end points for ngRepeat also support all other HTML directive syntax flavors provided in AngularJS (such |
||
* as **data-ng-repeat-start**, **x-ng-repeat-start** and **ng:repeat-start**). |
||
* |
||
* @animations |
||
* enter - when a new item is added to the list or when an item is revealed after a filter |
||
* leave - when an item is removed from the list or when an item is filtered out |
||
* move - when an adjacent item is filtered out causing a reorder or when the item contents are reordered |
||
* |
||
* @element ANY |
||
* @scope |
||
* @priority 1000 |
||
* @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. These |
||
* formats are currently supported: |
||
* |
||
* * `variable in expression` – where variable is the user defined loop variable and `expression` |
||
* is a scope expression giving the collection to enumerate. |
||
* |
||
* For example: `album in artist.albums`. |
||
* |
||
* * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers, |
||
* and `expression` is the scope expression giving the collection to enumerate. |
||
* |
||
* For example: `(name, age) in {'adam':10, 'amalie':12}`. |
||
* |
||
* * `variable in expression track by tracking_expression` – You can also provide an optional tracking function |
||
* which can be used to associate the objects in the collection with the DOM elements. If no tracking function |
||
* is specified the ng-repeat associates elements by identity in the collection. It is an error to have |
||
* more than one tracking function to resolve to the same key. (This would mean that two distinct objects are |
||
* mapped to the same DOM element, which is not possible.) Filters should be applied to the expression, |
||
* before specifying a tracking expression. |
||
* |
||
* For example: `item in items` is equivalent to `item in items track by $id(item)'. This implies that the DOM elements |
||
* will be associated by item identity in the array. |
||
* |
||
* For example: `item in items track by $id(item)`. A built in `$id()` function can be used to assign a unique |
||
* `$$hashKey` property to each item in the array. This property is then used as a key to associated DOM elements |
||
* with the corresponding item in the array by identity. Moving the same object in array would move the DOM |
||
* element in the same way in the DOM. |
||
* |
||
* For example: `item in items track by item.id` is a typical pattern when the items come from the database. In this |
||
* case the object identity does not matter. Two objects are considered equivalent as long as their `id` |
||
* property is same. |
||
* |
||
* For example: `item in items | filter:searchText track by item.id` is a pattern that might be used to apply a filter |
||
* to items in conjunction with a tracking expression. |
||
* |
||
* @example |
||
* This example initializes the scope to a list of names and |
||
* then uses `ngRepeat` to display every person: |
||
<example animations="true"> |
||
<file name="index.html"> |
||
<div ng-init="friends = [ |
||
{name:'John', age:25, gender:'boy'}, |
||
{name:'Jessie', age:30, gender:'girl'}, |
||
{name:'Johanna', age:28, gender:'girl'}, |
||
{name:'Joy', age:15, gender:'girl'}, |
||
{name:'Mary', age:28, gender:'girl'}, |
||
{name:'Peter', age:95, gender:'boy'}, |
||
{name:'Sebastian', age:50, gender:'boy'}, |
||
{name:'Erika', age:27, gender:'girl'}, |
||
{name:'Patrick', age:40, gender:'boy'}, |
||
{name:'Samantha', age:60, gender:'girl'} |
||
]"> |
||
I have {{friends.length}} friends. They are: |
||
<input type="search" ng-model="q" placeholder="filter friends..." /> |
||
<ul class="example-animate-container"> |
||
<li class="animate-repeat" ng-repeat="friend in friends | filter:q"> |
||
[{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old. |
||
</li> |
||
</ul> |
||
</div> |
||
</file> |
||
<file name="animations.css"> |
||
.example-animate-container { |
||
background:white; |
||
border:1px solid black; |
||
list-style:none; |
||
margin:0; |
||
padding:0 10px; |
||
} |
||
|
||
.animate-repeat { |
||
line-height:40px; |
||
list-style:none; |
||
box-sizing:border-box; |
||
} |
||
|
||
.animate-repeat.ng-move, |
||
.animate-repeat.ng-enter, |
||
.animate-repeat.ng-leave { |
||
-webkit-transition:all linear 0.5s; |
||
transition:all linear 0.5s; |
||
} |
||
|
||
.animate-repeat.ng-leave.ng-leave-active, |
||
.animate-repeat.ng-move, |
||
.animate-repeat.ng-enter { |
||
opacity:0; |
||
max-height:0; |
||
} |
||
|
||
.animate-repeat.ng-leave, |
||
.animate-repeat.ng-move.ng-move-active, |
||
.animate-repeat.ng-enter.ng-enter-active { |
||
opacity:1; |
||
max-height:40px; |
||
} |
||
</file> |
||
<file name="scenario.js"> |
||
it('should render initial data set', function() { |
||
var r = using('.doc-example-live').repeater('ul li'); |
||
expect(r.count()).toBe(10); |
||
expect(r.row(0)).toEqual(["1","John","25"]); |
||
expect(r.row(1)).toEqual(["2","Jessie","30"]); |
||
expect(r.row(9)).toEqual(["10","Samantha","60"]); |
||
expect(binding('friends.length')).toBe("10"); |
||
}); |
||
|
||
it('should update repeater when filter predicate changes', function() { |
||
var r = using('.doc-example-live').repeater('ul li'); |
||
expect(r.count()).toBe(10); |
||
|
||
input('q').enter('ma'); |
||
|
||
expect(r.count()).toBe(2); |
||
expect(r.row(0)).toEqual(["1","Mary","28"]); |
||
expect(r.row(1)).toEqual(["2","Samantha","60"]); |
||
}); |
||
</file> |
||
</example> |
||
*/ |
||
var ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) { |
||
var NG_REMOVED = '$$NG_REMOVED'; |
||
var ngRepeatMinErr = minErr('ngRepeat'); |
||
return { |
||
transclude: 'element', |
||
priority: 1000, |
||
terminal: true, |
||
$$tlb: true, |
||
link: function($scope, $element, $attr, ctrl, $transclude){ |
||
var expression = $attr.ngRepeat; |
||
var match = expression.match(/^\s*([\s\S]+?)\s+in\s+([\s\S]+?)(?:\s+track\s+by\s+([\s\S]+?))?\s*$/), |
||
trackByExp, trackByExpGetter, trackByIdExpFn, trackByIdArrayFn, trackByIdObjFn, |
||
lhs, rhs, valueIdentifier, keyIdentifier, |
||
hashFnLocals = {$id: hashKey}; |
||
|
||
if (!match) { |
||
throw ngRepeatMinErr('iexp', "Expected expression in form of '_item_ in _collection_[ track by _id_]' but got '{0}'.", |
||
expression); |
||
} |
||
|
||
lhs = match[1]; |
||
rhs = match[2]; |
||
trackByExp = match[3]; |
||
|
||
if (trackByExp) { |
||
trackByExpGetter = $parse(trackByExp); |
||
trackByIdExpFn = function(key, value, index) { |
||
// assign key, value, and $index to the locals so that they can be used in hash functions |
||
if (keyIdentifier) hashFnLocals[keyIdentifier] = key; |
||
hashFnLocals[valueIdentifier] = value; |
||
hashFnLocals.$index = index; |
||
return trackByExpGetter($scope, hashFnLocals); |
||
}; |
||
} else { |
||
trackByIdArrayFn = function(key, value) { |
||
return hashKey(value); |
||
}; |
||
trackByIdObjFn = function(key) { |
||
return key; |
||
}; |
||
} |
||
|
||
match = lhs.match(/^(?:([\$\w]+)|\(([\$\w]+)\s*,\s*([\$\w]+)\))$/); |
||
if (!match) { |
||
throw ngRepeatMinErr('iidexp', "'_item_' in '_item_ in _collection_' should be an identifier or '(_key_, _value_)' expression, but got '{0}'.", |
||
lhs); |
||
} |
||
valueIdentifier = match[3] || match[1]; |
||
keyIdentifier = match[2]; |
||
|
||
// Store a list of elements from previous run. This is a hash where key is the item from the |
||
// iterator, and the value is objects with following properties. |
||
// - scope: bound scope |
||
// - element: previous element. |
||
// - index: position |
||
var lastBlockMap = {}; |
||
|
||
//watch props |
||
$scope.$watchCollection(rhs, function ngRepeatAction(collection){ |
||
var index, length, |
||
previousNode = $element[0], // current position of the node |
||
nextNode, |
||
// Same as lastBlockMap but it has the current state. It will become the |
||
// lastBlockMap on the next iteration. |
||
nextBlockMap = {}, |
||
arrayLength, |
||
childScope, |
||
key, value, // key/value of iteration |
||
trackById, |
||
trackByIdFn, |
||
collectionKeys, |
||
block, // last object information {scope, element, id} |
||
nextBlockOrder = [], |
||
elementsToRemove; |
||
|
||
|
||
if (isArrayLike(collection)) { |
||
collectionKeys = collection; |
||
trackByIdFn = trackByIdExpFn || trackByIdArrayFn; |
||
} else { |
||
trackByIdFn = trackByIdExpFn || trackByIdObjFn; |
||
// if object, extract keys, sort them and use to determine order of iteration over obj props |
||
collectionKeys = []; |
||
for (key in collection) { |
||
if (collection.hasOwnProperty(key) && key.charAt(0) != '$') { |
||
collectionKeys.push(key); |
||
} |
||
} |
||
collectionKeys.sort(); |
||
} |
||
|
||
arrayLength = collectionKeys.length; |
||
|
||
// locate existing items |
||
length = nextBlockOrder.length = collectionKeys.length; |
||
for(index = 0; index < length; index++) { |
||
key = (collection === collectionKeys) ? index : collectionKeys[index]; |
||
value = collection[key]; |
||
trackById = trackByIdFn(key, value, index); |
||
assertNotHasOwnProperty(trackById, '`track by` id'); |
||
if(lastBlockMap.hasOwnProperty(trackById)) { |
||
block = lastBlockMap[trackById]; |
||
delete lastBlockMap[trackById]; |
||
nextBlockMap[trackById] = block; |
||
nextBlockOrder[index] = block; |
||
} else if (nextBlockMap.hasOwnProperty(trackById)) { |
||
// restore lastBlockMap |
||
forEach(nextBlockOrder, function(block) { |
||
if (block && block.scope) lastBlockMap[block.id] = block; |
||
}); |
||
// This is a duplicate and we need to throw an error |
||
throw ngRepeatMinErr('dupes', "Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}", |
||
expression, trackById); |
||
} else { |
||
// new never before seen block |
||
nextBlockOrder[index] = { id: trackById }; |
||
nextBlockMap[trackById] = false; |
||
} |
||
} |
||
|
||
// remove existing items |
||
for (key in lastBlockMap) { |
||
// lastBlockMap is our own object so we don't need to use special hasOwnPropertyFn |
||
if (lastBlockMap.hasOwnProperty(key)) { |
||
block = lastBlockMap[key]; |
||
elementsToRemove = getBlockElements(block.clone); |
||
$animate.leave(elementsToRemove); |
||
forEach(elementsToRemove, function(element) { element[NG_REMOVED] = true; }); |
||
block.scope.$destroy(); |
||
} |
||
} |
||
|
||
// we are not using forEach for perf reasons (trying to avoid #call) |
||
for (index = 0, length = collectionKeys.length; index < length; index++) { |
||
key = (collection === collectionKeys) ? index : collectionKeys[index]; |
||
value = collection[key]; |
||
block = nextBlockOrder[index]; |
||
if (nextBlockOrder[index - 1]) previousNode = getBlockEnd(nextBlockOrder[index - 1]); |
||
|
||
if (block.scope) { |
||
// if we have already seen this object, then we need to reuse the |
||
// associated scope/element |
||
childScope = block.scope; |
||
|
||
nextNode = previousNode; |
||
do { |
||
nextNode = nextNode.nextSibling; |
||
} while(nextNode && nextNode[NG_REMOVED]); |
||
|
||
if (getBlockStart(block) != nextNode) { |
||
// existing item which got moved |
||
$animate.move(getBlockElements(block.clone), null, jqLite(previousNode)); |
||
} |
||
previousNode = getBlockEnd(block); |
||
} else { |
||
// new item which we don't know about |
||
childScope = $scope.$new(); |
||
} |
||
|
||
childScope[valueIdentifier] = value; |
||
if (keyIdentifier) childScope[keyIdentifier] = key; |
||
childScope.$index = index; |
||
childScope.$first = (index === 0); |
||
childScope.$last = (index === (arrayLength - 1)); |
||
childScope.$middle = !(childScope.$first || childScope.$last); |
||
// jshint bitwise: false |
||
childScope.$odd = !(childScope.$even = (index&1) === 0); |
||
// jshint bitwise: true |
||
|
||
if (!block.scope) { |
||
$transclude(childScope, function(clone) { |
||
clone[clone.length++] = document.createComment(' end ngRepeat: ' + expression + ' '); |
||
$animate.enter(clone, null, jqLite(previousNode)); |
||
previousNode = clone; |
||
block.scope = childScope; |
||
// Note: We only need the first/last node of the cloned nodes. |
||
// However, we need to keep the reference to the jqlite wrapper as it might be changed later |
||
// by a directive with templateUrl when it's template arrives. |
||
block.clone = clone; |
||
nextBlockMap[block.id] = block; |
||
}); |
||
} |
||
} |
||
lastBlockMap = nextBlockMap; |
||
}); |
||
} |
||
}; |
||
|
||
function getBlockStart(block) { |
||
return block.clone[0]; |
||
} |
||
|
||
function getBlockEnd(block) { |
||
return block.clone[block.clone.length - 1]; |
||
} |
||
}]; |
||
|
||
/** |
||
* @ngdoc directive |
||
* @name ng.directive:ngShow |
||
* |
||
* @description |
||
* The `ngShow` directive shows or hides the given HTML element based on the expression |
||
* provided to the ngShow attribute. The element is shown or hidden by removing or adding |
||
* the `ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined |
||
* in AngularJS and sets the display style to none (using an !important flag). |
||
* For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}). |
||
* |
||
* <pre> |
||
* <!-- when $scope.myValue is truthy (element is visible) --> |
||
* <div ng-show="myValue"></div> |
||
* |
||
* <!-- when $scope.myValue is falsy (element is hidden) --> |
||
* <div ng-show="myValue" class="ng-hide"></div> |
||
* </pre> |
||
* |
||
* When the ngShow expression evaluates to false then the ng-hide CSS class is added to the class attribute |
||
* on the element causing it to become hidden. When true, the ng-hide CSS class is removed |
||
* from the element causing the element not to appear hidden. |
||
* |
||
* ## Why is !important used? |
||
* |
||
* You may be wondering why !important is used for the .ng-hide CSS class. This is because the `.ng-hide` selector |
||
* can be easily overridden by heavier selectors. For example, something as simple |
||
* as changing the display style on a HTML list item would make hidden elements appear visible. |
||
* This also becomes a bigger issue when dealing with CSS frameworks. |
||
* |
||
* By using !important, the show and hide behavior will work as expected despite any clash between CSS selector |
||
* specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the |
||
* styling to change how to hide an element then it is just a matter of using !important in their own CSS code. |
||
* |
||
* ### Overriding .ng-hide |
||
* |
||
* If you wish to change the hide behavior with ngShow/ngHide then this can be achieved by |
||
* restating the styles for the .ng-hide class in CSS: |
||
* <pre> |
||
* .ng-hide { |
||
* //!annotate CSS Specificity|Not to worry, this will override the AngularJS default... |
||
* display:block!important; |
||
* |
||
* //this is just another form of hiding an element |
||
* position:absolute; |
||
* top:-9999px; |
||
* left:-9999px; |
||
* } |
||
* </pre> |
||
* |
||
* Just remember to include the important flag so the CSS override will function. |
||
* |
||
* ## A note about animations with ngShow |
||
* |
||
* Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression |
||
* is true and false. This system works like the animation system present with ngClass except that |
||
* you must also include the !important flag to override the display property |
||
* so that you can perform an animation when the element is hidden during the time of the animation. |
||
* |
||
* <pre> |
||
* // |
||
* //a working example can be found at the bottom of this page |
||
* // |
||
* .my-element.ng-hide-add, .my-element.ng-hide-remove { |
||
* transition:0.5s linear all; |
||
* display:block!important; |
||
* } |
||
* |
||
* .my-element.ng-hide-add { ... } |
||
* .my-element.ng-hide-add.ng-hide-add-active { ... } |
||
* .my-element.ng-hide-remove { ... } |
||
* .my-element.ng-hide-remove.ng-hide-remove-active { ... } |
||
* </pre> |
||
* |
||
* @animations |
||
* addClass: .ng-hide - happens after the ngShow expression evaluates to a truthy value and the just before contents are set to visible |
||
* removeClass: .ng-hide - happens after the ngShow expression evaluates to a non truthy value and just before the contents are set to hidden |
||
* |
||
* @element ANY |
||
* @param {expression} ngShow If the {@link guide/expression expression} is truthy |
||
* then the element is shown or hidden respectively. |
||
* |
||
* @example |
||
<example animations="true"> |
||
<file name="index.html"> |
||
Click me: <input type="checkbox" ng-model="checked"><br/> |
||
<div> |
||
Show: |
||
<div class="check-element animate-show" ng-show="checked"> |
||
<span class="icon-thumbs-up"></span> I show up when your checkbox is checked. |
||
</div> |
||
</div> |
||
<div> |
||
Hide: |
||
<div class="check-element animate-show" ng-hide="checked"> |
||
<span class="icon-thumbs-down"></span> I hide when your checkbox is checked. |
||
</div> |
||
</div> |
||
</file> |
||
<file name="animations.css"> |
||
.animate-show { |
||
-webkit-transition:all linear 0.5s; |
||
transition:all linear 0.5s; |
||
line-height:20px; |
||
opacity:1; |
||
padding:10px; |
||
border:1px solid black; |
||
background:white; |
||
} |
||
|
||
.animate-show.ng-hide-add, |
||
.animate-show.ng-hide-remove { |
||
display:block!important; |
||
} |
||
|
||
.animate-show.ng-hide { |
||
line-height:0; |
||
opacity:0; |
||
padding:0 10px; |
||
} |
||
|
||
.check-element { |
||
padding:10px; |
||
border:1px solid black; |
||
background:white; |
||
} |
||
</file> |
||
<file name="scenario.js"> |
||
it('should check ng-show / ng-hide', function() { |
||
expect(element('.doc-example-live span:first:hidden').count()).toEqual(1); |
||
expect(element('.doc-example-live span:last:visible').count()).toEqual(1); |
||
|
||
input('checked').check(); |
||
|
||
expect(element('.doc-example-live span:first:visible').count()).toEqual(1); |
||
expect(element('.doc-example-live span:last:hidden').count()).toEqual(1); |
||
}); |
||
</file> |
||
</example> |
||
*/ |
||
var ngShowDirective = ['$animate', function($animate) { |
||
return function(scope, element, attr) { |
||
scope.$watch(attr.ngShow, function ngShowWatchAction(value){ |
||
$animate[toBoolean(value) ? 'removeClass' : 'addClass'](element, 'ng-hide'); |
||
}); |
||
}; |
||
}]; |
||
|
||
|
||
/** |
||
* @ngdoc directive |
||
* @name ng.directive:ngHide |
||
* |
||
* @description |
||
* The `ngHide` directive shows or hides the given HTML element based on the expression |
||
* provided to the ngHide attribute. The element is shown or hidden by removing or adding |
||
* the `ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined |
||
* in AngularJS and sets the display style to none (using an !important flag). |
||
* For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}). |
||
* |
||
* <pre> |
||
* <!-- when $scope.myValue is truthy (element is hidden) --> |
||
* <div ng-hide="myValue"></div> |
||
* |
||
* <!-- when $scope.myValue is falsy (element is visible) --> |
||
* <div ng-hide="myValue" class="ng-hide"></div> |
||
* </pre> |
||
* |
||
* When the ngHide expression evaluates to true then the .ng-hide CSS class is added to the class attribute |
||
* on the element causing it to become hidden. When false, the ng-hide CSS class is removed |
||
* from the element causing the element not to appear hidden. |
||
* |
||
* ## Why is !important used? |
||
* |
||
* You may be wondering why !important is used for the .ng-hide CSS class. This is because the `.ng-hide` selector |
||
* can be easily overridden by heavier selectors. For example, something as simple |
||
* as changing the display style on a HTML list item would make hidden elements appear visible. |
||
* This also becomes a bigger issue when dealing with CSS frameworks. |
||
* |
||
* By using !important, the show and hide behavior will work as expected despite any clash between CSS selector |
||
* specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the |
||
* styling to change how to hide an element then it is just a matter of using !important in their own CSS code. |
||
* |
||
* ### Overriding .ng-hide |
||
* |
||
* If you wish to change the hide behavior with ngShow/ngHide then this can be achieved by |
||
* restating the styles for the .ng-hide class in CSS: |
||
* <pre> |
||
* .ng-hide { |
||
* //!annotate CSS Specificity|Not to worry, this will override the AngularJS default... |
||
* display:block!important; |
||
* |
||
* //this is just another form of hiding an element |
||
* position:absolute; |
||
* top:-9999px; |
||
* left:-9999px; |
||
* } |
||
* </pre> |
||
* |
||
* Just remember to include the important flag so the CSS override will function. |
||
* |
||
* ## A note about animations with ngHide |
||
* |
||
* Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression |
||
* is true and false. This system works like the animation system present with ngClass, except that |
||
* you must also include the !important flag to override the display property so |
||
* that you can perform an animation when the element is hidden during the time of the animation. |
||
* |
||
* <pre> |
||
* // |
||
* //a working example can be found at the bottom of this page |
||
* // |
||
* .my-element.ng-hide-add, .my-element.ng-hide-remove { |
||
* transition:0.5s linear all; |
||
* display:block!important; |
||
* } |
||
* |
||
* .my-element.ng-hide-add { ... } |
||
* .my-element.ng-hide-add.ng-hide-add-active { ... } |
||
* .my-element.ng-hide-remove { ... } |
||
* .my-element.ng-hide-remove.ng-hide-remove-active { ... } |
||
* </pre> |
||
* |
||
* @animations |
||
* removeClass: .ng-hide - happens after the ngHide expression evaluates to a truthy value and just before the contents are set to hidden |
||
* addClass: .ng-hide - happens after the ngHide expression evaluates to a non truthy value and just before the contents are set to visible |
||
* |
||
* @element ANY |
||
* @param {expression} ngHide If the {@link guide/expression expression} is truthy then |
||
* the element is shown or hidden respectively. |
||
* |
||
* @example |
||
<example animations="true"> |
||
<file name="index.html"> |
||
Click me: <input type="checkbox" ng-model="checked"><br/> |
||
<div> |
||
Show: |
||
<div class="check-element animate-hide" ng-show="checked"> |
||
<span class="icon-thumbs-up"></span> I show up when your checkbox is checked. |
||
</div> |
||
</div> |
||
<div> |
||
Hide: |
||
<div class="check-element animate-hide" ng-hide="checked"> |
||
<span class="icon-thumbs-down"></span> I hide when your checkbox is checked. |
||
</div> |
||
</div> |
||
</file> |
||
<file name="animations.css"> |
||
.animate-hide { |
||
-webkit-transition:all linear 0.5s; |
||
transition:all linear 0.5s; |
||
line-height:20px; |
||
opacity:1; |
||
padding:10px; |
||
border:1px solid black; |
||
background:white; |
||
} |
||
|
||
.animate-hide.ng-hide-add, |
||
.animate-hide.ng-hide-remove { |
||
display:block!important; |
||
} |
||
|
||
.animate-hide.ng-hide { |
||
line-height:0; |
||
opacity:0; |
||
padding:0 10px; |
||
} |
||
|
||
.check-element { |
||
padding:10px; |
||
border:1px solid black; |
||
background:white; |
||
} |
||
</file> |
||
<file name="scenario.js"> |
||
it('should check ng-show / ng-hide', function() { |
||
expect(element('.doc-example-live .check-element:first:hidden').count()).toEqual(1); |
||
expect(element('.doc-example-live .check-element:last:visible').count()).toEqual(1); |
||
|
||
input('checked').check(); |
||
|
||
expect(element('.doc-example-live .check-element:first:visible').count()).toEqual(1); |
||
expect(element('.doc-example-live .check-element:last:hidden').count()).toEqual(1); |
||
}); |
||
</file> |
||
</example> |
||
*/ |
||
var ngHideDirective = ['$animate', function($animate) { |
||
return function(scope, element, attr) { |
||
scope.$watch(attr.ngHide, function ngHideWatchAction(value){ |
||
$animate[toBoolean(value) ? 'addClass' : 'removeClass'](element, 'ng-hide'); |
||
}); |
||
}; |
||
}]; |
||
|
||
/** |
||
* @ngdoc directive |
||
* @name ng.directive:ngStyle |
||
* @restrict AC |
||
* |
||
* @description |
||
* The `ngStyle` directive allows you to set CSS style on an HTML element conditionally. |
||
* |
||
* @element ANY |
||
* @param {expression} ngStyle {@link guide/expression Expression} which evals to an |
||
* object whose keys are CSS style names and values are corresponding values for those CSS |
||
* keys. |
||
* |
||
* @example |
||
<example> |
||
<file name="index.html"> |
||
<input type="button" value="set" ng-click="myStyle={color:'red'}"> |
||
<input type="button" value="clear" ng-click="myStyle={}"> |
||
<br/> |
||
<span ng-style="myStyle">Sample Text</span> |
||
<pre>myStyle={{myStyle}}</pre> |
||
</file> |
||
<file name="style.css"> |
||
span { |
||
color: black; |
||
} |
||
</file> |
||
<file name="scenario.js"> |
||
it('should check ng-style', function() { |
||
expect(element('.doc-example-live span').css('color')).toBe('rgb(0, 0, 0)'); |
||
element('.doc-example-live :button[value=set]').click(); |
||
expect(element('.doc-example-live span').css('color')).toBe('rgb(255, 0, 0)'); |
||
element('.doc-example-live :button[value=clear]').click(); |
||
expect(element('.doc-example-live span').css('color')).toBe('rgb(0, 0, 0)'); |
||
}); |
||
</file> |
||
</example> |
||
*/ |
||
var ngStyleDirective = ngDirective(function(scope, element, attr) { |
||
scope.$watch(attr.ngStyle, function ngStyleWatchAction(newStyles, oldStyles) { |
||
if (oldStyles && (newStyles !== oldStyles)) { |
||
forEach(oldStyles, function(val, style) { element.css(style, '');}); |
||
} |
||
if (newStyles) element.css(newStyles); |
||
}, true); |
||
}); |
||
|
||
/** |
||
* @ngdoc directive |
||
* @name ng.directive:ngSwitch |
||
* @restrict EA |
||
* |
||
* @description |
||
* The `ngSwitch` directive is used to conditionally swap DOM structure on your template based on a scope expression. |
||
* Elements within `ngSwitch` but without `ngSwitchWhen` or `ngSwitchDefault` directives will be preserved at the location |
||
* as specified in the template. |
||
* |
||
* The directive itself works similar to ngInclude, however, instead of downloading template code (or loading it |
||
* from the template cache), `ngSwitch` simply choses one of the nested elements and makes it visible based on which element |
||
* matches the value obtained from the evaluated expression. In other words, you define a container element |
||
* (where you place the directive), place an expression on the **`on="..."` attribute** |
||
* (or the **`ng-switch="..."` attribute**), define any inner elements inside of the directive and place |
||
* a when attribute per element. The when attribute is used to inform ngSwitch which element to display when the on |
||
* expression is evaluated. If a matching expression is not found via a when attribute then an element with the default |
||
* attribute is displayed. |
||
* |
||
* <div class="alert alert-info"> |
||
* Be aware that the attribute values to match against cannot be expressions. They are interpreted |
||
* as literal string values to match against. |
||
* For example, **`ng-switch-when="someVal"`** will match against the string `"someVal"` not against the |
||
* value of the expression `$scope.someVal`. |
||
* </div> |
||
|
||
* @animations |
||
* enter - happens after the ngSwitch contents change and the matched child element is placed inside the container |
||
* leave - happens just after the ngSwitch contents change and just before the former contents are removed from the DOM |
||
* |
||
* @usage |
||
* <ANY ng-switch="expression"> |
||
* <ANY ng-switch-when="matchValue1">...</ANY> |
||
* <ANY ng-switch-when="matchValue2">...</ANY> |
||
* <ANY ng-switch-default>...</ANY> |
||
* </ANY> |
||
* |
||
* |
||
* @scope |
||
* @priority 800 |
||
* @param {*} ngSwitch|on expression to match against <tt>ng-switch-when</tt>. |
||
* @paramDescription |
||
* On child elements add: |
||
* |
||
* * `ngSwitchWhen`: the case statement to match against. If match then this |
||
* case will be displayed. If the same match appears multiple times, all the |
||
* elements will be displayed. |
||
* * `ngSwitchDefault`: the default case when no other case match. If there |
||
* are multiple default cases, all of them will be displayed when no other |
||
* case match. |
||
* |
||
* |
||
* @example |
||
<example animations="true"> |
||
<file name="index.html"> |
||
<div ng-controller="Ctrl"> |
||
<select ng-model="selection" ng-options="item for item in items"> |
||
</select> |
||
<tt>selection={{selection}}</tt> |
||
<hr/> |
||
<div class="animate-switch-container" |
||
ng-switch on="selection"> |
||
<div class="animate-switch" ng-switch-when="settings">Settings Div</div> |
||
<div class="animate-switch" ng-switch-when="home">Home Span</div> |
||
<div class="animate-switch" ng-switch-default>default</div> |
||
</div> |
||
</div> |
||
</file> |
||
<file name="script.js"> |
||
function Ctrl($scope) { |
||
$scope.items = ['settings', 'home', 'other']; |
||
$scope.selection = $scope.items[0]; |
||
} |
||
</file> |
||
<file name="animations.css"> |
||
.animate-switch-container { |
||
position:relative; |
||
background:white; |
||
border:1px solid black; |
||
height:40px; |
||
overflow:hidden; |
||
} |
||
|
||
.animate-switch { |
||
padding:10px; |
||
} |
||
|
||
.animate-switch.ng-animate { |
||
-webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; |
||
transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; |
||
|
||
position:absolute; |
||
top:0; |
||
left:0; |
||
right:0; |
||
bottom:0; |
||
} |
||
|
||
.animate-switch.ng-leave.ng-leave-active, |
||
.animate-switch.ng-enter { |
||
top:-50px; |
||
} |
||
.animate-switch.ng-leave, |
||
.animate-switch.ng-enter.ng-enter-active { |
||
top:0; |
||
} |
||
</file> |
||
<file name="scenario.js"> |
||
it('should start in settings', function() { |
||
expect(element('.doc-example-live [ng-switch]').text()).toMatch(/Settings Div/); |
||
}); |
||
it('should change to home', function() { |
||
select('selection').option('home'); |
||
expect(element('.doc-example-live [ng-switch]').text()).toMatch(/Home Span/); |
||
}); |
||
it('should select default', function() { |
||
select('selection').option('other'); |
||
expect(element('.doc-example-live [ng-switch]').text()).toMatch(/default/); |
||
}); |
||
</file> |
||
</example> |
||
*/ |
||
var ngSwitchDirective = ['$animate', function($animate) { |
||
return { |
||
restrict: 'EA', |
||
require: 'ngSwitch', |
||
|
||
// asks for $scope to fool the BC controller module |
||
controller: ['$scope', function ngSwitchController() { |
||
this.cases = {}; |
||
}], |
||
link: function(scope, element, attr, ngSwitchController) { |
||
var watchExpr = attr.ngSwitch || attr.on, |
||
selectedTranscludes, |
||
selectedElements, |
||
selectedScopes = []; |
||
|
||
scope.$watch(watchExpr, function ngSwitchWatchAction(value) { |
||
for (var i= 0, ii=selectedScopes.length; i<ii; i++) { |
||
selectedScopes[i].$destroy(); |
||
$animate.leave(selectedElements[i]); |
||
} |
||
|
||
selectedElements = []; |
||
selectedScopes = []; |
||
|
||
if ((selectedTranscludes = ngSwitchController.cases['!' + value] || ngSwitchController.cases['?'])) { |
||
scope.$eval(attr.change); |
||
forEach(selectedTranscludes, function(selectedTransclude) { |
||
var selectedScope = scope.$new(); |
||
selectedScopes.push(selectedScope); |
||
selectedTransclude.transclude(selectedScope, function(caseElement) { |
||
var anchor = selectedTransclude.element; |
||
|
||
selectedElements.push(caseElement); |
||
$animate.enter(caseElement, anchor.parent(), anchor); |
||
}); |
||
}); |
||
} |
||
}); |
||
} |
||
}; |
||
}]; |
||
|
||
var ngSwitchWhenDirective = ngDirective({ |
||
transclude: 'element', |
||
priority: 800, |
||
require: '^ngSwitch', |
||
link: function(scope, element, attrs, ctrl, $transclude) { |
||
ctrl.cases['!' + attrs.ngSwitchWhen] = (ctrl.cases['!' + attrs.ngSwitchWhen] || []); |
||
ctrl.cases['!' + attrs.ngSwitchWhen].push({ transclude: $transclude, element: element }); |
||
} |
||
}); |
||
|
||
var ngSwitchDefaultDirective = ngDirective({ |
||
transclude: 'element', |
||
priority: 800, |
||
require: '^ngSwitch', |
||
link: function(scope, element, attr, ctrl, $transclude) { |
||
ctrl.cases['?'] = (ctrl.cases['?'] || []); |
||
ctrl.cases['?'].push({ transclude: $transclude, element: element }); |
||
} |
||
}); |
||
|
||
/** |
||
* @ngdoc directive |
||
* @name ng.directive:ngTransclude |
||
* @restrict AC |
||
* |
||
* @description |
||
* Directive that marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion. |
||
* |
||
* Any existing content of the element that this directive is placed on will be removed before the transcluded content is inserted. |
||
* |
||
* @element ANY |
||
* |
||
* @example |
||
<doc:example module="transclude"> |
||
<doc:source> |
||
<script> |
||
function Ctrl($scope) { |
||
$scope.title = 'Lorem Ipsum'; |
||
$scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...'; |
||
} |
||
|
||
angular.module('transclude', []) |
||
.directive('pane', function(){ |
||
return { |
||
restrict: 'E', |
||
transclude: true, |
||
scope: { title:'@' }, |
||
template: '<div style="border: 1px solid black;">' + |
||
'<div style="background-color: gray">{{title}}</div>' + |
||
'<div ng-transclude></div>' + |
||
'</div>' |
||
}; |
||
}); |
||
</script> |
||
<div ng-controller="Ctrl"> |
||
<input ng-model="title"><br> |
||
<textarea ng-model="text"></textarea> <br/> |
||
<pane title="{{title}}">{{text}}</pane> |
||
</div> |
||
</doc:source> |
||
<doc:scenario> |
||
it('should have transcluded', function() { |
||
input('title').enter('TITLE'); |
||
input('text').enter('TEXT'); |
||
expect(binding('title')).toEqual('TITLE'); |
||
expect(binding('text')).toEqual('TEXT'); |
||
}); |
||
</doc:scenario> |
||
</doc:example> |
||
* |
||
*/ |
||
var ngTranscludeDirective = ngDirective({ |
||
controller: ['$element', '$transclude', function($element, $transclude) { |
||
if (!$transclude) { |
||
throw minErr('ngTransclude')('orphan', |
||
'Illegal use of ngTransclude directive in the template! ' + |
||
'No parent directive that requires a transclusion found. ' + |
||
'Element: {0}', |
||
startingTag($element)); |
||
} |
||
|
||
// remember the transclusion fn but call it during linking so that we don't process transclusion before directives on |
||
// the parent element even when the transclusion replaces the current element. (we can't use priority here because |
||
// that applies only to compile fns and not controllers |
||
this.$transclude = $transclude; |
||
}], |
||
|
||
link: function($scope, $element, $attrs, controller) { |
||
controller.$transclude(function(clone) { |
||
$element.empty(); |
||
$element.append(clone); |
||
}); |
||
} |
||
}); |
||
|
||
/** |
||
* @ngdoc directive |
||
* @name ng.directive:script |
||
* @restrict E |
||
* |
||
* @description |
||
* Load the content of a `<script>` element into {@link api/ng.$templateCache `$templateCache`}, so that the |
||
* template can be used by {@link api/ng.directive:ngInclude `ngInclude`}, |
||
* {@link api/ngRoute.directive:ngView `ngView`}, or {@link guide/directive directives}. The type of the |
||
* `<script>` element must be specified as `text/ng-template`, and a cache name for the template must be |
||
* assigned through the element's `id`, which can then be used as a directive's `templateUrl`. |
||
* |
||
* @param {'text/ng-template'} type Must be set to `'text/ng-template'`. |
||
* @param {string} id Cache name of the template. |
||
* |
||
* @example |
||
<doc:example> |
||
<doc:source> |
||
<script type="text/ng-template" id="/tpl.html"> |
||
Content of the template. |
||
</script> |
||
|
||
<a ng-click="currentTpl='/tpl.html'" id="tpl-link">Load inlined template</a> |
||
<div id="tpl-content" ng-include src="currentTpl"></div> |
||
</doc:source> |
||
<doc:scenario> |
||
it('should load template defined inside script tag', function() { |
||
element('#tpl-link').click(); |
||
expect(element('#tpl-content').text()).toMatch(/Content of the template/); |
||
}); |
||
</doc:scenario> |
||
</doc:example> |
||
*/ |
||
var scriptDirective = ['$templateCache', function($templateCache) { |
||
return { |
||
restrict: 'E', |
||
terminal: true, |
||
compile: function(element, attr) { |
||
if (attr.type == 'text/ng-template') { |
||
var templateUrl = attr.id, |
||
// IE is not consistent, in scripts we have to read .text but in other nodes we have to read .textContent |
||
text = element[0].text; |
||
|
||
$templateCache.put(templateUrl, text); |
||
} |
||
} |
||
}; |
||
}]; |
||
|
||
var ngOptionsMinErr = minErr('ngOptions'); |
||
/** |
||
* @ngdoc directive |
||
* @name ng.directive:select |
||
* @restrict E |
||
* |
||
* @description |
||
* HTML `SELECT` element with angular data-binding. |
||
* |
||
* # `ngOptions` |
||
* |
||
* The `ngOptions` attribute can be used to dynamically generate a list of `<option>` |
||
* elements for the `<select>` element using the array or object obtained by evaluating the |
||
* `ngOptions` comprehension_expression. |
||
* |
||
* When an item in the `<select>` menu is selected, the array element or object property |
||
* represented by the selected option will be bound to the model identified by the `ngModel` |
||
* directive. |
||
* |
||
* Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can |
||
* be nested into the `<select>` element. This element will then represent the `null` or "not selected" |
||
* option. See example below for demonstration. |
||
* |
||
* Note: `ngOptions` provides iterator facility for `<option>` element which should be used instead |
||
* of {@link ng.directive:ngRepeat ngRepeat} when you want the |
||
* `select` model to be bound to a non-string value. This is because an option element can only |
||
* be bound to string values at present. |
||
* |
||
* @param {string} ngModel Assignable angular expression to data-bind to. |
||
* @param {string=} name Property name of the form under which the control is published. |
||
* @param {string=} required The control is considered valid only if value is entered. |
||
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to |
||
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of |
||
* `required` when you want to data-bind to the `required` attribute. |
||
* @param {comprehension_expression=} ngOptions in one of the following forms: |
||
* |
||
* * for array data sources: |
||
* * `label` **`for`** `value` **`in`** `array` |
||
* * `select` **`as`** `label` **`for`** `value` **`in`** `array` |
||
* * `label` **`group by`** `group` **`for`** `value` **`in`** `array` |
||
* * `select` **`as`** `label` **`group by`** `group` **`for`** `value` **`in`** `array` **`track by`** `trackexpr` |
||
* * for object data sources: |
||
* * `label` **`for (`**`key` **`,`** `value`**`) in`** `object` |
||
* * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object` |
||
* * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object` |
||
* * `select` **`as`** `label` **`group by`** `group` |
||
* **`for` `(`**`key`**`,`** `value`**`) in`** `object` |
||
* |
||
* Where: |
||
* |
||
* * `array` / `object`: an expression which evaluates to an array / object to iterate over. |
||
* * `value`: local variable which will refer to each item in the `array` or each property value |
||
* of `object` during iteration. |
||
* * `key`: local variable which will refer to a property name in `object` during iteration. |
||
* * `label`: The result of this expression will be the label for `<option>` element. The |
||
* `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`). |
||
* * `select`: The result of this expression will be bound to the model of the parent `<select>` |
||
* element. If not specified, `select` expression will default to `value`. |
||
* * `group`: The result of this expression will be used to group options using the `<optgroup>` |
||
* DOM element. |
||
* * `trackexpr`: Used when working with an array of objects. The result of this expression will be |
||
* used to identify the objects in the array. The `trackexpr` will most likely refer to the |
||
* `value` variable (e.g. `value.propertyName`). |
||
* |
||
* @example |
||
<doc:example> |
||
<doc:source> |
||
<script> |
||
function MyCntrl($scope) { |
||
$scope.colors = [ |
||
{name:'black', shade:'dark'}, |
||
{name:'white', shade:'light'}, |
||
{name:'red', shade:'dark'}, |
||
{name:'blue', shade:'dark'}, |
||
{name:'yellow', shade:'light'} |
||
]; |
||
$scope.color = $scope.colors[2]; // red |
||
} |
||
</script> |
||
<div ng-controller="MyCntrl"> |
||
<ul> |
||
<li ng-repeat="color in colors"> |
||
Name: <input ng-model="color.name"> |
||
[<a href ng-click="colors.splice($index, 1)">X</a>] |
||
</li> |
||
<li> |
||
[<a href ng-click="colors.push({})">add</a>] |
||
</li> |
||
</ul> |
||
<hr/> |
||
Color (null not allowed): |
||
<select ng-model="color" ng-options="c.name for c in colors"></select><br> |
||
|
||
Color (null allowed): |
||
<span class="nullable"> |
||
<select ng-model="color" ng-options="c.name for c in colors"> |
||
<option value="">-- choose color --</option> |
||
</select> |
||
</span><br/> |
||
|
||
Color grouped by shade: |
||
<select ng-model="color" ng-options="c.name group by c.shade for c in colors"> |
||
</select><br/> |
||
|
||
|
||
Select <a href ng-click="color={name:'not in list'}">bogus</a>.<br> |
||
<hr/> |
||
Currently selected: {{ {selected_color:color} }} |
||
<div style="border:solid 1px black; height:20px" |
||
ng-style="{'background-color':color.name}"> |
||
</div> |
||
</div> |
||
</doc:source> |
||
<doc:scenario> |
||
it('should check ng-options', function() { |
||
expect(binding('{selected_color:color}')).toMatch('red'); |
||
select('color').option('0'); |
||
expect(binding('{selected_color:color}')).toMatch('black'); |
||
using('.nullable').select('color').option(''); |
||
expect(binding('{selected_color:color}')).toMatch('null'); |
||
}); |
||
</doc:scenario> |
||
</doc:example> |
||
*/ |
||
|
||
var ngOptionsDirective = valueFn({ terminal: true }); |
||
// jshint maxlen: false |
||
var selectDirective = ['$compile', '$parse', function($compile, $parse) { |
||
//000011111111110000000000022222222220000000000000000000003333333333000000000000004444444444444440000000005555555555555550000000666666666666666000000000000000777777777700000000000000000008888888888 |
||
var NG_OPTIONS_REGEXP = /^\s*([\s\S]+?)(?:\s+as\s+([\s\S]+?))?(?:\s+group\s+by\s+([\s\S]+?))?\s+for\s+(?:([\$\w][\$\w]*)|(?:\(\s*([\$\w][\$\w]*)\s*,\s*([\$\w][\$\w]*)\s*\)))\s+in\s+([\s\S]+?)(?:\s+track\s+by\s+([\s\S]+?))?$/, |
||
nullModelCtrl = {$setViewValue: noop}; |
||
// jshint maxlen: 100 |
||
|
||
return { |
||
restrict: 'E', |
||
require: ['select', '?ngModel'], |
||
controller: ['$element', '$scope', '$attrs', function($element, $scope, $attrs) { |
||
var self = this, |
||
optionsMap = {}, |
||
ngModelCtrl = nullModelCtrl, |
||
nullOption, |
||
unknownOption; |
||
|
||
|
||
self.databound = $attrs.ngModel; |
||
|
||
|
||
self.init = function(ngModelCtrl_, nullOption_, unknownOption_) { |
||
ngModelCtrl = ngModelCtrl_; |
||
nullOption = nullOption_; |
||
unknownOption = unknownOption_; |
||
}; |
||
|
||
|
||
self.addOption = function(value) { |
||
assertNotHasOwnProperty(value, '"option value"'); |
||
optionsMap[value] = true; |
||
|
||
if (ngModelCtrl.$viewValue == value) { |
||
$element.val(value); |
||
if (unknownOption.parent()) unknownOption.remove(); |
||
} |
||
}; |
||
|
||
|
||
self.removeOption = function(value) { |
||
if (this.hasOption(value)) { |
||
delete optionsMap[value]; |
||
if (ngModelCtrl.$viewValue == value) { |
||
this.renderUnknownOption(value); |
||
} |
||
} |
||
}; |
||
|
||
|
||
self.renderUnknownOption = function(val) { |
||
var unknownVal = '? ' + hashKey(val) + ' ?'; |
||
unknownOption.val(unknownVal); |
||
$element.prepend(unknownOption); |
||
$element.val(unknownVal); |
||
unknownOption.prop('selected', true); // needed for IE |
||
}; |
||
|
||
|
||
self.hasOption = function(value) { |
||
return optionsMap.hasOwnProperty(value); |
||
}; |
||
|
||
$scope.$on('$destroy', function() { |
||
// disable unknown option so that we don't do work when the whole select is being destroyed |
||
self.renderUnknownOption = noop; |
||
}); |
||
}], |
||
|
||
link: function(scope, element, attr, ctrls) { |
||
// if ngModel is not defined, we don't need to do anything |
||
if (!ctrls[1]) return; |
||
|
||
var selectCtrl = ctrls[0], |
||
ngModelCtrl = ctrls[1], |
||
multiple = attr.multiple, |
||
optionsExp = attr.ngOptions, |
||
nullOption = false, // if false, user will not be able to select it (used by ngOptions) |
||
emptyOption, |
||
// we can't just jqLite('<option>') since jqLite is not smart enough |
||
// to create it in <select> and IE barfs otherwise. |
||
optionTemplate = jqLite(document.createElement('option')), |
||
optGroupTemplate =jqLite(document.createElement('optgroup')), |
||
unknownOption = optionTemplate.clone(); |
||
|
||
// find "null" option |
||
for(var i = 0, children = element.children(), ii = children.length; i < ii; i++) { |
||
if (children[i].value === '') { |
||
emptyOption = nullOption = children.eq(i); |
||
break; |
||
} |
||
} |
||
|
||
selectCtrl.init(ngModelCtrl, nullOption, unknownOption); |
||
|
||
// required validator |
||
if (multiple) { |
||
ngModelCtrl.$isEmpty = function(value) { |
||
return !value || value.length === 0; |
||
}; |
||
} |
||
|
||
if (optionsExp) setupAsOptions(scope, element, ngModelCtrl); |
||
else if (multiple) setupAsMultiple(scope, element, ngModelCtrl); |
||
else setupAsSingle(scope, element, ngModelCtrl, selectCtrl); |
||
|
||
|
||
//////////////////////////// |
||
|
||
|
||
|
||
function setupAsSingle(scope, selectElement, ngModelCtrl, selectCtrl) { |
||
ngModelCtrl.$render = function() { |
||
var viewValue = ngModelCtrl.$viewValue; |
||
|
||
if (selectCtrl.hasOption(viewValue)) { |
||
if (unknownOption.parent()) unknownOption.remove(); |
||
selectElement.val(viewValue); |
||
if (viewValue === '') emptyOption.prop('selected', true); // to make IE9 happy |
||
} else { |
||
if (isUndefined(viewValue) && emptyOption) { |
||
selectElement.val(''); |
||
} else { |
||
selectCtrl.renderUnknownOption(viewValue); |
||
} |
||
} |
||
}; |
||
|
||
selectElement.on('change', function() { |
||
scope.$apply(function() { |
||
if (unknownOption.parent()) unknownOption.remove(); |
||
ngModelCtrl.$setViewValue(selectElement.val()); |
||
}); |
||
}); |
||
} |
||
|
||
function setupAsMultiple(scope, selectElement, ctrl) { |
||
var lastView; |
||
ctrl.$render = function() { |
||
var items = new HashMap(ctrl.$viewValue); |
||
forEach(selectElement.find('option'), function(option) { |
||
option.selected = isDefined(items.get(option.value)); |
||
}); |
||
}; |
||
|
||
// we have to do it on each watch since ngModel watches reference, but |
||
// we need to work of an array, so we need to see if anything was inserted/removed |
||
scope.$watch(function selectMultipleWatch() { |
||
if (!equals(lastView, ctrl.$viewValue)) { |
||
lastView = copy(ctrl.$viewValue); |
||
ctrl.$render(); |
||
} |
||
}); |
||
|
||
selectElement.on('change', function() { |
||
scope.$apply(function() { |
||
var array = []; |
||
forEach(selectElement.find('option'), function(option) { |
||
if (option.selected) { |
||
array.push(option.value); |
||
} |
||
}); |
||
ctrl.$setViewValue(array); |
||
}); |
||
}); |
||
} |
||
|
||
function setupAsOptions(scope, selectElement, ctrl) { |
||
var match; |
||
|
||
if (! (match = optionsExp.match(NG_OPTIONS_REGEXP))) { |
||
throw ngOptionsMinErr('iexp', |
||
"Expected expression in form of " + |
||
"'_select_ (as _label_)? for (_key_,)?_value_ in _collection_'" + |
||
" but got '{0}'. Element: {1}", |
||
optionsExp, startingTag(selectElement)); |
||
} |
||
|
||
var displayFn = $parse(match[2] || match[1]), |
||
valueName = match[4] || match[6], |
||
keyName = match[5], |
||
groupByFn = $parse(match[3] || ''), |
||
valueFn = $parse(match[2] ? match[1] : valueName), |
||
valuesFn = $parse(match[7]), |
||
track = match[8], |
||
trackFn = track ? $parse(match[8]) : null, |
||
// This is an array of array of existing option groups in DOM. |
||
// We try to reuse these if possible |
||
// - optionGroupsCache[0] is the options with no option group |
||
// - optionGroupsCache[?][0] is the parent: either the SELECT or OPTGROUP element |
||
optionGroupsCache = [[{element: selectElement, label:''}]]; |
||
|
||
if (nullOption) { |
||
// compile the element since there might be bindings in it |
||
$compile(nullOption)(scope); |
||
|
||
// remove the class, which is added automatically because we recompile the element and it |
||
// becomes the compilation root |
||
nullOption.removeClass('ng-scope'); |
||
|
||
// we need to remove it before calling selectElement.empty() because otherwise IE will |
||
// remove the label from the element. wtf? |
||
nullOption.remove(); |
||
} |
||
|
||
// clear contents, we'll add what's needed based on the model |
||
selectElement.empty(); |
||
|
||
selectElement.on('change', function() { |
||
scope.$apply(function() { |
||
var optionGroup, |
||
collection = valuesFn(scope) || [], |
||
locals = {}, |
||
key, value, optionElement, index, groupIndex, length, groupLength, trackIndex; |
||
|
||
if (multiple) { |
||
value = []; |
||
for (groupIndex = 0, groupLength = optionGroupsCache.length; |
||
groupIndex < groupLength; |
||
groupIndex++) { |
||
// list of options for that group. (first item has the parent) |
||
optionGroup = optionGroupsCache[groupIndex]; |
||
|
||
for(index = 1, length = optionGroup.length; index < length; index++) { |
||
if ((optionElement = optionGroup[index].element)[0].selected) { |
||
key = optionElement.val(); |
||
if (keyName) locals[keyName] = key; |
||
if (trackFn) { |
||
for (trackIndex = 0; trackIndex < collection.length; trackIndex++) { |
||
locals[valueName] = collection[trackIndex]; |
||
if (trackFn(scope, locals) == key) break; |
||
} |
||
} else { |
||
locals[valueName] = collection[key]; |
||
} |
||
value.push(valueFn(scope, locals)); |
||
} |
||
} |
||
} |
||
} else { |
||
key = selectElement.val(); |
||
if (key == '?') { |
||
value = undefined; |
||
} else if (key === ''){ |
||
value = null; |
||
} else { |
||
if (trackFn) { |
||
for (trackIndex = 0; trackIndex < collection.length; trackIndex++) { |
||
locals[valueName] = collection[trackIndex]; |
||
if (trackFn(scope, locals) == key) { |
||
value = valueFn(scope, locals); |
||
break; |
||
} |
||
} |
||
} else { |
||
locals[valueName] = collection[key]; |
||
if (keyName) locals[keyName] = key; |
||
value = valueFn(scope, locals); |
||
} |
||
} |
||
} |
||
ctrl.$setViewValue(value); |
||
}); |
||
}); |
||
|
||
ctrl.$render = render; |
||
|
||
// TODO(vojta): can't we optimize this ? |
||
scope.$watch(render); |
||
|
||
function render() { |
||
// Temporary location for the option groups before we render them |
||
var optionGroups = {'':[]}, |
||
optionGroupNames = [''], |
||
optionGroupName, |
||
optionGroup, |
||
option, |
||
existingParent, existingOptions, existingOption, |
||
modelValue = ctrl.$modelValue, |
||
values = valuesFn(scope) || [], |
||
keys = keyName ? sortedKeys(values) : values, |
||
key, |
||
groupLength, length, |
||
groupIndex, index, |
||
locals = {}, |
||
selected, |
||
selectedSet = false, // nothing is selected yet |
||
lastElement, |
||
element, |
||
label; |
||
|
||
if (multiple) { |
||
if (trackFn && isArray(modelValue)) { |
||
selectedSet = new HashMap([]); |
||
for (var trackIndex = 0; trackIndex < modelValue.length; trackIndex++) { |
||
locals[valueName] = modelValue[trackIndex]; |
||
selectedSet.put(trackFn(scope, locals), modelValue[trackIndex]); |
||
} |
||
} else { |
||
selectedSet = new HashMap(modelValue); |
||
} |
||
} |
||
|
||
// We now build up the list of options we need (we merge later) |
||
for (index = 0; length = keys.length, index < length; index++) { |
||
|
||
key = index; |
||
if (keyName) { |
||
key = keys[index]; |
||
if ( key.charAt(0) === '$' ) continue; |
||
locals[keyName] = key; |
||
} |
||
|
||
locals[valueName] = values[key]; |
||
|
||
optionGroupName = groupByFn(scope, locals) || ''; |
||
if (!(optionGroup = optionGroups[optionGroupName])) { |
||
optionGroup = optionGroups[optionGroupName] = []; |
||
optionGroupNames.push(optionGroupName); |
||
} |
||
if (multiple) { |
||
selected = isDefined( |
||
selectedSet.remove(trackFn ? trackFn(scope, locals) : valueFn(scope, locals)) |
||
); |
||
} else { |
||
if (trackFn) { |
||
var modelCast = {}; |
||
modelCast[valueName] = modelValue; |
||
selected = trackFn(scope, modelCast) === trackFn(scope, locals); |
||
} else { |
||
selected = modelValue === valueFn(scope, locals); |
||
} |
||
selectedSet = selectedSet || selected; // see if at least one item is selected |
||
} |
||
label = displayFn(scope, locals); // what will be seen by the user |
||
|
||
// doing displayFn(scope, locals) || '' overwrites zero values |
||
label = isDefined(label) ? label : ''; |
||
optionGroup.push({ |
||
// either the index into array or key from object |
||
id: trackFn ? trackFn(scope, locals) : (keyName ? keys[index] : index), |
||
label: label, |
||
selected: selected // determine if we should be selected |
||
}); |
||
} |
||
if (!multiple) { |
||
if (nullOption || modelValue === null) { |
||
// insert null option if we have a placeholder, or the model is null |
||
optionGroups[''].unshift({id:'', label:'', selected:!selectedSet}); |
||
} else if (!selectedSet) { |
||
// option could not be found, we have to insert the undefined item |
||
optionGroups[''].unshift({id:'?', label:'', selected:true}); |
||
} |
||
} |
||
|
||
// Now we need to update the list of DOM nodes to match the optionGroups we computed above |
||
for (groupIndex = 0, groupLength = optionGroupNames.length; |
||
groupIndex < groupLength; |
||
groupIndex++) { |
||
// current option group name or '' if no group |
||
optionGroupName = optionGroupNames[groupIndex]; |
||
|
||
// list of options for that group. (first item has the parent) |
||
optionGroup = optionGroups[optionGroupName]; |
||
|
||
if (optionGroupsCache.length <= groupIndex) { |
||
// we need to grow the optionGroups |
||
existingParent = { |
||
element: optGroupTemplate.clone().attr('label', optionGroupName), |
||
label: optionGroup.label |
||
}; |
||
existingOptions = [existingParent]; |
||
optionGroupsCache.push(existingOptions); |
||
selectElement.append(existingParent.element); |
||
} else { |
||
existingOptions = optionGroupsCache[groupIndex]; |
||
existingParent = existingOptions[0]; // either SELECT (no group) or OPTGROUP element |
||
|
||
// update the OPTGROUP label if not the same. |
||
if (existingParent.label != optionGroupName) { |
||
existingParent.element.attr('label', existingParent.label = optionGroupName); |
||
} |
||
} |
||
|
||
lastElement = null; // start at the beginning |
||
for(index = 0, length = optionGroup.length; index < length; index++) { |
||
option = optionGroup[index]; |
||
if ((existingOption = existingOptions[index+1])) { |
||
// reuse elements |
||
lastElement = existingOption.element; |
||
if (existingOption.label !== option.label) { |
||
lastElement.text(existingOption.label = option.label); |
||
} |
||
if (existingOption.id !== option.id) { |
||
lastElement.val(existingOption.id = option.id); |
||
} |
||
// lastElement.prop('selected') provided by jQuery has side-effects |
||
if (lastElement[0].selected !== option.selected) { |
||
lastElement.prop('selected', (existingOption.selected = option.selected)); |
||
} |
||
} else { |
||
// grow elements |
||
|
||
// if it's a null option |
||
if (option.id === '' && nullOption) { |
||
// put back the pre-compiled element |
||
element = nullOption; |
||
} else { |
||
// jQuery(v1.4.2) Bug: We should be able to chain the method calls, but |
||
// in this version of jQuery on some browser the .text() returns a string |
||
// rather then the element. |
||
(element = optionTemplate.clone()) |
||
.val(option.id) |
||
.attr('selected', option.selected) |
||
.text(option.label); |
||
} |
||
|
||
existingOptions.push(existingOption = { |
||
element: element, |
||
label: option.label, |
||
id: option.id, |
||
selected: option.selected |
||
}); |
||
if (lastElement) { |
||
lastElement.after(element); |
||
} else { |
||
existingParent.element.append(element); |
||
} |
||
lastElement = element; |
||
} |
||
} |
||
// remove any excessive OPTIONs in a group |
||
index++; // increment since the existingOptions[0] is parent element not OPTION |
||
while(existingOptions.length > index) { |
||
existingOptions.pop().element.remove(); |
||
} |
||
} |
||
// remove any excessive OPTGROUPs from select |
||
while(optionGroupsCache.length > groupIndex) { |
||
optionGroupsCache.pop()[0].element.remove(); |
||
} |
||
} |
||
} |
||
} |
||
}; |
||
}]; |
||
|
||
var optionDirective = ['$interpolate', function($interpolate) { |
||
var nullSelectCtrl = { |
||
addOption: noop, |
||
removeOption: noop |
||
}; |
||
|
||
return { |
||
restrict: 'E', |
||
priority: 100, |
||
compile: function(element, attr) { |
||
if (isUndefined(attr.value)) { |
||
var interpolateFn = $interpolate(element.text(), true); |
||
if (!interpolateFn) { |
||
attr.$set('value', element.text()); |
||
} |
||
} |
||
|
||
return function (scope, element, attr) { |
||
var selectCtrlName = '$selectController', |
||
parent = element.parent(), |
||
selectCtrl = parent.data(selectCtrlName) || |
||
parent.parent().data(selectCtrlName); // in case we are in optgroup |
||
|
||
if (selectCtrl && selectCtrl.databound) { |
||
// For some reason Opera defaults to true and if not overridden this messes up the repeater. |
||
// We don't want the view to drive the initialization of the model anyway. |
||
element.prop('selected', false); |
||
} else { |
||
selectCtrl = nullSelectCtrl; |
||
} |
||
|
||
if (interpolateFn) { |
||
scope.$watch(interpolateFn, function interpolateWatchAction(newVal, oldVal) { |
||
attr.$set('value', newVal); |
||
if (newVal !== oldVal) selectCtrl.removeOption(oldVal); |
||
selectCtrl.addOption(newVal); |
||
}); |
||
} else { |
||
selectCtrl.addOption(attr.value); |
||
} |
||
|
||
element.on('$destroy', function() { |
||
selectCtrl.removeOption(attr.value); |
||
}); |
||
}; |
||
} |
||
}; |
||
}]; |
||
|
||
var styleDirective = valueFn({ |
||
restrict: 'E', |
||
terminal: true |
||
}); |
||
|
||
//try to bind to jquery now so that one can write angular.element().read() |
||
//but we will rebind on bootstrap again. |
||
bindJQuery(); |
||
|
||
publishExternalAPI(angular); |
||
|
||
jqLite(document).ready(function() { |
||
angularInit(document, bootstrap); |
||
}); |
||
|
||
})(window, document); |
||
|
||
!angular.$$csp() && angular.element(document).find('head').prepend('<style type="text/css">@charset "UTF-8";[ng\\:cloak],[ng-cloak],[data-ng-cloak],[x-ng-cloak],.ng-cloak,.x-ng-cloak,.ng-hide{display:none !important;}ng\\:form{display:block;}</style>'); |
||
/** |
||
* @license AngularJS v1.2.9 |
||
* (c) 2010-2014 Google, Inc. http://angularjs.org |
||
* License: MIT |
||
*/ |
||
(function(window, angular, undefined) {'use strict'; |
||
|
||
/** |
||
* @ngdoc overview |
||
* @name ngRoute |
||
* @description |
||
* |
||
* # ngRoute |
||
* |
||
* The `ngRoute` module provides routing and deeplinking services and directives for angular apps. |
||
* |
||
* ## Example |
||
* See {@link ngRoute.$route#example $route} for an example of configuring and using `ngRoute`. |
||
* |
||
* {@installModule route} |
||
* |
||
* <div doc-module-components="ngRoute"></div> |
||
*/ |
||
/* global -ngRouteModule */ |
||
var ngRouteModule = angular.module('ngRoute', ['ng']). |
||
provider('$route', $RouteProvider); |
||
|
||
/** |
||
* @ngdoc object |
||
* @name ngRoute.$routeProvider |
||
* @function |
||
* |
||
* @description |
||
* |
||
* Used for configuring routes. |
||
* |
||
* ## Example |
||
* See {@link ngRoute.$route#example $route} for an example of configuring and using `ngRoute`. |
||
* |
||
* ## Dependencies |
||
* Requires the {@link ngRoute `ngRoute`} module to be installed. |
||
*/ |
||
function $RouteProvider(){ |
||
function inherit(parent, extra) { |
||
return angular.extend(new (angular.extend(function() {}, {prototype:parent}))(), extra); |
||
} |
||
|
||
var routes = {}; |
||
|
||
/** |
||
* @ngdoc method |
||
* @name ngRoute.$routeProvider#when |
||
* @methodOf ngRoute.$routeProvider |
||
* |
||
* @param {string} path Route path (matched against `$location.path`). If `$location.path` |
||
* contains redundant trailing slash or is missing one, the route will still match and the |
||
* `$location.path` will be updated to add or drop the trailing slash to exactly match the |
||
* route definition. |
||
* |
||
* * `path` can contain named groups starting with a colon: e.g. `:name`. All characters up |
||
* to the next slash are matched and stored in `$routeParams` under the given `name` |
||
* when the route matches. |
||
* * `path` can contain named groups starting with a colon and ending with a star: |
||
* e.g.`:name*`. All characters are eagerly stored in `$routeParams` under the given `name` |
||
* when the route matches. |
||
* * `path` can contain optional named groups with a question mark: e.g.`:name?`. |
||
* |
||
* For example, routes like `/color/:color/largecode/:largecode*\/edit` will match |
||
* `/color/brown/largecode/code/with/slashs/edit` and extract: |
||
* |
||
* * `color: brown` |
||
* * `largecode: code/with/slashs`. |
||
* |
||
* |
||
* @param {Object} route Mapping information to be assigned to `$route.current` on route |
||
* match. |
||
* |
||
* Object properties: |
||
* |
||
* - `controller` – `{(string|function()=}` – Controller fn that should be associated with |
||
* newly created scope or the name of a {@link angular.Module#controller registered |
||
* controller} if passed as a string. |
||
* - `controllerAs` – `{string=}` – A controller alias name. If present the controller will be |
||
* published to scope under the `controllerAs` name. |
||
* - `template` – `{string=|function()=}` – html template as a string or a function that |
||
* returns an html template as a string which should be used by {@link |
||
* ngRoute.directive:ngView ngView} or {@link ng.directive:ngInclude ngInclude} directives. |
||
* This property takes precedence over `templateUrl`. |
||
* |
||
* If `template` is a function, it will be called with the following parameters: |
||
* |
||
* - `{Array.<Object>}` - route parameters extracted from the current |
||
* `$location.path()` by applying the current route |
||
* |
||
* - `templateUrl` – `{string=|function()=}` – path or function that returns a path to an html |
||
* template that should be used by {@link ngRoute.directive:ngView ngView}. |
||
* |
||
* If `templateUrl` is a function, it will be called with the following parameters: |
||
* |
||
* - `{Array.<Object>}` - route parameters extracted from the current |
||
* `$location.path()` by applying the current route |
||
* |
||
* - `resolve` - `{Object.<string, function>=}` - An optional map of dependencies which should |
||
* be injected into the controller. If any of these dependencies are promises, the router |
||
* will wait for them all to be resolved or one to be rejected before the controller is |
||
* instantiated. |
||
* If all the promises are resolved successfully, the values of the resolved promises are |
||
* injected and {@link ngRoute.$route#$routeChangeSuccess $routeChangeSuccess} event is |
||
* fired. If any of the promises are rejected the |
||
* {@link ngRoute.$route#$routeChangeError $routeChangeError} event is fired. The map object |
||
* is: |
||
* |
||
* - `key` – `{string}`: a name of a dependency to be injected into the controller. |
||
* - `factory` - `{string|function}`: If `string` then it is an alias for a service. |
||
* Otherwise if function, then it is {@link api/AUTO.$injector#invoke injected} |
||
* and the return value is treated as the dependency. If the result is a promise, it is |
||
* resolved before its value is injected into the controller. Be aware that |
||
* `ngRoute.$routeParams` will still refer to the previous route within these resolve |
||
* functions. Use `$route.current.params` to access the new route parameters, instead. |
||
* |
||
* - `redirectTo` – {(string|function())=} – value to update |
||
* {@link ng.$location $location} path with and trigger route redirection. |
||
* |
||
* If `redirectTo` is a function, it will be called with the following parameters: |
||
* |
||
* - `{Object.<string>}` - route parameters extracted from the current |
||
* `$location.path()` by applying the current route templateUrl. |
||
* - `{string}` - current `$location.path()` |
||
* - `{Object}` - current `$location.search()` |
||
* |
||
* The custom `redirectTo` function is expected to return a string which will be used |
||
* to update `$location.path()` and `$location.search()`. |
||
* |
||
* - `[reloadOnSearch=true]` - {boolean=} - reload route when only `$location.search()` |
||
* or `$location.hash()` changes. |
||
* |
||
* If the option is set to `false` and url in the browser changes, then |
||
* `$routeUpdate` event is broadcasted on the root scope. |
||
* |
||
* - `[caseInsensitiveMatch=false]` - {boolean=} - match routes without being case sensitive |
||
* |
||
* If the option is set to `true`, then the particular route can be matched without being |
||
* case sensitive |
||
* |
||
* @returns {Object} self |
||
* |
||
* @description |
||
* Adds a new route definition to the `$route` service. |
||
*/ |
||
this.when = function(path, route) { |
||
routes[path] = angular.extend( |
||
{reloadOnSearch: true}, |
||
route, |
||
path && pathRegExp(path, route) |
||
); |
||
|
||
// create redirection for trailing slashes |
||
if (path) { |
||
var redirectPath = (path[path.length-1] == '/') |
||
? path.substr(0, path.length-1) |
||
: path +'/'; |
||
|
||
routes[redirectPath] = angular.extend( |
||
{redirectTo: path}, |
||
pathRegExp(redirectPath, route) |
||
); |
||
} |
||
|
||
return this; |
||
}; |
||
|
||
/** |
||
* @param path {string} path |
||
* @param opts {Object} options |
||
* @return {?Object} |
||
* |
||
* @description |
||
* Normalizes the given path, returning a regular expression |
||
* and the original path. |
||
* |
||
* Inspired by pathRexp in visionmedia/express/lib/utils.js. |
||
*/ |
||
function pathRegExp(path, opts) { |
||
var insensitive = opts.caseInsensitiveMatch, |
||
ret = { |
||
originalPath: path, |
||
regexp: path |
||
}, |
||
keys = ret.keys = []; |
||
|
||
path = path |
||
.replace(/([().])/g, '\\$1') |
||
.replace(/(\/)?:(\w+)([\?|\*])?/g, function(_, slash, key, option){ |
||
var optional = option === '?' ? option : null; |
||
var star = option === '*' ? option : null; |
||
keys.push({ name: key, optional: !!optional }); |
||
slash = slash || ''; |
||
return '' |
||
+ (optional ? '' : slash) |
||
+ '(?:' |
||
+ (optional ? slash : '') |
||
+ (star && '(.+?)' || '([^/]+)') |
||
+ (optional || '') |
||
+ ')' |
||
+ (optional || ''); |
||
}) |
||
.replace(/([\/$\*])/g, '\\$1'); |
||
|
||
ret.regexp = new RegExp('^' + path + '$', insensitive ? 'i' : ''); |
||
return ret; |
||
} |
||
|
||
/** |
||
* @ngdoc method |
||
* @name ngRoute.$routeProvider#otherwise |
||
* @methodOf ngRoute.$routeProvider |
||
* |
||
* @description |
||
* Sets route definition that will be used on route change when no other route definition |
||
* is matched. |
||
* |
||
* @param {Object} params Mapping information to be assigned to `$route.current`. |
||
* @returns {Object} self |
||
*/ |
||
this.otherwise = function(params) { |
||
this.when(null, params); |
||
return this; |
||
}; |
||
|
||
|
||
this.$get = ['$rootScope', |
||
'$location', |
||
'$routeParams', |
||
'$q', |
||
'$injector', |
||
'$http', |
||
'$templateCache', |
||
'$sce', |
||
function($rootScope, $location, $routeParams, $q, $injector, $http, $templateCache, $sce) { |
||
|
||
/** |
||
* @ngdoc object |
||
* @name ngRoute.$route |
||
* @requires $location |
||
* @requires $routeParams |
||
* |
||
* @property {Object} current Reference to the current route definition. |
||
* The route definition contains: |
||
* |
||
* - `controller`: The controller constructor as define in route definition. |
||
* - `locals`: A map of locals which is used by {@link ng.$controller $controller} service for |
||
* controller instantiation. The `locals` contain |
||
* the resolved values of the `resolve` map. Additionally the `locals` also contain: |
||
* |
||
* - `$scope` - The current route scope. |
||
* - `$template` - The current route template HTML. |
||
* |
||
* @property {Array.<Object>} routes Array of all configured routes. |
||
* |
||
* @description |
||
* `$route` is used for deep-linking URLs to controllers and views (HTML partials). |
||
* It watches `$location.url()` and tries to map the path to an existing route definition. |
||
* |
||
* Requires the {@link ngRoute `ngRoute`} module to be installed. |
||
* |
||
* You can define routes through {@link ngRoute.$routeProvider $routeProvider}'s API. |
||
* |
||
* The `$route` service is typically used in conjunction with the |
||
* {@link ngRoute.directive:ngView `ngView`} directive and the |
||
* {@link ngRoute.$routeParams `$routeParams`} service. |
||
* |
||
* @example |
||
This example shows how changing the URL hash causes the `$route` to match a route against the |
||
URL, and the `ngView` pulls in the partial. |
||
|
||
Note that this example is using {@link ng.directive:script inlined templates} |
||
to get it working on jsfiddle as well. |
||
|
||
<example module="ngViewExample" deps="angular-route.js"> |
||
<file name="index.html"> |
||
<div ng-controller="MainCntl"> |
||
Choose: |
||
<a href="Book/Moby">Moby</a> | |
||
<a href="Book/Moby/ch/1">Moby: Ch1</a> | |
||
<a href="Book/Gatsby">Gatsby</a> | |
||
<a href="Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a> | |
||
<a href="Book/Scarlet">Scarlet Letter</a><br/> |
||
|
||
<div ng-view></div> |
||
<hr /> |
||
|
||
<pre>$location.path() = {{$location.path()}}</pre> |
||
<pre>$route.current.templateUrl = {{$route.current.templateUrl}}</pre> |
||
<pre>$route.current.params = {{$route.current.params}}</pre> |
||
<pre>$route.current.scope.name = {{$route.current.scope.name}}</pre> |
||
<pre>$routeParams = {{$routeParams}}</pre> |
||
</div> |
||
</file> |
||
|
||
<file name="book.html"> |
||
controller: {{name}}<br /> |
||
Book Id: {{params.bookId}}<br /> |
||
</file> |
||
|
||
<file name="chapter.html"> |
||
controller: {{name}}<br /> |
||
Book Id: {{params.bookId}}<br /> |
||
Chapter Id: {{params.chapterId}} |
||
</file> |
||
|
||
<file name="script.js"> |
||
angular.module('ngViewExample', ['ngRoute']) |
||
|
||
.config(function($routeProvider, $locationProvider) { |
||
$routeProvider.when('/Book/:bookId', { |
||
templateUrl: 'book.html', |
||
controller: BookCntl, |
||
resolve: { |
||
// I will cause a 1 second delay |
||
delay: function($q, $timeout) { |
||
var delay = $q.defer(); |
||
$timeout(delay.resolve, 1000); |
||
return delay.promise; |
||
} |
||
} |
||
}); |
||
$routeProvider.when('/Book/:bookId/ch/:chapterId', { |
||
templateUrl: 'chapter.html', |
||
controller: ChapterCntl |
||
}); |
||
|
||
// configure html5 to get links working on jsfiddle |
||
$locationProvider.html5Mode(true); |
||
}); |
||
|
||
function MainCntl($scope, $route, $routeParams, $location) { |
||
$scope.$route = $route; |
||
$scope.$location = $location; |
||
$scope.$routeParams = $routeParams; |
||
} |
||
|
||
function BookCntl($scope, $routeParams) { |
||
$scope.name = "BookCntl"; |
||
$scope.params = $routeParams; |
||
} |
||
|
||
function ChapterCntl($scope, $routeParams) { |
||
$scope.name = "ChapterCntl"; |
||
$scope.params = $routeParams; |
||
} |
||
</file> |
||
|
||
<file name="scenario.js"> |
||
it('should load and compile correct template', function() { |
||
element('a:contains("Moby: Ch1")').click(); |
||
var content = element('.doc-example-live [ng-view]').text(); |
||
expect(content).toMatch(/controller\: ChapterCntl/); |
||
expect(content).toMatch(/Book Id\: Moby/); |
||
expect(content).toMatch(/Chapter Id\: 1/); |
||
|
||
element('a:contains("Scarlet")').click(); |
||
sleep(2); // promises are not part of scenario waiting |
||
content = element('.doc-example-live [ng-view]').text(); |
||
expect(content).toMatch(/controller\: BookCntl/); |
||
expect(content).toMatch(/Book Id\: Scarlet/); |
||
}); |
||
</file> |
||
</example> |
||
*/ |
||
|
||
/** |
||
* @ngdoc event |
||
* @name ngRoute.$route#$routeChangeStart |
||
* @eventOf ngRoute.$route |
||
* @eventType broadcast on root scope |
||
* @description |
||
* Broadcasted before a route change. At this point the route services starts |
||
* resolving all of the dependencies needed for the route change to occurs. |
||
* Typically this involves fetching the view template as well as any dependencies |
||
* defined in `resolve` route property. Once all of the dependencies are resolved |
||
* `$routeChangeSuccess` is fired. |
||
* |
||
* @param {Object} angularEvent Synthetic event object. |
||
* @param {Route} next Future route information. |
||
* @param {Route} current Current route information. |
||
*/ |
||
|
||
/** |
||
* @ngdoc event |
||
* @name ngRoute.$route#$routeChangeSuccess |
||
* @eventOf ngRoute.$route |
||
* @eventType broadcast on root scope |
||
* @description |
||
* Broadcasted after a route dependencies are resolved. |
||
* {@link ngRoute.directive:ngView ngView} listens for the directive |
||
* to instantiate the controller and render the view. |
||
* |
||
* @param {Object} angularEvent Synthetic event object. |
||
* @param {Route} current Current route information. |
||
* @param {Route|Undefined} previous Previous route information, or undefined if current is |
||
* first route entered. |
||
*/ |
||
|
||
/** |
||
* @ngdoc event |
||
* @name ngRoute.$route#$routeChangeError |
||
* @eventOf ngRoute.$route |
||
* @eventType broadcast on root scope |
||
* @description |
||
* Broadcasted if any of the resolve promises are rejected. |
||
* |
||
* @param {Object} angularEvent Synthetic event object |
||
* @param {Route} current Current route information. |
||
* @param {Route} previous Previous route information. |
||
* @param {Route} rejection Rejection of the promise. Usually the error of the failed promise. |
||
*/ |
||
|
||
/** |
||
* @ngdoc event |
||
* @name ngRoute.$route#$routeUpdate |
||
* @eventOf ngRoute.$route |
||
* @eventType broadcast on root scope |
||
* @description |
||
* |
||
* The `reloadOnSearch` property has been set to false, and we are reusing the same |
||
* instance of the Controller. |
||
*/ |
||
|
||
var forceReload = false, |
||
$route = { |
||
routes: routes, |
||
|
||
/** |
||
* @ngdoc method |
||
* @name ngRoute.$route#reload |
||
* @methodOf ngRoute.$route |
||
* |
||
* @description |
||
* Causes `$route` service to reload the current route even if |
||
* {@link ng.$location $location} hasn't changed. |
||
* |
||
* As a result of that, {@link ngRoute.directive:ngView ngView} |
||
* creates new scope, reinstantiates the controller. |
||
*/ |
||
reload: function() { |
||
forceReload = true; |
||
$rootScope.$evalAsync(updateRoute); |
||
} |
||
}; |
||
|
||
$rootScope.$on('$locationChangeSuccess', updateRoute); |
||
|
||
return $route; |
||
|
||
///////////////////////////////////////////////////// |
||
|
||
/** |
||
* @param on {string} current url |
||
* @param route {Object} route regexp to match the url against |
||
* @return {?Object} |
||
* |
||
* @description |
||
* Check if the route matches the current url. |
||
* |
||
* Inspired by match in |
||
* visionmedia/express/lib/router/router.js. |
||
*/ |
||
function switchRouteMatcher(on, route) { |
||
var keys = route.keys, |
||
params = {}; |
||
|
||
if (!route.regexp) return null; |
||
|
||
var m = route.regexp.exec(on); |
||
if (!m) return null; |
||
|
||
for (var i = 1, len = m.length; i < len; ++i) { |
||
var key = keys[i - 1]; |
||
|
||
var val = 'string' == typeof m[i] |
||
? decodeURIComponent(m[i]) |
||
: m[i]; |
||
|
||
if (key && val) { |
||
params[key.name] = val; |
||
} |
||
} |
||
return params; |
||
} |
||
|
||
function updateRoute() { |
||
var next = parseRoute(), |
||
last = $route.current; |
||
|
||
if (next && last && next.$$route === last.$$route |
||
&& angular.equals(next.pathParams, last.pathParams) |
||
&& !next.reloadOnSearch && !forceReload) { |
||
last.params = next.params; |
||
angular.copy(last.params, $routeParams); |
||
$rootScope.$broadcast('$routeUpdate', last); |
||
} else if (next || last) { |
||
forceReload = false; |
||
$rootScope.$broadcast('$routeChangeStart', next, last); |
||
$route.current = next; |
||
if (next) { |
||
if (next.redirectTo) { |
||
if (angular.isString(next.redirectTo)) { |
||
$location.path(interpolate(next.redirectTo, next.params)).search(next.params) |
||
.replace(); |
||
} else { |
||
$location.url(next.redirectTo(next.pathParams, $location.path(), $location.search())) |
||
.replace(); |
||
} |
||
} |
||
} |
||
|
||
$q.when(next). |
||
then(function() { |
||
if (next) { |
||
var locals = angular.extend({}, next.resolve), |
||
template, templateUrl; |
||
|
||
angular.forEach(locals, function(value, key) { |
||
locals[key] = angular.isString(value) ? |
||
$injector.get(value) : $injector.invoke(value); |
||
}); |
||
|
||
if (angular.isDefined(template = next.template)) { |
||
if (angular.isFunction(template)) { |
||
template = template(next.params); |
||
} |
||
} else if (angular.isDefined(templateUrl = next.templateUrl)) { |
||
if (angular.isFunction(templateUrl)) { |
||
templateUrl = templateUrl(next.params); |
||
} |
||
templateUrl = $sce.getTrustedResourceUrl(templateUrl); |
||
if (angular.isDefined(templateUrl)) { |
||
next.loadedTemplateUrl = templateUrl; |
||
template = $http.get(templateUrl, {cache: $templateCache}). |
||
then(function(response) { return response.data; }); |
||
} |
||
} |
||
if (angular.isDefined(template)) { |
||
locals['$template'] = template; |
||
} |
||
return $q.all(locals); |
||
} |
||
}). |
||
// after route change |
||
then(function(locals) { |
||
if (next == $route.current) { |
||
if (next) { |
||
next.locals = locals; |
||
angular.copy(next.params, $routeParams); |
||
} |
||
$rootScope.$broadcast('$routeChangeSuccess', next, last); |
||
} |
||
}, function(error) { |
||
if (next == $route.current) { |
||
$rootScope.$broadcast('$routeChangeError', next, last, error); |
||
} |
||
}); |
||
} |
||
} |
||
|
||
|
||
/** |
||
* @returns the current active route, by matching it against the URL |
||
*/ |
||
function parseRoute() { |
||
// Match a route |
||
var params, match; |
||
angular.forEach(routes, function(route, path) { |
||
if (!match && (params = switchRouteMatcher($location.path(), route))) { |
||
match = inherit(route, { |
||
params: angular.extend({}, $location.search(), params), |
||
pathParams: params}); |
||
match.$$route = route; |
||
} |
||
}); |
||
// No route matched; fallback to "otherwise" route |
||
return match || routes[null] && inherit(routes[null], {params: {}, pathParams:{}}); |
||
} |
||
|
||
/** |
||
* @returns interpolation of the redirect path with the parameters |
||
*/ |
||
function interpolate(string, params) { |
||
var result = []; |
||
angular.forEach((string||'').split(':'), function(segment, i) { |
||
if (i === 0) { |
||
result.push(segment); |
||
} else { |
||
var segmentMatch = segment.match(/(\w+)(.*)/); |
||
var key = segmentMatch[1]; |
||
result.push(params[key]); |
||
result.push(segmentMatch[2] || ''); |
||
delete params[key]; |
||
} |
||
}); |
||
return result.join(''); |
||
} |
||
}]; |
||
} |
||
|
||
ngRouteModule.provider('$routeParams', $RouteParamsProvider); |
||
|
||
|
||
/** |
||
* @ngdoc object |
||
* @name ngRoute.$routeParams |
||
* @requires $route |
||
* |
||
* @description |
||
* The `$routeParams` service allows you to retrieve the current set of route parameters. |
||
* |
||
* Requires the {@link ngRoute `ngRoute`} module to be installed. |
||
* |
||
* The route parameters are a combination of {@link ng.$location `$location`}'s |
||
* {@link ng.$location#methods_search `search()`} and {@link ng.$location#methods_path `path()`}. |
||
* The `path` parameters are extracted when the {@link ngRoute.$route `$route`} path is matched. |
||
* |
||
* In case of parameter name collision, `path` params take precedence over `search` params. |
||
* |
||
* The service guarantees that the identity of the `$routeParams` object will remain unchanged |
||
* (but its properties will likely change) even when a route change occurs. |
||
* |
||
* Note that the `$routeParams` are only updated *after* a route change completes successfully. |
||
* This means that you cannot rely on `$routeParams` being correct in route resolve functions. |
||
* Instead you can use `$route.current.params` to access the new route's parameters. |
||
* |
||
* @example |
||
* <pre> |
||
* // Given: |
||
* // URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby |
||
* // Route: /Chapter/:chapterId/Section/:sectionId |
||
* // |
||
* // Then |
||
* $routeParams ==> {chapterId:1, sectionId:2, search:'moby'} |
||
* </pre> |
||
*/ |
||
function $RouteParamsProvider() { |
||
this.$get = function() { return {}; }; |
||
} |
||
|
||
ngRouteModule.directive('ngView', ngViewFactory); |
||
ngRouteModule.directive('ngView', ngViewFillContentFactory); |
||
|
||
|
||
/** |
||
* @ngdoc directive |
||
* @name ngRoute.directive:ngView |
||
* @restrict ECA |
||
* |
||
* @description |
||
* # Overview |
||
* `ngView` is a directive that complements the {@link ngRoute.$route $route} service by |
||
* including the rendered template of the current route into the main layout (`index.html`) file. |
||
* Every time the current route changes, the included view changes with it according to the |
||
* configuration of the `$route` service. |
||
* |
||
* Requires the {@link ngRoute `ngRoute`} module to be installed. |
||
* |
||
* @animations |
||
* enter - animation is used to bring new content into the browser. |
||
* leave - animation is used to animate existing content away. |
||
* |
||
* The enter and leave animation occur concurrently. |
||
* |
||
* @scope |
||
* @priority 400 |
||
* @param {string=} onload Expression to evaluate whenever the view updates. |
||
* |
||
* @param {string=} autoscroll Whether `ngView` should call {@link ng.$anchorScroll |
||
* $anchorScroll} to scroll the viewport after the view is updated. |
||
* |
||
* - If the attribute is not set, disable scrolling. |
||
* - If the attribute is set without value, enable scrolling. |
||
* - Otherwise enable scrolling only if the `autoscroll` attribute value evaluated |
||
* as an expression yields a truthy value. |
||
* @example |
||
<example module="ngViewExample" deps="angular-route.js" animations="true"> |
||
<file name="index.html"> |
||
<div ng-controller="MainCntl as main"> |
||
Choose: |
||
<a href="Book/Moby">Moby</a> | |
||
<a href="Book/Moby/ch/1">Moby: Ch1</a> | |
||
<a href="Book/Gatsby">Gatsby</a> | |
||
<a href="Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a> | |
||
<a href="Book/Scarlet">Scarlet Letter</a><br/> |
||
|
||
<div class="view-animate-container"> |
||
<div ng-view class="view-animate"></div> |
||
</div> |
||
<hr /> |
||
|
||
<pre>$location.path() = {{main.$location.path()}}</pre> |
||
<pre>$route.current.templateUrl = {{main.$route.current.templateUrl}}</pre> |
||
<pre>$route.current.params = {{main.$route.current.params}}</pre> |
||
<pre>$route.current.scope.name = {{main.$route.current.scope.name}}</pre> |
||
<pre>$routeParams = {{main.$routeParams}}</pre> |
||
</div> |
||
</file> |
||
|
||
<file name="book.html"> |
||
<div> |
||
controller: {{book.name}}<br /> |
||
Book Id: {{book.params.bookId}}<br /> |
||
</div> |
||
</file> |
||
|
||
<file name="chapter.html"> |
||
<div> |
||
controller: {{chapter.name}}<br /> |
||
Book Id: {{chapter.params.bookId}}<br /> |
||
Chapter Id: {{chapter.params.chapterId}} |
||
</div> |
||
</file> |
||
|
||
<file name="animations.css"> |
||
.view-animate-container { |
||
position:relative; |
||
height:100px!important; |
||
position:relative; |
||
background:white; |
||
border:1px solid black; |
||
height:40px; |
||
overflow:hidden; |
||
} |
||
|
||
.view-animate { |
||
padding:10px; |
||
} |
||
|
||
.view-animate.ng-enter, .view-animate.ng-leave { |
||
-webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s; |
||
transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s; |
||
|
||
display:block; |
||
width:100%; |
||
border-left:1px solid black; |
||
|
||
position:absolute; |
||
top:0; |
||
left:0; |
||
right:0; |
||
bottom:0; |
||
padding:10px; |
||
} |
||
|
||
.view-animate.ng-enter { |
||
left:100%; |
||
} |
||
.view-animate.ng-enter.ng-enter-active { |
||
left:0; |
||
} |
||
.view-animate.ng-leave.ng-leave-active { |
||
left:-100%; |
||
} |
||
</file> |
||
|
||
<file name="script.js"> |
||
angular.module('ngViewExample', ['ngRoute', 'ngAnimate'], |
||
function($routeProvider, $locationProvider) { |
||
$routeProvider.when('/Book/:bookId', { |
||
templateUrl: 'book.html', |
||
controller: BookCntl, |
||
controllerAs: 'book' |
||
}); |
||
$routeProvider.when('/Book/:bookId/ch/:chapterId', { |
||
templateUrl: 'chapter.html', |
||
controller: ChapterCntl, |
||
controllerAs: 'chapter' |
||
}); |
||
|
||
// configure html5 to get links working on jsfiddle |
||
$locationProvider.html5Mode(true); |
||
}); |
||
|
||
function MainCntl($route, $routeParams, $location) { |
||
this.$route = $route; |
||
this.$location = $location; |
||
this.$routeParams = $routeParams; |
||
} |
||
|
||
function BookCntl($routeParams) { |
||
this.name = "BookCntl"; |
||
this.params = $routeParams; |
||
} |
||
|
||
function ChapterCntl($routeParams) { |
||
this.name = "ChapterCntl"; |
||
this.params = $routeParams; |
||
} |
||
</file> |
||
|
||
<file name="scenario.js"> |
||
it('should load and compile correct template', function() { |
||
element('a:contains("Moby: Ch1")').click(); |
||
var content = element('.doc-example-live [ng-view]').text(); |
||
expect(content).toMatch(/controller\: ChapterCntl/); |
||
expect(content).toMatch(/Book Id\: Moby/); |
||
expect(content).toMatch(/Chapter Id\: 1/); |
||
|
||
element('a:contains("Scarlet")').click(); |
||
content = element('.doc-example-live [ng-view]').text(); |
||
expect(content).toMatch(/controller\: BookCntl/); |
||
expect(content).toMatch(/Book Id\: Scarlet/); |
||
}); |
||
</file> |
||
</example> |
||
*/ |
||
|
||
|
||
/** |
||
* @ngdoc event |
||
* @name ngRoute.directive:ngView#$viewContentLoaded |
||
* @eventOf ngRoute.directive:ngView |
||
* @eventType emit on the current ngView scope |
||
* @description |
||
* Emitted every time the ngView content is reloaded. |
||
*/ |
||
ngViewFactory.$inject = ['$route', '$anchorScroll', '$animate']; |
||
function ngViewFactory( $route, $anchorScroll, $animate) { |
||
return { |
||
restrict: 'ECA', |
||
terminal: true, |
||
priority: 400, |
||
transclude: 'element', |
||
link: function(scope, $element, attr, ctrl, $transclude) { |
||
var currentScope, |
||
currentElement, |
||
autoScrollExp = attr.autoscroll, |
||
onloadExp = attr.onload || ''; |
||
|
||
scope.$on('$routeChangeSuccess', update); |
||
update(); |
||
|
||
function cleanupLastView() { |
||
if (currentScope) { |
||
currentScope.$destroy(); |
||
currentScope = null; |
||
} |
||
if(currentElement) { |
||
$animate.leave(currentElement); |
||
currentElement = null; |
||
} |
||
} |
||
|
||
function update() { |
||
var locals = $route.current && $route.current.locals, |
||
template = locals && locals.$template; |
||
|
||
if (angular.isDefined(template)) { |
||
var newScope = scope.$new(); |
||
var current = $route.current; |
||
|
||
// Note: This will also link all children of ng-view that were contained in the original |
||
// html. If that content contains controllers, ... they could pollute/change the scope. |
||
// However, using ng-view on an element with additional content does not make sense... |
||
// Note: We can't remove them in the cloneAttchFn of $transclude as that |
||
// function is called before linking the content, which would apply child |
||
// directives to non existing elements. |
||
var clone = $transclude(newScope, function(clone) { |
||
$animate.enter(clone, null, currentElement || $element, function onNgViewEnter () { |
||
if (angular.isDefined(autoScrollExp) |
||
&& (!autoScrollExp || scope.$eval(autoScrollExp))) { |
||
$anchorScroll(); |
||
} |
||
}); |
||
cleanupLastView(); |
||
}); |
||
|
||
currentElement = clone; |
||
currentScope = current.scope = newScope; |
||
currentScope.$emit('$viewContentLoaded'); |
||
currentScope.$eval(onloadExp); |
||
} else { |
||
cleanupLastView(); |
||
} |
||
} |
||
} |
||
}; |
||
} |
||
|
||
// This directive is called during the $transclude call of the first `ngView` directive. |
||
// It will replace and compile the content of the element with the loaded template. |
||
// We need this directive so that the element content is already filled when |
||
// the link function of another directive on the same element as ngView |
||
// is called. |
||
ngViewFillContentFactory.$inject = ['$compile', '$controller', '$route']; |
||
function ngViewFillContentFactory($compile, $controller, $route) { |
||
return { |
||
restrict: 'ECA', |
||
priority: -400, |
||
link: function(scope, $element) { |
||
var current = $route.current, |
||
locals = current.locals; |
||
|
||
$element.html(locals.$template); |
||
|
||
var link = $compile($element.contents()); |
||
|
||
if (current.controller) { |
||
locals.$scope = scope; |
||
var controller = $controller(current.controller, locals); |
||
if (current.controllerAs) { |
||
scope[current.controllerAs] = controller; |
||
} |
||
$element.data('$ngControllerController', controller); |
||
$element.children().data('$ngControllerController', controller); |
||
} |
||
|
||
link(scope); |
||
} |
||
}; |
||
} |
||
|
||
|
||
})(window, window.angular); |
||
|
||
/** |
||
* @license AngularJS v1.2.9 |
||
* (c) 2010-2014 Google, Inc. http://angularjs.org |
||
* License: MIT |
||
*/ |
||
(function(window, angular, undefined) {'use strict'; |
||
|
||
/* jshint maxlen: false */ |
||
|
||
/** |
||
* @ngdoc overview |
||
* @name ngAnimate |
||
* @description |
||
* |
||
* # ngAnimate |
||
* |
||
* The `ngAnimate` module provides support for JavaScript, CSS3 transition and CSS3 keyframe animation hooks within existing core and custom directives. |
||
* |
||
* {@installModule animate} |
||
* |
||
* <div doc-module-components="ngAnimate"></div> |
||
* |
||
* # Usage |
||
* |
||
* To see animations in action, all that is required is to define the appropriate CSS classes |
||
* or to register a JavaScript animation via the myModule.animation() function. The directives that support animation automatically are: |
||
* `ngRepeat`, `ngInclude`, `ngIf`, `ngSwitch`, `ngShow`, `ngHide`, `ngView` and `ngClass`. Custom directives can take advantage of animation |
||
* by using the `$animate` service. |
||
* |
||
* Below is a more detailed breakdown of the supported animation events provided by pre-existing ng directives: |
||
* |
||
* | Directive | Supported Animations | |
||
* |---------------------------------------------------------- |----------------------------------------------------| |
||
* | {@link ng.directive:ngRepeat#usage_animations ngRepeat} | enter, leave and move | |
||
* | {@link ngRoute.directive:ngView#usage_animations ngView} | enter and leave | |
||
* | {@link ng.directive:ngInclude#usage_animations ngInclude} | enter and leave | |
||
* | {@link ng.directive:ngSwitch#usage_animations ngSwitch} | enter and leave | |
||
* | {@link ng.directive:ngIf#usage_animations ngIf} | enter and leave | |
||
* | {@link ng.directive:ngClass#usage_animations ngClass} | add and remove | |
||
* | {@link ng.directive:ngShow#usage_animations ngShow & ngHide} | add and remove (the ng-hide class value) | |
||
* |
||
* You can find out more information about animations upon visiting each directive page. |
||
* |
||
* Below is an example of how to apply animations to a directive that supports animation hooks: |
||
* |
||
* <pre> |
||
* <style type="text/css"> |
||
* .slide.ng-enter, .slide.ng-leave { |
||
* -webkit-transition:0.5s linear all; |
||
* transition:0.5s linear all; |
||
* } |
||
* |
||
* .slide.ng-enter { } /* starting animations for enter */ |
||
* .slide.ng-enter-active { } /* terminal animations for enter */ |
||
* .slide.ng-leave { } /* starting animations for leave */ |
||
* .slide.ng-leave-active { } /* terminal animations for leave */ |
||
* </style> |
||
* |
||
* <!-- |
||
* the animate service will automatically add .ng-enter and .ng-leave to the element |
||
* to trigger the CSS transition/animations |
||
* --> |
||
* <ANY class="slide" ng-include="..."></ANY> |
||
* </pre> |
||
* |
||
* Keep in mind that if an animation is running, any child elements cannot be animated until the parent element's |
||
* animation has completed. |
||
* |
||
* <h2>CSS-defined Animations</h2> |
||
* The animate service will automatically apply two CSS classes to the animated element and these two CSS classes |
||
* are designed to contain the start and end CSS styling. Both CSS transitions and keyframe animations are supported |
||
* and can be used to play along with this naming structure. |
||
* |
||
* The following code below demonstrates how to perform animations using **CSS transitions** with Angular: |
||
* |
||
* <pre> |
||
* <style type="text/css"> |
||
* /* |
||
* The animate class is apart of the element and the ng-enter class |
||
* is attached to the element once the enter animation event is triggered |
||
* */ |
||
* .reveal-animation.ng-enter { |
||
* -webkit-transition: 1s linear all; /* Safari/Chrome */ |
||
* transition: 1s linear all; /* All other modern browsers and IE10+ */ |
||
* |
||
* /* The animation preparation code */ |
||
* opacity: 0; |
||
* } |
||
* |
||
* /* |
||
* Keep in mind that you want to combine both CSS |
||
* classes together to avoid any CSS-specificity |
||
* conflicts |
||
* */ |
||
* .reveal-animation.ng-enter.ng-enter-active { |
||
* /* The animation code itself */ |
||
* opacity: 1; |
||
* } |
||
* </style> |
||
* |
||
* <div class="view-container"> |
||
* <div ng-view class="reveal-animation"></div> |
||
* </div> |
||
* </pre> |
||
* |
||
* The following code below demonstrates how to perform animations using **CSS animations** with Angular: |
||
* |
||
* <pre> |
||
* <style type="text/css"> |
||
* .reveal-animation.ng-enter { |
||
* -webkit-animation: enter_sequence 1s linear; /* Safari/Chrome */ |
||
* animation: enter_sequence 1s linear; /* IE10+ and Future Browsers */ |
||
* } |
||
* @-webkit-keyframes enter_sequence { |
||
* from { opacity:0; } |
||
* to { opacity:1; } |
||
* } |
||
* @keyframes enter_sequence { |
||
* from { opacity:0; } |
||
* to { opacity:1; } |
||
* } |
||
* </style> |
||
* |
||
* <div class="view-container"> |
||
* <div ng-view class="reveal-animation"></div> |
||
* </div> |
||
* </pre> |
||
* |
||
* Both CSS3 animations and transitions can be used together and the animate service will figure out the correct duration and delay timing. |
||
* |
||
* Upon DOM mutation, the event class is added first (something like `ng-enter`), then the browser prepares itself to add |
||
* the active class (in this case `ng-enter-active`) which then triggers the animation. The animation module will automatically |
||
* detect the CSS code to determine when the animation ends. Once the animation is over then both CSS classes will be |
||
* removed from the DOM. If a browser does not support CSS transitions or CSS animations then the animation will start and end |
||
* immediately resulting in a DOM element that is at its final state. This final state is when the DOM element |
||
* has no CSS transition/animation classes applied to it. |
||
* |
||
* <h3>CSS Staggering Animations</h3> |
||
* A Staggering animation is a collection of animations that are issued with a slight delay in between each successive operation resulting in a |
||
* curtain-like effect. The ngAnimate module, as of 1.2.0, supports staggering animations and the stagger effect can be |
||
* performed by creating a **ng-EVENT-stagger** CSS class and attaching that class to the base CSS class used for |
||
* the animation. The style property expected within the stagger class can either be a **transition-delay** or an |
||
* **animation-delay** property (or both if your animation contains both transitions and keyframe animations). |
||
* |
||
* <pre> |
||
* .my-animation.ng-enter { |
||
* /* standard transition code */ |
||
* -webkit-transition: 1s linear all; |
||
* transition: 1s linear all; |
||
* opacity:0; |
||
* } |
||
* .my-animation.ng-enter-stagger { |
||
* /* this will have a 100ms delay between each successive leave animation */ |
||
* -webkit-transition-delay: 0.1s; |
||
* transition-delay: 0.1s; |
||
* |
||
* /* in case the stagger doesn't work then these two values |
||
* must be set to 0 to avoid an accidental CSS inheritance */ |
||
* -webkit-transition-duration: 0s; |
||
* transition-duration: 0s; |
||
* } |
||
* .my-animation.ng-enter.ng-enter-active { |
||
* /* standard transition styles */ |
||
* opacity:1; |
||
* } |
||
* </pre> |
||
* |
||
* Staggering animations work by default in ngRepeat (so long as the CSS class is defined). Outside of ngRepeat, to use staggering animations |
||
* on your own, they can be triggered by firing multiple calls to the same event on $animate. However, the restrictions surrounding this |
||
* are that each of the elements must have the same CSS className value as well as the same parent element. A stagger operation |
||
* will also be reset if more than 10ms has passed after the last animation has been fired. |
||
* |
||
* The following code will issue the **ng-leave-stagger** event on the element provided: |
||
* |
||
* <pre> |
||
* var kids = parent.children(); |
||
* |
||
* $animate.leave(kids[0]); //stagger index=0 |
||
* $animate.leave(kids[1]); //stagger index=1 |
||
* $animate.leave(kids[2]); //stagger index=2 |
||
* $animate.leave(kids[3]); //stagger index=3 |
||
* $animate.leave(kids[4]); //stagger index=4 |
||
* |
||
* $timeout(function() { |
||
* //stagger has reset itself |
||
* $animate.leave(kids[5]); //stagger index=0 |
||
* $animate.leave(kids[6]); //stagger index=1 |
||
* }, 100, false); |
||
* </pre> |
||
* |
||
* Stagger animations are currently only supported within CSS-defined animations. |
||
* |
||
* <h2>JavaScript-defined Animations</h2> |
||
* In the event that you do not want to use CSS3 transitions or CSS3 animations or if you wish to offer animations on browsers that do not |
||
* yet support CSS transitions/animations, then you can make use of JavaScript animations defined inside of your AngularJS module. |
||
* |
||
* <pre> |
||
* //!annotate="YourApp" Your AngularJS Module|Replace this or ngModule with the module that you used to define your application. |
||
* var ngModule = angular.module('YourApp', ['ngAnimate']); |
||
* ngModule.animation('.my-crazy-animation', function() { |
||
* return { |
||
* enter: function(element, done) { |
||
* //run the animation here and call done when the animation is complete |
||
* return function(cancelled) { |
||
* //this (optional) function will be called when the animation |
||
* //completes or when the animation is cancelled (the cancelled |
||
* //flag will be set to true if cancelled). |
||
* }; |
||
* }, |
||
* leave: function(element, done) { }, |
||
* move: function(element, done) { }, |
||
* |
||
* //animation that can be triggered before the class is added |
||
* beforeAddClass: function(element, className, done) { }, |
||
* |
||
* //animation that can be triggered after the class is added |
||
* addClass: function(element, className, done) { }, |
||
* |
||
* //animation that can be triggered before the class is removed |
||
* beforeRemoveClass: function(element, className, done) { }, |
||
* |
||
* //animation that can be triggered after the class is removed |
||
* removeClass: function(element, className, done) { } |
||
* }; |
||
* }); |
||
* </pre> |
||
* |
||
* JavaScript-defined animations are created with a CSS-like class selector and a collection of events which are set to run |
||
* a javascript callback function. When an animation is triggered, $animate will look for a matching animation which fits |
||
* the element's CSS class attribute value and then run the matching animation event function (if found). |
||
* In other words, if the CSS classes present on the animated element match any of the JavaScript animations then the callback function will |
||
* be executed. It should be also noted that only simple, single class selectors are allowed (compound class selectors are not supported). |
||
* |
||
* Within a JavaScript animation, an object containing various event callback animation functions is expected to be returned. |
||
* As explained above, these callbacks are triggered based on the animation event. Therefore if an enter animation is run, |
||
* and the JavaScript animation is found, then the enter callback will handle that animation (in addition to the CSS keyframe animation |
||
* or transition code that is defined via a stylesheet). |
||
* |
||
*/ |
||
|
||
angular.module('ngAnimate', ['ng']) |
||
|
||
/** |
||
* @ngdoc object |
||
* @name ngAnimate.$animateProvider |
||
* @description |
||
* |
||
* The `$animateProvider` allows developers to register JavaScript animation event handlers directly inside of a module. |
||
* When an animation is triggered, the $animate service will query the $animate service to find any animations that match |
||
* the provided name value. |
||
* |
||
* Requires the {@link ngAnimate `ngAnimate`} module to be installed. |
||
* |
||
* Please visit the {@link ngAnimate `ngAnimate`} module overview page learn more about how to use animations in your application. |
||
* |
||
*/ |
||
.factory('$$animateReflow', ['$window', '$timeout', function($window, $timeout) { |
||
var requestAnimationFrame = $window.requestAnimationFrame || |
||
$window.webkitRequestAnimationFrame || |
||
function(fn) { |
||
return $timeout(fn, 10, false); |
||
}; |
||
|
||
var cancelAnimationFrame = $window.cancelAnimationFrame || |
||
$window.webkitCancelAnimationFrame || |
||
function(timer) { |
||
return $timeout.cancel(timer); |
||
}; |
||
return function(fn) { |
||
var id = requestAnimationFrame(fn); |
||
return function() { |
||
cancelAnimationFrame(id); |
||
}; |
||
}; |
||
}]) |
||
|
||
.config(['$provide', '$animateProvider', function($provide, $animateProvider) { |
||
var noop = angular.noop; |
||
var forEach = angular.forEach; |
||
var selectors = $animateProvider.$$selectors; |
||
|
||
var ELEMENT_NODE = 1; |
||
var NG_ANIMATE_STATE = '$$ngAnimateState'; |
||
var NG_ANIMATE_CLASS_NAME = 'ng-animate'; |
||
var rootAnimateState = {running: true}; |
||
|
||
function extractElementNode(element) { |
||
for(var i = 0; i < element.length; i++) { |
||
var elm = element[i]; |
||
if(elm.nodeType == ELEMENT_NODE) { |
||
return elm; |
||
} |
||
} |
||
} |
||
|
||
function isMatchingElement(elm1, elm2) { |
||
return extractElementNode(elm1) == extractElementNode(elm2); |
||
} |
||
|
||
$provide.decorator('$animate', ['$delegate', '$injector', '$sniffer', '$rootElement', '$timeout', '$rootScope', '$document', |
||
function($delegate, $injector, $sniffer, $rootElement, $timeout, $rootScope, $document) { |
||
|
||
$rootElement.data(NG_ANIMATE_STATE, rootAnimateState); |
||
|
||
// disable animations during bootstrap, but once we bootstrapped, wait again |
||
// for another digest until enabling animations. The reason why we digest twice |
||
// is because all structural animations (enter, leave and move) all perform a |
||
// post digest operation before animating. If we only wait for a single digest |
||
// to pass then the structural animation would render its animation on page load. |
||
// (which is what we're trying to avoid when the application first boots up.) |
||
$rootScope.$$postDigest(function() { |
||
$rootScope.$$postDigest(function() { |
||
rootAnimateState.running = false; |
||
}); |
||
}); |
||
|
||
var classNameFilter = $animateProvider.classNameFilter(); |
||
var isAnimatableClassName = !classNameFilter |
||
? function() { return true; } |
||
: function(className) { |
||
return classNameFilter.test(className); |
||
}; |
||
|
||
function async(fn) { |
||
return $timeout(fn, 0, false); |
||
} |
||
|
||
function lookup(name) { |
||
if (name) { |
||
var matches = [], |
||
flagMap = {}, |
||
classes = name.substr(1).split('.'); |
||
|
||
//the empty string value is the default animation |
||
//operation which performs CSS transition and keyframe |
||
//animations sniffing. This is always included for each |
||
//element animation procedure if the browser supports |
||
//transitions and/or keyframe animations |
||
if ($sniffer.transitions || $sniffer.animations) { |
||
classes.push(''); |
||
} |
||
|
||
for(var i=0; i < classes.length; i++) { |
||
var klass = classes[i], |
||
selectorFactoryName = selectors[klass]; |
||
if(selectorFactoryName && !flagMap[klass]) { |
||
matches.push($injector.get(selectorFactoryName)); |
||
flagMap[klass] = true; |
||
} |
||
} |
||
return matches; |
||
} |
||
} |
||
|
||
/** |
||
* @ngdoc object |
||
* @name ngAnimate.$animate |
||
* @function |
||
* |
||
* @description |
||
* The `$animate` service provides animation detection support while performing DOM operations (enter, leave and move) as well as during addClass and removeClass operations. |
||
* When any of these operations are run, the $animate service |
||
* will examine any JavaScript-defined animations (which are defined by using the $animateProvider provider object) |
||
* as well as any CSS-defined animations against the CSS classes present on the element once the DOM operation is run. |
||
* |
||
* The `$animate` service is used behind the scenes with pre-existing directives and animation with these directives |
||
* will work out of the box without any extra configuration. |
||
* |
||
* Requires the {@link ngAnimate `ngAnimate`} module to be installed. |
||
* |
||
* Please visit the {@link ngAnimate `ngAnimate`} module overview page learn more about how to use animations in your application. |
||
* |
||
*/ |
||
return { |
||
/** |
||
* @ngdoc function |
||
* @name ngAnimate.$animate#enter |
||
* @methodOf ngAnimate.$animate |
||
* @function |
||
* |
||
* @description |
||
* Appends the element to the parentElement element that resides in the document and then runs the enter animation. Once |
||
* the animation is started, the following CSS classes will be present on the element for the duration of the animation: |
||
* |
||
* Below is a breakdown of each step that occurs during enter animation: |
||
* |
||
* | Animation Step | What the element class attribute looks like | |
||
* |----------------------------------------------------------------------------------------------|---------------------------------------------| |
||
* | 1. $animate.enter(...) is called | class="my-animation" | |
||
* | 2. element is inserted into the parentElement element or beside the afterElement element | class="my-animation" | |
||
* | 3. $animate runs any JavaScript-defined animations on the element | class="my-animation ng-animate" | |
||
* | 4. the .ng-enter class is added to the element | class="my-animation ng-animate ng-enter" | |
||
* | 5. $animate scans the element styles to get the CSS transition/animation duration and delay | class="my-animation ng-animate ng-enter" | |
||
* | 6. $animate waits for 10ms (this performs a reflow) | class="my-animation ng-animate ng-enter" | |
||
* | 7. the .ng-enter-active and .ng-animate-active classes are added (this triggers the CSS transition/animation) | class="my-animation ng-animate ng-animate-active ng-enter ng-enter-active" | |
||
* | 8. $animate waits for X milliseconds for the animation to complete | class="my-animation ng-animate ng-animate-active ng-enter ng-enter-active" | |
||
* | 9. The animation ends and all generated CSS classes are removed from the element | class="my-animation" | |
||
* | 10. The doneCallback() callback is fired (if provided) | class="my-animation" | |
||
* |
||
* @param {jQuery/jqLite element} element the element that will be the focus of the enter animation |
||
* @param {jQuery/jqLite element} parentElement the parent element of the element that will be the focus of the enter animation |
||
* @param {jQuery/jqLite element} afterElement the sibling element (which is the previous element) of the element that will be the focus of the enter animation |
||
* @param {function()=} doneCallback the callback function that will be called once the animation is complete |
||
*/ |
||
enter : function(element, parentElement, afterElement, doneCallback) { |
||
this.enabled(false, element); |
||
$delegate.enter(element, parentElement, afterElement); |
||
$rootScope.$$postDigest(function() { |
||
performAnimation('enter', 'ng-enter', element, parentElement, afterElement, noop, doneCallback); |
||
}); |
||
}, |
||
|
||
/** |
||
* @ngdoc function |
||
* @name ngAnimate.$animate#leave |
||
* @methodOf ngAnimate.$animate |
||
* @function |
||
* |
||
* @description |
||
* Runs the leave animation operation and, upon completion, removes the element from the DOM. Once |
||
* the animation is started, the following CSS classes will be added for the duration of the animation: |
||
* |
||
* Below is a breakdown of each step that occurs during leave animation: |
||
* |
||
* | Animation Step | What the element class attribute looks like | |
||
* |----------------------------------------------------------------------------------------------|---------------------------------------------| |
||
* | 1. $animate.leave(...) is called | class="my-animation" | |
||
* | 2. $animate runs any JavaScript-defined animations on the element | class="my-animation ng-animate" | |
||
* | 3. the .ng-leave class is added to the element | class="my-animation ng-animate ng-leave" | |
||
* | 4. $animate scans the element styles to get the CSS transition/animation duration and delay | class="my-animation ng-animate ng-leave" | |
||
* | 5. $animate waits for 10ms (this performs a reflow) | class="my-animation ng-animate ng-leave" | |
||
* | 6. the .ng-leave-active and .ng-animate-active classes is added (this triggers the CSS transition/animation) | class="my-animation ng-animate ng-animate-active ng-leave ng-leave-active" | |
||
* | 7. $animate waits for X milliseconds for the animation to complete | class="my-animation ng-animate ng-animate-active ng-leave ng-leave-active" | |
||
* | 8. The animation ends and all generated CSS classes are removed from the element | class="my-animation" | |
||
* | 9. The element is removed from the DOM | ... | |
||
* | 10. The doneCallback() callback is fired (if provided) | ... | |
||
* |
||
* @param {jQuery/jqLite element} element the element that will be the focus of the leave animation |
||
* @param {function()=} doneCallback the callback function that will be called once the animation is complete |
||
*/ |
||
leave : function(element, doneCallback) { |
||
cancelChildAnimations(element); |
||
this.enabled(false, element); |
||
$rootScope.$$postDigest(function() { |
||
performAnimation('leave', 'ng-leave', element, null, null, function() { |
||
$delegate.leave(element); |
||
}, doneCallback); |
||
}); |
||
}, |
||
|
||
/** |
||
* @ngdoc function |
||
* @name ngAnimate.$animate#move |
||
* @methodOf ngAnimate.$animate |
||
* @function |
||
* |
||
* @description |
||
* Fires the move DOM operation. Just before the animation starts, the animate service will either append it into the parentElement container or |
||
* add the element directly after the afterElement element if present. Then the move animation will be run. Once |
||
* the animation is started, the following CSS classes will be added for the duration of the animation: |
||
* |
||
* Below is a breakdown of each step that occurs during move animation: |
||
* |
||
* | Animation Step | What the element class attribute looks like | |
||
* |----------------------------------------------------------------------------------------------|---------------------------------------------| |
||
* | 1. $animate.move(...) is called | class="my-animation" | |
||
* | 2. element is moved into the parentElement element or beside the afterElement element | class="my-animation" | |
||
* | 3. $animate runs any JavaScript-defined animations on the element | class="my-animation ng-animate" | |
||
* | 4. the .ng-move class is added to the element | class="my-animation ng-animate ng-move" | |
||
* | 5. $animate scans the element styles to get the CSS transition/animation duration and delay | class="my-animation ng-animate ng-move" | |
||
* | 6. $animate waits for 10ms (this performs a reflow) | class="my-animation ng-animate ng-move" | |
||
* | 7. the .ng-move-active and .ng-animate-active classes is added (this triggers the CSS transition/animation) | class="my-animation ng-animate ng-animate-active ng-move ng-move-active" | |
||
* | 8. $animate waits for X milliseconds for the animation to complete | class="my-animation ng-animate ng-animate-active ng-move ng-move-active" | |
||
* | 9. The animation ends and all generated CSS classes are removed from the element | class="my-animation" | |
||
* | 10. The doneCallback() callback is fired (if provided) | class="my-animation" | |
||
* |
||
* @param {jQuery/jqLite element} element the element that will be the focus of the move animation |
||
* @param {jQuery/jqLite element} parentElement the parentElement element of the element that will be the focus of the move animation |
||
* @param {jQuery/jqLite element} afterElement the sibling element (which is the previous element) of the element that will be the focus of the move animation |
||
* @param {function()=} doneCallback the callback function that will be called once the animation is complete |
||
*/ |
||
move : function(element, parentElement, afterElement, doneCallback) { |
||
cancelChildAnimations(element); |
||
this.enabled(false, element); |
||
$delegate.move(element, parentElement, afterElement); |
||
$rootScope.$$postDigest(function() { |
||
performAnimation('move', 'ng-move', element, parentElement, afterElement, noop, doneCallback); |
||
}); |
||
}, |
||
|
||
/** |
||
* @ngdoc function |
||
* @name ngAnimate.$animate#addClass |
||
* @methodOf ngAnimate.$animate |
||
* |
||
* @description |
||
* Triggers a custom animation event based off the className variable and then attaches the className value to the element as a CSS class. |
||
* Unlike the other animation methods, the animate service will suffix the className value with {@type -add} in order to provide |
||
* the animate service the setup and active CSS classes in order to trigger the animation (this will be skipped if no CSS transitions |
||
* or keyframes are defined on the -add or base CSS class). |
||
* |
||
* Below is a breakdown of each step that occurs during addClass animation: |
||
* |
||
* | Animation Step | What the element class attribute looks like | |
||
* |------------------------------------------------------------------------------------------------|---------------------------------------------| |
||
* | 1. $animate.addClass(element, 'super') is called | class="my-animation" | |
||
* | 2. $animate runs any JavaScript-defined animations on the element | class="my-animation ng-animate" | |
||
* | 3. the .super-add class are added to the element | class="my-animation ng-animate super-add" | |
||
* | 4. $animate scans the element styles to get the CSS transition/animation duration and delay | class="my-animation ng-animate super-add" | |
||
* | 5. $animate waits for 10ms (this performs a reflow) | class="my-animation ng-animate super-add" | |
||
* | 6. the .super, .super-add-active and .ng-animate-active classes are added (this triggers the CSS transition/animation) | class="my-animation ng-animate ng-animate-active super super-add super-add-active" | |
||
* | 7. $animate waits for X milliseconds for the animation to complete | class="my-animation super-add super-add-active" | |
||
* | 8. The animation ends and all generated CSS classes are removed from the element | class="my-animation super" | |
||
* | 9. The super class is kept on the element | class="my-animation super" | |
||
* | 10. The doneCallback() callback is fired (if provided) | class="my-animation super" | |
||
* |
||
* @param {jQuery/jqLite element} element the element that will be animated |
||
* @param {string} className the CSS class that will be added to the element and then animated |
||
* @param {function()=} doneCallback the callback function that will be called once the animation is complete |
||
*/ |
||
addClass : function(element, className, doneCallback) { |
||
performAnimation('addClass', className, element, null, null, function() { |
||
$delegate.addClass(element, className); |
||
}, doneCallback); |
||
}, |
||
|
||
/** |
||
* @ngdoc function |
||
* @name ngAnimate.$animate#removeClass |
||
* @methodOf ngAnimate.$animate |
||
* |
||
* @description |
||
* Triggers a custom animation event based off the className variable and then removes the CSS class provided by the className value |
||
* from the element. Unlike the other animation methods, the animate service will suffix the className value with {@type -remove} in |
||
* order to provide the animate service the setup and active CSS classes in order to trigger the animation (this will be skipped if |
||
* no CSS transitions or keyframes are defined on the -remove or base CSS classes). |
||
* |
||
* Below is a breakdown of each step that occurs during removeClass animation: |
||
* |
||
* | Animation Step | What the element class attribute looks like | |
||
* |-----------------------------------------------------------------------------------------------|---------------------------------------------| |
||
* | 1. $animate.removeClass(element, 'super') is called | class="my-animation super" | |
||
* | 2. $animate runs any JavaScript-defined animations on the element | class="my-animation super ng-animate" | |
||
* | 3. the .super-remove class are added to the element | class="my-animation super ng-animate super-remove"| |
||
* | 4. $animate scans the element styles to get the CSS transition/animation duration and delay | class="my-animation super ng-animate super-remove" | |
||
* | 5. $animate waits for 10ms (this performs a reflow) | class="my-animation super ng-animate super-remove" | |
||
* | 6. the .super-remove-active and .ng-animate-active classes are added and .super is removed (this triggers the CSS transition/animation) | class="my-animation ng-animate ng-animate-active super-remove super-remove-active" | |
||
* | 7. $animate waits for X milliseconds for the animation to complete | class="my-animation ng-animate ng-animate-active super-remove super-remove-active" | |
||
* | 8. The animation ends and all generated CSS classes are removed from the element | class="my-animation" | |
||
* | 9. The doneCallback() callback is fired (if provided) | class="my-animation" | |
||
* |
||
* |
||
* @param {jQuery/jqLite element} element the element that will be animated |
||
* @param {string} className the CSS class that will be animated and then removed from the element |
||
* @param {function()=} doneCallback the callback function that will be called once the animation is complete |
||
*/ |
||
removeClass : function(element, className, doneCallback) { |
||
performAnimation('removeClass', className, element, null, null, function() { |
||
$delegate.removeClass(element, className); |
||
}, doneCallback); |
||
}, |
||
|
||
/** |
||
* @ngdoc function |
||
* @name ngAnimate.$animate#enabled |
||
* @methodOf ngAnimate.$animate |
||
* @function |
||
* |
||
* @param {boolean=} value If provided then set the animation on or off. |
||
* @param {jQuery/jqLite element=} element If provided then the element will be used to represent the enable/disable operation |
||
* @return {boolean} Current animation state. |
||
* |
||
* @description |
||
* Globally enables/disables animations. |
||
* |
||
*/ |
||
enabled : function(value, element) { |
||
switch(arguments.length) { |
||
case 2: |
||
if(value) { |
||
cleanup(element); |
||
} else { |
||
var data = element.data(NG_ANIMATE_STATE) || {}; |
||
data.disabled = true; |
||
element.data(NG_ANIMATE_STATE, data); |
||
} |
||
break; |
||
|
||
case 1: |
||
rootAnimateState.disabled = !value; |
||
break; |
||
|
||
default: |
||
value = !rootAnimateState.disabled; |
||
break; |
||
} |
||
return !!value; |
||
} |
||
}; |
||
|
||
/* |
||
all animations call this shared animation triggering function internally. |
||
The animationEvent variable refers to the JavaScript animation event that will be triggered |
||
and the className value is the name of the animation that will be applied within the |
||
CSS code. Element, parentElement and afterElement are provided DOM elements for the animation |
||
and the onComplete callback will be fired once the animation is fully complete. |
||
*/ |
||
function performAnimation(animationEvent, className, element, parentElement, afterElement, domOperation, doneCallback) { |
||
var currentClassName, classes, node = extractElementNode(element); |
||
if(node) { |
||
currentClassName = node.className; |
||
classes = currentClassName + ' ' + className; |
||
} |
||
|
||
//transcluded directives may sometimes fire an animation using only comment nodes |
||
//best to catch this early on to prevent any animation operations from occurring |
||
if(!node || !isAnimatableClassName(classes)) { |
||
fireDOMOperation(); |
||
fireBeforeCallbackAsync(); |
||
fireAfterCallbackAsync(); |
||
closeAnimation(); |
||
return; |
||
} |
||
|
||
var animationLookup = (' ' + classes).replace(/\s+/g,'.'); |
||
if (!parentElement) { |
||
parentElement = afterElement ? afterElement.parent() : element.parent(); |
||
} |
||
|
||
var matches = lookup(animationLookup); |
||
var isClassBased = animationEvent == 'addClass' || animationEvent == 'removeClass'; |
||
var ngAnimateState = element.data(NG_ANIMATE_STATE) || {}; |
||
|
||
//skip the animation if animations are disabled, a parent is already being animated, |
||
//the element is not currently attached to the document body or then completely close |
||
//the animation if any matching animations are not found at all. |
||
//NOTE: IE8 + IE9 should close properly (run closeAnimation()) in case a NO animation is not found. |
||
if (animationsDisabled(element, parentElement) || matches.length === 0) { |
||
fireDOMOperation(); |
||
fireBeforeCallbackAsync(); |
||
fireAfterCallbackAsync(); |
||
closeAnimation(); |
||
return; |
||
} |
||
|
||
var animations = []; |
||
|
||
//only add animations if the currently running animation is not structural |
||
//or if there is no animation running at all |
||
var allowAnimations = isClassBased ? |
||
!ngAnimateState.disabled && (!ngAnimateState.running || !ngAnimateState.structural) : |
||
true; |
||
|
||
if(allowAnimations) { |
||
forEach(matches, function(animation) { |
||
//add the animation to the queue to if it is allowed to be cancelled |
||
if(!animation.allowCancel || animation.allowCancel(element, animationEvent, className)) { |
||
var beforeFn, afterFn = animation[animationEvent]; |
||
|
||
//Special case for a leave animation since there is no point in performing an |
||
//animation on a element node that has already been removed from the DOM |
||
if(animationEvent == 'leave') { |
||
beforeFn = afterFn; |
||
afterFn = null; //this must be falsy so that the animation is skipped for leave |
||
} else { |
||
beforeFn = animation['before' + animationEvent.charAt(0).toUpperCase() + animationEvent.substr(1)]; |
||
} |
||
animations.push({ |
||
before : beforeFn, |
||
after : afterFn |
||
}); |
||
} |
||
}); |
||
} |
||
|
||
//this would mean that an animation was not allowed so let the existing |
||
//animation do it's thing and close this one early |
||
if(animations.length === 0) { |
||
fireDOMOperation(); |
||
fireBeforeCallbackAsync(); |
||
fireAfterCallbackAsync(); |
||
fireDoneCallbackAsync(); |
||
return; |
||
} |
||
|
||
var ONE_SPACE = ' '; |
||
//this value will be searched for class-based CSS className lookup. Therefore, |
||
//we prefix and suffix the current className value with spaces to avoid substring |
||
//lookups of className tokens |
||
var futureClassName = ONE_SPACE + currentClassName + ONE_SPACE; |
||
if(ngAnimateState.running) { |
||
//if an animation is currently running on the element then lets take the steps |
||
//to cancel that animation and fire any required callbacks |
||
$timeout.cancel(ngAnimateState.closeAnimationTimeout); |
||
cleanup(element); |
||
cancelAnimations(ngAnimateState.animations); |
||
|
||
//in the event that the CSS is class is quickly added and removed back |
||
//then we don't want to wait until after the reflow to add/remove the CSS |
||
//class since both class animations may run into a race condition. |
||
//The code below will check to see if that is occurring and will |
||
//immediately remove the former class before the reflow so that the |
||
//animation can snap back to the original animation smoothly |
||
var isFullyClassBasedAnimation = isClassBased && !ngAnimateState.structural; |
||
var isRevertingClassAnimation = isFullyClassBasedAnimation && |
||
ngAnimateState.className == className && |
||
animationEvent != ngAnimateState.event; |
||
|
||
//if the class is removed during the reflow then it will revert the styles temporarily |
||
//back to the base class CSS styling causing a jump-like effect to occur. This check |
||
//here ensures that the domOperation is only performed after the reflow has commenced |
||
if(ngAnimateState.beforeComplete || isRevertingClassAnimation) { |
||
(ngAnimateState.done || noop)(true); |
||
} else if(isFullyClassBasedAnimation) { |
||
//class-based animations will compare element className values after cancelling the |
||
//previous animation to see if the element properties already contain the final CSS |
||
//class and if so then the animation will be skipped. Since the domOperation will |
||
//be performed only after the reflow is complete then our element's className value |
||
//will be invalid. Therefore the same string manipulation that would occur within the |
||
//DOM operation will be performed below so that the class comparison is valid... |
||
futureClassName = ngAnimateState.event == 'removeClass' ? |
||
futureClassName.replace(ONE_SPACE + ngAnimateState.className + ONE_SPACE, ONE_SPACE) : |
||
futureClassName + ngAnimateState.className + ONE_SPACE; |
||
} |
||
} |
||
|
||
//There is no point in perform a class-based animation if the element already contains |
||
//(on addClass) or doesn't contain (on removeClass) the className being animated. |
||
//The reason why this is being called after the previous animations are cancelled |
||
//is so that the CSS classes present on the element can be properly examined. |
||
var classNameToken = ONE_SPACE + className + ONE_SPACE; |
||
if((animationEvent == 'addClass' && futureClassName.indexOf(classNameToken) >= 0) || |
||
(animationEvent == 'removeClass' && futureClassName.indexOf(classNameToken) == -1)) { |
||
fireDOMOperation(); |
||
fireBeforeCallbackAsync(); |
||
fireAfterCallbackAsync(); |
||
fireDoneCallbackAsync(); |
||
return; |
||
} |
||
|
||
//the ng-animate class does nothing, but it's here to allow for |
||
//parent animations to find and cancel child animations when needed |
||
element.addClass(NG_ANIMATE_CLASS_NAME); |
||
|
||
element.data(NG_ANIMATE_STATE, { |
||
running:true, |
||
event:animationEvent, |
||
className:className, |
||
structural:!isClassBased, |
||
animations:animations, |
||
done:onBeforeAnimationsComplete |
||
}); |
||
|
||
//first we run the before animations and when all of those are complete |
||
//then we perform the DOM operation and run the next set of animations |
||
invokeRegisteredAnimationFns(animations, 'before', onBeforeAnimationsComplete); |
||
|
||
function onBeforeAnimationsComplete(cancelled) { |
||
fireDOMOperation(); |
||
if(cancelled === true) { |
||
closeAnimation(); |
||
return; |
||
} |
||
|
||
//set the done function to the final done function |
||
//so that the DOM event won't be executed twice by accident |
||
//if the after animation is cancelled as well |
||
var data = element.data(NG_ANIMATE_STATE); |
||
if(data) { |
||
data.done = closeAnimation; |
||
element.data(NG_ANIMATE_STATE, data); |
||
} |
||
invokeRegisteredAnimationFns(animations, 'after', closeAnimation); |
||
} |
||
|
||
function invokeRegisteredAnimationFns(animations, phase, allAnimationFnsComplete) { |
||
phase == 'after' ? |
||
fireAfterCallbackAsync() : |
||
fireBeforeCallbackAsync(); |
||
|
||
var endFnName = phase + 'End'; |
||
forEach(animations, function(animation, index) { |
||
var animationPhaseCompleted = function() { |
||
progress(index, phase); |
||
}; |
||
|
||
//there are no before functions for enter + move since the DOM |
||
//operations happen before the performAnimation method fires |
||
if(phase == 'before' && (animationEvent == 'enter' || animationEvent == 'move')) { |
||
animationPhaseCompleted(); |
||
return; |
||
} |
||
|
||
if(animation[phase]) { |
||
animation[endFnName] = isClassBased ? |
||
animation[phase](element, className, animationPhaseCompleted) : |
||
animation[phase](element, animationPhaseCompleted); |
||
} else { |
||
animationPhaseCompleted(); |
||
} |
||
}); |
||
|
||
function progress(index, phase) { |
||
var phaseCompletionFlag = phase + 'Complete'; |
||
var currentAnimation = animations[index]; |
||
currentAnimation[phaseCompletionFlag] = true; |
||
(currentAnimation[endFnName] || noop)(); |
||
|
||
for(var i=0;i<animations.length;i++) { |
||
if(!animations[i][phaseCompletionFlag]) return; |
||
} |
||
|
||
allAnimationFnsComplete(); |
||
} |
||
} |
||
|
||
function fireDOMCallback(animationPhase) { |
||
element.triggerHandler('$animate:' + animationPhase, { |
||
event : animationEvent, |
||
className : className |
||
}); |
||
} |
||
|
||
function fireBeforeCallbackAsync() { |
||
async(function() { |
||
fireDOMCallback('before'); |
||
}); |
||
} |
||
|
||
function fireAfterCallbackAsync() { |
||
async(function() { |
||
fireDOMCallback('after'); |
||
}); |
||
} |
||
|
||
function fireDoneCallbackAsync() { |
||
doneCallback && async(doneCallback); |
||
} |
||
|
||
//it is less complicated to use a flag than managing and cancelling |
||
//timeouts containing multiple callbacks. |
||
function fireDOMOperation() { |
||
if(!fireDOMOperation.hasBeenRun) { |
||
fireDOMOperation.hasBeenRun = true; |
||
domOperation(); |
||
} |
||
} |
||
|
||
function closeAnimation() { |
||
if(!closeAnimation.hasBeenRun) { |
||
closeAnimation.hasBeenRun = true; |
||
var data = element.data(NG_ANIMATE_STATE); |
||
if(data) { |
||
/* only structural animations wait for reflow before removing an |
||
animation, but class-based animations don't. An example of this |
||
failing would be when a parent HTML tag has a ng-class attribute |
||
causing ALL directives below to skip animations during the digest */ |
||
if(isClassBased) { |
||
cleanup(element); |
||
} else { |
||
data.closeAnimationTimeout = async(function() { |
||
cleanup(element); |
||
}); |
||
element.data(NG_ANIMATE_STATE, data); |
||
} |
||
} |
||
fireDoneCallbackAsync(); |
||
} |
||
} |
||
} |
||
|
||
function cancelChildAnimations(element) { |
||
var node = extractElementNode(element); |
||
forEach(node.querySelectorAll('.' + NG_ANIMATE_CLASS_NAME), function(element) { |
||
element = angular.element(element); |
||
var data = element.data(NG_ANIMATE_STATE); |
||
if(data) { |
||
cancelAnimations(data.animations); |
||
cleanup(element); |
||
} |
||
}); |
||
} |
||
|
||
function cancelAnimations(animations) { |
||
var isCancelledFlag = true; |
||
forEach(animations, function(animation) { |
||
if(!animation.beforeComplete) { |
||
(animation.beforeEnd || noop)(isCancelledFlag); |
||
} |
||
if(!animation.afterComplete) { |
||
(animation.afterEnd || noop)(isCancelledFlag); |
||
} |
||
}); |
||
} |
||
|
||
function cleanup(element) { |
||
if(isMatchingElement(element, $rootElement)) { |
||
if(!rootAnimateState.disabled) { |
||
rootAnimateState.running = false; |
||
rootAnimateState.structural = false; |
||
} |
||
} else { |
||
element.removeClass(NG_ANIMATE_CLASS_NAME); |
||
element.removeData(NG_ANIMATE_STATE); |
||
} |
||
} |
||
|
||
function animationsDisabled(element, parentElement) { |
||
if (rootAnimateState.disabled) return true; |
||
|
||
if(isMatchingElement(element, $rootElement)) { |
||
return rootAnimateState.disabled || rootAnimateState.running; |
||
} |
||
|
||
do { |
||
//the element did not reach the root element which means that it |
||
//is not apart of the DOM. Therefore there is no reason to do |
||
//any animations on it |
||
if(parentElement.length === 0) break; |
||
|
||
var isRoot = isMatchingElement(parentElement, $rootElement); |
||
var state = isRoot ? rootAnimateState : parentElement.data(NG_ANIMATE_STATE); |
||
var result = state && (!!state.disabled || !!state.running); |
||
if(isRoot || result) { |
||
return result; |
||
} |
||
|
||
if(isRoot) return true; |
||
} |
||
while(parentElement = parentElement.parent()); |
||
|
||
return true; |
||
} |
||
}]); |
||
|
||
$animateProvider.register('', ['$window', '$sniffer', '$timeout', '$$animateReflow', |
||
function($window, $sniffer, $timeout, $$animateReflow) { |
||
// Detect proper transitionend/animationend event names. |
||
var CSS_PREFIX = '', TRANSITION_PROP, TRANSITIONEND_EVENT, ANIMATION_PROP, ANIMATIONEND_EVENT; |
||
|
||
// If unprefixed events are not supported but webkit-prefixed are, use the latter. |
||
// Otherwise, just use W3C names, browsers not supporting them at all will just ignore them. |
||
// Note: Chrome implements `window.onwebkitanimationend` and doesn't implement `window.onanimationend` |
||
// but at the same time dispatches the `animationend` event and not `webkitAnimationEnd`. |
||
// Register both events in case `window.onanimationend` is not supported because of that, |
||
// do the same for `transitionend` as Safari is likely to exhibit similar behavior. |
||
// Also, the only modern browser that uses vendor prefixes for transitions/keyframes is webkit |
||
// therefore there is no reason to test anymore for other vendor prefixes: http://caniuse.com/#search=transition |
||
if (window.ontransitionend === undefined && window.onwebkittransitionend !== undefined) { |
||
CSS_PREFIX = '-webkit-'; |
||
TRANSITION_PROP = 'WebkitTransition'; |
||
TRANSITIONEND_EVENT = 'webkitTransitionEnd transitionend'; |
||
} else { |
||
TRANSITION_PROP = 'transition'; |
||
TRANSITIONEND_EVENT = 'transitionend'; |
||
} |
||
|
||
if (window.onanimationend === undefined && window.onwebkitanimationend !== undefined) { |
||
CSS_PREFIX = '-webkit-'; |
||
ANIMATION_PROP = 'WebkitAnimation'; |
||
ANIMATIONEND_EVENT = 'webkitAnimationEnd animationend'; |
||
} else { |
||
ANIMATION_PROP = 'animation'; |
||
ANIMATIONEND_EVENT = 'animationend'; |
||
} |
||
|
||
var DURATION_KEY = 'Duration'; |
||
var PROPERTY_KEY = 'Property'; |
||
var DELAY_KEY = 'Delay'; |
||
var ANIMATION_ITERATION_COUNT_KEY = 'IterationCount'; |
||
var NG_ANIMATE_PARENT_KEY = '$$ngAnimateKey'; |
||
var NG_ANIMATE_CSS_DATA_KEY = '$$ngAnimateCSS3Data'; |
||
var ELAPSED_TIME_MAX_DECIMAL_PLACES = 3; |
||
var CLOSING_TIME_BUFFER = 1.5; |
||
var ONE_SECOND = 1000; |
||
|
||
var animationCounter = 0; |
||
var lookupCache = {}; |
||
var parentCounter = 0; |
||
var animationReflowQueue = []; |
||
var animationElementQueue = []; |
||
var cancelAnimationReflow; |
||
var closingAnimationTime = 0; |
||
var timeOut = false; |
||
function afterReflow(element, callback) { |
||
if(cancelAnimationReflow) { |
||
cancelAnimationReflow(); |
||
} |
||
|
||
animationReflowQueue.push(callback); |
||
|
||
var node = extractElementNode(element); |
||
element = angular.element(node); |
||
animationElementQueue.push(element); |
||
|
||
var elementData = element.data(NG_ANIMATE_CSS_DATA_KEY); |
||
|
||
var stagger = elementData.stagger; |
||
var staggerTime = elementData.itemIndex * (Math.max(stagger.animationDelay, stagger.transitionDelay) || 0); |
||
|
||
var animationTime = (elementData.maxDelay + elementData.maxDuration) * CLOSING_TIME_BUFFER; |
||
closingAnimationTime = Math.max(closingAnimationTime, (staggerTime + animationTime) * ONE_SECOND); |
||
|
||
//by placing a counter we can avoid an accidental |
||
//race condition which may close an animation when |
||
//a follow-up animation is midway in its animation |
||
elementData.animationCount = animationCounter; |
||
|
||
cancelAnimationReflow = $$animateReflow(function() { |
||
forEach(animationReflowQueue, function(fn) { |
||
fn(); |
||
}); |
||
|
||
//copy the list of elements so that successive |
||
//animations won't conflict if they're added before |
||
//the closing animation timeout has run |
||
var elementQueueSnapshot = []; |
||
var animationCounterSnapshot = animationCounter; |
||
forEach(animationElementQueue, function(elm) { |
||
elementQueueSnapshot.push(elm); |
||
}); |
||
|
||
$timeout(function() { |
||
closeAllAnimations(elementQueueSnapshot, animationCounterSnapshot); |
||
elementQueueSnapshot = null; |
||
}, closingAnimationTime, false); |
||
|
||
animationReflowQueue = []; |
||
animationElementQueue = []; |
||
cancelAnimationReflow = null; |
||
lookupCache = {}; |
||
closingAnimationTime = 0; |
||
animationCounter++; |
||
}); |
||
} |
||
|
||
function closeAllAnimations(elements, count) { |
||
forEach(elements, function(element) { |
||
var elementData = element.data(NG_ANIMATE_CSS_DATA_KEY); |
||
if(elementData && elementData.animationCount == count) { |
||
(elementData.closeAnimationFn || noop)(); |
||
} |
||
}); |
||
} |
||
|
||
function getElementAnimationDetails(element, cacheKey) { |
||
var data = cacheKey ? lookupCache[cacheKey] : null; |
||
if(!data) { |
||
var transitionDuration = 0; |
||
var transitionDelay = 0; |
||
var animationDuration = 0; |
||
var animationDelay = 0; |
||
var transitionDelayStyle; |
||
var animationDelayStyle; |
||
var transitionDurationStyle; |
||
var transitionPropertyStyle; |
||
|
||
//we want all the styles defined before and after |
||
forEach(element, function(element) { |
||
if (element.nodeType == ELEMENT_NODE) { |
||
var elementStyles = $window.getComputedStyle(element) || {}; |
||
|
||
transitionDurationStyle = elementStyles[TRANSITION_PROP + DURATION_KEY]; |
||
|
||
transitionDuration = Math.max(parseMaxTime(transitionDurationStyle), transitionDuration); |
||
|
||
transitionPropertyStyle = elementStyles[TRANSITION_PROP + PROPERTY_KEY]; |
||
|
||
transitionDelayStyle = elementStyles[TRANSITION_PROP + DELAY_KEY]; |
||
|
||
transitionDelay = Math.max(parseMaxTime(transitionDelayStyle), transitionDelay); |
||
|
||
animationDelayStyle = elementStyles[ANIMATION_PROP + DELAY_KEY]; |
||
|
||
animationDelay = Math.max(parseMaxTime(animationDelayStyle), animationDelay); |
||
|
||
var aDuration = parseMaxTime(elementStyles[ANIMATION_PROP + DURATION_KEY]); |
||
|
||
if(aDuration > 0) { |
||
aDuration *= parseInt(elementStyles[ANIMATION_PROP + ANIMATION_ITERATION_COUNT_KEY], 10) || 1; |
||
} |
||
|
||
animationDuration = Math.max(aDuration, animationDuration); |
||
} |
||
}); |
||
data = { |
||
total : 0, |
||
transitionPropertyStyle: transitionPropertyStyle, |
||
transitionDurationStyle: transitionDurationStyle, |
||
transitionDelayStyle: transitionDelayStyle, |
||
transitionDelay: transitionDelay, |
||
transitionDuration: transitionDuration, |
||
animationDelayStyle: animationDelayStyle, |
||
animationDelay: animationDelay, |
||
animationDuration: animationDuration |
||
}; |
||
if(cacheKey) { |
||
lookupCache[cacheKey] = data; |
||
} |
||
} |
||
return data; |
||
} |
||
|
||
function parseMaxTime(str) { |
||
var maxValue = 0; |
||
var values = angular.isString(str) ? |
||
str.split(/\s*,\s*/) : |
||
[]; |
||
forEach(values, function(value) { |
||
maxValue = Math.max(parseFloat(value) || 0, maxValue); |
||
}); |
||
return maxValue; |
||
} |
||
|
||
function getCacheKey(element) { |
||
var parentElement = element.parent(); |
||
var parentID = parentElement.data(NG_ANIMATE_PARENT_KEY); |
||
if(!parentID) { |
||
parentElement.data(NG_ANIMATE_PARENT_KEY, ++parentCounter); |
||
parentID = parentCounter; |
||
} |
||
return parentID + '-' + extractElementNode(element).className; |
||
} |
||
|
||
function animateSetup(element, className, calculationDecorator) { |
||
var cacheKey = getCacheKey(element); |
||
var eventCacheKey = cacheKey + ' ' + className; |
||
var stagger = {}; |
||
var itemIndex = lookupCache[eventCacheKey] ? ++lookupCache[eventCacheKey].total : 0; |
||
|
||
if(itemIndex > 0) { |
||
var staggerClassName = className + '-stagger'; |
||
var staggerCacheKey = cacheKey + ' ' + staggerClassName; |
||
var applyClasses = !lookupCache[staggerCacheKey]; |
||
|
||
applyClasses && element.addClass(staggerClassName); |
||
|
||
stagger = getElementAnimationDetails(element, staggerCacheKey); |
||
|
||
applyClasses && element.removeClass(staggerClassName); |
||
} |
||
|
||
/* the animation itself may need to add/remove special CSS classes |
||
* before calculating the anmation styles */ |
||
calculationDecorator = calculationDecorator || |
||
function(fn) { return fn(); }; |
||
|
||
element.addClass(className); |
||
|
||
var timings = calculationDecorator(function() { |
||
return getElementAnimationDetails(element, eventCacheKey); |
||
}); |
||
|
||
/* there is no point in performing a reflow if the animation |
||
timeout is empty (this would cause a flicker bug normally |
||
in the page. There is also no point in performing an animation |
||
that only has a delay and no duration */ |
||
var maxDelay = Math.max(timings.transitionDelay, timings.animationDelay); |
||
var maxDuration = Math.max(timings.transitionDuration, timings.animationDuration); |
||
if(maxDuration === 0) { |
||
element.removeClass(className); |
||
return false; |
||
} |
||
|
||
//temporarily disable the transition so that the enter styles |
||
//don't animate twice (this is here to avoid a bug in Chrome/FF). |
||
var activeClassName = ''; |
||
timings.transitionDuration > 0 ? |
||
blockTransitions(element) : |
||
blockKeyframeAnimations(element); |
||
|
||
forEach(className.split(' '), function(klass, i) { |
||
activeClassName += (i > 0 ? ' ' : '') + klass + '-active'; |
||
}); |
||
|
||
element.data(NG_ANIMATE_CSS_DATA_KEY, { |
||
className : className, |
||
activeClassName : activeClassName, |
||
maxDuration : maxDuration, |
||
maxDelay : maxDelay, |
||
classes : className + ' ' + activeClassName, |
||
timings : timings, |
||
stagger : stagger, |
||
itemIndex : itemIndex |
||
}); |
||
|
||
return true; |
||
} |
||
|
||
function blockTransitions(element) { |
||
extractElementNode(element).style[TRANSITION_PROP + PROPERTY_KEY] = 'none'; |
||
} |
||
|
||
function blockKeyframeAnimations(element) { |
||
extractElementNode(element).style[ANIMATION_PROP] = 'none 0s'; |
||
} |
||
|
||
function unblockTransitions(element) { |
||
var prop = TRANSITION_PROP + PROPERTY_KEY; |
||
var node = extractElementNode(element); |
||
if(node.style[prop] && node.style[prop].length > 0) { |
||
node.style[prop] = ''; |
||
} |
||
} |
||
|
||
function unblockKeyframeAnimations(element) { |
||
var prop = ANIMATION_PROP; |
||
var node = extractElementNode(element); |
||
if(node.style[prop] && node.style[prop].length > 0) { |
||
node.style[prop] = ''; |
||
} |
||
} |
||
|
||
function animateRun(element, className, activeAnimationComplete) { |
||
var elementData = element.data(NG_ANIMATE_CSS_DATA_KEY); |
||
var node = extractElementNode(element); |
||
if(node.className.indexOf(className) == -1 || !elementData) { |
||
activeAnimationComplete(); |
||
return; |
||
} |
||
|
||
var timings = elementData.timings; |
||
var stagger = elementData.stagger; |
||
var maxDuration = elementData.maxDuration; |
||
var activeClassName = elementData.activeClassName; |
||
var maxDelayTime = Math.max(timings.transitionDelay, timings.animationDelay) * ONE_SECOND; |
||
var startTime = Date.now(); |
||
var css3AnimationEvents = ANIMATIONEND_EVENT + ' ' + TRANSITIONEND_EVENT; |
||
var itemIndex = elementData.itemIndex; |
||
|
||
var style = '', appliedStyles = []; |
||
if(timings.transitionDuration > 0) { |
||
var propertyStyle = timings.transitionPropertyStyle; |
||
if(propertyStyle.indexOf('all') == -1) { |
||
style += CSS_PREFIX + 'transition-property: ' + propertyStyle + ';'; |
||
style += CSS_PREFIX + 'transition-duration: ' + timings.transitionDurationStyle + ';'; |
||
appliedStyles.push(CSS_PREFIX + 'transition-property'); |
||
appliedStyles.push(CSS_PREFIX + 'transition-duration'); |
||
} |
||
} |
||
|
||
if(itemIndex > 0) { |
||
if(stagger.transitionDelay > 0 && stagger.transitionDuration === 0) { |
||
var delayStyle = timings.transitionDelayStyle; |
||
style += CSS_PREFIX + 'transition-delay: ' + |
||
prepareStaggerDelay(delayStyle, stagger.transitionDelay, itemIndex) + '; '; |
||
appliedStyles.push(CSS_PREFIX + 'transition-delay'); |
||
} |
||
|
||
if(stagger.animationDelay > 0 && stagger.animationDuration === 0) { |
||
style += CSS_PREFIX + 'animation-delay: ' + |
||
prepareStaggerDelay(timings.animationDelayStyle, stagger.animationDelay, itemIndex) + '; '; |
||
appliedStyles.push(CSS_PREFIX + 'animation-delay'); |
||
} |
||
} |
||
|
||
if(appliedStyles.length > 0) { |
||
//the element being animated may sometimes contain comment nodes in |
||
//the jqLite object, so we're safe to use a single variable to house |
||
//the styles since there is always only one element being animated |
||
var oldStyle = node.getAttribute('style') || ''; |
||
node.setAttribute('style', oldStyle + ' ' + style); |
||
} |
||
|
||
element.on(css3AnimationEvents, onAnimationProgress); |
||
element.addClass(activeClassName); |
||
elementData.closeAnimationFn = function() { |
||
onEnd(); |
||
activeAnimationComplete(); |
||
}; |
||
return onEnd; |
||
|
||
// This will automatically be called by $animate so |
||
// there is no need to attach this internally to the |
||
// timeout done method. |
||
function onEnd(cancelled) { |
||
element.off(css3AnimationEvents, onAnimationProgress); |
||
element.removeClass(activeClassName); |
||
animateClose(element, className); |
||
var node = extractElementNode(element); |
||
for (var i in appliedStyles) { |
||
node.style.removeProperty(appliedStyles[i]); |
||
} |
||
} |
||
|
||
function onAnimationProgress(event) { |
||
event.stopPropagation(); |
||
var ev = event.originalEvent || event; |
||
var timeStamp = ev.$manualTimeStamp || ev.timeStamp || Date.now(); |
||
|
||
/* Firefox (or possibly just Gecko) likes to not round values up |
||
* when a ms measurement is used for the animation */ |
||
var elapsedTime = parseFloat(ev.elapsedTime.toFixed(ELAPSED_TIME_MAX_DECIMAL_PLACES)); |
||
|
||
/* $manualTimeStamp is a mocked timeStamp value which is set |
||
* within browserTrigger(). This is only here so that tests can |
||
* mock animations properly. Real events fallback to event.timeStamp, |
||
* or, if they don't, then a timeStamp is automatically created for them. |
||
* We're checking to see if the timeStamp surpasses the expected delay, |
||
* but we're using elapsedTime instead of the timeStamp on the 2nd |
||
* pre-condition since animations sometimes close off early */ |
||
if(Math.max(timeStamp - startTime, 0) >= maxDelayTime && elapsedTime >= maxDuration) { |
||
activeAnimationComplete(); |
||
} |
||
} |
||
} |
||
|
||
function prepareStaggerDelay(delayStyle, staggerDelay, index) { |
||
var style = ''; |
||
forEach(delayStyle.split(','), function(val, i) { |
||
style += (i > 0 ? ',' : '') + |
||
(index * staggerDelay + parseInt(val, 10)) + 's'; |
||
}); |
||
return style; |
||
} |
||
|
||
function animateBefore(element, className, calculationDecorator) { |
||
if(animateSetup(element, className, calculationDecorator)) { |
||
return function(cancelled) { |
||
cancelled && animateClose(element, className); |
||
}; |
||
} |
||
} |
||
|
||
function animateAfter(element, className, afterAnimationComplete) { |
||
if(element.data(NG_ANIMATE_CSS_DATA_KEY)) { |
||
return animateRun(element, className, afterAnimationComplete); |
||
} else { |
||
animateClose(element, className); |
||
afterAnimationComplete(); |
||
} |
||
} |
||
|
||
function animate(element, className, animationComplete) { |
||
//If the animateSetup function doesn't bother returning a |
||
//cancellation function then it means that there is no animation |
||
//to perform at all |
||
var preReflowCancellation = animateBefore(element, className); |
||
if(!preReflowCancellation) { |
||
animationComplete(); |
||
return; |
||
} |
||
|
||
//There are two cancellation functions: one is before the first |
||
//reflow animation and the second is during the active state |
||
//animation. The first function will take care of removing the |
||
//data from the element which will not make the 2nd animation |
||
//happen in the first place |
||
var cancel = preReflowCancellation; |
||
afterReflow(element, function() { |
||
unblockTransitions(element); |
||
unblockKeyframeAnimations(element); |
||
//once the reflow is complete then we point cancel to |
||
//the new cancellation function which will remove all of the |
||
//animation properties from the active animation |
||
cancel = animateAfter(element, className, animationComplete); |
||
}); |
||
|
||
return function(cancelled) { |
||
(cancel || noop)(cancelled); |
||
}; |
||
} |
||
|
||
function animateClose(element, className) { |
||
element.removeClass(className); |
||
element.removeData(NG_ANIMATE_CSS_DATA_KEY); |
||
} |
||
|
||
return { |
||
allowCancel : function(element, animationEvent, className) { |
||
//always cancel the current animation if it is a |
||
//structural animation |
||
var oldClasses = (element.data(NG_ANIMATE_CSS_DATA_KEY) || {}).classes; |
||
if(!oldClasses || ['enter','leave','move'].indexOf(animationEvent) >= 0) { |
||
return true; |
||
} |
||
|
||
var parentElement = element.parent(); |
||
var clone = angular.element(extractElementNode(element).cloneNode()); |
||
|
||
//make the element super hidden and override any CSS style values |
||
clone.attr('style','position:absolute; top:-9999px; left:-9999px'); |
||
clone.removeAttr('id'); |
||
clone.empty(); |
||
|
||
forEach(oldClasses.split(' '), function(klass) { |
||
clone.removeClass(klass); |
||
}); |
||
|
||
var suffix = animationEvent == 'addClass' ? '-add' : '-remove'; |
||
clone.addClass(suffixClasses(className, suffix)); |
||
parentElement.append(clone); |
||
|
||
var timings = getElementAnimationDetails(clone); |
||
clone.remove(); |
||
|
||
return Math.max(timings.transitionDuration, timings.animationDuration) > 0; |
||
}, |
||
|
||
enter : function(element, animationCompleted) { |
||
return animate(element, 'ng-enter', animationCompleted); |
||
}, |
||
|
||
leave : function(element, animationCompleted) { |
||
return animate(element, 'ng-leave', animationCompleted); |
||
}, |
||
|
||
move : function(element, animationCompleted) { |
||
return animate(element, 'ng-move', animationCompleted); |
||
}, |
||
|
||
beforeAddClass : function(element, className, animationCompleted) { |
||
var cancellationMethod = animateBefore(element, suffixClasses(className, '-add'), function(fn) { |
||
|
||
/* when a CSS class is added to an element then the transition style that |
||
* is applied is the transition defined on the element when the CSS class |
||
* is added at the time of the animation. This is how CSS3 functions |
||
* outside of ngAnimate. */ |
||
element.addClass(className); |
||
var timings = fn(); |
||
element.removeClass(className); |
||
return timings; |
||
}); |
||
|
||
if(cancellationMethod) { |
||
afterReflow(element, function() { |
||
unblockTransitions(element); |
||
unblockKeyframeAnimations(element); |
||
animationCompleted(); |
||
}); |
||
return cancellationMethod; |
||
} |
||
animationCompleted(); |
||
}, |
||
|
||
addClass : function(element, className, animationCompleted) { |
||
return animateAfter(element, suffixClasses(className, '-add'), animationCompleted); |
||
}, |
||
|
||
beforeRemoveClass : function(element, className, animationCompleted) { |
||
var cancellationMethod = animateBefore(element, suffixClasses(className, '-remove'), function(fn) { |
||
/* when classes are removed from an element then the transition style |
||
* that is applied is the transition defined on the element without the |
||
* CSS class being there. This is how CSS3 functions outside of ngAnimate. |
||
* http://plnkr.co/edit/j8OzgTNxHTb4n3zLyjGW?p=preview */ |
||
var klass = element.attr('class'); |
||
element.removeClass(className); |
||
var timings = fn(); |
||
element.attr('class', klass); |
||
return timings; |
||
}); |
||
|
||
if(cancellationMethod) { |
||
afterReflow(element, function() { |
||
unblockTransitions(element); |
||
unblockKeyframeAnimations(element); |
||
animationCompleted(); |
||
}); |
||
return cancellationMethod; |
||
} |
||
animationCompleted(); |
||
}, |
||
|
||
removeClass : function(element, className, animationCompleted) { |
||
return animateAfter(element, suffixClasses(className, '-remove'), animationCompleted); |
||
} |
||
}; |
||
|
||
function suffixClasses(classes, suffix) { |
||
var className = ''; |
||
classes = angular.isArray(classes) ? classes : classes.split(/\s+/); |
||
forEach(classes, function(klass, i) { |
||
if(klass && klass.length > 0) { |
||
className += (i > 0 ? ' ' : '') + klass + suffix; |
||
} |
||
}); |
||
return className; |
||
} |
||
}]); |
||
}]); |
||
|
||
|
||
})(window, window.angular); |
||
|
||
/** |
||
* @license AngularJS v1.2.9 |
||
* (c) 2010-2014 Google, Inc. http://angularjs.org |
||
* License: MIT |
||
*/ |
||
(function(window, angular, undefined) {'use strict'; |
||
|
||
var $sanitizeMinErr = angular.$$minErr('$sanitize'); |
||
|
||
/** |
||
* @ngdoc overview |
||
* @name ngSanitize |
||
* @description |
||
* |
||
* # ngSanitize |
||
* |
||
* The `ngSanitize` module provides functionality to sanitize HTML. |
||
* |
||
* {@installModule sanitize} |
||
* |
||
* <div doc-module-components="ngSanitize"></div> |
||
* |
||
* See {@link ngSanitize.$sanitize `$sanitize`} for usage. |
||
*/ |
||
|
||
/* |
||
* HTML Parser By Misko Hevery ([email protected]) |
||
* based on: HTML Parser By John Resig (ejohn.org) |
||
* Original code by Erik Arvidsson, Mozilla Public License |
||
* http://erik.eae.net/simplehtmlparser/simplehtmlparser.js |
||
* |
||
* // Use like so: |
||
* htmlParser(htmlString, { |
||
* start: function(tag, attrs, unary) {}, |
||
* end: function(tag) {}, |
||
* chars: function(text) {}, |
||
* comment: function(text) {} |
||
* }); |
||
* |
||
*/ |
||
|
||
|
||
/** |
||
* @ngdoc service |
||
* @name ngSanitize.$sanitize |
||
* @function |
||
* |
||
* @description |
||
* The input is sanitized by parsing the html into tokens. All safe tokens (from a whitelist) are |
||
* then serialized back to properly escaped html string. This means that no unsafe input can make |
||
* it into the returned string, however, since our parser is more strict than a typical browser |
||
* parser, it's possible that some obscure input, which would be recognized as valid HTML by a |
||
* browser, won't make it through the sanitizer. |
||
* The whitelist is configured using the functions `aHrefSanitizationWhitelist` and |
||
* `imgSrcSanitizationWhitelist` of {@link ng.$compileProvider `$compileProvider`}. |
||
* |
||
* @param {string} html Html input. |
||
* @returns {string} Sanitized html. |
||
* |
||
* @example |
||
<doc:example module="ngSanitize"> |
||
<doc:source> |
||
<script> |
||
function Ctrl($scope, $sce) { |
||
$scope.snippet = |
||
'<p style="color:blue">an html\n' + |
||
'<em onmouseover="this.textContent=\'PWN3D!\'">click here</em>\n' + |
||
'snippet</p>'; |
||
$scope.deliberatelyTrustDangerousSnippet = function() { |
||
return $sce.trustAsHtml($scope.snippet); |
||
}; |
||
} |
||
</script> |
||
<div ng-controller="Ctrl"> |
||
Snippet: <textarea ng-model="snippet" cols="60" rows="3"></textarea> |
||
<table> |
||
<tr> |
||
<td>Directive</td> |
||
<td>How</td> |
||
<td>Source</td> |
||
<td>Rendered</td> |
||
</tr> |
||
<tr id="bind-html-with-sanitize"> |
||
<td>ng-bind-html</td> |
||
<td>Automatically uses $sanitize</td> |
||
<td><pre><div ng-bind-html="snippet"><br/></div></pre></td> |
||
<td><div ng-bind-html="snippet"></div></td> |
||
</tr> |
||
<tr id="bind-html-with-trust"> |
||
<td>ng-bind-html</td> |
||
<td>Bypass $sanitize by explicitly trusting the dangerous value</td> |
||
<td> |
||
<pre><div ng-bind-html="deliberatelyTrustDangerousSnippet()"> |
||
</div></pre> |
||
</td> |
||
<td><div ng-bind-html="deliberatelyTrustDangerousSnippet()"></div></td> |
||
</tr> |
||
<tr id="bind-default"> |
||
<td>ng-bind</td> |
||
<td>Automatically escapes</td> |
||
<td><pre><div ng-bind="snippet"><br/></div></pre></td> |
||
<td><div ng-bind="snippet"></div></td> |
||
</tr> |
||
</table> |
||
</div> |
||
</doc:source> |
||
<doc:scenario> |
||
it('should sanitize the html snippet by default', function() { |
||
expect(using('#bind-html-with-sanitize').element('div').html()). |
||
toBe('<p>an html\n<em>click here</em>\nsnippet</p>'); |
||
}); |
||
|
||
it('should inline raw snippet if bound to a trusted value', function() { |
||
expect(using('#bind-html-with-trust').element("div").html()). |
||
toBe("<p style=\"color:blue\">an html\n" + |
||
"<em onmouseover=\"this.textContent='PWN3D!'\">click here</em>\n" + |
||
"snippet</p>"); |
||
}); |
||
|
||
it('should escape snippet without any filter', function() { |
||
expect(using('#bind-default').element('div').html()). |
||
toBe("<p style=\"color:blue\">an html\n" + |
||
"<em onmouseover=\"this.textContent='PWN3D!'\">click here</em>\n" + |
||
"snippet</p>"); |
||
}); |
||
|
||
it('should update', function() { |
||
input('snippet').enter('new <b onclick="alert(1)">text</b>'); |
||
expect(using('#bind-html-with-sanitize').element('div').html()).toBe('new <b>text</b>'); |
||
expect(using('#bind-html-with-trust').element('div').html()).toBe( |
||
'new <b onclick="alert(1)">text</b>'); |
||
expect(using('#bind-default').element('div').html()).toBe( |
||
"new <b onclick=\"alert(1)\">text</b>"); |
||
}); |
||
</doc:scenario> |
||
</doc:example> |
||
*/ |
||
function $SanitizeProvider() { |
||
this.$get = ['$$sanitizeUri', function($$sanitizeUri) { |
||
return function(html) { |
||
var buf = []; |
||
htmlParser(html, htmlSanitizeWriter(buf, function(uri, isImage) { |
||
return !/^unsafe/.test($$sanitizeUri(uri, isImage)); |
||
})); |
||
return buf.join(''); |
||
}; |
||
}]; |
||
} |
||
|
||
function sanitizeText(chars) { |
||
var buf = []; |
||
var writer = htmlSanitizeWriter(buf, angular.noop); |
||
writer.chars(chars); |
||
return buf.join(''); |
||
} |
||
|
||
|
||
// Regular Expressions for parsing tags and attributes |
||
var START_TAG_REGEXP = |
||
/^<\s*([\w:-]+)((?:\s+[\w:-]+(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)\s*>/, |
||
END_TAG_REGEXP = /^<\s*\/\s*([\w:-]+)[^>]*>/, |
||
ATTR_REGEXP = /([\w:-]+)(?:\s*=\s*(?:(?:"((?:[^"])*)")|(?:'((?:[^'])*)')|([^>\s]+)))?/g, |
||
BEGIN_TAG_REGEXP = /^</, |
||
BEGING_END_TAGE_REGEXP = /^<\s*\//, |
||
COMMENT_REGEXP = /<!--(.*?)-->/g, |
||
DOCTYPE_REGEXP = /<!DOCTYPE([^>]*?)>/i, |
||
CDATA_REGEXP = /<!\[CDATA\[(.*?)]]>/g, |
||
// Match everything outside of normal chars and " (quote character) |
||
NON_ALPHANUMERIC_REGEXP = /([^\#-~| |!])/g; |
||
|
||
|
||
// Good source of info about elements and attributes |
||
// http://dev.w3.org/html5/spec/Overview.html#semantics |
||
// http://simon.html5.org/html-elements |
||
|
||
// Safe Void Elements - HTML5 |
||
// http://dev.w3.org/html5/spec/Overview.html#void-elements |
||
var voidElements = makeMap("area,br,col,hr,img,wbr"); |
||
|
||
// Elements that you can, intentionally, leave open (and which close themselves) |
||
// http://dev.w3.org/html5/spec/Overview.html#optional-tags |
||
var optionalEndTagBlockElements = makeMap("colgroup,dd,dt,li,p,tbody,td,tfoot,th,thead,tr"), |
||
optionalEndTagInlineElements = makeMap("rp,rt"), |
||
optionalEndTagElements = angular.extend({}, |
||
optionalEndTagInlineElements, |
||
optionalEndTagBlockElements); |
||
|
||
// Safe Block Elements - HTML5 |
||
var blockElements = angular.extend({}, optionalEndTagBlockElements, makeMap("address,article," + |
||
"aside,blockquote,caption,center,del,dir,div,dl,figure,figcaption,footer,h1,h2,h3,h4,h5," + |
||
"h6,header,hgroup,hr,ins,map,menu,nav,ol,pre,script,section,table,ul")); |
||
|
||
// Inline Elements - HTML5 |
||
var inlineElements = angular.extend({}, optionalEndTagInlineElements, makeMap("a,abbr,acronym,b," + |
||
"bdi,bdo,big,br,cite,code,del,dfn,em,font,i,img,ins,kbd,label,map,mark,q,ruby,rp,rt,s," + |
||
"samp,small,span,strike,strong,sub,sup,time,tt,u,var")); |
||
|
||
|
||
// Special Elements (can contain anything) |
||
var specialElements = makeMap("script,style"); |
||
|
||
var validElements = angular.extend({}, |
||
voidElements, |
||
blockElements, |
||
inlineElements, |
||
optionalEndTagElements); |
||
|
||
//Attributes that have href and hence need to be sanitized |
||
var uriAttrs = makeMap("background,cite,href,longdesc,src,usemap"); |
||
var validAttrs = angular.extend({}, uriAttrs, makeMap( |
||
'abbr,align,alt,axis,bgcolor,border,cellpadding,cellspacing,class,clear,'+ |
||
'color,cols,colspan,compact,coords,dir,face,headers,height,hreflang,hspace,'+ |
||
'ismap,lang,language,nohref,nowrap,rel,rev,rows,rowspan,rules,'+ |
||
'scope,scrolling,shape,size,span,start,summary,target,title,type,'+ |
||
'valign,value,vspace,width')); |
||
|
||
function makeMap(str) { |
||
var obj = {}, items = str.split(','), i; |
||
for (i = 0; i < items.length; i++) obj[items[i]] = true; |
||
return obj; |
||
} |
||
|
||
|
||
/** |
||
* @example |
||
* htmlParser(htmlString, { |
||
* start: function(tag, attrs, unary) {}, |
||
* end: function(tag) {}, |
||
* chars: function(text) {}, |
||
* comment: function(text) {} |
||
* }); |
||
* |
||
* @param {string} html string |
||
* @param {object} handler |
||
*/ |
||
function htmlParser( html, handler ) { |
||
var index, chars, match, stack = [], last = html; |
||
stack.last = function() { return stack[ stack.length - 1 ]; }; |
||
|
||
while ( html ) { |
||
chars = true; |
||
|
||
// Make sure we're not in a script or style element |
||
if ( !stack.last() || !specialElements[ stack.last() ] ) { |
||
|
||
// Comment |
||
if ( html.indexOf("<!--") === 0 ) { |
||
// comments containing -- are not allowed unless they terminate the comment |
||
index = html.indexOf("--", 4); |
||
|
||
if ( index >= 0 && html.lastIndexOf("-->", index) === index) { |
||
if (handler.comment) handler.comment( html.substring( 4, index ) ); |
||
html = html.substring( index + 3 ); |
||
chars = false; |
||
} |
||
// DOCTYPE |
||
} else if ( DOCTYPE_REGEXP.test(html) ) { |
||
match = html.match( DOCTYPE_REGEXP ); |
||
|
||
if ( match ) { |
||
html = html.replace( match[0] , ''); |
||
chars = false; |
||
} |
||
// end tag |
||
} else if ( BEGING_END_TAGE_REGEXP.test(html) ) { |
||
match = html.match( END_TAG_REGEXP ); |
||
|
||
if ( match ) { |
||
html = html.substring( match[0].length ); |
||
match[0].replace( END_TAG_REGEXP, parseEndTag ); |
||
chars = false; |
||
} |
||
|
||
// start tag |
||
} else if ( BEGIN_TAG_REGEXP.test(html) ) { |
||
match = html.match( START_TAG_REGEXP ); |
||
|
||
if ( match ) { |
||
html = html.substring( match[0].length ); |
||
match[0].replace( START_TAG_REGEXP, parseStartTag ); |
||
chars = false; |
||
} |
||
} |
||
|
||
if ( chars ) { |
||
index = html.indexOf("<"); |
||
|
||
var text = index < 0 ? html : html.substring( 0, index ); |
||
html = index < 0 ? "" : html.substring( index ); |
||
|
||
if (handler.chars) handler.chars( decodeEntities(text) ); |
||
} |
||
|
||
} else { |
||
html = html.replace(new RegExp("(.*)<\\s*\\/\\s*" + stack.last() + "[^>]*>", 'i'), |
||
function(all, text){ |
||
text = text.replace(COMMENT_REGEXP, "$1").replace(CDATA_REGEXP, "$1"); |
||
|
||
if (handler.chars) handler.chars( decodeEntities(text) ); |
||
|
||
return ""; |
||
}); |
||
|
||
parseEndTag( "", stack.last() ); |
||
} |
||
|
||
if ( html == last ) { |
||
throw $sanitizeMinErr('badparse', "The sanitizer was unable to parse the following block " + |
||
"of html: {0}", html); |
||
} |
||
last = html; |
||
} |
||
|
||
// Clean up any remaining tags |
||
parseEndTag(); |
||
|
||
function parseStartTag( tag, tagName, rest, unary ) { |
||
tagName = angular.lowercase(tagName); |
||
if ( blockElements[ tagName ] ) { |
||
while ( stack.last() && inlineElements[ stack.last() ] ) { |
||
parseEndTag( "", stack.last() ); |
||
} |
||
} |
||
|
||
if ( optionalEndTagElements[ tagName ] && stack.last() == tagName ) { |
||
parseEndTag( "", tagName ); |
||
} |
||
|
||
unary = voidElements[ tagName ] || !!unary; |
||
|
||
if ( !unary ) |
||
stack.push( tagName ); |
||
|
||
var attrs = {}; |
||
|
||
rest.replace(ATTR_REGEXP, |
||
function(match, name, doubleQuotedValue, singleQuotedValue, unquotedValue) { |
||
var value = doubleQuotedValue |
||
|| singleQuotedValue |
||
|| unquotedValue |
||
|| ''; |
||
|
||
attrs[name] = decodeEntities(value); |
||
}); |
||
if (handler.start) handler.start( tagName, attrs, unary ); |
||
} |
||
|
||
function parseEndTag( tag, tagName ) { |
||
var pos = 0, i; |
||
tagName = angular.lowercase(tagName); |
||
if ( tagName ) |
||
// Find the closest opened tag of the same type |
||
for ( pos = stack.length - 1; pos >= 0; pos-- ) |
||
if ( stack[ pos ] == tagName ) |
||
break; |
||
|
||
if ( pos >= 0 ) { |
||
// Close all the open elements, up the stack |
||
for ( i = stack.length - 1; i >= pos; i-- ) |
||
if (handler.end) handler.end( stack[ i ] ); |
||
|
||
// Remove the open elements from the stack |
||
stack.length = pos; |
||
} |
||
} |
||
} |
||
|
||
var hiddenPre=document.createElement("pre"); |
||
var spaceRe = /^(\s*)([\s\S]*?)(\s*)$/; |
||
/** |
||
* decodes all entities into regular string |
||
* @param value |
||
* @returns {string} A string with decoded entities. |
||
*/ |
||
function decodeEntities(value) { |
||
if (!value) { return ''; } |
||
|
||
// Note: IE8 does not preserve spaces at the start/end of innerHTML |
||
// so we must capture them and reattach them afterward |
||
var parts = spaceRe.exec(value); |
||
var spaceBefore = parts[1]; |
||
var spaceAfter = parts[3]; |
||
var content = parts[2]; |
||
if (content) { |
||
hiddenPre.innerHTML=content.replace(/</g,"<"); |
||
// innerText depends on styling as it doesn't display hidden elements. |
||
// Therefore, it's better to use textContent not to cause unnecessary |
||
// reflows. However, IE<9 don't support textContent so the innerText |
||
// fallback is necessary. |
||
content = 'textContent' in hiddenPre ? |
||
hiddenPre.textContent : hiddenPre.innerText; |
||
} |
||
return spaceBefore + content + spaceAfter; |
||
} |
||
|
||
/** |
||
* Escapes all potentially dangerous characters, so that the |
||
* resulting string can be safely inserted into attribute or |
||
* element text. |
||
* @param value |
||
* @returns escaped text |
||
*/ |
||
function encodeEntities(value) { |
||
return value. |
||
replace(/&/g, '&'). |
||
replace(NON_ALPHANUMERIC_REGEXP, function(value){ |
||
return '&#' + value.charCodeAt(0) + ';'; |
||
}). |
||
replace(/</g, '<'). |
||
replace(/>/g, '>'); |
||
} |
||
|
||
/** |
||
* create an HTML/XML writer which writes to buffer |
||
* @param {Array} buf use buf.jain('') to get out sanitized html string |
||
* @returns {object} in the form of { |
||
* start: function(tag, attrs, unary) {}, |
||
* end: function(tag) {}, |
||
* chars: function(text) {}, |
||
* comment: function(text) {} |
||
* } |
||
*/ |
||
function htmlSanitizeWriter(buf, uriValidator){ |
||
var ignore = false; |
||
var out = angular.bind(buf, buf.push); |
||
return { |
||
start: function(tag, attrs, unary){ |
||
tag = angular.lowercase(tag); |
||
if (!ignore && specialElements[tag]) { |
||
ignore = tag; |
||
} |
||
if (!ignore && validElements[tag] === true) { |
||
out('<'); |
||
out(tag); |
||
angular.forEach(attrs, function(value, key){ |
||
var lkey=angular.lowercase(key); |
||
var isImage = (tag === 'img' && lkey === 'src') || (lkey === 'background'); |
||
if (validAttrs[lkey] === true && |
||
(uriAttrs[lkey] !== true || uriValidator(value, isImage))) { |
||
out(' '); |
||
out(key); |
||
out('="'); |
||
out(encodeEntities(value)); |
||
out('"'); |
||
} |
||
}); |
||
out(unary ? '/>' : '>'); |
||
} |
||
}, |
||
end: function(tag){ |
||
tag = angular.lowercase(tag); |
||
if (!ignore && validElements[tag] === true) { |
||
out('</'); |
||
out(tag); |
||
out('>'); |
||
} |
||
if (tag == ignore) { |
||
ignore = false; |
||
} |
||
}, |
||
chars: function(chars){ |
||
if (!ignore) { |
||
out(encodeEntities(chars)); |
||
} |
||
} |
||
}; |
||
} |
||
|
||
|
||
// define ngSanitize module and register $sanitize service |
||
angular.module('ngSanitize', []).provider('$sanitize', $SanitizeProvider); |
||
|
||
/* global sanitizeText: false */ |
||
|
||
/** |
||
* @ngdoc filter |
||
* @name ngSanitize.filter:linky |
||
* @function |
||
* |
||
* @description |
||
* Finds links in text input and turns them into html links. Supports http/https/ftp/mailto and |
||
* plain email address links. |
||
* |
||
* Requires the {@link ngSanitize `ngSanitize`} module to be installed. |
||
* |
||
* @param {string} text Input text. |
||
* @param {string} target Window (_blank|_self|_parent|_top) or named frame to open links in. |
||
* @returns {string} Html-linkified text. |
||
* |
||
* @usage |
||
<span ng-bind-html="linky_expression | linky"></span> |
||
* |
||
* @example |
||
<doc:example module="ngSanitize"> |
||
<doc:source> |
||
<script> |
||
function Ctrl($scope) { |
||
$scope.snippet = |
||
'Pretty text with some links:\n'+ |
||
'http://angularjs.org/,\n'+ |
||
'mailto:[email protected],\n'+ |
||
'[email protected],\n'+ |
||
'and one more: ftp://127.0.0.1/.'; |
||
$scope.snippetWithTarget = 'http://angularjs.org/'; |
||
} |
||
</script> |
||
<div ng-controller="Ctrl"> |
||
Snippet: <textarea ng-model="snippet" cols="60" rows="3"></textarea> |
||
<table> |
||
<tr> |
||
<td>Filter</td> |
||
<td>Source</td> |
||
<td>Rendered</td> |
||
</tr> |
||
<tr id="linky-filter"> |
||
<td>linky filter</td> |
||
<td> |
||
<pre><div ng-bind-html="snippet | linky"><br></div></pre> |
||
</td> |
||
<td> |
||
<div ng-bind-html="snippet | linky"></div> |
||
</td> |
||
</tr> |
||
<tr id="linky-target"> |
||
<td>linky target</td> |
||
<td> |
||
<pre><div ng-bind-html="snippetWithTarget | linky:'_blank'"><br></div></pre> |
||
</td> |
||
<td> |
||
<div ng-bind-html="snippetWithTarget | linky:'_blank'"></div> |
||
</td> |
||
</tr> |
||
<tr id="escaped-html"> |
||
<td>no filter</td> |
||
<td><pre><div ng-bind="snippet"><br></div></pre></td> |
||
<td><div ng-bind="snippet"></div></td> |
||
</tr> |
||
</table> |
||
</doc:source> |
||
<doc:scenario> |
||
it('should linkify the snippet with urls', function() { |
||
expect(using('#linky-filter').binding('snippet | linky')). |
||
toBe('Pretty text with some links: ' + |
||
'<a href="http://angularjs.org/">http://angularjs.org/</a>, ' + |
||
'<a href="mailto:[email protected]">[email protected]</a>, ' + |
||
'<a href="mailto:[email protected]">[email protected]</a>, ' + |
||
'and one more: <a href="ftp://127.0.0.1/">ftp://127.0.0.1/</a>.'); |
||
}); |
||
|
||
it ('should not linkify snippet without the linky filter', function() { |
||
expect(using('#escaped-html').binding('snippet')). |
||
toBe("Pretty text with some links:\n" + |
||
"http://angularjs.org/,\n" + |
||
"mailto:[email protected],\n" + |
||
"[email protected],\n" + |
||
"and one more: ftp://127.0.0.1/."); |
||
}); |
||
|
||
it('should update', function() { |
||
input('snippet').enter('new http://link.'); |
||
expect(using('#linky-filter').binding('snippet | linky')). |
||
toBe('new <a href="http://link">http://link</a>.'); |
||
expect(using('#escaped-html').binding('snippet')).toBe('new http://link.'); |
||
}); |
||
|
||
it('should work with the target property', function() { |
||
expect(using('#linky-target').binding("snippetWithTarget | linky:'_blank'")). |
||
toBe('<a target="_blank" href="http://angularjs.org/">http://angularjs.org/</a>'); |
||
}); |
||
</doc:scenario> |
||
</doc:example> |
||
*/ |
||
angular.module('ngSanitize').filter('linky', ['$sanitize', function($sanitize) { |
||
var LINKY_URL_REGEXP = |
||
/((ftp|https?):\/\/|(mailto:)?[A-Za-z0-9._%+-]+@)\S*[^\s.;,(){}<>]/, |
||
MAILTO_REGEXP = /^mailto:/; |
||
|
||
return function(text, target) { |
||
if (!text) return text; |
||
var match; |
||
var raw = text; |
||
var html = []; |
||
var url; |
||
var i; |
||
while ((match = raw.match(LINKY_URL_REGEXP))) { |
||
// We can not end in these as they are sometimes found at the end of the sentence |
||
url = match[0]; |
||
// if we did not match ftp/http/mailto then assume mailto |
||
if (match[2] == match[3]) url = 'mailto:' + url; |
||
i = match.index; |
||
addText(raw.substr(0, i)); |
||
addLink(url, match[0].replace(MAILTO_REGEXP, '')); |
||
raw = raw.substring(i + match[0].length); |
||
} |
||
addText(raw); |
||
return $sanitize(html.join('')); |
||
|
||
function addText(text) { |
||
if (!text) { |
||
return; |
||
} |
||
html.push(sanitizeText(text)); |
||
} |
||
|
||
function addLink(url, text) { |
||
html.push('<a '); |
||
if (angular.isDefined(target)) { |
||
html.push('target="'); |
||
html.push(target); |
||
html.push('" '); |
||
} |
||
html.push('href="'); |
||
html.push(url); |
||
html.push('">'); |
||
addText(text); |
||
html.push('</a>'); |
||
} |
||
}; |
||
}]); |
||
|
||
|
||
})(window, window.angular); |
||
|
||
/* |
||
* angular-ui-bootstrap |
||
* http://angular-ui.github.io/bootstrap/ |
||
|
||
* Version: 0.10.0 - 2014-02-10 |
||
* License: MIT |
||
*/ |
||
angular.module("ui.bootstrap", ["ui.bootstrap.tpls", "ui.bootstrap.transition","ui.bootstrap.collapse","ui.bootstrap.dropdownToggle","ui.bootstrap.modal","ui.bootstrap.position","ui.bootstrap.bindHtml","ui.bootstrap.tooltip"]); |
||
angular.module("ui.bootstrap.tpls", ["template/modal/backdrop.html","template/modal/window.html","template/tooltip/tooltip-html-unsafe-popup.html","template/tooltip/tooltip-popup.html"]); |
||
angular.module('ui.bootstrap.transition', []) |
||
|
||
/** |
||
* $transition service provides a consistent interface to trigger CSS 3 transitions and to be informed when they complete. |
||
* @param {DOMElement} element The DOMElement that will be animated. |
||
* @param {string|object|function} trigger The thing that will cause the transition to start: |
||
* - As a string, it represents the css class to be added to the element. |
||
* - As an object, it represents a hash of style attributes to be applied to the element. |
||
* - As a function, it represents a function to be called that will cause the transition to occur. |
||
* @return {Promise} A promise that is resolved when the transition finishes. |
||
*/ |
||
.factory('$transition', ['$q', '$timeout', '$rootScope', function($q, $timeout, $rootScope) { |
||
|
||
var $transition = function(element, trigger, options) { |
||
options = options || {}; |
||
var deferred = $q.defer(); |
||
var endEventName = $transition[options.animation ? "animationEndEventName" : "transitionEndEventName"]; |
||
|
||
var transitionEndHandler = function(event) { |
||
$rootScope.$apply(function() { |
||
element.unbind(endEventName, transitionEndHandler); |
||
deferred.resolve(element); |
||
}); |
||
}; |
||
|
||
if (endEventName) { |
||
element.bind(endEventName, transitionEndHandler); |
||
} |
||
|
||
// Wrap in a timeout to allow the browser time to update the DOM before the transition is to occur |
||
$timeout(function() { |
||
if ( angular.isString(trigger) ) { |
||
element.addClass(trigger); |
||
} else if ( angular.isFunction(trigger) ) { |
||
trigger(element); |
||
} else if ( angular.isObject(trigger) ) { |
||
element.css(trigger); |
||
} |
||
//If browser does not support transitions, instantly resolve |
||
if ( !endEventName ) { |
||
deferred.resolve(element); |
||
} |
||
}); |
||
|
||
// Add our custom cancel function to the promise that is returned |
||
// We can call this if we are about to run a new transition, which we know will prevent this transition from ending, |
||
// i.e. it will therefore never raise a transitionEnd event for that transition |
||
deferred.promise.cancel = function() { |
||
if ( endEventName ) { |
||
element.unbind(endEventName, transitionEndHandler); |
||
} |
||
deferred.reject('Transition cancelled'); |
||
}; |
||
|
||
return deferred.promise; |
||
}; |
||
|
||
// Work out the name of the transitionEnd event |
||
var transElement = document.createElement('trans'); |
||
var transitionEndEventNames = { |
||
'WebkitTransition': 'webkitTransitionEnd', |
||
'MozTransition': 'transitionend', |
||
'OTransition': 'oTransitionEnd', |
||
'transition': 'transitionend' |
||
}; |
||
var animationEndEventNames = { |
||
'WebkitTransition': 'webkitAnimationEnd', |
||
'MozTransition': 'animationend', |
||
'OTransition': 'oAnimationEnd', |
||
'transition': 'animationend' |
||
}; |
||
function findEndEventName(endEventNames) { |
||
for (var name in endEventNames){ |
||
if (transElement.style[name] !== undefined) { |
||
return endEventNames[name]; |
||
} |
||
} |
||
} |
||
$transition.transitionEndEventName = findEndEventName(transitionEndEventNames); |
||
$transition.animationEndEventName = findEndEventName(animationEndEventNames); |
||
return $transition; |
||
}]); |
||
|
||
angular.module('ui.bootstrap.collapse', ['ui.bootstrap.transition']) |
||
|
||
.directive('collapse', ['$transition', function ($transition, $timeout) { |
||
|
||
return { |
||
link: function (scope, element, attrs) { |
||
|
||
var initialAnimSkip = true; |
||
var currentTransition; |
||
|
||
function doTransition(change) { |
||
var newTransition = $transition(element, change); |
||
if (currentTransition) { |
||
currentTransition.cancel(); |
||
} |
||
currentTransition = newTransition; |
||
newTransition.then(newTransitionDone, newTransitionDone); |
||
return newTransition; |
||
|
||
function newTransitionDone() { |
||
// Make sure it's this transition, otherwise, leave it alone. |
||
if (currentTransition === newTransition) { |
||
currentTransition = undefined; |
||
} |
||
} |
||
} |
||
|
||
function expand() { |
||
if (initialAnimSkip) { |
||
initialAnimSkip = false; |
||
expandDone(); |
||
} else { |
||
element.removeClass('collapse').addClass('collapsing'); |
||
doTransition({ height: element[0].scrollHeight + 'px' }).then(expandDone); |
||
} |
||
} |
||
|
||
function expandDone() { |
||
element.removeClass('collapsing'); |
||
element.addClass('collapse in'); |
||
element.css({height: 'auto'}); |
||
} |
||
|
||
function collapse() { |
||
if (initialAnimSkip) { |
||
initialAnimSkip = false; |
||
collapseDone(); |
||
element.css({height: 0}); |
||
} else { |
||
// CSS transitions don't work with height: auto, so we have to manually change the height to a specific value |
||
element.css({ height: element[0].scrollHeight + 'px' }); |
||
//trigger reflow so a browser realizes that height was updated from auto to a specific value |
||
var x = element[0].offsetWidth; |
||
|
||
element.removeClass('collapse in').addClass('collapsing'); |
||
|
||
doTransition({ height: 0 }).then(collapseDone); |
||
} |
||
} |
||
|
||
function collapseDone() { |
||
element.removeClass('collapsing'); |
||
element.addClass('collapse'); |
||
} |
||
|
||
scope.$watch(attrs.collapse, function (shouldCollapse) { |
||
if (shouldCollapse) { |
||
collapse(); |
||
} else { |
||
expand(); |
||
} |
||
}); |
||
} |
||
}; |
||
}]); |
||
|
||
/* |
||
* dropdownToggle - Provides dropdown menu functionality in place of bootstrap js |
||
* @restrict class or attribute |
||
* @example: |
||
<li class="dropdown"> |
||
<a class="dropdown-toggle">My Dropdown Menu</a> |
||
<ul class="dropdown-menu"> |
||
<li ng-repeat="choice in dropChoices"> |
||
<a ng-href="{{choice.href}}">{{choice.text}}</a> |
||
</li> |
||
</ul> |
||
</li> |
||
*/ |
||
|
||
angular.module('ui.bootstrap.dropdownToggle', []).directive('dropdownToggle', ['$document', '$location', function ($document, $location) { |
||
var openElement = null, |
||
closeMenu = angular.noop; |
||
return { |
||
restrict: 'CA', |
||
link: function(scope, element, attrs) { |
||
scope.$watch('$location.path', function() { closeMenu(); }); |
||
element.parent().bind('click', function() { closeMenu(); }); |
||
element.bind('click', function (event) { |
||
|
||
var elementWasOpen = (element === openElement); |
||
|
||
event.preventDefault(); |
||
event.stopPropagation(); |
||
|
||
if (!!openElement) { |
||
closeMenu(); |
||
} |
||
|
||
if (!elementWasOpen && !element.hasClass('disabled') && !element.prop('disabled')) { |
||
element.parent().addClass('open'); |
||
openElement = element; |
||
closeMenu = function (event) { |
||
if (event) { |
||
event.preventDefault(); |
||
event.stopPropagation(); |
||
} |
||
$document.unbind('click', closeMenu); |
||
element.parent().removeClass('open'); |
||
closeMenu = angular.noop; |
||
openElement = null; |
||
}; |
||
$document.bind('click', closeMenu); |
||
} |
||
}); |
||
} |
||
}; |
||
}]); |
||
|
||
angular.module('ui.bootstrap.modal', ['ui.bootstrap.transition']) |
||
|
||
/** |
||
* A helper, internal data structure that acts as a map but also allows getting / removing |
||
* elements in the LIFO order |
||
*/ |
||
.factory('$$stackedMap', function () { |
||
return { |
||
createNew: function () { |
||
var stack = []; |
||
|
||
return { |
||
add: function (key, value) { |
||
stack.push({ |
||
key: key, |
||
value: value |
||
}); |
||
}, |
||
get: function (key) { |
||
for (var i = 0; i < stack.length; i++) { |
||
if (key == stack[i].key) { |
||
return stack[i]; |
||
} |
||
} |
||
}, |
||
keys: function() { |
||
var keys = []; |
||
for (var i = 0; i < stack.length; i++) { |
||
keys.push(stack[i].key); |
||
} |
||
return keys; |
||
}, |
||
top: function () { |
||
return stack[stack.length - 1]; |
||
}, |
||
remove: function (key) { |
||
var idx = -1; |
||
for (var i = 0; i < stack.length; i++) { |
||
if (key == stack[i].key) { |
||
idx = i; |
||
break; |
||
} |
||
} |
||
return stack.splice(idx, 1)[0]; |
||
}, |
||
removeTop: function () { |
||
return stack.splice(stack.length - 1, 1)[0]; |
||
}, |
||
length: function () { |
||
return stack.length; |
||
} |
||
}; |
||
} |
||
}; |
||
}) |
||
|
||
/** |
||
* A helper directive for the $modal service. It creates a backdrop element. |
||
*/ |
||
.directive('modalBackdrop', ['$timeout', function ($timeout) { |
||
return { |
||
restrict: 'EA', |
||
replace: true, |
||
templateUrl: 'template/modal/backdrop.html', |
||
link: function (scope) { |
||
|
||
scope.animate = false; |
||
|
||
//trigger CSS transitions |
||
$timeout(function () { |
||
scope.animate = true; |
||
}); |
||
} |
||
}; |
||
}]) |
||
|
||
.directive('modalWindow', ['$modalStack', '$timeout', function ($modalStack, $timeout) { |
||
return { |
||
restrict: 'EA', |
||
scope: { |
||
index: '@', |
||
animate: '=' |
||
}, |
||
replace: true, |
||
transclude: true, |
||
templateUrl: 'template/modal/window.html', |
||
link: function (scope, element, attrs) { |
||
scope.windowClass = attrs.windowClass || ''; |
||
|
||
$timeout(function () { |
||
// trigger CSS transitions |
||
scope.animate = true; |
||
// focus a freshly-opened modal |
||
element[0].focus(); |
||
}); |
||
|
||
scope.close = function (evt) { |
||
var modal = $modalStack.getTop(); |
||
if (modal && modal.value.backdrop && modal.value.backdrop != 'static' && (evt.target === evt.currentTarget)) { |
||
evt.preventDefault(); |
||
evt.stopPropagation(); |
||
$modalStack.dismiss(modal.key, 'backdrop click'); |
||
} |
||
}; |
||
} |
||
}; |
||
}]) |
||
|
||
.factory('$modalStack', ['$transition', '$timeout', '$document', '$compile', '$rootScope', '$$stackedMap', |
||
function ($transition, $timeout, $document, $compile, $rootScope, $$stackedMap) { |
||
|
||
var OPENED_MODAL_CLASS = 'modal-open'; |
||
|
||
var backdropDomEl, backdropScope; |
||
var openedWindows = $$stackedMap.createNew(); |
||
var $modalStack = {}; |
||
|
||
function backdropIndex() { |
||
var topBackdropIndex = -1; |
||
var opened = openedWindows.keys(); |
||
for (var i = 0; i < opened.length; i++) { |
||
if (openedWindows.get(opened[i]).value.backdrop) { |
||
topBackdropIndex = i; |
||
} |
||
} |
||
return topBackdropIndex; |
||
} |
||
|
||
$rootScope.$watch(backdropIndex, function(newBackdropIndex){ |
||
if (backdropScope) { |
||
backdropScope.index = newBackdropIndex; |
||
} |
||
}); |
||
|
||
function removeModalWindow(modalInstance) { |
||
|
||
var body = $document.find('body').eq(0); |
||
var modalWindow = openedWindows.get(modalInstance).value; |
||
|
||
//clean up the stack |
||
openedWindows.remove(modalInstance); |
||
|
||
//remove window DOM element |
||
removeAfterAnimate(modalWindow.modalDomEl, modalWindow.modalScope, 300, checkRemoveBackdrop); |
||
body.toggleClass(OPENED_MODAL_CLASS, openedWindows.length() > 0); |
||
} |
||
|
||
function checkRemoveBackdrop() { |
||
//remove backdrop if no longer needed |
||
if (backdropDomEl && backdropIndex() == -1) { |
||
var backdropScopeRef = backdropScope; |
||
removeAfterAnimate(backdropDomEl, backdropScope, 150, function () { |
||
backdropScopeRef.$destroy(); |
||
backdropScopeRef = null; |
||
}); |
||
backdropDomEl = undefined; |
||
backdropScope = undefined; |
||
} |
||
} |
||
|
||
function removeAfterAnimate(domEl, scope, emulateTime, done) { |
||
// Closing animation |
||
scope.animate = false; |
||
|
||
var transitionEndEventName = $transition.transitionEndEventName; |
||
if (transitionEndEventName) { |
||
// transition out |
||
var timeout = $timeout(afterAnimating, emulateTime); |
||
|
||
domEl.bind(transitionEndEventName, function () { |
||
$timeout.cancel(timeout); |
||
afterAnimating(); |
||
scope.$apply(); |
||
}); |
||
} else { |
||
// Ensure this call is async |
||
$timeout(afterAnimating, 0); |
||
} |
||
|
||
function afterAnimating() { |
||
if (afterAnimating.done) { |
||
return; |
||
} |
||
afterAnimating.done = true; |
||
|
||
domEl.remove(); |
||
if (done) { |
||
done(); |
||
} |
||
} |
||
} |
||
|
||
$document.bind('keydown', function (evt) { |
||
var modal; |
||
|
||
if (evt.which === 27) { |
||
modal = openedWindows.top(); |
||
if (modal && modal.value.keyboard) { |
||
$rootScope.$apply(function () { |
||
$modalStack.dismiss(modal.key); |
||
}); |
||
} |
||
} |
||
}); |
||
|
||
$modalStack.open = function (modalInstance, modal) { |
||
|
||
openedWindows.add(modalInstance, { |
||
deferred: modal.deferred, |
||
modalScope: modal.scope, |
||
backdrop: modal.backdrop, |
||
keyboard: modal.keyboard |
||
}); |
||
|
||
var body = $document.find('body').eq(0), |
||
currBackdropIndex = backdropIndex(); |
||
|
||
if (currBackdropIndex >= 0 && !backdropDomEl) { |
||
backdropScope = $rootScope.$new(true); |
||
backdropScope.index = currBackdropIndex; |
||
backdropDomEl = $compile('<div modal-backdrop></div>')(backdropScope); |
||
body.append(backdropDomEl); |
||
} |
||
|
||
var angularDomEl = angular.element('<div modal-window></div>'); |
||
angularDomEl.attr('window-class', modal.windowClass); |
||
angularDomEl.attr('index', openedWindows.length() - 1); |
||
angularDomEl.attr('animate', 'animate'); |
||
angularDomEl.html(modal.content); |
||
|
||
var modalDomEl = $compile(angularDomEl)(modal.scope); |
||
openedWindows.top().value.modalDomEl = modalDomEl; |
||
body.append(modalDomEl); |
||
body.addClass(OPENED_MODAL_CLASS); |
||
}; |
||
|
||
$modalStack.close = function (modalInstance, result) { |
||
var modalWindow = openedWindows.get(modalInstance).value; |
||
if (modalWindow) { |
||
modalWindow.deferred.resolve(result); |
||
removeModalWindow(modalInstance); |
||
} |
||
}; |
||
|
||
$modalStack.dismiss = function (modalInstance, reason) { |
||
var modalWindow = openedWindows.get(modalInstance).value; |
||
if (modalWindow) { |
||
modalWindow.deferred.reject(reason); |
||
removeModalWindow(modalInstance); |
||
} |
||
}; |
||
|
||
$modalStack.dismissAll = function (reason) { |
||
var topModal = this.getTop(); |
||
while (topModal) { |
||
this.dismiss(topModal.key, reason); |
||
topModal = this.getTop(); |
||
} |
||
}; |
||
|
||
$modalStack.getTop = function () { |
||
return openedWindows.top(); |
||
}; |
||
|
||
return $modalStack; |
||
}]) |
||
|
||
.provider('$modal', function () { |
||
|
||
var $modalProvider = { |
||
options: { |
||
backdrop: true, //can be also false or 'static' |
||
keyboard: true |
||
}, |
||
$get: ['$injector', '$rootScope', '$q', '$http', '$templateCache', '$controller', '$modalStack', |
||
function ($injector, $rootScope, $q, $http, $templateCache, $controller, $modalStack) { |
||
|
||
var $modal = {}; |
||
|
||
function getTemplatePromise(options) { |
||
return options.template ? $q.when(options.template) : |
||
$http.get(options.templateUrl, {cache: $templateCache}).then(function (result) { |
||
return result.data; |
||
}); |
||
} |
||
|
||
function getResolvePromises(resolves) { |
||
var promisesArr = []; |
||
angular.forEach(resolves, function (value, key) { |
||
if (angular.isFunction(value) || angular.isArray(value)) { |
||
promisesArr.push($q.when($injector.invoke(value))); |
||
} |
||
}); |
||
return promisesArr; |
||
} |
||
|
||
$modal.open = function (modalOptions) { |
||
|
||
var modalResultDeferred = $q.defer(); |
||
var modalOpenedDeferred = $q.defer(); |
||
|
||
//prepare an instance of a modal to be injected into controllers and returned to a caller |
||
var modalInstance = { |
||
result: modalResultDeferred.promise, |
||
opened: modalOpenedDeferred.promise, |
||
close: function (result) { |
||
$modalStack.close(modalInstance, result); |
||
}, |
||
dismiss: function (reason) { |
||
$modalStack.dismiss(modalInstance, reason); |
||
} |
||
}; |
||
|
||
//merge and clean up options |
||
modalOptions = angular.extend({}, $modalProvider.options, modalOptions); |
||
modalOptions.resolve = modalOptions.resolve || {}; |
||
|
||
//verify options |
||
if (!modalOptions.template && !modalOptions.templateUrl) { |
||
throw new Error('One of template or templateUrl options is required.'); |
||
} |
||
|
||
var templateAndResolvePromise = |
||
$q.all([getTemplatePromise(modalOptions)].concat(getResolvePromises(modalOptions.resolve))); |
||
|
||
|
||
templateAndResolvePromise.then(function resolveSuccess(tplAndVars) { |
||
|
||
var modalScope = (modalOptions.scope || $rootScope).$new(); |
||
modalScope.$close = modalInstance.close; |
||
modalScope.$dismiss = modalInstance.dismiss; |
||
|
||
var ctrlInstance, ctrlLocals = {}; |
||
var resolveIter = 1; |
||
|
||
//controllers |
||
if (modalOptions.controller) { |
||
ctrlLocals.$scope = modalScope; |
||
ctrlLocals.$modalInstance = modalInstance; |
||
angular.forEach(modalOptions.resolve, function (value, key) { |
||
ctrlLocals[key] = tplAndVars[resolveIter++]; |
||
}); |
||
|
||
ctrlInstance = $controller(modalOptions.controller, ctrlLocals); |
||
} |
||
|
||
$modalStack.open(modalInstance, { |
||
scope: modalScope, |
||
deferred: modalResultDeferred, |
||
content: tplAndVars[0], |
||
backdrop: modalOptions.backdrop, |
||
keyboard: modalOptions.keyboard, |
||
windowClass: modalOptions.windowClass |
||
}); |
||
|
||
}, function resolveError(reason) { |
||
modalResultDeferred.reject(reason); |
||
}); |
||
|
||
templateAndResolvePromise.then(function () { |
||
modalOpenedDeferred.resolve(true); |
||
}, function () { |
||
modalOpenedDeferred.reject(false); |
||
}); |
||
|
||
return modalInstance; |
||
}; |
||
|
||
return $modal; |
||
}] |
||
}; |
||
|
||
return $modalProvider; |
||
}); |
||
|
||
angular.module('ui.bootstrap.position', []) |
||
|
||
/** |
||
* A set of utility methods that can be use to retrieve position of DOM elements. |
||
* It is meant to be used where we need to absolute-position DOM elements in |
||
* relation to other, existing elements (this is the case for tooltips, popovers, |
||
* typeahead suggestions etc.). |
||
*/ |
||
.factory('$position', ['$document', '$window', function ($document, $window) { |
||
|
||
function getStyle(el, cssprop) { |
||
if (el.currentStyle) { //IE |
||
return el.currentStyle[cssprop]; |
||
} else if ($window.getComputedStyle) { |
||
return $window.getComputedStyle(el)[cssprop]; |
||
} |
||
// finally try and get inline style |
||
return el.style[cssprop]; |
||
} |
||
|
||
/** |
||
* Checks if a given element is statically positioned |
||
* @param element - raw DOM element |
||
*/ |
||
function isStaticPositioned(element) { |
||
return (getStyle(element, "position") || 'static' ) === 'static'; |
||
} |
||
|
||
/** |
||
* returns the closest, non-statically positioned parentOffset of a given element |
||
* @param element |
||
*/ |
||
var parentOffsetEl = function (element) { |
||
var docDomEl = $document[0]; |
||
var offsetParent = element.offsetParent || docDomEl; |
||
while (offsetParent && offsetParent !== docDomEl && isStaticPositioned(offsetParent) ) { |
||
offsetParent = offsetParent.offsetParent; |
||
} |
||
return offsetParent || docDomEl; |
||
}; |
||
|
||
return { |
||
/** |
||
* Provides read-only equivalent of jQuery's position function: |
||
* http://api.jquery.com/position/ |
||
*/ |
||
position: function (element) { |
||
var elBCR = this.offset(element); |
||
var offsetParentBCR = { top: 0, left: 0 }; |
||
var offsetParentEl = parentOffsetEl(element[0]); |
||
if (offsetParentEl != $document[0]) { |
||
offsetParentBCR = this.offset(angular.element(offsetParentEl)); |
||
offsetParentBCR.top += offsetParentEl.clientTop - offsetParentEl.scrollTop; |
||
offsetParentBCR.left += offsetParentEl.clientLeft - offsetParentEl.scrollLeft; |
||
} |
||
|
||
var boundingClientRect = element[0].getBoundingClientRect(); |
||
return { |
||
width: boundingClientRect.width || element.prop('offsetWidth'), |
||
height: boundingClientRect.height || element.prop('offsetHeight'), |
||
top: elBCR.top - offsetParentBCR.top, |
||
left: elBCR.left - offsetParentBCR.left |
||
}; |
||
}, |
||
|
||
/** |
||
* Provides read-only equivalent of jQuery's offset function: |
||
* http://api.jquery.com/offset/ |
||
*/ |
||
offset: function (element) { |
||
var boundingClientRect = element[0].getBoundingClientRect(); |
||
return { |
||
width: boundingClientRect.width || element.prop('offsetWidth'), |
||
height: boundingClientRect.height || element.prop('offsetHeight'), |
||
top: boundingClientRect.top + ($window.pageYOffset || $document[0].body.scrollTop || $document[0].documentElement.scrollTop), |
||
left: boundingClientRect.left + ($window.pageXOffset || $document[0].body.scrollLeft || $document[0].documentElement.scrollLeft) |
||
}; |
||
} |
||
}; |
||
}]); |
||
|
||
angular.module('ui.bootstrap.bindHtml', []) |
||
|
||
.directive('bindHtmlUnsafe', function () { |
||
return function (scope, element, attr) { |
||
element.addClass('ng-binding').data('$binding', attr.bindHtmlUnsafe); |
||
scope.$watch(attr.bindHtmlUnsafe, function bindHtmlUnsafeWatchAction(value) { |
||
element.html(value || ''); |
||
}); |
||
}; |
||
}); |
||
/** |
||
* The following features are still outstanding: animation as a |
||
* function, placement as a function, inside, support for more triggers than |
||
* just mouse enter/leave, html tooltips, and selector delegation. |
||
*/ |
||
angular.module( 'ui.bootstrap.tooltip', [ 'ui.bootstrap.position', 'ui.bootstrap.bindHtml' ] ) |
||
|
||
/** |
||
* The $tooltip service creates tooltip- and popover-like directives as well as |
||
* houses global options for them. |
||
*/ |
||
.provider( '$tooltip', function () { |
||
// The default options tooltip and popover. |
||
var defaultOptions = { |
||
placement: 'top', |
||
animation: true, |
||
popupDelay: 0 |
||
}; |
||
|
||
// Default hide triggers for each show trigger |
||
var triggerMap = { |
||
'mouseenter': 'mouseleave', |
||
'click': 'click', |
||
'focus': 'blur' |
||
}; |
||
|
||
// The options specified to the provider globally. |
||
var globalOptions = {}; |
||
|
||
/** |
||
* `options({})` allows global configuration of all tooltips in the |
||
* application. |
||
* |
||
* var app = angular.module( 'App', ['ui.bootstrap.tooltip'], function( $tooltipProvider ) { |
||
* // place tooltips left instead of top by default |
||
* $tooltipProvider.options( { placement: 'left' } ); |
||
* }); |
||
*/ |
||
this.options = function( value ) { |
||
angular.extend( globalOptions, value ); |
||
}; |
||
|
||
/** |
||
* This allows you to extend the set of trigger mappings available. E.g.: |
||
* |
||
* $tooltipProvider.setTriggers( 'openTrigger': 'closeTrigger' ); |
||
*/ |
||
this.setTriggers = function setTriggers ( triggers ) { |
||
angular.extend( triggerMap, triggers ); |
||
}; |
||
|
||
/** |
||
* This is a helper function for translating camel-case to snake-case. |
||
*/ |
||
function snake_case(name){ |
||
var regexp = /[A-Z]/g; |
||
var separator = '-'; |
||
return name.replace(regexp, function(letter, pos) { |
||
return (pos ? separator : '') + letter.toLowerCase(); |
||
}); |
||
} |
||
|
||
/** |
||
* Returns the actual instance of the $tooltip service. |
||
* TODO support multiple triggers |
||
*/ |
||
this.$get = [ '$window', '$compile', '$timeout', '$parse', '$document', '$position', '$interpolate', function ( $window, $compile, $timeout, $parse, $document, $position, $interpolate ) { |
||
return function $tooltip ( type, prefix, defaultTriggerShow ) { |
||
var options = angular.extend( {}, defaultOptions, globalOptions ); |
||
|
||
/** |
||
* Returns an object of show and hide triggers. |
||
* |
||
* If a trigger is supplied, |
||
* it is used to show the tooltip; otherwise, it will use the `trigger` |
||
* option passed to the `$tooltipProvider.options` method; else it will |
||
* default to the trigger supplied to this directive factory. |
||
* |
||
* The hide trigger is based on the show trigger. If the `trigger` option |
||
* was passed to the `$tooltipProvider.options` method, it will use the |
||
* mapped trigger from `triggerMap` or the passed trigger if the map is |
||
* undefined; otherwise, it uses the `triggerMap` value of the show |
||
* trigger; else it will just use the show trigger. |
||
*/ |
||
function getTriggers ( trigger ) { |
||
var show = trigger || options.trigger || defaultTriggerShow; |
||
var hide = triggerMap[show] || show; |
||
return { |
||
show: show, |
||
hide: hide |
||
}; |
||
} |
||
|
||
var directiveName = snake_case( type ); |
||
|
||
var startSym = $interpolate.startSymbol(); |
||
var endSym = $interpolate.endSymbol(); |
||
var template = |
||
'<div '+ directiveName +'-popup '+ |
||
'title="'+startSym+'tt_title'+endSym+'" '+ |
||
'content="'+startSym+'tt_content'+endSym+'" '+ |
||
'placement="'+startSym+'tt_placement'+endSym+'" '+ |
||
'animation="tt_animation" '+ |
||
'is-open="tt_isOpen"'+ |
||
'>'+ |
||
'</div>'; |
||
|
||
return { |
||
restrict: 'EA', |
||
scope: true, |
||
compile: function (tElem, tAttrs) { |
||
var tooltipLinker = $compile( template ); |
||
|
||
return function link ( scope, element, attrs ) { |
||
var tooltip; |
||
var transitionTimeout; |
||
var popupTimeout; |
||
var appendToBody = angular.isDefined( options.appendToBody ) ? options.appendToBody : false; |
||
var triggers = getTriggers( undefined ); |
||
var hasRegisteredTriggers = false; |
||
var hasEnableExp = angular.isDefined(attrs[prefix+'Enable']); |
||
|
||
var positionTooltip = function (){ |
||
var position, |
||
ttWidth, |
||
ttHeight, |
||
ttPosition; |
||
// Get the position of the directive element. |
||
position = appendToBody ? $position.offset( element ) : $position.position( element ); |
||
|
||
// Get the height and width of the tooltip so we can center it. |
||
ttWidth = tooltip.prop( 'offsetWidth' ); |
||
ttHeight = tooltip.prop( 'offsetHeight' ); |
||
|
||
// Calculate the tooltip's top and left coordinates to center it with |
||
// this directive. |
||
switch ( scope.tt_placement ) { |
||
case 'right': |
||
ttPosition = { |
||
top: position.top + position.height / 2 - ttHeight / 2, |
||
left: position.left + position.width |
||
}; |
||
break; |
||
case 'bottom': |
||
ttPosition = { |
||
top: position.top + position.height, |
||
left: position.left + position.width / 2 - ttWidth / 2 |
||
}; |
||
break; |
||
case 'left': |
||
ttPosition = { |
||
top: position.top + position.height / 2 - ttHeight / 2, |
||
left: position.left - ttWidth |
||
}; |
||
break; |
||
default: |
||
ttPosition = { |
||
top: position.top - ttHeight, |
||
left: position.left + position.width / 2 - ttWidth / 2 |
||
}; |
||
break; |
||
} |
||
|
||
ttPosition.top += 'px'; |
||
ttPosition.left += 'px'; |
||
|
||
// Now set the calculated positioning. |
||
tooltip.css( ttPosition ); |
||
|
||
}; |
||
|
||
// By default, the tooltip is not open. |
||
// TODO add ability to start tooltip opened |
||
scope.tt_isOpen = false; |
||
|
||
function toggleTooltipBind () { |
||
if ( ! scope.tt_isOpen ) { |
||
showTooltipBind(); |
||
} else { |
||
hideTooltipBind(); |
||
} |
||
} |
||
|
||
// Show the tooltip with delay if specified, otherwise show it immediately |
||
function showTooltipBind() { |
||
if(hasEnableExp && !scope.$eval(attrs[prefix+'Enable'])) { |
||
return; |
||
} |
||
if ( scope.tt_popupDelay ) { |
||
popupTimeout = $timeout( show, scope.tt_popupDelay, false ); |
||
popupTimeout.then(function(reposition){reposition();}); |
||
} else { |
||
show()(); |
||
} |
||
} |
||
|
||
function hideTooltipBind () { |
||
scope.$apply(function () { |
||
hide(); |
||
}); |
||
} |
||
|
||
// Show the tooltip popup element. |
||
function show() { |
||
|
||
|
||
// Don't show empty tooltips. |
||
if ( ! scope.tt_content ) { |
||
return angular.noop; |
||
} |
||
|
||
createTooltip(); |
||
|
||
// If there is a pending remove transition, we must cancel it, lest the |
||
// tooltip be mysteriously removed. |
||
if ( transitionTimeout ) { |
||
$timeout.cancel( transitionTimeout ); |
||
} |
||
|
||
// Set the initial positioning. |
||
tooltip.css({ top: 0, left: 0, display: 'block' }); |
||
|
||
// Now we add it to the DOM because need some info about it. But it's not |
||
// visible yet anyway. |
||
if ( appendToBody ) { |
||
$document.find( 'body' ).append( tooltip ); |
||
} else { |
||
element.after( tooltip ); |
||
} |
||
|
||
positionTooltip(); |
||
|
||
// And show the tooltip. |
||
scope.tt_isOpen = true; |
||
scope.$digest(); // digest required as $apply is not called |
||
|
||
// Return positioning function as promise callback for correct |
||
// positioning after draw. |
||
return positionTooltip; |
||
} |
||
|
||
// Hide the tooltip popup element. |
||
function hide() { |
||
// First things first: we don't show it anymore. |
||
scope.tt_isOpen = false; |
||
|
||
//if tooltip is going to be shown after delay, we must cancel this |
||
$timeout.cancel( popupTimeout ); |
||
|
||
// And now we remove it from the DOM. However, if we have animation, we |
||
// need to wait for it to expire beforehand. |
||
// FIXME: this is a placeholder for a port of the transitions library. |
||
if ( scope.tt_animation ) { |
||
transitionTimeout = $timeout(removeTooltip, 500); |
||
} else { |
||
removeTooltip(); |
||
} |
||
} |
||
|
||
function createTooltip() { |
||
// There can only be one tooltip element per directive shown at once. |
||
if (tooltip) { |
||
removeTooltip(); |
||
} |
||
tooltip = tooltipLinker(scope, function () {}); |
||
|
||
// Get contents rendered into the tooltip |
||
scope.$digest(); |
||
} |
||
|
||
function removeTooltip() { |
||
if (tooltip) { |
||
tooltip.remove(); |
||
tooltip = null; |
||
} |
||
} |
||
|
||
/** |
||
* Observe the relevant attributes. |
||
*/ |
||
attrs.$observe( type, function ( val ) { |
||
scope.tt_content = val; |
||
|
||
if (!val && scope.tt_isOpen ) { |
||
hide(); |
||
} |
||
}); |
||
|
||
attrs.$observe( prefix+'Title', function ( val ) { |
||
scope.tt_title = val; |
||
}); |
||
|
||
attrs.$observe( prefix+'Placement', function ( val ) { |
||
scope.tt_placement = angular.isDefined( val ) ? val : options.placement; |
||
}); |
||
|
||
attrs.$observe( prefix+'PopupDelay', function ( val ) { |
||
var delay = parseInt( val, 10 ); |
||
scope.tt_popupDelay = ! isNaN(delay) ? delay : options.popupDelay; |
||
}); |
||
|
||
var unregisterTriggers = function() { |
||
if (hasRegisteredTriggers) { |
||
element.unbind( triggers.show, showTooltipBind ); |
||
element.unbind( triggers.hide, hideTooltipBind ); |
||
} |
||
}; |
||
|
||
attrs.$observe( prefix+'Trigger', function ( val ) { |
||
unregisterTriggers(); |
||
|
||
triggers = getTriggers( val ); |
||
|
||
if ( triggers.show === triggers.hide ) { |
||
element.bind( triggers.show, toggleTooltipBind ); |
||
} else { |
||
element.bind( triggers.show, showTooltipBind ); |
||
element.bind( triggers.hide, hideTooltipBind ); |
||
} |
||
|
||
hasRegisteredTriggers = true; |
||
}); |
||
|
||
var animation = scope.$eval(attrs[prefix + 'Animation']); |
||
scope.tt_animation = angular.isDefined(animation) ? !!animation : options.animation; |
||
|
||
attrs.$observe( prefix+'AppendToBody', function ( val ) { |
||
appendToBody = angular.isDefined( val ) ? $parse( val )( scope ) : appendToBody; |
||
}); |
||
|
||
// if a tooltip is attached to <body> we need to remove it on |
||
// location change as its parent scope will probably not be destroyed |
||
// by the change. |
||
if ( appendToBody ) { |
||
scope.$on('$locationChangeSuccess', function closeTooltipOnLocationChangeSuccess () { |
||
if ( scope.tt_isOpen ) { |
||
hide(); |
||
} |
||
}); |
||
} |
||
|
||
// Make sure tooltip is destroyed and removed. |
||
scope.$on('$destroy', function onDestroyTooltip() { |
||
$timeout.cancel( transitionTimeout ); |
||
$timeout.cancel( popupTimeout ); |
||
unregisterTriggers(); |
||
removeTooltip(); |
||
}); |
||
}; |
||
} |
||
}; |
||
}; |
||
}]; |
||
}) |
||
|
||
.directive( 'tooltipPopup', function () { |
||
return { |
||
restrict: 'EA', |
||
replace: true, |
||
scope: { content: '@', placement: '@', animation: '&', isOpen: '&' }, |
||
templateUrl: 'template/tooltip/tooltip-popup.html' |
||
}; |
||
}) |
||
|
||
.directive( 'tooltip', [ '$tooltip', function ( $tooltip ) { |
||
return $tooltip( 'tooltip', 'tooltip', 'mouseenter' ); |
||
}]) |
||
|
||
.directive( 'tooltipHtmlUnsafePopup', function () { |
||
return { |
||
restrict: 'EA', |
||
replace: true, |
||
scope: { content: '@', placement: '@', animation: '&', isOpen: '&' }, |
||
templateUrl: 'template/tooltip/tooltip-html-unsafe-popup.html' |
||
}; |
||
}) |
||
|
||
.directive( 'tooltipHtmlUnsafe', [ '$tooltip', function ( $tooltip ) { |
||
return $tooltip( 'tooltipHtmlUnsafe', 'tooltip', 'mouseenter' ); |
||
}]); |
||
|
||
angular.module("template/modal/backdrop.html", []).run(["$templateCache", function($templateCache) { |
||
$templateCache.put("template/modal/backdrop.html", |
||
"<div class=\"modal-backdrop fade\" ng-class=\"{in: animate}\" ng-style=\"{'z-index': 1040 + index*10 + 1}\"></div>"); |
||
}]); |
||
|
||
angular.module("template/modal/window.html", []).run(["$templateCache", function($templateCache) { |
||
$templateCache.put("template/modal/window.html", |
||
"<div tabindex=\"-1\" class=\"modal fade {{ windowClass }}\" ng-class=\"{in: animate}\" ng-style=\"{'z-index': 1050 + index*10, display: 'block'}\" ng-click=\"close($event)\">\n" + |
||
" <div class=\"modal_close_wrap hidden-xs hidden-sm\" ng-click=\"close($event)\">\n" + |
||
" <div class=\"modal_close\"></div>\n" + |
||
" </div>\n" + |
||
" <div class=\"modal-dialog\"><div class=\"modal-content\" ng-transclude></div></div>\n" + |
||
"</div>"); |
||
}]); |
||
|
||
angular.module("template/tooltip/tooltip-html-unsafe-popup.html", []).run(["$templateCache", function($templateCache) { |
||
$templateCache.put("template/tooltip/tooltip-html-unsafe-popup.html", |
||
"<div class=\"tooltip {{placement}}\" ng-class=\"{ in: isOpen(), fade: animation() }\">\n" + |
||
" <div class=\"tooltip-arrow\"></div>\n" + |
||
" <div class=\"tooltip-inner\" bind-html-unsafe=\"content\"></div>\n" + |
||
"</div>\n" + |
||
""); |
||
}]); |
||
|
||
angular.module("template/tooltip/tooltip-popup.html", []).run(["$templateCache", function($templateCache) { |
||
$templateCache.put("template/tooltip/tooltip-popup.html", |
||
"<div class=\"tooltip {{placement}}\" ng-class=\"{ in: isOpen(), fade: animation() }\">\n" + |
||
" <div class=\"tooltip-arrow\"></div>\n" + |
||
" <div class=\"tooltip-inner\" ng-bind=\"content\"></div>\n" + |
||
"</div>\n" + |
||
""); |
||
}]); |
||
|
||
// Copyright (c) 2005 Tom Wu |
||
// All Rights Reserved. |
||
// See "LICENSE" for details. |
||
|
||
// Basic JavaScript BN library - subset useful for RSA encryption. |
||
|
||
// Bits per digit |
||
var dbits; |
||
|
||
// JavaScript engine analysis |
||
var canary = 0xdeadbeefcafe; |
||
var j_lm = ((canary&0xffffff)==0xefcafe); |
||
|
||
// (public) Constructor |
||
function BigInteger(a,b,c) { |
||
if(a != null) |
||
if("number" == typeof a) this.fromNumber(a,b,c); |
||
else if(b == null && "string" != typeof a) this.fromString(a,256); |
||
else this.fromString(a,b); |
||
} |
||
|
||
// return new, unset BigInteger |
||
function nbi() { return new BigInteger(null); } |
||
|
||
// am: Compute w_j += (x*this_i), propagate carries, |
||
// c is initial carry, returns final carry. |
||
// c < 3*dvalue, x < 2*dvalue, this_i < dvalue |
||
// We need to select the fastest one that works in this environment. |
||
|
||
// am1: use a single mult and divide to get the high bits, |
||
// max digit bits should be 26 because |
||
// max internal value = 2*dvalue^2-2*dvalue (< 2^53) |
||
function am1(i,x,w,j,c,n) { |
||
while(--n >= 0) { |
||
var v = x*this[i++]+w[j]+c; |
||
c = Math.floor(v/0x4000000); |
||
w[j++] = v&0x3ffffff; |
||
} |
||
return c; |
||
} |
||
// am2 avoids a big mult-and-extract completely. |
||
// Max digit bits should be <= 30 because we do bitwise ops |
||
// on values up to 2*hdvalue^2-hdvalue-1 (< 2^31) |
||
function am2(i,x,w,j,c,n) { |
||
var xl = x&0x7fff, xh = x>>15; |
||
while(--n >= 0) { |
||
var l = this[i]&0x7fff; |
||
var h = this[i++]>>15; |
||
var m = xh*l+h*xl; |
||
l = xl*l+((m&0x7fff)<<15)+w[j]+(c&0x3fffffff); |
||
c = (l>>>30)+(m>>>15)+xh*h+(c>>>30); |
||
w[j++] = l&0x3fffffff; |
||
} |
||
return c; |
||
} |
||
// Alternately, set max digit bits to 28 since some |
||
// browsers slow down when dealing with 32-bit numbers. |
||
function am3(i,x,w,j,c,n) { |
||
var xl = x&0x3fff, xh = x>>14; |
||
while(--n >= 0) { |
||
var l = this[i]&0x3fff; |
||
var h = this[i++]>>14; |
||
var m = xh*l+h*xl; |
||
l = xl*l+((m&0x3fff)<<14)+w[j]+c; |
||
c = (l>>28)+(m>>14)+xh*h; |
||
w[j++] = l&0xfffffff; |
||
} |
||
return c; |
||
} |
||
if(j_lm && (navigator.appName == "Microsoft Internet Explorer")) { |
||
BigInteger.prototype.am = am2; |
||
dbits = 30; |
||
} |
||
else if(j_lm && (navigator.appName != "Netscape")) { |
||
BigInteger.prototype.am = am1; |
||
dbits = 26; |
||
} |
||
else { // Mozilla/Netscape seems to prefer am3 |
||
BigInteger.prototype.am = am3; |
||
dbits = 28; |
||
} |
||
|
||
BigInteger.prototype.DB = dbits; |
||
BigInteger.prototype.DM = ((1<<dbits)-1); |
||
BigInteger.prototype.DV = (1<<dbits); |
||
|
||
var BI_FP = 52; |
||
BigInteger.prototype.FV = Math.pow(2,BI_FP); |
||
BigInteger.prototype.F1 = BI_FP-dbits; |
||
BigInteger.prototype.F2 = 2*dbits-BI_FP; |
||
|
||
// Digit conversions |
||
var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz"; |
||
var BI_RC = new Array(); |
||
var rr,vv; |
||
rr = "0".charCodeAt(0); |
||
for(vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv; |
||
rr = "a".charCodeAt(0); |
||
for(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; |
||
rr = "A".charCodeAt(0); |
||
for(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; |
||
|
||
function int2char(n) { return BI_RM.charAt(n); } |
||
function intAt(s,i) { |
||
var c = BI_RC[s.charCodeAt(i)]; |
||
return (c==null)?-1:c; |
||
} |
||
|
||
// (protected) copy this to r |
||
function bnpCopyTo(r) { |
||
for(var i = this.t-1; i >= 0; --i) r[i] = this[i]; |
||
r.t = this.t; |
||
r.s = this.s; |
||
} |
||
|
||
// (protected) set from integer value x, -DV <= x < DV |
||
function bnpFromInt(x) { |
||
this.t = 1; |
||
this.s = (x<0)?-1:0; |
||
if(x > 0) this[0] = x; |
||
else if(x < -1) this[0] = x+this.DV; |
||
else this.t = 0; |
||
} |
||
|
||
// return bigint initialized to value |
||
function nbv(i) { var r = nbi(); r.fromInt(i); return r; } |
||
|
||
// (protected) set from string and radix |
||
function bnpFromString(s,b,signed) { |
||
var k; |
||
if(b == 16) k = 4; |
||
else if(b == 8) k = 3; |
||
else if(b == 256) k = 8; // byte array |
||
else if(b == 2) k = 1; |
||
else if(b == 32) k = 5; |
||
else if(b == 4) k = 2; |
||
else { this.fromRadix(s,b); return; } |
||
this.t = 0; |
||
this.s = 0; |
||
var i = s.length, mi = false, sh = 0; |
||
while(--i >= 0) { |
||
var x = (k==8)?s[i]&0xff:intAt(s,i); |
||
if(x < 0) { |
||
if(s.charAt(i) == "-") mi = true; |
||
continue; |
||
} |
||
mi = false; |
||
if(sh == 0) |
||
this[this.t++] = x; |
||
else if(sh+k > this.DB) { |
||
this[this.t-1] |= (x&((1<<(this.DB-sh))-1))<<sh; |
||
this[this.t++] = (x>>(this.DB-sh)); |
||
} |
||
else |
||
this[this.t-1] |= x<<sh; |
||
sh += k; |
||
if(sh >= this.DB) sh -= this.DB; |
||
} |
||
// Disabled due to '-' prefix in toString |
||
if(k == 8 && (s[0]&0x80) != 0 && signed) { |
||
this.s = -1; |
||
if(sh > 0) this[this.t-1] |= ((1<<(this.DB-sh))-1)<<sh; |
||
} |
||
this.clamp(); |
||
if(mi) BigInteger.ZERO.subTo(this,this); |
||
} |
||
|
||
// (protected) clamp off excess high words |
||
function bnpClamp() { |
||
var c = this.s&this.DM; |
||
while(this.t > 0 && this[this.t-1] == c) --this.t; |
||
} |
||
|
||
// (public) return string representation in given radix |
||
function bnToString(b) { |
||
if(this.s < 0) return "-"+this.negate().toString(b); |
||
var k; |
||
if(b == 16) k = 4; |
||
else if(b == 8) k = 3; |
||
else if(b == 2) k = 1; |
||
else if(b == 32) k = 5; |
||
else if(b == 4) k = 2; |
||
else return this.toRadix(b); |
||
var km = (1<<k)-1, d, m = false, r = "", i = this.t; |
||
var p = this.DB-(i*this.DB)%k; |
||
if(i-- > 0) { |
||
if(p < this.DB && (d = this[i]>>p) > 0) { m = true; r = int2char(d); } |
||
while(i >= 0) { |
||
if(p < k) { |
||
d = (this[i]&((1<<p)-1))<<(k-p); |
||
d |= this[--i]>>(p+=this.DB-k); |
||
} |
||
else { |
||
d = (this[i]>>(p-=k))&km; |
||
if(p <= 0) { p += this.DB; --i; } |
||
} |
||
if(d > 0) m = true; |
||
if(m) r += int2char(d); |
||
} |
||
} |
||
return m?r:"0"; |
||
} |
||
|
||
// (public) -this |
||
function bnNegate() { var r = nbi(); BigInteger.ZERO.subTo(this,r); return r; } |
||
|
||
// (public) |this| |
||
function bnAbs() { return (this.s<0)?this.negate():this; } |
||
|
||
// (public) return + if this > a, - if this < a, 0 if equal |
||
function bnCompareTo(a) { |
||
var r = this.s-a.s; |
||
if(r != 0) return r; |
||
var i = this.t; |
||
r = i-a.t; |
||
if(r != 0) return (this.s<0)?-r:r; |
||
while(--i >= 0) if((r=this[i]-a[i]) != 0) return r; |
||
return 0; |
||
} |
||
|
||
// returns bit length of the integer x |
||
function nbits(x) { |
||
var r = 1, t; |
||
if((t=x>>>16) != 0) { x = t; r += 16; } |
||
if((t=x>>8) != 0) { x = t; r += 8; } |
||
if((t=x>>4) != 0) { x = t; r += 4; } |
||
if((t=x>>2) != 0) { x = t; r += 2; } |
||
if((t=x>>1) != 0) { x = t; r += 1; } |
||
return r; |
||
} |
||
|
||
// (public) return the number of bits in "this" |
||
function bnBitLength() { |
||
if(this.t <= 0) return 0; |
||
return this.DB*(this.t-1)+nbits(this[this.t-1]^(this.s&this.DM)); |
||
} |
||
|
||
// (protected) r = this << n*DB |
||
function bnpDLShiftTo(n,r) { |
||
var i; |
||
for(i = this.t-1; i >= 0; --i) r[i+n] = this[i]; |
||
for(i = n-1; i >= 0; --i) r[i] = 0; |
||
r.t = this.t+n; |
||
r.s = this.s; |
||
} |
||
|
||
// (protected) r = this >> n*DB |
||
function bnpDRShiftTo(n,r) { |
||
for(var i = n; i < this.t; ++i) r[i-n] = this[i]; |
||
r.t = Math.max(this.t-n,0); |
||
r.s = this.s; |
||
} |
||
|
||
// (protected) r = this << n |
||
function bnpLShiftTo(n,r) { |
||
var bs = n%this.DB; |
||
var cbs = this.DB-bs; |
||
var bm = (1<<cbs)-1; |
||
var ds = Math.floor(n/this.DB), c = (this.s<<bs)&this.DM, i; |
||
for(i = this.t-1; i >= 0; --i) { |
||
r[i+ds+1] = (this[i]>>cbs)|c; |
||
c = (this[i]&bm)<<bs; |
||
} |
||
for(i = ds-1; i >= 0; --i) r[i] = 0; |
||
r[ds] = c; |
||
r.t = this.t+ds+1; |
||
r.s = this.s; |
||
r.clamp(); |
||
} |
||
|
||
// (protected) r = this >> n |
||
function bnpRShiftTo(n,r) { |
||
r.s = this.s; |
||
var ds = Math.floor(n/this.DB); |
||
if(ds >= this.t) { r.t = 0; return; } |
||
var bs = n%this.DB; |
||
var cbs = this.DB-bs; |
||
var bm = (1<<bs)-1; |
||
r[0] = this[ds]>>bs; |
||
for(var i = ds+1; i < this.t; ++i) { |
||
r[i-ds-1] |= (this[i]&bm)<<cbs; |
||
r[i-ds] = this[i]>>bs; |
||
} |
||
if(bs > 0) r[this.t-ds-1] |= (this.s&bm)<<cbs; |
||
r.t = this.t-ds; |
||
r.clamp(); |
||
} |
||
|
||
// (protected) r = this - a |
||
function bnpSubTo(a,r) { |
||
var i = 0, c = 0, m = Math.min(a.t,this.t); |
||
while(i < m) { |
||
c += this[i]-a[i]; |
||
r[i++] = c&this.DM; |
||
c >>= this.DB; |
||
} |
||
if(a.t < this.t) { |
||
c -= a.s; |
||
while(i < this.t) { |
||
c += this[i]; |
||
r[i++] = c&this.DM; |
||
c >>= this.DB; |
||
} |
||
c += this.s; |
||
} |
||
else { |
||
c += this.s; |
||
while(i < a.t) { |
||
c -= a[i]; |
||
r[i++] = c&this.DM; |
||
c >>= this.DB; |
||
} |
||
c -= a.s; |
||
} |
||
r.s = (c<0)?-1:0; |
||
if(c < -1) r[i++] = this.DV+c; |
||
else if(c > 0) r[i++] = c; |
||
r.t = i; |
||
r.clamp(); |
||
} |
||
|
||
// (protected) r = this * a, r != this,a (HAC 14.12) |
||
// "this" should be the larger one if appropriate. |
||
function bnpMultiplyTo(a,r) { |
||
var x = this.abs(), y = a.abs(); |
||
var i = x.t; |
||
r.t = i+y.t; |
||
while(--i >= 0) r[i] = 0; |
||
for(i = 0; i < y.t; ++i) r[i+x.t] = x.am(0,y[i],r,i,0,x.t); |
||
r.s = 0; |
||
r.clamp(); |
||
if(this.s != a.s) BigInteger.ZERO.subTo(r,r); |
||
} |
||
|
||
// (protected) r = this^2, r != this (HAC 14.16) |
||
function bnpSquareTo(r) { |
||
var x = this.abs(); |
||
var i = r.t = 2*x.t; |
||
while(--i >= 0) r[i] = 0; |
||
for(i = 0; i < x.t-1; ++i) { |
||
var c = x.am(i,x[i],r,2*i,0,1); |
||
if((r[i+x.t]+=x.am(i+1,2*x[i],r,2*i+1,c,x.t-i-1)) >= x.DV) { |
||
r[i+x.t] -= x.DV; |
||
r[i+x.t+1] = 1; |
||
} |
||
} |
||
if(r.t > 0) r[r.t-1] += x.am(i,x[i],r,2*i,0,1); |
||
r.s = 0; |
||
r.clamp(); |
||
} |
||
|
||
// (protected) divide this by m, quotient and remainder to q, r (HAC 14.20) |
||
// r != q, this != m. q or r may be null. |
||
function bnpDivRemTo(m,q,r) { |
||
var pm = m.abs(); |
||
if(pm.t <= 0) return; |
||
var pt = this.abs(); |
||
if(pt.t < pm.t) { |
||
if(q != null) q.fromInt(0); |
||
if(r != null) this.copyTo(r); |
||
return; |
||
} |
||
if(r == null) r = nbi(); |
||
var y = nbi(), ts = this.s, ms = m.s; |
||
var nsh = this.DB-nbits(pm[pm.t-1]); // normalize modulus |
||
if(nsh > 0) { pm.lShiftTo(nsh,y); pt.lShiftTo(nsh,r); } |
||
else { pm.copyTo(y); pt.copyTo(r); } |
||
var ys = y.t; |
||
var y0 = y[ys-1]; |
||
if(y0 == 0) return; |
||
var yt = y0*(1<<this.F1)+((ys>1)?y[ys-2]>>this.F2:0); |
||
var d1 = this.FV/yt, d2 = (1<<this.F1)/yt, e = 1<<this.F2; |
||
var i = r.t, j = i-ys, t = (q==null)?nbi():q; |
||
y.dlShiftTo(j,t); |
||
if(r.compareTo(t) >= 0) { |
||
r[r.t++] = 1; |
||
r.subTo(t,r); |
||
} |
||
BigInteger.ONE.dlShiftTo(ys,t); |
||
t.subTo(y,y); // "negative" y so we can replace sub with am later |
||
while(y.t < ys) y[y.t++] = 0; |
||
while(--j >= 0) { |
||
// Estimate quotient digit |
||
var qd = (r[--i]==y0)?this.DM:Math.floor(r[i]*d1+(r[i-1]+e)*d2); |
||
if((r[i]+=y.am(0,qd,r,j,0,ys)) < qd) { // Try it out |
||
y.dlShiftTo(j,t); |
||
r.subTo(t,r); |
||
while(r[i] < --qd) r.subTo(t,r); |
||
} |
||
} |
||
if(q != null) { |
||
r.drShiftTo(ys,q); |
||
if(ts != ms) BigInteger.ZERO.subTo(q,q); |
||
} |
||
r.t = ys; |
||
r.clamp(); |
||
if(nsh > 0) r.rShiftTo(nsh,r); // Denormalize remainder |
||
if(ts < 0) BigInteger.ZERO.subTo(r,r); |
||
} |
||
|
||
// (public) this mod a |
||
function bnMod(a) { |
||
var r = nbi(); |
||
this.abs().divRemTo(a,null,r); |
||
if(this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r,r); |
||
return r; |
||
} |
||
|
||
// Modular reduction using "classic" algorithm |
||
function Classic(m) { this.m = m; } |
||
function cConvert(x) { |
||
if(x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m); |
||
else return x; |
||
} |
||
function cRevert(x) { return x; } |
||
function cReduce(x) { x.divRemTo(this.m,null,x); } |
||
function cMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } |
||
function cSqrTo(x,r) { x.squareTo(r); this.reduce(r); } |
||
|
||
Classic.prototype.convert = cConvert; |
||
Classic.prototype.revert = cRevert; |
||
Classic.prototype.reduce = cReduce; |
||
Classic.prototype.mulTo = cMulTo; |
||
Classic.prototype.sqrTo = cSqrTo; |
||
|
||
// (protected) return "-1/this % 2^DB"; useful for Mont. reduction |
||
// justification: |
||
// xy == 1 (mod m) |
||
// xy = 1+km |
||
// xy(2-xy) = (1+km)(1-km) |
||
// x[y(2-xy)] = 1-k^2m^2 |
||
// x[y(2-xy)] == 1 (mod m^2) |
||
// if y is 1/x mod m, then y(2-xy) is 1/x mod m^2 |
||
// should reduce x and y(2-xy) by m^2 at each step to keep size bounded. |
||
// JS multiply "overflows" differently from C/C++, so care is needed here. |
||
function bnpInvDigit() { |
||
if(this.t < 1) return 0; |
||
var x = this[0]; |
||
if((x&1) == 0) return 0; |
||
var y = x&3; // y == 1/x mod 2^2 |
||
y = (y*(2-(x&0xf)*y))&0xf; // y == 1/x mod 2^4 |
||
y = (y*(2-(x&0xff)*y))&0xff; // y == 1/x mod 2^8 |
||
y = (y*(2-(((x&0xffff)*y)&0xffff)))&0xffff; // y == 1/x mod 2^16 |
||
// last step - calculate inverse mod DV directly; |
||
// assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints |
||
y = (y*(2-x*y%this.DV))%this.DV; // y == 1/x mod 2^dbits |
||
// we really want the negative inverse, and -DV < y < DV |
||
return (y>0)?this.DV-y:-y; |
||
} |
||
|
||
// Montgomery reduction |
||
function Montgomery(m) { |
||
this.m = m; |
||
this.mp = m.invDigit(); |
||
this.mpl = this.mp&0x7fff; |
||
this.mph = this.mp>>15; |
||
this.um = (1<<(m.DB-15))-1; |
||
this.mt2 = 2*m.t; |
||
} |
||
|
||
// xR mod m |
||
function montConvert(x) { |
||
var r = nbi(); |
||
x.abs().dlShiftTo(this.m.t,r); |
||
r.divRemTo(this.m,null,r); |
||
if(x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r,r); |
||
return r; |
||
} |
||
|
||
// x/R mod m |
||
function montRevert(x) { |
||
var r = nbi(); |
||
x.copyTo(r); |
||
this.reduce(r); |
||
return r; |
||
} |
||
|
||
// x = x/R mod m (HAC 14.32) |
||
function montReduce(x) { |
||
while(x.t <= this.mt2) // pad x so am has enough room later |
||
x[x.t++] = 0; |
||
for(var i = 0; i < this.m.t; ++i) { |
||
// faster way of calculating u0 = x[i]*mp mod DV |
||
var j = x[i]&0x7fff; |
||
var u0 = (j*this.mpl+(((j*this.mph+(x[i]>>15)*this.mpl)&this.um)<<15))&x.DM; |
||
// use am to combine the multiply-shift-add into one call |
||
j = i+this.m.t; |
||
x[j] += this.m.am(0,u0,x,i,0,this.m.t); |
||
// propagate carry |
||
while(x[j] >= x.DV) { x[j] -= x.DV; x[++j]++; } |
||
} |
||
x.clamp(); |
||
x.drShiftTo(this.m.t,x); |
||
if(x.compareTo(this.m) >= 0) x.subTo(this.m,x); |
||
} |
||
|
||
// r = "x^2/R mod m"; x != r |
||
function montSqrTo(x,r) { x.squareTo(r); this.reduce(r); } |
||
|
||
// r = "xy/R mod m"; x,y != r |
||
function montMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } |
||
|
||
Montgomery.prototype.convert = montConvert; |
||
Montgomery.prototype.revert = montRevert; |
||
Montgomery.prototype.reduce = montReduce; |
||
Montgomery.prototype.mulTo = montMulTo; |
||
Montgomery.prototype.sqrTo = montSqrTo; |
||
|
||
// (protected) true iff this is even |
||
function bnpIsEven() { return ((this.t>0)?(this[0]&1):this.s) == 0; } |
||
|
||
// (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79) |
||
function bnpExp(e,z) { |
||
if(e > 0xffffffff || e < 1) return BigInteger.ONE; |
||
var r = nbi(), r2 = nbi(), g = z.convert(this), i = nbits(e)-1; |
||
g.copyTo(r); |
||
while(--i >= 0) { |
||
z.sqrTo(r,r2); |
||
if((e&(1<<i)) > 0) z.mulTo(r2,g,r); |
||
else { var t = r; r = r2; r2 = t; } |
||
} |
||
return z.revert(r); |
||
} |
||
|
||
// (public) this^e % m, 0 <= e < 2^32 |
||
function bnModPowInt(e,m) { |
||
var z; |
||
if(e < 256 || m.isEven()) z = new Classic(m); else z = new Montgomery(m); |
||
return this.exp(e,z); |
||
} |
||
|
||
// protected |
||
BigInteger.prototype.copyTo = bnpCopyTo; |
||
BigInteger.prototype.fromInt = bnpFromInt; |
||
BigInteger.prototype.fromString = bnpFromString; |
||
BigInteger.prototype.clamp = bnpClamp; |
||
BigInteger.prototype.dlShiftTo = bnpDLShiftTo; |
||
BigInteger.prototype.drShiftTo = bnpDRShiftTo; |
||
BigInteger.prototype.lShiftTo = bnpLShiftTo; |
||
BigInteger.prototype.rShiftTo = bnpRShiftTo; |
||
BigInteger.prototype.subTo = bnpSubTo; |
||
BigInteger.prototype.multiplyTo = bnpMultiplyTo; |
||
BigInteger.prototype.squareTo = bnpSquareTo; |
||
BigInteger.prototype.divRemTo = bnpDivRemTo; |
||
BigInteger.prototype.invDigit = bnpInvDigit; |
||
BigInteger.prototype.isEven = bnpIsEven; |
||
BigInteger.prototype.exp = bnpExp; |
||
|
||
// public |
||
BigInteger.prototype.toString = bnToString; |
||
BigInteger.prototype.negate = bnNegate; |
||
BigInteger.prototype.abs = bnAbs; |
||
BigInteger.prototype.compareTo = bnCompareTo; |
||
BigInteger.prototype.bitLength = bnBitLength; |
||
BigInteger.prototype.mod = bnMod; |
||
BigInteger.prototype.modPowInt = bnModPowInt; |
||
|
||
// "constants" |
||
BigInteger.ZERO = nbv(0); |
||
BigInteger.ONE = nbv(1); |
||
|
||
|
||
|
||
// Copyright (c) 2005-2009 Tom Wu |
||
// All Rights Reserved. |
||
// See "LICENSE" for details. |
||
|
||
// Extended JavaScript BN functions, required for RSA private ops. |
||
|
||
// Version 1.1: new BigInteger("0", 10) returns "proper" zero |
||
// Version 1.2: square() API, isProbablePrime fix |
||
|
||
// (public) |
||
function bnClone() { var r = nbi(); this.copyTo(r); return r; } |
||
|
||
// (public) return value as integer |
||
function bnIntValue() { |
||
if(this.s < 0) { |
||
if(this.t == 1) return this[0]-this.DV; |
||
else if(this.t == 0) return -1; |
||
} |
||
else if(this.t == 1) return this[0]; |
||
else if(this.t == 0) return 0; |
||
// assumes 16 < DB < 32 |
||
return ((this[1]&((1<<(32-this.DB))-1))<<this.DB)|this[0]; |
||
} |
||
|
||
// (public) return value as byte |
||
function bnByteValue() { return (this.t==0)?this.s:(this[0]<<24)>>24; } |
||
|
||
// (public) return value as short (assumes DB>=16) |
||
function bnShortValue() { return (this.t==0)?this.s:(this[0]<<16)>>16; } |
||
|
||
// (protected) return x s.t. r^x < DV |
||
function bnpChunkSize(r) { return Math.floor(Math.LN2*this.DB/Math.log(r)); } |
||
|
||
// (public) 0 if this == 0, 1 if this > 0 |
||
function bnSigNum() { |
||
if(this.s < 0) return -1; |
||
else if(this.t <= 0 || (this.t == 1 && this[0] <= 0)) return 0; |
||
else return 1; |
||
} |
||
|
||
// (protected) convert to radix string |
||
function bnpToRadix(b) { |
||
if(b == null) b = 10; |
||
if(this.signum() == 0 || b < 2 || b > 36) return "0"; |
||
var cs = this.chunkSize(b); |
||
var a = Math.pow(b,cs); |
||
var d = nbv(a), y = nbi(), z = nbi(), r = ""; |
||
this.divRemTo(d,y,z); |
||
while(y.signum() > 0) { |
||
r = (a+z.intValue()).toString(b).substr(1) + r; |
||
y.divRemTo(d,y,z); |
||
} |
||
return z.intValue().toString(b) + r; |
||
} |
||
|
||
// (protected) convert from radix string |
||
function bnpFromRadix(s,b) { |
||
this.fromInt(0); |
||
if(b == null) b = 10; |
||
var cs = this.chunkSize(b); |
||
var d = Math.pow(b,cs), mi = false, j = 0, w = 0; |
||
for(var i = 0; i < s.length; ++i) { |
||
var x = intAt(s,i); |
||
if(x < 0) { |
||
if(s.charAt(i) == "-" && this.signum() == 0) mi = true; |
||
continue; |
||
} |
||
w = b*w+x; |
||
if(++j >= cs) { |
||
this.dMultiply(d); |
||
this.dAddOffset(w,0); |
||
j = 0; |
||
w = 0; |
||
} |
||
} |
||
if(j > 0) { |
||
this.dMultiply(Math.pow(b,j)); |
||
this.dAddOffset(w,0); |
||
} |
||
if(mi) BigInteger.ZERO.subTo(this,this); |
||
} |
||
|
||
// (protected) alternate constructor |
||
function bnpFromNumber(a,b,c) { |
||
if("number" == typeof b) { |
||
// new BigInteger(int,int,RNG) |
||
if(a < 2) this.fromInt(1); |
||
else { |
||
this.fromNumber(a,c); |
||
if(!this.testBit(a-1)) // force MSB set |
||
this.bitwiseTo(BigInteger.ONE.shiftLeft(a-1),op_or,this); |
||
if(this.isEven()) this.dAddOffset(1,0); // force odd |
||
while(!this.isProbablePrime(b)) { |
||
this.dAddOffset(2,0); |
||
if(this.bitLength() > a) this.subTo(BigInteger.ONE.shiftLeft(a-1),this); |
||
} |
||
} |
||
} |
||
else { |
||
// new BigInteger(int,RNG) |
||
var x = new Array(), t = a&7; |
||
x.length = (a>>3)+1; |
||
b.nextBytes(x); |
||
if(t > 0) x[0] &= ((1<<t)-1); else x[0] = 0; |
||
this.fromString(x,256); |
||
} |
||
} |
||
|
||
// (public) convert to bigendian byte array |
||
function bnToByteArray(signed) { |
||
var i = this.t, r = new Array(); |
||
r[0] = this.s; |
||
var p = this.DB-(i*this.DB)%8, d, k = 0; |
||
if(i-- > 0) { |
||
if(p < this.DB && (d = this[i]>>p) != (this.s&this.DM)>>p) |
||
r[k++] = d|(this.s<<(this.DB-p)); |
||
while(i >= 0) { |
||
if(p < 8) { |
||
d = (this[i]&((1<<p)-1))<<(8-p); |
||
d |= this[--i]>>(p+=this.DB-8); |
||
} |
||
else { |
||
d = (this[i]>>(p-=8))&0xff; |
||
if(p <= 0) { p += this.DB; --i; } |
||
} |
||
if(signed && (d&0x80) != 0) d |= -256; |
||
if(k == 0 && (this.s&0x80) != (d&0x80)) ++k; |
||
if(k > 0 || d != this.s) r[k++] = d; |
||
} |
||
} |
||
return r; |
||
} |
||
|
||
function bnEquals(a) { return(this.compareTo(a)==0); } |
||
function bnMin(a) { return(this.compareTo(a)<0)?this:a; } |
||
function bnMax(a) { return(this.compareTo(a)>0)?this:a; } |
||
|
||
// (protected) r = this op a (bitwise) |
||
function bnpBitwiseTo(a,op,r) { |
||
var i, f, m = Math.min(a.t,this.t); |
||
for(i = 0; i < m; ++i) r[i] = op(this[i],a[i]); |
||
if(a.t < this.t) { |
||
f = a.s&this.DM; |
||
for(i = m; i < this.t; ++i) r[i] = op(this[i],f); |
||
r.t = this.t; |
||
} |
||
else { |
||
f = this.s&this.DM; |
||
for(i = m; i < a.t; ++i) r[i] = op(f,a[i]); |
||
r.t = a.t; |
||
} |
||
r.s = op(this.s,a.s); |
||
r.clamp(); |
||
} |
||
|
||
// (public) this & a |
||
function op_and(x,y) { return x&y; } |
||
function bnAnd(a) { var r = nbi(); this.bitwiseTo(a,op_and,r); return r; } |
||
|
||
// (public) this | a |
||
function op_or(x,y) { return x|y; } |
||
function bnOr(a) { var r = nbi(); this.bitwiseTo(a,op_or,r); return r; } |
||
|
||
// (public) this ^ a |
||
function op_xor(x,y) { return x^y; } |
||
function bnXor(a) { var r = nbi(); this.bitwiseTo(a,op_xor,r); return r; } |
||
|
||
// (public) this & ~a |
||
function op_andnot(x,y) { return x&~y; } |
||
function bnAndNot(a) { var r = nbi(); this.bitwiseTo(a,op_andnot,r); return r; } |
||
|
||
// (public) ~this |
||
function bnNot() { |
||
var r = nbi(); |
||
for(var i = 0; i < this.t; ++i) r[i] = this.DM&~this[i]; |
||
r.t = this.t; |
||
r.s = ~this.s; |
||
return r; |
||
} |
||
|
||
// (public) this << n |
||
function bnShiftLeft(n) { |
||
var r = nbi(); |
||
if(n < 0) this.rShiftTo(-n,r); else this.lShiftTo(n,r); |
||
return r; |
||
} |
||
|
||
// (public) this >> n |
||
function bnShiftRight(n) { |
||
var r = nbi(); |
||
if(n < 0) this.lShiftTo(-n,r); else this.rShiftTo(n,r); |
||
return r; |
||
} |
||
|
||
// return index of lowest 1-bit in x, x < 2^31 |
||
function lbit(x) { |
||
if(x == 0) return -1; |
||
var r = 0; |
||
if((x&0xffff) == 0) { x >>= 16; r += 16; } |
||
if((x&0xff) == 0) { x >>= 8; r += 8; } |
||
if((x&0xf) == 0) { x >>= 4; r += 4; } |
||
if((x&3) == 0) { x >>= 2; r += 2; } |
||
if((x&1) == 0) ++r; |
||
return r; |
||
} |
||
|
||
// (public) returns index of lowest 1-bit (or -1 if none) |
||
function bnGetLowestSetBit() { |
||
for(var i = 0; i < this.t; ++i) |
||
if(this[i] != 0) return i*this.DB+lbit(this[i]); |
||
if(this.s < 0) return this.t*this.DB; |
||
return -1; |
||
} |
||
|
||
// return number of 1 bits in x |
||
function cbit(x) { |
||
var r = 0; |
||
while(x != 0) { x &= x-1; ++r; } |
||
return r; |
||
} |
||
|
||
// (public) return number of set bits |
||
function bnBitCount() { |
||
var r = 0, x = this.s&this.DM; |
||
for(var i = 0; i < this.t; ++i) r += cbit(this[i]^x); |
||
return r; |
||
} |
||
|
||
// (public) true iff nth bit is set |
||
function bnTestBit(n) { |
||
var j = Math.floor(n/this.DB); |
||
if(j >= this.t) return(this.s!=0); |
||
return((this[j]&(1<<(n%this.DB)))!=0); |
||
} |
||
|
||
// (protected) this op (1<<n) |
||
function bnpChangeBit(n,op) { |
||
var r = BigInteger.ONE.shiftLeft(n); |
||
this.bitwiseTo(r,op,r); |
||
return r; |
||
} |
||
|
||
// (public) this | (1<<n) |
||
function bnSetBit(n) { return this.changeBit(n,op_or); } |
||
|
||
// (public) this & ~(1<<n) |
||
function bnClearBit(n) { return this.changeBit(n,op_andnot); } |
||
|
||
// (public) this ^ (1<<n) |
||
function bnFlipBit(n) { return this.changeBit(n,op_xor); } |
||
|
||
// (protected) r = this + a |
||
function bnpAddTo(a,r) { |
||
var i = 0, c = 0, m = Math.min(a.t,this.t); |
||
while(i < m) { |
||
c += this[i]+a[i]; |
||
r[i++] = c&this.DM; |
||
c >>= this.DB; |
||
} |
||
if(a.t < this.t) { |
||
c += a.s; |
||
while(i < this.t) { |
||
c += this[i]; |
||
r[i++] = c&this.DM; |
||
c >>= this.DB; |
||
} |
||
c += this.s; |
||
} |
||
else { |
||
c += this.s; |
||
while(i < a.t) { |
||
c += a[i]; |
||
r[i++] = c&this.DM; |
||
c >>= this.DB; |
||
} |
||
c += a.s; |
||
} |
||
r.s = (c<0)?-1:0; |
||
if(c > 0) r[i++] = c; |
||
else if(c < -1) r[i++] = this.DV+c; |
||
r.t = i; |
||
r.clamp(); |
||
} |
||
|
||
// (public) this + a |
||
function bnAdd(a) { var r = nbi(); this.addTo(a,r); return r; } |
||
|
||
// (public) this - a |
||
function bnSubtract(a) { var r = nbi(); this.subTo(a,r); return r; } |
||
|
||
// (public) this * a |
||
function bnMultiply(a) { var r = nbi(); this.multiplyTo(a,r); return r; } |
||
|
||
// (public) this^2 |
||
function bnSquare() { var r = nbi(); this.squareTo(r); return r; } |
||
|
||
// (public) this / a |
||
function bnDivide(a) { var r = nbi(); this.divRemTo(a,r,null); return r; } |
||
|
||
// (public) this % a |
||
function bnRemainder(a) { var r = nbi(); this.divRemTo(a,null,r); return r; } |
||
|
||
// (public) [this/a,this%a] |
||
function bnDivideAndRemainder(a) { |
||
var q = nbi(), r = nbi(); |
||
this.divRemTo(a,q,r); |
||
return new Array(q,r); |
||
} |
||
|
||
// (protected) this *= n, this >= 0, 1 < n < DV |
||
function bnpDMultiply(n) { |
||
this[this.t] = this.am(0,n-1,this,0,0,this.t); |
||
++this.t; |
||
this.clamp(); |
||
} |
||
|
||
// (protected) this += n << w words, this >= 0 |
||
function bnpDAddOffset(n,w) { |
||
if(n == 0) return; |
||
while(this.t <= w) this[this.t++] = 0; |
||
this[w] += n; |
||
while(this[w] >= this.DV) { |
||
this[w] -= this.DV; |
||
if(++w >= this.t) this[this.t++] = 0; |
||
++this[w]; |
||
} |
||
} |
||
|
||
// A "null" reducer |
||
function NullExp() {} |
||
function nNop(x) { return x; } |
||
function nMulTo(x,y,r) { x.multiplyTo(y,r); } |
||
function nSqrTo(x,r) { x.squareTo(r); } |
||
|
||
NullExp.prototype.convert = nNop; |
||
NullExp.prototype.revert = nNop; |
||
NullExp.prototype.mulTo = nMulTo; |
||
NullExp.prototype.sqrTo = nSqrTo; |
||
|
||
// (public) this^e |
||
function bnPow(e) { return this.exp(e,new NullExp()); } |
||
|
||
// (protected) r = lower n words of "this * a", a.t <= n |
||
// "this" should be the larger one if appropriate. |
||
function bnpMultiplyLowerTo(a,n,r) { |
||
var i = Math.min(this.t+a.t,n); |
||
r.s = 0; // assumes a,this >= 0 |
||
r.t = i; |
||
while(i > 0) r[--i] = 0; |
||
var j; |
||
for(j = r.t-this.t; i < j; ++i) r[i+this.t] = this.am(0,a[i],r,i,0,this.t); |
||
for(j = Math.min(a.t,n); i < j; ++i) this.am(0,a[i],r,i,0,n-i); |
||
r.clamp(); |
||
} |
||
|
||
// (protected) r = "this * a" without lower n words, n > 0 |
||
// "this" should be the larger one if appropriate. |
||
function bnpMultiplyUpperTo(a,n,r) { |
||
--n; |
||
var i = r.t = this.t+a.t-n; |
||
r.s = 0; // assumes a,this >= 0 |
||
while(--i >= 0) r[i] = 0; |
||
for(i = Math.max(n-this.t,0); i < a.t; ++i) |
||
r[this.t+i-n] = this.am(n-i,a[i],r,0,0,this.t+i-n); |
||
r.clamp(); |
||
r.drShiftTo(1,r); |
||
} |
||
|
||
// Barrett modular reduction |
||
function Barrett(m) { |
||
// setup Barrett |
||
this.r2 = nbi(); |
||
this.q3 = nbi(); |
||
BigInteger.ONE.dlShiftTo(2*m.t,this.r2); |
||
this.mu = this.r2.divide(m); |
||
this.m = m; |
||
} |
||
|
||
function barrettConvert(x) { |
||
if(x.s < 0 || x.t > 2*this.m.t) return x.mod(this.m); |
||
else if(x.compareTo(this.m) < 0) return x; |
||
else { var r = nbi(); x.copyTo(r); this.reduce(r); return r; } |
||
} |
||
|
||
function barrettRevert(x) { return x; } |
||
|
||
// x = x mod m (HAC 14.42) |
||
function barrettReduce(x) { |
||
x.drShiftTo(this.m.t-1,this.r2); |
||
if(x.t > this.m.t+1) { x.t = this.m.t+1; x.clamp(); } |
||
this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3); |
||
this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2); |
||
while(x.compareTo(this.r2) < 0) x.dAddOffset(1,this.m.t+1); |
||
x.subTo(this.r2,x); |
||
while(x.compareTo(this.m) >= 0) x.subTo(this.m,x); |
||
} |
||
|
||
// r = x^2 mod m; x != r |
||
function barrettSqrTo(x,r) { x.squareTo(r); this.reduce(r); } |
||
|
||
// r = x*y mod m; x,y != r |
||
function barrettMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } |
||
|
||
Barrett.prototype.convert = barrettConvert; |
||
Barrett.prototype.revert = barrettRevert; |
||
Barrett.prototype.reduce = barrettReduce; |
||
Barrett.prototype.mulTo = barrettMulTo; |
||
Barrett.prototype.sqrTo = barrettSqrTo; |
||
|
||
// (public) this^e % m (HAC 14.85) |
||
function bnModPow(e,m) { |
||
var i = e.bitLength(), k, r = nbv(1), z; |
||
if(i <= 0) return r; |
||
else if(i < 18) k = 1; |
||
else if(i < 48) k = 3; |
||
else if(i < 144) k = 4; |
||
else if(i < 768) k = 5; |
||
else k = 6; |
||
if(i < 8) |
||
z = new Classic(m); |
||
else if(m.isEven()) |
||
z = new Barrett(m); |
||
else |
||
z = new Montgomery(m); |
||
|
||
// precomputation |
||
var g = new Array(), n = 3, k1 = k-1, km = (1<<k)-1; |
||
g[1] = z.convert(this); |
||
if(k > 1) { |
||
var g2 = nbi(); |
||
z.sqrTo(g[1],g2); |
||
while(n <= km) { |
||
g[n] = nbi(); |
||
z.mulTo(g2,g[n-2],g[n]); |
||
n += 2; |
||
} |
||
} |
||
|
||
var j = e.t-1, w, is1 = true, r2 = nbi(), t; |
||
i = nbits(e[j])-1; |
||
while(j >= 0) { |
||
if(i >= k1) w = (e[j]>>(i-k1))&km; |
||
else { |
||
w = (e[j]&((1<<(i+1))-1))<<(k1-i); |
||
if(j > 0) w |= e[j-1]>>(this.DB+i-k1); |
||
} |
||
|
||
n = k; |
||
while((w&1) == 0) { w >>= 1; --n; } |
||
if((i -= n) < 0) { i += this.DB; --j; } |
||
if(is1) { // ret == 1, don't bother squaring or multiplying it |
||
g[w].copyTo(r); |
||
is1 = false; |
||
} |
||
else { |
||
while(n > 1) { z.sqrTo(r,r2); z.sqrTo(r2,r); n -= 2; } |
||
if(n > 0) z.sqrTo(r,r2); else { t = r; r = r2; r2 = t; } |
||
z.mulTo(r2,g[w],r); |
||
} |
||
|
||
while(j >= 0 && (e[j]&(1<<i)) == 0) { |
||
z.sqrTo(r,r2); t = r; r = r2; r2 = t; |
||
if(--i < 0) { i = this.DB-1; --j; } |
||
} |
||
} |
||
return z.revert(r); |
||
} |
||
|
||
// (public) gcd(this,a) (HAC 14.54) |
||
function bnGCD(a) { |
||
var x = (this.s<0)?this.negate():this.clone(); |
||
var y = (a.s<0)?a.negate():a.clone(); |
||
if(x.compareTo(y) < 0) { var t = x; x = y; y = t; } |
||
var i = x.getLowestSetBit(), g = y.getLowestSetBit(); |
||
if(g < 0) return x; |
||
if(i < g) g = i; |
||
if(g > 0) { |
||
x.rShiftTo(g,x); |
||
y.rShiftTo(g,y); |
||
} |
||
while(x.signum() > 0) { |
||
if((i = x.getLowestSetBit()) > 0) x.rShiftTo(i,x); |
||
if((i = y.getLowestSetBit()) > 0) y.rShiftTo(i,y); |
||
if(x.compareTo(y) >= 0) { |
||
x.subTo(y,x); |
||
x.rShiftTo(1,x); |
||
} |
||
else { |
||
y.subTo(x,y); |
||
y.rShiftTo(1,y); |
||
} |
||
} |
||
if(g > 0) y.lShiftTo(g,y); |
||
return y; |
||
} |
||
|
||
// (protected) this % n, n < 2^26 |
||
function bnpModInt(n) { |
||
if(n <= 0) return 0; |
||
var d = this.DV%n, r = (this.s<0)?n-1:0; |
||
if(this.t > 0) |
||
if(d == 0) r = this[0]%n; |
||
else for(var i = this.t-1; i >= 0; --i) r = (d*r+this[i])%n; |
||
return r; |
||
} |
||
|
||
// (public) 1/this % m (HAC 14.61) |
||
function bnModInverse(m) { |
||
var ac = m.isEven(); |
||
if((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO; |
||
var u = m.clone(), v = this.clone(); |
||
var a = nbv(1), b = nbv(0), c = nbv(0), d = nbv(1); |
||
while(u.signum() != 0) { |
||
while(u.isEven()) { |
||
u.rShiftTo(1,u); |
||
if(ac) { |
||
if(!a.isEven() || !b.isEven()) { a.addTo(this,a); b.subTo(m,b); } |
||
a.rShiftTo(1,a); |
||
} |
||
else if(!b.isEven()) b.subTo(m,b); |
||
b.rShiftTo(1,b); |
||
} |
||
while(v.isEven()) { |
||
v.rShiftTo(1,v); |
||
if(ac) { |
||
if(!c.isEven() || !d.isEven()) { c.addTo(this,c); d.subTo(m,d); } |
||
c.rShiftTo(1,c); |
||
} |
||
else if(!d.isEven()) d.subTo(m,d); |
||
d.rShiftTo(1,d); |
||
} |
||
if(u.compareTo(v) >= 0) { |
||
u.subTo(v,u); |
||
if(ac) a.subTo(c,a); |
||
b.subTo(d,b); |
||
} |
||
else { |
||
v.subTo(u,v); |
||
if(ac) c.subTo(a,c); |
||
d.subTo(b,d); |
||
} |
||
} |
||
if(v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO; |
||
if(d.compareTo(m) >= 0) return d.subtract(m); |
||
if(d.signum() < 0) d.addTo(m,d); else return d; |
||
if(d.signum() < 0) return d.add(m); else return d; |
||
} |
||
|
||
var lowprimes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997]; |
||
var lplim = (1<<26)/lowprimes[lowprimes.length-1]; |
||
|
||
// (public) test primality with certainty >= 1-.5^t |
||
function bnIsProbablePrime(t) { |
||
var i, x = this.abs(); |
||
if(x.t == 1 && x[0] <= lowprimes[lowprimes.length-1]) { |
||
for(i = 0; i < lowprimes.length; ++i) |
||
if(x[0] == lowprimes[i]) return true; |
||
return false; |
||
} |
||
if(x.isEven()) return false; |
||
i = 1; |
||
while(i < lowprimes.length) { |
||
var m = lowprimes[i], j = i+1; |
||
while(j < lowprimes.length && m < lplim) m *= lowprimes[j++]; |
||
m = x.modInt(m); |
||
while(i < j) if(m%lowprimes[i++] == 0) return false; |
||
} |
||
return x.millerRabin(t); |
||
} |
||
|
||
// (protected) true if probably prime (HAC 4.24, Miller-Rabin) |
||
function bnpMillerRabin(t) { |
||
var n1 = this.subtract(BigInteger.ONE); |
||
var k = n1.getLowestSetBit(); |
||
if(k <= 0) return false; |
||
var r = n1.shiftRight(k); |
||
t = (t+1)>>1; |
||
if(t > lowprimes.length) t = lowprimes.length; |
||
var a = nbi(); |
||
for(var i = 0; i < t; ++i) { |
||
//Pick bases at random, instead of starting at 2 |
||
a.fromInt(lowprimes[Math.floor(Math.random()*lowprimes.length)]); |
||
var y = a.modPow(r,this); |
||
if(y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) { |
||
var j = 1; |
||
while(j++ < k && y.compareTo(n1) != 0) { |
||
y = y.modPowInt(2,this); |
||
if(y.compareTo(BigInteger.ONE) == 0) return false; |
||
} |
||
if(y.compareTo(n1) != 0) return false; |
||
} |
||
} |
||
return true; |
||
} |
||
|
||
// protected |
||
BigInteger.prototype.chunkSize = bnpChunkSize; |
||
BigInteger.prototype.toRadix = bnpToRadix; |
||
BigInteger.prototype.fromRadix = bnpFromRadix; |
||
BigInteger.prototype.fromNumber = bnpFromNumber; |
||
BigInteger.prototype.bitwiseTo = bnpBitwiseTo; |
||
BigInteger.prototype.changeBit = bnpChangeBit; |
||
BigInteger.prototype.addTo = bnpAddTo; |
||
BigInteger.prototype.dMultiply = bnpDMultiply; |
||
BigInteger.prototype.dAddOffset = bnpDAddOffset; |
||
BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo; |
||
BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo; |
||
BigInteger.prototype.modInt = bnpModInt; |
||
BigInteger.prototype.millerRabin = bnpMillerRabin; |
||
|
||
// public |
||
BigInteger.prototype.clone = bnClone; |
||
BigInteger.prototype.intValue = bnIntValue; |
||
BigInteger.prototype.byteValue = bnByteValue; |
||
BigInteger.prototype.shortValue = bnShortValue; |
||
BigInteger.prototype.signum = bnSigNum; |
||
BigInteger.prototype.toByteArray = bnToByteArray; |
||
BigInteger.prototype.equals = bnEquals; |
||
BigInteger.prototype.min = bnMin; |
||
BigInteger.prototype.max = bnMax; |
||
BigInteger.prototype.and = bnAnd; |
||
BigInteger.prototype.or = bnOr; |
||
BigInteger.prototype.xor = bnXor; |
||
BigInteger.prototype.andNot = bnAndNot; |
||
BigInteger.prototype.not = bnNot; |
||
BigInteger.prototype.shiftLeft = bnShiftLeft; |
||
BigInteger.prototype.shiftRight = bnShiftRight; |
||
BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit; |
||
BigInteger.prototype.bitCount = bnBitCount; |
||
BigInteger.prototype.testBit = bnTestBit; |
||
BigInteger.prototype.setBit = bnSetBit; |
||
BigInteger.prototype.clearBit = bnClearBit; |
||
BigInteger.prototype.flipBit = bnFlipBit; |
||
BigInteger.prototype.add = bnAdd; |
||
BigInteger.prototype.subtract = bnSubtract; |
||
BigInteger.prototype.multiply = bnMultiply; |
||
BigInteger.prototype.divide = bnDivide; |
||
BigInteger.prototype.remainder = bnRemainder; |
||
BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder; |
||
BigInteger.prototype.modPow = bnModPow; |
||
BigInteger.prototype.modInverse = bnModInverse; |
||
BigInteger.prototype.pow = bnPow; |
||
BigInteger.prototype.gcd = bnGCD; |
||
BigInteger.prototype.isProbablePrime = bnIsProbablePrime; |
||
|
||
// JSBN-specific extension |
||
BigInteger.prototype.square = bnSquare; |
||
|
||
// BigInteger interfaces not implemented in jsbn: |
||
|
||
// BigInteger(int signum, byte[] magnitude) |
||
// double doubleValue() |
||
// float floatValue() |
||
// int hashCode() |
||
// long longValue() |
||
// static BigInteger valueOf(long val) |
||
|
||
|
||
|
||
|
||
|
||
// Random number generator - requires a PRNG backend, e.g. prng4.js |
||
|
||
// For best results, put code like |
||
// <body onClick='rng_seed_time();' onKeyPress='rng_seed_time();'> |
||
// in your main HTML document. |
||
|
||
var rng_state; |
||
var rng_pool; |
||
var rng_pptr; |
||
|
||
// Mix in a 32-bit integer into the pool |
||
function rng_seed_int(x) { |
||
rng_pool[rng_pptr++] ^= x & 255; |
||
rng_pool[rng_pptr++] ^= (x >> 8) & 255; |
||
rng_pool[rng_pptr++] ^= (x >> 16) & 255; |
||
rng_pool[rng_pptr++] ^= (x >> 24) & 255; |
||
if(rng_pptr >= rng_psize) rng_pptr -= rng_psize; |
||
} |
||
|
||
// Mix in the current time (w/milliseconds) into the pool |
||
function rng_seed_time() { |
||
rng_seed_int(new Date().getTime()); |
||
} |
||
|
||
// Initialize the pool with junk if needed. |
||
if(rng_pool == null) { |
||
rng_pool = new Array(); |
||
rng_pptr = 0; |
||
var global = typeof window !== 'undefined' ? window : this; |
||
var t; |
||
if (global && global.crypto && global.crypto.getRandomValues) { |
||
// Use webcrypto if available |
||
var ua = new Uint8Array(32); |
||
global.crypto.getRandomValues(ua); |
||
for(t = 0; t < 32; ++t) |
||
rng_pool[rng_pptr++] = ua[t]; |
||
} |
||
if(navigator.appName == "Netscape" && navigator.appVersion < "5" && global && global.crypto) { |
||
// Extract entropy (256 bits) from NS4 RNG if available |
||
var z = global.crypto.random(32); |
||
for(t = 0; t < z.length; ++t) |
||
rng_pool[rng_pptr++] = z.charCodeAt(t) & 255; |
||
} |
||
while(rng_pptr < rng_psize) { // extract some randomness from Math.random() |
||
t = Math.floor(65536 * Math.random()); |
||
rng_pool[rng_pptr++] = t >>> 8; |
||
rng_pool[rng_pptr++] = t & 255; |
||
} |
||
rng_pptr = 0; |
||
rng_seed_time(); |
||
//rng_seed_int(window.screenX); |
||
//rng_seed_int(window.screenY); |
||
} |
||
|
||
function rng_get_byte() { |
||
if(rng_state == null) { |
||
rng_seed_time(); |
||
rng_state = prng_newstate(); |
||
rng_state.init(rng_pool); |
||
for(rng_pptr = 0; rng_pptr < rng_pool.length; ++rng_pptr) |
||
rng_pool[rng_pptr] = 0; |
||
rng_pptr = 0; |
||
//rng_pool = null; |
||
} |
||
// TODO: allow reseeding after first request |
||
return rng_state.next(); |
||
} |
||
|
||
function rng_get_bytes(ba) { |
||
var i; |
||
for(i = 0; i < ba.length; ++i) ba[i] = rng_get_byte(); |
||
} |
||
|
||
function SecureRandom() {} |
||
|
||
SecureRandom.prototype.nextBytes = rng_get_bytes; |
||
|
||
|
||
|
||
// prng4.js - uses Arcfour as a PRNG |
||
|
||
function Arcfour() { |
||
this.i = 0; |
||
this.j = 0; |
||
this.S = new Array(); |
||
} |
||
|
||
// Initialize arcfour context from key, an array of ints, each from [0..255] |
||
function ARC4init(key) { |
||
var i, j, t; |
||
for(i = 0; i < 256; ++i) |
||
this.S[i] = i; |
||
j = 0; |
||
for(i = 0; i < 256; ++i) { |
||
j = (j + this.S[i] + key[i % key.length]) & 255; |
||
t = this.S[i]; |
||
this.S[i] = this.S[j]; |
||
this.S[j] = t; |
||
} |
||
this.i = 0; |
||
this.j = 0; |
||
} |
||
|
||
function ARC4next() { |
||
var t; |
||
this.i = (this.i + 1) & 255; |
||
this.j = (this.j + this.S[this.i]) & 255; |
||
t = this.S[this.i]; |
||
this.S[this.i] = this.S[this.j]; |
||
this.S[this.j] = t; |
||
return this.S[(t + this.S[this.i]) & 255]; |
||
} |
||
|
||
Arcfour.prototype.init = ARC4init; |
||
Arcfour.prototype.next = ARC4next; |
||
|
||
// Plug in your RNG constructor here |
||
function prng_newstate() { |
||
return new Arcfour(); |
||
} |
||
|
||
// Pool size must be a multiple of 4 and greater than 32. |
||
// An array of bytes the size of the pool will be passed to init() |
||
var rng_psize = 256; |
||
|
||
/* |
||
CryptoJS v3.1.2 |
||
code.google.com/p/crypto-js |
||
(c) 2009-2013 by Jeff Mott. All rights reserved. |
||
code.google.com/p/crypto-js/wiki/License |
||
*/ |
||
/** |
||
* CryptoJS core components. |
||
*/ |
||
var CryptoJS = CryptoJS || (function (Math, undefined) { |
||
/** |
||
* CryptoJS namespace. |
||
*/ |
||
var C = {}; |
||
|
||
/** |
||
* Library namespace. |
||
*/ |
||
var C_lib = C.lib = {}; |
||
|
||
/** |
||
* Base object for prototypal inheritance. |
||
*/ |
||
var Base = C_lib.Base = (function () { |
||
function F() {} |
||
|
||
return { |
||
/** |
||
* Creates a new object that inherits from this object. |
||
* |
||
* @param {Object} overrides Properties to copy into the new object. |
||
* |
||
* @return {Object} The new object. |
||
* |
||
* @static |
||
* |
||
* @example |
||
* |
||
* var MyType = CryptoJS.lib.Base.extend({ |
||
* field: 'value', |
||
* |
||
* method: function () { |
||
* } |
||
* }); |
||
*/ |
||
extend: function (overrides) { |
||
// Spawn |
||
F.prototype = this; |
||
var subtype = new F(); |
||
|
||
// Augment |
||
if (overrides) { |
||
subtype.mixIn(overrides); |
||
} |
||
|
||
// Create default initializer |
||
if (!subtype.hasOwnProperty('init')) { |
||
subtype.init = function () { |
||
subtype.$super.init.apply(this, arguments); |
||
}; |
||
} |
||
|
||
// Initializer's prototype is the subtype object |
||
subtype.init.prototype = subtype; |
||
|
||
// Reference supertype |
||
subtype.$super = this; |
||
|
||
return subtype; |
||
}, |
||
|
||
/** |
||
* Extends this object and runs the init method. |
||
* Arguments to create() will be passed to init(). |
||
* |
||
* @return {Object} The new object. |
||
* |
||
* @static |
||
* |
||
* @example |
||
* |
||
* var instance = MyType.create(); |
||
*/ |
||
create: function () { |
||
var instance = this.extend(); |
||
instance.init.apply(instance, arguments); |
||
|
||
return instance; |
||
}, |
||
|
||
/** |
||
* Initializes a newly created object. |
||
* Override this method to add some logic when your objects are created. |
||
* |
||
* @example |
||
* |
||
* var MyType = CryptoJS.lib.Base.extend({ |
||
* init: function () { |
||
* // ... |
||
* } |
||
* }); |
||
*/ |
||
init: function () { |
||
}, |
||
|
||
/** |
||
* Copies properties into this object. |
||
* |
||
* @param {Object} properties The properties to mix in. |
||
* |
||
* @example |
||
* |
||
* MyType.mixIn({ |
||
* field: 'value' |
||
* }); |
||
*/ |
||
mixIn: function (properties) { |
||
for (var propertyName in properties) { |
||
if (properties.hasOwnProperty(propertyName)) { |
||
this[propertyName] = properties[propertyName]; |
||
} |
||
} |
||
|
||
// IE won't copy toString using the loop above |
||
if (properties.hasOwnProperty('toString')) { |
||
this.toString = properties.toString; |
||
} |
||
}, |
||
|
||
/** |
||
* Creates a copy of this object. |
||
* |
||
* @return {Object} The clone. |
||
* |
||
* @example |
||
* |
||
* var clone = instance.clone(); |
||
*/ |
||
clone: function () { |
||
return this.init.prototype.extend(this); |
||
} |
||
}; |
||
}()); |
||
|
||
/** |
||
* An array of 32-bit words. |
||
* |
||
* @property {Array} words The array of 32-bit words. |
||
* @property {number} sigBytes The number of significant bytes in this word array. |
||
*/ |
||
var WordArray = C_lib.WordArray = Base.extend({ |
||
/** |
||
* Initializes a newly created word array. |
||
* |
||
* @param {Array} words (Optional) An array of 32-bit words. |
||
* @param {number} sigBytes (Optional) The number of significant bytes in the words. |
||
* |
||
* @example |
||
* |
||
* var wordArray = CryptoJS.lib.WordArray.create(); |
||
* var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]); |
||
* var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6); |
||
*/ |
||
init: function (words, sigBytes) { |
||
words = this.words = words || []; |
||
|
||
if (sigBytes != undefined) { |
||
this.sigBytes = sigBytes; |
||
} else { |
||
this.sigBytes = words.length * 4; |
||
} |
||
}, |
||
|
||
/** |
||
* Converts this word array to a string. |
||
* |
||
* @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex |
||
* |
||
* @return {string} The stringified word array. |
||
* |
||
* @example |
||
* |
||
* var string = wordArray + ''; |
||
* var string = wordArray.toString(); |
||
* var string = wordArray.toString(CryptoJS.enc.Utf8); |
||
*/ |
||
toString: function (encoder) { |
||
return (encoder || Hex).stringify(this); |
||
}, |
||
|
||
/** |
||
* Concatenates a word array to this word array. |
||
* |
||
* @param {WordArray} wordArray The word array to append. |
||
* |
||
* @return {WordArray} This word array. |
||
* |
||
* @example |
||
* |
||
* wordArray1.concat(wordArray2); |
||
*/ |
||
concat: function (wordArray) { |
||
// Shortcuts |
||
var thisWords = this.words; |
||
var thatWords = wordArray.words; |
||
var thisSigBytes = this.sigBytes; |
||
var thatSigBytes = wordArray.sigBytes; |
||
|
||
// Clamp excess bits |
||
this.clamp(); |
||
|
||
// Concat |
||
if (thisSigBytes % 4) { |
||
// Copy one byte at a time |
||
for (var i = 0; i < thatSigBytes; i++) { |
||
var thatByte = (thatWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; |
||
thisWords[(thisSigBytes + i) >>> 2] |= thatByte << (24 - ((thisSigBytes + i) % 4) * 8); |
||
} |
||
} else if (thatWords.length > 0xffff) { |
||
// Copy one word at a time |
||
for (var i = 0; i < thatSigBytes; i += 4) { |
||
thisWords[(thisSigBytes + i) >>> 2] = thatWords[i >>> 2]; |
||
} |
||
} else { |
||
// Copy all words at once |
||
// thisWords.push.apply(thisWords, thatWords); |
||
|
||
// HOTFIX from: https://code.google.com/p/crypto-js/issues/detail?id=90 |
||
for (var i = 0; i < thatWords.length; i++) { |
||
thisWords.push(thatWords[i]); |
||
} |
||
} |
||
this.sigBytes += thatSigBytes; |
||
|
||
// Chainable |
||
return this; |
||
}, |
||
|
||
/** |
||
* Removes insignificant bits. |
||
* |
||
* @example |
||
* |
||
* wordArray.clamp(); |
||
*/ |
||
clamp: function () { |
||
// Shortcuts |
||
var words = this.words; |
||
var sigBytes = this.sigBytes; |
||
|
||
// Clamp |
||
words[sigBytes >>> 2] &= 0xffffffff << (32 - (sigBytes % 4) * 8); |
||
words.length = Math.ceil(sigBytes / 4); |
||
}, |
||
|
||
/** |
||
* Creates a copy of this word array. |
||
* |
||
* @return {WordArray} The clone. |
||
* |
||
* @example |
||
* |
||
* var clone = wordArray.clone(); |
||
*/ |
||
clone: function () { |
||
var clone = Base.clone.call(this); |
||
clone.words = this.words.slice(0); |
||
|
||
return clone; |
||
}, |
||
|
||
/** |
||
* Creates a word array filled with random bytes. |
||
* |
||
* @param {number} nBytes The number of random bytes to generate. |
||
* |
||
* @return {WordArray} The random word array. |
||
* |
||
* @static |
||
* |
||
* @example |
||
* |
||
* var wordArray = CryptoJS.lib.WordArray.random(16); |
||
*/ |
||
random: function (nBytes) { |
||
var words = []; |
||
for (var i = 0; i < nBytes; i += 4) { |
||
words.push((Math.random() * 0x100000000) | 0); |
||
} |
||
|
||
return new WordArray.init(words, nBytes); |
||
} |
||
}); |
||
|
||
/** |
||
* Encoder namespace. |
||
*/ |
||
var C_enc = C.enc = {}; |
||
|
||
/** |
||
* Hex encoding strategy. |
||
*/ |
||
var Hex = C_enc.Hex = { |
||
/** |
||
* Converts a word array to a hex string. |
||
* |
||
* @param {WordArray} wordArray The word array. |
||
* |
||
* @return {string} The hex string. |
||
* |
||
* @static |
||
* |
||
* @example |
||
* |
||
* var hexString = CryptoJS.enc.Hex.stringify(wordArray); |
||
*/ |
||
stringify: function (wordArray) { |
||
// Shortcuts |
||
var words = wordArray.words; |
||
var sigBytes = wordArray.sigBytes; |
||
|
||
// Convert |
||
var hexChars = []; |
||
for (var i = 0; i < sigBytes; i++) { |
||
var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; |
||
hexChars.push((bite >>> 4).toString(16)); |
||
hexChars.push((bite & 0x0f).toString(16)); |
||
} |
||
|
||
return hexChars.join(''); |
||
}, |
||
|
||
/** |
||
* Converts a hex string to a word array. |
||
* |
||
* @param {string} hexStr The hex string. |
||
* |
||
* @return {WordArray} The word array. |
||
* |
||
* @static |
||
* |
||
* @example |
||
* |
||
* var wordArray = CryptoJS.enc.Hex.parse(hexString); |
||
*/ |
||
parse: function (hexStr) { |
||
// Shortcut |
||
var hexStrLength = hexStr.length; |
||
|
||
// Convert |
||
var words = []; |
||
for (var i = 0; i < hexStrLength; i += 2) { |
||
words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << (24 - (i % 8) * 4); |
||
} |
||
|
||
return new WordArray.init(words, hexStrLength / 2); |
||
} |
||
}; |
||
|
||
/** |
||
* Latin1 encoding strategy. |
||
*/ |
||
var Latin1 = C_enc.Latin1 = { |
||
/** |
||
* Converts a word array to a Latin1 string. |
||
* |
||
* @param {WordArray} wordArray The word array. |
||
* |
||
* @return {string} The Latin1 string. |
||
* |
||
* @static |
||
* |
||
* @example |
||
* |
||
* var latin1String = CryptoJS.enc.Latin1.stringify(wordArray); |
||
*/ |
||
stringify: function (wordArray) { |
||
// Shortcuts |
||
var words = wordArray.words; |
||
var sigBytes = wordArray.sigBytes; |
||
|
||
// Convert |
||
var latin1Chars = []; |
||
for (var i = 0; i < sigBytes; i++) { |
||
var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; |
||
latin1Chars.push(String.fromCharCode(bite)); |
||
} |
||
|
||
return latin1Chars.join(''); |
||
}, |
||
|
||
/** |
||
* Converts a Latin1 string to a word array. |
||
* |
||
* @param {string} latin1Str The Latin1 string. |
||
* |
||
* @return {WordArray} The word array. |
||
* |
||
* @static |
||
* |
||
* @example |
||
* |
||
* var wordArray = CryptoJS.enc.Latin1.parse(latin1String); |
||
*/ |
||
parse: function (latin1Str) { |
||
// Shortcut |
||
var latin1StrLength = latin1Str.length; |
||
|
||
// Convert |
||
var words = []; |
||
for (var i = 0; i < latin1StrLength; i++) { |
||
words[i >>> 2] |= (latin1Str.charCodeAt(i) & 0xff) << (24 - (i % 4) * 8); |
||
} |
||
|
||
return new WordArray.init(words, latin1StrLength); |
||
} |
||
}; |
||
|
||
/** |
||
* UTF-8 encoding strategy. |
||
*/ |
||
var Utf8 = C_enc.Utf8 = { |
||
/** |
||
* Converts a word array to a UTF-8 string. |
||
* |
||
* @param {WordArray} wordArray The word array. |
||
* |
||
* @return {string} The UTF-8 string. |
||
* |
||
* @static |
||
* |
||
* @example |
||
* |
||
* var utf8String = CryptoJS.enc.Utf8.stringify(wordArray); |
||
*/ |
||
stringify: function (wordArray) { |
||
try { |
||
return decodeURIComponent(escape(Latin1.stringify(wordArray))); |
||
} catch (e) { |
||
throw new Error('Malformed UTF-8 data'); |
||
} |
||
}, |
||
|
||
/** |
||
* Converts a UTF-8 string to a word array. |
||
* |
||
* @param {string} utf8Str The UTF-8 string. |
||
* |
||
* @return {WordArray} The word array. |
||
* |
||
* @static |
||
* |
||
* @example |
||
* |
||
* var wordArray = CryptoJS.enc.Utf8.parse(utf8String); |
||
*/ |
||
parse: function (utf8Str) { |
||
return Latin1.parse(unescape(encodeURIComponent(utf8Str))); |
||
} |
||
}; |
||
|
||
/** |
||
* Abstract buffered block algorithm template. |
||
* |
||
* The property blockSize must be implemented in a concrete subtype. |
||
* |
||
* @property {number} _minBufferSize The number of blocks that should be kept unprocessed in the buffer. Default: 0 |
||
*/ |
||
var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({ |
||
/** |
||
* Resets this block algorithm's data buffer to its initial state. |
||
* |
||
* @example |
||
* |
||
* bufferedBlockAlgorithm.reset(); |
||
*/ |
||
reset: function () { |
||
// Initial values |
||
this._data = new WordArray.init(); |
||
this._nDataBytes = 0; |
||
}, |
||
|
||
/** |
||
* Adds new data to this block algorithm's buffer. |
||
* |
||
* @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8. |
||
* |
||
* @example |
||
* |
||
* bufferedBlockAlgorithm._append('data'); |
||
* bufferedBlockAlgorithm._append(wordArray); |
||
*/ |
||
_append: function (data) { |
||
// Convert string to WordArray, else assume WordArray already |
||
if (typeof data == 'string') { |
||
data = Utf8.parse(data); |
||
} |
||
|
||
// Append |
||
this._data.concat(data); |
||
this._nDataBytes += data.sigBytes; |
||
}, |
||
|
||
/** |
||
* Processes available data blocks. |
||
* |
||
* This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype. |
||
* |
||
* @param {boolean} doFlush Whether all blocks and partial blocks should be processed. |
||
* |
||
* @return {WordArray} The processed data. |
||
* |
||
* @example |
||
* |
||
* var processedData = bufferedBlockAlgorithm._process(); |
||
* var processedData = bufferedBlockAlgorithm._process(!!'flush'); |
||
*/ |
||
_process: function (doFlush) { |
||
// Shortcuts |
||
var data = this._data; |
||
var dataWords = data.words; |
||
var dataSigBytes = data.sigBytes; |
||
var blockSize = this.blockSize; |
||
var blockSizeBytes = blockSize * 4; |
||
|
||
// Count blocks ready |
||
var nBlocksReady = dataSigBytes / blockSizeBytes; |
||
if (doFlush) { |
||
// Round up to include partial blocks |
||
nBlocksReady = Math.ceil(nBlocksReady); |
||
} else { |
||
// Round down to include only full blocks, |
||
// less the number of blocks that must remain in the buffer |
||
nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0); |
||
} |
||
|
||
// Count words ready |
||
var nWordsReady = nBlocksReady * blockSize; |
||
|
||
// Count bytes ready |
||
var nBytesReady = Math.min(nWordsReady * 4, dataSigBytes); |
||
|
||
// Process blocks |
||
if (nWordsReady) { |
||
for (var offset = 0; offset < nWordsReady; offset += blockSize) { |
||
// Perform concrete-algorithm logic |
||
this._doProcessBlock(dataWords, offset); |
||
} |
||
|
||
// Remove processed words |
||
var processedWords = dataWords.splice(0, nWordsReady); |
||
data.sigBytes -= nBytesReady; |
||
} |
||
|
||
// Return processed words |
||
return new WordArray.init(processedWords, nBytesReady); |
||
}, |
||
|
||
/** |
||
* Creates a copy of this object. |
||
* |
||
* @return {Object} The clone. |
||
* |
||
* @example |
||
* |
||
* var clone = bufferedBlockAlgorithm.clone(); |
||
*/ |
||
clone: function () { |
||
var clone = Base.clone.call(this); |
||
clone._data = this._data.clone(); |
||
|
||
return clone; |
||
}, |
||
|
||
_minBufferSize: 0 |
||
}); |
||
|
||
/** |
||
* Abstract hasher template. |
||
* |
||
* @property {number} blockSize The number of 32-bit words this hasher operates on. Default: 16 (512 bits) |
||
*/ |
||
var Hasher = C_lib.Hasher = BufferedBlockAlgorithm.extend({ |
||
/** |
||
* Configuration options. |
||
*/ |
||
cfg: Base.extend(), |
||
|
||
/** |
||
* Initializes a newly created hasher. |
||
* |
||
* @param {Object} cfg (Optional) The configuration options to use for this hash computation. |
||
* |
||
* @example |
||
* |
||
* var hasher = CryptoJS.algo.SHA256.create(); |
||
*/ |
||
init: function (cfg) { |
||
// Apply config defaults |
||
this.cfg = this.cfg.extend(cfg); |
||
|
||
// Set initial values |
||
this.reset(); |
||
}, |
||
|
||
/** |
||
* Resets this hasher to its initial state. |
||
* |
||
* @example |
||
* |
||
* hasher.reset(); |
||
*/ |
||
reset: function () { |
||
// Reset data buffer |
||
BufferedBlockAlgorithm.reset.call(this); |
||
|
||
// Perform concrete-hasher logic |
||
this._doReset(); |
||
}, |
||
|
||
/** |
||
* Updates this hasher with a message. |
||
* |
||
* @param {WordArray|string} messageUpdate The message to append. |
||
* |
||
* @return {Hasher} This hasher. |
||
* |
||
* @example |
||
* |
||
* hasher.update('message'); |
||
* hasher.update(wordArray); |
||
*/ |
||
update: function (messageUpdate) { |
||
// Append |
||
this._append(messageUpdate); |
||
|
||
// Update the hash |
||
this._process(); |
||
|
||
// Chainable |
||
return this; |
||
}, |
||
|
||
/** |
||
* Finalizes the hash computation. |
||
* Note that the finalize operation is effectively a destructive, read-once operation. |
||
* |
||
* @param {WordArray|string} messageUpdate (Optional) A final message update. |
||
* |
||
* @return {WordArray} The hash. |
||
* |
||
* @example |
||
* |
||
* var hash = hasher.finalize(); |
||
* var hash = hasher.finalize('message'); |
||
* var hash = hasher.finalize(wordArray); |
||
*/ |
||
finalize: function (messageUpdate) { |
||
// Final message update |
||
if (messageUpdate) { |
||
this._append(messageUpdate); |
||
} |
||
|
||
// Perform concrete-hasher logic |
||
var hash = this._doFinalize(); |
||
|
||
return hash; |
||
}, |
||
|
||
blockSize: 512/32, |
||
|
||
/** |
||
* Creates a shortcut function to a hasher's object interface. |
||
* |
||
* @param {Hasher} hasher The hasher to create a helper for. |
||
* |
||
* @return {Function} The shortcut function. |
||
* |
||
* @static |
||
* |
||
* @example |
||
* |
||
* var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256); |
||
*/ |
||
_createHelper: function (hasher) { |
||
return function (message, cfg) { |
||
return new hasher.init(cfg).finalize(message); |
||
}; |
||
}, |
||
|
||
/** |
||
* Creates a shortcut function to the HMAC's object interface. |
||
* |
||
* @param {Hasher} hasher The hasher to use in this HMAC helper. |
||
* |
||
* @return {Function} The shortcut function. |
||
* |
||
* @static |
||
* |
||
* @example |
||
* |
||
* var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256); |
||
*/ |
||
_createHmacHelper: function (hasher) { |
||
return function (message, key) { |
||
return new C_algo.HMAC.init(hasher, key).finalize(message); |
||
}; |
||
} |
||
}); |
||
|
||
/** |
||
* Algorithm namespace. |
||
*/ |
||
var C_algo = C.algo = {}; |
||
|
||
return C; |
||
}(Math)); |
||
|
||
|
||
|
||
/* |
||
CryptoJS v3.1.2 |
||
code.google.com/p/crypto-js |
||
(c) 2009-2013 by Jeff Mott. All rights reserved. |
||
code.google.com/p/crypto-js/wiki/License |
||
*/ |
||
/** |
||
* Cipher core components. |
||
*/ |
||
CryptoJS.lib.Cipher || (function (undefined) { |
||
// Shortcuts |
||
var C = CryptoJS; |
||
var C_lib = C.lib; |
||
var Base = C_lib.Base; |
||
var WordArray = C_lib.WordArray; |
||
var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm; |
||
var C_enc = C.enc; |
||
var Utf8 = C_enc.Utf8; |
||
var Base64 = C_enc.Base64; |
||
var C_algo = C.algo; |
||
var EvpKDF = C_algo.EvpKDF; |
||
|
||
/** |
||
* Abstract base cipher template. |
||
* |
||
* @property {number} keySize This cipher's key size. Default: 4 (128 bits) |
||
* @property {number} ivSize This cipher's IV size. Default: 4 (128 bits) |
||
* @property {number} _ENC_XFORM_MODE A constant representing encryption mode. |
||
* @property {number} _DEC_XFORM_MODE A constant representing decryption mode. |
||
*/ |
||
var Cipher = C_lib.Cipher = BufferedBlockAlgorithm.extend({ |
||
/** |
||
* Configuration options. |
||
* |
||
* @property {WordArray} iv The IV to use for this operation. |
||
*/ |
||
cfg: Base.extend(), |
||
|
||
/** |
||
* Creates this cipher in encryption mode. |
||
* |
||
* @param {WordArray} key The key. |
||
* @param {Object} cfg (Optional) The configuration options to use for this operation. |
||
* |
||
* @return {Cipher} A cipher instance. |
||
* |
||
* @static |
||
* |
||
* @example |
||
* |
||
* var cipher = CryptoJS.algo.AES.createEncryptor(keyWordArray, { iv: ivWordArray }); |
||
*/ |
||
createEncryptor: function (key, cfg) { |
||
return this.create(this._ENC_XFORM_MODE, key, cfg); |
||
}, |
||
|
||
/** |
||
* Creates this cipher in decryption mode. |
||
* |
||
* @param {WordArray} key The key. |
||
* @param {Object} cfg (Optional) The configuration options to use for this operation. |
||
* |
||
* @return {Cipher} A cipher instance. |
||
* |
||
* @static |
||
* |
||
* @example |
||
* |
||
* var cipher = CryptoJS.algo.AES.createDecryptor(keyWordArray, { iv: ivWordArray }); |
||
*/ |
||
createDecryptor: function (key, cfg) { |
||
return this.create(this._DEC_XFORM_MODE, key, cfg); |
||
}, |
||
|
||
/** |
||
* Initializes a newly created cipher. |
||
* |
||
* @param {number} xformMode Either the encryption or decryption transormation mode constant. |
||
* @param {WordArray} key The key. |
||
* @param {Object} cfg (Optional) The configuration options to use for this operation. |
||
* |
||
* @example |
||
* |
||
* var cipher = CryptoJS.algo.AES.create(CryptoJS.algo.AES._ENC_XFORM_MODE, keyWordArray, { iv: ivWordArray }); |
||
*/ |
||
init: function (xformMode, key, cfg) { |
||
// Apply config defaults |
||
this.cfg = this.cfg.extend(cfg); |
||
|
||
// Store transform mode and key |
||
this._xformMode = xformMode; |
||
this._key = key; |
||
|
||
// Set initial values |
||
this.reset(); |
||
}, |
||
|
||
/** |
||
* Resets this cipher to its initial state. |
||
* |
||
* @example |
||
* |
||
* cipher.reset(); |
||
*/ |
||
reset: function () { |
||
// Reset data buffer |
||
BufferedBlockAlgorithm.reset.call(this); |
||
|
||
// Perform concrete-cipher logic |
||
this._doReset(); |
||
}, |
||
|
||
/** |
||
* Adds data to be encrypted or decrypted. |
||
* |
||
* @param {WordArray|string} dataUpdate The data to encrypt or decrypt. |
||
* |
||
* @return {WordArray} The data after processing. |
||
* |
||
* @example |
||
* |
||
* var encrypted = cipher.process('data'); |
||
* var encrypted = cipher.process(wordArray); |
||
*/ |
||
process: function (dataUpdate) { |
||
// Append |
||
this._append(dataUpdate); |
||
|
||
// Process available blocks |
||
return this._process(); |
||
}, |
||
|
||
/** |
||
* Finalizes the encryption or decryption process. |
||
* Note that the finalize operation is effectively a destructive, read-once operation. |
||
* |
||
* @param {WordArray|string} dataUpdate The final data to encrypt or decrypt. |
||
* |
||
* @return {WordArray} The data after final processing. |
||
* |
||
* @example |
||
* |
||
* var encrypted = cipher.finalize(); |
||
* var encrypted = cipher.finalize('data'); |
||
* var encrypted = cipher.finalize(wordArray); |
||
*/ |
||
finalize: function (dataUpdate) { |
||
// Final data update |
||
if (dataUpdate) { |
||
this._append(dataUpdate); |
||
} |
||
|
||
// Perform concrete-cipher logic |
||
var finalProcessedData = this._doFinalize(); |
||
|
||
return finalProcessedData; |
||
}, |
||
|
||
keySize: 128/32, |
||
|
||
ivSize: 128/32, |
||
|
||
_ENC_XFORM_MODE: 1, |
||
|
||
_DEC_XFORM_MODE: 2, |
||
|
||
/** |
||
* Creates shortcut functions to a cipher's object interface. |
||
* |
||
* @param {Cipher} cipher The cipher to create a helper for. |
||
* |
||
* @return {Object} An object with encrypt and decrypt shortcut functions. |
||
* |
||
* @static |
||
* |
||
* @example |
||
* |
||
* var AES = CryptoJS.lib.Cipher._createHelper(CryptoJS.algo.AES); |
||
*/ |
||
_createHelper: (function () { |
||
function selectCipherStrategy(key) { |
||
if (typeof key == 'string') { |
||
return PasswordBasedCipher; |
||
} else { |
||
return SerializableCipher; |
||
} |
||
} |
||
|
||
return function (cipher) { |
||
return { |
||
encrypt: function (message, key, cfg) { |
||
return selectCipherStrategy(key).encrypt(cipher, message, key, cfg); |
||
}, |
||
|
||
decrypt: function (ciphertext, key, cfg) { |
||
return selectCipherStrategy(key).decrypt(cipher, ciphertext, key, cfg); |
||
} |
||
}; |
||
}; |
||
}()) |
||
}); |
||
|
||
/** |
||
* Abstract base stream cipher template. |
||
* |
||
* @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 1 (32 bits) |
||
*/ |
||
var StreamCipher = C_lib.StreamCipher = Cipher.extend({ |
||
_doFinalize: function () { |
||
// Process partial blocks |
||
var finalProcessedBlocks = this._process(!!'flush'); |
||
|
||
return finalProcessedBlocks; |
||
}, |
||
|
||
blockSize: 1 |
||
}); |
||
|
||
/** |
||
* Mode namespace. |
||
*/ |
||
var C_mode = C.mode = {}; |
||
|
||
/** |
||
* Abstract base block cipher mode template. |
||
*/ |
||
var BlockCipherMode = C_lib.BlockCipherMode = Base.extend({ |
||
/** |
||
* Creates this mode for encryption. |
||
* |
||
* @param {Cipher} cipher A block cipher instance. |
||
* @param {Array} iv The IV words. |
||
* |
||
* @static |
||
* |
||
* @example |
||
* |
||
* var mode = CryptoJS.mode.CBC.createEncryptor(cipher, iv.words); |
||
*/ |
||
createEncryptor: function (cipher, iv) { |
||
return this.Encryptor.create(cipher, iv); |
||
}, |
||
|
||
/** |
||
* Creates this mode for decryption. |
||
* |
||
* @param {Cipher} cipher A block cipher instance. |
||
* @param {Array} iv The IV words. |
||
* |
||
* @static |
||
* |
||
* @example |
||
* |
||
* var mode = CryptoJS.mode.CBC.createDecryptor(cipher, iv.words); |
||
*/ |
||
createDecryptor: function (cipher, iv) { |
||
return this.Decryptor.create(cipher, iv); |
||
}, |
||
|
||
/** |
||
* Initializes a newly created mode. |
||
* |
||
* @param {Cipher} cipher A block cipher instance. |
||
* @param {Array} iv The IV words. |
||
* |
||
* @example |
||
* |
||
* var mode = CryptoJS.mode.CBC.Encryptor.create(cipher, iv.words); |
||
*/ |
||
init: function (cipher, iv) { |
||
this._cipher = cipher; |
||
this._iv = iv; |
||
} |
||
}); |
||
|
||
/** |
||
* Cipher Block Chaining mode. |
||
*/ |
||
var CBC = C_mode.CBC = (function () { |
||
/** |
||
* Abstract base CBC mode. |
||
*/ |
||
var CBC = BlockCipherMode.extend(); |
||
|
||
/** |
||
* CBC encryptor. |
||
*/ |
||
CBC.Encryptor = CBC.extend({ |
||
/** |
||
* Processes the data block at offset. |
||
* |
||
* @param {Array} words The data words to operate on. |
||
* @param {number} offset The offset where the block starts. |
||
* |
||
* @example |
||
* |
||
* mode.processBlock(data.words, offset); |
||
*/ |
||
processBlock: function (words, offset) { |
||
// Shortcuts |
||
var cipher = this._cipher; |
||
var blockSize = cipher.blockSize; |
||
|
||
// XOR and encrypt |
||
xorBlock.call(this, words, offset, blockSize); |
||
cipher.encryptBlock(words, offset); |
||
|
||
// Remember this block to use with next block |
||
this._prevBlock = words.slice(offset, offset + blockSize); |
||
} |
||
}); |
||
|
||
/** |
||
* CBC decryptor. |
||
*/ |
||
CBC.Decryptor = CBC.extend({ |
||
/** |
||
* Processes the data block at offset. |
||
* |
||
* @param {Array} words The data words to operate on. |
||
* @param {number} offset The offset where the block starts. |
||
* |
||
* @example |
||
* |
||
* mode.processBlock(data.words, offset); |
||
*/ |
||
processBlock: function (words, offset) { |
||
// Shortcuts |
||
var cipher = this._cipher; |
||
var blockSize = cipher.blockSize; |
||
|
||
// Remember this block to use with next block |
||
var thisBlock = words.slice(offset, offset + blockSize); |
||
|
||
// Decrypt and XOR |
||
cipher.decryptBlock(words, offset); |
||
xorBlock.call(this, words, offset, blockSize); |
||
|
||
// This block becomes the previous block |
||
this._prevBlock = thisBlock; |
||
} |
||
}); |
||
|
||
function xorBlock(words, offset, blockSize) { |
||
// Shortcut |
||
var iv = this._iv; |
||
|
||
// Choose mixing block |
||
if (iv) { |
||
var block = iv; |
||
|
||
// Remove IV for subsequent blocks |
||
this._iv = undefined; |
||
} else { |
||
var block = this._prevBlock; |
||
} |
||
|
||
// XOR blocks |
||
for (var i = 0; i < blockSize; i++) { |
||
words[offset + i] ^= block[i]; |
||
} |
||
} |
||
|
||
return CBC; |
||
}()); |
||
|
||
|
||
/** |
||
* Infinite Garble Extension mode. |
||
*/ |
||
var IGE = C_mode.IGE = (function () { |
||
/** |
||
* Abstract base IGE mode. |
||
*/ |
||
var IGE = BlockCipherMode.extend(); |
||
|
||
/** |
||
* IGE encryptor. |
||
*/ |
||
IGE.Encryptor = IGE.extend({ |
||
/** |
||
* Processes the data block at offset. |
||
* |
||
* @param {Array} words The data words to operate on. |
||
* @param {number} offset The offset where the block starts. |
||
* |
||
* @example |
||
* |
||
* mode.processBlock(data.words, offset); |
||
*/ |
||
processBlock: function (words, offset) { |
||
// Shortcuts |
||
var cipher = this._cipher; |
||
var blockSize = cipher.blockSize; |
||
|
||
if (this._ivp === undefined) { |
||
this._ivp = this._iv.slice(0, blockSize); |
||
this._iv2p = this._iv.slice(blockSize, blockSize + blockSize); |
||
} |
||
|
||
|
||
// Remember this block to use with next block |
||
var nextIv2p = words.slice(offset, offset + blockSize); |
||
|
||
// XOR with previous ciphertext |
||
xorBlock(words, this._ivp, offset, blockSize); |
||
|
||
// Block cipher |
||
cipher.encryptBlock(words, offset); |
||
|
||
// XOR with previous plaintext |
||
xorBlock(words, this._iv2p, offset, blockSize); |
||
|
||
this._ivp = words.slice(offset, offset + blockSize); |
||
this._iv2p = nextIv2p; |
||
} |
||
}); |
||
|
||
/** |
||
* IGE decryptor. |
||
*/ |
||
IGE.Decryptor = IGE.extend({ |
||
/** |
||
* Processes the data block at offset. |
||
* |
||
* @param {Array} words The data words to operate on. |
||
* @param {number} offset The offset where the block starts. |
||
* |
||
* @example |
||
* |
||
* mode.processBlock(data.words, offset); |
||
*/ |
||
processBlock: function (words, offset) { |
||
// Shortcuts |
||
var cipher = this._cipher; |
||
var blockSize = cipher.blockSize; |
||
|
||
if (this._ivp === undefined) { |
||
this._ivp = this._iv.slice(0, blockSize); |
||
this._iv2p = this._iv.slice(blockSize, 2 * blockSize); |
||
} |
||
|
||
// Remember this block to use with next block |
||
var nextIvp = words.slice(offset, offset + blockSize); |
||
|
||
// XOR with previous ciphertext |
||
xorBlock(words, this._iv2p, offset, blockSize); |
||
|
||
// Block cipher |
||
cipher.decryptBlock(words, offset); |
||
|
||
// XOR with previous plaintext |
||
xorBlock(words, this._ivp, offset, blockSize); |
||
|
||
this._ivp = nextIvp; |
||
this._iv2p = words.slice(offset, offset + blockSize); |
||
} |
||
}); |
||
|
||
function xorBlock(words, block, offset, blockSize) { |
||
for (var i = 0; i < blockSize; i++) { |
||
words[offset + i] ^= block[i]; |
||
} |
||
} |
||
|
||
return IGE; |
||
}()); |
||
|
||
/** |
||
* Padding namespace. |
||
*/ |
||
var C_pad = C.pad = {}; |
||
|
||
/** |
||
* PKCS #5/7 padding strategy. |
||
*/ |
||
var Pkcs7 = C_pad.Pkcs7 = { |
||
/** |
||
* Pads data using the algorithm defined in PKCS #5/7. |
||
* |
||
* @param {WordArray} data The data to pad. |
||
* @param {number} blockSize The multiple that the data should be padded to. |
||
* |
||
* @static |
||
* |
||
* @example |
||
* |
||
* CryptoJS.pad.Pkcs7.pad(wordArray, 4); |
||
*/ |
||
pad: function (data, blockSize) { |
||
// Shortcut |
||
var blockSizeBytes = blockSize * 4; |
||
|
||
// Count padding bytes |
||
var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes; |
||
|
||
// Create padding word |
||
var paddingWord = (nPaddingBytes << 24) | (nPaddingBytes << 16) | (nPaddingBytes << 8) | nPaddingBytes; |
||
|
||
// Create padding |
||
var paddingWords = []; |
||
for (var i = 0; i < nPaddingBytes; i += 4) { |
||
paddingWords.push(paddingWord); |
||
} |
||
var padding = WordArray.create(paddingWords, nPaddingBytes); |
||
|
||
// Add padding |
||
data.concat(padding); |
||
}, |
||
|
||
/** |
||
* Unpads data that had been padded using the algorithm defined in PKCS #5/7. |
||
* |
||
* @param {WordArray} data The data to unpad. |
||
* |
||
* @static |
||
* |
||
* @example |
||
* |
||
* CryptoJS.pad.Pkcs7.unpad(wordArray); |
||
*/ |
||
unpad: function (data) { |
||
// Get number of padding bytes from last byte |
||
var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff; |
||
|
||
// Remove padding |
||
data.sigBytes -= nPaddingBytes; |
||
} |
||
}; |
||
|
||
var NoPadding = C_pad.NoPadding = { |
||
pad: function () { |
||
}, |
||
|
||
unpad: function () { |
||
} |
||
}; |
||
|
||
|
||
/** |
||
* Abstract base block cipher template. |
||
* |
||
* @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 4 (128 bits) |
||
*/ |
||
var BlockCipher = C_lib.BlockCipher = Cipher.extend({ |
||
/** |
||
* Configuration options. |
||
* |
||
* @property {Mode} mode The block mode to use. Default: CBC |
||
* @property {Padding} padding The padding strategy to use. Default: Pkcs7 |
||
*/ |
||
cfg: Cipher.cfg.extend({ |
||
mode: CBC, |
||
padding: Pkcs7 |
||
}), |
||
|
||
reset: function () { |
||
// Reset cipher |
||
Cipher.reset.call(this); |
||
|
||
// Shortcuts |
||
var cfg = this.cfg; |
||
var iv = cfg.iv; |
||
var mode = cfg.mode; |
||
|
||
// Reset block mode |
||
if (this._xformMode == this._ENC_XFORM_MODE) { |
||
var modeCreator = mode.createEncryptor; |
||
} else /* if (this._xformMode == this._DEC_XFORM_MODE) */ { |
||
var modeCreator = mode.createDecryptor; |
||
|
||
// Keep at least one block in the buffer for unpadding |
||
this._minBufferSize = 1; |
||
} |
||
this._mode = modeCreator.call(mode, this, iv && iv.words); |
||
}, |
||
|
||
_doProcessBlock: function (words, offset) { |
||
this._mode.processBlock(words, offset); |
||
}, |
||
|
||
_doFinalize: function () { |
||
// Shortcut |
||
var padding = this.cfg.padding; |
||
|
||
// Finalize |
||
if (this._xformMode == this._ENC_XFORM_MODE) { |
||
// Pad data |
||
padding.pad(this._data, this.blockSize); |
||
|
||
// Process final blocks |
||
var finalProcessedBlocks = this._process(!!'flush'); |
||
} else /* if (this._xformMode == this._DEC_XFORM_MODE) */ { |
||
// Process final blocks |
||
var finalProcessedBlocks = this._process(!!'flush'); |
||
|
||
// Unpad data |
||
padding.unpad(finalProcessedBlocks); |
||
} |
||
|
||
return finalProcessedBlocks; |
||
}, |
||
|
||
blockSize: 128/32 |
||
}); |
||
|
||
/** |
||
* A collection of cipher parameters. |
||
* |
||
* @property {WordArray} ciphertext The raw ciphertext. |
||
* @property {WordArray} key The key to this ciphertext. |
||
* @property {WordArray} iv The IV used in the ciphering operation. |
||
* @property {WordArray} salt The salt used with a key derivation function. |
||
* @property {Cipher} algorithm The cipher algorithm. |
||
* @property {Mode} mode The block mode used in the ciphering operation. |
||
* @property {Padding} padding The padding scheme used in the ciphering operation. |
||
* @property {number} blockSize The block size of the cipher. |
||
* @property {Format} formatter The default formatting strategy to convert this cipher params object to a string. |
||
*/ |
||
var CipherParams = C_lib.CipherParams = Base.extend({ |
||
/** |
||
* Initializes a newly created cipher params object. |
||
* |
||
* @param {Object} cipherParams An object with any of the possible cipher parameters. |
||
* |
||
* @example |
||
* |
||
* var cipherParams = CryptoJS.lib.CipherParams.create({ |
||
* ciphertext: ciphertextWordArray, |
||
* key: keyWordArray, |
||
* iv: ivWordArray, |
||
* salt: saltWordArray, |
||
* algorithm: CryptoJS.algo.AES, |
||
* mode: CryptoJS.mode.CBC, |
||
* padding: CryptoJS.pad.PKCS7, |
||
* blockSize: 4, |
||
* formatter: CryptoJS.format.OpenSSL |
||
* }); |
||
*/ |
||
init: function (cipherParams) { |
||
this.mixIn(cipherParams); |
||
}, |
||
|
||
/** |
||
* Converts this cipher params object to a string. |
||
* |
||
* @param {Format} formatter (Optional) The formatting strategy to use. |
||
* |
||
* @return {string} The stringified cipher params. |
||
* |
||
* @throws Error If neither the formatter nor the default formatter is set. |
||
* |
||
* @example |
||
* |
||
* var string = cipherParams + ''; |
||
* var string = cipherParams.toString(); |
||
* var string = cipherParams.toString(CryptoJS.format.OpenSSL); |
||
*/ |
||
toString: function (formatter) { |
||
return (formatter || this.formatter).stringify(this); |
||
} |
||
}); |
||
|
||
/** |
||
* Format namespace. |
||
*/ |
||
var C_format = C.format = {}; |
||
|
||
/** |
||
* OpenSSL formatting strategy. |
||
*/ |
||
var OpenSSLFormatter = C_format.OpenSSL = { |
||
/** |
||
* Converts a cipher params object to an OpenSSL-compatible string. |
||
* |
||
* @param {CipherParams} cipherParams The cipher params object. |
||
* |
||
* @return {string} The OpenSSL-compatible string. |
||
* |
||
* @static |
||
* |
||
* @example |
||
* |
||
* var openSSLString = CryptoJS.format.OpenSSL.stringify(cipherParams); |
||
*/ |
||
stringify: function (cipherParams) { |
||
// Shortcuts |
||
var ciphertext = cipherParams.ciphertext; |
||
var salt = cipherParams.salt; |
||
|
||
// Format |
||
if (salt) { |
||
var wordArray = WordArray.create([0x53616c74, 0x65645f5f]).concat(salt).concat(ciphertext); |
||
} else { |
||
var wordArray = ciphertext; |
||
} |
||
|
||
return wordArray.toString(Base64); |
||
}, |
||
|
||
/** |
||
* Converts an OpenSSL-compatible string to a cipher params object. |
||
* |
||
* @param {string} openSSLStr The OpenSSL-compatible string. |
||
* |
||
* @return {CipherParams} The cipher params object. |
||
* |
||
* @static |
||
* |
||
* @example |
||
* |
||
* var cipherParams = CryptoJS.format.OpenSSL.parse(openSSLString); |
||
*/ |
||
parse: function (openSSLStr) { |
||
// Parse base64 |
||
var ciphertext = Base64.parse(openSSLStr); |
||
|
||
// Shortcut |
||
var ciphertextWords = ciphertext.words; |
||
|
||
// Test for salt |
||
if (ciphertextWords[0] == 0x53616c74 && ciphertextWords[1] == 0x65645f5f) { |
||
// Extract salt |
||
var salt = WordArray.create(ciphertextWords.slice(2, 4)); |
||
|
||
// Remove salt from ciphertext |
||
ciphertextWords.splice(0, 4); |
||
ciphertext.sigBytes -= 16; |
||
} |
||
|
||
return CipherParams.create({ ciphertext: ciphertext, salt: salt }); |
||
} |
||
}; |
||
|
||
/** |
||
* A cipher wrapper that returns ciphertext as a serializable cipher params object. |
||
*/ |
||
var SerializableCipher = C_lib.SerializableCipher = Base.extend({ |
||
/** |
||
* Configuration options. |
||
* |
||
* @property {Formatter} format The formatting strategy to convert cipher param objects to and from a string. Default: OpenSSL |
||
*/ |
||
cfg: Base.extend({ |
||
format: OpenSSLFormatter |
||
}), |
||
|
||
/** |
||
* Encrypts a message. |
||
* |
||
* @param {Cipher} cipher The cipher algorithm to use. |
||
* @param {WordArray|string} message The message to encrypt. |
||
* @param {WordArray} key The key. |
||
* @param {Object} cfg (Optional) The configuration options to use for this operation. |
||
* |
||
* @return {CipherParams} A cipher params object. |
||
* |
||
* @static |
||
* |
||
* @example |
||
* |
||
* var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key); |
||
* var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv }); |
||
* var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv, format: CryptoJS.format.OpenSSL }); |
||
*/ |
||
encrypt: function (cipher, message, key, cfg) { |
||
// Apply config defaults |
||
cfg = this.cfg.extend(cfg); |
||
|
||
// Encrypt |
||
var encryptor = cipher.createEncryptor(key, cfg); |
||
var ciphertext = encryptor.finalize(message); |
||
|
||
// Shortcut |
||
var cipherCfg = encryptor.cfg; |
||
|
||
// Create and return serializable cipher params |
||
return CipherParams.create({ |
||
ciphertext: ciphertext, |
||
key: key, |
||
iv: cipherCfg.iv, |
||
algorithm: cipher, |
||
mode: cipherCfg.mode, |
||
padding: cipherCfg.padding, |
||
blockSize: cipher.blockSize, |
||
formatter: cfg.format |
||
}); |
||
}, |
||
|
||
/** |
||
* Decrypts serialized ciphertext. |
||
* |
||
* @param {Cipher} cipher The cipher algorithm to use. |
||
* @param {CipherParams|string} ciphertext The ciphertext to decrypt. |
||
* @param {WordArray} key The key. |
||
* @param {Object} cfg (Optional) The configuration options to use for this operation. |
||
* |
||
* @return {WordArray} The plaintext. |
||
* |
||
* @static |
||
* |
||
* @example |
||
* |
||
* var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, key, { iv: iv, format: CryptoJS.format.OpenSSL }); |
||
* var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, key, { iv: iv, format: CryptoJS.format.OpenSSL }); |
||
*/ |
||
decrypt: function (cipher, ciphertext, key, cfg) { |
||
// Apply config defaults |
||
cfg = this.cfg.extend(cfg); |
||
|
||
// Convert string to CipherParams |
||
ciphertext = this._parse(ciphertext, cfg.format); |
||
|
||
// Decrypt |
||
var plaintext = cipher.createDecryptor(key, cfg).finalize(ciphertext.ciphertext); |
||
|
||
return plaintext; |
||
}, |
||
|
||
/** |
||
* Converts serialized ciphertext to CipherParams, |
||
* else assumed CipherParams already and returns ciphertext unchanged. |
||
* |
||
* @param {CipherParams|string} ciphertext The ciphertext. |
||
* @param {Formatter} format The formatting strategy to use to parse serialized ciphertext. |
||
* |
||
* @return {CipherParams} The unserialized ciphertext. |
||
* |
||
* @static |
||
* |
||
* @example |
||
* |
||
* var ciphertextParams = CryptoJS.lib.SerializableCipher._parse(ciphertextStringOrParams, format); |
||
*/ |
||
_parse: function (ciphertext, format) { |
||
if (typeof ciphertext == 'string') { |
||
return format.parse(ciphertext, this); |
||
} else { |
||
return ciphertext; |
||
} |
||
} |
||
}); |
||
|
||
/** |
||
* Key derivation function namespace. |
||
*/ |
||
var C_kdf = C.kdf = {}; |
||
|
||
/** |
||
* OpenSSL key derivation function. |
||
*/ |
||
var OpenSSLKdf = C_kdf.OpenSSL = { |
||
/** |
||
* Derives a key and IV from a password. |
||
* |
||
* @param {string} password The password to derive from. |
||
* @param {number} keySize The size in words of the key to generate. |
||
* @param {number} ivSize The size in words of the IV to generate. |
||
* @param {WordArray|string} salt (Optional) A 64-bit salt to use. If omitted, a salt will be generated randomly. |
||
* |
||
* @return {CipherParams} A cipher params object with the key, IV, and salt. |
||
* |
||
* @static |
||
* |
||
* @example |
||
* |
||
* var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32); |
||
* var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32, 'saltsalt'); |
||
*/ |
||
execute: function (password, keySize, ivSize, salt) { |
||
// Generate random salt |
||
if (!salt) { |
||
salt = WordArray.random(64/8); |
||
} |
||
|
||
// Derive key and IV |
||
var key = EvpKDF.create({ keySize: keySize + ivSize }).compute(password, salt); |
||
|
||
// Separate key and IV |
||
var iv = WordArray.create(key.words.slice(keySize), ivSize * 4); |
||
key.sigBytes = keySize * 4; |
||
|
||
// Return params |
||
return CipherParams.create({ key: key, iv: iv, salt: salt }); |
||
} |
||
}; |
||
|
||
/** |
||
* A serializable cipher wrapper that derives the key from a password, |
||
* and returns ciphertext as a serializable cipher params object. |
||
*/ |
||
var PasswordBasedCipher = C_lib.PasswordBasedCipher = SerializableCipher.extend({ |
||
/** |
||
* Configuration options. |
||
* |
||
* @property {KDF} kdf The key derivation function to use to generate a key and IV from a password. Default: OpenSSL |
||
*/ |
||
cfg: SerializableCipher.cfg.extend({ |
||
kdf: OpenSSLKdf |
||
}), |
||
|
||
/** |
||
* Encrypts a message using a password. |
||
* |
||
* @param {Cipher} cipher The cipher algorithm to use. |
||
* @param {WordArray|string} message The message to encrypt. |
||
* @param {string} password The password. |
||
* @param {Object} cfg (Optional) The configuration options to use for this operation. |
||
* |
||
* @return {CipherParams} A cipher params object. |
||
* |
||
* @static |
||
* |
||
* @example |
||
* |
||
* var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password'); |
||
* var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password', { format: CryptoJS.format.OpenSSL }); |
||
*/ |
||
encrypt: function (cipher, message, password, cfg) { |
||
// Apply config defaults |
||
cfg = this.cfg.extend(cfg); |
||
|
||
// Derive key and other params |
||
var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize); |
||
|
||
// Add IV to config |
||
cfg.iv = derivedParams.iv; |
||
|
||
// Encrypt |
||
var ciphertext = SerializableCipher.encrypt.call(this, cipher, message, derivedParams.key, cfg); |
||
|
||
// Mix in derived params |
||
ciphertext.mixIn(derivedParams); |
||
|
||
return ciphertext; |
||
}, |
||
|
||
/** |
||
* Decrypts serialized ciphertext using a password. |
||
* |
||
* @param {Cipher} cipher The cipher algorithm to use. |
||
* @param {CipherParams|string} ciphertext The ciphertext to decrypt. |
||
* @param {string} password The password. |
||
* @param {Object} cfg (Optional) The configuration options to use for this operation. |
||
* |
||
* @return {WordArray} The plaintext. |
||
* |
||
* @static |
||
* |
||
* @example |
||
* |
||
* var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, 'password', { format: CryptoJS.format.OpenSSL }); |
||
* var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, 'password', { format: CryptoJS.format.OpenSSL }); |
||
*/ |
||
decrypt: function (cipher, ciphertext, password, cfg) { |
||
// Apply config defaults |
||
cfg = this.cfg.extend(cfg); |
||
|
||
// Convert string to CipherParams |
||
ciphertext = this._parse(ciphertext, cfg.format); |
||
|
||
// Derive key and other params |
||
var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize, ciphertext.salt); |
||
|
||
// Add IV to config |
||
cfg.iv = derivedParams.iv; |
||
|
||
// Decrypt |
||
var plaintext = SerializableCipher.decrypt.call(this, cipher, ciphertext, derivedParams.key, cfg); |
||
|
||
return plaintext; |
||
} |
||
}); |
||
}()); |
||
|
||
|
||
|
||
|
||
/* |
||
CryptoJS v3.1.2 |
||
code.google.com/p/crypto-js |
||
(c) 2009-2013 by Jeff Mott. All rights reserved. |
||
code.google.com/p/crypto-js/wiki/License |
||
*/ |
||
(function () { |
||
// Shortcuts |
||
var C = CryptoJS; |
||
var C_lib = C.lib; |
||
var BlockCipher = C_lib.BlockCipher; |
||
var C_algo = C.algo; |
||
|
||
// Lookup tables |
||
var SBOX = []; |
||
var INV_SBOX = []; |
||
var SUB_MIX_0 = []; |
||
var SUB_MIX_1 = []; |
||
var SUB_MIX_2 = []; |
||
var SUB_MIX_3 = []; |
||
var INV_SUB_MIX_0 = []; |
||
var INV_SUB_MIX_1 = []; |
||
var INV_SUB_MIX_2 = []; |
||
var INV_SUB_MIX_3 = []; |
||
|
||
// Compute lookup tables |
||
(function () { |
||
// Compute double table |
||
var d = []; |
||
for (var i = 0; i < 256; i++) { |
||
if (i < 128) { |
||
d[i] = i << 1; |
||
} else { |
||
d[i] = (i << 1) ^ 0x11b; |
||
} |
||
} |
||
|
||
// Walk GF(2^8) |
||
var x = 0; |
||
var xi = 0; |
||
for (var i = 0; i < 256; i++) { |
||
// Compute sbox |
||
var sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4); |
||
sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63; |
||
SBOX[x] = sx; |
||
INV_SBOX[sx] = x; |
||
|
||
// Compute multiplication |
||
var x2 = d[x]; |
||
var x4 = d[x2]; |
||
var x8 = d[x4]; |
||
|
||
// Compute sub bytes, mix columns tables |
||
var t = (d[sx] * 0x101) ^ (sx * 0x1010100); |
||
SUB_MIX_0[x] = (t << 24) | (t >>> 8); |
||
SUB_MIX_1[x] = (t << 16) | (t >>> 16); |
||
SUB_MIX_2[x] = (t << 8) | (t >>> 24); |
||
SUB_MIX_3[x] = t; |
||
|
||
// Compute inv sub bytes, inv mix columns tables |
||
var t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100); |
||
INV_SUB_MIX_0[sx] = (t << 24) | (t >>> 8); |
||
INV_SUB_MIX_1[sx] = (t << 16) | (t >>> 16); |
||
INV_SUB_MIX_2[sx] = (t << 8) | (t >>> 24); |
||
INV_SUB_MIX_3[sx] = t; |
||
|
||
// Compute next counter |
||
if (!x) { |
||
x = xi = 1; |
||
} else { |
||
x = x2 ^ d[d[d[x8 ^ x2]]]; |
||
xi ^= d[d[xi]]; |
||
} |
||
} |
||
}()); |
||
|
||
// Precomputed Rcon lookup |
||
var RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36]; |
||
|
||
/** |
||
* AES block cipher algorithm. |
||
*/ |
||
var AES = C_algo.AES = BlockCipher.extend({ |
||
_doReset: function () { |
||
// Shortcuts |
||
var key = this._key; |
||
var keyWords = key.words; |
||
var keySize = key.sigBytes / 4; |
||
|
||
// Compute number of rounds |
||
var nRounds = this._nRounds = keySize + 6 |
||
|
||
// Compute number of key schedule rows |
||
var ksRows = (nRounds + 1) * 4; |
||
|
||
// Compute key schedule |
||
var keySchedule = this._keySchedule = []; |
||
for (var ksRow = 0; ksRow < ksRows; ksRow++) { |
||
if (ksRow < keySize) { |
||
keySchedule[ksRow] = keyWords[ksRow]; |
||
} else { |
||
var t = keySchedule[ksRow - 1]; |
||
|
||
if (!(ksRow % keySize)) { |
||
// Rot word |
||
t = (t << 8) | (t >>> 24); |
||
|
||
// Sub word |
||
t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff]; |
||
|
||
// Mix Rcon |
||
t ^= RCON[(ksRow / keySize) | 0] << 24; |
||
} else if (keySize > 6 && ksRow % keySize == 4) { |
||
// Sub word |
||
t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff]; |
||
} |
||
|
||
keySchedule[ksRow] = keySchedule[ksRow - keySize] ^ t; |
||
} |
||
} |
||
|
||
// Compute inv key schedule |
||
var invKeySchedule = this._invKeySchedule = []; |
||
for (var invKsRow = 0; invKsRow < ksRows; invKsRow++) { |
||
var ksRow = ksRows - invKsRow; |
||
|
||
if (invKsRow % 4) { |
||
var t = keySchedule[ksRow]; |
||
} else { |
||
var t = keySchedule[ksRow - 4]; |
||
} |
||
|
||
if (invKsRow < 4 || ksRow <= 4) { |
||
invKeySchedule[invKsRow] = t; |
||
} else { |
||
invKeySchedule[invKsRow] = INV_SUB_MIX_0[SBOX[t >>> 24]] ^ INV_SUB_MIX_1[SBOX[(t >>> 16) & 0xff]] ^ |
||
INV_SUB_MIX_2[SBOX[(t >>> 8) & 0xff]] ^ INV_SUB_MIX_3[SBOX[t & 0xff]]; |
||
} |
||
} |
||
}, |
||
|
||
encryptBlock: function (M, offset) { |
||
this._doCryptBlock(M, offset, this._keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX); |
||
}, |
||
|
||
decryptBlock: function (M, offset) { |
||
// Swap 2nd and 4th rows |
||
var t = M[offset + 1]; |
||
M[offset + 1] = M[offset + 3]; |
||
M[offset + 3] = t; |
||
|
||
this._doCryptBlock(M, offset, this._invKeySchedule, INV_SUB_MIX_0, INV_SUB_MIX_1, INV_SUB_MIX_2, INV_SUB_MIX_3, INV_SBOX); |
||
|
||
// Inv swap 2nd and 4th rows |
||
var t = M[offset + 1]; |
||
M[offset + 1] = M[offset + 3]; |
||
M[offset + 3] = t; |
||
}, |
||
|
||
_doCryptBlock: function (M, offset, keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX) { |
||
// Shortcut |
||
var nRounds = this._nRounds; |
||
|
||
// Get input, add round key |
||
var s0 = M[offset] ^ keySchedule[0]; |
||
var s1 = M[offset + 1] ^ keySchedule[1]; |
||
var s2 = M[offset + 2] ^ keySchedule[2]; |
||
var s3 = M[offset + 3] ^ keySchedule[3]; |
||
|
||
// Key schedule row counter |
||
var ksRow = 4; |
||
|
||
// Rounds |
||
for (var round = 1; round < nRounds; round++) { |
||
// Shift rows, sub bytes, mix columns, add round key |
||
var t0 = SUB_MIX_0[s0 >>> 24] ^ SUB_MIX_1[(s1 >>> 16) & 0xff] ^ SUB_MIX_2[(s2 >>> 8) & 0xff] ^ SUB_MIX_3[s3 & 0xff] ^ keySchedule[ksRow++]; |
||
var t1 = SUB_MIX_0[s1 >>> 24] ^ SUB_MIX_1[(s2 >>> 16) & 0xff] ^ SUB_MIX_2[(s3 >>> 8) & 0xff] ^ SUB_MIX_3[s0 & 0xff] ^ keySchedule[ksRow++]; |
||
var t2 = SUB_MIX_0[s2 >>> 24] ^ SUB_MIX_1[(s3 >>> 16) & 0xff] ^ SUB_MIX_2[(s0 >>> 8) & 0xff] ^ SUB_MIX_3[s1 & 0xff] ^ keySchedule[ksRow++]; |
||
var t3 = SUB_MIX_0[s3 >>> 24] ^ SUB_MIX_1[(s0 >>> 16) & 0xff] ^ SUB_MIX_2[(s1 >>> 8) & 0xff] ^ SUB_MIX_3[s2 & 0xff] ^ keySchedule[ksRow++]; |
||
|
||
// Update state |
||
s0 = t0; |
||
s1 = t1; |
||
s2 = t2; |
||
s3 = t3; |
||
} |
||
|
||
// Shift rows, sub bytes, add round key |
||
var t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++]; |
||
var t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++]; |
||
var t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++]; |
||
var t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++]; |
||
|
||
// Set output |
||
M[offset] = t0; |
||
M[offset + 1] = t1; |
||
M[offset + 2] = t2; |
||
M[offset + 3] = t3; |
||
}, |
||
|
||
keySize: 256/32 |
||
}); |
||
|
||
/** |
||
* Shortcut functions to the cipher's object interface. |
||
* |
||
* @example |
||
* |
||
* var ciphertext = CryptoJS.AES.encrypt(message, key, cfg); |
||
* var plaintext = CryptoJS.AES.decrypt(ciphertext, key, cfg); |
||
*/ |
||
C.AES = BlockCipher._createHelper(AES); |
||
}()); |
||
|
||
|
||
|
||
/** |
||
* Copyright (c) 2012 T. Michael Keesey |
||
* LICENSE: http://opensource.org/licenses/MIT |
||
*/ |
||
var sha1; |
||
(function (sha1) { |
||
var POW_2_24 = Math.pow(2, 24); |
||
var POW_2_32 = Math.pow(2, 32); |
||
function hex(n) { |
||
var s = "", v; |
||
for(var i = 7; i >= 0; --i) { |
||
v = (n >>> (i << 2)) & 15; |
||
s += v.toString(16); |
||
} |
||
return s; |
||
}; |
||
|
||
function toBytes(n) { |
||
var b = [], v; |
||
for(var i = 3; i >= 0; --i) { |
||
v = (n >> (i * 8)) & 255; |
||
b.push(v); |
||
} |
||
return b; |
||
}; |
||
|
||
function lrot(n, bits) { |
||
return ((n << bits) | (n >>> (32 - bits))); |
||
} |
||
var Uint32ArrayBigEndian = (function () { |
||
function Uint32ArrayBigEndian(length) { |
||
this.bytes = new Uint8Array(length << 2); |
||
} |
||
Uint32ArrayBigEndian.prototype.get = function (index) { |
||
index <<= 2; |
||
return (this.bytes[index] * POW_2_24) + ((this.bytes[index + 1] << 16) | (this.bytes[index + 2] << 8) | this.bytes[index + 3]); |
||
}; |
||
Uint32ArrayBigEndian.prototype.set = function (index, value) { |
||
var high = Math.floor(value / POW_2_24), rest = value - (high * POW_2_24); |
||
index <<= 2; |
||
this.bytes[index] = high; |
||
this.bytes[index + 1] = rest >> 16; |
||
this.bytes[index + 2] = (rest >> 8) & 255; |
||
this.bytes[index + 3] = rest & 255; |
||
}; |
||
return Uint32ArrayBigEndian; |
||
})(); |
||
function string2ArrayBuffer(s) { |
||
s = s.replace(/[\u0080-\u07ff]/g, function (c) { |
||
var code = c.charCodeAt(0); |
||
return String.fromCharCode(192 | code >> 6, 128 | code & 63); |
||
}); |
||
s = s.replace(/[\u0080-\uffff]/g, function (c) { |
||
var code = c.charCodeAt(0); |
||
return String.fromCharCode(224 | code >> 12, 128 | code >> 6 & 63, 128 | code & 63); |
||
}); |
||
var n = s.length, array = new Uint8Array(n); |
||
for(var i = 0; i < n; ++i) { |
||
array[i] = s.charCodeAt(i); |
||
} |
||
return array.buffer; |
||
} |
||
function bytes2ArrayBuffer(b) { |
||
var n = b.length, array = new Uint8Array(n); |
||
for(var i = 0; i < n; ++i) { |
||
array[i] = b[i]; |
||
} |
||
return array.buffer; |
||
} |
||
|
||
function hash(bufferOrString, byteArray) { |
||
var source; |
||
if (bufferOrString instanceof ArrayBuffer) { |
||
source = bufferOrString; |
||
} else if (Object.prototype.toString.apply(bufferOrString) == '[object Array]') { |
||
source = bytes2ArrayBuffer(bufferOrString); |
||
} else { |
||
source = string2ArrayBuffer(String(bufferOrString)); |
||
} |
||
var h0 = 1732584193, h1 = 4023233417, h2 = 2562383102, h3 = 271733878, h4 = 3285377520, i, sbytes = source.byteLength, sbits = sbytes << 3, minbits = sbits + 65, bits = Math.ceil(minbits / 512) << 9, bytes = bits >>> 3, slen = bytes >>> 2, s = new Uint32ArrayBigEndian(slen), s8 = s.bytes, j, w = new Uint32Array(80), sourceArray = new Uint8Array(source); |
||
for(i = 0; i < sbytes; ++i) { |
||
s8[i] = sourceArray[i]; |
||
} |
||
s8[sbytes] = 128; |
||
s.set(slen - 2, Math.floor(sbits / POW_2_32)); |
||
s.set(slen - 1, sbits & 4294967295); |
||
for(i = 0; i < slen; i += 16) { |
||
for(j = 0; j < 16; ++j) { |
||
w[j] = s.get(i + j); |
||
} |
||
for(; j < 80; ++j) { |
||
w[j] = lrot(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1); |
||
} |
||
var a = h0, b = h1, c = h2, d = h3, e = h4, f, k, temp; |
||
for(j = 0; j < 80; ++j) { |
||
if(j < 20) { |
||
f = (b & c) | ((~b) & d); |
||
k = 1518500249; |
||
} else { |
||
if(j < 40) { |
||
f = b ^ c ^ d; |
||
k = 1859775393; |
||
} else { |
||
if(j < 60) { |
||
f = (b & c) ^ (b & d) ^ (c & d); |
||
k = 2400959708; |
||
} else { |
||
f = b ^ c ^ d; |
||
k = 3395469782; |
||
} |
||
} |
||
} |
||
temp = (lrot(a, 5) + f + e + k + w[j]) & 4294967295; |
||
e = d; |
||
d = c; |
||
c = lrot(b, 30); |
||
b = a; |
||
a = temp; |
||
} |
||
h0 = (h0 + a) & 4294967295; |
||
h1 = (h1 + b) & 4294967295; |
||
h2 = (h2 + c) & 4294967295; |
||
h3 = (h3 + d) & 4294967295; |
||
h4 = (h4 + e) & 4294967295; |
||
} |
||
|
||
if (byteArray) { |
||
return toBytes(h0).concat(toBytes(h1), toBytes(h2), toBytes(h3), toBytes(h4)); |
||
} |
||
return hex(h0) + hex(h1) + hex(h2) + hex(h3) + hex(h4); |
||
} |
||
sha1.hash = hash; |
||
})(sha1 || (sha1 = {})); |
||
|
||
/** @license zlib.js 2012 - imaya [ https://github.com/imaya/zlib.js ] The MIT License */(function() {'use strict';function n(e){throw e;}var p=void 0,aa=this;function r(e,c){var d=e.split("."),b=aa;!(d[0]in b)&&b.execScript&&b.execScript("var "+d[0]);for(var a;d.length&&(a=d.shift());)!d.length&&c!==p?b[a]=c:b=b[a]?b[a]:b[a]={}};var u="undefined"!==typeof Uint8Array&&"undefined"!==typeof Uint16Array&&"undefined"!==typeof Uint32Array;new (u?Uint8Array:Array)(256);var v;for(v=0;256>v;++v)for(var w=v,ba=7,w=w>>>1;w;w>>>=1)--ba;function x(e,c,d){var b,a="number"===typeof c?c:c=0,f="number"===typeof d?d:e.length;b=-1;for(a=f&7;a--;++c)b=b>>>8^y[(b^e[c])&255];for(a=f>>3;a--;c+=8)b=b>>>8^y[(b^e[c])&255],b=b>>>8^y[(b^e[c+1])&255],b=b>>>8^y[(b^e[c+2])&255],b=b>>>8^y[(b^e[c+3])&255],b=b>>>8^y[(b^e[c+4])&255],b=b>>>8^y[(b^e[c+5])&255],b=b>>>8^y[(b^e[c+6])&255],b=b>>>8^y[(b^e[c+7])&255];return(b^4294967295)>>>0} |
||
var z=[0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759, |
||
2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977, |
||
2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755, |
||
2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462,1090812512,3747672003,2825379669,829329135,1181335161,3412177804,3160834842,628085408,1382605366,3423369109,3138078467,570562233,1426400815,3317316542,2998733608,733239954,1555261956, |
||
3268935591,3050360625,752459403,1541320221,2607071920,3965973030,1969922972,40735498,2617837225,3943577151,1913087877,83908371,2512341634,3803740692,2075208622,213261112,2463272603,3855990285,2094854071,198958881,2262029012,4057260610,1759359992,534414190,2176718541,4139329115,1873836001,414664567,2282248934,4279200368,1711684554,285281116,2405801727,4167216745,1634467795,376229701,2685067896,3608007406,1308918612,956543938,2808555105,3495958263,1231636301,1047427035,2932959818,3654703836,1088359270, |
||
936918E3,2847714899,3736837829,1202900863,817233897,3183342108,3401237130,1404277552,615818150,3134207493,3453421203,1423857449,601450431,3009837614,3294710456,1567103746,711928724,3020668471,3272380065,1510334235,755167117],y=u?new Uint32Array(z):z;function A(){}A.prototype.getName=function(){return this.name};A.prototype.getData=function(){return this.data};A.prototype.G=function(){return this.H};r("Zlib.GunzipMember",A);r("Zlib.GunzipMember.prototype.getName",A.prototype.getName);r("Zlib.GunzipMember.prototype.getData",A.prototype.getData);r("Zlib.GunzipMember.prototype.getMtime",A.prototype.G);function C(e){var c=e.length,d=0,b=Number.POSITIVE_INFINITY,a,f,g,k,m,q,t,h,l;for(h=0;h<c;++h)e[h]>d&&(d=e[h]),e[h]<b&&(b=e[h]);a=1<<d;f=new (u?Uint32Array:Array)(a);g=1;k=0;for(m=2;g<=d;){for(h=0;h<c;++h)if(e[h]===g){q=0;t=k;for(l=0;l<g;++l)q=q<<1|t&1,t>>=1;for(l=q;l<a;l+=m)f[l]=g<<16|h;++k}++g;k<<=1;m<<=1}return[f,d,b]};var D=[],E;for(E=0;288>E;E++)switch(!0){case 143>=E:D.push([E+48,8]);break;case 255>=E:D.push([E-144+400,9]);break;case 279>=E:D.push([E-256+0,7]);break;case 287>=E:D.push([E-280+192,8]);break;default:n("invalid literal: "+E)} |
||
var ca=function(){function e(a){switch(!0){case 3===a:return[257,a-3,0];case 4===a:return[258,a-4,0];case 5===a:return[259,a-5,0];case 6===a:return[260,a-6,0];case 7===a:return[261,a-7,0];case 8===a:return[262,a-8,0];case 9===a:return[263,a-9,0];case 10===a:return[264,a-10,0];case 12>=a:return[265,a-11,1];case 14>=a:return[266,a-13,1];case 16>=a:return[267,a-15,1];case 18>=a:return[268,a-17,1];case 22>=a:return[269,a-19,2];case 26>=a:return[270,a-23,2];case 30>=a:return[271,a-27,2];case 34>=a:return[272, |
||
a-31,2];case 42>=a:return[273,a-35,3];case 50>=a:return[274,a-43,3];case 58>=a:return[275,a-51,3];case 66>=a:return[276,a-59,3];case 82>=a:return[277,a-67,4];case 98>=a:return[278,a-83,4];case 114>=a:return[279,a-99,4];case 130>=a:return[280,a-115,4];case 162>=a:return[281,a-131,5];case 194>=a:return[282,a-163,5];case 226>=a:return[283,a-195,5];case 257>=a:return[284,a-227,5];case 258===a:return[285,a-258,0];default:n("invalid length: "+a)}}var c=[],d,b;for(d=3;258>=d;d++)b=e(d),c[d]=b[2]<<24|b[1]<< |
||
16|b[0];return c}();u&&new Uint32Array(ca);function G(e,c){this.i=[];this.j=32768;this.d=this.f=this.c=this.n=0;this.input=u?new Uint8Array(e):e;this.o=!1;this.k=H;this.w=!1;if(c||!(c={}))c.index&&(this.c=c.index),c.bufferSize&&(this.j=c.bufferSize),c.bufferType&&(this.k=c.bufferType),c.resize&&(this.w=c.resize);switch(this.k){case I:this.a=32768;this.b=new (u?Uint8Array:Array)(32768+this.j+258);break;case H:this.a=0;this.b=new (u?Uint8Array:Array)(this.j);this.e=this.D;this.q=this.A;this.l=this.C;break;default:n(Error("invalid inflate mode"))}} |
||
var I=0,H=1; |
||
G.prototype.g=function(){for(;!this.o;){var e=J(this,3);e&1&&(this.o=!0);e>>>=1;switch(e){case 0:var c=this.input,d=this.c,b=this.b,a=this.a,f=p,g=p,k=p,m=b.length,q=p;this.d=this.f=0;f=c[d++];f===p&&n(Error("invalid uncompressed block header: LEN (first byte)"));g=f;f=c[d++];f===p&&n(Error("invalid uncompressed block header: LEN (second byte)"));g|=f<<8;f=c[d++];f===p&&n(Error("invalid uncompressed block header: NLEN (first byte)"));k=f;f=c[d++];f===p&&n(Error("invalid uncompressed block header: NLEN (second byte)"));k|= |
||
f<<8;g===~k&&n(Error("invalid uncompressed block header: length verify"));d+g>c.length&&n(Error("input buffer is broken"));switch(this.k){case I:for(;a+g>b.length;){q=m-a;g-=q;if(u)b.set(c.subarray(d,d+q),a),a+=q,d+=q;else for(;q--;)b[a++]=c[d++];this.a=a;b=this.e();a=this.a}break;case H:for(;a+g>b.length;)b=this.e({t:2});break;default:n(Error("invalid inflate mode"))}if(u)b.set(c.subarray(d,d+g),a),a+=g,d+=g;else for(;g--;)b[a++]=c[d++];this.c=d;this.a=a;this.b=b;break;case 1:this.l(da,ea);break; |
||
case 2:fa(this);break;default:n(Error("unknown BTYPE: "+e))}}return this.q()}; |
||
var K=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],L=u?new Uint16Array(K):K,N=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,258,258],O=u?new Uint16Array(N):N,P=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0],Q=u?new Uint8Array(P):P,T=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577],ga=u?new Uint16Array(T):T,ha=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12, |
||
13,13],U=u?new Uint8Array(ha):ha,V=new (u?Uint8Array:Array)(288),W,ia;W=0;for(ia=V.length;W<ia;++W)V[W]=143>=W?8:255>=W?9:279>=W?7:8;var da=C(V),X=new (u?Uint8Array:Array)(30),Y,ja;Y=0;for(ja=X.length;Y<ja;++Y)X[Y]=5;var ea=C(X);function J(e,c){for(var d=e.f,b=e.d,a=e.input,f=e.c,g;b<c;)g=a[f++],g===p&&n(Error("input buffer is broken")),d|=g<<b,b+=8;g=d&(1<<c)-1;e.f=d>>>c;e.d=b-c;e.c=f;return g} |
||
function Z(e,c){for(var d=e.f,b=e.d,a=e.input,f=e.c,g=c[0],k=c[1],m,q,t;b<k;){m=a[f++];if(m===p)break;d|=m<<b;b+=8}q=g[d&(1<<k)-1];t=q>>>16;e.f=d>>t;e.d=b-t;e.c=f;return q&65535} |
||
function fa(e){function c(a,c,b){var d,e,f,g;for(g=0;g<a;)switch(d=Z(this,c),d){case 16:for(f=3+J(this,2);f--;)b[g++]=e;break;case 17:for(f=3+J(this,3);f--;)b[g++]=0;e=0;break;case 18:for(f=11+J(this,7);f--;)b[g++]=0;e=0;break;default:e=b[g++]=d}return b}var d=J(e,5)+257,b=J(e,5)+1,a=J(e,4)+4,f=new (u?Uint8Array:Array)(L.length),g,k,m,q;for(q=0;q<a;++q)f[L[q]]=J(e,3);g=C(f);k=new (u?Uint8Array:Array)(d);m=new (u?Uint8Array:Array)(b);e.l(C(c.call(e,d,g,k)),C(c.call(e,b,g,m)))} |
||
G.prototype.l=function(e,c){var d=this.b,b=this.a;this.r=e;for(var a=d.length-258,f,g,k,m;256!==(f=Z(this,e));)if(256>f)b>=a&&(this.a=b,d=this.e(),b=this.a),d[b++]=f;else{g=f-257;m=O[g];0<Q[g]&&(m+=J(this,Q[g]));f=Z(this,c);k=ga[f];0<U[f]&&(k+=J(this,U[f]));b>=a&&(this.a=b,d=this.e(),b=this.a);for(;m--;)d[b]=d[b++-k]}for(;8<=this.d;)this.d-=8,this.c--;this.a=b}; |
||
G.prototype.C=function(e,c){var d=this.b,b=this.a;this.r=e;for(var a=d.length,f,g,k,m;256!==(f=Z(this,e));)if(256>f)b>=a&&(d=this.e(),a=d.length),d[b++]=f;else{g=f-257;m=O[g];0<Q[g]&&(m+=J(this,Q[g]));f=Z(this,c);k=ga[f];0<U[f]&&(k+=J(this,U[f]));b+m>a&&(d=this.e(),a=d.length);for(;m--;)d[b]=d[b++-k]}for(;8<=this.d;)this.d-=8,this.c--;this.a=b}; |
||
G.prototype.e=function(){var e=new (u?Uint8Array:Array)(this.a-32768),c=this.a-32768,d,b,a=this.b;if(u)e.set(a.subarray(32768,e.length));else{d=0;for(b=e.length;d<b;++d)e[d]=a[d+32768]}this.i.push(e);this.n+=e.length;if(u)a.set(a.subarray(c,c+32768));else for(d=0;32768>d;++d)a[d]=a[c+d];this.a=32768;return a}; |
||
G.prototype.D=function(e){var c,d=this.input.length/this.c+1|0,b,a,f,g=this.input,k=this.b;e&&("number"===typeof e.t&&(d=e.t),"number"===typeof e.z&&(d+=e.z));2>d?(b=(g.length-this.c)/this.r[2],f=258*(b/2)|0,a=f<k.length?k.length+f:k.length<<1):a=k.length*d;u?(c=new Uint8Array(a),c.set(k)):c=k;return this.b=c}; |
||
G.prototype.q=function(){var e=0,c=this.b,d=this.i,b,a=new (u?Uint8Array:Array)(this.n+(this.a-32768)),f,g,k,m;if(0===d.length)return u?this.b.subarray(32768,this.a):this.b.slice(32768,this.a);f=0;for(g=d.length;f<g;++f){b=d[f];k=0;for(m=b.length;k<m;++k)a[e++]=b[k]}f=32768;for(g=this.a;f<g;++f)a[e++]=c[f];this.i=[];return this.buffer=a}; |
||
G.prototype.A=function(){var e,c=this.a;u?this.w?(e=new Uint8Array(c),e.set(this.b.subarray(0,c))):e=this.b.subarray(0,c):(this.b.length>c&&(this.b.length=c),e=this.b);return this.buffer=e};function $(e){this.input=e;this.c=0;this.m=[];this.s=!1}$.prototype.F=function(){this.s||this.g();return this.m.slice()}; |
||
$.prototype.g=function(){for(var e=this.input.length;this.c<e;){var c=new A,d=p,b=p,a=p,f=p,g=p,k=p,m=p,q=p,t=p,h=this.input,l=this.c;c.u=h[l++];c.v=h[l++];(31!==c.u||139!==c.v)&&n(Error("invalid file signature:"+c.u+","+c.v));c.p=h[l++];switch(c.p){case 8:break;default:n(Error("unknown compression method: "+c.p))}c.h=h[l++];q=h[l++]|h[l++]<<8|h[l++]<<16|h[l++]<<24;c.H=new Date(1E3*q);c.N=h[l++];c.M=h[l++];0<(c.h&4)&&(c.I=h[l++]|h[l++]<<8,l+=c.I);if(0<(c.h&8)){m=[];for(k=0;0<(g=h[l++]);)m[k++]=String.fromCharCode(g); |
||
c.name=m.join("")}if(0<(c.h&16)){m=[];for(k=0;0<(g=h[l++]);)m[k++]=String.fromCharCode(g);c.J=m.join("")}0<(c.h&2)&&(c.B=x(h,0,l)&65535,c.B!==(h[l++]|h[l++]<<8)&&n(Error("invalid header crc16")));d=h[h.length-4]|h[h.length-3]<<8|h[h.length-2]<<16|h[h.length-1]<<24;h.length-l-4-4<512*d&&(f=d);b=new G(h,{index:l,bufferSize:f});c.data=a=b.g();l=b.c;c.K=t=(h[l++]|h[l++]<<8|h[l++]<<16|h[l++]<<24)>>>0;x(a,p,p)!==t&&n(Error("invalid CRC-32 checksum: 0x"+x(a,p,p).toString(16)+" / 0x"+t.toString(16)));c.L= |
||
d=(h[l++]|h[l++]<<8|h[l++]<<16|h[l++]<<24)>>>0;(a.length&4294967295)!==d&&n(Error("invalid input size: "+(a.length&4294967295)+" / "+d));this.m.push(c);this.c=l}this.s=!0;var F=this.m,s,M,R=0,S=0,B;s=0;for(M=F.length;s<M;++s)S+=F[s].data.length;if(u){B=new Uint8Array(S);for(s=0;s<M;++s)B.set(F[s].data,R),R+=F[s].data.length}else{B=[];for(s=0;s<M;++s)B[s]=F[s].data;B=Array.prototype.concat.apply([],B)}return B};r("Zlib.Gunzip",$);r("Zlib.Gunzip.prototype.decompress",$.prototype.g);r("Zlib.Gunzip.prototype.getMembers",$.prototype.F);}).call(this); //@ sourceMappingURL=gunzip.min.js.map |
||
|
||
Config = window.Config || {}; |
||
Config.Schema = Config.Schema || {}; |
||
|
||
|
||
Config.Schema.MTProto = {"constructors":[{"id":"481674261","predicate":"vector","params":[],"type":"Vector t"},{"id":"85337187","predicate":"resPQ","params":[{"name":"nonce","type":"int128"},{"name":"server_nonce","type":"int128"},{"name":"pq","type":"bytes"},{"name":"server_public_key_fingerprints","type":"Vector<long>"}],"type":"ResPQ"},{"id":"-2083955988","predicate":"p_q_inner_data","params":[{"name":"pq","type":"bytes"},{"name":"p","type":"bytes"},{"name":"q","type":"bytes"},{"name":"nonce","type":"int128"},{"name":"server_nonce","type":"int128"},{"name":"new_nonce","type":"int256"}],"type":"P_Q_inner_data"},{"id":"2043348061","predicate":"server_DH_params_fail","params":[{"name":"nonce","type":"int128"},{"name":"server_nonce","type":"int128"},{"name":"new_nonce_hash","type":"int128"}],"type":"Server_DH_Params"},{"id":"-790100132","predicate":"server_DH_params_ok","params":[{"name":"nonce","type":"int128"},{"name":"server_nonce","type":"int128"},{"name":"encrypted_answer","type":"bytes"}],"type":"Server_DH_Params"},{"id":"-1249309254","predicate":"server_DH_inner_data","params":[{"name":"nonce","type":"int128"},{"name":"server_nonce","type":"int128"},{"name":"g","type":"int"},{"name":"dh_prime","type":"bytes"},{"name":"g_a","type":"bytes"},{"name":"server_time","type":"int"}],"type":"Server_DH_inner_data"},{"id":"1715713620","predicate":"client_DH_inner_data","params":[{"name":"nonce","type":"int128"},{"name":"server_nonce","type":"int128"},{"name":"retry_id","type":"long"},{"name":"g_b","type":"bytes"}],"type":"Client_DH_Inner_Data"},{"id":"1003222836","predicate":"dh_gen_ok","params":[{"name":"nonce","type":"int128"},{"name":"server_nonce","type":"int128"},{"name":"new_nonce_hash1","type":"int128"}],"type":"Set_client_DH_params_answer"},{"id":"1188831161","predicate":"dh_gen_retry","params":[{"name":"nonce","type":"int128"},{"name":"server_nonce","type":"int128"},{"name":"new_nonce_hash2","type":"int128"}],"type":"Set_client_DH_params_answer"},{"id":"-1499615742","predicate":"dh_gen_fail","params":[{"name":"nonce","type":"int128"},{"name":"server_nonce","type":"int128"},{"name":"new_nonce_hash3","type":"int128"}],"type":"Set_client_DH_params_answer"},{"id":"-212046591","predicate":"rpc_result","params":[{"name":"req_msg_id","type":"long"},{"name":"result","type":"Object"}],"type":"RpcResult"},{"id":"558156313","predicate":"rpc_error","params":[{"name":"error_code","type":"int"},{"name":"error_message","type":"string"}],"type":"RpcError"},{"id":"1579864942","predicate":"rpc_answer_unknown","params":[],"type":"RpcDropAnswer"},{"id":"-847714938","predicate":"rpc_answer_dropped_running","params":[],"type":"RpcDropAnswer"},{"id":"-1539647305","predicate":"rpc_answer_dropped","params":[{"name":"msg_id","type":"long"},{"name":"seq_no","type":"int"},{"name":"bytes","type":"int"}],"type":"RpcDropAnswer"},{"id":"155834844","predicate":"future_salt","params":[{"name":"valid_since","type":"int"},{"name":"valid_until","type":"int"},{"name":"salt","type":"long"}],"type":"FutureSalt"},{"id":"-1370486635","predicate":"future_salts","params":[{"name":"req_msg_id","type":"long"},{"name":"now","type":"int"},{"name":"salts","type":"vector<future_salt>"}],"type":"FutureSalts"},{"id":"880243653","predicate":"pong","params":[{"name":"msg_id","type":"long"},{"name":"ping_id","type":"long"}],"type":"Pong"},{"id":"-501201412","predicate":"destroy_session_ok","params":[{"name":"session_id","type":"long"}],"type":"DestroySessionRes"},{"id":"1658015945","predicate":"destroy_session_none","params":[{"name":"session_id","type":"long"}],"type":"DestroySessionRes"},{"id":"-1631450872","predicate":"new_session_created","params":[{"name":"first_msg_id","type":"long"},{"name":"unique_id","type":"long"},{"name":"server_salt","type":"long"}],"type":"NewSession"},{"id":"1945237724","predicate":"msg_container","params":[{"name":"messages","type":"vector<%Message>"}],"type":"MessageContainer"},{"id":"1538843921","predicate":"message","params":[{"name":"msg_id","type":"long"},{"name":"seqno","type":"int"},{"name":"bytes","type":"int"},{"name":"body","type":"Object"}],"type":"Message"},{"id":"-530561358","predicate":"msg_copy","params":[{"name":"orig_message","type":"Message"}],"type":"MessageCopy"},{"id":"812830625","predicate":"gzip_packed","params":[{"name":"packed_data","type":"bytes"}],"type":"Object"},{"id":"1658238041","predicate":"msgs_ack","params":[{"name":"msg_ids","type":"Vector<long>"}],"type":"MsgsAck"},{"id":"-1477445615","predicate":"bad_msg_notification","params":[{"name":"bad_msg_id","type":"long"},{"name":"bad_msg_seqno","type":"int"},{"name":"error_code","type":"int"}],"type":"BadMsgNotification"},{"id":"-307542917","predicate":"bad_server_salt","params":[{"name":"bad_msg_id","type":"long"},{"name":"bad_msg_seqno","type":"int"},{"name":"error_code","type":"int"},{"name":"new_server_salt","type":"long"}],"type":"BadMsgNotification"},{"id":"2105940488","predicate":"msg_resend_req","params":[{"name":"msg_ids","type":"Vector<long>"}],"type":"MsgResendReq"},{"id":"-630588590","predicate":"msgs_state_req","params":[{"name":"msg_ids","type":"Vector<long>"}],"type":"MsgsStateReq"},{"id":"81704317","predicate":"msgs_state_info","params":[{"name":"req_msg_id","type":"long"},{"name":"info","type":"bytes"}],"type":"MsgsStateInfo"},{"id":"-1933520591","predicate":"msgs_all_info","params":[{"name":"msg_ids","type":"Vector<long>"},{"name":"info","type":"bytes"}],"type":"MsgsAllInfo"},{"id":"661470918","predicate":"msg_detailed_info","params":[{"name":"msg_id","type":"long"},{"name":"answer_msg_id","type":"long"},{"name":"bytes","type":"int"},{"name":"status","type":"int"}],"type":"MsgDetailedInfo"},{"id":"-2137147681","predicate":"msg_new_detailed_info","params":[{"name":"answer_msg_id","type":"long"},{"name":"bytes","type":"int"},{"name":"status","type":"int"}],"type":"MsgDetailedInfo"}],"methods":[{"id":"1615239032","method":"req_pq","params":[{"name":"nonce","type":"int128"}],"type":"ResPQ"},{"id":"-686627650","method":"req_DH_params","params":[{"name":"nonce","type":"int128"},{"name":"server_nonce","type":"int128"},{"name":"p","type":"bytes"},{"name":"q","type":"bytes"},{"name":"public_key_fingerprint","type":"long"},{"name":"encrypted_data","type":"bytes"}],"type":"Server_DH_Params"},{"id":"-184262881","method":"set_client_DH_params","params":[{"name":"nonce","type":"int128"},{"name":"server_nonce","type":"int128"},{"name":"encrypted_data","type":"bytes"}],"type":"Set_client_DH_params_answer"},{"id":"1491380032","method":"rpc_drop_answer","params":[{"name":"req_msg_id","type":"long"}],"type":"RpcDropAnswer"},{"id":"-1188971260","method":"get_future_salts","params":[{"name":"num","type":"int"}],"type":"FutureSalts"},{"id":"2059302892","method":"ping","params":[{"name":"ping_id","type":"long"}],"type":"Pong"},{"id":"-213746804","method":"ping_delay_disconnect","params":[{"name":"ping_id","type":"long"},{"name":"disconnect_delay","type":"int"}],"type":"Pong"},{"id":"-414113498","method":"destroy_session","params":[{"name":"session_id","type":"long"}],"type":"DestroySessionRes"},{"id":"-1835453025","method":"http_wait","params":[{"name":"max_delay","type":"int"},{"name":"wait_after","type":"int"},{"name":"max_wait","type":"int"}],"type":"HttpWait"}]}; |
||
|
||
|
||
|
||
|
||
Config.Schema.API = {"constructors":[{"id":"-1132882121","predicate":"boolFalse","params":[],"type":"Bool"},{"id":"-1720552011","predicate":"boolTrue","params":[],"type":"Bool"},{"id":"481674261","predicate":"vector","params":[],"type":"Vector t"},{"id":"-994444869","predicate":"error","params":[{"name":"code","type":"int"},{"name":"text","type":"string"}],"type":"Error"},{"id":"1450380236","predicate":"null","params":[],"type":"Null"},{"id":"2134579434","predicate":"inputPeerEmpty","params":[],"type":"InputPeer"},{"id":"2107670217","predicate":"inputPeerSelf","params":[],"type":"InputPeer"},{"id":"270785512","predicate":"inputPeerContact","params":[{"name":"user_id","type":"int"}],"type":"InputPeer"},{"id":"-1690012891","predicate":"inputPeerForeign","params":[{"name":"user_id","type":"int"},{"name":"access_hash","type":"long"}],"type":"InputPeer"},{"id":"396093539","predicate":"inputPeerChat","params":[{"name":"chat_id","type":"int"}],"type":"InputPeer"},{"id":"-1182234929","predicate":"inputUserEmpty","params":[],"type":"InputUser"},{"id":"-138301121","predicate":"inputUserSelf","params":[],"type":"InputUser"},{"id":"-2031530139","predicate":"inputUserContact","params":[{"name":"user_id","type":"int"}],"type":"InputUser"},{"id":"1700689151","predicate":"inputUserForeign","params":[{"name":"user_id","type":"int"},{"name":"access_hash","type":"long"}],"type":"InputUser"},{"id":"-208488460","predicate":"inputPhoneContact","params":[{"name":"client_id","type":"long"},{"name":"phone","type":"string"},{"name":"first_name","type":"string"},{"name":"last_name","type":"string"}],"type":"InputContact"},{"id":"-181407105","predicate":"inputFile","params":[{"name":"id","type":"long"},{"name":"parts","type":"int"},{"name":"name","type":"string"},{"name":"md5_checksum","type":"string"}],"type":"InputFile"},{"id":"-1771768449","predicate":"inputMediaEmpty","params":[],"type":"InputMedia"},{"id":"767900285","predicate":"inputMediaUploadedPhoto","params":[{"name":"file","type":"InputFile"}],"type":"InputMedia"},{"id":"-1893027092","predicate":"inputMediaPhoto","params":[{"name":"id","type":"InputPhoto"}],"type":"InputMedia"},{"id":"-104578748","predicate":"inputMediaGeoPoint","params":[{"name":"geo_point","type":"InputGeoPoint"}],"type":"InputMedia"},{"id":"-1494984313","predicate":"inputMediaContact","params":[{"name":"phone_number","type":"string"},{"name":"first_name","type":"string"},{"name":"last_name","type":"string"}],"type":"InputMedia"},{"id":"1212668202","predicate":"inputMediaUploadedVideo","params":[{"name":"file","type":"InputFile"},{"name":"duration","type":"int"},{"name":"w","type":"int"},{"name":"h","type":"int"}],"type":"InputMedia"},{"id":"-433544891","predicate":"inputMediaUploadedThumbVideo","params":[{"name":"file","type":"InputFile"},{"name":"thumb","type":"InputFile"},{"name":"duration","type":"int"},{"name":"w","type":"int"},{"name":"h","type":"int"}],"type":"InputMedia"},{"id":"2130852582","predicate":"inputMediaVideo","params":[{"name":"id","type":"InputVideo"}],"type":"InputMedia"},{"id":"480546647","predicate":"inputChatPhotoEmpty","params":[],"type":"InputChatPhoto"},{"id":"-1809496270","predicate":"inputChatUploadedPhoto","params":[{"name":"file","type":"InputFile"},{"name":"crop","type":"InputPhotoCrop"}],"type":"InputChatPhoto"},{"id":"-1293828344","predicate":"inputChatPhoto","params":[{"name":"id","type":"InputPhoto"},{"name":"crop","type":"InputPhotoCrop"}],"type":"InputChatPhoto"},{"id":"-457104426","predicate":"inputGeoPointEmpty","params":[],"type":"InputGeoPoint"},{"id":"-206066487","predicate":"inputGeoPoint","params":[{"name":"lat","type":"double"},{"name":"long","type":"double"}],"type":"InputGeoPoint"},{"id":"483901197","predicate":"inputPhotoEmpty","params":[],"type":"InputPhoto"},{"id":"-74070332","predicate":"inputPhoto","params":[{"name":"id","type":"long"},{"name":"access_hash","type":"long"}],"type":"InputPhoto"},{"id":"1426648181","predicate":"inputVideoEmpty","params":[],"type":"InputVideo"},{"id":"-296249774","predicate":"inputVideo","params":[{"name":"id","type":"long"},{"name":"access_hash","type":"long"}],"type":"InputVideo"},{"id":"342061462","predicate":"inputFileLocation","params":[{"name":"volume_id","type":"long"},{"name":"local_id","type":"int"},{"name":"secret","type":"long"}],"type":"InputFileLocation"},{"id":"1023632620","predicate":"inputVideoFileLocation","params":[{"name":"id","type":"long"},{"name":"access_hash","type":"long"}],"type":"InputFileLocation"},{"id":"-1377390588","predicate":"inputPhotoCropAuto","params":[],"type":"InputPhotoCrop"},{"id":"-644787419","predicate":"inputPhotoCrop","params":[{"name":"crop_left","type":"double"},{"name":"crop_top","type":"double"},{"name":"crop_width","type":"double"}],"type":"InputPhotoCrop"},{"id":"1996904104","predicate":"inputAppEvent","params":[{"name":"time","type":"double"},{"name":"type","type":"string"},{"name":"peer","type":"long"},{"name":"data","type":"string"}],"type":"InputAppEvent"},{"id":"-1649296275","predicate":"peerUser","params":[{"name":"user_id","type":"int"}],"type":"Peer"},{"id":"-1160714821","predicate":"peerChat","params":[{"name":"chat_id","type":"int"}],"type":"Peer"},{"id":"-1432995067","predicate":"storage.fileUnknown","params":[],"type":"storage.FileType"},{"id":"8322574","predicate":"storage.fileJpeg","params":[],"type":"storage.FileType"},{"id":"-891180321","predicate":"storage.fileGif","params":[],"type":"storage.FileType"},{"id":"172975040","predicate":"storage.filePng","params":[],"type":"storage.FileType"},{"id":"-1373745011","predicate":"storage.filePdf","params":[],"type":"storage.FileType"},{"id":"1384777335","predicate":"storage.fileMp3","params":[],"type":"storage.FileType"},{"id":"1258941372","predicate":"storage.fileMov","params":[],"type":"storage.FileType"},{"id":"1086091090","predicate":"storage.filePartial","params":[],"type":"storage.FileType"},{"id":"-1278304028","predicate":"storage.fileMp4","params":[],"type":"storage.FileType"},{"id":"276907596","predicate":"storage.fileWebp","params":[],"type":"storage.FileType"},{"id":"2086234950","predicate":"fileLocationUnavailable","params":[{"name":"volume_id","type":"long"},{"name":"local_id","type":"int"},{"name":"secret","type":"long"}],"type":"FileLocation"},{"id":"1406570614","predicate":"fileLocation","params":[{"name":"dc_id","type":"int"},{"name":"volume_id","type":"long"},{"name":"local_id","type":"int"},{"name":"secret","type":"long"}],"type":"FileLocation"},{"id":"537022650","predicate":"userEmpty","params":[{"name":"id","type":"int"}],"type":"User"},{"id":"1912944108","predicate":"userSelf","params":[{"name":"id","type":"int"},{"name":"first_name","type":"string"},{"name":"last_name","type":"string"},{"name":"phone","type":"string"},{"name":"photo","type":"UserProfilePhoto"},{"name":"status","type":"UserStatus"},{"name":"inactive","type":"Bool"}],"type":"User"},{"id":"-218397927","predicate":"userContact","params":[{"name":"id","type":"int"},{"name":"first_name","type":"string"},{"name":"last_name","type":"string"},{"name":"access_hash","type":"long"},{"name":"phone","type":"string"},{"name":"photo","type":"UserProfilePhoto"},{"name":"status","type":"UserStatus"}],"type":"User"},{"id":"585682608","predicate":"userRequest","params":[{"name":"id","type":"int"},{"name":"first_name","type":"string"},{"name":"last_name","type":"string"},{"name":"access_hash","type":"long"},{"name":"phone","type":"string"},{"name":"photo","type":"UserProfilePhoto"},{"name":"status","type":"UserStatus"}],"type":"User"},{"id":"1377093789","predicate":"userForeign","params":[{"name":"id","type":"int"},{"name":"first_name","type":"string"},{"name":"last_name","type":"string"},{"name":"access_hash","type":"long"},{"name":"photo","type":"UserProfilePhoto"},{"name":"status","type":"UserStatus"}],"type":"User"},{"id":"-1298475060","predicate":"userDeleted","params":[{"name":"id","type":"int"},{"name":"first_name","type":"string"},{"name":"last_name","type":"string"}],"type":"User"},{"id":"1326562017","predicate":"userProfilePhotoEmpty","params":[],"type":"UserProfilePhoto"},{"id":"-715532088","predicate":"userProfilePhoto","params":[{"name":"photo_id","type":"long"},{"name":"photo_small","type":"FileLocation"},{"name":"photo_big","type":"FileLocation"}],"type":"UserProfilePhoto"},{"id":"164646985","predicate":"userStatusEmpty","params":[],"type":"UserStatus"},{"id":"-306628279","predicate":"userStatusOnline","params":[{"name":"expires","type":"int"}],"type":"UserStatus"},{"id":"9203775","predicate":"userStatusOffline","params":[{"name":"was_online","type":"int"}],"type":"UserStatus"},{"id":"-1683826688","predicate":"chatEmpty","params":[{"name":"id","type":"int"}],"type":"Chat"},{"id":"1855757255","predicate":"chat","params":[{"name":"id","type":"int"},{"name":"title","type":"string"},{"name":"photo","type":"ChatPhoto"},{"name":"participants_count","type":"int"},{"name":"date","type":"int"},{"name":"left","type":"Bool"},{"name":"version","type":"int"}],"type":"Chat"},{"id":"-83047359","predicate":"chatForbidden","params":[{"name":"id","type":"int"},{"name":"title","type":"string"},{"name":"date","type":"int"}],"type":"Chat"},{"id":"1661886910","predicate":"chatFull","params":[{"name":"id","type":"int"},{"name":"participants","type":"ChatParticipants"},{"name":"chat_photo","type":"Photo"},{"name":"notify_settings","type":"PeerNotifySettings"}],"type":"ChatFull"},{"id":"-925415106","predicate":"chatParticipant","params":[{"name":"user_id","type":"int"},{"name":"inviter_id","type":"int"},{"name":"date","type":"int"}],"type":"ChatParticipant"},{"id":"265468810","predicate":"chatParticipantsForbidden","params":[{"name":"chat_id","type":"int"}],"type":"ChatParticipants"},{"id":"2017571861","predicate":"chatParticipants","params":[{"name":"chat_id","type":"int"},{"name":"admin_id","type":"int"},{"name":"participants","type":"Vector<ChatParticipant>"},{"name":"version","type":"int"}],"type":"ChatParticipants"},{"id":"935395612","predicate":"chatPhotoEmpty","params":[],"type":"ChatPhoto"},{"id":"1632839530","predicate":"chatPhoto","params":[{"name":"photo_small","type":"FileLocation"},{"name":"photo_big","type":"FileLocation"}],"type":"ChatPhoto"},{"id":"-2082087340","predicate":"messageEmpty","params":[{"name":"id","type":"int"}],"type":"Message"},{"id":"585853626","predicate":"message","params":[{"name":"id","type":"int"},{"name":"from_id","type":"int"},{"name":"to_id","type":"Peer"},{"name":"out","type":"Bool"},{"name":"unread","type":"Bool"},{"name":"date","type":"int"},{"name":"message","type":"string"},{"name":"media","type":"MessageMedia"}],"type":"Message"},{"id":"99903492","predicate":"messageForwarded","params":[{"name":"id","type":"int"},{"name":"fwd_from_id","type":"int"},{"name":"fwd_date","type":"int"},{"name":"from_id","type":"int"},{"name":"to_id","type":"Peer"},{"name":"out","type":"Bool"},{"name":"unread","type":"Bool"},{"name":"date","type":"int"},{"name":"message","type":"string"},{"name":"media","type":"MessageMedia"}],"type":"Message"},{"id":"-1618124613","predicate":"messageService","params":[{"name":"id","type":"int"},{"name":"from_id","type":"int"},{"name":"to_id","type":"Peer"},{"name":"out","type":"Bool"},{"name":"unread","type":"Bool"},{"name":"date","type":"int"},{"name":"action","type":"MessageAction"}],"type":"Message"},{"id":"1038967584","predicate":"messageMediaEmpty","params":[],"type":"MessageMedia"},{"id":"-926655958","predicate":"messageMediaPhoto","params":[{"name":"photo","type":"Photo"}],"type":"MessageMedia"},{"id":"-1563278704","predicate":"messageMediaVideo","params":[{"name":"video","type":"Video"}],"type":"MessageMedia"},{"id":"1457575028","predicate":"messageMediaGeo","params":[{"name":"geo","type":"GeoPoint"}],"type":"MessageMedia"},{"id":"1585262393","predicate":"messageMediaContact","params":[{"name":"phone_number","type":"string"},{"name":"first_name","type":"string"},{"name":"last_name","type":"string"},{"name":"user_id","type":"int"}],"type":"MessageMedia"},{"id":"694364726","predicate":"messageMediaUnsupported","params":[{"name":"bytes","type":"bytes"}],"type":"MessageMedia"},{"id":"-1230047312","predicate":"messageActionEmpty","params":[],"type":"MessageAction"},{"id":"-1503425638","predicate":"messageActionChatCreate","params":[{"name":"title","type":"string"},{"name":"users","type":"Vector<int>"}],"type":"MessageAction"},{"id":"-1247687078","predicate":"messageActionChatEditTitle","params":[{"name":"title","type":"string"}],"type":"MessageAction"},{"id":"2144015272","predicate":"messageActionChatEditPhoto","params":[{"name":"photo","type":"Photo"}],"type":"MessageAction"},{"id":"-1780220945","predicate":"messageActionChatDeletePhoto","params":[],"type":"MessageAction"},{"id":"1581055051","predicate":"messageActionChatAddUser","params":[{"name":"user_id","type":"int"}],"type":"MessageAction"},{"id":"-1297179892","predicate":"messageActionChatDeleteUser","params":[{"name":"user_id","type":"int"}],"type":"MessageAction"},{"id":"558533855","predicate":"dialog","params":[{"name":"peer","type":"Peer"},{"name":"top_message","type":"int"},{"name":"unread_count","type":"int"}],"type":"Dialog"},{"id":"590459437","predicate":"photoEmpty","params":[{"name":"id","type":"long"}],"type":"Photo"},{"id":"582313809","predicate":"photo","params":[{"name":"id","type":"long"},{"name":"access_hash","type":"long"},{"name":"user_id","type":"int"},{"name":"date","type":"int"},{"name":"caption","type":"string"},{"name":"geo","type":"GeoPoint"},{"name":"sizes","type":"Vector<PhotoSize>"}],"type":"Photo"},{"id":"236446268","predicate":"photoSizeEmpty","params":[{"name":"type","type":"string"}],"type":"PhotoSize"},{"id":"2009052699","predicate":"photoSize","params":[{"name":"type","type":"string"},{"name":"location","type":"FileLocation"},{"name":"w","type":"int"},{"name":"h","type":"int"},{"name":"size","type":"int"}],"type":"PhotoSize"},{"id":"-374917894","predicate":"photoCachedSize","params":[{"name":"type","type":"string"},{"name":"location","type":"FileLocation"},{"name":"w","type":"int"},{"name":"h","type":"int"},{"name":"bytes","type":"bytes"}],"type":"PhotoSize"},{"id":"-1056548696","predicate":"videoEmpty","params":[{"name":"id","type":"long"}],"type":"Video"},{"id":"1510253727","predicate":"video","params":[{"name":"id","type":"long"},{"name":"access_hash","type":"long"},{"name":"user_id","type":"int"},{"name":"date","type":"int"},{"name":"caption","type":"string"},{"name":"duration","type":"int"},{"name":"size","type":"int"},{"name":"thumb","type":"PhotoSize"},{"name":"dc_id","type":"int"},{"name":"w","type":"int"},{"name":"h","type":"int"}],"type":"Video"},{"id":"286776671","predicate":"geoPointEmpty","params":[],"type":"GeoPoint"},{"id":"541710092","predicate":"geoPoint","params":[{"name":"long","type":"double"},{"name":"lat","type":"double"}],"type":"GeoPoint"},{"id":"-486486981","predicate":"auth.checkedPhone","params":[{"name":"phone_registered","type":"Bool"},{"name":"phone_invited","type":"Bool"}],"type":"auth.CheckedPhone"},{"id":"-269659687","predicate":"auth.sentCode","params":[{"name":"phone_registered","type":"Bool"},{"name":"phone_code_hash","type":"string"},{"name":"send_call_timeout","type":"int"},{"name":"is_password","type":"Bool"}],"type":"auth.SentCode"},{"id":"-155815004","predicate":"auth.authorization","params":[{"name":"expires","type":"int"},{"name":"user","type":"User"}],"type":"auth.Authorization"},{"id":"-543777747","predicate":"auth.exportedAuthorization","params":[{"name":"id","type":"int"},{"name":"bytes","type":"bytes"}],"type":"auth.ExportedAuthorization"},{"id":"-1195615476","predicate":"inputNotifyPeer","params":[{"name":"peer","type":"InputPeer"}],"type":"InputNotifyPeer"},{"id":"423314455","predicate":"inputNotifyUsers","params":[],"type":"InputNotifyPeer"},{"id":"1251338318","predicate":"inputNotifyChats","params":[],"type":"InputNotifyPeer"},{"id":"-1540769658","predicate":"inputNotifyAll","params":[],"type":"InputNotifyPeer"},{"id":"-265263912","predicate":"inputPeerNotifyEventsEmpty","params":[],"type":"InputPeerNotifyEvents"},{"id":"-395694988","predicate":"inputPeerNotifyEventsAll","params":[],"type":"InputPeerNotifyEvents"},{"id":"1185074840","predicate":"inputPeerNotifySettings","params":[{"name":"mute_until","type":"int"},{"name":"sound","type":"string"},{"name":"show_previews","type":"Bool"},{"name":"events_mask","type":"int"}],"type":"InputPeerNotifySettings"},{"id":"-1378534221","predicate":"peerNotifyEventsEmpty","params":[],"type":"PeerNotifyEvents"},{"id":"1830677896","predicate":"peerNotifyEventsAll","params":[],"type":"PeerNotifyEvents"},{"id":"1889961234","predicate":"peerNotifySettingsEmpty","params":[],"type":"PeerNotifySettings"},{"id":"-1923214866","predicate":"peerNotifySettings","params":[{"name":"mute_until","type":"int"},{"name":"sound","type":"string"},{"name":"show_previews","type":"Bool"},{"name":"events_mask","type":"int"}],"type":"PeerNotifySettings"},{"id":"-860866985","predicate":"wallPaper","params":[{"name":"id","type":"int"},{"name":"title","type":"string"},{"name":"sizes","type":"Vector<PhotoSize>"},{"name":"color","type":"int"}],"type":"WallPaper"},{"id":"1997575642","predicate":"userFull","params":[{"name":"user","type":"User"},{"name":"link","type":"contacts.Link"},{"name":"profile_photo","type":"Photo"},{"name":"notify_settings","type":"PeerNotifySettings"},{"name":"blocked","type":"Bool"},{"name":"real_first_name","type":"string"},{"name":"real_last_name","type":"string"}],"type":"UserFull"},{"id":"-116274796","predicate":"contact","params":[{"name":"user_id","type":"int"},{"name":"mutual","type":"Bool"}],"type":"Contact"},{"id":"-805141448","predicate":"importedContact","params":[{"name":"user_id","type":"int"},{"name":"client_id","type":"long"}],"type":"ImportedContact"},{"id":"1444661369","predicate":"contactBlocked","params":[{"name":"user_id","type":"int"},{"name":"date","type":"int"}],"type":"ContactBlocked"},{"id":"-360210539","predicate":"contactFound","params":[{"name":"user_id","type":"int"}],"type":"ContactFound"},{"id":"1038193057","predicate":"contactSuggested","params":[{"name":"user_id","type":"int"},{"name":"mutual_contacts","type":"int"}],"type":"ContactSuggested"},{"id":"-1434994573","predicate":"contactStatus","params":[{"name":"user_id","type":"int"},{"name":"expires","type":"int"}],"type":"ContactStatus"},{"id":"909233996","predicate":"chatLocated","params":[{"name":"chat_id","type":"int"},{"name":"distance","type":"int"}],"type":"ChatLocated"},{"id":"322183672","predicate":"contacts.foreignLinkUnknown","params":[],"type":"contacts.ForeignLink"},{"id":"-1484775609","predicate":"contacts.foreignLinkRequested","params":[{"name":"has_phone","type":"Bool"}],"type":"contacts.ForeignLink"},{"id":"468356321","predicate":"contacts.foreignLinkMutual","params":[],"type":"contacts.ForeignLink"},{"id":"-768992160","predicate":"contacts.myLinkEmpty","params":[],"type":"contacts.MyLink"},{"id":"1818882030","predicate":"contacts.myLinkRequested","params":[{"name":"contact","type":"Bool"}],"type":"contacts.MyLink"},{"id":"-1035932711","predicate":"contacts.myLinkContact","params":[],"type":"contacts.MyLink"},{"id":"-322001931","predicate":"contacts.link","params":[{"name":"my_link","type":"contacts.MyLink"},{"name":"foreign_link","type":"contacts.ForeignLink"},{"name":"user","type":"User"}],"type":"contacts.Link"},{"id":"1871416498","predicate":"contacts.contacts","params":[{"name":"contacts","type":"Vector<Contact>"},{"name":"users","type":"Vector<User>"}],"type":"contacts.Contacts"},{"id":"-1219778094","predicate":"contacts.contactsNotModified","params":[],"type":"contacts.Contacts"},{"id":"-775091636","predicate":"contacts.importedContacts","params":[{"name":"imported","type":"Vector<ImportedContact>"},{"name":"users","type":"Vector<User>"}],"type":"contacts.ImportedContacts"},{"id":"471043349","predicate":"contacts.blocked","params":[{"name":"blocked","type":"Vector<ContactBlocked>"},{"name":"users","type":"Vector<User>"}],"type":"contacts.Blocked"},{"id":"-1878523231","predicate":"contacts.blockedSlice","params":[{"name":"count","type":"int"},{"name":"blocked","type":"Vector<ContactBlocked>"},{"name":"users","type":"Vector<User>"}],"type":"contacts.Blocked"},{"id":"90570766","predicate":"contacts.found","params":[{"name":"results","type":"Vector<ContactFound>"},{"name":"users","type":"Vector<User>"}],"type":"contacts.Found"},{"id":"1447681221","predicate":"contacts.suggested","params":[{"name":"results","type":"Vector<ContactSuggested>"},{"name":"users","type":"Vector<User>"}],"type":"contacts.Suggested"},{"id":"364538944","predicate":"messages.dialogs","params":[{"name":"dialogs","type":"Vector<Dialog>"},{"name":"messages","type":"Vector<Message>"},{"name":"chats","type":"Vector<Chat>"},{"name":"users","type":"Vector<User>"}],"type":"messages.Dialogs"},{"id":"1910543603","predicate":"messages.dialogsSlice","params":[{"name":"count","type":"int"},{"name":"dialogs","type":"Vector<Dialog>"},{"name":"messages","type":"Vector<Message>"},{"name":"chats","type":"Vector<Chat>"},{"name":"users","type":"Vector<User>"}],"type":"messages.Dialogs"},{"id":"-1938715001","predicate":"messages.messages","params":[{"name":"messages","type":"Vector<Message>"},{"name":"chats","type":"Vector<Chat>"},{"name":"users","type":"Vector<User>"}],"type":"messages.Messages"},{"id":"189033187","predicate":"messages.messagesSlice","params":[{"name":"count","type":"int"},{"name":"messages","type":"Vector<Message>"},{"name":"chats","type":"Vector<Chat>"},{"name":"users","type":"Vector<User>"}],"type":"messages.Messages"},{"id":"1062078024","predicate":"messages.messageEmpty","params":[],"type":"messages.Message"},{"id":"-7289833","predicate":"messages.message","params":[{"name":"message","type":"Message"},{"name":"chats","type":"Vector<Chat>"},{"name":"users","type":"Vector<User>"}],"type":"messages.Message"},{"id":"-1768654661","predicate":"messages.statedMessages","params":[{"name":"messages","type":"Vector<Message>"},{"name":"chats","type":"Vector<Chat>"},{"name":"users","type":"Vector<User>"},{"name":"pts","type":"int"},{"name":"seq","type":"int"}],"type":"messages.StatedMessages"},{"id":"-797251802","predicate":"messages.statedMessage","params":[{"name":"message","type":"Message"},{"name":"chats","type":"Vector<Chat>"},{"name":"users","type":"Vector<User>"},{"name":"pts","type":"int"},{"name":"seq","type":"int"}],"type":"messages.StatedMessage"},{"id":"-772484260","predicate":"messages.sentMessage","params":[{"name":"id","type":"int"},{"name":"date","type":"int"},{"name":"pts","type":"int"},{"name":"seq","type":"int"}],"type":"messages.SentMessage"},{"id":"1089011754","predicate":"messages.chat","params":[{"name":"chat","type":"Chat"},{"name":"users","type":"Vector<User>"}],"type":"messages.Chat"},{"id":"-2125411368","predicate":"messages.chats","params":[{"name":"chats","type":"Vector<Chat>"},{"name":"users","type":"Vector<User>"}],"type":"messages.Chats"},{"id":"-438840932","predicate":"messages.chatFull","params":[{"name":"full_chat","type":"ChatFull"},{"name":"chats","type":"Vector<Chat>"},{"name":"users","type":"Vector<User>"}],"type":"messages.ChatFull"},{"id":"-1210173710","predicate":"messages.affectedHistory","params":[{"name":"pts","type":"int"},{"name":"seq","type":"int"},{"name":"offset","type":"int"}],"type":"messages.AffectedHistory"},{"id":"1474492012","predicate":"inputMessagesFilterEmpty","params":[],"type":"MessagesFilter"},{"id":"-1777752804","predicate":"inputMessagesFilterPhotos","params":[],"type":"MessagesFilter"},{"id":"-1614803355","predicate":"inputMessagesFilterVideo","params":[],"type":"MessagesFilter"},{"id":"1458172132","predicate":"inputMessagesFilterPhotoVideo","params":[],"type":"MessagesFilter"},{"id":"-1629621880","predicate":"inputMessagesFilterDocument","params":[],"type":"MessagesFilter"},{"id":"20626867","predicate":"updateNewMessage","params":[{"name":"message","type":"Message"},{"name":"pts","type":"int"}],"type":"Update"},{"id":"1318109142","predicate":"updateMessageID","params":[{"name":"id","type":"int"},{"name":"random_id","type":"long"}],"type":"Update"},{"id":"-966484431","predicate":"updateReadMessages","params":[{"name":"messages","type":"Vector<int>"},{"name":"pts","type":"int"}],"type":"Update"},{"id":"-1456734682","predicate":"updateDeleteMessages","params":[{"name":"messages","type":"Vector<int>"},{"name":"pts","type":"int"}],"type":"Update"},{"id":"-782376883","predicate":"updateRestoreMessages","params":[{"name":"messages","type":"Vector<int>"},{"name":"pts","type":"int"}],"type":"Update"},{"id":"1806337288","predicate":"updateUserTyping","params":[{"name":"user_id","type":"int"}],"type":"Update"},{"id":"1011273702","predicate":"updateChatUserTyping","params":[{"name":"chat_id","type":"int"},{"name":"user_id","type":"int"}],"type":"Update"},{"id":"125178264","predicate":"updateChatParticipants","params":[{"name":"participants","type":"ChatParticipants"}],"type":"Update"},{"id":"469489699","predicate":"updateUserStatus","params":[{"name":"user_id","type":"int"},{"name":"status","type":"UserStatus"}],"type":"Update"},{"id":"-635250259","predicate":"updateUserName","params":[{"name":"user_id","type":"int"},{"name":"first_name","type":"string"},{"name":"last_name","type":"string"}],"type":"Update"},{"id":"-1791935732","predicate":"updateUserPhoto","params":[{"name":"user_id","type":"int"},{"name":"date","type":"int"},{"name":"photo","type":"UserProfilePhoto"},{"name":"previous","type":"Bool"}],"type":"Update"},{"id":"628472761","predicate":"updateContactRegistered","params":[{"name":"user_id","type":"int"},{"name":"date","type":"int"}],"type":"Update"},{"id":"1369737882","predicate":"updateContactLink","params":[{"name":"user_id","type":"int"},{"name":"my_link","type":"contacts.MyLink"},{"name":"foreign_link","type":"contacts.ForeignLink"}],"type":"Update"},{"id":"1869154659","predicate":"updateActivation","params":[{"name":"user_id","type":"int"}],"type":"Update"},{"id":"-1895411046","predicate":"updateNewAuthorization","params":[{"name":"auth_key_id","type":"long"},{"name":"date","type":"int"},{"name":"device","type":"string"},{"name":"location","type":"string"}],"type":"Update"},{"id":"-1519637954","predicate":"updates.state","params":[{"name":"pts","type":"int"},{"name":"qts","type":"int"},{"name":"date","type":"int"},{"name":"seq","type":"int"},{"name":"unread_count","type":"int"}],"type":"updates.State"},{"id":"1567990072","predicate":"updates.differenceEmpty","params":[{"name":"date","type":"int"},{"name":"seq","type":"int"}],"type":"updates.Difference"},{"id":"16030880","predicate":"updates.difference","params":[{"name":"new_messages","type":"Vector<Message>"},{"name":"new_encrypted_messages","type":"Vector<EncryptedMessage>"},{"name":"other_updates","type":"Vector<Update>"},{"name":"chats","type":"Vector<Chat>"},{"name":"users","type":"Vector<User>"},{"name":"state","type":"updates.State"}],"type":"updates.Difference"},{"id":"-1459938943","predicate":"updates.differenceSlice","params":[{"name":"new_messages","type":"Vector<Message>"},{"name":"new_encrypted_messages","type":"Vector<EncryptedMessage>"},{"name":"other_updates","type":"Vector<Update>"},{"name":"chats","type":"Vector<Chat>"},{"name":"users","type":"Vector<User>"},{"name":"intermediate_state","type":"updates.State"}],"type":"updates.Difference"},{"id":"-484987010","predicate":"updatesTooLong","params":[],"type":"Updates"},{"id":"-738961532","predicate":"updateShortMessage","params":[{"name":"id","type":"int"},{"name":"from_id","type":"int"},{"name":"message","type":"string"},{"name":"pts","type":"int"},{"name":"date","type":"int"},{"name":"seq","type":"int"}],"type":"Updates"},{"id":"724548942","predicate":"updateShortChatMessage","params":[{"name":"id","type":"int"},{"name":"from_id","type":"int"},{"name":"chat_id","type":"int"},{"name":"message","type":"string"},{"name":"pts","type":"int"},{"name":"date","type":"int"},{"name":"seq","type":"int"}],"type":"Updates"},{"id":"2027216577","predicate":"updateShort","params":[{"name":"update","type":"Update"},{"name":"date","type":"int"}],"type":"Updates"},{"id":"1918567619","predicate":"updatesCombined","params":[{"name":"updates","type":"Vector<Update>"},{"name":"users","type":"Vector<User>"},{"name":"chats","type":"Vector<Chat>"},{"name":"date","type":"int"},{"name":"seq_start","type":"int"},{"name":"seq","type":"int"}],"type":"Updates"},{"id":"1957577280","predicate":"updates","params":[{"name":"updates","type":"Vector<Update>"},{"name":"users","type":"Vector<User>"},{"name":"chats","type":"Vector<Chat>"},{"name":"date","type":"int"},{"name":"seq","type":"int"}],"type":"Updates"},{"id":"-1916114267","predicate":"photos.photos","params":[{"name":"photos","type":"Vector<Photo>"},{"name":"users","type":"Vector<User>"}],"type":"photos.Photos"},{"id":"352657236","predicate":"photos.photosSlice","params":[{"name":"count","type":"int"},{"name":"photos","type":"Vector<Photo>"},{"name":"users","type":"Vector<User>"}],"type":"photos.Photos"},{"id":"539045032","predicate":"photos.photo","params":[{"name":"photo","type":"Photo"},{"name":"users","type":"Vector<User>"}],"type":"photos.Photo"},{"id":"157948117","predicate":"upload.file","params":[{"name":"type","type":"storage.FileType"},{"name":"mtime","type":"int"},{"name":"bytes","type":"bytes"}],"type":"upload.File"},{"id":"784507964","predicate":"dcOption","params":[{"name":"id","type":"int"},{"name":"hostname","type":"string"},{"name":"ip_address","type":"string"},{"name":"port","type":"int"}],"type":"DcOption"},{"id":"777313652","predicate":"config","params":[{"name":"date","type":"int"},{"name":"test_mode","type":"Bool"},{"name":"this_dc","type":"int"},{"name":"dc_options","type":"Vector<DcOption>"},{"name":"chat_size_max","type":"int"},{"name":"broadcast_size_max","type":"int"}],"type":"Config"},{"id":"-1910892683","predicate":"nearestDc","params":[{"name":"country","type":"string"},{"name":"this_dc","type":"int"},{"name":"nearest_dc","type":"int"}],"type":"NearestDc"},{"id":"-1987579119","predicate":"help.appUpdate","params":[{"name":"id","type":"int"},{"name":"critical","type":"Bool"},{"name":"url","type":"string"},{"name":"text","type":"string"}],"type":"help.AppUpdate"},{"id":"-1000708810","predicate":"help.noAppUpdate","params":[],"type":"help.AppUpdate"},{"id":"415997816","predicate":"help.inviteText","params":[{"name":"message","type":"string"}],"type":"help.InviteText"},{"id":"1047852486","predicate":"messages.statedMessagesLinks","params":[{"name":"messages","type":"Vector<Message>"},{"name":"chats","type":"Vector<Chat>"},{"name":"users","type":"Vector<User>"},{"name":"links","type":"Vector<contacts.Link>"},{"name":"pts","type":"int"},{"name":"seq","type":"int"}],"type":"messages.StatedMessages"},{"id":"-1448138623","predicate":"messages.statedMessageLink","params":[{"name":"message","type":"Message"},{"name":"chats","type":"Vector<Chat>"},{"name":"users","type":"Vector<User>"},{"name":"links","type":"Vector<contacts.Link>"},{"name":"pts","type":"int"},{"name":"seq","type":"int"}],"type":"messages.StatedMessage"},{"id":"-371504577","predicate":"messages.sentMessageLink","params":[{"name":"id","type":"int"},{"name":"date","type":"int"},{"name":"pts","type":"int"},{"name":"seq","type":"int"},{"name":"links","type":"Vector<contacts.Link>"}],"type":"messages.SentMessage"},{"id":"1960072954","predicate":"inputGeoChat","params":[{"name":"chat_id","type":"int"},{"name":"access_hash","type":"long"}],"type":"InputGeoChat"},{"id":"1301143240","predicate":"inputNotifyGeoChatPeer","params":[{"name":"peer","type":"InputGeoChat"}],"type":"InputNotifyPeer"},{"id":"1978329690","predicate":"geoChat","params":[{"name":"id","type":"int"},{"name":"access_hash","type":"long"},{"name":"title","type":"string"},{"name":"address","type":"string"},{"name":"venue","type":"string"},{"name":"geo","type":"GeoPoint"},{"name":"photo","type":"ChatPhoto"},{"name":"participants_count","type":"int"},{"name":"date","type":"int"},{"name":"checked_in","type":"Bool"},{"name":"version","type":"int"}],"type":"Chat"},{"id":"1613830811","predicate":"geoChatMessageEmpty","params":[{"name":"chat_id","type":"int"},{"name":"id","type":"int"}],"type":"GeoChatMessage"},{"id":"1158019297","predicate":"geoChatMessage","params":[{"name":"chat_id","type":"int"},{"name":"id","type":"int"},{"name":"from_id","type":"int"},{"name":"date","type":"int"},{"name":"message","type":"string"},{"name":"media","type":"MessageMedia"}],"type":"GeoChatMessage"},{"id":"-749755826","predicate":"geoChatMessageService","params":[{"name":"chat_id","type":"int"},{"name":"id","type":"int"},{"name":"from_id","type":"int"},{"name":"date","type":"int"},{"name":"action","type":"MessageAction"}],"type":"GeoChatMessage"},{"id":"397498251","predicate":"geochats.statedMessage","params":[{"name":"message","type":"GeoChatMessage"},{"name":"chats","type":"Vector<Chat>"},{"name":"users","type":"Vector<User>"},{"name":"seq","type":"int"}],"type":"geochats.StatedMessage"},{"id":"1224651367","predicate":"geochats.located","params":[{"name":"results","type":"Vector<ChatLocated>"},{"name":"messages","type":"Vector<GeoChatMessage>"},{"name":"chats","type":"Vector<Chat>"},{"name":"users","type":"Vector<User>"}],"type":"geochats.Located"},{"id":"-783127119","predicate":"geochats.messages","params":[{"name":"messages","type":"Vector<GeoChatMessage>"},{"name":"chats","type":"Vector<Chat>"},{"name":"users","type":"Vector<User>"}],"type":"geochats.Messages"},{"id":"-1135057944","predicate":"geochats.messagesSlice","params":[{"name":"count","type":"int"},{"name":"messages","type":"Vector<GeoChatMessage>"},{"name":"chats","type":"Vector<Chat>"},{"name":"users","type":"Vector<User>"}],"type":"geochats.Messages"},{"id":"1862504124","predicate":"messageActionGeoChatCreate","params":[{"name":"title","type":"string"},{"name":"address","type":"string"}],"type":"MessageAction"},{"id":"209540062","predicate":"messageActionGeoChatCheckin","params":[],"type":"MessageAction"},{"id":"1516823543","predicate":"updateNewGeoChatMessage","params":[{"name":"message","type":"GeoChatMessage"}],"type":"Update"},{"id":"1662091044","predicate":"wallPaperSolid","params":[{"name":"id","type":"int"},{"name":"title","type":"string"},{"name":"bg_color","type":"int"},{"name":"color","type":"int"}],"type":"WallPaper"},{"id":"314359194","predicate":"updateNewEncryptedMessage","params":[{"name":"message","type":"EncryptedMessage"},{"name":"qts","type":"int"}],"type":"Update"},{"id":"386986326","predicate":"updateEncryptedChatTyping","params":[{"name":"chat_id","type":"int"}],"type":"Update"},{"id":"-1264392051","predicate":"updateEncryption","params":[{"name":"chat","type":"EncryptedChat"},{"name":"date","type":"int"}],"type":"Update"},{"id":"956179895","predicate":"updateEncryptedMessagesRead","params":[{"name":"chat_id","type":"int"},{"name":"max_date","type":"int"},{"name":"date","type":"int"}],"type":"Update"},{"id":"-1417756512","predicate":"encryptedChatEmpty","params":[{"name":"id","type":"int"}],"type":"EncryptedChat"},{"id":"1006044124","predicate":"encryptedChatWaiting","params":[{"name":"id","type":"int"},{"name":"access_hash","type":"long"},{"name":"date","type":"int"},{"name":"admin_id","type":"int"},{"name":"participant_id","type":"int"}],"type":"EncryptedChat"},{"id":"-931638658","predicate":"encryptedChatRequested","params":[{"name":"id","type":"int"},{"name":"access_hash","type":"long"},{"name":"date","type":"int"},{"name":"admin_id","type":"int"},{"name":"participant_id","type":"int"},{"name":"g_a","type":"bytes"}],"type":"EncryptedChat"},{"id":"-94974410","predicate":"encryptedChat","params":[{"name":"id","type":"int"},{"name":"access_hash","type":"long"},{"name":"date","type":"int"},{"name":"admin_id","type":"int"},{"name":"participant_id","type":"int"},{"name":"g_a_or_b","type":"bytes"},{"name":"key_fingerprint","type":"long"}],"type":"EncryptedChat"},{"id":"332848423","predicate":"encryptedChatDiscarded","params":[{"name":"id","type":"int"}],"type":"EncryptedChat"},{"id":"-247351839","predicate":"inputEncryptedChat","params":[{"name":"chat_id","type":"int"},{"name":"access_hash","type":"long"}],"type":"InputEncryptedChat"},{"id":"-1038136962","predicate":"encryptedFileEmpty","params":[],"type":"EncryptedFile"},{"id":"1248893260","predicate":"encryptedFile","params":[{"name":"id","type":"long"},{"name":"access_hash","type":"long"},{"name":"size","type":"int"},{"name":"dc_id","type":"int"},{"name":"key_fingerprint","type":"int"}],"type":"EncryptedFile"},{"id":"406307684","predicate":"inputEncryptedFileEmpty","params":[],"type":"InputEncryptedFile"},{"id":"1690108678","predicate":"inputEncryptedFileUploaded","params":[{"name":"id","type":"long"},{"name":"parts","type":"int"},{"name":"md5_checksum","type":"string"},{"name":"key_fingerprint","type":"int"}],"type":"InputEncryptedFile"},{"id":"1511503333","predicate":"inputEncryptedFile","params":[{"name":"id","type":"long"},{"name":"access_hash","type":"long"}],"type":"InputEncryptedFile"},{"id":"-182231723","predicate":"inputEncryptedFileLocation","params":[{"name":"id","type":"long"},{"name":"access_hash","type":"long"}],"type":"InputFileLocation"},{"id":"-317144808","predicate":"encryptedMessage","params":[{"name":"random_id","type":"long"},{"name":"chat_id","type":"int"},{"name":"date","type":"int"},{"name":"bytes","type":"bytes"},{"name":"file","type":"EncryptedFile"}],"type":"EncryptedMessage"},{"id":"594758406","predicate":"encryptedMessageService","params":[{"name":"random_id","type":"long"},{"name":"chat_id","type":"int"},{"name":"date","type":"int"},{"name":"bytes","type":"bytes"}],"type":"EncryptedMessage"},{"id":"-1717290801","predicate":"decryptedMessageLayer","params":[{"name":"layer","type":"int"},{"name":"message","type":"DecryptedMessage"}],"type":"DecryptedMessageLayer"},{"id":"528568095","predicate":"decryptedMessage","params":[{"name":"random_id","type":"long"},{"name":"random_bytes","type":"bytes"},{"name":"message","type":"string"},{"name":"media","type":"DecryptedMessageMedia"}],"type":"DecryptedMessage"},{"id":"-1438109059","predicate":"decryptedMessageService","params":[{"name":"random_id","type":"long"},{"name":"random_bytes","type":"bytes"},{"name":"action","type":"DecryptedMessageAction"}],"type":"DecryptedMessage"},{"id":"144661578","predicate":"decryptedMessageMediaEmpty","params":[],"type":"DecryptedMessageMedia"},{"id":"846826124","predicate":"decryptedMessageMediaPhoto","params":[{"name":"thumb","type":"bytes"},{"name":"thumb_w","type":"int"},{"name":"thumb_h","type":"int"},{"name":"w","type":"int"},{"name":"h","type":"int"},{"name":"size","type":"int"},{"name":"key","type":"bytes"},{"name":"iv","type":"bytes"}],"type":"DecryptedMessageMedia"},{"id":"1290694387","predicate":"decryptedMessageMediaVideo","params":[{"name":"thumb","type":"bytes"},{"name":"thumb_w","type":"int"},{"name":"thumb_h","type":"int"},{"name":"duration","type":"int"},{"name":"w","type":"int"},{"name":"h","type":"int"},{"name":"size","type":"int"},{"name":"key","type":"bytes"},{"name":"iv","type":"bytes"}],"type":"DecryptedMessageMedia"},{"id":"893913689","predicate":"decryptedMessageMediaGeoPoint","params":[{"name":"lat","type":"double"},{"name":"long","type":"double"}],"type":"DecryptedMessageMedia"},{"id":"1485441687","predicate":"decryptedMessageMediaContact","params":[{"name":"phone_number","type":"string"},{"name":"first_name","type":"string"},{"name":"last_name","type":"string"},{"name":"user_id","type":"int"}],"type":"DecryptedMessageMedia"},{"id":"-1586283796","predicate":"decryptedMessageActionSetMessageTTL","params":[{"name":"ttl_seconds","type":"int"}],"type":"DecryptedMessageAction"},{"id":"-1058912715","predicate":"messages.dhConfigNotModified","params":[{"name":"random","type":"bytes"}],"type":"messages.DhConfig"},{"id":"740433629","predicate":"messages.dhConfig","params":[{"name":"g","type":"int"},{"name":"p","type":"bytes"},{"name":"version","type":"int"},{"name":"random","type":"bytes"}],"type":"messages.DhConfig"},{"id":"1443858741","predicate":"messages.sentEncryptedMessage","params":[{"name":"date","type":"int"}],"type":"messages.SentEncryptedMessage"},{"id":"-1802240206","predicate":"messages.sentEncryptedFile","params":[{"name":"date","type":"int"},{"name":"file","type":"EncryptedFile"}],"type":"messages.SentEncryptedMessage"},{"id":"-95482955","predicate":"inputFileBig","params":[{"name":"id","type":"long"},{"name":"parts","type":"int"},{"name":"name","type":"string"}],"type":"InputFile"},{"id":"767652808","predicate":"inputEncryptedFileBigUploaded","params":[{"name":"id","type":"long"},{"name":"parts","type":"int"},{"name":"key_fingerprint","type":"int"}],"type":"InputEncryptedFile"},{"id":"974056226","predicate":"updateChatParticipantAdd","params":[{"name":"chat_id","type":"int"},{"name":"user_id","type":"int"},{"name":"inviter_id","type":"int"},{"name":"version","type":"int"}],"type":"Update"},{"id":"1851755554","predicate":"updateChatParticipantDelete","params":[{"name":"chat_id","type":"int"},{"name":"user_id","type":"int"},{"name":"version","type":"int"}],"type":"Update"},{"id":"-1906403213","predicate":"updateDcOptions","params":[{"name":"dc_options","type":"Vector<DcOption>"}],"type":"Update"},{"id":"1638323254","predicate":"inputMediaUploadedAudio","params":[{"name":"file","type":"InputFile"},{"name":"duration","type":"int"}],"type":"InputMedia"},{"id":"-1986820223","predicate":"inputMediaAudio","params":[{"name":"id","type":"InputAudio"}],"type":"InputMedia"},{"id":"887592125","predicate":"inputMediaUploadedDocument","params":[{"name":"file","type":"InputFile"},{"name":"file_name","type":"string"},{"name":"mime_type","type":"string"}],"type":"InputMedia"},{"id":"1044831837","predicate":"inputMediaUploadedThumbDocument","params":[{"name":"file","type":"InputFile"},{"name":"thumb","type":"InputFile"},{"name":"file_name","type":"string"},{"name":"mime_type","type":"string"}],"type":"InputMedia"},{"id":"-779818943","predicate":"inputMediaDocument","params":[{"name":"id","type":"InputDocument"}],"type":"InputMedia"},{"id":"802824708","predicate":"messageMediaDocument","params":[{"name":"document","type":"Document"}],"type":"MessageMedia"},{"id":"-961117440","predicate":"messageMediaAudio","params":[{"name":"audio","type":"Audio"}],"type":"MessageMedia"},{"id":"-648356732","predicate":"inputAudioEmpty","params":[],"type":"InputAudio"},{"id":"2010398975","predicate":"inputAudio","params":[{"name":"id","type":"long"},{"name":"access_hash","type":"long"}],"type":"InputAudio"},{"id":"1928391342","predicate":"inputDocumentEmpty","params":[],"type":"InputDocument"},{"id":"410618194","predicate":"inputDocument","params":[{"name":"id","type":"long"},{"name":"access_hash","type":"long"}],"type":"InputDocument"},{"id":"1960591437","predicate":"inputAudioFileLocation","params":[{"name":"id","type":"long"},{"name":"access_hash","type":"long"}],"type":"InputFileLocation"},{"id":"1313188841","predicate":"inputDocumentFileLocation","params":[{"name":"id","type":"long"},{"name":"access_hash","type":"long"}],"type":"InputFileLocation"},{"id":"-1332395189","predicate":"decryptedMessageMediaDocument","params":[{"name":"thumb","type":"bytes"},{"name":"thumb_w","type":"int"},{"name":"thumb_h","type":"int"},{"name":"file_name","type":"string"},{"name":"mime_type","type":"string"},{"name":"size","type":"int"},{"name":"key","type":"bytes"},{"name":"iv","type":"bytes"}],"type":"DecryptedMessageMedia"},{"id":"1619031439","predicate":"decryptedMessageMediaAudio","params":[{"name":"duration","type":"int"},{"name":"size","type":"int"},{"name":"key","type":"bytes"},{"name":"iv","type":"bytes"}],"type":"DecryptedMessageMedia"},{"id":"1483311320","predicate":"audioEmpty","params":[{"name":"id","type":"long"}],"type":"Audio"},{"id":"1114908135","predicate":"audio","params":[{"name":"id","type":"long"},{"name":"access_hash","type":"long"},{"name":"user_id","type":"int"},{"name":"date","type":"int"},{"name":"duration","type":"int"},{"name":"size","type":"int"},{"name":"dc_id","type":"int"}],"type":"Audio"},{"id":"922273905","predicate":"documentEmpty","params":[{"name":"id","type":"long"}],"type":"Document"},{"id":"-1627626714","predicate":"document","params":[{"name":"id","type":"long"},{"name":"access_hash","type":"long"},{"name":"user_id","type":"int"},{"name":"date","type":"int"},{"name":"file_name","type":"string"},{"name":"mime_type","type":"string"},{"name":"size","type":"int"},{"name":"thumb","type":"PhotoSize"},{"name":"dc_id","type":"int"}],"type":"Document"},{"id":"398898678","predicate":"help.support","params":[{"name":"phone_number","type":"string"},{"name":"user","type":"User"}],"type":"help.Support"}],"methods":[{"id":"-878758099","method":"invokeAfterMsg","params":[{"name":"msg_id","type":"long"},{"name":"query","type":"!X"}],"type":"X"},{"id":"1036301552","method":"invokeAfterMsgs","params":[{"name":"msg_ids","type":"Vector<long>"},{"name":"query","type":"!X"}],"type":"X"},{"id":"1877286395","method":"auth.checkPhone","params":[{"name":"phone_number","type":"string"}],"type":"auth.CheckedPhone"},{"id":"1988976461","method":"auth.sendCode","params":[{"name":"phone_number","type":"string"},{"name":"sms_type","type":"int"},{"name":"api_id","type":"int"},{"name":"api_hash","type":"string"},{"name":"lang_code","type":"string"}],"type":"auth.SentCode"},{"id":"63247716","method":"auth.sendCall","params":[{"name":"phone_number","type":"string"},{"name":"phone_code_hash","type":"string"}],"type":"Bool"},{"id":"453408308","method":"auth.signUp","params":[{"name":"phone_number","type":"string"},{"name":"phone_code_hash","type":"string"},{"name":"phone_code","type":"string"},{"name":"first_name","type":"string"},{"name":"last_name","type":"string"}],"type":"auth.Authorization"},{"id":"-1126886015","method":"auth.signIn","params":[{"name":"phone_number","type":"string"},{"name":"phone_code_hash","type":"string"},{"name":"phone_code","type":"string"}],"type":"auth.Authorization"},{"id":"1461180992","method":"auth.logOut","params":[],"type":"Bool"},{"id":"-1616179942","method":"auth.resetAuthorizations","params":[],"type":"Bool"},{"id":"1998331287","method":"auth.sendInvites","params":[{"name":"phone_numbers","type":"Vector<string>"},{"name":"message","type":"string"}],"type":"Bool"},{"id":"-440401971","method":"auth.exportAuthorization","params":[{"name":"dc_id","type":"int"}],"type":"auth.ExportedAuthorization"},{"id":"-470837741","method":"auth.importAuthorization","params":[{"name":"id","type":"int"},{"name":"bytes","type":"bytes"}],"type":"auth.Authorization"},{"id":"1147957548","method":"account.registerDevice","params":[{"name":"token_type","type":"int"},{"name":"token","type":"string"},{"name":"device_model","type":"string"},{"name":"system_version","type":"string"},{"name":"app_version","type":"string"},{"name":"app_sandbox","type":"Bool"},{"name":"lang_code","type":"string"}],"type":"Bool"},{"id":"1707432768","method":"account.unregisterDevice","params":[{"name":"token_type","type":"int"},{"name":"token","type":"string"}],"type":"Bool"},{"id":"-2067899501","method":"account.updateNotifySettings","params":[{"name":"peer","type":"InputNotifyPeer"},{"name":"settings","type":"InputPeerNotifySettings"}],"type":"Bool"},{"id":"313765169","method":"account.getNotifySettings","params":[{"name":"peer","type":"InputNotifyPeer"}],"type":"PeerNotifySettings"},{"id":"-612493497","method":"account.resetNotifySettings","params":[],"type":"Bool"},{"id":"-259486360","method":"account.updateProfile","params":[{"name":"first_name","type":"string"},{"name":"last_name","type":"string"}],"type":"User"},{"id":"1713919532","method":"account.updateStatus","params":[{"name":"offline","type":"Bool"}],"type":"Bool"},{"id":"-1068696894","method":"account.getWallPapers","params":[],"type":"Vector<WallPaper>"},{"id":"227648840","method":"users.getUsers","params":[{"name":"id","type":"Vector<InputUser>"}],"type":"Vector<User>"},{"id":"-902781519","method":"users.getFullUser","params":[{"name":"id","type":"InputUser"}],"type":"UserFull"},{"id":"-995929106","method":"contacts.getStatuses","params":[],"type":"Vector<ContactStatus>"},{"id":"583445000","method":"contacts.getContacts","params":[{"name":"hash","type":"string"}],"type":"contacts.Contacts"},{"id":"-634342611","method":"contacts.importContacts","params":[{"name":"contacts","type":"Vector<InputContact>"},{"name":"replace","type":"Bool"}],"type":"contacts.ImportedContacts"},{"id":"301470424","method":"contacts.search","params":[{"name":"q","type":"string"},{"name":"limit","type":"int"}],"type":"contacts.Found"},{"id":"-847825880","method":"contacts.getSuggested","params":[{"name":"limit","type":"int"}],"type":"contacts.Suggested"},{"id":"-1902823612","method":"contacts.deleteContact","params":[{"name":"id","type":"InputUser"}],"type":"contacts.Link"},{"id":"1504393374","method":"contacts.deleteContacts","params":[{"name":"id","type":"Vector<InputUser>"}],"type":"Bool"},{"id":"858475004","method":"contacts.block","params":[{"name":"id","type":"InputUser"}],"type":"Bool"},{"id":"-448724803","method":"contacts.unblock","params":[{"name":"id","type":"InputUser"}],"type":"Bool"},{"id":"-176409329","method":"contacts.getBlocked","params":[{"name":"offset","type":"int"},{"name":"limit","type":"int"}],"type":"contacts.Blocked"},{"id":"1109588596","method":"messages.getMessages","params":[{"name":"id","type":"Vector<int>"}],"type":"messages.Messages"},{"id":"-321970698","method":"messages.getDialogs","params":[{"name":"offset","type":"int"},{"name":"max_id","type":"int"},{"name":"limit","type":"int"}],"type":"messages.Dialogs"},{"id":"-1834885329","method":"messages.getHistory","params":[{"name":"peer","type":"InputPeer"},{"name":"offset","type":"int"},{"name":"max_id","type":"int"},{"name":"limit","type":"int"}],"type":"messages.Messages"},{"id":"132772523","method":"messages.search","params":[{"name":"peer","type":"InputPeer"},{"name":"q","type":"string"},{"name":"filter","type":"MessagesFilter"},{"name":"min_date","type":"int"},{"name":"max_date","type":"int"},{"name":"offset","type":"int"},{"name":"max_id","type":"int"},{"name":"limit","type":"int"}],"type":"messages.Messages"},{"id":"-1336990448","method":"messages.readHistory","params":[{"name":"peer","type":"InputPeer"},{"name":"max_id","type":"int"},{"name":"offset","type":"int"}],"type":"messages.AffectedHistory"},{"id":"-185009311","method":"messages.deleteHistory","params":[{"name":"peer","type":"InputPeer"},{"name":"offset","type":"int"}],"type":"messages.AffectedHistory"},{"id":"351460618","method":"messages.deleteMessages","params":[{"name":"id","type":"Vector<int>"}],"type":"Vector<int>"},{"id":"962567550","method":"messages.restoreMessages","params":[{"name":"id","type":"Vector<int>"}],"type":"Vector<int>"},{"id":"682347368","method":"messages.receivedMessages","params":[{"name":"max_id","type":"int"}],"type":"Vector<int>"},{"id":"1905801705","method":"messages.setTyping","params":[{"name":"peer","type":"InputPeer"},{"name":"typing","type":"Bool"}],"type":"Bool"},{"id":"1289620139","method":"messages.sendMessage","params":[{"name":"peer","type":"InputPeer"},{"name":"message","type":"string"},{"name":"random_id","type":"long"}],"type":"messages.SentMessage"},{"id":"-1547149962","method":"messages.sendMedia","params":[{"name":"peer","type":"InputPeer"},{"name":"media","type":"InputMedia"},{"name":"random_id","type":"long"}],"type":"messages.StatedMessage"},{"id":"1363988751","method":"messages.forwardMessages","params":[{"name":"peer","type":"InputPeer"},{"name":"id","type":"Vector<int>"}],"type":"messages.StatedMessages"},{"id":"1013621127","method":"messages.getChats","params":[{"name":"id","type":"Vector<int>"}],"type":"messages.Chats"},{"id":"998448230","method":"messages.getFullChat","params":[{"name":"chat_id","type":"int"}],"type":"messages.ChatFull"},{"id":"-1262720843","method":"messages.editChatTitle","params":[{"name":"chat_id","type":"int"},{"name":"title","type":"string"}],"type":"messages.StatedMessage"},{"id":"-662601187","method":"messages.editChatPhoto","params":[{"name":"chat_id","type":"int"},{"name":"photo","type":"InputChatPhoto"}],"type":"messages.StatedMessage"},{"id":"787082910","method":"messages.addChatUser","params":[{"name":"chat_id","type":"int"},{"name":"user_id","type":"InputUser"},{"name":"fwd_limit","type":"int"}],"type":"messages.StatedMessage"},{"id":"-1010447069","method":"messages.deleteChatUser","params":[{"name":"chat_id","type":"int"},{"name":"user_id","type":"InputUser"}],"type":"messages.StatedMessage"},{"id":"1100847854","method":"messages.createChat","params":[{"name":"users","type":"Vector<InputUser>"},{"name":"title","type":"string"}],"type":"messages.StatedMessage"},{"id":"-304838614","method":"updates.getState","params":[],"type":"updates.State"},{"id":"168039573","method":"updates.getDifference","params":[{"name":"pts","type":"int"},{"name":"date","type":"int"},{"name":"qts","type":"int"}],"type":"updates.Difference"},{"id":"-285902432","method":"photos.updateProfilePhoto","params":[{"name":"id","type":"InputPhoto"},{"name":"crop","type":"InputPhotoCrop"}],"type":"UserProfilePhoto"},{"id":"-720397176","method":"photos.uploadProfilePhoto","params":[{"name":"file","type":"InputFile"},{"name":"caption","type":"string"},{"name":"geo_point","type":"InputGeoPoint"},{"name":"crop","type":"InputPhotoCrop"}],"type":"photos.Photo"},{"id":"-1291540959","method":"upload.saveFilePart","params":[{"name":"file_id","type":"long"},{"name":"file_part","type":"int"},{"name":"bytes","type":"bytes"}],"type":"Bool"},{"id":"-475607115","method":"upload.getFile","params":[{"name":"location","type":"InputFileLocation"},{"name":"offset","type":"int"},{"name":"limit","type":"int"}],"type":"upload.File"},{"id":"-990308245","method":"help.getConfig","params":[],"type":"Config"},{"id":"531836966","method":"help.getNearestDc","params":[],"type":"NearestDc"},{"id":"-938300290","method":"help.getAppUpdate","params":[{"name":"device_model","type":"string"},{"name":"system_version","type":"string"},{"name":"app_version","type":"string"},{"name":"lang_code","type":"string"}],"type":"help.AppUpdate"},{"id":"1862465352","method":"help.saveAppLog","params":[{"name":"events","type":"Vector<InputAppEvent>"}],"type":"Bool"},{"id":"-1532407418","method":"help.getInviteText","params":[{"name":"lang_code","type":"string"}],"type":"help.InviteText"},{"id":"-1209117380","method":"photos.getUserPhotos","params":[{"name":"user_id","type":"InputUser"},{"name":"offset","type":"int"},{"name":"max_id","type":"int"},{"name":"limit","type":"int"}],"type":"photos.Photos"},{"id":"66319602","method":"messages.forwardMessage","params":[{"name":"peer","type":"InputPeer"},{"name":"id","type":"int"},{"name":"random_id","type":"long"}],"type":"messages.StatedMessage"},{"id":"1102776690","method":"messages.sendBroadcast","params":[{"name":"contacts","type":"Vector<InputUser>"},{"name":"message","type":"string"},{"name":"media","type":"InputMedia"}],"type":"messages.StatedMessages"},{"id":"2132356495","method":"geochats.getLocated","params":[{"name":"geo_point","type":"InputGeoPoint"},{"name":"radius","type":"int"},{"name":"limit","type":"int"}],"type":"geochats.Located"},{"id":"-515735953","method":"geochats.getRecents","params":[{"name":"offset","type":"int"},{"name":"limit","type":"int"}],"type":"geochats.Messages"},{"id":"1437853947","method":"geochats.checkin","params":[{"name":"peer","type":"InputGeoChat"}],"type":"geochats.StatedMessage"},{"id":"1730338159","method":"geochats.getFullChat","params":[{"name":"peer","type":"InputGeoChat"}],"type":"messages.ChatFull"},{"id":"1284383347","method":"geochats.editChatTitle","params":[{"name":"peer","type":"InputGeoChat"},{"name":"title","type":"string"},{"name":"address","type":"string"}],"type":"geochats.StatedMessage"},{"id":"903355029","method":"geochats.editChatPhoto","params":[{"name":"peer","type":"InputGeoChat"},{"name":"photo","type":"InputChatPhoto"}],"type":"geochats.StatedMessage"},{"id":"-808598451","method":"geochats.search","params":[{"name":"peer","type":"InputGeoChat"},{"name":"q","type":"string"},{"name":"filter","type":"MessagesFilter"},{"name":"min_date","type":"int"},{"name":"max_date","type":"int"},{"name":"offset","type":"int"},{"name":"max_id","type":"int"},{"name":"limit","type":"int"}],"type":"geochats.Messages"},{"id":"-1254131096","method":"geochats.getHistory","params":[{"name":"peer","type":"InputGeoChat"},{"name":"offset","type":"int"},{"name":"max_id","type":"int"},{"name":"limit","type":"int"}],"type":"geochats.Messages"},{"id":"146319145","method":"geochats.setTyping","params":[{"name":"peer","type":"InputGeoChat"},{"name":"typing","type":"Bool"}],"type":"Bool"},{"id":"102432836","method":"geochats.sendMessage","params":[{"name":"peer","type":"InputGeoChat"},{"name":"message","type":"string"},{"name":"random_id","type":"long"}],"type":"geochats.StatedMessage"},{"id":"-1192173825","method":"geochats.sendMedia","params":[{"name":"peer","type":"InputGeoChat"},{"name":"media","type":"InputMedia"},{"name":"random_id","type":"long"}],"type":"geochats.StatedMessage"},{"id":"235482646","method":"geochats.createGeoChat","params":[{"name":"title","type":"string"},{"name":"geo_point","type":"InputGeoPoint"},{"name":"address","type":"string"},{"name":"venue","type":"string"}],"type":"geochats.StatedMessage"},{"id":"651135312","method":"messages.getDhConfig","params":[{"name":"version","type":"int"},{"name":"random_length","type":"int"}],"type":"messages.DhConfig"},{"id":"-162681021","method":"messages.requestEncryption","params":[{"name":"user_id","type":"InputUser"},{"name":"random_id","type":"int"},{"name":"g_a","type":"bytes"}],"type":"EncryptedChat"},{"id":"1035731989","method":"messages.acceptEncryption","params":[{"name":"peer","type":"InputEncryptedChat"},{"name":"g_b","type":"bytes"},{"name":"key_fingerprint","type":"long"}],"type":"EncryptedChat"},{"id":"-304536635","method":"messages.discardEncryption","params":[{"name":"chat_id","type":"int"}],"type":"Bool"},{"id":"2031374829","method":"messages.setEncryptedTyping","params":[{"name":"peer","type":"InputEncryptedChat"},{"name":"typing","type":"Bool"}],"type":"Bool"},{"id":"2135648522","method":"messages.readEncryptedHistory","params":[{"name":"peer","type":"InputEncryptedChat"},{"name":"max_date","type":"int"}],"type":"Bool"},{"id":"-1451792525","method":"messages.sendEncrypted","params":[{"name":"peer","type":"InputEncryptedChat"},{"name":"random_id","type":"long"},{"name":"data","type":"bytes"}],"type":"messages.SentEncryptedMessage"},{"id":"-1701831834","method":"messages.sendEncryptedFile","params":[{"name":"peer","type":"InputEncryptedChat"},{"name":"random_id","type":"long"},{"name":"data","type":"bytes"},{"name":"file","type":"InputEncryptedFile"}],"type":"messages.SentEncryptedMessage"},{"id":"852769188","method":"messages.sendEncryptedService","params":[{"name":"peer","type":"InputEncryptedChat"},{"name":"random_id","type":"long"},{"name":"data","type":"bytes"}],"type":"messages.SentEncryptedMessage"},{"id":"1436924774","method":"messages.receivedQueue","params":[{"name":"max_qts","type":"int"}],"type":"Vector<long>"},{"id":"-562337987","method":"upload.saveBigFilePart","params":[{"name":"file_id","type":"long"},{"name":"file_part","type":"int"},{"name":"file_total_parts","type":"int"},{"name":"bytes","type":"bytes"}],"type":"Bool"},{"id":"1769565673","method":"initConnection","params":[{"name":"api_id","type":"int"},{"name":"device_model","type":"string"},{"name":"system_version","type":"string"},{"name":"app_version","type":"string"},{"name":"lang_code","type":"string"},{"name":"query","type":"!X"}],"type":"X"},{"id":"-1663104819","method":"help.getSupport","params":[],"type":"help.Support"},{"id":"-576320196","method":"invokeWithLayer12","params":[{"name":"query","type":"!X"}],"type":"X"}]}; |
||
|
||
Config.Schema.API.layer = 12; |
||
|
||
Config.Emoji = {"00a9":["\u00A9",["copyright"]],"00ae":["\u00AE",["registered"]],"203c":["\u203C",["bangbang"]],"2049":["\u2049",["interrobang"]],"2122":["\u2122",["tm"]],"2139":["\u2139",["information_source"]],"2194":["\u2194",["left_right_arrow"]],"2195":["\u2195",["arrow_up_down"]],"2196":["\u2196",["arrow_upper_left"]],"2197":["\u2197",["arrow_upper_right"]],"2198":["\u2198",["arrow_lower_right"]],"2199":["\u2199",["arrow_lower_left"]],"21a9":["\u21A9",["leftwards_arrow_with_hook"]],"21aa":["\u21AA",["arrow_right_hook"]],"231a":["\u231A",["watch"]],"231b":["\u231B",["hourglass"]],"23e9":["\u23E9",["fast_forward"]],"23ea":["\u23EA",["rewind"]],"23eb":["\u23EB",["arrow_double_up"]],"23ec":["\u23EC",["arrow_double_down"]],"23f0":["\u23F0",["alarm_clock"]],"23f3":["\u23F3",["hourglass_flowing_sand"]],"24c2":["\u24C2",["m"]],"25aa":["\u25AA",["black_small_square"]],"25ab":["\u25AB",["white_small_square"]],"25b6":["\u25B6",["arrow_forward"]],"25c0":["\u25C0",["arrow_backward"]],"25fb":["\u25FB",["white_medium_square"]],"25fc":["\u25FC",["black_medium_square"]],"25fd":["\u25FD",["white_medium_small_square"]],"25fe":["\u25FE",["black_medium_small_square"]],"2600":["\u2600",["sunny"]],"2601":["\u2601",["cloud"]],"260e":["\u260E",["phone","telephone"]],"2611":["\u2611",["ballot_box_with_check"]],"2614":["\u2614",["umbrella"]],"2615":["\u2615",["coffee"]],"261d":["\u261D",["point_up"]],"263a":["\u263A",["relaxed"]],"2648":["\u2648",["aries"]],"2649":["\u2649",["taurus"]],"264a":["\u264A",["gemini"]],"264b":["\u264B",["cancer"]],"264c":["\u264C",["leo"]],"264d":["\u264D",["virgo"]],"264e":["\u264E",["libra"]],"264f":["\u264F",["scorpius"]],"2650":["\u2650",["sagittarius"]],"2651":["\u2651",["capricorn"]],"2652":["\u2652",["aquarius"]],"2653":["\u2653",["pisces"]],"2660":["\u2660",["spades"]],"2663":["\u2663",["clubs"]],"2665":["\u2665",["hearts"]],"2666":["\u2666",["diamonds"]],"2668":["\u2668",["hotsprings"]],"267b":["\u267B",["recycle"]],"267f":["\u267F",["wheelchair"]],"2693":["\u2693",["anchor"]],"26a0":["\u26A0",["warning"]],"26a1":["\u26A1",["zap"]],"26aa":["\u26AA",["white_circle"]],"26ab":["\u26AB",["black_circle"]],"26bd":["\u26BD",["soccer"]],"26be":["\u26BE",["baseball"]],"26c4":["\u26C4",["snowman"]],"26c5":["\u26C5",["partly_sunny"]],"26ce":["\u26CE",["ophiuchus"]],"26d4":["\u26D4",["no_entry"]],"26ea":["\u26EA",["church"]],"26f2":["\u26F2",["fountain"]],"26f3":["\u26F3",["golf"]],"26f5":["\u26F5",["boat","sailboat"]],"26fa":["\u26FA",["tent"]],"26fd":["\u26FD",["fuelpump"]],"2702":["\u2702",["scissors"]],"2705":["\u2705",["white_check_mark"]],"2708":["\u2708",["airplane"]],"2709":["\u2709",["email","envelope"]],"270a":["\u270A",["fist"]],"270b":["\u270B",["hand","raised_hand"]],"270c":["\u270C",["v"]],"270f":["\u270F",["pencil2"]],"2712":["\u2712",["black_nib"]],"2714":["\u2714",["heavy_check_mark"]],"2716":["\u2716",["heavy_multiplication_x"]],"2728":["\u2728",["sparkles"]],"2733":["\u2733",["eight_spoked_asterisk"]],"2734":["\u2734",["eight_pointed_black_star"]],"2744":["\u2744",["snowflake"]],"2747":["\u2747",["sparkle"]],"274c":["\u274C",["x"]],"274e":["\u274E",["negative_squared_cross_mark"]],"2753":["\u2753",["question"]],"2754":["\u2754",["grey_question"]],"2755":["\u2755",["grey_exclamation"]],"2757":["\u2757",["exclamation","heavy_exclamation_mark"]],"2764":["\u2764",["heart"],"<3"],"2795":["\u2795",["heavy_plus_sign"]],"2796":["\u2796",["heavy_minus_sign"]],"2797":["\u2797",["heavy_division_sign"]],"27a1":["\u27A1",["arrow_right"]],"27b0":["\u27B0",["curly_loop"]],"27bf":["\u27BF",["loop"]],"2934":["\u2934",["arrow_heading_up"]],"2935":["\u2935",["arrow_heading_down"]],"2b05":["\u2B05",["arrow_left"]],"2b06":["\u2B06",["arrow_up"]],"2b07":["\u2B07",["arrow_down"]],"2b1b":["\u2B1B",["black_large_square"]],"2b1c":["\u2B1C",["white_large_square"]],"2b50":["\u2B50",["star"]],"2b55":["\u2B55",["o"]],"3030":["\u3030",["wavy_dash"]],"303d":["\u303D",["part_alternation_mark"]],"3297":["\u3297",["congratulations"]],"3299":["\u3299",["secret"]],"1f004":["\uD83C\uDC04",["mahjong"]],"1f0cf":["\uD83C\uDCCF",["black_joker"]],"1f170":["\uD83C\uDD70",["a"]],"1f171":["\uD83C\uDD71",["b"]],"1f17e":["\uD83C\uDD7E",["o2"]],"1f17f":["\uD83C\uDD7F",["parking"]],"1f18e":["\uD83C\uDD8E",["ab"]],"1f191":["\uD83C\uDD91",["cl"]],"1f192":["\uD83C\uDD92",["cool"]],"1f193":["\uD83C\uDD93",["free"]],"1f194":["\uD83C\uDD94",["id"]],"1f195":["\uD83C\uDD95",["new"]],"1f196":["\uD83C\uDD96",["ng"]],"1f197":["\uD83C\uDD97",["ok"]],"1f198":["\uD83C\uDD98",["sos"]],"1f199":["\uD83C\uDD99",["up"]],"1f19a":["\uD83C\uDD9A",["vs"]],"1f201":["\uD83C\uDE01",["koko"]],"1f202":["\uD83C\uDE02",["sa"]],"1f21a":["\uD83C\uDE1A",["u7121"]],"1f22f":["\uD83C\uDE2F",["u6307"]],"1f232":["\uD83C\uDE32",["u7981"]],"1f233":["\uD83C\uDE33",["u7a7a"]],"1f234":["\uD83C\uDE34",["u5408"]],"1f235":["\uD83C\uDE35",["u6e80"]],"1f236":["\uD83C\uDE36",["u6709"]],"1f237":["\uD83C\uDE37",["u6708"]],"1f238":["\uD83C\uDE38",["u7533"]],"1f239":["\uD83C\uDE39",["u5272"]],"1f23a":["\uD83C\uDE3A",["u55b6"]],"1f250":["\uD83C\uDE50",["ideograph_advantage"]],"1f251":["\uD83C\uDE51",["accept"]],"1f300":["\uD83C\uDF00",["cyclone"]],"1f301":["\uD83C\uDF01",["foggy"]],"1f302":["\uD83C\uDF02",["closed_umbrella"]],"1f303":["\uD83C\uDF03",["stars"]],"1f304":["\uD83C\uDF04",["sunrise_over_mountains"]],"1f305":["\uD83C\uDF05",["sunrise"]],"1f306":["\uD83C\uDF06",["city_sunset"]],"1f307":["\uD83C\uDF07",["city_sunrise"]],"1f308":["\uD83C\uDF08",["rainbow"]],"1f309":["\uD83C\uDF09",["bridge_at_night"]],"1f30a":["\uD83C\uDF0A",["ocean"]],"1f30b":["\uD83C\uDF0B",["volcano"]],"1f30c":["\uD83C\uDF0C",["milky_way"]],"1f30d":["\uD83C\uDF0D",["earth_africa"]],"1f30e":["\uD83C\uDF0E",["earth_americas"]],"1f30f":["\uD83C\uDF0F",["earth_asia"]],"1f310":["\uD83C\uDF10",["globe_with_meridians"]],"1f311":["\uD83C\uDF11",["new_moon"]],"1f312":["\uD83C\uDF12",["waxing_crescent_moon"]],"1f313":["\uD83C\uDF13",["first_quarter_moon"]],"1f314":["\uD83C\uDF14",["moon","waxing_gibbous_moon"]],"1f315":["\uD83C\uDF15",["full_moon"]],"1f316":["\uD83C\uDF16",["waning_gibbous_moon"]],"1f317":["\uD83C\uDF17",["last_quarter_moon"]],"1f318":["\uD83C\uDF18",["waning_crescent_moon"]],"1f319":["\uD83C\uDF19",["crescent_moon"]],"1f31a":["\uD83C\uDF1A",["new_moon_with_face"]],"1f31b":["\uD83C\uDF1B",["first_quarter_moon_with_face"]],"1f31c":["\uD83C\uDF1C",["last_quarter_moon_with_face"]],"1f31d":["\uD83C\uDF1D",["full_moon_with_face"]],"1f31e":["\uD83C\uDF1E",["sun_with_face"]],"1f31f":["\uD83C\uDF1F",["star2"]],"1f330":["\uD83C\uDF30",["chestnut"]],"1f331":["\uD83C\uDF31",["seedling"]],"1f332":["\uD83C\uDF32",["evergreen_tree"]],"1f333":["\uD83C\uDF33",["deciduous_tree"]],"1f334":["\uD83C\uDF34",["palm_tree"]],"1f335":["\uD83C\uDF35",["cactus"]],"1f337":["\uD83C\uDF37",["tulip"]],"1f338":["\uD83C\uDF38",["cherry_blossom"]],"1f339":["\uD83C\uDF39",["rose"]],"1f33a":["\uD83C\uDF3A",["hibiscus"]],"1f33b":["\uD83C\uDF3B",["sunflower"]],"1f33c":["\uD83C\uDF3C",["blossom"]],"1f33d":["\uD83C\uDF3D",["corn"]],"1f33e":["\uD83C\uDF3E",["ear_of_rice"]],"1f33f":["\uD83C\uDF3F",["herb"]],"1f340":["\uD83C\uDF40",["four_leaf_clover"]],"1f341":["\uD83C\uDF41",["maple_leaf"]],"1f342":["\uD83C\uDF42",["fallen_leaf"]],"1f343":["\uD83C\uDF43",["leaves"]],"1f344":["\uD83C\uDF44",["mushroom"]],"1f345":["\uD83C\uDF45",["tomato"]],"1f346":["\uD83C\uDF46",["eggplant"]],"1f347":["\uD83C\uDF47",["grapes"]],"1f348":["\uD83C\uDF48",["melon"]],"1f349":["\uD83C\uDF49",["watermelon"]],"1f34a":["\uD83C\uDF4A",["tangerine"]],"1f34b":["\uD83C\uDF4B",["lemon"]],"1f34c":["\uD83C\uDF4C",["banana"]],"1f34d":["\uD83C\uDF4D",["pineapple"]],"1f34e":["\uD83C\uDF4E",["apple"]],"1f34f":["\uD83C\uDF4F",["green_apple"]],"1f350":["\uD83C\uDF50",["pear"]],"1f351":["\uD83C\uDF51",["peach"]],"1f352":["\uD83C\uDF52",["cherries"]],"1f353":["\uD83C\uDF53",["strawberry"]],"1f354":["\uD83C\uDF54",["hamburger"]],"1f355":["\uD83C\uDF55",["pizza"]],"1f356":["\uD83C\uDF56",["meat_on_bone"]],"1f357":["\uD83C\uDF57",["poultry_leg"]],"1f358":["\uD83C\uDF58",["rice_cracker"]],"1f359":["\uD83C\uDF59",["rice_ball"]],"1f35a":["\uD83C\uDF5A",["rice"]],"1f35b":["\uD83C\uDF5B",["curry"]],"1f35c":["\uD83C\uDF5C",["ramen"]],"1f35d":["\uD83C\uDF5D",["spaghetti"]],"1f35e":["\uD83C\uDF5E",["bread"]],"1f35f":["\uD83C\uDF5F",["fries"]],"1f360":["\uD83C\uDF60",["sweet_potato"]],"1f361":["\uD83C\uDF61",["dango"]],"1f362":["\uD83C\uDF62",["oden"]],"1f363":["\uD83C\uDF63",["sushi"]],"1f364":["\uD83C\uDF64",["fried_shrimp"]],"1f365":["\uD83C\uDF65",["fish_cake"]],"1f366":["\uD83C\uDF66",["icecream"]],"1f367":["\uD83C\uDF67",["shaved_ice"]],"1f368":["\uD83C\uDF68",["ice_cream"]],"1f369":["\uD83C\uDF69",["doughnut"]],"1f36a":["\uD83C\uDF6A",["cookie"]],"1f36b":["\uD83C\uDF6B",["chocolate_bar"]],"1f36c":["\uD83C\uDF6C",["candy"]],"1f36d":["\uD83C\uDF6D",["lollipop"]],"1f36e":["\uD83C\uDF6E",["custard"]],"1f36f":["\uD83C\uDF6F",["honey_pot"]],"1f370":["\uD83C\uDF70",["cake"]],"1f371":["\uD83C\uDF71",["bento"]],"1f372":["\uD83C\uDF72",["stew"]],"1f373":["\uD83C\uDF73",["egg"]],"1f374":["\uD83C\uDF74",["fork_and_knife"]],"1f375":["\uD83C\uDF75",["tea"]],"1f376":["\uD83C\uDF76",["sake"]],"1f377":["\uD83C\uDF77",["wine_glass"]],"1f378":["\uD83C\uDF78",["cocktail"]],"1f379":["\uD83C\uDF79",["tropical_drink"]],"1f37a":["\uD83C\uDF7A",["beer"]],"1f37b":["\uD83C\uDF7B",["beers"]],"1f37c":["\uD83C\uDF7C",["baby_bottle"]],"1f380":["\uD83C\uDF80",["ribbon"]],"1f381":["\uD83C\uDF81",["gift"]],"1f382":["\uD83C\uDF82",["birthday"]],"1f383":["\uD83C\uDF83",["jack_o_lantern"]],"1f384":["\uD83C\uDF84",["christmas_tree"]],"1f385":["\uD83C\uDF85",["santa"]],"1f386":["\uD83C\uDF86",["fireworks"]],"1f387":["\uD83C\uDF87",["sparkler"]],"1f388":["\uD83C\uDF88",["balloon"]],"1f389":["\uD83C\uDF89",["tada"]],"1f38a":["\uD83C\uDF8A",["confetti_ball"]],"1f38b":["\uD83C\uDF8B",["tanabata_tree"]],"1f38c":["\uD83C\uDF8C",["crossed_flags"]],"1f38d":["\uD83C\uDF8D",["bamboo"]],"1f38e":["\uD83C\uDF8E",["dolls"]],"1f38f":["\uD83C\uDF8F",["flags"]],"1f390":["\uD83C\uDF90",["wind_chime"]],"1f391":["\uD83C\uDF91",["rice_scene"]],"1f392":["\uD83C\uDF92",["school_satchel"]],"1f393":["\uD83C\uDF93",["mortar_board"]],"1f3a0":["\uD83C\uDFA0",["carousel_horse"]],"1f3a1":["\uD83C\uDFA1",["ferris_wheel"]],"1f3a2":["\uD83C\uDFA2",["roller_coaster"]],"1f3a3":["\uD83C\uDFA3",["fishing_pole_and_fish"]],"1f3a4":["\uD83C\uDFA4",["microphone"]],"1f3a5":["\uD83C\uDFA5",["movie_camera"]],"1f3a6":["\uD83C\uDFA6",["cinema"]],"1f3a7":["\uD83C\uDFA7",["headphones"]],"1f3a8":["\uD83C\uDFA8",["art"]],"1f3a9":["\uD83C\uDFA9",["tophat"]],"1f3aa":["\uD83C\uDFAA",["circus_tent"]],"1f3ab":["\uD83C\uDFAB",["ticket"]],"1f3ac":["\uD83C\uDFAC",["clapper"]],"1f3ad":["\uD83C\uDFAD",["performing_arts"]],"1f3ae":["\uD83C\uDFAE",["video_game"]],"1f3af":["\uD83C\uDFAF",["dart"]],"1f3b0":["\uD83C\uDFB0",["slot_machine"]],"1f3b1":["\uD83C\uDFB1",["8ball"]],"1f3b2":["\uD83C\uDFB2",["game_die"]],"1f3b3":["\uD83C\uDFB3",["bowling"]],"1f3b4":["\uD83C\uDFB4",["flower_playing_cards"]],"1f3b5":["\uD83C\uDFB5",["musical_note"]],"1f3b6":["\uD83C\uDFB6",["notes"]],"1f3b7":["\uD83C\uDFB7",["saxophone"]],"1f3b8":["\uD83C\uDFB8",["guitar"]],"1f3b9":["\uD83C\uDFB9",["musical_keyboard"]],"1f3ba":["\uD83C\uDFBA",["trumpet"]],"1f3bb":["\uD83C\uDFBB",["violin"]],"1f3bc":["\uD83C\uDFBC",["musical_score"]],"1f3bd":["\uD83C\uDFBD",["running_shirt_with_sash"]],"1f3be":["\uD83C\uDFBE",["tennis"]],"1f3bf":["\uD83C\uDFBF",["ski"]],"1f3c0":["\uD83C\uDFC0",["basketball"]],"1f3c1":["\uD83C\uDFC1",["checkered_flag"]],"1f3c2":["\uD83C\uDFC2",["snowboarder"]],"1f3c3":["\uD83C\uDFC3",["runner","running"]],"1f3c4":["\uD83C\uDFC4",["surfer"]],"1f3c6":["\uD83C\uDFC6",["trophy"]],"1f3c7":["\uD83C\uDFC7",["horse_racing"]],"1f3c8":["\uD83C\uDFC8",["football"]],"1f3c9":["\uD83C\uDFC9",["rugby_football"]],"1f3ca":["\uD83C\uDFCA",["swimmer"]],"1f3e0":["\uD83C\uDFE0",["house"]],"1f3e1":["\uD83C\uDFE1",["house_with_garden"]],"1f3e2":["\uD83C\uDFE2",["office"]],"1f3e3":["\uD83C\uDFE3",["post_office"]],"1f3e4":["\uD83C\uDFE4",["european_post_office"]],"1f3e5":["\uD83C\uDFE5",["hospital"]],"1f3e6":["\uD83C\uDFE6",["bank"]],"1f3e7":["\uD83C\uDFE7",["atm"]],"1f3e8":["\uD83C\uDFE8",["hotel"]],"1f3e9":["\uD83C\uDFE9",["love_hotel"]],"1f3ea":["\uD83C\uDFEA",["convenience_store"]],"1f3eb":["\uD83C\uDFEB",["school"]],"1f3ec":["\uD83C\uDFEC",["department_store"]],"1f3ed":["\uD83C\uDFED",["factory"]],"1f3ee":["\uD83C\uDFEE",["izakaya_lantern","lantern"]],"1f3ef":["\uD83C\uDFEF",["japanese_castle"]],"1f3f0":["\uD83C\uDFF0",["european_castle"]],"1f400":["\uD83D\uDC00",["rat"]],"1f401":["\uD83D\uDC01",["mouse2"]],"1f402":["\uD83D\uDC02",["ox"]],"1f403":["\uD83D\uDC03",["water_buffalo"]],"1f404":["\uD83D\uDC04",["cow2"]],"1f405":["\uD83D\uDC05",["tiger2"]],"1f406":["\uD83D\uDC06",["leopard"]],"1f407":["\uD83D\uDC07",["rabbit2"]],"1f408":["\uD83D\uDC08",["cat2"]],"1f409":["\uD83D\uDC09",["dragon"]],"1f40a":["\uD83D\uDC0A",["crocodile"]],"1f40b":["\uD83D\uDC0B",["whale2"]],"1f40c":["\uD83D\uDC0C",["snail"]],"1f40d":["\uD83D\uDC0D",["snake"]],"1f40e":["\uD83D\uDC0E",["racehorse"]],"1f40f":["\uD83D\uDC0F",["ram"]],"1f410":["\uD83D\uDC10",["goat"]],"1f411":["\uD83D\uDC11",["sheep"]],"1f412":["\uD83D\uDC12",["monkey"]],"1f413":["\uD83D\uDC13",["rooster"]],"1f414":["\uD83D\uDC14",["chicken"]],"1f415":["\uD83D\uDC15",["dog2"]],"1f416":["\uD83D\uDC16",["pig2"]],"1f417":["\uD83D\uDC17",["boar"]],"1f418":["\uD83D\uDC18",["elephant"]],"1f419":["\uD83D\uDC19",["octopus"]],"1f41a":["\uD83D\uDC1A",["shell"]],"1f41b":["\uD83D\uDC1B",["bug"]],"1f41c":["\uD83D\uDC1C",["ant"]],"1f41d":["\uD83D\uDC1D",["bee","honeybee"]],"1f41e":["\uD83D\uDC1E",["beetle"]],"1f41f":["\uD83D\uDC1F",["fish"]],"1f420":["\uD83D\uDC20",["tropical_fish"]],"1f421":["\uD83D\uDC21",["blowfish"]],"1f422":["\uD83D\uDC22",["turtle"]],"1f423":["\uD83D\uDC23",["hatching_chick"]],"1f424":["\uD83D\uDC24",["baby_chick"]],"1f425":["\uD83D\uDC25",["hatched_chick"]],"1f426":["\uD83D\uDC26",["bird"]],"1f427":["\uD83D\uDC27",["penguin"]],"1f428":["\uD83D\uDC28",["koala"]],"1f429":["\uD83D\uDC29",["poodle"]],"1f42a":["\uD83D\uDC2A",["dromedary_camel"]],"1f42b":["\uD83D\uDC2B",["camel"]],"1f42c":["\uD83D\uDC2C",["dolphin","flipper"]],"1f42d":["\uD83D\uDC2D",["mouse"]],"1f42e":["\uD83D\uDC2E",["cow"]],"1f42f":["\uD83D\uDC2F",["tiger"]],"1f430":["\uD83D\uDC30",["rabbit"]],"1f431":["\uD83D\uDC31",["cat"]],"1f432":["\uD83D\uDC32",["dragon_face"]],"1f433":["\uD83D\uDC33",["whale"]],"1f434":["\uD83D\uDC34",["horse"]],"1f435":["\uD83D\uDC35",["monkey_face"]],"1f436":["\uD83D\uDC36",["dog"]],"1f437":["\uD83D\uDC37",["pig"]],"1f438":["\uD83D\uDC38",["frog"]],"1f439":["\uD83D\uDC39",["hamster"]],"1f43a":["\uD83D\uDC3A",["wolf"]],"1f43b":["\uD83D\uDC3B",["bear"]],"1f43c":["\uD83D\uDC3C",["panda_face"]],"1f43d":["\uD83D\uDC3D",["pig_nose"]],"1f43e":["\uD83D\uDC3E",["feet","paw_prints"]],"1f440":["\uD83D\uDC40",["eyes"]],"1f442":["\uD83D\uDC42",["ear"]],"1f443":["\uD83D\uDC43",["nose"]],"1f444":["\uD83D\uDC44",["lips"]],"1f445":["\uD83D\uDC45",["tongue"]],"1f446":["\uD83D\uDC46",["point_up_2"]],"1f447":["\uD83D\uDC47",["point_down"]],"1f448":["\uD83D\uDC48",["point_left"]],"1f449":["\uD83D\uDC49",["point_right"]],"1f44a":["\uD83D\uDC4A",["facepunch","punch"]],"1f44b":["\uD83D\uDC4B",["wave"]],"1f44c":["\uD83D\uDC4C",["ok_hand"]],"1f44d":["\uD83D\uDC4D",["+1","thumbsup"]],"1f44e":["\uD83D\uDC4E",["-1","thumbsdown"]],"1f44f":["\uD83D\uDC4F",["clap"]],"1f450":["\uD83D\uDC50",["open_hands"]],"1f451":["\uD83D\uDC51",["crown"]],"1f452":["\uD83D\uDC52",["womans_hat"]],"1f453":["\uD83D\uDC53",["eyeglasses"]],"1f454":["\uD83D\uDC54",["necktie"]],"1f455":["\uD83D\uDC55",["shirt","tshirt"]],"1f456":["\uD83D\uDC56",["jeans"]],"1f457":["\uD83D\uDC57",["dress"]],"1f458":["\uD83D\uDC58",["kimono"]],"1f459":["\uD83D\uDC59",["bikini"]],"1f45a":["\uD83D\uDC5A",["womans_clothes"]],"1f45b":["\uD83D\uDC5B",["purse"]],"1f45c":["\uD83D\uDC5C",["handbag"]],"1f45d":["\uD83D\uDC5D",["pouch"]],"1f45e":["\uD83D\uDC5E",["mans_shoe","shoe"]],"1f45f":["\uD83D\uDC5F",["athletic_shoe"]],"1f460":["\uD83D\uDC60",["high_heel"]],"1f461":["\uD83D\uDC61",["sandal"]],"1f462":["\uD83D\uDC62",["boot"]],"1f463":["\uD83D\uDC63",["footprints"]],"1f464":["\uD83D\uDC64",["bust_in_silhouette"]],"1f465":["\uD83D\uDC65",["busts_in_silhouette"]],"1f466":["\uD83D\uDC66",["boy"]],"1f467":["\uD83D\uDC67",["girl"]],"1f468":["\uD83D\uDC68",["man"]],"1f469":["\uD83D\uDC69",["woman"]],"1f46a":["\uD83D\uDC6A",["family"]],"1f46b":["\uD83D\uDC6B",["couple"]],"1f46c":["\uD83D\uDC6C",["two_men_holding_hands"]],"1f46d":["\uD83D\uDC6D",["two_women_holding_hands"]],"1f46e":["\uD83D\uDC6E",["cop"]],"1f46f":["\uD83D\uDC6F",["dancers"]],"1f470":["\uD83D\uDC70",["bride_with_veil"]],"1f471":["\uD83D\uDC71",["person_with_blond_hair"]],"1f472":["\uD83D\uDC72",["man_with_gua_pi_mao"]],"1f473":["\uD83D\uDC73",["man_with_turban"]],"1f474":["\uD83D\uDC74",["older_man"]],"1f475":["\uD83D\uDC75",["older_woman"]],"1f476":["\uD83D\uDC76",["baby"]],"1f477":["\uD83D\uDC77",["construction_worker"]],"1f478":["\uD83D\uDC78",["princess"]],"1f479":["\uD83D\uDC79",["japanese_ogre"]],"1f47a":["\uD83D\uDC7A",["japanese_goblin"]],"1f47b":["\uD83D\uDC7B",["ghost"]],"1f47c":["\uD83D\uDC7C",["angel"]],"1f47d":["\uD83D\uDC7D",["alien"]],"1f47e":["\uD83D\uDC7E",["space_invader"]],"1f47f":["\uD83D\uDC7F",["imp"]],"1f480":["\uD83D\uDC80",["skull"]],"1f481":["\uD83D\uDC81",["information_desk_person"]],"1f482":["\uD83D\uDC82",["guardsman"]],"1f483":["\uD83D\uDC83",["dancer"]],"1f484":["\uD83D\uDC84",["lipstick"]],"1f485":["\uD83D\uDC85",["nail_care"]],"1f486":["\uD83D\uDC86",["massage"]],"1f487":["\uD83D\uDC87",["haircut"]],"1f488":["\uD83D\uDC88",["barber"]],"1f489":["\uD83D\uDC89",["syringe"]],"1f48a":["\uD83D\uDC8A",["pill"]],"1f48b":["\uD83D\uDC8B",["kiss"]],"1f48c":["\uD83D\uDC8C",["love_letter"]],"1f48d":["\uD83D\uDC8D",["ring"]],"1f48e":["\uD83D\uDC8E",["gem"]],"1f48f":["\uD83D\uDC8F",["couplekiss"]],"1f490":["\uD83D\uDC90",["bouquet"]],"1f491":["\uD83D\uDC91",["couple_with_heart"]],"1f492":["\uD83D\uDC92",["wedding"]],"1f493":["\uD83D\uDC93",["heartbeat"]],"1f494":["\uD83D\uDC94",["broken_heart"],"<\/3"],"1f495":["\uD83D\uDC95",["two_hearts"]],"1f496":["\uD83D\uDC96",["sparkling_heart"]],"1f497":["\uD83D\uDC97",["heartpulse"]],"1f498":["\uD83D\uDC98",["cupid"]],"1f499":["\uD83D\uDC99",["blue_heart"],"<3"],"1f49a":["\uD83D\uDC9A",["green_heart"],"<3"],"1f49b":["\uD83D\uDC9B",["yellow_heart"],"<3"],"1f49c":["\uD83D\uDC9C",["purple_heart"],"<3"],"1f49d":["\uD83D\uDC9D",["gift_heart"]],"1f49e":["\uD83D\uDC9E",["revolving_hearts"]],"1f49f":["\uD83D\uDC9F",["heart_decoration"]],"1f4a0":["\uD83D\uDCA0",["diamond_shape_with_a_dot_inside"]],"1f4a1":["\uD83D\uDCA1",["bulb"]],"1f4a2":["\uD83D\uDCA2",["anger"]],"1f4a3":["\uD83D\uDCA3",["bomb"]],"1f4a4":["\uD83D\uDCA4",["zzz"]],"1f4a5":["\uD83D\uDCA5",["boom","collision"]],"1f4a6":["\uD83D\uDCA6",["sweat_drops"]],"1f4a7":["\uD83D\uDCA7",["droplet"]],"1f4a8":["\uD83D\uDCA8",["dash"]],"1f4a9":["\uD83D\uDCA9",["hankey","poop","shit"]],"1f4aa":["\uD83D\uDCAA",["muscle"]],"1f4ab":["\uD83D\uDCAB",["dizzy"]],"1f4ac":["\uD83D\uDCAC",["speech_balloon"]],"1f4ad":["\uD83D\uDCAD",["thought_balloon"]],"1f4ae":["\uD83D\uDCAE",["white_flower"]],"1f4af":["\uD83D\uDCAF",["100"]],"1f4b0":["\uD83D\uDCB0",["moneybag"]],"1f4b1":["\uD83D\uDCB1",["currency_exchange"]],"1f4b2":["\uD83D\uDCB2",["heavy_dollar_sign"]],"1f4b3":["\uD83D\uDCB3",["credit_card"]],"1f4b4":["\uD83D\uDCB4",["yen"]],"1f4b5":["\uD83D\uDCB5",["dollar"]],"1f4b6":["\uD83D\uDCB6",["euro"]],"1f4b7":["\uD83D\uDCB7",["pound"]],"1f4b8":["\uD83D\uDCB8",["money_with_wings"]],"1f4b9":["\uD83D\uDCB9",["chart"]],"1f4ba":["\uD83D\uDCBA",["seat"]],"1f4bb":["\uD83D\uDCBB",["computer"]],"1f4bc":["\uD83D\uDCBC",["briefcase"]],"1f4bd":["\uD83D\uDCBD",["minidisc"]],"1f4be":["\uD83D\uDCBE",["floppy_disk"]],"1f4bf":["\uD83D\uDCBF",["cd"]],"1f4c0":["\uD83D\uDCC0",["dvd"]],"1f4c1":["\uD83D\uDCC1",["file_folder"]],"1f4c2":["\uD83D\uDCC2",["open_file_folder"]],"1f4c3":["\uD83D\uDCC3",["page_with_curl"]],"1f4c4":["\uD83D\uDCC4",["page_facing_up"]],"1f4c5":["\uD83D\uDCC5",["date"]],"1f4c6":["\uD83D\uDCC6",["calendar"]],"1f4c7":["\uD83D\uDCC7",["card_index"]],"1f4c8":["\uD83D\uDCC8",["chart_with_upwards_trend"]],"1f4c9":["\uD83D\uDCC9",["chart_with_downwards_trend"]],"1f4ca":["\uD83D\uDCCA",["bar_chart"]],"1f4cb":["\uD83D\uDCCB",["clipboard"]],"1f4cc":["\uD83D\uDCCC",["pushpin"]],"1f4cd":["\uD83D\uDCCD",["round_pushpin"]],"1f4ce":["\uD83D\uDCCE",["paperclip"]],"1f4cf":["\uD83D\uDCCF",["straight_ruler"]],"1f4d0":["\uD83D\uDCD0",["triangular_ruler"]],"1f4d1":["\uD83D\uDCD1",["bookmark_tabs"]],"1f4d2":["\uD83D\uDCD2",["ledger"]],"1f4d3":["\uD83D\uDCD3",["notebook"]],"1f4d4":["\uD83D\uDCD4",["notebook_with_decorative_cover"]],"1f4d5":["\uD83D\uDCD5",["closed_book"]],"1f4d6":["\uD83D\uDCD6",["book","open_book"]],"1f4d7":["\uD83D\uDCD7",["green_book"]],"1f4d8":["\uD83D\uDCD8",["blue_book"]],"1f4d9":["\uD83D\uDCD9",["orange_book"]],"1f4da":["\uD83D\uDCDA",["books"]],"1f4db":["\uD83D\uDCDB",["name_badge"]],"1f4dc":["\uD83D\uDCDC",["scroll"]],"1f4dd":["\uD83D\uDCDD",["memo","pencil"]],"1f4de":["\uD83D\uDCDE",["telephone_receiver"]],"1f4df":["\uD83D\uDCDF",["pager"]],"1f4e0":["\uD83D\uDCE0",["fax"]],"1f4e1":["\uD83D\uDCE1",["satellite"]],"1f4e2":["\uD83D\uDCE2",["loudspeaker"]],"1f4e3":["\uD83D\uDCE3",["mega"]],"1f4e4":["\uD83D\uDCE4",["outbox_tray"]],"1f4e5":["\uD83D\uDCE5",["inbox_tray"]],"1f4e6":["\uD83D\uDCE6",["package"]],"1f4e7":["\uD83D\uDCE7",["e-mail"]],"1f4e8":["\uD83D\uDCE8",["incoming_envelope"]],"1f4e9":["\uD83D\uDCE9",["envelope_with_arrow"]],"1f4ea":["\uD83D\uDCEA",["mailbox_closed"]],"1f4eb":["\uD83D\uDCEB",["mailbox"]],"1f4ec":["\uD83D\uDCEC",["mailbox_with_mail"]],"1f4ed":["\uD83D\uDCED",["mailbox_with_no_mail"]],"1f4ee":["\uD83D\uDCEE",["postbox"]],"1f4ef":["\uD83D\uDCEF",["postal_horn"]],"1f4f0":["\uD83D\uDCF0",["newspaper"]],"1f4f1":["\uD83D\uDCF1",["iphone"]],"1f4f2":["\uD83D\uDCF2",["calling"]],"1f4f3":["\uD83D\uDCF3",["vibration_mode"]],"1f4f4":["\uD83D\uDCF4",["mobile_phone_off"]],"1f4f5":["\uD83D\uDCF5",["no_mobile_phones"]],"1f4f6":["\uD83D\uDCF6",["signal_strength"]],"1f4f7":["\uD83D\uDCF7",["camera"]],"1f4f9":["\uD83D\uDCF9",["video_camera"]],"1f4fa":["\uD83D\uDCFA",["tv"]],"1f4fb":["\uD83D\uDCFB",["radio"]],"1f4fc":["\uD83D\uDCFC",["vhs"]],"1f500":["\uD83D\uDD00",["twisted_rightwards_arrows"]],"1f501":["\uD83D\uDD01",["repeat"]],"1f502":["\uD83D\uDD02",["repeat_one"]],"1f503":["\uD83D\uDD03",["arrows_clockwise"]],"1f504":["\uD83D\uDD04",["arrows_counterclockwise"]],"1f505":["\uD83D\uDD05",["low_brightness"]],"1f506":["\uD83D\uDD06",["high_brightness"]],"1f507":["\uD83D\uDD07",["mute"]],"1f509":["\uD83D\uDD09",["sound"]],"1f50a":["\uD83D\uDD0A",["speaker"]],"1f50b":["\uD83D\uDD0B",["battery"]],"1f50c":["\uD83D\uDD0C",["electric_plug"]],"1f50d":["\uD83D\uDD0D",["mag"]],"1f50e":["\uD83D\uDD0E",["mag_right"]],"1f50f":["\uD83D\uDD0F",["lock_with_ink_pen"]],"1f510":["\uD83D\uDD10",["closed_lock_with_key"]],"1f511":["\uD83D\uDD11",["key"]],"1f512":["\uD83D\uDD12",["lock"]],"1f513":["\uD83D\uDD13",["unlock"]],"1f514":["\uD83D\uDD14",["bell"]],"1f515":["\uD83D\uDD15",["no_bell"]],"1f516":["\uD83D\uDD16",["bookmark"]],"1f517":["\uD83D\uDD17",["link"]],"1f518":["\uD83D\uDD18",["radio_button"]],"1f519":["\uD83D\uDD19",["back"]],"1f51a":["\uD83D\uDD1A",["end"]],"1f51b":["\uD83D\uDD1B",["on"]],"1f51c":["\uD83D\uDD1C",["soon"]],"1f51d":["\uD83D\uDD1D",["top"]],"1f51e":["\uD83D\uDD1E",["underage"]],"1f51f":["\uD83D\uDD1F",["keycap_ten"]],"1f520":["\uD83D\uDD20",["capital_abcd"]],"1f521":["\uD83D\uDD21",["abcd"]],"1f522":["\uD83D\uDD22",["1234"]],"1f523":["\uD83D\uDD23",["symbols"]],"1f524":["\uD83D\uDD24",["abc"]],"1f525":["\uD83D\uDD25",["fire"]],"1f526":["\uD83D\uDD26",["flashlight"]],"1f527":["\uD83D\uDD27",["wrench"]],"1f528":["\uD83D\uDD28",["hammer"]],"1f529":["\uD83D\uDD29",["nut_and_bolt"]],"1f52a":["\uD83D\uDD2A",["hocho"]],"1f52b":["\uD83D\uDD2B",["gun"]],"1f52c":["\uD83D\uDD2C",["microscope"]],"1f52d":["\uD83D\uDD2D",["telescope"]],"1f52e":["\uD83D\uDD2E",["crystal_ball"]],"1f52f":["\uD83D\uDD2F",["six_pointed_star"]],"1f530":["\uD83D\uDD30",["beginner"]],"1f531":["\uD83D\uDD31",["trident"]],"1f532":["\uD83D\uDD32",["black_square_button"]],"1f533":["\uD83D\uDD33",["white_square_button"]],"1f534":["\uD83D\uDD34",["red_circle"]],"1f535":["\uD83D\uDD35",["large_blue_circle"]],"1f536":["\uD83D\uDD36",["large_orange_diamond"]],"1f537":["\uD83D\uDD37",["large_blue_diamond"]],"1f538":["\uD83D\uDD38",["small_orange_diamond"]],"1f539":["\uD83D\uDD39",["small_blue_diamond"]],"1f53a":["\uD83D\uDD3A",["small_red_triangle"]],"1f53b":["\uD83D\uDD3B",["small_red_triangle_down"]],"1f53c":["\uD83D\uDD3C",["arrow_up_small"]],"1f53d":["\uD83D\uDD3D",["arrow_down_small"]],"1f550":["\uD83D\uDD50",["clock1"]],"1f551":["\uD83D\uDD51",["clock2"]],"1f552":["\uD83D\uDD52",["clock3"]],"1f553":["\uD83D\uDD53",["clock4"]],"1f554":["\uD83D\uDD54",["clock5"]],"1f555":["\uD83D\uDD55",["clock6"]],"1f556":["\uD83D\uDD56",["clock7"]],"1f557":["\uD83D\uDD57",["clock8"]],"1f558":["\uD83D\uDD58",["clock9"]],"1f559":["\uD83D\uDD59",["clock10"]],"1f55a":["\uD83D\uDD5A",["clock11"]],"1f55b":["\uD83D\uDD5B",["clock12"]],"1f55c":["\uD83D\uDD5C",["clock130"]],"1f55d":["\uD83D\uDD5D",["clock230"]],"1f55e":["\uD83D\uDD5E",["clock330"]],"1f55f":["\uD83D\uDD5F",["clock430"]],"1f560":["\uD83D\uDD60",["clock530"]],"1f561":["\uD83D\uDD61",["clock630"]],"1f562":["\uD83D\uDD62",["clock730"]],"1f563":["\uD83D\uDD63",["clock830"]],"1f564":["\uD83D\uDD64",["clock930"]],"1f565":["\uD83D\uDD65",["clock1030"]],"1f566":["\uD83D\uDD66",["clock1130"]],"1f567":["\uD83D\uDD67",["clock1230"]],"1f5fb":["\uD83D\uDDFB",["mount_fuji"]],"1f5fc":["\uD83D\uDDFC",["tokyo_tower"]],"1f5fd":["\uD83D\uDDFD",["statue_of_liberty"]],"1f5fe":["\uD83D\uDDFE",["japan"]],"1f5ff":["\uD83D\uDDFF",["moyai"]],"1f600":["\uD83D\uDE00",["grinning"]],"1f601":["\uD83D\uDE01",["grin"]],"1f602":["\uD83D\uDE02",["joy"]],"1f603":["\uD83D\uDE03",["smiley"],":)"],"1f604":["\uD83D\uDE04",["smile"],":)"],"1f605":["\uD83D\uDE05",["sweat_smile"]],"1f606":["\uD83D\uDE06",["laughing","satisfied"]],"1f607":["\uD83D\uDE07",["innocent"]],"1f608":["\uD83D\uDE08",["smiling_imp"]],"1f609":["\uD83D\uDE09",["wink"],";)"],"1f60a":["\uD83D\uDE0A",["blush"]],"1f60b":["\uD83D\uDE0B",["yum"]],"1f60c":["\uD83D\uDE0C",["relieved"]],"1f60d":["\uD83D\uDE0D",["heart_eyes"]],"1f60e":["\uD83D\uDE0E",["sunglasses"]],"1f60f":["\uD83D\uDE0F",["smirk"]],"1f610":["\uD83D\uDE10",["neutral_face"]],"1f611":["\uD83D\uDE11",["expressionless"]],"1f612":["\uD83D\uDE12",["unamused"]],"1f613":["\uD83D\uDE13",["sweat"]],"1f614":["\uD83D\uDE14",["pensive"]],"1f615":["\uD83D\uDE15",["confused"]],"1f616":["\uD83D\uDE16",["confounded"]],"1f617":["\uD83D\uDE17",["kissing"]],"1f618":["\uD83D\uDE18",["kissing_heart"]],"1f619":["\uD83D\uDE19",["kissing_smiling_eyes"]],"1f61a":["\uD83D\uDE1A",["kissing_closed_eyes"]],"1f61b":["\uD83D\uDE1B",["stuck_out_tongue"]],"1f61c":["\uD83D\uDE1C",["stuck_out_tongue_winking_eye"],";p"],"1f61d":["\uD83D\uDE1D",["stuck_out_tongue_closed_eyes"]],"1f61e":["\uD83D\uDE1E",["disappointed"],":("],"1f61f":["\uD83D\uDE1F",["worried"]],"1f620":["\uD83D\uDE20",["angry"]],"1f621":["\uD83D\uDE21",["rage"]],"1f622":["\uD83D\uDE22",["cry"],":'("],"1f623":["\uD83D\uDE23",["persevere"]],"1f624":["\uD83D\uDE24",["triumph"]],"1f625":["\uD83D\uDE25",["disappointed_relieved"]],"1f626":["\uD83D\uDE26",["frowning"]],"1f627":["\uD83D\uDE27",["anguished"]],"1f628":["\uD83D\uDE28",["fearful"]],"1f629":["\uD83D\uDE29",["weary"]],"1f62a":["\uD83D\uDE2A",["sleepy"]],"1f62b":["\uD83D\uDE2B",["tired_face"]],"1f62c":["\uD83D\uDE2C",["grimacing"]],"1f62d":["\uD83D\uDE2D",["sob"],":'("],"1f62e":["\uD83D\uDE2E",["open_mouth"]],"1f62f":["\uD83D\uDE2F",["hushed"]],"1f630":["\uD83D\uDE30",["cold_sweat"]],"1f631":["\uD83D\uDE31",["scream"]],"1f632":["\uD83D\uDE32",["astonished"]],"1f633":["\uD83D\uDE33",["flushed"]],"1f634":["\uD83D\uDE34",["sleeping"]],"1f635":["\uD83D\uDE35",["dizzy_face"]],"1f636":["\uD83D\uDE36",["no_mouth"]],"1f637":["\uD83D\uDE37",["mask"]],"1f638":["\uD83D\uDE38",["smile_cat"]],"1f639":["\uD83D\uDE39",["joy_cat"]],"1f63a":["\uD83D\uDE3A",["smiley_cat"]],"1f63b":["\uD83D\uDE3B",["heart_eyes_cat"]],"1f63c":["\uD83D\uDE3C",["smirk_cat"]],"1f63d":["\uD83D\uDE3D",["kissing_cat"]],"1f63e":["\uD83D\uDE3E",["pouting_cat"]],"1f63f":["\uD83D\uDE3F",["crying_cat_face"]],"1f640":["\uD83D\uDE40",["scream_cat"]],"1f645":["\uD83D\uDE45",["no_good"]],"1f646":["\uD83D\uDE46",["ok_woman"]],"1f647":["\uD83D\uDE47",["bow"]],"1f648":["\uD83D\uDE48",["see_no_evil"]],"1f649":["\uD83D\uDE49",["hear_no_evil"]],"1f64a":["\uD83D\uDE4A",["speak_no_evil"]],"1f64b":["\uD83D\uDE4B",["raising_hand"]],"1f64c":["\uD83D\uDE4C",["raised_hands"]],"1f64d":["\uD83D\uDE4D",["person_frowning"]],"1f64e":["\uD83D\uDE4E",["person_with_pouting_face"]],"1f64f":["\uD83D\uDE4F",["pray"]],"1f680":["\uD83D\uDE80",["rocket"]],"1f681":["\uD83D\uDE81",["helicopter"]],"1f682":["\uD83D\uDE82",["steam_locomotive"]],"1f683":["\uD83D\uDE83",["railway_car","train"]],"1f684":["\uD83D\uDE84",["bullettrain_side"]],"1f685":["\uD83D\uDE85",["bullettrain_front"]],"1f686":["\uD83D\uDE86",["train2"]],"1f687":["\uD83D\uDE87",["metro"]],"1f688":["\uD83D\uDE88",["light_rail"]],"1f689":["\uD83D\uDE89",["station"]],"1f68a":["\uD83D\uDE8A",["tram"]],"1f68c":["\uD83D\uDE8C",["bus"]],"1f68d":["\uD83D\uDE8D",["oncoming_bus"]],"1f68e":["\uD83D\uDE8E",["trolleybus"]],"1f68f":["\uD83D\uDE8F",["busstop"]],"1f690":["\uD83D\uDE90",["minibus"]],"1f691":["\uD83D\uDE91",["ambulance"]],"1f692":["\uD83D\uDE92",["fire_engine"]],"1f693":["\uD83D\uDE93",["police_car"]],"1f694":["\uD83D\uDE94",["oncoming_police_car"]],"1f695":["\uD83D\uDE95",["taxi"]],"1f696":["\uD83D\uDE96",["oncoming_taxi"]],"1f697":["\uD83D\uDE97",["car","red_car"]],"1f698":["\uD83D\uDE98",["oncoming_automobile"]],"1f699":["\uD83D\uDE99",["blue_car"]],"1f69a":["\uD83D\uDE9A",["truck"]],"1f69b":["\uD83D\uDE9B",["articulated_lorry"]],"1f69c":["\uD83D\uDE9C",["tractor"]],"1f69d":["\uD83D\uDE9D",["monorail"]],"1f69e":["\uD83D\uDE9E",["mountain_railway"]],"1f69f":["\uD83D\uDE9F",["suspension_railway"]],"1f6a0":["\uD83D\uDEA0",["mountain_cableway"]],"1f6a1":["\uD83D\uDEA1",["aerial_tramway"]],"1f6a2":["\uD83D\uDEA2",["ship"]],"1f6a3":["\uD83D\uDEA3",["rowboat"]],"1f6a4":["\uD83D\uDEA4",["speedboat"]],"1f6a5":["\uD83D\uDEA5",["traffic_light"]],"1f6a6":["\uD83D\uDEA6",["vertical_traffic_light"]],"1f6a7":["\uD83D\uDEA7",["construction"]],"1f6a8":["\uD83D\uDEA8",["rotating_light"]],"1f6a9":["\uD83D\uDEA9",["triangular_flag_on_post"]],"1f6aa":["\uD83D\uDEAA",["door"]],"1f6ab":["\uD83D\uDEAB",["no_entry_sign"]],"1f6ac":["\uD83D\uDEAC",["smoking"]],"1f6ad":["\uD83D\uDEAD",["no_smoking"]],"1f6ae":["\uD83D\uDEAE",["put_litter_in_its_place"]],"1f6af":["\uD83D\uDEAF",["do_not_litter"]],"1f6b0":["\uD83D\uDEB0",["potable_water"]],"1f6b1":["\uD83D\uDEB1",["non-potable_water"]],"1f6b2":["\uD83D\uDEB2",["bike"]],"1f6b3":["\uD83D\uDEB3",["no_bicycles"]],"1f6b4":["\uD83D\uDEB4",["bicyclist"]],"1f6b5":["\uD83D\uDEB5",["mountain_bicyclist"]],"1f6b6":["\uD83D\uDEB6",["walking"]],"1f6b7":["\uD83D\uDEB7",["no_pedestrians"]],"1f6b8":["\uD83D\uDEB8",["children_crossing"]],"1f6b9":["\uD83D\uDEB9",["mens"]],"1f6ba":["\uD83D\uDEBA",["womens"]],"1f6bb":["\uD83D\uDEBB",["restroom"]],"1f6bc":["\uD83D\uDEBC",["baby_symbol"]],"1f6bd":["\uD83D\uDEBD",["toilet"]],"1f6be":["\uD83D\uDEBE",["wc"]],"1f6bf":["\uD83D\uDEBF",["shower"]],"1f6c0":["\uD83D\uDEC0",["bath"]],"1f6c1":["\uD83D\uDEC1",["bathtub"]],"1f6c2":["\uD83D\uDEC2",["passport_control"]],"1f6c3":["\uD83D\uDEC3",["customs"]],"1f6c4":["\uD83D\uDEC4",["baggage_claim"]],"1f6c5":["\uD83D\uDEC5",["left_luggage"]],"0023":["\u0023\u20E3",["hash"]],"0030":["\u0030\u20E3",["zero"]],"0031":["\u0031\u20E3",["one"]],"0032":["\u0032\u20E3",["two"]],"0033":["\u0033\u20E3",["three"]],"0034":["\u0034\u20E3",["four"]],"0035":["\u0035\u20E3",["five"]],"0036":["\u0036\u20E3",["six"]],"0037":["\u0037\u20E3",["seven"]],"0038":["\u0038\u20E3",["eight"]],"0039":["\u0039\u20E3",["nine"]],"1f1e8-1f1f3":["\uD83C\uDDE8\uD83C\uDDF3",["cn"]],"1f1e9-1f1ea":["\uD83C\uDDE9\uD83C\uDDEA",["de"]],"1f1ea-1f1f8":["\uD83C\uDDEA\uD83C\uDDF8",["es"]],"1f1eb-1f1f7":["\uD83C\uDDEB\uD83C\uDDF7",["fr"]],"1f1ec-1f1e7":["\uD83C\uDDEC\uD83C\uDDE7",["gb","uk"]],"1f1ee-1f1f9":["\uD83C\uDDEE\uD83C\uDDF9",["it"]],"1f1ef-1f1f5":["\uD83C\uDDEF\uD83C\uDDF5",["jp"]],"1f1f0-1f1f7":["\uD83C\uDDF0\uD83C\uDDF7",["kr"]],"1f1f7-1f1fa":["\uD83C\uDDF7\uD83C\uDDFA",["ru"]],"1f1fa-1f1f8":["\uD83C\uDDFA\uD83C\uDDF8",["us"]]} |
||
|
||
Config.EmojiCategories = [[ "1f604", "1f603", "1f600", "1f60a", "263a", "1f609", "1f60d","1f618", "1f61a", "1f617", "1f619", "1f61c", "1f61d", "1f61b","1f633", "1f601", "1f614", "1f60c", "1f612", "1f61e", "1f623","1f622", "1f602", "1f62d", "1f62a", "1f625", "1f630", "1f605","1f613", "1f629", "1f62b", "1f628", "1f631", "1f620", "1f621","1f624", "1f616", "1f606", "1f60b", "1f637", "1f60e", "1f634","1f635", "1f632", "1f61f", "1f626", "1f627", "1f608", "1f47f","1f62e", "1f62c", "1f610", "1f615", "1f62f", "1f636", "1f607","1f60f", "1f611", "1f472", "1f473", "1f46e", "1f477", "1f482","1f476", "1f466", "1f467", "1f468", "1f469", "1f474", "1f475","1f471", "1f47c", "1f478", "1f63a", "1f638", "1f63b", "1f63d","1f63c", "1f640", "1f63f", "1f639", "1f63e", "1f479", "1f47a","1f648", "1f649", "1f64a", "1f480", "1f47d", "1f4a9", "1f525","2728", "1f31f", "1f4ab", "1f4a5", "1f4a2", "1f4a6", "1f4a7","1f4a4", "1f4a8", "1f442", "1f440", "1f443", "1f445", "1f444","1f44d", "1f44e", "1f44c", "1f44a", "270a", "270c", "1f44b","270b", "1f450", "1f446", "1f447", "1f449", "1f448", "1f64c","1f64f", "261d", "1f44f", "1f4aa", "1f6b6", "1f3c3", "1f483","1f46b", "1f46a", "1f46c", "1f46d", "1f48f", "1f491", "1f46f","1f646", "1f645", "1f481", "1f64b", "1f486", "1f487", "1f485","1f470", "1f64e", "1f64d", "1f647", "1f3a9", "1f451", "1f452","1f45f", "1f45e", "1f461", "1f460", "1f462", "1f455", "1f454","1f45a", "1f457", "1f3bd", "1f456", "1f458", "1f459", "1f4bc","1f45c", "1f45d", "1f45b", "1f453", "1f380", "1f302", "1f484","1f49b", "1f499", "1f49c", "1f49a", "2764", "1f494", "1f497","1f493", "1f495", "1f496", "1f49e", "1f498", "1f48c", "1f48b","1f48d", "1f48e", "1f464", "1f465", "1f4ac", "1f463", "1f4ad" ],[ "1f436", "1f43a", "1f431", "1f42d", "1f439", "1f430", "1f438","1f42f", "1f428", "1f43b", "1f437", "1f43d", "1f42e", "1f417","1f435", "1f412", "1f434", "1f411", "1f418", "1f43c", "1f427","1f426", "1f424", "1f425", "1f423", "1f414", "1f40d", "1f422","1f41b", "1f41d", "1f41c", "1f41e", "1f40c", "1f419", "1f41a","1f420", "1f41f", "1f42c", "1f433", "1f40b", "1f404", "1f40f","1f400", "1f403", "1f405", "1f407", "1f409", "1f40e", "1f410","1f413", "1f415", "1f416", "1f401", "1f402", "1f432", "1f421","1f40a", "1f42b", "1f42a", "1f406", "1f408", "1f429", "1f43e","1f490", "1f338", "1f337", "1f340", "1f339", "1f33b", "1f33a","1f341", "1f343", "1f342", "1f33f", "1f33e", "1f344", "1f335","1f334", "1f332", "1f333", "1f330", "1f331", "1f33c", "1f310","1f31e", "1f31d", "1f31a", "1f311", "1f312", "1f313", "1f314","1f315", "1f316", "1f317", "1f318", "1f31c", "1f31b", "1f319","1f30d", "1f30e", "1f30f", "1f30b", "1f30c", "1f30d", "2b50","2600", "26c5", "2601", "26a1", "2614", "2744", "26c4", "1f300","1f301", "1f308", "1f30a" ],[ "1f38d", "1f49d", "1f38e", "1f392", "1f393", "1f38f", "1f386","1f387", "1f390", "1f391", "1f383", "1f47b", "1f385", "1f384","1f381", "1f38b", "1f389", "1f38a", "1f388", "1f38c", "1f52e","1f3a5", "1f4f7", "1f4f9", "1f4fc", "1f4bf", "1f4c0", "1f4bd","1f4be", "1f4bb", "1f4f1", "260e", "1f4de", "1f4df", "1f4e0","1f4e1", "1f4fa", "1f4fb", "1f50a", "1f509", "1f509", "1f507","1f514", "1f514", "1f4e2", "1f4e3", "23f3", "231b", "23f0","231a", "1f513", "1f512", "1f50f", "1f510", "1f511", "1f50e","1f4a1", "1f526", "1f506", "1f505", "1f50c", "1f50b", "1f50d","1f6c0", "1f6bf", "1f6bd", "1f527", "1f529", "1f528", "1f6aa","1f6ac", "1f4a3", "1f52b", "1f52a", "1f48a", "1f489", "1f4b0","1f4b4", "1f4b5", "1f4b7", "1f4b6", "1f4b3", "1f4b8", "1f4f2","1f4e7", "1f4e5", "1f4e4", "2709", "1f4e9", "1f4e8", "1f4ef","1f4eb", "1f4ea", "1f4ec", "1f4ed", "1f4ee", "1f4e6", "1f4dd","1f4c4", "1f4c3", "1f4d1", "1f4ca", "1f4c8", "1f4c9", "1f4dc","1f4cb", "1f4c5", "1f4c6", "1f4c7", "1f4c1", "1f4c2", "2702","1f4cc", "1f4ce", "2712", "270f", "1f4cf", "1f4d0", "1f4d5","1f4d7", "1f4d8", "1f4d9", "1f4d3", "1f4d4", "1f4d2", "1f4da","1f4d6", "1f516", "1f4db", "1f52c", "1f52d", "1f4f0", "1f3a8","1f3ac", "1f3a4", "1f3a7", "1f3bc", "1f3b5", "1f3b6", "1f3b9","1f3bb", "1f3ba", "1f3b7", "1f3b8", "1f47e", "1f3ae", "1f0cf","1f3b4", "1f004", "1f3b2", "1f3af", "1f3c8", "1f3c0", "26bd","26be", "1f3be", "1f3b1", "1f3c9", "1f3b3", "26f3", "1f6b5","1f6b4", "1f3c1", "1f3c7", "1f3c6", "1f3bf", "1f3c2", "1f3ca","1f3c4", "1f3a3", "2615", "1f375", "1f376", "1f37c", "1f37a","1f37b", "1f378", "1f379", "1f377", "1f374", "1f355", "1f354","1f35f", "1f357", "1f356", "1f35d", "1f35b", "1f364", "1f371","1f363", "1f365", "1f359", "1f358", "1f35a", "1f35c", "1f372","1f362", "1f361", "1f373", "1f35e", "1f369", "1f36e", "1f366","1f368", "1f367", "1f382", "1f370", "1f36a", "1f36b", "1f36c","1f36d", "1f36f", "1f34e", "1f34f", "1f34a", "1f34b", "1f352","1f347", "1f349", "1f353", "1f351", "1f348", "1f34c", "1f350","1f34d", "1f360", "1f346", "1f345", "1f33d" ],[ "1f3e0", "1f3e1", "1f3eb", "1f3e2", "1f3e3", "1f3e5", "1f3e6","1f3ea", "1f3e9", "1f3e8", "1f492", "26ea", "1f3ec", "1f3e4","1f307", "1f306", "1f3ef", "1f3f0", "26fa", "1f3ed", "1f5fc","1f5fe", "1f5fb", "1f304", "1f305", "1f303", "1f5fd", "1f309","1f3a0", "1f3a1", "26f2", "1f3a2", "1f6a2", "26f5", "1f6a4","1f6a3", "2693", "1f680", "2708", "1f4ba", "1f681", "1f682","1f68a", "1f689", "1f69e", "1f686", "1f684", "1f685", "1f688","1f687", "1f69d", "1f69d", "1f683", "1f68e", "1f68c", "1f68d","1f699", "1f698", "1f697", "1f695", "1f696", "1f69b", "1f69a","1f6a8", "1f693", "1f694", "1f692", "1f691", "1f690", "1f6b2","1f6a1", "1f69f", "1f6a0", "1f69c", "1f488", "1f68f", "1f3ab","1f6a6", "1f6a5", "26a0", "1f6a7", "1f530", "26fd", "1f3ee","1f3b0", "2668", "1f5ff", "1f3aa", "1f3ad", "1f4cd", "1f6a9","1f1ef-1f1f5", "1f1f0-1f1f7", "1f1e9-1f1ea", "1f1e8-1f1f3", "1f1fa-1f1f8", "1f1eb-1f1f7", "1f1ea-1f1f8","1f1ee-1f1f9", "1f1f7-1f1fa", "1f1ec-1f1e7" ],[ "0031", "0032", "0033", "0034", "0035", "0036", "0037","0038", "0039", "0030", "1f51f", "1f522", "0023", "1f523","2b06", "2b07", "2b05", "27a1", "1f520", "1f521", "1f524","2197", "2196", "2198", "2199", "2194", "2195", "1f504","25c0", "25b6", "1f53c", "1f53d", "21a9", "21aa", "2139","23ea", "23e9", "23eb", "23ec", "2935", "2934", "1f197","1f500", "1f501", "1f502", "1f195", "1f199", "1f192", "1f193","1f196", "1f4f6", "1f3a6", "1f201", "1f22f", "1f233", "1f235","1f232", "1f234", "1f232", "1f250", "1f239", "1f23a", "1f236","1f21a", "1f6bb", "1f6b9", "1f6ba", "1f6bc", "1f6be", "1f6b0","1f6ae", "1f17f", "267f", "1f6ad", "1f237", "1f238", "1f202","24c2", "1f251", "3299", "3297", "1f191", "1f198", "1f194","1f6ab", "1f51e", "1f4f5", "1f6af", "1f6b1", "1f6b3", "1f6b7","1f6b8", "26d4", "2733", "2747", "274e", "2705", "2734","1f49f", "1f19a", "1f4f3", "1f4f4", "1f170", "1f171", "1f18e","1f17e", "1f4a0", "27bf", "267b", "2648", "2649", "264a","264b", "264c", "264d", "264e", "264f", "2650", "2651","2652", "2653", "26ce", "1f52f", "1f3e7", "1f4b9", "1f4b2","1f4b1", "00a9", "00ae", "2122", "303d", "3030", "1f51d","1f51a", "1f519", "1f51b", "1f51c", "274c", "2b55", "2757","2753", "2755", "2754", "1f503", "1f55b", "1f567", "1f550","1f55c", "1f551", "1f55d", "1f552", "1f55e", "1f553", "1f55f","1f554", "1f560", "1f555", "1f556", "1f557", "1f558", "1f559","1f55a", "1f561", "1f562", "1f563", "1f564", "1f565", "1f566","2716", "2795", "2796", "2797", "2660", "2665", "2663","2666", "1f4ae", "1f4af", "2714", "2611", "1f518", "1f517","27b0", "1f531", "1f532", "1f533", "25fc", "25fb", "25fe","25fd", "25aa", "25ab", "1f53a", "2b1c", "2b1b", "26ab","26aa", "1f534", "1f535", "1f53b", "1f536", "1f537", "1f538","1f539" ]]; |
||
|
||
Config.EmojiCategorySpritesheetDimens = [[7, 27], [4, 29], [7, 33], [3, 34], [6,34]]; |
||
|
||
/*! |
||
* Webogram v0.0.20 - messaging web application for MTProto |
||
* https://github.com/zhukov/webogram |
||
* Copyright (C) 2014 Igor Zhukov <[email protected]> |
||
* https://github.com/zhukov/webogram/blob/master/LICENSE |
||
*/ |
||
|
||
function bigint (num) { |
||
return new BigInteger(num.toString(16), 16); |
||
} |
||
|
||
function bigStringInt (strNum) { |
||
return new BigInteger(strNum, 10); |
||
} |
||
|
||
function dHexDump (bytes) { |
||
var arr = []; |
||
for (var i = 0; i < bytes.length; i++) { |
||
if (i && !(i % 2)) { |
||
if (!(i % 16)) { |
||
arr.push("\n"); |
||
} else if (!(i % 4)) { |
||
arr.push(' '); |
||
} else { |
||
arr.push(' '); |
||
} |
||
} |
||
arr.push((bytes[i] < 16 ? '0' : '') + bytes[i].toString(16)); |
||
} |
||
|
||
console.log(arr.join('')); |
||
} |
||
|
||
function bytesToHex (bytes) { |
||
var arr = []; |
||
for (var i = 0; i < bytes.length; i++) { |
||
arr.push((bytes[i] < 16 ? '0' : '') + bytes[i].toString(16)); |
||
} |
||
return arr.join(''); |
||
} |
||
|
||
function bytesFromHex (hexString) { |
||
var len = hexString.length, |
||
i, |
||
bytes = []; |
||
|
||
for (i = 0; i < len; i += 2) { |
||
bytes.push(parseInt(hexString.substr(i, 2), 16)); |
||
} |
||
|
||
return bytes; |
||
} |
||
|
||
function bytesToBase64 (bytes) { |
||
var mod3, result = ''; |
||
|
||
for (var nLen = bytes.length, nUint24 = 0, nIdx = 0; nIdx < nLen; nIdx++) { |
||
mod3 = nIdx % 3; |
||
nUint24 |= bytes[nIdx] << (16 >>> mod3 & 24); |
||
if (mod3 === 2 || nLen - nIdx === 1) { |
||
result += String.fromCharCode( |
||
uint6ToBase64(nUint24 >>> 18 & 63), |
||
uint6ToBase64(nUint24 >>> 12 & 63), |
||
uint6ToBase64(nUint24 >>> 6 & 63), |
||
uint6ToBase64(nUint24 & 63) |
||
); |
||
nUint24 = 0; |
||
} |
||
} |
||
|
||
return result.replace(/A(?=A$|$)/g, '='); |
||
} |
||
|
||
function uint6ToBase64 (nUint6) { |
||
return nUint6 < 26 |
||
? nUint6 + 65 |
||
: nUint6 < 52 |
||
? nUint6 + 71 |
||
: nUint6 < 62 |
||
? nUint6 - 4 |
||
: nUint6 === 62 |
||
? 43 |
||
: nUint6 === 63 |
||
? 47 |
||
: 65; |
||
} |
||
|
||
function bytesCmp (bytes1, bytes2) { |
||
var len = bytes1.length; |
||
if (len != bytes2.length) { |
||
return false; |
||
} |
||
|
||
for (var i = 0; i < len; i++) { |
||
if (bytes1[i] != bytes2[i]) { |
||
return false; |
||
} |
||
} |
||
return true; |
||
} |
||
|
||
function bytesXor (bytes1, bytes2) { |
||
var len = bytes1.length, |
||
bytes = []; |
||
|
||
for (var i = 0; i < len; ++i) { |
||
bytes[i] = bytes1[i] ^ bytes2[i]; |
||
} |
||
|
||
return bytes; |
||
} |
||
|
||
function bytesToWords (bytes) { |
||
var len = bytes.length, |
||
words = []; |
||
|
||
for (var i = 0; i < len; i++) { |
||
words[i >>> 2] |= bytes[i] << (24 - (i % 4) * 8); |
||
} |
||
|
||
return new CryptoJS.lib.WordArray.init(words, len); |
||
} |
||
|
||
function bytesFromWords (wordArray) { |
||
var words = wordArray.words, |
||
sigBytes = wordArray.sigBytes, |
||
bytes = []; |
||
|
||
for (var i = 0; i < sigBytes; i++) { |
||
bytes.push((words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff); |
||
} |
||
|
||
return bytes; |
||
} |
||
|
||
function bytesFromBigInt (bigInt, len) { |
||
var bytes = bigInt.toByteArray(); |
||
|
||
while (!bytes[0] && (!len || bytes.length > len)) { |
||
bytes = bytes.slice(1); |
||
} |
||
|
||
return bytes; |
||
} |
||
|
||
function bytesToArrayBuffer (b) { |
||
return (new Uint8Array(b)).buffer; |
||
} |
||
|
||
function bytesFromArrayBuffer (buffer) { |
||
var len = buffer.byteLength, |
||
byteView = new Uint8Array(buffer), |
||
bytes = []; |
||
|
||
for (var i = 0; i < len; ++i) { |
||
bytes[i] = byteView[i]; |
||
} |
||
|
||
return bytes; |
||
} |
||
|
||
function longToInts (sLong) { |
||
var divRem = bigStringInt(sLong).divideAndRemainder(bigint(0x100000000)); |
||
|
||
return [divRem[0].intValue(), divRem[1].intValue()]; |
||
} |
||
|
||
function longToBytes (sLong) { |
||
return bytesFromWords({words: longToInts(sLong), sigBytes: 8}).reverse(); |
||
} |
||
|
||
function longFromInts (high, low) { |
||
return bigint(high).shiftLeft(32).add(bigint(low)).toString(10); |
||
} |
||
|
||
function intToUint (val) { |
||
val = parseInt(val); |
||
if (val < 0) { |
||
val = val + 4294967296; |
||
} |
||
return val; |
||
} |
||
|
||
function uintToInt (val) { |
||
if (val > 2147483647) { |
||
val = val - 4294967296; |
||
} |
||
return val; |
||
} |
||
|
||
function sha1Hash (bytes) { |
||
// console.log('SHA-1 hash start'); |
||
var hashBytes = sha1.hash(bytes, true); |
||
// console.log('SHA-1 hash finish'); |
||
|
||
return hashBytes; |
||
} |
||
|
||
|
||
|
||
function rsaEncrypt (publicKey, bytes) { |
||
var needPadding = 255 - bytes.length; |
||
if (needPadding > 0) { |
||
var padding = new Array(needPadding); |
||
(new SecureRandom()).nextBytes(padding); |
||
|
||
bytes = bytes.concat(padding); |
||
} |
||
|
||
// console.log('RSA encrypt start'); |
||
var N = new BigInteger(publicKey.modulus, 16), |
||
E = new BigInteger(publicKey.exponent, 16), |
||
X = new BigInteger(bytes), |
||
encryptedBigInt = X.modPowInt(E, N), |
||
encryptedBytes = bytesFromBigInt(encryptedBigInt, 256); |
||
|
||
// console.log('RSA encrypt finish'); |
||
|
||
return encryptedBytes; |
||
} |
||
|
||
function aesEncrypt (bytes, keyBytes, ivBytes) { |
||
// console.log('AES encrypt start', bytes.length/*, bytesToHex(keyBytes), bytesToHex(ivBytes)*/); |
||
|
||
var needPadding = 16 - (bytes.length % 16); |
||
if (needPadding > 0 && needPadding < 16) { |
||
var padding = new Array(needPadding); |
||
(new SecureRandom()).nextBytes(padding); |
||
|
||
bytes = bytes.concat(padding); |
||
} |
||
|
||
var encryptedWords = CryptoJS.AES.encrypt(bytesToWords(bytes), bytesToWords(keyBytes), { |
||
iv: bytesToWords(ivBytes), |
||
padding: CryptoJS.pad.NoPadding, |
||
mode: CryptoJS.mode.IGE |
||
}).ciphertext; |
||
|
||
var encryptedBytes = bytesFromWords(encryptedWords); |
||
|
||
// console.log('AES encrypt finish'); |
||
|
||
return encryptedBytes; |
||
} |
||
|
||
function aesDecrypt (encryptedBytes, keyBytes, ivBytes) { |
||
// console.log('AES decrypt start', encryptedBytes.length/*, bytesToHex(keyBytes), bytesToHex(ivBytes)*/); |
||
|
||
var decryptedWords = CryptoJS.AES.decrypt({ciphertext: bytesToWords(encryptedBytes)}, bytesToWords(keyBytes), { |
||
iv: bytesToWords(ivBytes), |
||
padding: CryptoJS.pad.NoPadding, |
||
mode: CryptoJS.mode.IGE |
||
}); |
||
|
||
var bytes = bytesFromWords(decryptedWords); |
||
|
||
// console.log('AES decrypt finish'); |
||
|
||
return bytes; |
||
} |
||
|
||
function gzipUncompress (bytes) { |
||
// console.log('Gzip uncompress start'); |
||
var result = (new Zlib.Gunzip(bytes)).decompress(); |
||
// console.log('Gzip uncompress finish'); |
||
return result; |
||
} |
||
|
||
function nextRandomInt (maxValue) { |
||
return Math.floor(Math.random() * maxValue); |
||
}; |
||
|
||
function pqPrimeFactorization (pqBytes) { |
||
console.log('PQ start'); |
||
|
||
var what = new BigInteger(pqBytes), |
||
g; |
||
|
||
var it = 0; |
||
for (var i = 0; i < 3; i++) { |
||
var q = (nextRandomInt(128) & 15) + 17, |
||
x = bigint(nextRandomInt(1000000000) + 1), |
||
y = x.clone(), |
||
lim = 1 << (i + 18); |
||
|
||
for (var j = 1; j < lim; j++) { |
||
++it; |
||
var a = x.clone(), |
||
b = x.clone(), |
||
c = bigint(q); |
||
|
||
while (!b.equals(BigInteger.ZERO)) { |
||
if (!b.and(BigInteger.ONE).equals(BigInteger.ZERO)) { |
||
c = c.add(a); |
||
if (c.compareTo(what) > 0) { |
||
c = c.subtract(what); |
||
} |
||
} |
||
a = a.add(a); |
||
if (a.compareTo(what) > 0) { |
||
a = a.subtract(what); |
||
} |
||
b = b.shiftRight(1); |
||
} |
||
|
||
x = c.clone(); |
||
var z = x.compareTo(y) < 0 ? y.subtract(x) : x.subtract(y); |
||
g = z.gcd(what); |
||
if (!g.equals(BigInteger.ONE)) { |
||
break; |
||
} |
||
if ((j & (j - 1)) == 0) { |
||
y = x.clone(); |
||
} |
||
} |
||
if (g.compareTo(BigInteger.ONE) > 0) { |
||
break; |
||
} |
||
} |
||
|
||
var f = what.divide(g), P, Q; |
||
|
||
if (g.compareTo(f) > 0) { |
||
P = f; |
||
Q = g; |
||
} else { |
||
P = g; |
||
Q = f; |
||
} |
||
|
||
console.log('PQ finish', it + ' iterations'); |
||
|
||
return [bytesFromBigInt(P), bytesFromBigInt(Q)]; |
||
} |
||
|
||
|
||
function TLSerialization (options) { |
||
options = options || {}; |
||
this.maxLength = options.startMaxLength || 2048; // 2Kb |
||
this.offset = 0; // in bytes |
||
|
||
this.createBuffer(); |
||
|
||
// this.debug = options.debug !== undefined ? options.debug : window._debugMode; |
||
this.mtproto = options.mtproto || false; |
||
return this; |
||
} |
||
|
||
TLSerialization.prototype.createBuffer = function () { |
||
this.buffer = new ArrayBuffer(this.maxLength); |
||
this.intView = new Int32Array(this.buffer); |
||
this.byteView = new Uint8Array(this.buffer); |
||
}; |
||
|
||
TLSerialization.prototype.getArray = function () { |
||
var resultBuffer = new ArrayBuffer(this.offset); |
||
var resultArray = new Int32Array(resultBuffer); |
||
|
||
resultArray.set(this.intView.subarray(0, this.offset / 4)); |
||
|
||
return resultArray; |
||
}; |
||
|
||
TLSerialization.prototype.getBuffer = function () { |
||
return this.getArray().buffer; |
||
}; |
||
|
||
TLSerialization.prototype.getBytes = function () { |
||
var bytes = []; |
||
for (var i = 0; i < this.offset; i++) { |
||
bytes.push(this.byteView[i]); |
||
} |
||
return bytes; |
||
}; |
||
|
||
TLSerialization.prototype.checkLength = function (needBytes) { |
||
if (this.offset + needBytes < this.maxLength) { |
||
return; |
||
} |
||
|
||
console.trace('Increase buffer', this.offset, needBytes, this.maxLength); |
||
this.maxLength = Math.ceil(Math.max(this.maxLength * 2, this.offset + needBytes + 16) / 4) * 4; |
||
var previousBuffer = this.buffer, |
||
previousArray = new Int32Array(previousBuffer); |
||
|
||
this.createBuffer(); |
||
|
||
new Int32Array(this.buffer).set(previousArray); |
||
}; |
||
|
||
TLSerialization.prototype.writeInt = function (i, field) { |
||
this.debug && console.log('>>>', i.toString(16), i, field); |
||
|
||
this.checkLength(4); |
||
this.intView[this.offset / 4] = i; |
||
this.offset += 4; |
||
}; |
||
|
||
TLSerialization.prototype.storeInt = function (i, field) { |
||
this.writeInt(i, (field || '') + ':int'); |
||
}; |
||
|
||
TLSerialization.prototype.storeBool = function (i, field) { |
||
if (i) { |
||
this.writeInt(0x997275b5, (field || '') + ':bool'); |
||
} else { |
||
this.writeInt(0xbc799737, (field || '') + ':bool'); |
||
} |
||
}; |
||
|
||
TLSerialization.prototype.storeLongP = function (iHigh, iLow, field) { |
||
this.writeInt(iLow, (field || '') + ':long[low]'); |
||
this.writeInt(iHigh, (field || '') + ':long[high]'); |
||
}; |
||
|
||
TLSerialization.prototype.storeLong = function (sLong, field) { |
||
if (angular.isArray(sLong)) { |
||
if (sLong.length == 2) { |
||
return this.storeLongP(sLong[0], sLong[1], field); |
||
} else { |
||
return this.storeIntBytes(sLong, 64, field); |
||
} |
||
} |
||
|
||
var divRem = bigStringInt(sLong).divideAndRemainder(bigint(0x100000000)); |
||
|
||
this.writeInt(intToUint(divRem[1].intValue()), (field || '') + ':long[low]'); |
||
this.writeInt(intToUint(divRem[0].intValue()), (field || '') + ':long[high]'); |
||
}; |
||
|
||
TLSerialization.prototype.storeDouble = function (f) { |
||
var buffer = new ArrayBuffer(8); |
||
var intView = new Int32Array(buffer); |
||
var doubleView = new Float64Array(buffer); |
||
|
||
doubleView[0] = f; |
||
|
||
this.writeInt(intView[0], (field || '') + ':double[low]'); |
||
this.writeInt(intView[1], (field || '') + ':double[high]'); |
||
}; |
||
|
||
TLSerialization.prototype.storeString = function (s, field) { |
||
this.debug && console.log('>>>', s, (field || '') + ':string'); |
||
|
||
var sUTF8 = unescape(encodeURIComponent(s)); |
||
|
||
this.checkLength(sUTF8.length + 8); |
||
|
||
|
||
var len = sUTF8.length; |
||
if (len <= 253) { |
||
this.byteView[this.offset++] = len; |
||
} else { |
||
this.byteView[this.offset++] = 254; |
||
this.byteView[this.offset++] = len & 0xFF; |
||
this.byteView[this.offset++] = (len & 0xFF00) >> 8; |
||
this.byteView[this.offset++] = (len & 0xFF0000) >> 16; |
||
} |
||
for (var i = 0; i < len; i++) { |
||
this.byteView[this.offset++] = sUTF8.charCodeAt(i); |
||
} |
||
|
||
// Padding |
||
while (this.offset % 4) { |
||
this.byteView[this.offset++] = 0; |
||
} |
||
} |
||
|
||
|
||
TLSerialization.prototype.storeBytes = function (bytes, field) { |
||
this.debug && console.log('>>>', bytesToHex(bytes), (field || '') + ':bytes'); |
||
|
||
this.checkLength(bytes.length + 8); |
||
|
||
var len = bytes.length; |
||
if (len <= 253) { |
||
this.byteView[this.offset++] = len; |
||
} else { |
||
this.byteView[this.offset++] = 254; |
||
this.byteView[this.offset++] = len & 0xFF; |
||
this.byteView[this.offset++] = (len & 0xFF00) >> 8; |
||
this.byteView[this.offset++] = (len & 0xFF0000) >> 16; |
||
} |
||
for (var i = 0; i < len; i++) { |
||
this.byteView[this.offset++] = bytes[i]; |
||
} |
||
|
||
// Padding |
||
while (this.offset % 4) { |
||
this.byteView[this.offset++] = 0; |
||
} |
||
} |
||
|
||
TLSerialization.prototype.storeIntBytes = function (bytes, bits, field) { |
||
var len = bytes.length; |
||
if ((bits % 32) || (len * 8) != bits) { |
||
throw new Error('Invalid bits: ' + bits + ', ' + bytes.length); |
||
} |
||
|
||
this.debug && console.log('>>>', bytesToHex(bytes), (field || '') + ':int' + bits); |
||
this.checkLength(len); |
||
|
||
for (var i = 0; i < len; i++) { |
||
this.byteView[this.offset++] = bytes[i]; |
||
} |
||
}; |
||
|
||
TLSerialization.prototype.storeRawBytes = function (bytes, field) { |
||
var len = bytes.length; |
||
|
||
this.debug && console.log('>>>', bytesToHex(bytes), (field || '')); |
||
this.checkLength(len); |
||
|
||
for (var i = 0; i < len; i++) { |
||
this.byteView[this.offset++] = bytes[i]; |
||
} |
||
}; |
||
|
||
|
||
TLSerialization.prototype.storeMethod = function (methodName, params) { |
||
var schema = this.mtproto ? Config.Schema.MTProto : Config.Schema.API, |
||
methodData = false, |
||
i; |
||
|
||
for (i = 0; i < schema.methods.length; i++) { |
||
if (schema.methods[i].method == methodName) { |
||
methodData = schema.methods[i]; |
||
break |
||
} |
||
} |
||
if (!methodData) { |
||
throw new Error('No method ' + methodName + ' found'); |
||
} |
||
|
||
this.storeInt(intToUint(methodData.id), methodName + '[id]'); |
||
|
||
var self = this; |
||
angular.forEach(methodData.params, function (param) { |
||
self.storeObject(params[param.name], param.type, methodName + '[' + param.name + ']'); |
||
}); |
||
}; |
||
|
||
TLSerialization.prototype.storeObject = function (obj, type, field) { |
||
switch (type) { |
||
case 'int': return this.storeInt(obj, field); |
||
case 'long': return this.storeLong(obj, field); |
||
case 'int128': return this.storeIntBytes(obj, 128, field); |
||
case 'int256': return this.storeIntBytes(obj, 256, field); |
||
case 'int512': return this.storeIntBytes(obj, 512, field); |
||
case 'string': return this.storeString(obj, field); |
||
case 'bytes': return this.storeBytes(obj, field); |
||
case 'double': return this.storeDouble(obj, field); |
||
case 'Bool': return this.storeBool(obj, field); |
||
} |
||
|
||
if (angular.isArray(obj)) { |
||
if (type.substr(0, 6) == 'Vector') { |
||
this.writeInt(0x1cb5c415, field + '[id]'); |
||
} |
||
else if (type.substr(0, 6) != 'vector') { |
||
throw new Error('Invalid vector type ' + type); |
||
} |
||
var itemType = type.substr(7, type.length - 8); // for "Vector<itemType>" |
||
this.writeInt(obj.length, field + '[count]'); |
||
for (var i = 0; i < obj.length; i++) { |
||
this.storeObject(obj[i], itemType, field + '[' + i + ']'); |
||
} |
||
return true; |
||
} |
||
else if (type.substr(0, 6).toLowerCase() == 'vector') { |
||
throw new Error('Invalid vector object'); |
||
} |
||
|
||
if (!angular.isObject(obj)) { |
||
throw new Error('Invalid object for type ' + type); |
||
} |
||
|
||
var schema = this.mtproto ? Config.Schema.MTProto : Config.Schema.API, |
||
predicate = obj['_'], |
||
isBare = false, |
||
constructorData = false, |
||
i; |
||
|
||
if (isBare = (type.charAt(0) == '%')) { |
||
type = type.substr(1); |
||
} |
||
|
||
for (i = 0; i < schema.constructors.length; i++) { |
||
if (schema.constructors[i].predicate == predicate) { |
||
constructorData = schema.constructors[i]; |
||
break |
||
} |
||
} |
||
if (!constructorData) { |
||
throw new Error('No predicate ' + predicate + ' found'); |
||
} |
||
|
||
if (predicate == type) { |
||
isBare = true; |
||
} |
||
|
||
if (!isBare) { |
||
this.writeInt(intToUint(constructorData.id), field + '[' + predicate + '][id]'); |
||
} |
||
|
||
var self = this; |
||
angular.forEach(constructorData.params, function (param) { |
||
self.storeObject(obj[param.name], param.type, field + '[' + predicate + '][' + param.name + ']'); |
||
}); |
||
}; |
||
|
||
|
||
|
||
function TLDeserialization (buffer, options) { |
||
options = options || {}; |
||
|
||
this.offset = 0; // in bytes |
||
|
||
this.buffer = buffer; |
||
this.intView = new Uint32Array(this.buffer); |
||
this.byteView = new Uint8Array(this.buffer); |
||
|
||
// this.debug = options.debug !== undefined ? options.debug : window._debugMode; |
||
this.mtproto = options.mtproto || false; |
||
return this; |
||
} |
||
|
||
TLDeserialization.prototype.readInt = function (field) { |
||
if (this.offset >= this.intView.length * 4) { |
||
throw new Error('Nothing to fetch'); |
||
} |
||
|
||
var i = this.intView[this.offset / 4]; |
||
|
||
this.debug && console.log('<<<', i.toString(16), i, field); |
||
|
||
this.offset += 4; |
||
|
||
return i; |
||
}; |
||
|
||
TLDeserialization.prototype.fetchInt = function (field) { |
||
return this.readInt((field || '') + ':int'); |
||
} |
||
|
||
TLDeserialization.prototype.fetchDouble = function (field) { |
||
var buffer = new ArrayBuffer(8); |
||
var intView = new Int32Array(buffer); |
||
var doubleView = new Float64Array(buffer); |
||
|
||
intView[0] = this.readInt((field || '') + ':double[low]'), |
||
intView[1] = this.readInt((field || '') + ':double[high]'); |
||
|
||
return doubleView[0]; |
||
}; |
||
|
||
TLDeserialization.prototype.fetchLong = function (field) { |
||
var iLow = this.readInt((field || '') + ':long[low]'), |
||
iHigh = this.readInt((field || '') + ':long[high]'); |
||
|
||
var longDec = bigint(iHigh).shiftLeft(32).add(bigint(iLow)).toString(); |
||
|
||
return longDec; |
||
} |
||
|
||
TLDeserialization.prototype.fetchBool = function (field) { |
||
var i = this.readInt((field || '') + ':bool'); |
||
if (i == 0x997275b5) { |
||
return true; |
||
} else if (i == 0xbc799737) { |
||
return false |
||
} |
||
throw new Error('Unknown Bool constructor ' + i); |
||
} |
||
|
||
TLDeserialization.prototype.fetchString = function (field) { |
||
var len = this.byteView[this.offset++]; |
||
|
||
if (len == 254) { |
||
var len = this.byteView[this.offset++] | |
||
(this.byteView[this.offset++] << 8) | |
||
(this.byteView[this.offset++] << 16); |
||
} |
||
|
||
var sUTF8 = ''; |
||
for (var i = 0; i < len; i++) { |
||
sUTF8 += String.fromCharCode(this.byteView[this.offset++]); |
||
} |
||
|
||
// Padding |
||
while (this.offset % 4) { |
||
this.offset++; |
||
} |
||
|
||
try { |
||
var s = decodeURIComponent(escape(sUTF8)); |
||
} catch (e) { |
||
var s = sUTF8; |
||
} |
||
|
||
this.debug && console.log('<<<', s, (field || '') + ':string'); |
||
|
||
return s; |
||
} |
||
|
||
|
||
TLDeserialization.prototype.fetchBytes = function (field) { |
||
var len = this.byteView[this.offset++]; |
||
|
||
if (len == 254) { |
||
var len = this.byteView[this.offset++] | |
||
(this.byteView[this.offset++] << 8) | |
||
(this.byteView[this.offset++] << 16); |
||
} |
||
|
||
var bytes = []; |
||
for (var i = 0; i < len; i++) { |
||
bytes.push(this.byteView[this.offset++]); |
||
} |
||
|
||
// Padding |
||
while (this.offset % 4) { |
||
this.offset++; |
||
} |
||
|
||
this.debug && console.log('<<<', bytesToHex(bytes), (field || '') + ':bytes'); |
||
|
||
return bytes; |
||
} |
||
|
||
TLDeserialization.prototype.fetchIntBytes = function (bits, field) { |
||
if (bits % 32) { |
||
throw new Error('Invalid bits: ' + bits); |
||
} |
||
|
||
var len = bits / 8; |
||
var bytes = []; |
||
for (var i = 0; i < len; i++) { |
||
bytes.push(this.byteView[this.offset++]); |
||
} |
||
|
||
this.debug && console.log('<<<', bytesToHex(bytes), (field || '') + ':int' + bits); |
||
|
||
return bytes; |
||
}; |
||
|
||
|
||
TLDeserialization.prototype.fetchRawBytes = function (len, field) { |
||
if (len === false) { |
||
len = this.readInt((field || '') + '_length'); |
||
} |
||
|
||
var bytes = []; |
||
for (var i = 0; i < len; i++) { |
||
bytes.push(this.byteView[this.offset++]); |
||
} |
||
|
||
this.debug && console.log('<<<', bytesToHex(bytes), (field || '')); |
||
|
||
return bytes; |
||
}; |
||
|
||
TLDeserialization.prototype.fetchObject = function (type, field) { |
||
switch (type) { |
||
case 'int': return this.fetchInt(field); |
||
case 'long': return this.fetchLong(field); |
||
case 'int128': return this.fetchIntBytes(128, field); |
||
case 'int256': return this.fetchIntBytes(256, field); |
||
case 'int512': return this.fetchIntBytes(512, field); |
||
case 'string': return this.fetchString(field); |
||
case 'bytes': return this.fetchBytes(field); |
||
case 'double': return this.fetchDouble(field); |
||
case 'Bool': return this.fetchBool(field); |
||
} |
||
|
||
field = field || type || 'Object'; |
||
|
||
if (type.substr(0, 6) == 'Vector' || type.substr(0, 6) == 'vector') { |
||
if (type.charAt(0) == 'V') { |
||
var constructor = this.readInt(field + '[id]'); |
||
if (constructor != 0x1cb5c415) { |
||
throw new Error('Invalid vector constructor ' + constructor); |
||
} |
||
} |
||
var len = this.readInt(field + '[count]'); |
||
var result = []; |
||
if (len > 0) { |
||
var itemType = type.substr(7, type.length - 8); // for "Vector<itemType>" |
||
for (var i = 0; i < len; i++) { |
||
result.push(this.fetchObject(itemType, field + '[' + i + ']')) |
||
} |
||
} |
||
|
||
return result; |
||
} |
||
|
||
var schema = this.mtproto ? Config.Schema.MTProto : Config.Schema.API, |
||
predicate = false, |
||
constructorData = false; |
||
|
||
if (type.charAt(0) == '%') { |
||
var checkType = type.substr(1); |
||
for (i = 0; i < schema.constructors.length; i++) { |
||
if (schema.constructors[i].type == checkType) { |
||
constructorData = schema.constructors[i]; |
||
break |
||
} |
||
} |
||
if (!constructorData) { |
||
throw new Error('Constructor not found for type: ' + type); |
||
} |
||
} |
||
else if (type.charAt(0) >= 97 && type.charAt(0) <= 122) { |
||
for (i = 0; i < schema.constructors.length; i++) { |
||
if (schema.constructors[i].predicate == type) { |
||
constructorData = schema.constructors[i]; |
||
break |
||
} |
||
} |
||
if (!constructorData) { |
||
throw new Error('Constructor not found for predicate: ' + type); |
||
} |
||
} |
||
else { |
||
var constructor = this.readInt(field + '[id]'), |
||
constructorCmp = uintToInt(constructor); |
||
|
||
if (constructorCmp == 0x3072cfa1) { // Gzip packed |
||
var compressed = this.fetchBytes(field + '[packed_string]'), |
||
uncompressed = gzipUncompress(compressed), |
||
buffer = bytesToArrayBuffer(uncompressed), |
||
newDeserializer = (new TLDeserialization(buffer)); |
||
|
||
return newDeserializer.fetchObject(type, field); |
||
} |
||
|
||
for (i = 0; i < schema.constructors.length; i++) { |
||
if (schema.constructors[i].id == constructorCmp) { |
||
constructorData = schema.constructors[i]; |
||
break; |
||
} |
||
} |
||
|
||
var fallback = false; |
||
if (!constructorData && this.mtproto) { |
||
var schemaFallback = Config.Schema.API; |
||
for (i = 0; i < schemaFallback.constructors.length; i++) { |
||
if (schemaFallback.constructors[i].id == constructorCmp) { |
||
constructorData = schemaFallback.constructors[i]; |
||
|
||
delete this.mtproto; |
||
fallback = true; |
||
break; |
||
} |
||
} |
||
} |
||
if (!constructorData) { |
||
throw new Error('Constructor not found: ' + constructor); |
||
} |
||
} |
||
|
||
predicate = constructorData.predicate; |
||
|
||
var result = {'_': predicate}; |
||
|
||
var self = this; |
||
angular.forEach(constructorData.params, function (param) { |
||
result[param.name] = self.fetchObject(param.type, field + '[' + predicate + '][' + param.name + ']'); |
||
}); |
||
|
||
if (fallback) { |
||
this.mtproto = true; |
||
} |
||
|
||
return result; |
||
}; |
||
|
||
TLDeserialization.prototype.getOffset = function () { |
||
return this.offset; |
||
}; |
||
|
||
TLDeserialization.prototype.fetchEnd = function () { |
||
if (this.offset != this.byteView.length) { |
||
throw new Error('Fetch end with non-empty buffer'); |
||
} |
||
return true; |
||
}; |
||
|
||
if (typeof angular != 'undefined') angular.module('mtproto.services', ['myApp.services']). |
||
|
||
factory('MtpDcConfigurator', function () { |
||
var dcOptions = window._testMode |
||
? [ |
||
{id: 1, host: '173.240.5.253', port: 80}, |
||
{id: 2, host: '109.239.131.195', port: 80}, |
||
{id: 3, host: '174.140.142.5', port: 80} |
||
] |
||
: [ |
||
{id: 1, host: '173.240.5.1', port: 80}, |
||
{id: 2, host: '109.239.131.193', port: 80}, |
||
{id: 3, host: '174.140.142.6', port: 80}, |
||
{id: 4, host: '31.210.235.12', port: 80}, |
||
{id: 5, host: '116.51.22.2', port: 80}, |
||
]; |
||
|
||
var chosenServers = {}; |
||
|
||
function chooseServer(dcID) { |
||
if (chosenServers[dcID] === undefined) { |
||
var chosenServer = false, |
||
i, dcOption; |
||
for (i = 0; i < dcOptions.length; i++) { |
||
dcOption = dcOptions[i]; |
||
if (dcOption.id == dcID) { |
||
chosenServer = dcOption.host + ':' + dcOption.port; |
||
} |
||
} |
||
chosenServers[dcID] = chosenServer; |
||
} |
||
|
||
return chosenServers[dcID]; |
||
} |
||
|
||
return { |
||
chooseServer: chooseServer |
||
}; |
||
}). |
||
|
||
factory('MtpRsaKeysManager', function () { |
||
|
||
/** |
||
* Server public key, obtained from here: https://core.telegram.org/api/obtaining_api_id |
||
* |
||
* -----BEGIN RSA PUBLIC KEY----- |
||
* MIIBCgKCAQEAwVACPi9w23mF3tBkdZz+zwrzKOaaQdr01vAbU4E1pvkfj4sqDsm6 |
||
* lyDONS789sVoD/xCS9Y0hkkC3gtL1tSfTlgCMOOul9lcixlEKzwKENj1Yz/s7daS |
||
* an9tqw3bfUV/nqgbhGX81v/+7RFAEd+RwFnK7a+XYl9sluzHRyVVaTTveB2GazTw |
||
* Efzk2DWgkBluml8OREmvfraX3bkHZJTKX4EQSjBbbdJ2ZXIsRrYOXfaA+xayEGB+ |
||
* 8hdlLmAjbCVfaigxX0CDqWeR1yFL9kwd9P0NsZRPsmoqVwMbMu7mStFai6aIhc3n |
||
* Slv8kg9qv1m6XHVQY3PnEw+QQtqSIXklHwIDAQAB |
||
* -----END RSA PUBLIC KEY----- |
||
*/ |
||
|
||
var publisKeysHex = [{ |
||
modulus: 'c150023e2f70db7985ded064759cfecf0af328e69a41daf4d6f01b538135a6f91f8f8b2a0ec9ba9720ce352efcf6c5680ffc424bd634864902de0b4bd6d49f4e580230e3ae97d95c8b19442b3c0a10d8f5633fecedd6926a7f6dab0ddb7d457f9ea81b8465fcd6fffeed114011df91c059caedaf97625f6c96ecc74725556934ef781d866b34f011fce4d835a090196e9a5f0e4449af7eb697ddb9076494ca5f81104a305b6dd27665722c46b60e5df680fb16b210607ef217652e60236c255f6a28315f4083a96791d7214bf64c1df4fd0db1944fb26a2a57031b32eee64ad15a8ba68885cde74a5bfc920f6abf59ba5c75506373e7130f9042da922179251f', |
||
exponent: '010001' |
||
}]; |
||
|
||
var publicKeysParsed = {}; |
||
var prepared = false; |
||
|
||
function prepareRsaKeys () { |
||
if (prepared) { |
||
return; |
||
} |
||
|
||
for (var i = 0; i < publisKeysHex.length; i++) { |
||
var keyParsed = publisKeysHex[i]; |
||
|
||
var RSAPublicKey = new TLSerialization(); |
||
RSAPublicKey.storeBytes(bytesFromHex(keyParsed.modulus), 'n'); |
||
RSAPublicKey.storeBytes(bytesFromHex(keyParsed.exponent), 'e'); |
||
|
||
var buffer = RSAPublicKey.getBuffer(); |
||
|
||
var fingerprintBytes = sha1Hash(buffer).slice(-8); |
||
fingerprintBytes.reverse(); |
||
|
||
var fingerprint = new BigInteger(fingerprintBytes).toString(16); |
||
|
||
publicKeysParsed[fingerprint] = { |
||
modulus: keyParsed.modulus, |
||
exponent: keyParsed.exponent |
||
}; |
||
} |
||
|
||
prepared = true; |
||
}; |
||
|
||
function selectRsaKeyByFingerPrint (fingerprints) { |
||
prepareRsaKeys(); |
||
|
||
var fingerprintHex, foundKey, i; |
||
for (i = 0; i < fingerprints.length; i++) { |
||
fingerprintHex = bigStringInt(fingerprints[i]).toString(16); |
||
if (foundKey = publicKeysParsed[fingerprintHex]) { |
||
return angular.extend({fingerprint: fingerprints[i]}, foundKey); |
||
} |
||
} |
||
|
||
return false; |
||
}; |
||
|
||
return { |
||
prepare: prepareRsaKeys, |
||
select: selectRsaKeyByFingerPrint |
||
}; |
||
}). |
||
|
||
service('MtpSecureRandom', SecureRandom). |
||
|
||
factory('MtpMessageIdGenerator', function (AppConfigManager) { |
||
var lastMessageID = [0, 0], |
||
timeOffset = 0; |
||
|
||
AppConfigManager.get('server_time_offset').then(function (to) { |
||
if (to) { |
||
timeOffset = to; |
||
} |
||
}); |
||
|
||
function generateMessageID () { |
||
var timeTicks = tsNow(), |
||
timeSec = Math.floor(timeTicks / 1000) + timeOffset, |
||
timeMSec = timeTicks % 1000, |
||
random = nextRandomInt(0xFFFF); |
||
|
||
var messageID = [timeSec, (timeMSec << 21) | (random << 3) | 4]; |
||
if (lastMessageID[0] > messageID[0] || |
||
lastMessageID[0] == messageID[0] && lastMessageID[1] >= messageID[1]) { |
||
|
||
messageID = [lastMessageID[0], lastMessageID[1] + 4]; |
||
} |
||
|
||
lastMessageID = messageID; |
||
|
||
// console.log('generated msg id', messageID); |
||
|
||
return longFromInts(messageID[0], messageID[1]); |
||
}; |
||
|
||
function applyServerTime (serverTime, localTime) { |
||
var newTimeOffset = serverTime - Math.floor((localTime || tsNow()) / 1000), |
||
changed = Math.abs(timeOffset - newTimeOffset) > 10; |
||
AppConfigManager.set({server_time_offset: newTimeOffset}); |
||
|
||
lastMessageID = [0, 0]; |
||
timeOffset = newTimeOffset; |
||
console.log('Apply server time', serverTime, localTime, newTimeOffset, changed); |
||
|
||
return changed; |
||
}; |
||
|
||
return { |
||
generateID: generateMessageID, |
||
applyServerTime: applyServerTime |
||
}; |
||
}). |
||
|
||
factory('MtpAuthorizer', function (MtpDcConfigurator, MtpRsaKeysManager, MtpSecureRandom, MtpMessageIdGenerator, $http, $q, $timeout) { |
||
|
||
function mtpSendPlainRequest (dcID, requestBuffer) { |
||
var requestLength = requestBuffer.byteLength, |
||
requestArray = new Int32Array(requestBuffer); |
||
|
||
var header = new TLSerialization(); |
||
header.storeLongP(0, 0, 'auth_key_id'); // Auth key |
||
header.storeLong(MtpMessageIdGenerator.generateID(), 'msg_id'); // Msg_id |
||
header.storeInt(requestLength, 'request_length'); |
||
|
||
var headerBuffer = header.getBuffer(), |
||
headerArray = new Int32Array(headerBuffer), |
||
headerLength = headerBuffer.byteLength; |
||
|
||
var resultBuffer = new ArrayBuffer(headerLength + requestLength), |
||
resultArray = new Int32Array(resultBuffer); |
||
|
||
resultArray.set(headerArray); |
||
resultArray.set(requestArray, headerArray.length); |
||
|
||
delete $http.defaults.headers.post['Content-Type']; |
||
delete $http.defaults.headers.common['Accept']; |
||
|
||
return $http.post('http://' + MtpDcConfigurator.chooseServer(dcID) + '/apiw1', resultArray.buffer, { |
||
responseType: 'arraybuffer', |
||
transformRequest: null, |
||
transformResponse: function (responseBuffer) { |
||
var deserializer = new TLDeserialization(responseBuffer, {mtproto: true}); |
||
|
||
var auth_key_id = deserializer.fetchLong('auth_key_id'); |
||
var msg_id = deserializer.fetchLong('msg_id'); |
||
var msg_len = deserializer.fetchInt('msg_len'); |
||
|
||
rng_seed_time(); |
||
|
||
return deserializer; |
||
} |
||
}); |
||
}; |
||
|
||
function mtpSendReqPQ (auth) { |
||
var deferred = auth.deferred; |
||
|
||
var request = new TLSerialization({mtproto: true}); |
||
|
||
request.storeMethod('req_pq', {nonce: auth.nonce}); |
||
|
||
console.log('Send req_pq', bytesToHex(auth.nonce)); |
||
mtpSendPlainRequest(auth.dcID, request.getBuffer()).then(function (result) { |
||
var deserializer = result.data; |
||
var response = deserializer.fetchObject('ResPQ'); |
||
|
||
if (response._ != 'resPQ') { |
||
throw new Error('resPQ response invalid: ' + response._); |
||
} |
||
|
||
if (!bytesCmp (auth.nonce, response.nonce)) { |
||
throw new Error('resPQ nonce mismatch'); |
||
} |
||
|
||
auth.serverNonce = response.server_nonce; |
||
auth.pq = response.pq; |
||
auth.fingerprints = response.server_public_key_fingerprints; |
||
|
||
console.log('Got ResPQ', bytesToHex(auth.serverNonce), bytesToHex(auth.pq), auth.fingerprints); |
||
|
||
auth.publicKey = MtpRsaKeysManager.select(auth.fingerprints); |
||
|
||
if (!auth.publicKey) { |
||
throw new Error('No public key found'); |
||
} |
||
|
||
console.log('PQ factorization start'); |
||
if (!!window.Worker) { |
||
var worker = new Worker('js/lib/pq_worker.js'); |
||
|
||
worker.onmessage = function (e) { |
||
auth.p = e.data[0]; |
||
auth.q = e.data[1]; |
||
mtpSendReqDhParams(auth); |
||
}; |
||
worker.onerror = function(error) { |
||
console.log('Worker error', error, error.stack); |
||
deferred.reject(error); |
||
}; |
||
worker.postMessage(auth.pq) |
||
} else { |
||
var pAndQ = pqPrimeFactorization(auth.pq); |
||
auth.p = pAndQ[0]; |
||
auth.q = pAndQ[1]; |
||
|
||
mtpSendReqDhParams(auth); |
||
} |
||
}, function (error) { |
||
deferred.reject(error); |
||
}); |
||
|
||
$timeout(function () { |
||
MtpRsaKeysManager.prepare(); |
||
}); |
||
}; |
||
|
||
function mtpSendReqDhParams (auth) { |
||
var deferred = auth.deferred; |
||
|
||
auth.newNonce = new Array(32); |
||
MtpSecureRandom.nextBytes(auth.newNonce); |
||
|
||
var data = new TLSerialization({mtproto: true}); |
||
data.storeObject({ |
||
_: 'p_q_inner_data', |
||
pq: auth.pq, |
||
p: auth.p, |
||
q: auth.q, |
||
nonce: auth.nonce, |
||
server_nonce: auth.serverNonce, |
||
new_nonce: auth.newNonce |
||
}, 'P_Q_inner_data', 'DECRYPTED_DATA'); |
||
|
||
var dataWithHash = sha1Hash(data.getBuffer()).concat(data.getBytes()); |
||
|
||
var request = new TLSerialization({mtproto: true}); |
||
request.storeMethod('req_DH_params', { |
||
nonce: auth.nonce, |
||
server_nonce: auth.serverNonce, |
||
p: auth.p, |
||
q: auth.q, |
||
public_key_fingerprint: auth.publicKey.fingerprint, |
||
encrypted_data: rsaEncrypt(auth.publicKey, dataWithHash) |
||
}); |
||
|
||
console.log('Send req_DH_params'); |
||
mtpSendPlainRequest(auth.dcID, request.getBuffer()).then(function (result) { |
||
var deserializer = result.data; |
||
var response = deserializer.fetchObject('Server_DH_Params', 'RESPONSE'); |
||
|
||
if (response._ != 'server_DH_params_fail' && response._ != 'server_DH_params_ok') { |
||
deferred.reject(new Error('Server_DH_Params response invalid: ' + response._)); |
||
return false; |
||
} |
||
|
||
if (!bytesCmp (auth.nonce, response.nonce)) { |
||
deferred.reject(new Error('Server_DH_Params nonce mismatch')); |
||
return false; |
||
} |
||
|
||
if (!bytesCmp (auth.serverNonce, response.server_nonce)) { |
||
deferred.reject(new Error('Server_DH_Params server_nonce mismatch')); |
||
return false; |
||
} |
||
|
||
if (response._ == 'server_DH_params_fail') { |
||
var newNonceHash = sha1Hash(auth.newNonce).slice(-16) |
||
if (!bytesCmp (newNonceHash, response.new_nonce_hash)) { |
||
deferred.reject(new Error('server_DH_params_fail new_nonce_hash mismatch')); |
||
return false; |
||
} |
||
deferred.reject(new Error('server_DH_params_fail')); |
||
return false; |
||
} |
||
|
||
try { |
||
mtpDecryptServerDhDataAnswer(auth, response.encrypted_answer); |
||
} catch (e) { |
||
deferred.reject(e); |
||
return false; |
||
} |
||
|
||
mtpSendSetClientDhParams(auth); |
||
}, function (error) { |
||
deferred.reject(error); |
||
}); |
||
}; |
||
|
||
function mtpDecryptServerDhDataAnswer (auth, encryptedAnswer) { |
||
auth.localTime = tsNow(); |
||
|
||
auth.tmpAesKey = sha1Hash(auth.newNonce.concat(auth.serverNonce)).concat(sha1Hash(auth.serverNonce.concat(auth.newNonce)).slice(0, 12)); |
||
auth.tmpAesIv = sha1Hash(auth.serverNonce.concat(auth.newNonce)).slice(12).concat(sha1Hash([].concat(auth.newNonce, auth.newNonce)), auth.newNonce.slice(0, 4)); |
||
|
||
var answerWithHash = aesDecrypt(encryptedAnswer, auth.tmpAesKey, auth.tmpAesIv); |
||
|
||
var hash = answerWithHash.slice(0, 20); |
||
var answerWithPadding = answerWithHash.slice(20); |
||
var buffer = bytesToArrayBuffer(answerWithPadding); |
||
|
||
var deserializer = new TLDeserialization(buffer, {mtproto: true}); |
||
var response = deserializer.fetchObject('Server_DH_inner_data'); |
||
|
||
if (response._ != 'server_DH_inner_data') { |
||
throw new Error('server_DH_inner_data response invalid: ' + constructor); |
||
} |
||
|
||
if (!bytesCmp (auth.nonce, response.nonce)) { |
||
throw new Error('server_DH_inner_data nonce mismatch'); |
||
} |
||
|
||
if (!bytesCmp (auth.serverNonce, response.server_nonce)) { |
||
throw new Error('server_DH_inner_data serverNonce mismatch'); |
||
} |
||
|
||
console.log('Done decrypting answer'); |
||
auth.g = response.g; |
||
auth.dhPrime = response.dh_prime; |
||
auth.gA = response.g_a; |
||
auth.serverTime = response.server_time; |
||
auth.retry = 0; |
||
|
||
var offset = deserializer.getOffset(); |
||
|
||
if (!bytesCmp(hash, sha1Hash(answerWithPadding.slice(0, offset)))) { |
||
throw new Error('server_DH_inner_data SHA1-hash mismatch'); |
||
} |
||
|
||
MtpMessageIdGenerator.applyServerTime(auth.serverTime, auth.localTime); |
||
}; |
||
|
||
function mtpSendSetClientDhParams(auth) { |
||
var deferred = auth.deferred; |
||
|
||
auth.b = new Array(256); |
||
MtpSecureRandom.nextBytes(auth.b); |
||
|
||
var bBigInt = new BigInteger(auth.b); |
||
var dhPrimeBigInt = new BigInteger(auth.dhPrime); |
||
|
||
var gB = bytesFromBigInt(bigint(auth.g).modPow(bBigInt, dhPrimeBigInt)); |
||
|
||
var data = new TLSerialization({mtproto: true}); |
||
data.storeObject({ |
||
_: 'client_DH_inner_data', |
||
nonce: auth.nonce, |
||
server_nonce: auth.serverNonce, |
||
retry_id: [0, auth.retry++], |
||
g_b: gB, |
||
}, 'Client_DH_Inner_Data'); |
||
|
||
var dataWithHash = sha1Hash(data.getBuffer()).concat(data.getBytes()); |
||
|
||
var encryptedData = aesEncrypt(dataWithHash, auth.tmpAesKey, auth.tmpAesIv); |
||
|
||
var request = new TLSerialization({mtproto: true}); |
||
request.storeMethod('set_client_DH_params', { |
||
nonce: auth.nonce, |
||
server_nonce: auth.serverNonce, |
||
encrypted_data: encryptedData |
||
}); |
||
|
||
console.log('Send set_client_DH_params'); |
||
mtpSendPlainRequest(auth.dcID, request.getBuffer()).then(function (result) { |
||
var deserializer = result.data; |
||
var response = deserializer.fetchObject('Set_client_DH_params_answer'); |
||
|
||
if (response._ != 'dh_gen_ok' && response._ != 'dh_gen_retry' && response._ != 'dh_gen_fail') { |
||
deferred.reject(new Error('Set_client_DH_params_answer response invalid: ' + response._)); |
||
return false; |
||
} |
||
|
||
if (!bytesCmp (auth.nonce, response.nonce)) { |
||
deferred.reject(new Error('Set_client_DH_params_answer nonce mismatch')); |
||
return false |
||
} |
||
|
||
if (!bytesCmp (auth.serverNonce, response.server_nonce)) { |
||
deferred.reject(new Error('Set_client_DH_params_answer server_nonce mismatch')); |
||
return false; |
||
} |
||
|
||
var bBigInt = new BigInteger(auth.b); |
||
var dhPrimeBigInt = new BigInteger(auth.dhPrime); |
||
|
||
var authKey = bytesFromBigInt((new BigInteger(auth.gA)).modPow(bBigInt, dhPrimeBigInt)), |
||
authKeyHash = sha1Hash(authKey), |
||
authKeyAux = authKeyHash.slice(0, 8), |
||
authKeyID = authKeyHash.slice(-8); |
||
|
||
console.log('Got Set_client_DH_params_answer', response._); |
||
switch (response._) { |
||
case 'dh_gen_ok': |
||
var newNonceHash1 = sha1Hash(auth.newNonce.concat([1], authKeyAux)).slice(-16); |
||
|
||
if (!bytesCmp(newNonceHash1, response.new_nonce_hash1)) { |
||
deferred.reject(new Error('Set_client_DH_params_answer new_nonce_hash1 mismatch')); |
||
return false; |
||
} |
||
|
||
var serverSalt = bytesXor(auth.newNonce.slice(0, 8), auth.serverNonce.slice(0, 8)); |
||
// console.log('Auth successfull!', authKeyID, authKey, serverSalt); |
||
|
||
auth.authKeyID = authKeyID; |
||
auth.authKey = authKey; |
||
auth.serverSalt = serverSalt; |
||
|
||
deferred.resolve(auth); |
||
break; |
||
|
||
case 'dh_gen_retry': |
||
var newNonceHash2 = sha1Hash(auth.newNonce.concat([2], authKeyAux)).slice(-16); |
||
if (!bytesCmp(newNonceHash2, response.new_nonce_hash2)) { |
||
deferred.reject(new Error('Set_client_DH_params_answer new_nonce_hash2 mismatch')); |
||
return false; |
||
} |
||
|
||
return mtpSendSetClientDhParams(auth); |
||
|
||
case 'dh_gen_fail': |
||
var newNonceHash3 = sha1Hash(auth.newNonce.concat([3], authKeyAux)).slice(-16); |
||
if (!bytesCmp(newNonceHash3, response.new_nonce_hash3)) { |
||
deferred.reject(new Error('Set_client_DH_params_answer new_nonce_hash3 mismatch')); |
||
return false; |
||
} |
||
|
||
deferred.reject(new Error('Set_client_DH_params_answer fail')); |
||
return false; |
||
} |
||
|
||
}, function (error) { |
||
deferred.reject(error); |
||
}); |
||
}; |
||
|
||
var cached = {}; |
||
|
||
function mtpAuth (dcID) { |
||
if (cached[dcID] !== undefined) { |
||
return cached[dcID]; |
||
} |
||
|
||
var nonce = []; |
||
for (var i = 0; i < 16; i++) { |
||
nonce.push(nextRandomInt(0xFF)); |
||
} |
||
|
||
if (!MtpDcConfigurator.chooseServer(dcID)) { |
||
return $q.reject(new Error('No server found for dc ' + dcID)); |
||
} |
||
|
||
var auth = { |
||
dcID: dcID, |
||
nonce: nonce, |
||
deferred: $q.defer() |
||
}; |
||
|
||
$timeout(function () { |
||
mtpSendReqPQ(auth); |
||
}); |
||
|
||
return cached[dcID] = auth.deferred.promise; |
||
}; |
||
|
||
return { |
||
auth: mtpAuth |
||
}; |
||
|
||
}). |
||
|
||
factory('MtpAesService', function ($q) { |
||
if (!window.Worker/* || true*/) { |
||
return { |
||
encrypt: function (bytes, keyBytes, ivBytes) { |
||
return $q.when(aesEncrypt(bytes, keyBytes, ivBytes)); |
||
}, |
||
decrypt: function (encryptedBytes, keyBytes, ivBytes) { |
||
return $q.when(aesDecrypt(encryptedBytes, keyBytes, ivBytes)); |
||
} |
||
}; |
||
} |
||
|
||
var worker = new Worker('js/lib/aes_worker.js'), |
||
taskID = 0, |
||
awaiting = {}; |
||
|
||
worker.onmessage = function (e) { |
||
var deferred = awaiting[e.data.taskID]; |
||
if (deferred !== undefined) { |
||
deferred.resolve(e.data.result); |
||
delete awaiting[e.data.taskID]; |
||
} |
||
// console.log('AES worker message', e.data, deferred); |
||
}; |
||
worker.onerror = function(error) { |
||
console.log('AES Worker error', error, error.stack); |
||
}; |
||
|
||
return { |
||
encrypt: function (bytes, keyBytes, ivBytes) { |
||
var deferred = $q.defer(); |
||
|
||
awaiting[taskID] = deferred; |
||
|
||
// console.log('AES post message', {taskID: taskID, task: 'encrypt', bytes: bytes, keyBytes: keyBytes, ivBytes: ivBytes}) |
||
worker.postMessage({taskID: taskID, task: 'encrypt', bytes: bytes, keyBytes: keyBytes, ivBytes: ivBytes}); |
||
|
||
taskID++ |
||
|
||
return deferred.promise; |
||
}, |
||
decrypt: function (encryptedBytes, keyBytes, ivBytes) { |
||
var deferred = $q.defer(); |
||
|
||
awaiting[taskID] = deferred; |
||
worker.postMessage({taskID: taskID, task: 'decrypt', encryptedBytes: encryptedBytes, keyBytes: keyBytes, ivBytes: ivBytes}); |
||
|
||
taskID++; |
||
|
||
return deferred.promise; |
||
} |
||
} |
||
}). |
||
|
||
|
||
factory('MtpSha1Service', function ($q) { |
||
if (!window.Worker/* || true*/) { |
||
return { |
||
hash: function (bytes) { |
||
return $q.when(sha1Hash(bytes)); |
||
} |
||
}; |
||
} |
||
|
||
var worker = new Worker('js/lib/sha1_worker.js'), |
||
taskID = 0, |
||
awaiting = {}; |
||
|
||
worker.onmessage = function (e) { |
||
var deferred = awaiting[e.data.taskID]; |
||
if (deferred !== undefined) { |
||
deferred.resolve(e.data.result); |
||
delete awaiting[e.data.taskID]; |
||
} |
||
// console.log('sha1 got message', e.data, deferred); |
||
}; |
||
worker.onerror = function(error) { |
||
console.log('SHA-1 Worker error', error, error.stack); |
||
}; |
||
|
||
return { |
||
hash: function (bytes) { |
||
var deferred = $q.defer(); |
||
|
||
awaiting[taskID] = deferred; |
||
// console.log(11, taskID, bytes); |
||
worker.postMessage({taskID: taskID, bytes: bytes}); |
||
|
||
taskID++; |
||
|
||
return deferred.promise; |
||
} |
||
} |
||
}). |
||
|
||
factory('MtpNetworkerFactory', function (MtpDcConfigurator, MtpMessageIdGenerator, MtpSecureRandom, MtpSha1Service, MtpAesService, AppConfigManager, $http, $q, $timeout, $interval, $rootScope) { |
||
|
||
var updatesProcessor, |
||
iii = 0, |
||
offline, |
||
offlineInited = false; |
||
|
||
$rootScope.retryOnline = function () { |
||
$(document.body).trigger('online'); |
||
} |
||
|
||
function MtpNetworker(dcID, authKey, serverSalt, options) { |
||
options = options || {}; |
||
|
||
this.dcID = dcID; |
||
this.iii = iii++; |
||
|
||
this.authKey = authKey; |
||
this.authKeyID = sha1Hash(authKey).slice(-8); |
||
|
||
this.serverSalt = serverSalt; |
||
|
||
this.upload = options.upload || false; |
||
|
||
this.updateSession(); |
||
|
||
this.currentRequests = 0; |
||
this.checkConnectionPeriod = 0; |
||
|
||
this.sentMessages = {}; |
||
this.serverMessages = []; |
||
this.clientMessages = []; |
||
|
||
this.pendingMessages = {}; |
||
this.pendingAcks = []; |
||
this.pendingResends = []; |
||
this.connectionInited = false; |
||
|
||
this.pendingTimeouts = []; |
||
|
||
this.longPollInt = $interval(this.checkLongPoll.bind(this), 10000); |
||
this.checkLongPoll(); |
||
|
||
if (!offlineInited) { |
||
offlineInited = true; |
||
$rootScope.offline = true; |
||
$rootScope.offlineConnecting = true; |
||
} |
||
}; |
||
|
||
MtpNetworker.prototype.updateSession = function () { |
||
console.log('Update session'); |
||
this.seqNo = 0; |
||
this.sessionID = new Array(8); |
||
MtpSecureRandom.nextBytes(this.sessionID); |
||
|
||
if (false) { |
||
this.sessionID[0] = 0xAB; |
||
this.sessionID[1] = 0xCD; |
||
} |
||
}; |
||
|
||
MtpNetworker.prototype.updateSentMessage = function (sentMessageID) { |
||
var sentMessage = this.sentMessages[sentMessageID]; |
||
if (!sentMessage) { |
||
return false; |
||
} |
||
var self = this; |
||
if (sentMessage.container) { |
||
var newInner = []; |
||
angular.forEach(sentMessage.inner, function(innerSentMessageID){ |
||
var innerSentMessage = self.updateSentMessage(innerSentMessageID); |
||
if (innerSentMessage) { |
||
newInner.push(innerSentMessage.msg_id); |
||
} |
||
}); |
||
sentMessage.inner = newInner; |
||
} |
||
|
||
sentMessage.msg_id = MtpMessageIdGenerator.generateID(); |
||
sentMessage.seq_no = this.generateSeqNo( |
||
sentMessage.notContentRelated || |
||
sentMessage.container |
||
); |
||
this.sentMessages[sentMessage.msg_id] = sentMessage; |
||
delete self.sentMessages[sentMessageID]; |
||
|
||
return sentMessage; |
||
}; |
||
|
||
MtpNetworker.prototype.generateSeqNo = function (notContentRelated) { |
||
var seqNo = this.seqNo * 2; |
||
|
||
if (!notContentRelated) { |
||
seqNo++; |
||
this.seqNo++; |
||
} |
||
|
||
return seqNo; |
||
} |
||
|
||
MtpNetworker.prototype.wrapMtpCall = function (method, params, options) { |
||
var serializer = new TLSerialization({mtproto: true}); |
||
|
||
serializer.storeMethod(method, params); |
||
|
||
var messageID = MtpMessageIdGenerator.generateID(), |
||
seqNo = this.generateSeqNo(), |
||
message = { |
||
msg_id: messageID, |
||
seq_no: seqNo, |
||
body: serializer.getBytes() |
||
}; |
||
|
||
if (window._debugMode) { |
||
console.log('MT call', method, params, messageID, seqNo); |
||
} |
||
|
||
return this.pushMessage(message, options); |
||
}; |
||
|
||
MtpNetworker.prototype.wrapMtpMessage = function (object, options) { |
||
options = options || {}; |
||
|
||
var serializer = new TLSerialization({mtproto: true}); |
||
serializer.storeObject(object, 'Object'); |
||
|
||
var messageID = MtpMessageIdGenerator.generateID(), |
||
seqNo = this.generateSeqNo(options.notContentRelated), |
||
message = { |
||
msg_id: messageID, |
||
seq_no: seqNo, |
||
body: serializer.getBytes() |
||
}; |
||
|
||
if (window._debugMode) { |
||
console.log('MT message', object, messageID, seqNo); |
||
} |
||
|
||
return this.pushMessage(message, options); |
||
}; |
||
|
||
MtpNetworker.prototype.wrapApiCall = function (method, params, options) { |
||
var serializer = new TLSerialization(options); |
||
|
||
if (!this.connectionInited) { |
||
serializer.storeInt(0xdda60d3c, 'invokeWithLayer12'); |
||
serializer.storeInt(0x69796de9, 'initConnection'); |
||
serializer.storeInt(2496, 'api_id'); |
||
serializer.storeString(navigator.userAgent || 'Unknown UserAgent', 'device_model'); |
||
serializer.storeString(navigator.platform || 'Unknown Platform', 'system_version'); |
||
serializer.storeString('0.1', 'app_version'); |
||
serializer.storeString(navigator.language || 'en', 'lang_code'); |
||
} |
||
|
||
if (options.afterMessageID) { |
||
serializer.storeInt(0xcb9f372d, 'invokeAfterMsg'); |
||
serializer.storeLong(options.afterMessageID, 'msg_id'); |
||
} |
||
|
||
serializer.storeMethod(method, params); |
||
|
||
var messageID = MtpMessageIdGenerator.generateID(), |
||
seqNo = this.generateSeqNo(), |
||
message = { |
||
msg_id: messageID, |
||
seq_no: seqNo, |
||
body: serializer.getBytes(), |
||
isAPI: true |
||
}; |
||
|
||
if (window._debugMode) { |
||
console.log('Api call', method, params, messageID, seqNo, options); |
||
} else { |
||
console.log('Api call', method, messageID, seqNo); |
||
} |
||
|
||
return this.pushMessage(message, options); |
||
}; |
||
|
||
MtpNetworker.prototype.checkLongPoll = function(force) { |
||
var isClean = this.cleanupSent(); |
||
// console.log('Check lp', this.longPollPending, tsNow()); |
||
if (this.longPollPending && tsNow() < this.longPollPending || this.offline) { |
||
return false; |
||
} |
||
var self = this; |
||
AppConfigManager.get('dc').then(function (baseDcID) { |
||
if (isClean && (baseDcID != self.dcID || self.upload)) { |
||
// console.warn('send long-poll for guest DC is delayed', self.dcID); |
||
return; |
||
} |
||
self.sendLongPoll(); |
||
}); |
||
}; |
||
|
||
MtpNetworker.prototype.sendLongPoll = function() { |
||
var maxWait = 25000, |
||
self = this; |
||
|
||
this.longPollPending = tsNow() + maxWait; |
||
// console.log('Set lp', this.longPollPending, tsNow()); |
||
|
||
this.wrapMtpCall('http_wait', { |
||
max_delay: 0, |
||
wait_after: 0, |
||
max_wait: maxWait |
||
}, { |
||
noResponse: true |
||
}).then(function () { |
||
delete self.longPollPending; |
||
$timeout(self.checkLongPoll.bind(self), 0); |
||
}, function () { |
||
console.log('Long-poll failed'); |
||
}); |
||
|
||
}; |
||
|
||
MtpNetworker.prototype.pushMessage = function(message, options) { |
||
var deferred = $q.defer(); |
||
|
||
this.sentMessages[message.msg_id] = angular.extend(message, options || {}, {deferred: deferred}); |
||
this.pendingMessages[message.msg_id] = 0; |
||
|
||
if (!options || !options.noShedule) { |
||
this.sheduleRequest(); |
||
} |
||
if (angular.isObject(options)) { |
||
options.messageID = message.msg_id; |
||
} |
||
|
||
return deferred.promise; |
||
}; |
||
|
||
MtpNetworker.prototype.pushResend = function(messageID, delay) { |
||
var value = delay ? tsNow() + delay : 0; |
||
var sentMessage = this.sentMessages[messageID]; |
||
if (sentMessage.container) { |
||
for (var i = 0; i < sentMessage.inner.length; i++) { |
||
this.pendingMessages[sentMessage.inner[i]] = value; |
||
} |
||
} else { |
||
this.pendingMessages[messageID] = value; |
||
} |
||
|
||
// console.log('Resend due', messageID, this.pendingMessages); |
||
|
||
this.sheduleRequest(delay); |
||
}; |
||
|
||
MtpNetworker.prototype.getMsgKeyIv = function (msgKey, isOut) { |
||
var authKey = this.authKey, |
||
x = isOut ? 0 : 8; |
||
|
||
var promises = { |
||
sha1a: MtpSha1Service.hash(msgKey.concat(authKey.slice(x, x + 32))), |
||
sha1b: MtpSha1Service.hash(authKey.slice(32 + x, 48 + x).concat(msgKey, authKey.slice(48 + x, 64 + x))), |
||
sha1c: MtpSha1Service.hash(authKey.slice(64 + x, 96 + x).concat(msgKey)), |
||
sha1d: MtpSha1Service.hash(msgKey.concat(authKey.slice(96 + x, 128 + x))) |
||
}; |
||
|
||
return $q.all(promises).then(function (result) { |
||
var aesKey = result.sha1a.slice(0, 8).concat(result.sha1b.slice(8, 20), result.sha1c.slice(4, 16)); |
||
var aesIv = result.sha1a.slice(8, 20).concat(result.sha1b.slice(0, 8), result.sha1c.slice(16, 20), result.sha1d.slice(0, 8)); |
||
|
||
return [aesKey, aesIv]; |
||
}); |
||
}; |
||
|
||
MtpNetworker.prototype.checkConnection = function(event) { |
||
$rootScope.offlineConnecting = true; |
||
|
||
console.log('check connection', event); |
||
$timeout.cancel(this.checkConnectionPromise); |
||
|
||
var serializer = new TLSerialization({mtproto: true}), |
||
pingID = [nextRandomInt(0xFFFFFFFF), nextRandomInt(0xFFFFFFFF)]; |
||
|
||
serializer.storeMethod('ping', {ping_id: pingID}); |
||
|
||
var pingMessage = { |
||
msg_id: MtpMessageIdGenerator.generateID(), |
||
seq_no: this.generateSeqNo(true), |
||
body: serializer.getBytes() |
||
}; |
||
|
||
var self = this; |
||
this.sendEncryptedRequest(pingMessage).then(function (result) { |
||
delete $rootScope.offlineConnecting; |
||
self.toggleOffline(false); |
||
}, function () { |
||
console.log('delay ', self.checkConnectionPeriod * 1000); |
||
self.checkConnectionPromise = $timeout(self.checkConnection.bind(self), parseInt(self.checkConnectionPeriod * 1000)); |
||
self.checkConnectionPeriod = Math.min(60, self.checkConnectionPeriod * 1.5); |
||
$timeout(function () { |
||
delete $rootScope.offlineConnecting; |
||
}, 1000); |
||
}) |
||
}; |
||
|
||
MtpNetworker.prototype.toggleOffline = function(enabled) { |
||
// console.log('toggle ', enabled, this.dcID, this.iii); |
||
if (this.offline !== undefined && this.offline == enabled) { |
||
return false; |
||
} |
||
|
||
this.offline = enabled; |
||
$rootScope.offline = enabled; |
||
$rootScope.offlineConnecting = false; |
||
|
||
if (this.offline) { |
||
$timeout.cancel(this.nextReqPromise); |
||
delete this.nextReq; |
||
|
||
if (this.checkConnectionPeriod < 1.5) { |
||
this.checkConnectionPeriod = 0; |
||
} |
||
|
||
this.checkConnectionPromise = $timeout(this.checkConnection.bind(this), parseInt(this.checkConnectionPeriod * 1000)); |
||
this.checkConnectionPeriod = Math.min(60, (1 + this.checkConnectionPeriod) * 1.5); |
||
|
||
this.onOnlineCb = this.checkConnection.bind(this); |
||
|
||
$(document.body).on('online', this.onOnlineCb); |
||
} else { |
||
delete this.longPollPending; |
||
this.checkLongPoll(); |
||
this.sheduleRequest(); |
||
|
||
if (this.onOnlineCb) { |
||
$(document.body).off('online', this.onOnlineCb); |
||
} |
||
$timeout.cancel(this.checkConnectionPromise); |
||
} |
||
|
||
}; |
||
|
||
|
||
|
||
MtpNetworker.prototype.performSheduledRequest = function() { |
||
// console.trace('sheduled', this.dcID, this.iii); |
||
if (this.offline) { |
||
console.log('cancel sheduled'); |
||
return false; |
||
} |
||
delete this.nextReq; |
||
if (this.pendingAcks.length) { |
||
var ackMsgIDs = []; |
||
for (var i = 0; i < this.pendingAcks.length; i++) { |
||
ackMsgIDs.push(this.pendingAcks[i]); |
||
} |
||
// console.log('acking messages', ackMsgIDs); |
||
this.wrapMtpMessage({_: 'msgs_ack', msg_ids: ackMsgIDs}, {notContentRelated: true, noShedule: true}); |
||
} |
||
|
||
if (this.pendingResends.length) { |
||
var resendMsgIDs = []; |
||
for (var i = 0; i < this.pendingResends.length; i++) { |
||
resendMsgIDs.push(this.pendingResends[i]); |
||
} |
||
// console.log('resendReq messages', resendMsgIDs); |
||
this.wrapMtpMessage({_: 'msg_resend_req', msg_ids: resendMsgIDs}, {noShedule: true}); |
||
} |
||
|
||
var messages = [], |
||
message, |
||
messagesByteLen = 0, |
||
currentTime = tsNow(), |
||
self = this; |
||
|
||
angular.forEach(this.pendingMessages, function (value, messageID) { |
||
if (!value || value >= currentTime) { |
||
if (message = self.sentMessages[messageID]) { |
||
messages.push(message); |
||
messagesByteLen += message.body.length + 32; |
||
} else { |
||
// console.log(message, messageID); |
||
} |
||
delete self.pendingMessages[messageID]; |
||
} |
||
}); |
||
|
||
if (!messages.length) { |
||
// console.log('no sheduled messages'); |
||
return; |
||
} |
||
|
||
var noResponseMsgs = []; |
||
|
||
if (messages.length > 1) { |
||
var container = new TLSerialization({mtproto: true, startMaxLength: messagesByteLen + 64}); |
||
container.storeInt(0x73f1f8dc, 'CONTAINER[id]'); |
||
container.storeInt(messages.length, 'CONTAINER[count]'); |
||
var onloads = []; |
||
var innerMessages = []; |
||
for (var i = 0; i < messages.length; i++) { |
||
container.storeLong(messages[i].msg_id, 'CONTAINER[' + i + '][msg_id]'); |
||
innerMessages.push(messages[i].msg_id); |
||
container.storeInt(messages[i].seq_no, 'CONTAINER[' + i + '][seq_no]'); |
||
container.storeInt(messages[i].body.length, 'CONTAINER[' + i + '][bytes]'); |
||
container.storeRawBytes(messages[i].body, 'CONTAINER[' + i + '][body]'); |
||
if (messages[i].noResponse) { |
||
noResponseMsgs.push(messages[i].msg_id); |
||
} |
||
} |
||
|
||
var containerSentMessage = { |
||
msg_id: MtpMessageIdGenerator.generateID(), |
||
seq_no: this.generateSeqNo(true), |
||
container: true, |
||
inner: innerMessages |
||
} |
||
|
||
message = angular.extend({body: container.getBytes()}, containerSentMessage); |
||
|
||
this.sentMessages[message.msg_id] = containerSentMessage; |
||
|
||
if (window._debugMode) { |
||
console.log('Container', innerMessages, message.msg_id, message.seq_no); |
||
} |
||
} else { |
||
if (message.noResponse) { |
||
noResponseMsgs.push(message.msg_id); |
||
} |
||
this.sentMessages[message.msg_id] = message; |
||
} |
||
|
||
this.pendingAcks = []; |
||
|
||
var self = this; |
||
this.sendEncryptedRequest(message).then(function (result) { |
||
self.toggleOffline(false); |
||
self.parseResponse(result.data).then(function (response) { |
||
if (window._debugMode) { |
||
console.log('Server response', self.dcID, response); |
||
} |
||
|
||
self.processMessage(response.response, response.messageID, response.sessionID); |
||
|
||
angular.forEach(noResponseMsgs, function (msgID) { |
||
if (self.sentMessages[msgID]) { |
||
var deferred = self.sentMessages[msgID].deferred; |
||
delete self.sentMessages[msgID]; |
||
deferred.resolve(); |
||
} |
||
}); |
||
|
||
self.checkLongPoll(); |
||
|
||
this.checkConnectionPeriod = Math.max(1.1, Math.sqrt(this.checkConnectionPeriod)); |
||
|
||
}); |
||
}, function (error) { |
||
console.log('Encrypted request failed', error); |
||
|
||
if (message.container) { |
||
angular.forEach(message.inner, function (msgID) { |
||
self.pendingMessages[msgID] = 0; |
||
}); |
||
delete self.sentMessages[message.msg_id]; |
||
} else { |
||
self.pendingMessages[message.msg_id] = 0; |
||
} |
||
|
||
angular.forEach(noResponseMsgs, function (msgID) { |
||
if (self.sentMessages[msgID]) { |
||
var deferred = self.sentMessages[msgID].deferred; |
||
delete self.sentMessages[msgID]; |
||
delete self.pendingMessages[msgID]; |
||
deferred.reject(); |
||
} |
||
}); |
||
|
||
self.toggleOffline(true); |
||
}); |
||
}; |
||
|
||
MtpNetworker.prototype.getEncryptedMessage = function (bytes) { |
||
var self = this; |
||
|
||
// console.log('enc', bytes); |
||
|
||
return MtpSha1Service.hash(bytes).then(function (bytesHash) { |
||
// console.log('bytesHash', bytesHash); |
||
var msgKey = bytesHash.slice(-16); |
||
return self.getMsgKeyIv(msgKey, true).then(function (keyIv) { |
||
// console.log('keyIv', keyIv); |
||
return MtpAesService.encrypt(bytes, keyIv[0], keyIv[1]).then(function (encryptedBytes) { |
||
// console.log('encryptedBytes', encryptedBytes); |
||
return { |
||
bytes: encryptedBytes, |
||
msgKey: msgKey |
||
}; |
||
}) |
||
}) |
||
}) |
||
}; |
||
|
||
MtpNetworker.prototype.getDecryptedMessage = function (msgKey, encryptedData) { |
||
return this.getMsgKeyIv(msgKey, false).then(function (keyIv) { |
||
return MtpAesService.decrypt(encryptedData, keyIv[0], keyIv[1]); |
||
}); |
||
}; |
||
|
||
MtpNetworker.prototype.sendEncryptedRequest = function (message) { |
||
var self = this; |
||
// console.log('send encrypted', message); |
||
// console.trace(); |
||
var data = new TLSerialization({startMaxLength: message.body.length + 64}); |
||
|
||
data.storeIntBytes(this.serverSalt, 64, 'salt'); |
||
data.storeIntBytes(this.sessionID, 64, 'session_id'); |
||
|
||
data.storeLong(message.msg_id, 'message_id'); |
||
data.storeInt(message.seq_no, 'seq_no'); |
||
|
||
data.storeInt(message.body.length, 'message_data_length'); |
||
data.storeRawBytes(message.body, 'message_data'); |
||
|
||
return this.getEncryptedMessage(data.getBytes()).then(function (encryptedResult) { |
||
// console.log('got enc result', encryptedResult); |
||
var request = new TLSerialization({startMaxLength: encryptedResult.bytes.length + 256}); |
||
request.storeIntBytes(self.authKeyID, 64, 'auth_key_id'); |
||
request.storeIntBytes(encryptedResult.msgKey, 128, 'msg_key'); |
||
request.storeRawBytes(encryptedResult.bytes, 'encrypted_data'); |
||
|
||
delete $http.defaults.headers.post['Content-Type']; |
||
delete $http.defaults.headers.common['Accept']; |
||
|
||
return $http.post('http://' + MtpDcConfigurator.chooseServer(self.dcID) + '/apiw1', request.getBuffer(), { |
||
responseType: 'arraybuffer', |
||
transformRequest: null |
||
}); |
||
}); |
||
}; |
||
|
||
MtpNetworker.prototype.parseResponse = function (responseBuffer) { |
||
var self = this; |
||
|
||
var deserializer = new TLDeserialization(responseBuffer); |
||
|
||
var authKeyID = deserializer.fetchIntBytes(64, 'auth_key_id'); |
||
if (!bytesCmp(authKeyID, this.authKeyID)) { |
||
throw new Error('Invalid server auth_key_id: ' + bytesToHex(authKeyID)); |
||
} |
||
var msgKey = deserializer.fetchIntBytes(128, 'msg_key'); |
||
|
||
var dataLength = responseBuffer.byteLength - deserializer.getOffset(); |
||
var encryptedData = deserializer.fetchRawBytes(dataLength, 'encrypted_data'); |
||
|
||
return this.getDecryptedMessage(msgKey, encryptedData).then(function (dataWithPadding) { |
||
var buffer = bytesToArrayBuffer(dataWithPadding); |
||
|
||
var deserializer = new TLDeserialization(buffer, {mtproto: true}); |
||
|
||
var salt = deserializer.fetchIntBytes(64, 'salt'); |
||
var sessionID = deserializer.fetchIntBytes(64, 'session_id'); |
||
var messageID = deserializer.fetchLong('message_id'); |
||
|
||
var seqNo = deserializer.fetchInt('seq_no'); |
||
|
||
var messageBody = deserializer.fetchRawBytes(false, 'message_data'); |
||
|
||
var offset = deserializer.getOffset(); |
||
|
||
return MtpSha1Service.hash(dataWithPadding.slice(0, offset)).then(function (dataHashed) { |
||
if (!bytesCmp(msgKey, dataHashed.slice(-16))) { |
||
throw new Error('server msgKey mismatch'); |
||
} |
||
|
||
var buffer = bytesToArrayBuffer(messageBody); |
||
var deserializer = new TLDeserialization(buffer, {mtproto: true}); |
||
|
||
var response = deserializer.fetchObject('', 'INPUT'); |
||
|
||
return { |
||
response: response, |
||
messageID: messageID, |
||
sessionID: sessionID, |
||
seqNo: seqNo |
||
}; |
||
}); |
||
}); |
||
}; |
||
|
||
MtpNetworker.prototype.applyServerSalt = function (newServerSalt) { |
||
var serverSalt = longToBytes(newServerSalt); |
||
|
||
var storeObj = {}; |
||
storeObj['dc' + this.dcID + '_server_salt'] = bytesToHex(serverSalt); |
||
AppConfigManager.set(storeObj); |
||
|
||
this.serverSalt = serverSalt; |
||
return true; |
||
}; |
||
|
||
MtpNetworker.prototype.sheduleRequest = function (delay) { |
||
if (this.offline) { |
||
this.checkConnection('forced shedule'); |
||
} |
||
var nextReq = tsNow() + delay; |
||
|
||
if (delay && this.nextReq && this.nextReq <= nextReq) { |
||
return false; |
||
} |
||
|
||
// console.log('shedule req', delay); |
||
// console.trace(); |
||
|
||
$timeout.cancel(this.nextReqPromise); |
||
|
||
this.nextReqPromise = $timeout(this.performSheduledRequest.bind(this), delay || 0); |
||
this.nextReq = nextReq; |
||
}; |
||
|
||
MtpNetworker.prototype.onSessionCreate = function (sessionID, messageID) { |
||
console.log('New session created', bytesToHex(sessionID)); |
||
}; |
||
|
||
MtpNetworker.prototype.ackMessage = function (msgID) { |
||
// console.log('ack message', msgID); |
||
this.pendingAcks.push(msgID); |
||
this.sheduleRequest(30000); |
||
}; |
||
|
||
MtpNetworker.prototype.reqResendMessage = function (msgID) { |
||
console.log('req resend', msgID); |
||
this.pendingResends.push(msgID); |
||
this.sheduleRequest(100); |
||
}; |
||
|
||
MtpNetworker.prototype.cleanupSent = function () { |
||
var self = this; |
||
var notEmpty = false; |
||
// console.log('clean start', this.dcID/*, this.sentMessages*/); |
||
angular.forEach(this.sentMessages, function(message, msgID) { |
||
// console.log('clean iter', msgID, message); |
||
if (message.notContentRelated && self.pendingMessages[msgID] === undefined) { |
||
// console.log('clean notContentRelated', msgID); |
||
delete self.sentMessages[msgID]; |
||
} |
||
else if (message.container) { |
||
for (var i = 0; i < message.inner.length; i++) { |
||
if (self.sentMessages[message.inner[i]] !== undefined) { |
||
// console.log('clean failed, found', msgID, message.inner[i], self.sentMessages[message.inner[i]].seq_no); |
||
notEmpty = true; |
||
return; |
||
} |
||
} |
||
// console.log('clean container', msgID); |
||
delete self.sentMessages[msgID]; |
||
} else { |
||
notEmpty = true; |
||
} |
||
}); |
||
|
||
return !notEmpty; |
||
}; |
||
|
||
|
||
MtpNetworker.prototype.processMessageAck = function (messageID) { |
||
var sentMessage = this.sentMessages[messageID]; |
||
if (sentMessage && !sentMessage.acked) { |
||
delete sentMessage.body; |
||
sentMessage.acked = true; |
||
|
||
return true; |
||
} |
||
|
||
return false; |
||
}; |
||
|
||
MtpNetworker.prototype.processError = function (rawError) { |
||
var matches = (rawError.error_message || '').match(/^([A-Z_0-9]+\b)(: (.+))?/) || []; |
||
rawError.error_code = uintToInt(rawError.error_code); |
||
|
||
return { |
||
code: !rawError.error_code || rawError.error_code <= 0 ? 500 : rawError.error_code, |
||
type: matches[1] || 'UNKNOWN', |
||
description: matches[3] || ('CODE#' + rawError.error_code + ' ' + rawError.error_message), |
||
originalError: rawError |
||
}; |
||
}; |
||
|
||
|
||
MtpNetworker.prototype.processMessage = function (message, messageID, sessionID) { |
||
// console.log('process message', message, messageID, sessionID); |
||
switch (message._) { |
||
case 'msg_container': |
||
var len = message.messages.length; |
||
for (var i = 0; i < len; i++) { |
||
this.processMessage(message.messages[i], messageID, sessionID); |
||
} |
||
break; |
||
|
||
case 'bad_server_salt': |
||
console.log('Bad server salt', message); |
||
var sentMessage = this.sentMessages[message.bad_msg_id]; |
||
if (!sentMessage || sentMessage.seq_no != message.bad_msg_seqno) { |
||
console.log(message.bad_msg_id, message.bad_msg_seqno); |
||
throw new Error('Bad server salt for invalid message'); |
||
} |
||
|
||
this.applyServerSalt(message.new_server_salt); |
||
this.pushResend(message.bad_msg_id); |
||
this.ackMessage(messageID); |
||
break; |
||
|
||
case 'bad_msg_notification': |
||
console.log('Bad msg notification', message); |
||
var sentMessage = this.sentMessages[message.bad_msg_id]; |
||
if (!sentMessage || sentMessage.seq_no != message.bad_msg_seqno) { |
||
console.log(message.bad_msg_id, message.bad_msg_seqno); |
||
throw new Error('Bad msg notification for invalid message'); |
||
} |
||
|
||
if (message.error_code == 16 || message.error_code == 17) { |
||
if (MtpMessageIdGenerator.applyServerTime( |
||
bigStringInt(messageID).shiftRight(32).toString(10) |
||
)) { |
||
this.updateSession(); |
||
} |
||
var badMessage = this.updateSentMessage(message.bad_msg_id); |
||
this.pushResend(badMessage.msg_id); |
||
this.ackMessage(messageID); |
||
} |
||
break; |
||
|
||
case 'message': |
||
this.serverMessages.push(message.msg_id); |
||
this.processMessage(message.body, message.msg_id, sessionID); |
||
break; |
||
|
||
case 'new_session_created': |
||
this.ackMessage(messageID); |
||
|
||
this.processMessageAck(message.first_msg_id); |
||
this.applyServerSalt(message.server_salt); |
||
this.onSessionCreate(sessionID, messageID); |
||
break; |
||
|
||
case 'msgs_ack': |
||
for (var i = 0; i < message.msg_ids.length; i++) { |
||
this.processMessageAck(message.msg_ids[i]); |
||
} |
||
break; |
||
|
||
case 'msg_detailed_info': |
||
if (!this.sentMessages[message.msg_id]) { |
||
this.ackMessage(message.answer_msg_id); |
||
break; |
||
} |
||
case 'msg_new_detailed_info': |
||
// this.ackMessage(message.answer_msg_id); |
||
this.reqResendMessage(message.answer_msg_id); |
||
break; |
||
|
||
case 'rpc_result': |
||
this.ackMessage(messageID); |
||
|
||
var sentMessageID = message.req_msg_id, |
||
sentMessage = this.sentMessages[sentMessageID]; |
||
|
||
this.processMessageAck(sentMessageID); |
||
if (sentMessage) { |
||
var deferred = sentMessage.deferred; |
||
if (message.result._ == 'rpc_error') { |
||
var error = this.processError(message.result); |
||
console.log('rpc error', error) |
||
if (deferred) { |
||
deferred.reject(error) |
||
} |
||
} else { |
||
if (deferred) { |
||
if (window._debugMode) { |
||
console.log('rpc response', message.result); |
||
} else { |
||
console.log('rpc response', message.result._); |
||
} |
||
sentMessage.deferred.resolve(message.result); |
||
} |
||
if (sentMessage.isAPI) { |
||
this.connectionInited = true; |
||
} |
||
} |
||
|
||
delete this.sentMessages[sentMessageID]; |
||
} |
||
break; |
||
|
||
default: |
||
this.ackMessage(messageID); |
||
|
||
// console.log('Update', message); |
||
if (updatesProcessor) { |
||
updatesProcessor(message); |
||
} |
||
break; |
||
|
||
} |
||
}; |
||
|
||
return { |
||
getNetworker: function (dcID, authKey, serverSalt, options) { |
||
return new MtpNetworker(dcID, authKey, serverSalt, options); |
||
}, |
||
setUpdatesProcessor: function (callback) { |
||
updatesProcessor = callback; |
||
} |
||
}; |
||
|
||
}). |
||
|
||
factory('MtpApiManager', function (AppConfigManager, MtpAuthorizer, MtpNetworkerFactory, $q) { |
||
var cachedNetworkers = {}, |
||
cachedUploadNetworkers = {}, |
||
cachedExportPromise = {}, |
||
baseDcID = false; |
||
|
||
AppConfigManager.get('dc').then(function (dcID) { |
||
if (dcID) { |
||
baseDcID = dcID; |
||
} |
||
}); |
||
|
||
function mtpSetUserAuth (dcID, userAuth) { |
||
AppConfigManager.set({ |
||
dc: dcID, |
||
user_auth: angular.extend({dcID: dcID}, userAuth) |
||
}); |
||
|
||
baseDcID = dcID; |
||
} |
||
|
||
function mtpLogOut () { |
||
return mtpInvokeApi('auth.logOut').then(function () { |
||
AppConfigManager.remove('dc', 'user_auth'); |
||
|
||
baseDcID = false; |
||
}, function (error) { |
||
AppConfigManager.remove('dc', 'user_auth'); |
||
if (error && error.code != 401) { |
||
AppConfigManager.remove('dc' + baseDcID + '_auth_key'); |
||
} |
||
baseDcID = false; |
||
}); |
||
} |
||
|
||
function mtpGetNetworker (dcID, upload) { |
||
var cache = upload ? cachedUploadNetworkers : cachedNetworkers; |
||
if (!dcID) { |
||
throw new Exception('get Networker without dcID'); |
||
} |
||
|
||
if (cache[dcID] !== undefined) { |
||
return $q.when(cache[dcID]); |
||
} |
||
|
||
var akk = 'dc' + dcID + '_auth_key', |
||
ssk = 'dc' + dcID + '_server_salt'; |
||
|
||
return AppConfigManager.get(akk, ssk).then(function (result) { |
||
|
||
if (cache[dcID] !== undefined) { |
||
return cache[dcID]; |
||
} |
||
|
||
var authKeyHex = result[0], |
||
serverSaltHex = result[1]; |
||
// console.log('ass', dcID, authKeyHex, serverSaltHex); |
||
if (authKeyHex && authKeyHex.length == 512) { |
||
var authKey = bytesFromHex(authKeyHex); |
||
var serverSalt = bytesFromHex(serverSaltHex); |
||
|
||
return cache[dcID] = MtpNetworkerFactory.getNetworker(dcID, authKey, serverSalt, {upload: upload}); |
||
} |
||
|
||
return MtpAuthorizer.auth(dcID).then(function (auth) { |
||
var storeObj = {}; |
||
storeObj[akk] = bytesToHex(auth.authKey); |
||
storeObj[ssk] = bytesToHex(auth.serverSalt); |
||
AppConfigManager.set(storeObj); |
||
|
||
return cache[dcID] = MtpNetworkerFactory.getNetworker(dcID, auth.authKey, auth.serverSalt, {upload: upload}); |
||
}, function (error) { |
||
console.log('Get networker error', error, error.stack); |
||
return $q.reject(error); |
||
}); |
||
}); |
||
}; |
||
|
||
function mtpInvokeApi (method, params, options) { |
||
options = options || {}; |
||
|
||
var deferred = $q.defer(), |
||
dcID, |
||
upload = options.fileDownload || options.fileUpload, |
||
networkerPromise; |
||
|
||
if (dcID = options.dcID) { |
||
networkerPromise = mtpGetNetworker(dcID, upload); |
||
} else { |
||
networkerPromise = AppConfigManager.get('dc').then(function (baseDcID) { |
||
return mtpGetNetworker(dcID = baseDcID || 1, upload); |
||
}); |
||
} |
||
|
||
var cachedNetworker; |
||
|
||
networkerPromise.then(function (networker) { |
||
return (cachedNetworker = networker).wrapApiCall(method, params, options).then( |
||
function (result) { |
||
deferred.resolve(result); |
||
// $timeout(function () { |
||
// deferred.resolve(result); |
||
// }, 1000); |
||
}, |
||
function (error) { |
||
console.log('error', error.code, error.type, baseDcID, dcID); |
||
if (error.code == 401 && baseDcID && dcID != baseDcID) { |
||
if (cachedExportPromise[dcID] === undefined) { |
||
var exportDeferred = $q.defer(); |
||
|
||
mtpInvokeApi('auth.exportAuthorization', {dc_id: dcID}).then(function (exportedAuth) { |
||
mtpInvokeApi('auth.importAuthorization', { |
||
id: exportedAuth.id, |
||
bytes: exportedAuth.bytes |
||
}, {dcID: dcID}).then(function () { |
||
exportDeferred.resolve(); |
||
}, function (e) { |
||
exportDeferred.reject(e); |
||
}) |
||
}, function (e) { |
||
exportDeferred.reject(e) |
||
}); |
||
|
||
cachedExportPromise[dcID] = exportDeferred.promise; |
||
} |
||
|
||
// console.log('promise', cachedExportPromise[dcID]); |
||
|
||
cachedExportPromise[dcID] = cachedExportPromise[dcID].then(function () { |
||
(cachedNetworker = networker).wrapApiCall(method, params, options).then(function (result) { |
||
deferred.resolve(result); |
||
}, function (error) { |
||
deferred.reject(error); |
||
}); |
||
}, function (error) { |
||
deferred.reject(error); |
||
}); |
||
} |
||
else if (error.code == 303) { |
||
var newDcID = error.type.match(/^(PHONE_MIGRATE_|NETWORK_MIGRATE_)(\d+)/)[2]; |
||
if (newDcID != dcID) { |
||
if (options.dcID) { |
||
options.dcID = newDcID; |
||
} else { |
||
AppConfigManager.set({dc: baseDcID = newDcID}); |
||
} |
||
|
||
mtpGetNetworker(newDcID).then(function (networker) { |
||
networker.wrapApiCall(method, params, options).then(function (result) { |
||
deferred.resolve(result); |
||
}, function (error) { |
||
deferred.reject(error); |
||
}); |
||
}); |
||
} |
||
} |
||
else { |
||
deferred.reject(error); |
||
} |
||
}); |
||
}, function (error) { |
||
deferred.reject(error); |
||
}); |
||
|
||
return deferred.promise; |
||
}; |
||
|
||
function mtpGetUserID () { |
||
return AppConfigManager.get('user_auth').then(function (auth) { |
||
return auth.id || 0; |
||
}); |
||
} |
||
|
||
function getBaseDcID () { |
||
return baseDcID || false; |
||
} |
||
|
||
return { |
||
getBaseDcID: getBaseDcID, |
||
getUserID: mtpGetUserID, |
||
invokeApi: mtpInvokeApi, |
||
setUserAuth: mtpSetUserAuth, |
||
logOut: mtpLogOut |
||
} |
||
}). |
||
|
||
|
||
factory('MtpApiFileManager', function (MtpApiManager, $q, $window) { |
||
|
||
var cachedFS = false; |
||
var apiUploadPromise = $q.when(); |
||
var cachedSavePromises = {}; |
||
var cachedDownloadPromises = {}; |
||
var cachedDownloads = {}; |
||
|
||
var downloadPulls = {}; |
||
var downloadActives = {}; |
||
var downloadLimit = 5; |
||
|
||
function downloadRequest(dcID, cb, activeDelta) { |
||
if (downloadPulls[dcID] === undefined) { |
||
downloadPulls[dcID] = []; |
||
downloadActives[dcID] = 0 |
||
} |
||
var downloadPull = downloadPulls[dcID]; |
||
var deferred = $q.defer(); |
||
downloadPull.push({cb: cb, deferred: deferred, activeDelta: activeDelta}); |
||
downloadCheck(dcID); |
||
|
||
return deferred.promise; |
||
}; |
||
|
||
var index = 0; |
||
|
||
function downloadCheck(dcID) { |
||
var downloadPull = downloadPulls[dcID]; |
||
|
||
if (downloadActives[dcID] >= downloadLimit || !downloadPull || !downloadPull.length) { |
||
return false; |
||
} |
||
|
||
var data = downloadPull.shift(), |
||
activeDelta = data.activeDelta || 1; |
||
|
||
downloadActives[dcID] += activeDelta; |
||
|
||
var a = index++; |
||
data.cb() |
||
.then(function (result) { |
||
downloadActives[dcID] -= activeDelta; |
||
downloadCheck(dcID); |
||
|
||
data.deferred.resolve(result); |
||
|
||
}, function (error) { |
||
downloadActives[dcID] -= activeDelta; |
||
downloadCheck(dcID); |
||
|
||
data.deferred.reject(error); |
||
}) |
||
}; |
||
|
||
function requestFS (argument) { |
||
if (cachedFS) { |
||
return $q.when(cachedFS); |
||
} |
||
|
||
$window.requestFileSystem = $window.requestFileSystem || $window.webkitRequestFileSystem; |
||
|
||
if (!$window.requestFileSystem/* || true*/) { |
||
return $q.reject({type: 'FS_BROWSER_UNSUPPORTED', description: 'requestFileSystem not present'}); |
||
} |
||
|
||
var deferred = $q.defer(); |
||
|
||
$window.requestFileSystem($window.TEMPORARY, 5*1024*1024, function (fs) { |
||
cachedFS = fs; |
||
deferred.resolve(); |
||
}, function (e) { |
||
deferred.reject(e); |
||
}); |
||
|
||
return deferred.promise; |
||
}; |
||
|
||
function fileWriteBytes(fileWriter, bytes) { |
||
var deferred = $q.defer(); |
||
|
||
fileWriter.onwriteend = function(e) { |
||
deferred.resolve(); |
||
}; |
||
fileWriter.onerror = function (e) { |
||
deferred.reject(); |
||
}; |
||
|
||
if (false) { // is file bytes |
||
fileWriter.write(bytes); |
||
} else { |
||
fileWriter.write(new Blob([bytesToArrayBuffer(bytes)])); |
||
} |
||
|
||
return deferred.promise; |
||
} |
||
|
||
function getFileName(location) { |
||
switch (location._) { |
||
case 'inputVideoFileLocation': |
||
return 'video' + location.id + '.mp4'; |
||
|
||
case 'inputDocumentFileLocation': |
||
return 'doc' + location.id; |
||
|
||
case 'inputAudioFileLocation': |
||
return 'audio' + location.id; |
||
} |
||
|
||
if (!location.volume_id) { |
||
console.trace('Empty location', location); |
||
} |
||
|
||
return location.volume_id + '_' + location.local_id + '_' + location.secret + '.jpg'; |
||
}; |
||
|
||
function getTempFileName(file) { |
||
var size = file.size || -1; |
||
var random = nextRandomInt(0xFFFFFFFF); |
||
return '_temp' + random + '_' + size; |
||
}; |
||
|
||
function getCachedFile (location) { |
||
if (!location) { |
||
return false; |
||
} |
||
var fileName = getFileName(location); |
||
|
||
return cachedDownloads[fileName] || false; |
||
} |
||
|
||
function saveSmallFile (location, bytes) { |
||
var fileName = getFileName(location); |
||
|
||
if (cachedSavePromises[fileName]) { |
||
return cachedSavePromises[fileName]; |
||
} |
||
var deferred = $q.defer(), |
||
cacheFileWriter, |
||
errorHandler = function (error) { |
||
deferred.reject(error); |
||
if (cacheFileWriter) cacheFileWriter.truncate(0); |
||
errorHandler = angular.noop; |
||
}; |
||
|
||
requestFS().then(function () { |
||
cachedFS.root.getFile(fileName, {create: false}, function(fileEntry) { |
||
deferred.resolve(cachedDownloads[fileName] = fileEntry.toURL()); |
||
}, function () { |
||
cachedFS.root.getFile(fileName, {create: true}, function(fileEntry) { |
||
fileEntry.createWriter(function (fileWriter) { |
||
cacheFileWriter = fileWriter; |
||
fileWriteBytes(fileWriter, bytes).then(function () { |
||
deferred.resolve(cachedDownloads[fileName] = fileEntry.toURL()); |
||
}, errorHandler); |
||
}, errorHandler); |
||
}, errorHandler); |
||
}); |
||
}, errorHandler); |
||
|
||
return cachedSavePromises[fileName] = deferred.promise; |
||
} |
||
|
||
function downloadSmallFile(location) { |
||
// console.log('dload small', location); |
||
var fileName = getFileName(location), |
||
cachedPromise = cachedSavePromises[fileName] || cachedDownloadPromises[fileName]; |
||
|
||
if (cachedPromise) { |
||
return cachedPromise; |
||
} |
||
|
||
var deferred = $q.defer(), |
||
cacheFileWriter, |
||
errorHandler = function (error) { |
||
deferred.reject(error); |
||
if (cacheFileWriter) cacheFileWriter.truncate(0); |
||
errorHandler = angular.noop; |
||
}, |
||
doDownload = function () { |
||
cachedFS.root.getFile(fileName, {create: true}, function(fileEntry) { |
||
var downloadPromise = downloadRequest(location.dc_id, function () { |
||
// console.log('next small promise'); |
||
return MtpApiManager.invokeApi('upload.getFile', { |
||
location: angular.extend({}, location, {_: 'inputFileLocation'}), |
||
offset: 0, |
||
limit: 0 |
||
}, { |
||
dcID: location.dc_id, |
||
fileDownload: true |
||
}); |
||
}); |
||
|
||
fileEntry.createWriter(function (fileWriter) { |
||
cacheFileWriter = fileWriter; |
||
downloadPromise.then(function (result) { |
||
fileWriteBytes(fileWriter, result.bytes).then(function () { |
||
// console.log('Success', location, fileEntry.toURL()); |
||
deferred.resolve(cachedDownloads[fileName] = fileEntry.toURL()); |
||
}, errorHandler); |
||
}, errorHandler); |
||
}, errorHandler); |
||
}, errorHandler); |
||
}; |
||
|
||
requestFS().then(function () { |
||
cachedFS.root.getFile(fileName, {create: false}, function(fileEntry) { |
||
fileEntry.file(function(file) { |
||
if (file.size) { |
||
deferred.resolve(cachedDownloads[fileName] = fileEntry.toURL()); |
||
} else { |
||
console.log('Small file empty', file); |
||
doDownload(); |
||
} |
||
}, errorHandler); |
||
}, doDownload); |
||
}, function (error) { |
||
|
||
downloadRequest(location.dc_id, function () { |
||
// console.log('next small promise'); |
||
return MtpApiManager.invokeApi('upload.getFile', { |
||
location: angular.extend({}, location, {_: 'inputFileLocation'}), |
||
offset: 0, |
||
limit: 0 |
||
}, { |
||
dcID: location.dc_id, |
||
fileDownload: true |
||
}); |
||
}).then(function (result) { |
||
deferred.resolve(cachedDownloads[fileName] = 'data:image/jpeg;base64,' + bytesToBase64(result.bytes)) |
||
}, errorHandler); |
||
}); |
||
|
||
return cachedDownloadPromises[fileName] = deferred.promise; |
||
} |
||
|
||
function downloadFile (dcID, location, size, fileEntry, options) { |
||
options = options || {}; |
||
|
||
console.log('dload file', dcID, location, size); |
||
var fileName = getFileName(location), |
||
cachedPromise = cachedSavePromises[fileName] || cachedDownloadPromises[fileName]; |
||
|
||
if (cachedPromise) { |
||
return cachedPromise; |
||
} |
||
|
||
var deferred = $q.defer(), |
||
cacheFileWriter, |
||
errorHandler = function (error) { |
||
console.error(error); |
||
// console.log('fail'); |
||
deferred.reject(error); |
||
if (cacheFileWriter) cacheFileWriter.truncate(0); |
||
errorHandler = angular.noop; |
||
}, |
||
saveToFileEntry = function (fileEntry) { |
||
fileEntry.createWriter(function (fileWriter) { |
||
cacheFileWriter = fileWriter; |
||
|
||
// var limit = size > 102400 ? 65536 : 4096; |
||
var limit = size > 30400 ? 524288 : 4096; |
||
// var limit = size > 30400 ? 20480 : 4096; |
||
var writeFilePromise = $q.when(), |
||
writeFileDeferred; |
||
for (var offset = 0; offset < size; offset += limit) { |
||
writeFileDeferred = $q.defer(); |
||
(function (isFinal, offset, writeFileDeferred, writeFilePromise) { |
||
return downloadRequest(dcID, function () { |
||
// console.log('next big promise'); |
||
return MtpApiManager.invokeApi('upload.getFile', { |
||
location: location, |
||
offset: offset, |
||
limit: limit |
||
}, { |
||
dcID: dcID, |
||
fileDownload: true |
||
}); |
||
|
||
}, 6).then(function (result) { |
||
|
||
// console.log('waiting for file promise', offset); |
||
writeFilePromise.then(function () { |
||
// console.log('resolved file promise', offset); |
||
|
||
return fileWriteBytes(fileWriter, result.bytes).then(function () { |
||
|
||
// console.log('resolve file promise', offset); |
||
writeFileDeferred.resolve(); |
||
|
||
}, errorHandler).then(function () { |
||
|
||
if (isFinal) { |
||
deferred.resolve(cachedDownloads[fileName] = fileEntry.toURL(options.mime || 'image/jpeg')); |
||
} else { |
||
// console.log('notify', {done: offset + limit, total: size}); |
||
deferred.notify({done: offset + limit, total: size}); |
||
}; |
||
|
||
}); |
||
|
||
}); |
||
|
||
}); |
||
|
||
})(offset + limit >= size, offset, writeFileDeferred, writeFilePromise); |
||
|
||
writeFilePromise = writeFileDeferred.promise; |
||
|
||
} |
||
}, errorHandler); |
||
|
||
}; |
||
|
||
if (fileEntry) { |
||
saveToFileEntry(fileEntry); |
||
} else { |
||
requestFS().then(function () { |
||
cachedFS.root.getFile(fileName, {create: false}, function(fileEntry) { |
||
fileEntry.file(function(file) { |
||
console.log('check size', file.size, size); |
||
if (file.size >= size) { |
||
deferred.resolve(cachedDownloads[fileName] = fileEntry.toURL()); |
||
} else { |
||
console.log('File bad size', file, size); |
||
cachedFS.root.getFile(fileName, {create: true}, saveToFileEntry, errorHandler) |
||
} |
||
}, errorHandler); |
||
}, function () { |
||
cachedFS.root.getFile(fileName, {create: true}, saveToFileEntry, errorHandler) |
||
}); |
||
}, function () { |
||
|
||
var blobParts = []; |
||
var limit = size > 30400 ? 524288 : 4096; |
||
var writeBlobPromise = $q.when(), |
||
writeBlobDeferred; |
||
for (var offset = 0; offset < size; offset += limit) { |
||
writeBlobDeferred = $q.defer(); |
||
(function (isFinal, offset, writeBlobDeferred, writeBlobPromise) { |
||
return downloadRequest(dcID, function () { |
||
return MtpApiManager.invokeApi('upload.getFile', { |
||
location: location, |
||
offset: offset, |
||
limit: limit |
||
}, { |
||
dcID: dcID, |
||
fileDownload: true |
||
}); |
||
}, 6).then(function (result) { |
||
writeBlobPromise.then(function () { |
||
try { |
||
blobParts.push(bytesToArrayBuffer(result.bytes)); |
||
writeBlobDeferred.resolve(); |
||
|
||
if (isFinal) { |
||
try { |
||
var blob = new Blob(blobParts, {type: options.mime || 'image/jpeg'}); |
||
} catch (e) { |
||
window.BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder; |
||
var bb = new BlobBuilder; |
||
angular.forEach(blobParts, function(blobPart) { |
||
bb.append(blobPart); |
||
}); |
||
var blob = bb.getBlob(options.mime || 'image/jpeg'); |
||
} |
||
|
||
|
||
window.URL = window.URL || window.webkitURL; |
||
deferred.resolve(cachedDownloads[fileName] = URL.createObjectURL(blob)); |
||
} else { |
||
deferred.notify({done: offset + limit, total: size}); |
||
}; |
||
} catch (e) { |
||
errorHandler(e); |
||
} |
||
}, errorHandler); |
||
|
||
}); |
||
|
||
})(offset + limit >= size, offset, writeBlobDeferred, writeBlobPromise); |
||
|
||
writeBlobPromise = writeBlobDeferred.promise; |
||
|
||
} |
||
|
||
}); |
||
} |
||
|
||
return cachedDownloadPromises[fileName] = deferred.promise; |
||
} |
||
|
||
function writeFile (file) { |
||
console.log('write file', file); |
||
var fileName = getTempFileName(file); |
||
|
||
var deferred = $q.defer(), |
||
cacheFileWriter, |
||
errorHandler = function (error) { |
||
console.log('fail'); |
||
deferred.reject(error); |
||
if (cacheFileWriter) cacheFileWriter.truncate(0); |
||
errorHandler = angular.noop; |
||
}; |
||
|
||
requestFS().then(function () { |
||
cachedFS.root.getFile(fileName, {create: false}, function(fileEntry) { |
||
deferred.resolve(fileEntry); |
||
}, function () { |
||
cachedFS.root.getFile(fileName, {create: true}, function(fileEntry) { |
||
fileEntry.createWriter(function (fileWriter) { |
||
cacheFileWriter = fileWriter; |
||
fileWriteBytes(fileWriter, file).then(function () { |
||
deferred.resolve(fileEntry); |
||
}, errorHandler); |
||
}, errorHandler); |
||
}); |
||
}); |
||
}); |
||
}; |
||
|
||
function uploadFile (file) { |
||
var fileSize = file.size, |
||
// partSize = fileSize > 102400 ? 65536 : 4096, |
||
partSize = fileSize > 102400 ? 524288 : 4096, |
||
totalParts = Math.ceil(fileSize / partSize), |
||
doneParts = 0; |
||
|
||
if (totalParts > 1500) { |
||
return $q.reject({type: 'FILE_TOO_BIG'}); |
||
} |
||
|
||
var fileID = [nextRandomInt(0xFFFFFFFF), nextRandomInt(0xFFFFFFFF)], |
||
deferred = $q.defer(), |
||
errorHandler = function (error) { |
||
console.log('error', error); |
||
deferred.reject(error); |
||
errorHandler = angular.noop; |
||
}, |
||
part = 0, |
||
offset, |
||
resultInputFile = { |
||
_: 'inputFile', |
||
id:fileID, |
||
parts: totalParts, |
||
name: file.name, |
||
md5_checksum: '' |
||
}; |
||
|
||
|
||
var fileReadPromise = $q.when(); |
||
|
||
for (offset = 0; offset < fileSize; offset += partSize) { |
||
(function (offset, part) { |
||
fileReadPromise = fileReadPromise.then(function () { |
||
var fileReadDeferred = $q.defer(); |
||
|
||
var reader = new FileReader(); |
||
var blob = file.slice(offset, offset + partSize); |
||
|
||
reader.onloadend = function (e) { |
||
if (e.target.readyState != FileReader.DONE) { |
||
return; |
||
} |
||
var apiCurPromise = apiUploadPromise = apiUploadPromise.then(function () { |
||
return MtpApiManager.invokeApi('upload.saveFilePart', { |
||
file_id: fileID, |
||
file_part: part, |
||
bytes: bytesFromArrayBuffer(e.target.result) |
||
}, { |
||
startMaxLength: partSize + 256, |
||
fileUpload: true |
||
}); |
||
}, errorHandler); |
||
|
||
apiCurPromise.then(function (result) { |
||
doneParts++; |
||
fileReadDeferred.resolve(); |
||
if (doneParts >= totalParts) { |
||
deferred.resolve(resultInputFile); |
||
} else { |
||
console.log('Progress', doneParts * partSize / fileSize); |
||
deferred.notify({done: doneParts * partSize, total: fileSize}); |
||
} |
||
}, errorHandler); |
||
}; |
||
|
||
reader.readAsArrayBuffer(blob); |
||
|
||
return fileReadDeferred.promise; |
||
}); |
||
})(offset, part++); |
||
} |
||
|
||
return deferred.promise; |
||
} |
||
|
||
|
||
return { |
||
getCachedFile: getCachedFile, |
||
downloadFile: downloadFile, |
||
downloadSmallFile: downloadSmallFile, |
||
saveSmallFile: saveSmallFile, |
||
uploadFile: uploadFile |
||
}; |
||
}) |
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
/*! |
||
* Webogram v0.0.20 - messaging web application for MTProto |
||
* https://github.com/zhukov/webogram |
||
* Copyright (C) 2014 Igor Zhukov <[email protected]> |
||
* https://github.com/zhukov/webogram/blob/master/LICENSE |
||
*/ |
||
|
||
var _logTimer = (new Date()).getTime(); |
||
function dT () { |
||
return '[' + (((new Date()).getTime() - _logTimer) / 1000).toFixed(3) + ']'; |
||
} |
||
|
||
function checkClick (e, noprevent) { |
||
if (e.which == 1 && (e.ctrlKey || e.metaKey) || e.which == 2) { |
||
return true; |
||
} |
||
|
||
if (!noprevent) { |
||
e.preventDefault(); |
||
} |
||
|
||
return false; |
||
} |
||
|
||
function checkDragEvent(e) { |
||
if (!e || e.target && (e.target.tagName == 'IMG' || e.target.tagName == 'A')) return false; |
||
if (e.dataTransfer && e.dataTransfer.types) { |
||
for (var i = 0; i < e.dataTransfer.types.length; i++) { |
||
if (e.dataTransfer.types[i] == 'Files') { |
||
return true; |
||
} |
||
} |
||
} else { |
||
return true; |
||
} |
||
|
||
return false; |
||
} |
||
|
||
function cancelEvent (event) { |
||
event = event || window.event; |
||
|
||
event.stopPropagation && event.stopPropagation(); |
||
event.preventDefault && event.preventDefault(); |
||
|
||
return false; |
||
} |
||
|
||
function onCtrlEnter (textarea, cb) { |
||
$(textarea).on('keydown', function (e) { |
||
if (e.keyCode == 13 && (e.ctrlKey || e.metaKey)) { |
||
cb(); |
||
return cancelEvent(e); |
||
} |
||
}); |
||
} |
||
|
||
function onContentLoaded (cb) { |
||
setTimeout(cb, 0); |
||
}; |
||
|
||
function tsNow (seconds) { |
||
var t = +new Date(); |
||
return seconds ? Math.floor(t / 1000) : t; |
||
} |
||
|
||
function safeReplaceObject (wasObject, newObject) { |
||
for (var key in wasObject) { |
||
if (!newObject.hasOwnProperty(key) && key.charAt(0) != '$') { |
||
delete wasObject[key]; |
||
} |
||
} |
||
for (var key in newObject) { |
||
if (newObject.hasOwnProperty(key)) { |
||
wasObject[key] = newObject[key]; |
||
} |
||
} |
||
} |
||
|
||
function safeConfirm (message) { |
||
try { |
||
return confirm(message); |
||
} catch (e) { |
||
// Sorry, temp solution until UI boxes are done |
||
return true; |
||
} |
||
} |
||
|
||
/*! |
||
* Webogram v0.0.20 - messaging web application for MTProto |
||
* https://github.com/zhukov/webogram |
||
* Copyright (C) 2014 Igor Zhukov <[email protected]> |
||
* https://github.com/zhukov/webogram/blob/master/LICENSE |
||
*/ |
||
|
||
'use strict'; |
||
|
||
window._testMode = location.search.indexOf('test=1') > 0; |
||
window._debugMode = location.search.indexOf('debug=1') > 0; |
||
window._osX = (navigator.platform || '').toLowerCase().indexOf('mac') != -1 || |
||
(navigator.userAgent || '').toLowerCase().indexOf('mac') != -1; |
||
window._retina = window.devicePixelRatio > 1; |
||
|
||
if (!window._osX) { |
||
$('body').addClass('non_osx'); |
||
} |
||
$('body').addClass(window._retina ? 'is_2x' : 'is_1x'); |
||
|
||
$(window).on('load', function () { |
||
setTimeout(function () { |
||
window.scrollTo(0,1); |
||
}, 0); |
||
}); |
||
|
||
// Declare app level module which depends on filters, and services |
||
angular.module('myApp', [ |
||
'ngRoute', |
||
'ngAnimate', |
||
'ngSanitize', |
||
'ui.bootstrap', |
||
'mtproto.services', |
||
'myApp.filters', |
||
'myApp.services', |
||
/*PRODUCTION_ONLY_BEGIN*/ |
||
'myApp.templates', |
||
/*PRODUCTION_ONLY_END*/ |
||
'myApp.directives', |
||
'myApp.controllers' |
||
]). |
||
config(['$locationProvider', '$routeProvider', '$compileProvider', function($locationProvider, $routeProvider, $compileProvider) { |
||
|
||
var icons = {}, reverseIcons = {}, i, j, hex, name, dataItem, row, column, totalColumns; |
||
|
||
for (j = 0; j < Config.EmojiCategories.length; j++) { |
||
totalColumns = Config.EmojiCategorySpritesheetDimens[j][1]; |
||
for (i = 0; i < Config.EmojiCategories[j].length; i++) { |
||
dataItem = Config.Emoji[Config.EmojiCategories[j][i]]; |
||
name = dataItem[1][0]; |
||
row = Math.floor(i / totalColumns); |
||
column = (i % totalColumns); |
||
icons[':' + name + ':'] = [j, row, column, ':'+name+':']; |
||
reverseIcons[name] = dataItem[0]; |
||
} |
||
} |
||
|
||
$.emojiarea.spritesheetPath = 'img/emojisprite_!.png'; |
||
$.emojiarea.spritesheetDimens = Config.EmojiCategorySpritesheetDimens; |
||
$.emojiarea.iconSize = 20; |
||
$.emojiarea.icons = icons; |
||
$.emojiarea.reverseIcons = reverseIcons; |
||
|
||
$compileProvider.imgSrcSanitizationWhitelist(/^\s*(https?|ftp|file|blob|filesystem|chrome-extension|app):|data:image\//); |
||
$compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|file|mailto|blob|filesystem|chrome-extension|app):|data:image\//); |
||
|
||
|
||
// $locationProvider.html5Mode(true); |
||
$routeProvider.when('/', {templateUrl: 'partials/welcome.html', controller: 'AppWelcomeController'}); |
||
$routeProvider.when('/login', {templateUrl: 'partials/login.html', controller: 'AppLoginController'}); |
||
$routeProvider.when('/im', {templateUrl: 'partials/im.html', controller: 'AppIMController', reloadOnSearch: false}); |
||
$routeProvider.otherwise({redirectTo: '/'}); |
||
|
||
}]); |
||
|
||
/*! |
||
* Webogram v0.0.20 - messaging web application for MTProto |
||
* https://github.com/zhukov/webogram |
||
* Copyright (C) 2014 Igor Zhukov <[email protected]> |
||
* https://github.com/zhukov/webogram/blob/master/LICENSE |
||
*/ |
||
|
||
'use strict'; |
||
|
||
/* Services */ |
||
|
||
angular.module('myApp.services', []) |
||
|
||
.service('AppConfigManager', function ($q) { |
||
var testPrefix = window._testMode ? 't_' : ''; |
||
var cache = {}; |
||
var useCs = !!(window.chrome && chrome.storage && chrome.storage.local); |
||
var useLs = !useCs && !!window.localStorage; |
||
|
||
function getValue() { |
||
var keys = Array.prototype.slice.call(arguments), |
||
result = [], |
||
single = keys.length == 1, |
||
allFound = true; |
||
|
||
for (var i = 0; i < keys.length; i++) { |
||
keys[i] = testPrefix + keys[i]; |
||
} |
||
|
||
angular.forEach(keys, function (key) { |
||
if (cache[key] !== undefined) { |
||
result.push(cache[key]); |
||
} |
||
else if (useLs) { |
||
var value = localStorage.getItem(key); |
||
value = (value === undefined || value === null) ? false : JSON.parse(value); |
||
result.push(cache[key] = value); |
||
} |
||
else if (!useCs) { |
||
result.push(cache[key] = false); |
||
} |
||
else { |
||
allFound = false; |
||
} |
||
}); |
||
|
||
if (allFound) { |
||
return $q.when(single ? result[0] : result); |
||
} |
||
|
||
var deferred = $q.defer(); |
||
|
||
chrome.storage.local.get(keys, function (resultObj) { |
||
result = []; |
||
angular.forEach(keys, function (key) { |
||
var value = resultObj[key]; |
||
value = value === undefined || value === null ? false : JSON.parse(value); |
||
result.push(cache[key] = value); |
||
}); |
||
|
||
deferred.resolve(single ? result[0] : result); |
||
}); |
||
|
||
return deferred.promise; |
||
}; |
||
|
||
function setValue(obj) { |
||
var keyValues = {}; |
||
angular.forEach(obj, function (value, key) { |
||
keyValues[testPrefix + key] = JSON.stringify(value); |
||
cache[testPrefix + key] = value; |
||
}); |
||
|
||
if (useLs) { |
||
angular.forEach(keyValues, function (value, key) { |
||
localStorage.setItem(key, value); |
||
}); |
||
return $q.when(); |
||
} |
||
|
||
if (!useCs) { |
||
return $q.when(); |
||
} |
||
|
||
var deferred = $q.defer(); |
||
|
||
chrome.storage.local.set(keyValues, function () { |
||
deferred.resolve(); |
||
}); |
||
|
||
return deferred.promise; |
||
}; |
||
|
||
function removeValue () { |
||
var keys = Array.prototype.slice.call(arguments); |
||
|
||
for (var i = 0; i < keys.length; i++) { |
||
keys[i] = testPrefix + keys[i]; |
||
} |
||
|
||
angular.forEach(keys, function(key){ |
||
delete cache[key]; |
||
}); |
||
|
||
if (useLs) { |
||
angular.forEach(keys, function(key){ |
||
localStorage.removeItem(key); |
||
}); |
||
|
||
return $q.when(); |
||
} |
||
|
||
if (!useCs) { |
||
return $q.when(); |
||
} |
||
|
||
var deferred = $q.defer(); |
||
|
||
chrome.storage.local.remove(keys, function () { |
||
deferred.resolve(); |
||
}); |
||
|
||
return deferred.promise; |
||
}; |
||
|
||
return { |
||
get: getValue, |
||
set: setValue, |
||
remove: removeValue |
||
}; |
||
}) |
||
|
||
.service('AppUsersManager', function ($rootScope, $modal, $modalStack, $filter, MtpApiFileManager, MtpApiManager, RichTextProcessor, SearchIndexManager) { |
||
var users = {}, |
||
cachedPhotoLocations = {}, |
||
contactsFillPromise, |
||
contactsList, |
||
contactsIndex = SearchIndexManager.createIndex(); |
||
|
||
function fillContacts () { |
||
if (contactsFillPromise) { |
||
return contactsFillPromise; |
||
} |
||
return contactsFillPromise = MtpApiManager.invokeApi('contacts.getContacts', { |
||
hash: '' |
||
}).then(function (result) { |
||
var userID, searchText, i; |
||
contactsList = []; |
||
saveApiUsers(result.users); |
||
|
||
for (var i = 0; i < result.contacts.length; i++) { |
||
userID = result.contacts[i].user_id; |
||
contactsList.push(userID); |
||
SearchIndexManager.indexObject(userID, getUserSearchText(userID), contactsIndex); |
||
} |
||
|
||
return contactsList; |
||
}); |
||
} |
||
|
||
function getUserSearchText (id) { |
||
var user = users[id]; |
||
if (!user) { |
||
return false; |
||
} |
||
|
||
return (user.first_name || '') + ' ' + (user.last_name || '') + ' ' + (user.phone || ''); |
||
} |
||
|
||
function getContacts (query) { |
||
return fillContacts().then(function (contactsList) { |
||
if (angular.isString(query) && query.length) { |
||
var results = SearchIndexManager.search(query, contactsIndex), |
||
filteredContactsList = []; |
||
|
||
for (var i = 0; i < contactsList.length; i++) { |
||
if (results[contactsList[i]]) { |
||
filteredContactsList.push(contactsList[i]) |
||
} |
||
} |
||
contactsList = filteredContactsList; |
||
} |
||
|
||
return contactsList; |
||
}); |
||
}; |
||
|
||
function saveApiUsers (apiUsers) { |
||
angular.forEach(apiUsers, saveApiUser); |
||
}; |
||
|
||
function saveApiUser (apiUser) { |
||
if (!angular.isObject(apiUser)) { |
||
return; |
||
} |
||
|
||
if (apiUser.phone) { |
||
apiUser.rPhone = $filter('phoneNumber')(apiUser.phone); |
||
} |
||
|
||
if (apiUser.first_name) { |
||
apiUser.rFirstName = RichTextProcessor.wrapRichText(apiUser.first_name, {noLinks: true, noLinebreaks: true}); |
||
apiUser.rFullName = RichTextProcessor.wrapRichText(apiUser.first_name + ' ' + (apiUser.last_name || ''), {noLinks: true, noLinebreaks: true}); |
||
} else { |
||
apiUser.rFirstName = RichTextProcessor.wrapRichText(apiUser.last_name, {noLinks: true, noLinebreaks: true}) || apiUser.rPhone || 'DELETED'; |
||
apiUser.rFullName = RichTextProcessor.wrapRichText(apiUser.last_name, {noLinks: true, noLinebreaks: true}) || apiUser.rPhone || 'DELETED'; |
||
} |
||
apiUser.sortName = SearchIndexManager.cleanSearchText(apiUser.first_name + ' ' + (apiUser.last_name || '')); |
||
apiUser.sortStatus = apiUser.status && (apiUser.status.expires || apiUser.status.was_online) || 0; |
||
|
||
|
||
if (users[apiUser.id] === undefined) { |
||
users[apiUser.id] = apiUser; |
||
} else { |
||
safeReplaceObject(users[apiUser.id], apiUser); |
||
} |
||
|
||
if (cachedPhotoLocations[apiUser.id] !== undefined) { |
||
safeReplaceObject(cachedPhotoLocations[apiUser.id], apiUser && apiUser.photo && apiUser.photo.photo_small || {empty: true}); |
||
} |
||
}; |
||
|
||
function getUser (id) { |
||
if (angular.isObject(id)) { |
||
return id; |
||
} |
||
return users[id] || {id: id, deleted: true}; |
||
} |
||
|
||
function hasUser(id) { |
||
return angular.isObject(users[id]); |
||
} |
||
|
||
function getUserPhoto(id, placeholder) { |
||
var user = getUser(id); |
||
|
||
if (id == 333000) { |
||
return { |
||
placeholder: 'img/placeholders/[email protected]' |
||
} |
||
}; |
||
|
||
if (cachedPhotoLocations[id] === undefined) { |
||
cachedPhotoLocations[id] = user && user.photo && user.photo.photo_small || {empty: true}; |
||
} |
||
|
||
var num = (Math.abs(id) % 8) + 1; |
||
|
||
return { |
||
num: num, |
||
placeholder: 'img/placeholders/' + placeholder + 'Avatar' + num + '@2x.png', |
||
location: cachedPhotoLocations[id] |
||
}; |
||
} |
||
|
||
function getUserString (id) { |
||
var user = getUser(id); |
||
return 'u' + id + (user.access_hash ? '_' + user.access_hash : ''); |
||
} |
||
|
||
function getUserInput (id) { |
||
var user = getUser(id); |
||
if (user._ == 'userSelf') { |
||
return {_: 'inputUserSelf'}; |
||
} |
||
return { |
||
_: 'inputUserForeign', |
||
user_id: id, |
||
access_hash: user.access_hash || 0 |
||
}; |
||
} |
||
|
||
function wrapForFull (id) { |
||
var user = getUser(id); |
||
|
||
user.thumb = { |
||
placeholder: 'img/placeholders/UserAvatar'+((Math.abs(id) % 8) + 1)+'@2x.png', |
||
location: user && user.photo && user.photo.photo_small, |
||
width: 120, |
||
height: 120, |
||
size: 0 |
||
}; |
||
user.peerString = getUserString(id); |
||
|
||
return user; |
||
} |
||
|
||
function openUser (userID, accessHash) { |
||
var scope = $rootScope.$new(); |
||
scope.userID = userID; |
||
|
||
var modalInstance = $modal.open({ |
||
templateUrl: 'partials/user_modal.html', |
||
controller: 'UserModalController', |
||
scope: scope, |
||
windowClass: 'user_modal_window' |
||
}); |
||
} |
||
|
||
$rootScope.openUser = openUser; |
||
|
||
$rootScope.$on('apiUpdate', function (e, update) { |
||
// console.log('on apiUpdate', update); |
||
switch (update._) { |
||
case 'updateUserStatus': |
||
var userID = update.user_id, |
||
user = users[userID]; |
||
if (user) { |
||
user.status = update.status; |
||
user.sortStatus = update.status && (update.status.expires || update.status.was_online) || 0; |
||
$rootScope.$broadcast('user_update', userID); |
||
} |
||
break; |
||
|
||
case 'updateUserPhoto': |
||
var userID = update.user_id; |
||
if (users[userID]) { |
||
safeReplaceObject(users[userID].photo, update.photo); |
||
|
||
if (cachedPhotoLocations[userID] !== undefined) { |
||
safeReplaceObject(cachedPhotoLocations[userID], update.photo && update.photo.photo_small || {empty: true}); |
||
} |
||
|
||
$rootScope.$broadcast('user_update', userID); |
||
} |
||
break; |
||
|
||
case 'updateContactLink': |
||
if (angular.isArray(contactsList)) { |
||
var userID = update.user_id, |
||
curPos = curIsContact = contactsList.indexOf(userID), |
||
curIsContact = curPos != -1, |
||
newIsContact = update.my_link._ == 'contacts.myLinkContact'; |
||
|
||
if (newIsContact != curIsContact) { |
||
if (newIsContact) { |
||
contactsList.push(userID); |
||
SearchIndexManager.indexObject(userID, getUserSearchText(userID), contactsIndex); |
||
} else { |
||
contactsList.splice(curPos, 1); |
||
} |
||
} |
||
} |
||
break; |
||
} |
||
}); |
||
|
||
|
||
return { |
||
getContacts: getContacts, |
||
saveApiUsers: saveApiUsers, |
||
saveApiUser: saveApiUser, |
||
getUser: getUser, |
||
getUserPhoto: getUserPhoto, |
||
getUserString: getUserString, |
||
getUserSearchText: getUserSearchText, |
||
hasUser: hasUser, |
||
wrapForFull: wrapForFull, |
||
openUser: openUser |
||
} |
||
}) |
||
|
||
.service('AppChatsManager', function ($rootScope, $modal, MtpApiFileManager, MtpApiManager, AppUsersManager, RichTextProcessor) { |
||
var chats = {}, |
||
cachedPhotoLocations = {}; |
||
|
||
function saveApiChats (apiChats) { |
||
angular.forEach(apiChats, saveApiChat); |
||
}; |
||
|
||
function saveApiChat (apiChat) { |
||
if (!angular.isObject(apiChat)) { |
||
return; |
||
} |
||
apiChat.rTitle = RichTextProcessor.wrapRichText(apiChat.title, {noLinks: true, noLinebreaks: true}) || 'DELETED'; |
||
if (chats[apiChat.id] === undefined) { |
||
chats[apiChat.id] = apiChat; |
||
} else { |
||
safeReplaceObject(chats[apiChat.id], apiChat); |
||
} |
||
|
||
if (cachedPhotoLocations[apiChat.id] !== undefined) { |
||
safeReplaceObject(cachedPhotoLocations[apiChat.id], apiChat && apiChat.photo && apiChat.photo.photo_small || {empty: true}); |
||
} |
||
}; |
||
|
||
function getChat (id) { |
||
return chats[id] || {id: id, deleted: true}; |
||
} |
||
|
||
function hasChat (id) { |
||
return angular.isObject(chats[id]); |
||
} |
||
|
||
function getChatPhoto(id, placeholder) { |
||
var chat = getChat(id); |
||
|
||
if (cachedPhotoLocations[id] === undefined) { |
||
cachedPhotoLocations[id] = chat && chat.photo && chat.photo.photo_small || {empty: true}; |
||
} |
||
|
||
return { |
||
placeholder: 'img/placeholders/' + placeholder + 'Avatar'+((Math.abs(id) % 4) + 1)+'@2x.png', |
||
location: cachedPhotoLocations[id] |
||
}; |
||
} |
||
|
||
function getChatString (id) { |
||
var chat = getChat(id); |
||
return 'g' + id; |
||
} |
||
|
||
function wrapForFull (id, fullChat) { |
||
var chatFull = angular.copy(fullChat), |
||
chat = getChat(id); |
||
|
||
|
||
if (chatFull.participants && chatFull.participants._ == 'chatParticipants') { |
||
MtpApiManager.getUserID().then(function (myID) { |
||
angular.forEach(chatFull.participants.participants, function(participant){ |
||
participant.user = AppUsersManager.getUser(participant.user_id); |
||
participant.userPhoto = AppUsersManager.getUserPhoto(participant.user_id, 'User'); |
||
participant.inviter = AppUsersManager.getUser(participant.inviter_id); |
||
participant.canKick = myID != participant.user_id && (myID == chatFull.participants.admin_id || myID == participant.inviter_id); |
||
}); |
||
}); |
||
} |
||
|
||
chatFull.thumb = { |
||
placeholder: 'img/placeholders/GroupAvatar'+((Math.abs(id) % 4) + 1)+'@2x.png', |
||
location: chat && chat.photo && chat.photo.photo_small, |
||
width: 120, |
||
height: 120, |
||
size: 0 |
||
}; |
||
chatFull.peerString = getChatString(id); |
||
chatFull.chat = chat; |
||
|
||
return chatFull; |
||
} |
||
|
||
function openChat (chatID, accessHash) { |
||
var scope = $rootScope.$new(); |
||
scope.chatID = chatID; |
||
|
||
var modalInstance = $modal.open({ |
||
templateUrl: 'partials/chat_modal.html', |
||
controller: 'ChatModalController', |
||
windowClass: 'chat_modal_window', |
||
scope: scope |
||
}); |
||
} |
||
|
||
$rootScope.openChat = openChat; |
||
|
||
|
||
return { |
||
saveApiChats: saveApiChats, |
||
saveApiChat: saveApiChat, |
||
getChat: getChat, |
||
getChatPhoto: getChatPhoto, |
||
getChatString: getChatString, |
||
hasChat: hasChat, |
||
wrapForFull: wrapForFull, |
||
openChat: openChat |
||
} |
||
}) |
||
|
||
.service('AppPeersManager', function (AppUsersManager, AppChatsManager) { |
||
return { |
||
getInputPeer: function (peerString) { |
||
var isUser = peerString.charAt(0) == 'u', |
||
peerParams = peerString.substr(1).split('_'); |
||
|
||
return isUser |
||
? {_: 'inputPeerForeign', user_id: peerParams[0], access_hash: peerParams[1]} |
||
: {_: 'inputPeerChat', chat_id: peerParams[0]}; |
||
}, |
||
getInputPeerByID: function (peerID) { |
||
if (peerID > 0) { |
||
return { |
||
_: 'inputPeerForeign', |
||
user_id: peerID, |
||
access_hash: AppUsersManager.getUser(peerID).access_hash || 0 |
||
}; |
||
} else if (peerID < 0) { |
||
return { |
||
_: 'inputPeerChat', |
||
chat_id: -peerID |
||
}; |
||
} |
||
}, |
||
getPeerSearchText: function (peerID) { |
||
var text; |
||
if (peerID > 0) { |
||
text = AppUsersManager.getUserSearchText(peerID); |
||
} else if (peerID < 0) { |
||
var chat = AppChatsManager.getChat(-peerID); |
||
text = chat.title || ''; |
||
} |
||
return text; |
||
}, |
||
getOutputPeer: function (peerID) { |
||
return peerID > 0 |
||
? {_: 'peerUser', user_id: peerID} |
||
: {_: 'peerChat', chat_id: -peerID}; |
||
}, |
||
getPeerID: function (peerString) { |
||
if (angular.isObject(peerString)) { |
||
return peerString.user_id |
||
? peerString.user_id |
||
: -peerString.chat_id; |
||
} |
||
var isUser = peerString.charAt(0) == 'u', |
||
peerParams = peerString.substr(1).split('_'); |
||
|
||
return isUser ? peerParams[0] : -peerParams[0] || 0; |
||
}, |
||
getPeer: function (peerID) { |
||
return peerID > 0 |
||
? AppUsersManager.getUser(peerID) |
||
: AppChatsManager.getChat(-peerID); |
||
}, |
||
getPeerPhoto: function (peerID, userPlaceholder, chatPlaceholder) { |
||
return peerID > 0 |
||
? AppUsersManager.getUserPhoto(peerID, userPlaceholder) |
||
: AppChatsManager.getChatPhoto(-peerID, chatPlaceholder) |
||
} |
||
} |
||
}) |
||
|
||
.service('SearchIndexManager', function () { |
||
var badCharsRe = /[`~!@#$%^&*()\-_=+\[\]\\|{}'";:\/?.>,<\s]+/g, |
||
trimRe = /^\s+|\s$/g, |
||
accentsReplace = { |
||
a: /[áâäà]/g, |
||
e: /[éêëè]/g, |
||
i: /[íîïì]/g, |
||
o: /[óôöò]/g, |
||
u: /[úûüù]/g, |
||
c: /ç/g, |
||
ss: /ß/g |
||
} |
||
|
||
return { |
||
createIndex: createIndex, |
||
indexObject: indexObject, |
||
cleanSearchText: cleanSearchText, |
||
search: search |
||
}; |
||
|
||
function createIndex () { |
||
return { |
||
shortIndexes: {}, |
||
fullTexts: {} |
||
} |
||
} |
||
|
||
function cleanSearchText (text) { |
||
text = text.replace(badCharsRe, ' ').replace(trimRe, '').toLowerCase(); |
||
|
||
for (var key in accentsReplace) { |
||
if (accentsReplace.hasOwnProperty(key)) { |
||
text = text.replace(accentsReplace[key], key); |
||
} |
||
} |
||
|
||
return text; |
||
} |
||
|
||
function indexObject (id, searchText, searchIndex) { |
||
if (searchIndex.fullTexts[id] !== undefined) { |
||
return false; |
||
} |
||
|
||
searchText = cleanSearchText(searchText); |
||
|
||
if (!searchText.length) { |
||
return false; |
||
} |
||
|
||
var shortIndexes = searchIndex.shortIndexes; |
||
|
||
searchIndex.fullTexts[id] = searchText; |
||
|
||
angular.forEach(searchText.split(' '), function(searchWord) { |
||
var len = Math.min(searchWord.length, 3), |
||
wordPart, i; |
||
for (i = 1; i <= len; i++) { |
||
wordPart = searchWord.substr(0, i); |
||
if (shortIndexes[wordPart] === undefined) { |
||
shortIndexes[wordPart] = [id]; |
||
} else { |
||
shortIndexes[wordPart].push(id); |
||
} |
||
} |
||
}); |
||
} |
||
|
||
function search (query, searchIndex) { |
||
console.time('search'); |
||
var shortIndexes = searchIndex.shortIndexes, |
||
fullTexts = searchIndex.fullTexts; |
||
|
||
query = cleanSearchText(query); |
||
|
||
var queryWords = query.split(' '), |
||
foundObjs = false, |
||
newFoundObjs, i, j, searchText, found; |
||
|
||
for (i = 0; i < queryWords.length; i++) { |
||
newFoundObjs = shortIndexes[queryWords[i].substr(0, 3)]; |
||
if (!newFoundObjs) { |
||
foundObjs = []; |
||
break; |
||
} |
||
if (foundObjs === false || foundObjs.length > newFoundObjs.length) { |
||
foundObjs = newFoundObjs; |
||
} |
||
} |
||
|
||
newFoundObjs = {}; |
||
|
||
for (j = 0; j < foundObjs.length; j++) { |
||
found = true; |
||
searchText = fullTexts[foundObjs[j]]; |
||
for (i = 0; i < queryWords.length; i++) { |
||
if (searchText.indexOf(queryWords[i]) == -1) { |
||
found = false; |
||
break; |
||
} |
||
} |
||
if (found) { |
||
newFoundObjs[foundObjs[j]] = true; |
||
} |
||
} |
||
|
||
console.timeEnd('search'); |
||
return newFoundObjs; |
||
} |
||
}) |
||
|
||
.service('AppMessagesManager', function ($q, $rootScope, $location, ApiUpdatesManager, AppUsersManager, AppChatsManager, AppPeersManager, AppPhotosManager, AppVideoManager, AppDocsManager, AppAudioManager, MtpApiManager, MtpApiFileManager, RichTextProcessor, NotificationsManager, SearchIndexManager) { |
||
|
||
var messagesStorage = {}; |
||
var messagesForHistory = {}; |
||
var messagesForDialogs = {}; |
||
var historiesStorage = {}; |
||
var dialogsStorage = {count: null, dialogs: []}; |
||
var pendingByRandomID = {}; |
||
var pendingByMessageID = {}; |
||
var pendingAfterMsgs = {}; |
||
var tempID = -1; |
||
|
||
|
||
var dialogsIndex = SearchIndexManager.createIndex(), |
||
cachedResults = {query: false}; |
||
|
||
NotificationsManager.start(); |
||
|
||
function getDialogs (query, maxID, limit) { |
||
|
||
var curDialogStorage = dialogsStorage; |
||
|
||
if (angular.isString(query) && query.length) { |
||
if (!limit || cachedResults.query !== query) { |
||
cachedResults.query = query; |
||
|
||
var results = SearchIndexManager.search(query, dialogsIndex); |
||
|
||
cachedResults.dialogs = []; |
||
angular.forEach(dialogsStorage.dialogs, function (dialog) { |
||
if (results[dialog.peerID]) { |
||
cachedResults.dialogs.push(dialog); |
||
} |
||
}); |
||
cachedResults.count = cachedResults.dialogs.length; |
||
} |
||
curDialogStorage = cachedResults; |
||
} else { |
||
cachedResults.query = false; |
||
} |
||
|
||
var offset = 0; |
||
if (maxID > 0) { |
||
for (offset = 0; offset < curDialogStorage.dialogs.length; offset++) { |
||
if (maxID > curDialogStorage.dialogs[offset].top_message) { |
||
break; |
||
} |
||
} |
||
} |
||
|
||
if (curDialogStorage.count !== null && curDialogStorage.dialogs.length == curDialogStorage.count || |
||
curDialogStorage.dialogs.length >= offset + (limit || 1) |
||
) { |
||
return $q.when({ |
||
count: curDialogStorage.count, |
||
dialogs: curDialogStorage.dialogs.slice(offset, offset + (limit || 20)) |
||
}); |
||
} |
||
|
||
limit = limit || 20; |
||
|
||
return MtpApiManager.invokeApi('messages.getDialogs', { |
||
offset: offset, |
||
limit: limit, |
||
max_id: maxID || 0 |
||
}).then(function (dialogsResult) { |
||
AppUsersManager.saveApiUsers(dialogsResult.users); |
||
AppChatsManager.saveApiChats(dialogsResult.chats); |
||
saveMessages(dialogsResult.messages); |
||
|
||
if (maxID > 0) { |
||
for (offset = 0; offset < curDialogStorage.dialogs.length; offset++) { |
||
if (maxID > curDialogStorage.dialogs[offset].top_message) { |
||
break; |
||
} |
||
} |
||
} |
||
|
||
curDialogStorage.count = dialogsResult._ == 'messages.dialogsSlice' |
||
? dialogsResult.count |
||
: dialogsResult.dialogs.length; |
||
|
||
curDialogStorage.dialogs.splice(offset, curDialogStorage.dialogs.length - offset); |
||
angular.forEach(dialogsResult.dialogs, function (dialog) { |
||
var peerID = AppPeersManager.getPeerID(dialog.peer), |
||
peerText = AppPeersManager.getPeerSearchText(peerID); |
||
|
||
SearchIndexManager.indexObject(peerID, peerText, dialogsIndex); |
||
|
||
curDialogStorage.dialogs.push({ |
||
peerID: peerID, |
||
top_message: dialog.top_message, |
||
unread_count: dialog.unread_count |
||
}); |
||
|
||
if (historiesStorage[peerID] === undefined) { |
||
historiesStorage[peerID] = {count: null, history: [dialog.top_message], pending: []} |
||
} |
||
}); |
||
|
||
return { |
||
count: curDialogStorage.count, |
||
dialogs: curDialogStorage.dialogs.slice(offset, offset + limit) |
||
}; |
||
}); |
||
} |
||
|
||
function fillHistoryStorage (inputPeer, maxID, fullLimit, historyStorage) { |
||
return MtpApiManager.invokeApi('messages.getHistory', { |
||
peer: inputPeer, |
||
offset: 0, |
||
limit: fullLimit, |
||
max_id: maxID || 0 |
||
}).then(function (historyResult) { |
||
AppUsersManager.saveApiUsers(historyResult.users); |
||
AppChatsManager.saveApiChats(historyResult.chats); |
||
saveMessages(historyResult.messages); |
||
|
||
historyStorage.count = historyResult._ == 'messages.messagesSlice' |
||
? historyResult.count |
||
: historyResult.messages.length; |
||
|
||
var offset = 0; |
||
if (maxID > 0) { |
||
for (offset = 0; offset < historyStorage.history.length; offset++) { |
||
if (maxID > historyStorage.history[offset]) { |
||
break; |
||
} |
||
} |
||
} |
||
|
||
historyStorage.history.splice(offset, historyStorage.history.length - offset); |
||
angular.forEach(historyResult.messages, function (message) { |
||
historyStorage.history.push(message.id); |
||
}); |
||
|
||
fullLimit -= historyResult.messages.length; |
||
|
||
if (fullLimit > 0 && historyStorage.history.length < historyStorage.count) { |
||
maxID = historyStorage.history[historyStorage.history.length - 1]; |
||
return fillHistoryStorage(inputPeer, maxID, fullLimit, historyStorage); |
||
} |
||
|
||
return true; |
||
}); |
||
}; |
||
|
||
function getHistory (inputPeer, maxID, limit) { |
||
|
||
var peerID = AppPeersManager.getPeerID(inputPeer), |
||
historyStorage = historiesStorage[peerID], |
||
offset = 0, |
||
resultPending = []; |
||
|
||
if (historyStorage === undefined) { |
||
historyStorage = historiesStorage[peerID] = {count: null, history: [], pending: []}; |
||
} |
||
else if (!maxID && historyStorage.pending.length) { |
||
resultPending = historyStorage.pending.slice(); |
||
} |
||
|
||
var unreadLimit = false; |
||
if (!limit && !maxID) { |
||
var foundDialog = getDialogByPeerID(peerID); |
||
if (foundDialog && foundDialog[0] && foundDialog[0].unread_count > 1) { |
||
unreadLimit = Math.min(1000, foundDialog[0].unread_count); |
||
limit = unreadLimit; |
||
} |
||
} |
||
|
||
if (maxID > 0) { |
||
for (offset = 0; offset < historyStorage.history.length; offset++) { |
||
if (maxID > historyStorage.history[offset]) { |
||
break; |
||
} |
||
} |
||
} |
||
|
||
if (historyStorage.count !== null && historyStorage.history.length == historyStorage.count || |
||
historyStorage.history.length >= offset + (limit || 1) |
||
) { |
||
return $q.when({ |
||
count: historyStorage.count, |
||
history: resultPending.concat(historyStorage.history.slice(offset, offset + (limit || 20))), |
||
unreadLimit: unreadLimit |
||
}); |
||
} |
||
|
||
if (unreadLimit) { |
||
limit = Math.max(20, unreadLimit + 2); |
||
} |
||
|
||
limit = limit || 20; |
||
|
||
return fillHistoryStorage(inputPeer, maxID, limit, historyStorage).then(function () { |
||
offset = 0; |
||
if (maxID > 0) { |
||
for (offset = 0; offset < historyStorage.history.length; offset++) { |
||
if (maxID > historyStorage.history[offset]) { |
||
break; |
||
} |
||
} |
||
} |
||
|
||
return { |
||
count: historyStorage.count, |
||
history: resultPending.concat(historyStorage.history.slice(offset, offset + limit)), |
||
unreadLimit: unreadLimit |
||
}; |
||
}); |
||
} |
||
|
||
function getSearch (inputPeer, query, inputFilter, maxID, limit) { |
||
return MtpApiManager.invokeApi('messages.search', { |
||
peer: inputPeer, |
||
q: query || '', |
||
filter: inputFilter || {_: 'inputMessagesFilterEmpty'}, |
||
min_date: 0, |
||
max_date: 0, |
||
limit: limit || 20, |
||
max_id: maxID || 0 |
||
}).then(function (searchResult) { |
||
AppUsersManager.saveApiUsers(searchResult.users); |
||
AppChatsManager.saveApiChats(searchResult.chats); |
||
saveMessages(searchResult.messages); |
||
|
||
var foundCount = searchResult._ == 'messages.messagesSlice' |
||
? searchResult.count |
||
: searchResult.messages.length; |
||
|
||
var foundMsgs = []; |
||
angular.forEach(searchResult.messages, function (message) { |
||
foundMsgs.push(message.id); |
||
}); |
||
|
||
return { |
||
count: foundCount, |
||
history: foundMsgs |
||
}; |
||
}); |
||
} |
||
|
||
function deleteMessages (messageIDs) { |
||
return MtpApiManager.invokeApi('messages.deleteMessages', { |
||
id: messageIDs |
||
}).then(function (deletedMessageIDs) { |
||
|
||
ApiUpdatesManager.saveUpdate({ |
||
_: 'updateDeleteMessages', |
||
messages: deletedMessageIDs |
||
}); |
||
|
||
return deletedMessageIDs; |
||
}); |
||
|
||
|
||
} |
||
|
||
function processAffectedHistory (inputPeer, affectedHistory, method) { |
||
if (!ApiUpdatesManager.saveSeq(affectedHistory.seq)) { |
||
return false; |
||
} |
||
if (!affectedHistory.offset) { |
||
return $q.when(); |
||
} |
||
|
||
return MtpApiManager.invokeApi(method, { |
||
peer: inputPeer, |
||
offset: affectedHistory.offset, |
||
max_id: 0 |
||
}).then(function (affectedHistory) { |
||
return processAffectedHistory(inputPeer, affectedHistory, method); |
||
}); |
||
} |
||
|
||
function readHistory (inputPeer) { |
||
// console.trace('start read'); |
||
var peerID = AppPeersManager.getPeerID(inputPeer), |
||
historyStorage = historiesStorage[peerID], |
||
foundDialog = getDialogByPeerID(peerID); |
||
|
||
if (!foundDialog[0] || !foundDialog[0].unread_count) { |
||
|
||
if (!historyStorage || !historyStorage.history.length) { |
||
return false; |
||
} |
||
|
||
var messageID, |
||
message, |
||
foundUnread = false; |
||
for (i = historyStorage.history.length; i >= 0; i--) { |
||
messageID = historyStorage.history[i]; |
||
message = messagesStorage[messageID]; |
||
// console.log('ms', message); |
||
if (message && !message.out && message.unread) { |
||
foundUnread = true; |
||
break; |
||
} |
||
} |
||
if (!foundUnread) { |
||
return false; |
||
} |
||
} |
||
|
||
var promise = MtpApiManager.invokeApi('messages.readHistory', { |
||
peer: inputPeer, |
||
offset: 0, |
||
max_id: 0 |
||
}).then(function (affectedHistory) { |
||
return processAffectedHistory(inputPeer, affectedHistory, 'messages.readHistory'); |
||
}).then(function () { |
||
if (foundDialog[0]) { |
||
// console.log('done read history', peerID); |
||
foundDialog[0].unread_count = 0; |
||
$rootScope.$broadcast('dialog_unread', {peerID: peerID, count: 0}); |
||
} |
||
}); |
||
|
||
|
||
if (historyStorage && historyStorage.history.length) { |
||
var messageID, message, i, peerID, foundDialog, dialog; |
||
for (i = 0; i < historyStorage.history.length; i++) { |
||
messageID = historyStorage.history[i]; |
||
message = messagesStorage[messageID]; |
||
if (message && !message.out) { |
||
message.unread = false; |
||
if (messagesForHistory[messageID]) { |
||
messagesForHistory[messageID].unread = false; |
||
} |
||
if (messagesForDialogs[messageID]) { |
||
messagesForDialogs[messageID].unread = false; |
||
} |
||
} |
||
} |
||
} |
||
|
||
return promise; |
||
} |
||
|
||
function flushHistory (inputPeer) { |
||
// console.log('start flush'); |
||
var peerID = AppPeersManager.getPeerID(inputPeer), |
||
historyStorage = historiesStorage[peerID]; |
||
|
||
return MtpApiManager.invokeApi('messages.deleteHistory', { |
||
peer: inputPeer, |
||
offset: 0 |
||
}).then(function (affectedHistory) { |
||
return processAffectedHistory(inputPeer, affectedHistory, 'messages.deleteHistory'); |
||
}).then(function () { |
||
var foundDialog = getDialogByPeerID(peerID); |
||
if (foundDialog[0]) { |
||
dialogsStorage.dialogs.splice(foundDialog[1], 1); |
||
} |
||
delete historiesStorage[peerID]; |
||
$rootScope.$broadcast('dialog_flush', {peerID: peerID}); |
||
}); |
||
} |
||
|
||
function saveMessages (apiMessages) { |
||
angular.forEach(apiMessages, function (apiMessage) { |
||
messagesStorage[apiMessage.id] = apiMessage; |
||
|
||
if (apiMessage.media && apiMessage.media._ == 'messageMediaPhoto') { |
||
AppPhotosManager.savePhoto(apiMessage.media.photo); |
||
} |
||
if (apiMessage.media && apiMessage.media._ == 'messageMediaVideo') { |
||
AppVideoManager.saveVideo(apiMessage.media.video); |
||
} |
||
if (apiMessage.media && apiMessage.media._ == 'messageMediaDocument') { |
||
AppDocsManager.saveDoc(apiMessage.media.document); |
||
} |
||
if (apiMessage.media && apiMessage.media._ == 'messageMediaAudio') { |
||
AppAudioManager.saveAudio(apiMessage.media.audio); |
||
} |
||
if (apiMessage.action && apiMessage.action._ == 'messageActionChatEditPhoto') { |
||
AppPhotosManager.savePhoto(apiMessage.action.photo); |
||
} |
||
}); |
||
} |
||
|
||
function sendText(peerID, text) { |
||
var messageID = tempID--, |
||
randomID = [nextRandomInt(0xFFFFFFFF), nextRandomInt(0xFFFFFFFF)], |
||
randomIDS = bigint(randomID[0]).shiftLeft(32).add(bigint(randomID[1])).toString(), |
||
historyStorage = historiesStorage[peerID], |
||
inputPeer = AppPeersManager.getInputPeerByID(peerID), |
||
message; |
||
|
||
if (historyStorage === undefined) { |
||
historyStorage = historiesStorage[peerID] = {count: null, history: [], pending: []}; |
||
} |
||
|
||
MtpApiManager.getUserID().then(function (fromID) { |
||
message = { |
||
_: 'message', |
||
id: messageID, |
||
from_id: fromID, |
||
to_id: AppPeersManager.getOutputPeer(peerID), |
||
out: true, |
||
unread: true, |
||
date: tsNow() / 1000, |
||
message: text, |
||
media: {_: 'messageMediaEmpty'}, |
||
random_id: randomIDS, |
||
pending: true |
||
}; |
||
|
||
var toggleError = function (on) { |
||
var historyMessage = messagesForHistory[messageID]; |
||
if (on) { |
||
message.error = true; |
||
if (historyMessage) { |
||
historyMessage.error = true; |
||
} |
||
} else { |
||
delete message.error; |
||
if (historyMessage) { |
||
delete historyMessage.error; |
||
} |
||
} |
||
} |
||
|
||
message.send = function () { |
||
toggleError(false); |
||
var sentRequestOptions = {}; |
||
if (pendingAfterMsgs[peerID]) { |
||
sentRequestOptions.afterMessageID = pendingAfterMsgs[peerID].messageID; |
||
} |
||
MtpApiManager.invokeApi('messages.sendMessage', { |
||
peer: inputPeer, |
||
message: text, |
||
random_id: randomID |
||
}, sentRequestOptions).then(function (result) { |
||
if (pendingAfterMsgs[peerID] === sentRequestOptions) { |
||
delete pendingAfterMsgs[peerID]; |
||
} |
||
if (ApiUpdatesManager.saveSeq(result.seq)) { |
||
ApiUpdatesManager.saveUpdate({ |
||
_: 'updateMessageID', |
||
random_id: randomIDS, |
||
id: result.id |
||
}); |
||
|
||
message.date = result.date; |
||
message.id = result.id; |
||
ApiUpdatesManager.saveUpdate({ |
||
_: 'updateNewMessage', |
||
message: message, |
||
pts: result.pts |
||
}); |
||
} |
||
}, function (error) { |
||
toggleError(true); |
||
}); |
||
|
||
pendingAfterMsgs[peerID] = sentRequestOptions; |
||
}; |
||
|
||
saveMessages([message]); |
||
historyStorage.pending.unshift(messageID); |
||
$rootScope.$broadcast('history_append', {peerID: peerID, messageID: messageID, my: true}); |
||
|
||
// setTimeout(function () { |
||
message.send(); |
||
// }, 5000); |
||
}); |
||
|
||
pendingByRandomID[randomIDS] = [peerID, messageID]; |
||
}; |
||
|
||
function sendFile(peerID, file, options) { |
||
options = options || {}; |
||
var messageID = tempID--, |
||
randomID = [nextRandomInt(0xFFFFFFFF), nextRandomInt(0xFFFFFFFF)], |
||
randomIDS = bigint(randomID[0]).shiftLeft(32).add(bigint(randomID[1])).toString(), |
||
historyStorage = historiesStorage[peerID], |
||
inputPeer = AppPeersManager.getInputPeerByID(peerID), |
||
attachType, fileName, fileName; |
||
|
||
if (!options.isMedia) { |
||
attachType = 'document'; |
||
fileName = 'document.' + file.type.split('/')[1]; |
||
} else if (['image/jpeg', 'image/gif', 'image/png', 'image/bmp'].indexOf(file.type) >= 0) { |
||
attachType = 'photo'; |
||
fileName = 'photo.' + file.type.split('/')[1]; |
||
} else if (file.type.substr(0, 6) == 'video/') { |
||
attachType = 'video'; |
||
fileName = 'video.mp4'; |
||
} else if (file.type == 'audio/mpeg' || file.type == 'audio/mp3') { |
||
attachType = 'audio'; |
||
fileName = 'audio.mp3'; |
||
} else { |
||
attachType = 'document'; |
||
fileName = 'document.' + file.type.split('/')[1]; |
||
} |
||
|
||
if (!file.name) { |
||
file.name = fileName; |
||
} |
||
|
||
if (historyStorage === undefined) { |
||
historyStorage = historiesStorage[peerID] = {count: null, history: [], pending: []}; |
||
} |
||
|
||
MtpApiManager.getUserID().then(function (fromID) { |
||
var media = { |
||
_: 'messageMediaPending', |
||
type: attachType, |
||
file_name: file.name, |
||
size: file.size, |
||
progress: {percent: 1, total: file.size} |
||
}; |
||
|
||
var message = { |
||
_: 'message', |
||
id: messageID, |
||
from_id: fromID, |
||
to_id: AppPeersManager.getOutputPeer(peerID), |
||
out: true, |
||
unread: true, |
||
date: tsNow() / 1000, |
||
message: '', |
||
media: media, |
||
random_id: randomIDS, |
||
pending: true |
||
}; |
||
|
||
var toggleError = function (on) { |
||
var historyMessage = messagesForHistory[messageID]; |
||
if (on) { |
||
message.error = true; |
||
if (historyMessage) { |
||
historyMessage.error = true; |
||
} |
||
} else { |
||
delete message.error; |
||
if (historyMessage) { |
||
delete historyMessage.error; |
||
} |
||
} |
||
} |
||
|
||
message.send = function () { |
||
MtpApiFileManager.uploadFile(file).then(function (inputFile) { |
||
var inputMedia; |
||
switch (attachType) { |
||
case 'photo': |
||
inputMedia = {_: 'inputMediaUploadedPhoto', file: inputFile}; |
||
break; |
||
|
||
case 'video': |
||
inputMedia = {_: 'inputMediaUploadedVideo', file: inputFile, duration: 0, w: 0, h: 0}; |
||
break; |
||
|
||
case 'audio': |
||
inputMedia = {_: 'inputMediaUploadedAudio', file: inputFile, duration: 0}; |
||
break; |
||
|
||
case 'document': |
||
default: |
||
inputMedia = {_: 'inputMediaUploadedDocument', file: inputFile, file_name: file.name, mime_type: file.type}; |
||
} |
||
MtpApiManager.invokeApi('messages.sendMedia', { |
||
peer: inputPeer, |
||
media: inputMedia, |
||
random_id: randomID |
||
}).then(function (result) { |
||
if (ApiUpdatesManager.saveSeq(result.seq)) { |
||
ApiUpdatesManager.saveUpdate({ |
||
_: 'updateMessageID', |
||
random_id: randomIDS, |
||
id: result.message.id |
||
}); |
||
|
||
message.date = result.message.date; |
||
message.id = result.message.id; |
||
message.media = result.message.media; |
||
|
||
ApiUpdatesManager.saveUpdate({ |
||
_: 'updateNewMessage', |
||
message: message, |
||
pts: result.pts |
||
}); |
||
} |
||
|
||
}, function (error) { |
||
toggleError(true); |
||
}); |
||
}, function (error) { |
||
toggleError(true); |
||
}, function (progress) { |
||
// console.log('upload progress', progress); |
||
var historyMessage = messagesForHistory[messageID], |
||
percent = Math.max(1, Math.floor(100 * progress.done / progress.total)); |
||
|
||
media.progress.done = progress.done; |
||
media.progress.percent = percent; |
||
if (historyMessage) { |
||
historyMessage.media.progress.done = progress.done; |
||
historyMessage.media.progress.percent = percent; |
||
$rootScope.$broadcast('history_update', {peerID: peerID}); |
||
} |
||
}); |
||
}; |
||
|
||
saveMessages([message]); |
||
historyStorage.pending.unshift(messageID); |
||
$rootScope.$broadcast('history_append', {peerID: peerID, messageID: messageID, my: true}); |
||
|
||
message.send(); |
||
}); |
||
|
||
pendingByRandomID[randomIDS] = [peerID, messageID]; |
||
} |
||
|
||
function forwardMessages (msgIDs, inputPeer) { |
||
return MtpApiManager.invokeApi('messages.forwardMessages', { |
||
peer: inputPeer, |
||
id: msgIDs |
||
}).then(function (forwardResult) { |
||
AppUsersManager.saveApiUsers(forwardResult.users); |
||
AppChatsManager.saveApiChats(forwardResult.chats); |
||
|
||
if (ApiUpdatesManager.saveSeq(forwardResult.seq)) { |
||
angular.forEach(forwardResult.messages, function(apiMessage) { |
||
|
||
ApiUpdatesManager.saveUpdate({ |
||
_: 'updateNewMessage', |
||
message: apiMessage, |
||
pts: forwardResult.pts |
||
}); |
||
|
||
}); |
||
} |
||
|
||
}); |
||
}; |
||
|
||
function finalizePendingMessage(randomID, finalMessage) { |
||
var pendingData = pendingByRandomID[randomID]; |
||
// console.log('pdata', randomID, pendingData); |
||
|
||
if (pendingData) { |
||
var peerID = pendingData[0], |
||
tempID = pendingData[1], |
||
historyStorage = historiesStorage[peerID], |
||
index = false, |
||
message = false, |
||
historyMessage = false, |
||
i; |
||
|
||
// console.log('pending', randomID, historyStorage.pending); |
||
for (i = 0; i < historyStorage.pending.length; i++) { |
||
if (historyStorage.pending[i] == tempID) { |
||
historyStorage.pending.splice(i, 1); |
||
break; |
||
} |
||
} |
||
|
||
if (message = messagesStorage[tempID]) { |
||
delete message.pending; |
||
delete message.error; |
||
delete message.random_id; |
||
delete message.send; |
||
} |
||
|
||
if (historyMessage = messagesForHistory[tempID]) { |
||
messagesForHistory[finalMessage.id] = angular.extend(historyMessage, wrapForHistory(finalMessage.id)); |
||
delete historyMessage.pending; |
||
delete historyMessage.error; |
||
delete historyMessage.random_id; |
||
delete historyMessage.send; |
||
} |
||
|
||
delete messagesForHistory[tempID]; |
||
delete messagesStorage[tempID]; |
||
|
||
return message; |
||
} |
||
|
||
return false; |
||
} |
||
|
||
function getMessagePeer (message) { |
||
var toID = message.to_id && AppPeersManager.getPeerID(message.to_id) || 0; |
||
|
||
if (toID < 0) { |
||
return toID; |
||
} else if (message.out) { |
||
return toID; |
||
} |
||
return message.from_id; |
||
} |
||
|
||
function wrapForDialog (msgID, unreadCount) { |
||
if (messagesForDialogs[msgID] !== undefined) { |
||
return messagesForDialogs[msgID]; |
||
} |
||
|
||
var message = angular.copy(messagesStorage[msgID]) || {id: msgID}; |
||
|
||
message.fromUser = AppUsersManager.getUser(message.from_id); |
||
|
||
if (message.chatID = message.to_id.chat_id) { |
||
message.peerID = -message.chatID; |
||
message.peerData = AppChatsManager.getChat(message.chatID); |
||
message.peerString = AppChatsManager.getChatString(message.chatID); |
||
} else { |
||
message.peerID = message.out ? message.to_id.user_id : message.from_id; |
||
message.peerData = AppUsersManager.getUser(message.peerID); |
||
message.peerString = AppUsersManager.getUserString(message.peerID); |
||
} |
||
|
||
message.peerPhoto = AppPeersManager.getPeerPhoto(message.peerID, 'User', 'Group'); |
||
message.unreadCount = unreadCount; |
||
|
||
if (message._ == 'messageService' && message.action.user_id) { |
||
message.action.user = AppUsersManager.getUser(message.action.user_id); |
||
} |
||
|
||
if (message.message && message.message.length) { |
||
message.richMessage = RichTextProcessor.wrapRichText(message.message.substr(0, 64), {noLinks: true, noLinebreaks: true}); |
||
} |
||
|
||
|
||
return messagesForDialogs[msgID] = message; |
||
} |
||
|
||
function wrapForHistory (msgID) { |
||
if (messagesForHistory[msgID] !== undefined) { |
||
return messagesForHistory[msgID]; |
||
} |
||
|
||
var message = angular.copy(messagesStorage[msgID]) || {id: msgID}; |
||
|
||
message.fromUser = AppUsersManager.getUser(message.from_id); |
||
message.fromPhoto = AppUsersManager.getUserPhoto(message.from_id, 'User'); |
||
|
||
if (message._ == 'messageForwarded') { |
||
message.fwdUser = AppUsersManager.getUser(message.fwd_from_id); |
||
} |
||
|
||
if (message.media) { |
||
switch (message.media._) { |
||
case 'messageMediaPhoto': |
||
message.media.photo = AppPhotosManager.wrapForHistory(message.media.photo.id) |
||
break; |
||
|
||
case 'messageMediaVideo': |
||
message.media.video = AppVideoManager.wrapForHistory(message.media.video.id); |
||
break; |
||
|
||
case 'messageMediaDocument': |
||
message.media.document = AppDocsManager.wrapForHistory(message.media.document.id); |
||
break; |
||
|
||
case 'messageMediaAudio': |
||
message.media.audio = AppAudioManager.wrapForHistory(message.media.audio.id); |
||
break; |
||
} |
||
|
||
if (message.media.user_id) { |
||
message.media.user = AppUsersManager.getUser(message.media.user_id); |
||
message.media.userPhoto = AppUsersManager.getUserPhoto(message.media.user_id, 'User'); |
||
} |
||
} |
||
else if (message.action) { |
||
if (message.action._ == 'messageActionChatEditPhoto') { |
||
message.action.photo = AppPhotosManager.wrapForHistory(message.action.photo.id); |
||
} |
||
|
||
if (message.action.user_id) { |
||
message.action.user = AppUsersManager.getUser(message.action.user_id); |
||
message.action.userPhoto = AppUsersManager.getUserPhoto(message.action.user_id, 'User'); |
||
} |
||
} |
||
|
||
if (message.message && message.message.length) { |
||
message.richMessage = RichTextProcessor.wrapRichText(message.message); |
||
} |
||
|
||
return messagesForHistory[msgID] = message; |
||
} |
||
|
||
function getDialogByPeerID (peerID) { |
||
for (var i = 0; i < dialogsStorage.dialogs.length; i++) { |
||
if (dialogsStorage.dialogs[i].peerID == peerID) { |
||
return [dialogsStorage.dialogs[i], i]; |
||
} |
||
} |
||
|
||
return []; |
||
} |
||
|
||
function notifyAboutMessage (message) { |
||
var peerID = getMessagePeer(message); |
||
var fromUser = AppUsersManager.getUser(message.from_id); |
||
var fromPhoto = AppUsersManager.getUserPhoto(message.from_id, 'User'); |
||
var peerString; |
||
var notification = {}, |
||
notificationMessage = false, |
||
notificationPhoto; |
||
|
||
if (message.message) { |
||
notificationMessage = message.message; |
||
} else if (message.media && message.media._ != 'messageMediaEmpty') { |
||
switch (message.media._) { |
||
case 'messageMediaPhoto': notificationMessage = 'Photo'; break; |
||
case 'messageMediaVideo': notificationMessage = 'Video'; break; |
||
case 'messageMediaDocument': notificationMessage = 'Document'; break; |
||
case 'messageMediaGeo': notificationMessage = 'Location'; break; |
||
case 'messageMediaContact': notificationMessage = 'Contact'; break; |
||
default: notificationMessage = 'Attachment'; break; |
||
} |
||
} else if (message._ == 'messageService') { |
||
switch (message.action._) { |
||
case 'messageActionChatCreate': notificationMessage = 'created the group'; break; |
||
case 'messageActionChatEditTitle': notificationMessage = 'changed group name'; break; |
||
case 'messageActionChatEditPhoto': notificationMessage = 'changed group photo'; break; |
||
case 'messageActionChatDeletePhoto': notificationMessage = 'removed group photo'; break; |
||
case 'messageActionChatAddUser': notificationMessage = 'invited user'; break; |
||
case 'messageActionChatDeleteUser': notificationMessage = 'kicked user'; break; |
||
} |
||
} |
||
|
||
if (peerID > 0) { |
||
notification.title = (fromUser.first_name || '') + |
||
(fromUser.first_name && fromUser.last_name ? ' ' : '') + |
||
(fromUser.last_name || ''); |
||
|
||
notificationPhoto = fromPhoto; |
||
|
||
peerString = AppUsersManager.getUserString(peerID); |
||
|
||
} else { |
||
notification.title = (fromUser.first_name || fromUser.last_name || 'Somebody') + |
||
' @ ' + |
||
(AppChatsManager.getChat(-peerID).title || 'Unknown chat'); |
||
|
||
notificationPhoto = AppChatsManager.getChatPhoto(-peerID, 'Group'); |
||
|
||
peerString = AppChatsManager.getChatString(-peerID); |
||
} |
||
|
||
notification.onclick = function () { |
||
$rootScope.$broadcast('history_focus', {peerString: peerString}); |
||
}; |
||
|
||
notification.message = notificationMessage; |
||
notification.image = notificationPhoto.placeholder; |
||
notification.key = 'msg' + message.id; |
||
|
||
if (notificationPhoto.location && !notificationPhoto.location.empty) { |
||
MtpApiFileManager.downloadSmallFile(notificationPhoto.location, notificationPhoto.size).then(function (url) { |
||
notification.image = url; |
||
|
||
if (message.unread) { |
||
NotificationsManager.notify(notification); |
||
} |
||
}); |
||
} else { |
||
NotificationsManager.notify(notification); |
||
} |
||
} |
||
|
||
$rootScope.$on('apiUpdate', function (e, update) { |
||
// if (update._ != 'updateUserStatus') { |
||
// console.log('on apiUpdate', update); |
||
// } |
||
switch (update._) { |
||
case 'updateMessageID': |
||
pendingByMessageID[update.id] = update.random_id; |
||
break; |
||
|
||
case 'updateNewMessage': |
||
var message = update.message, |
||
peerID = getMessagePeer(message), |
||
historyStorage = historiesStorage[peerID]; |
||
|
||
if (historyStorage !== undefined) { |
||
var topMsgID = historiesStorage[peerID].history[0]; |
||
if (message.id <= topMsgID) { |
||
return false; |
||
} |
||
} else { |
||
historyStorage = historiesStorage[peerID] = {count: null, history: [], pending: []}; |
||
} |
||
|
||
saveMessages([message]); |
||
|
||
if (historyStorage.count !== null) { |
||
historyStorage.count++; |
||
} |
||
|
||
historyStorage.history.unshift(message.id); |
||
var randomID = pendingByMessageID[message.id], |
||
pendingMessage; |
||
|
||
|
||
if (randomID) { |
||
if (pendingMessage = finalizePendingMessage(randomID, message)) { |
||
$rootScope.$broadcast('history_update', {peerID: peerID}); |
||
} |
||
delete pendingByMessageID[message.id]; |
||
} |
||
|
||
// console.log(11, randomID, pendingMessage); |
||
if (!pendingMessage) { |
||
$rootScope.$broadcast('history_append', {peerID: peerID, messageID: message.id}); |
||
} |
||
|
||
var foundDialog = getDialogByPeerID(peerID), |
||
dialog; |
||
|
||
if (foundDialog.length) { |
||
dialog = foundDialog[0]; |
||
dialogsStorage.dialogs.splice(foundDialog[1], 1); |
||
} else { |
||
dialog = {peerID: peerID, unread_count: 0, top_message: false} |
||
} |
||
if (!message.out && message.unread) { |
||
// console.log('inc unread count', dialog.unread_count); |
||
dialog.unread_count++; |
||
} |
||
dialog.top_message = message.id; |
||
|
||
// console.log('new message', message, peerID, historyStorage, foundDialog, dialog); |
||
|
||
SearchIndexManager.indexObject(peerID, AppPeersManager.getPeerSearchText(peerID), dialogsIndex); |
||
|
||
dialogsStorage.dialogs.unshift(dialog); |
||
$rootScope.$broadcast('dialogs_update', dialog); |
||
|
||
|
||
if ($rootScope.idle.isIDLE && !message.out && message.unread) { |
||
NotificationsManager.getPeerMuted(peerID).then(function (muted) { |
||
if (!message.unread || muted) { |
||
return; |
||
} |
||
notifyAboutMessage(message); |
||
}); |
||
} |
||
break; |
||
|
||
case 'updateReadMessages': |
||
var dialogsUpdated = {}, |
||
messageID, message, i, peerID, foundDialog, dialog; |
||
for (i = 0; i < update.messages.length; i++) { |
||
messageID = update.messages[i]; |
||
message = messagesStorage[messageID]; |
||
// console.log('read', messageID, message.unread, message); |
||
if (message && message.unread) { |
||
message.unread = false; |
||
if (messagesForHistory[messageID]) { |
||
messagesForHistory[messageID].unread = false; |
||
} |
||
if (messagesForDialogs[messageID]) { |
||
messagesForDialogs[messageID].unread = false; |
||
} |
||
peerID = getMessagePeer(message); |
||
if (!message.out) { |
||
foundDialog = getDialogByPeerID(peerID); |
||
if (foundDialog) { |
||
dialogsUpdated[peerID] = --foundDialog[0].unread_count; |
||
} |
||
|
||
NotificationsManager.cancel('msg' + messageID); |
||
} |
||
} |
||
} |
||
|
||
angular.forEach(dialogsUpdated, function(count, peerID) { |
||
$rootScope.$broadcast('dialog_unread', {peerID: peerID, count: count}); |
||
}); |
||
break; |
||
|
||
case 'updateDeleteMessages': |
||
var dialogsUpdated = {}, |
||
historiesUpdated = {}, |
||
messageID, message, i, peerID, foundDialog, dialog, history; |
||
|
||
for (i = 0; i < update.messages.length; i++) { |
||
messageID = update.messages[i]; |
||
message = messagesStorage[messageID]; |
||
if (message) { |
||
peerID = getMessagePeer(message); |
||
history = historiesUpdated[peerID] || (historiesUpdated[peerID] = {count: 0, unread: 0, msgs: {}}); |
||
|
||
if (!message.out && message.unread) { |
||
history.unread++; |
||
NotificationsManager.cancel('msg' + messageID); |
||
} |
||
history.count++; |
||
history.msgs[messageID] = true; |
||
|
||
if (messagesForHistory[messageID]) { |
||
messagesForHistory[messageID].DELETED = true; |
||
delete messagesForHistory[messageID]; |
||
} |
||
if (messagesForDialogs[messageID]) { |
||
messagesForDialogs[messageID].DELETED = true; |
||
delete messagesForDialogs[messageID]; |
||
} |
||
message.DELETED = true; |
||
delete messagesStorage[messageID]; |
||
} |
||
} |
||
|
||
angular.forEach(historiesUpdated, function (updatedData, peerID) { |
||
var foundDialog = getDialogByPeerID(peerID); |
||
if (foundDialog) { |
||
if (updatedData.unread) { |
||
foundDialog[0].unread_count -= updatedData.unread; |
||
|
||
$rootScope.$broadcast('dialog_unread', {peerID: peerID, count: foundDialog[0].unread_count}); |
||
} |
||
} |
||
|
||
var historyStorage = historiesStorage[peerID]; |
||
if (historyStorage !== undefined) { |
||
var newHistory = []; |
||
for (var i = 0; i < historyStorage.history.length; i++) { |
||
if (!updatedData.msgs[historyStorage.history[i]]) { |
||
newHistory.push(historyStorage.history[i]); |
||
} |
||
} |
||
historyStorage.history = newHistory; |
||
$rootScope.$broadcast('history_delete', {peerID: peerID, msgs: updatedData.msgs}); |
||
} |
||
}); |
||
break; |
||
} |
||
}); |
||
|
||
return { |
||
getDialogs: getDialogs, |
||
getHistory: getHistory, |
||
getSearch: getSearch, |
||
readHistory: readHistory, |
||
flushHistory: flushHistory, |
||
deleteMessages: deleteMessages, |
||
saveMessages: saveMessages, |
||
sendText: sendText, |
||
sendFile: sendFile, |
||
forwardMessages: forwardMessages, |
||
getMessagePeer: getMessagePeer, |
||
wrapForDialog: wrapForDialog, |
||
wrapForHistory: wrapForHistory |
||
} |
||
}) |
||
|
||
.service('AppPhotosManager', function ($modal, $window, $rootScope, MtpApiFileManager, AppUsersManager) { |
||
var photos = {}; |
||
|
||
function savePhoto (apiPhoto) { |
||
photos[apiPhoto.id] = apiPhoto; |
||
angular.forEach(apiPhoto.sizes, function (photoSize) { |
||
if (photoSize._ == 'photoCachedSize') { |
||
MtpApiFileManager.saveSmallFile(photoSize.location, photoSize.bytes); |
||
|
||
// Memory |
||
photoSize.size = photoSize.bytes.length; |
||
delete photoSize.bytes; |
||
photoSize._ = 'photoSize'; |
||
} |
||
}); |
||
}; |
||
|
||
function choosePhotoSize (photo, width, height) { |
||
var bestPhotoSize = {_: 'photoSizeEmpty'}, |
||
bestDiff = 0xFFFFFF; |
||
|
||
angular.forEach(photo.sizes, function (photoSize) { |
||
var diff = Math.abs(photoSize.w * photoSize.h - width * height); |
||
if (diff < bestDiff) { |
||
bestPhotoSize = photoSize; |
||
bestDiff = diff; |
||
} |
||
}); |
||
|
||
// console.log('choosing', photo, width, height, bestPhotoSize); |
||
|
||
return bestPhotoSize; |
||
} |
||
|
||
function wrapForHistory (photoID) { |
||
var photo = angular.copy(photos[photoID]) || {_: 'photoEmpty'}, |
||
width = 260, |
||
height = 260, |
||
thumbPhotoSize = choosePhotoSize(photo, width, height), |
||
thumb = { |
||
placeholder: 'img/placeholders/PhotoThumbConversation.gif', |
||
width: width, |
||
height: height |
||
}; |
||
|
||
// console.log('chosen photo size', photoID, thumbPhotoSize); |
||
if (thumbPhotoSize && thumbPhotoSize._ != 'photoSizeEmpty') { |
||
if (thumbPhotoSize.w > thumbPhotoSize.h) { |
||
thumb.height = parseInt(thumbPhotoSize.h * width / thumbPhotoSize.w); |
||
} else { |
||
thumb.width = parseInt(thumbPhotoSize.w * height / thumbPhotoSize.h); |
||
} |
||
|
||
thumb.location = thumbPhotoSize.location; |
||
thumb.size = thumbPhotoSize.size; |
||
} else { |
||
thumb.width = 100; |
||
thumb.height = 100; |
||
} |
||
|
||
photo.thumb = thumb; |
||
|
||
return photo; |
||
} |
||
|
||
function wrapForFull (photoID) { |
||
var photo = wrapForHistory(photoID), |
||
fullWidth = Math.min($(window).width() - 60, 542), |
||
fullHeight = $($window).height() - 150, |
||
fullPhotoSize = choosePhotoSize(photo, fullWidth, fullHeight), |
||
full = { |
||
placeholder: 'img/placeholders/PhotoThumbModal.gif', |
||
width: fullWidth, |
||
height: fullHeight |
||
}; |
||
|
||
if (fullPhotoSize && fullPhotoSize._ != 'photoSizeEmpty') { |
||
if (fullPhotoSize.w > fullPhotoSize.h) { |
||
full.height = parseInt(fullPhotoSize.h * fullWidth / fullPhotoSize.w); |
||
} else { |
||
full.width = parseInt(fullPhotoSize.w * fullHeight / fullPhotoSize.h); |
||
if (full.width > fullWidth) { |
||
full.height = parseInt(full.height * fullWidth / full.width); |
||
full.width = fullWidth; |
||
} |
||
} |
||
|
||
full.location = fullPhotoSize.location; |
||
full.size = fullPhotoSize.size; |
||
} |
||
|
||
photo.full = full; |
||
photo.fromUser = AppUsersManager.getUser(photo.user_id); |
||
|
||
return photo; |
||
} |
||
|
||
function openPhoto (photoID, accessHash) { |
||
var scope = $rootScope.$new(true); |
||
scope.photoID = photoID; |
||
|
||
var modalInstance = $modal.open({ |
||
templateUrl: 'partials/photo_modal.html', |
||
controller: 'PhotoModalController', |
||
scope: scope |
||
}); |
||
} |
||
|
||
$rootScope.openPhoto = openPhoto; |
||
|
||
|
||
return { |
||
savePhoto: savePhoto, |
||
wrapForHistory: wrapForHistory, |
||
wrapForFull: wrapForFull, |
||
openPhoto: openPhoto |
||
} |
||
}) |
||
|
||
|
||
.service('AppVideoManager', function ($rootScope, $modal, $window, MtpApiFileManager, AppUsersManager) { |
||
var videos = {}; |
||
|
||
function saveVideo (apiVideo) { |
||
videos[apiVideo.id] = apiVideo; |
||
|
||
if (apiVideo.thumb && apiVideo.thumb._ == 'photoCachedSize') { |
||
MtpApiFileManager.saveSmallFile(apiVideo.thumb.location, apiVideo.thumb.bytes); |
||
|
||
// Memory |
||
apiVideo.thumb.size = apiVideo.thumb.bytes.length; |
||
delete apiVideo.thumb.bytes; |
||
apiVideo.thumb._ = 'photoSize'; |
||
} |
||
}; |
||
|
||
function wrapForHistory (videoID) { |
||
var video = angular.copy(videos[videoID]), |
||
width = 200, |
||
height = 200, |
||
thumbPhotoSize = video.thumb, |
||
thumb = { |
||
placeholder: 'img/placeholders/VideoThumbConversation.gif', |
||
width: width, |
||
height: height |
||
}; |
||
|
||
if (thumbPhotoSize && thumbPhotoSize._ != 'photoSizeEmpty') { |
||
if (thumbPhotoSize.w > thumbPhotoSize.h) { |
||
thumb.height = parseInt(thumbPhotoSize.h * width / thumbPhotoSize.w); |
||
} else { |
||
thumb.width = parseInt(thumbPhotoSize.w * height / thumbPhotoSize.h); |
||
} |
||
|
||
thumb.location = thumbPhotoSize.location; |
||
thumb.size = thumbPhotoSize.size; |
||
} |
||
|
||
video.thumb = thumb; |
||
|
||
return video; |
||
} |
||
|
||
function wrapForFull (videoID) { |
||
var video = wrapForHistory(videoID), |
||
fullWidth = Math.min($(window).width() - 60, 542), |
||
fullHeight = $($window).height() - 150, |
||
fullPhotoSize = video, |
||
full = { |
||
placeholder: 'img/placeholders/VideoThumbModal.gif', |
||
width: fullWidth, |
||
height: fullHeight, |
||
}; |
||
|
||
if (!video.w || !video.h) { |
||
full.height = full.width = Math.min(fullWidth, fullHeight); |
||
} |
||
else if (video.w > video.h) { |
||
full.height = parseInt(video.h * fullWidth / video.w); |
||
} |
||
else { |
||
full.width = parseInt(video.w * fullHeight / video.h); |
||
if (full.width > fullWidth) { |
||
full.height = parseInt(full.height * fullWidth / full.width); |
||
full.width = fullWidth; |
||
} |
||
} |
||
// console.log(222, video.w, video.h, full.width, full.height); |
||
|
||
video.full = full; |
||
video.fromUser = AppUsersManager.getUser(video.user_id); |
||
|
||
return video; |
||
} |
||
|
||
function openVideo (videoID, accessHash) { |
||
var scope = $rootScope.$new(true); |
||
scope.videoID = videoID; |
||
scope.progress = {enabled: false}; |
||
scope.player = {}; |
||
|
||
var modalInstance = $modal.open({ |
||
templateUrl: 'partials/video_modal.html', |
||
controller: 'VideoModalController', |
||
scope: scope |
||
}); |
||
} |
||
|
||
$rootScope.openVideo = openVideo; |
||
|
||
return { |
||
saveVideo: saveVideo, |
||
wrapForHistory: wrapForHistory, |
||
wrapForFull: wrapForFull, |
||
openVideo: openVideo |
||
} |
||
}) |
||
|
||
.service('AppDocsManager', function ($rootScope, $modal, $window, $timeout, MtpApiFileManager) { |
||
var docs = {}; |
||
var docsForHistory = {}; |
||
|
||
function saveDoc (apiDoc) { |
||
docs[apiDoc.id] = apiDoc; |
||
|
||
if (apiDoc.thumb && apiDoc.thumb._ == 'photoCachedSize') { |
||
MtpApiFileManager.saveSmallFile(apiDoc.thumb.location, apiDoc.thumb.bytes); |
||
|
||
// Memory |
||
apiDoc.thumb.size = apiDoc.thumb.bytes.length; |
||
delete apiDoc.thumb.bytes; |
||
apiDoc.thumb._ = 'photoSize'; |
||
} |
||
}; |
||
|
||
function wrapForHistory (docID) { |
||
if (docsForHistory[docID] !== undefined) { |
||
return docsForHistory[docID]; |
||
} |
||
|
||
var doc = angular.copy(docs[docID]), |
||
width = 100, |
||
height = 100, |
||
thumbPhotoSize = doc.thumb, |
||
thumb = { |
||
// placeholder: 'img/placeholders/DocThumbConversation.jpg', |
||
width: width, |
||
height: height |
||
}; |
||
|
||
if (thumbPhotoSize && thumbPhotoSize._ != 'photoSizeEmpty') { |
||
if (thumbPhotoSize.w > thumbPhotoSize.h) { |
||
thumb.height = parseInt(thumbPhotoSize.h * width / thumbPhotoSize.w); |
||
} else { |
||
thumb.width = parseInt(thumbPhotoSize.w * height / thumbPhotoSize.h); |
||
} |
||
|
||
thumb.location = thumbPhotoSize.location; |
||
thumb.size = thumbPhotoSize.size; |
||
} else { |
||
thumb = false; |
||
} |
||
doc.thumb = thumb; |
||
|
||
doc.canDownload = !(window.chrome && chrome.fileSystem && chrome.fileSystem.chooseEntry); |
||
doc.withPreview = doc.canDownload && doc.mime_type.match(/^(image\/|application\/pdf)/); |
||
|
||
return docsForHistory[docID] = doc; |
||
} |
||
|
||
function openDoc (docID, accessHash, popup) { |
||
var doc = docs[docID], |
||
historyDoc = docsForHistory[docID] || doc || {}, |
||
inputFileLocation = { |
||
_: 'inputDocumentFileLocation', |
||
id: docID, |
||
access_hash: accessHash || doc.access_hash |
||
}; |
||
|
||
historyDoc.progress = {enabled: true, percent: 1, total: doc.size}; |
||
|
||
function updateDownloadProgress (progress) { |
||
console.log('dl progress', progress); |
||
historyDoc.progress.done = progress.done; |
||
historyDoc.progress.percent = Math.max(1, Math.floor(100 * progress.done / progress.total)); |
||
$rootScope.$broadcast('history_update'); |
||
} |
||
|
||
|
||
if (window.chrome && chrome.fileSystem && chrome.fileSystem.chooseEntry) { |
||
var ext = (doc.file_name.split('.', 2) || [])[1] || ''; |
||
|
||
chrome.fileSystem.chooseEntry({ |
||
type: 'saveFile', |
||
suggestedName: doc.file_name, |
||
accepts: [{ |
||
mimeTypes: [doc.mime_type], |
||
extensions: [ext] |
||
}] |
||
}, function (writableFileEntry) { |
||
MtpApiFileManager.downloadFile(doc.dc_id, inputFileLocation, doc.size, writableFileEntry, {mime: doc.mime_type}).then(function (url) { |
||
delete historyDoc.progress; |
||
console.log('file save done'); |
||
}, function (e) { |
||
console.log('document download failed', e); |
||
historyDoc.progress.enabled = false; |
||
}, updateDownloadProgress); |
||
}); |
||
} else { |
||
MtpApiFileManager.downloadFile(doc.dc_id, inputFileLocation, doc.size, null, {mime: doc.mime_type}).then(function (url) { |
||
delete historyDoc.progress; |
||
|
||
if (popup) { |
||
window.open(url, '_blank'); |
||
return |
||
} |
||
|
||
var a = $('<a>Download</a>').css({position: 'absolute', top: 1, left: 1}).attr('href', url).attr('target', '_blank').attr('download', doc.file_name).appendTo('body'); |
||
a[0].dataset.downloadurl = ['png', doc.file_name, url].join(':'); |
||
a[0].click(); |
||
$timeout(function () { |
||
a.remove(); |
||
}, 100); |
||
}, function (e) { |
||
console.log('document download failed', e); |
||
historyDoc.progress.enabled = false; |
||
}, updateDownloadProgress); |
||
} |
||
} |
||
|
||
$rootScope.openDoc = openDoc; |
||
|
||
return { |
||
saveDoc: saveDoc, |
||
wrapForHistory: wrapForHistory, |
||
openDoc: openDoc |
||
} |
||
}) |
||
|
||
.service('AppAudioManager', function ($rootScope, $modal, $window, $timeout, $sce, MtpApiFileManager) { |
||
var audios = {}; |
||
var audiosForHistory = {}; |
||
|
||
function saveAudio (apiAudio) { |
||
audios[apiAudio.id] = apiAudio; |
||
}; |
||
|
||
function wrapForHistory (audioID) { |
||
if (audiosForHistory[audioID] !== undefined) { |
||
return audiosForHistory[audioID]; |
||
} |
||
|
||
var audio = angular.copy(audios[audioID]); |
||
|
||
return audiosForHistory[audioID] = audio; |
||
} |
||
|
||
function openAudio (audioID, accessHash) { |
||
var audio = audios[audioID], |
||
historyAudio = audiosForHistory[audioID] || audio || {}, |
||
inputFileLocation = { |
||
_: 'inputAudioFileLocation', |
||
id: audioID, |
||
access_hash: accessHash || audio.access_hash |
||
}; |
||
|
||
historyAudio.progress = {enabled: true, percent: 1, total: audio.size}; |
||
|
||
function updateDownloadProgress (progress) { |
||
console.log('dl progress', progress); |
||
historyAudio.progress.done = progress.done; |
||
historyAudio.progress.percent = Math.max(1, Math.floor(100 * progress.done / progress.total)); |
||
$rootScope.$broadcast('history_update'); |
||
} |
||
|
||
MtpApiFileManager.downloadFile(audio.dc_id, inputFileLocation, audio.size, null, {mime: 'audio/mpeg'}).then(function (url) { |
||
delete historyAudio.progress; |
||
historyAudio.url = $sce.trustAsResourceUrl(url); |
||
historyAudio.autoplay = true; |
||
$timeout(function () { |
||
console.log('disable autoplay'); |
||
delete historyAudio.autoplay; |
||
$rootScope.$broadcast('history_update'); |
||
}, 1000); |
||
}, function (e) { |
||
console.log('document download failed', e); |
||
historyDoc.progress.enabled = false; |
||
}, updateDownloadProgress); |
||
} |
||
|
||
$rootScope.openAudio = openAudio; |
||
|
||
return { |
||
saveAudio: saveAudio, |
||
wrapForHistory: wrapForHistory, |
||
openAudio: openAudio |
||
} |
||
}) |
||
|
||
.service('ExternalResourcesManager', function ($q, $http) { |
||
var urlPromises = {}; |
||
|
||
function downloadImage (url) { |
||
if (urlPromises[url] !== undefined) { |
||
return urlPromises[url]; |
||
} |
||
|
||
return urlPromises[url] = $http.get(url, {responseType: 'blob', transformRequest: null}) |
||
.then(function (response) { |
||
return window.webkitURL.createObjectURL(response.data); |
||
}); |
||
} |
||
|
||
return { |
||
downloadImage: downloadImage |
||
} |
||
}) |
||
|
||
|
||
.service('ApiUpdatesManager', function ($rootScope, MtpNetworkerFactory, AppUsersManager, AppChatsManager, AppPeersManager, MtpApiManager) { |
||
|
||
var curState = {invalid: true}; |
||
|
||
function processUpdateMessage (updateMessage) { |
||
if (curState.invalid) { |
||
return false; |
||
} |
||
|
||
if (updateMessage.seq) { |
||
if (!saveSeq(updateMessage.seq, updateMessage.seq_start)) { |
||
return false; |
||
} |
||
if (updateMessage.date) { |
||
curState.date = updateMessage.date; |
||
} |
||
} |
||
|
||
|
||
switch (updateMessage._) { |
||
case 'updatesTooLong': |
||
getDifference(); |
||
break; |
||
|
||
case 'updateShort': |
||
saveUpdate(updateMessage.update); |
||
break; |
||
|
||
case 'updatesCombined': |
||
case 'updates': |
||
AppUsersManager.saveApiUsers(updateMessage.users); |
||
AppChatsManager.saveApiChats(updateMessage.chats); |
||
|
||
var i, update, message; |
||
for (var i = 0; i < updateMessage.updates.length; i++) { |
||
update = updateMessage.updates[i]; |
||
switch (update._) { |
||
case 'updateNewMessage': |
||
message = update.message; |
||
if (message.from_id && !AppUsersManager.hasUser(message.from_id)) { |
||
console.log('User not found', message.from_id, 'getDiff'); |
||
getDifference(); |
||
return false; |
||
} |
||
if (message.to_id.chat_id && !AppChatsManager.hasChat(message.to_id.chat_id)) { |
||
console.log('Chat not found', message.to_id.chat_id, 'getDiff'); |
||
getDifference(); |
||
return false; |
||
} |
||
break; |
||
} |
||
} |
||
|
||
angular.forEach(updateMessage.updates, function (update) { |
||
saveUpdate(update); |
||
}); |
||
break; |
||
|
||
case 'updateShortMessage': |
||
if (!AppUsersManager.hasUser(updateMessage.from_id)) { |
||
console.log('User not found', updateMessage.from_id, 'getDiff'); |
||
getDifference(); |
||
break; |
||
} |
||
saveUpdate({ |
||
_: 'updateNewMessage', |
||
message: { |
||
_: 'message', |
||
id: updateMessage.id, |
||
from_id: updateMessage.from_id, |
||
to_id: AppPeersManager.getOutputPeer(MtpApiManager.getUserID()), |
||
out: false, |
||
unread: true, |
||
date: updateMessage.date, |
||
message: updateMessage.message, |
||
media: {_: 'messageMediaEmpty'} |
||
}, |
||
pts: updateMessage.pts |
||
}); |
||
break; |
||
|
||
case 'updateShortChatMessage': |
||
if (!AppUsersManager.hasUser(updateMessage.from_id) || |
||
!AppChatsManager.hasChat(updateMessage.chat_id)) { |
||
console.log('User or chat not found', updateMessage.from_id, updateMessage.chat_id, 'getDiff'); |
||
getDifference(); |
||
break; |
||
} |
||
saveUpdate({ |
||
_: 'updateNewMessage', |
||
message: { |
||
_: 'message', |
||
id: updateMessage.id, |
||
from_id: updateMessage.from_id, |
||
to_id: AppPeersManager.getOutputPeer(-updateMessage.chat_id), |
||
out: false, |
||
unread: true, |
||
date: updateMessage.date, |
||
message: updateMessage.message, |
||
media: {_: 'messageMediaEmpty'} |
||
}, |
||
pts: updateMessage.pts |
||
}); |
||
break; |
||
} |
||
|
||
return true; |
||
} |
||
|
||
function getDifference (force) { |
||
if (curState.invalid && !force) { |
||
return false; |
||
} |
||
|
||
curState.invalid = true; |
||
MtpApiManager.invokeApi('updates.getDifference', {pts: curState.pts, date: curState.date, qts: 0}).then(function (differenceResult) { |
||
if (differenceResult._ == 'updates.differenceEmpty') { |
||
curState.date = differenceResult.date; |
||
curState.seq = differenceResult.seq; |
||
delete curState.invalid; |
||
return false; |
||
} |
||
|
||
AppUsersManager.saveApiUsers(differenceResult.users); |
||
AppChatsManager.saveApiChats(differenceResult.chats); |
||
|
||
// Should be first because of updateMessageID |
||
angular.forEach(differenceResult.other_updates, function(update){ |
||
saveUpdate(update, true); |
||
}); |
||
|
||
angular.forEach(differenceResult.new_messages, function (apiMessage) { |
||
saveUpdate({ |
||
_: 'updateNewMessage', |
||
message: apiMessage, |
||
pts: curState.pts |
||
}, true); |
||
}); |
||
|
||
var nextState = differenceResult.intermediate_state || differenceResult.state; |
||
curState.seq = nextState.seq; |
||
curState.pts = nextState.pts; |
||
curState.date = nextState.date; |
||
|
||
if (differenceResult._ == 'updates.differenceSlice') { |
||
getDifference(true); |
||
} else { |
||
delete curState.invalid; |
||
} |
||
}); |
||
} |
||
|
||
function saveUpdate (update, force) { |
||
if (curState.invalid && !force) { |
||
return false; |
||
} |
||
if (update.pts) { |
||
curState.pts = update.pts; |
||
} |
||
|
||
$rootScope.$broadcast('apiUpdate', update); |
||
} |
||
|
||
function saveSeq (seq, seqStart) { |
||
// console.log('saving seq', curState.invalid, seq, seqStart, curState.seq); |
||
|
||
if (curState.invalid) { |
||
return false; |
||
} |
||
|
||
seqStart = seqStart || seq; |
||
|
||
if (!seqStart) { |
||
return true; |
||
} |
||
|
||
if (seqStart != curState.seq + 1) { |
||
if (seqStart > curState.seq) { |
||
console.warn('Seq hole', seqStart, curState.seq); |
||
getDifference(); |
||
} |
||
return false; |
||
} |
||
|
||
curState.seq = seq; |
||
|
||
return true; |
||
} |
||
|
||
function attach () { |
||
MtpNetworkerFactory.setUpdatesProcessor(processUpdateMessage); |
||
MtpApiManager.invokeApi('updates.getState').then(function (stateResult) { |
||
curState.seq = stateResult.seq; |
||
curState.pts = stateResult.pts; |
||
curState.date = stateResult.date; |
||
delete curState.invalid; |
||
}) |
||
} |
||
|
||
|
||
return { |
||
saveUpdate: saveUpdate, |
||
saveSeq: saveSeq, |
||
attach: attach |
||
} |
||
}) |
||
|
||
.service('RichTextProcessor', function ($sce, $sanitize) { |
||
|
||
var emojiUtf = [], |
||
emojiMap = {}, |
||
emojiData = Config.Emoji, |
||
emojiIconSize = 18, |
||
emojiCode; |
||
|
||
for (emojiCode in emojiData) { |
||
emojiUtf.push(emojiData[emojiCode][0]); |
||
emojiMap[emojiData[emojiCode][0]] = emojiCode; |
||
} |
||
|
||
var regExp = new RegExp('((?:(ftp|https?)://|(?:mailto:)?([A-Za-z0-9._%+-]+@))(\\S*\\.\\S*[^\\s.;,(){}<>"\']))|(\\n)|(' + emojiUtf.join('|') + ')', 'i'); |
||
|
||
return { |
||
wrapRichText: wrapRichText |
||
}; |
||
|
||
function encodeEntities(value) { |
||
return value. |
||
replace(/&/g, '&'). |
||
replace(/([^\#-~| |!])/g, function (value) { // non-alphanumeric |
||
return '&#' + value.charCodeAt(0) + ';'; |
||
}). |
||
replace(/</g, '<'). |
||
replace(/>/g, '>'); |
||
} |
||
|
||
function getEmojiSpritesheetCoords(emojiCode) { |
||
var i, row, column, totalColumns; |
||
for (var cat = 0; cat < Config.EmojiCategories.length; cat++) { |
||
totalColumns = Config.EmojiCategorySpritesheetDimens[cat][1]; |
||
i = Config.EmojiCategories[cat].indexOf(emojiCode); |
||
if (i > -1) { |
||
row = Math.floor(i / totalColumns); |
||
column = (i % totalColumns); |
||
return { category: cat, row: row, column: column }; |
||
} |
||
} |
||
console.error('emoji not found in spritesheet', emojiCode); |
||
return null; |
||
} |
||
|
||
function wrapRichText(text, options) { |
||
if (!text || !text.length) { |
||
return ''; |
||
} |
||
|
||
options = options || {}; |
||
|
||
text = text.replace(/\ufe0f/g, '', text); |
||
|
||
var match, |
||
raw = text, |
||
html = [], |
||
url, |
||
emojiFound = false, |
||
emojiTitle, |
||
emojiCoords; |
||
|
||
while ((match = raw.match(regExp))) { |
||
// console.log(2, match); |
||
html.push(encodeEntities(raw.substr(0, match.index))); |
||
|
||
if (match[1]) { // URL |
||
if (!options.noLinks) { |
||
if (match[3]) { |
||
html.push( |
||
'<a href="', |
||
encodeEntities('mailto:' + match[3] + match[4]), |
||
'" target="_blank">', |
||
encodeEntities(match[3] + match[4]), |
||
'</a>' |
||
); |
||
} else { |
||
html.push( |
||
'<a href="', |
||
encodeEntities(match[2] + '://' + match[4]), |
||
'" target="_blank">', |
||
encodeEntities(match[2] + '://' + match[4]), |
||
'</a>' |
||
); |
||
} |
||
} else { |
||
html.push(encodeEntities(match[0])); |
||
} |
||
} |
||
else if (match[5]) { // New line |
||
if (!options.noLinebreaks) { |
||
html.push('<br/>'); |
||
} else { |
||
html.push(' '); |
||
} |
||
} |
||
else if (match[6]) { |
||
|
||
if ((emojiCode = emojiMap[match[6]]) && |
||
(emojiCoords = getEmojiSpritesheetCoords(emojiCode))) { |
||
|
||
emojiTitle = encodeEntities(emojiData[emojiCode][1][0]); |
||
emojiFound = true; |
||
html.push( |
||
'<span class="emoji emoji-', |
||
emojiCoords.category, |
||
'-', |
||
(emojiIconSize * emojiCoords.column), |
||
'-', |
||
(emojiIconSize * emojiCoords.row), |
||
'" ', |
||
'title="',emojiTitle, '">', |
||
':', emojiTitle, ':</span>' |
||
); |
||
} else { |
||
html.push(encodeEntities(match[6])); |
||
} |
||
} |
||
raw = raw.substr(match.index + match[0].length); |
||
} |
||
|
||
html.push(encodeEntities(raw)); |
||
|
||
text = $sanitize(html.join('')); |
||
|
||
// console.log(3, text, html); |
||
|
||
if (emojiFound) { |
||
text = text.replace(/<span class="emoji emoji-(\d)-(\d+)-(\d+)"(.+?)<\/span>/g, |
||
'<span class="emoji emoji-spritesheet-$1" style="background-position: -$2px -$3px;" $4</span>'); |
||
} |
||
|
||
// console.log(4, text, html); |
||
|
||
return $sce.trustAs('html', text); |
||
} |
||
|
||
}) |
||
|
||
|
||
.service('IdleManager', function ($rootScope, $window, $timeout) { |
||
|
||
$rootScope.idle = {isIDLE: false}; |
||
|
||
var toPromise, started = false; |
||
|
||
return { |
||
start: start |
||
}; |
||
|
||
function start () { |
||
if (!started) { |
||
started = true; |
||
$($window).on('blur focus keydown mousedown touchstart', onEvent); |
||
} |
||
} |
||
|
||
function onEvent (e) { |
||
// console.log('event', e.type); |
||
if (e.type == 'mousemove') { |
||
$($window).off('mousemove', onEvent); |
||
} |
||
var isIDLE = e.type == 'blur' || e.type == 'timeout' ? true : false; |
||
|
||
$timeout.cancel(toPromise); |
||
if (!isIDLE) { |
||
// console.log('update timeout'); |
||
toPromise = $timeout(function () { |
||
onEvent({type: 'timeout'}); |
||
}, 30000); |
||
} |
||
|
||
if ($rootScope.idle.isIDLE == isIDLE) { |
||
return; |
||
} |
||
|
||
// console.log('IDLE changed', isIDLE); |
||
$rootScope.$apply(function () { |
||
$rootScope.idle.isIDLE = isIDLE; |
||
}); |
||
|
||
if (isIDLE && e.type == 'timeout') { |
||
$($window).on('mousemove', onEvent); |
||
} |
||
} |
||
}) |
||
|
||
.service('StatusManager', function ($timeout, $rootScope, MtpApiManager, IdleManager) { |
||
|
||
var toPromise, lastOnlineUpdated = 0, started = false; |
||
|
||
return { |
||
start: start |
||
}; |
||
|
||
function start() { |
||
if (!started) { |
||
started = true; |
||
$rootScope.$watch('idle.isIDLE', checkIDLE); |
||
$rootScope.$watch('offline', checkIDLE); |
||
} |
||
} |
||
|
||
function sendUpdateStatusReq(offline) { |
||
var date = tsNow(); |
||
if (offline && !lastOnlineUpdated || |
||
!offline && (date - lastOnlineUpdated) < 50000 || |
||
$rootScope.offline) { |
||
return; |
||
} |
||
lastOnlineUpdated = offline ? 0 : date; |
||
return MtpApiManager.invokeApi('account.updateStatus', { |
||
offline: offline |
||
}); |
||
} |
||
|
||
function checkIDLE() { |
||
toPromise && $timeout.cancel(toPromise); |
||
if ($rootScope.idle.isIDLE) { |
||
toPromise = $timeout(function () { |
||
sendUpdateStatusReq(true); |
||
}, 5000); |
||
} else { |
||
sendUpdateStatusReq(false); |
||
toPromise = $timeout(checkIDLE, 60000); |
||
} |
||
} |
||
|
||
}) |
||
|
||
.service('NotificationsManager', function ($rootScope, $window, $timeout, $interval, $q, MtpApiManager, AppPeersManager, IdleManager, AppConfigManager) { |
||
|
||
var notificationsUiSupport = 'Notification' in window; |
||
var notificationsShown = {}; |
||
// var lastClosed = []; |
||
var notificationIndex = 0; |
||
var notificationsCount = 0; |
||
var peerSettings = {}; |
||
var faviconBackupEl = $('link[rel="icon"]'), |
||
faviconNewEl = $('<link rel="icon" href="favicon_unread.ico" type="image/x-icon" />'); |
||
|
||
var titleBackup = document.title, |
||
titlePromise; |
||
|
||
$rootScope.$watch('idle.isIDLE', function (newVal) { |
||
// console.log('isIDLE watch', newVal); |
||
$interval.cancel(titlePromise); |
||
|
||
if (!newVal) { |
||
notificationsCount = 0; |
||
document.title = titleBackup; |
||
$('link[rel="icon"]').replaceWith(faviconBackupEl); |
||
notificationsClear(); |
||
} else { |
||
titleBackup = document.title; |
||
|
||
titlePromise = $interval(function () { |
||
var time = tsNow(); |
||
if (!notificationsCount || time % 2000 > 1000) { |
||
document.title = titleBackup; |
||
$('link[rel="icon"]').replaceWith(faviconBackupEl); |
||
} else { |
||
document.title = notificationsCount > 1 |
||
? (notificationsCount + ' notifications') |
||
: '1 notification'; |
||
|
||
$('link[rel="icon"]').replaceWith(faviconNewEl); |
||
} |
||
}, 1000); |
||
} |
||
}); |
||
|
||
return { |
||
start: start, |
||
notify: notify, |
||
cancel: notificationCancel, |
||
clear: notificationsClear, |
||
getPeerSettings: getPeerSettings, |
||
getPeerMuted: getPeerMuted, |
||
savePeerSettings: savePeerSettings |
||
}; |
||
|
||
function getPeerSettings (peerID) { |
||
if (peerSettings[peerID] !== undefined) { |
||
return peerSettings[peerID]; |
||
} |
||
|
||
return peerSettings[peerID] = MtpApiManager.invokeApi('account.getNotifySettings', { |
||
peer: { |
||
_: 'inputNotifyPeer', |
||
peer: AppPeersManager.getInputPeerByID(peerID) |
||
} |
||
}); |
||
} |
||
|
||
function savePeerSettings (peerID, settings) { |
||
var inputSettings = angular.copy(settings); |
||
inputSettings._ = 'inputPeerNotifySettings'; |
||
|
||
peerSettings[peerID] = $q.when(settings); |
||
|
||
return MtpApiManager.invokeApi('account.updateNotifySettings', { |
||
peer: { |
||
_: 'inputNotifyPeer', |
||
peer: AppPeersManager.getInputPeerByID(peerID) |
||
}, |
||
settings: inputSettings |
||
}); |
||
} |
||
|
||
function getPeerMuted (peerID) { |
||
return getPeerSettings(peerID).then(function (peerNotifySettings) { |
||
return peerNotifySettings._ == 'peerNotifySettings' && |
||
peerNotifySettings.mute_until * 1000 > tsNow(); |
||
}); |
||
} |
||
|
||
function start () { |
||
if (!notificationsUiSupport) { |
||
return false; |
||
} |
||
|
||
if (Notification.permission !== 'granted' && Notification.permission !== 'denied') { |
||
$($window).on('click', requestPermission); |
||
} |
||
|
||
|
||
try { |
||
$($window).on('beforeunload', notificationsClear); |
||
} catch (e) {} |
||
} |
||
|
||
function requestPermission() { |
||
Notification.requestPermission(); |
||
$($window).off('click', requestPermission); |
||
} |
||
|
||
function notify (data) { |
||
// console.log('notify', $rootScope.idle.isIDLE, notificationsUiSupport); |
||
if (!$rootScope.idle.isIDLE) { |
||
return false; |
||
} |
||
|
||
notificationsCount++; |
||
|
||
if (!notificationsUiSupport || |
||
Notification.permission !== 'granted') { |
||
return false; |
||
} |
||
|
||
AppConfigManager.get('notify_nosound').then(function (noSound) { |
||
if (!noSound) { |
||
playSound(); |
||
} |
||
}) |
||
|
||
AppConfigManager.get('notify_nodesktop').then(function (noShow) { |
||
if (noShow) { |
||
return; |
||
} |
||
var idx = ++notificationIndex, |
||
key = data.key || 'k' + idx; |
||
|
||
var notification = new Notification(data.title, { |
||
icon: data.image || '', |
||
body: data.message || '' |
||
}); |
||
|
||
notification.onclick = function () { |
||
notification.close(); |
||
if (window.chrome && chrome.app && chrome.app.window) { |
||
chrome.app.window.current().focus(); |
||
} |
||
window.focus(); |
||
notificationsClear(); |
||
if (data.onclick) { |
||
data.onclick(); |
||
} |
||
}; |
||
|
||
notification.onclose = function () { |
||
delete notificationsShown[key]; |
||
// lastClosed.push(tsNow()); |
||
notificationsClear(); |
||
}; |
||
|
||
notificationsShown[key] = notification; |
||
}); |
||
}; |
||
|
||
function playSound () { |
||
var filename = 'img/sound_a.wav'; |
||
$('#notify_sound').html('<audio autoplay="autoplay"><source src="' + filename + '" type="audio/mpeg" /><embed hidden="true" autostart="true" loop="false" src="' + filename +'" /></audio>'); |
||
} |
||
|
||
function notificationCancel (key) { |
||
var notification = notificationsShown[key]; |
||
if (notification) { |
||
try { |
||
if (notification.close) { |
||
notification.close(); |
||
} |
||
} catch (e) {} |
||
} |
||
} |
||
|
||
function notificationsClear() { |
||
angular.forEach(notificationsShown, function (notification) { |
||
try { |
||
if (notification.close) { |
||
notification.close() |
||
} |
||
} catch (e) {} |
||
}); |
||
notificationsShown = {}; |
||
} |
||
}) |
||
|
||
|
||
.service('ErrorService', function ($rootScope, $modal) { |
||
|
||
function showError (templateUrl, params, options) { |
||
var scope = $rootScope.$new(); |
||
angular.extend(scope, params); |
||
|
||
return $modal.open({ |
||
templateUrl: templateUrl, |
||
// controller: 'ErrorModalController', |
||
scope: scope, |
||
windowClass: options.windowClass || '' |
||
}); |
||
} |
||
|
||
function showSimpleError (title, description) { |
||
return showError ('partials/error_modal.html', { |
||
title: title, |
||
description: description |
||
}, { |
||
windowClass: 'error_modal_window' |
||
}); |
||
}; |
||
|
||
return { |
||
showError: showError, |
||
showSimpleError: showSimpleError |
||
} |
||
}) |
||
|
||
|
||
|
||
.service('PeersSelectService', function ($rootScope, $modal) { |
||
|
||
function selectPeer () { |
||
var scope = $rootScope.$new(); |
||
// angular.extend(scope, params); |
||
|
||
return $modal.open({ |
||
templateUrl: 'partials/peer_select.html', |
||
controller: 'PeerSelectController', |
||
scope: scope, |
||
windowClass: 'peer_select_window' |
||
}).result; |
||
} |
||
|
||
|
||
return { |
||
selectPeer: selectPeer |
||
} |
||
}) |
||
|
||
|
||
.service('ContactsSelectService', function ($rootScope, $modal) { |
||
|
||
function select (multiSelect, options) { |
||
options = options || {}; |
||
|
||
var scope = $rootScope.$new(); |
||
scope.multiSelect = multiSelect; |
||
angular.extend(scope, options); |
||
|
||
return $modal.open({ |
||
templateUrl: 'partials/contacts_modal.html', |
||
controller: 'ContactsModalController', |
||
scope: scope, |
||
windowClass: 'contacts_modal_window' |
||
}).result; |
||
} |
||
|
||
|
||
return { |
||
selectContacts: function (options) { |
||
return select (true, options); |
||
}, |
||
selectContact: function (options) { |
||
return select (false, options); |
||
}, |
||
} |
||
}) |
||
|
||
/*! |
||
* Webogram v0.0.20 - messaging web application for MTProto |
||
* https://github.com/zhukov/webogram |
||
* Copyright (C) 2014 Igor Zhukov <[email protected]> |
||
* https://github.com/zhukov/webogram/blob/master/LICENSE |
||
*/ |
||
|
||
'use strict'; |
||
|
||
/* Controllers */ |
||
|
||
angular.module('myApp.controllers', []) |
||
|
||
.controller('AppWelcomeController', function($scope, $location, MtpApiManager) { |
||
MtpApiManager.getUserID().then(function (id) { |
||
if (id) { |
||
$location.url('/im'); |
||
} else { |
||
$scope.showWelcome = true; |
||
} |
||
}); |
||
}) |
||
|
||
.controller('AppLoginController', function ($scope, $location, $timeout, MtpApiManager, ErrorService) { |
||
MtpApiManager.getUserID().then(function (id) { |
||
if (id) { |
||
$location.url('/im'); |
||
return; |
||
} |
||
}); |
||
var options = {dcID: 1}; |
||
|
||
$scope.credentials = {}; |
||
$scope.progress = {}; |
||
$scope.callPending = {}; |
||
|
||
var callTimeout; |
||
|
||
function saveAuth (result) { |
||
MtpApiManager.setUserAuth(options.dcID, { |
||
expires: result.expires, |
||
id: result.user.id |
||
}); |
||
$timeout.cancel(callTimeout); |
||
|
||
$location.url('/im'); |
||
}; |
||
|
||
function callCheck () { |
||
$timeout.cancel(callTimeout); |
||
if (!(--$scope.callPending.remaining)) { |
||
$scope.callPending.success = false; |
||
MtpApiManager.invokeApi('auth.sendCall', { |
||
phone_number: $scope.credentials.phone_number, |
||
phone_code_hash: $scope.credentials.phone_code_hash |
||
}, options).then(function () { |
||
$scope.callPending.success = true; |
||
}); |
||
} else { |
||
callTimeout = $timeout(callCheck, 1000); |
||
} |
||
} |
||
|
||
$scope.sendCode = function () { |
||
$timeout.cancel(callTimeout); |
||
$scope.progress.enabled = true; |
||
MtpApiManager.invokeApi('auth.checkPhone', { |
||
phone_number: $scope.credentials.phone_number |
||
}, options).then(function (result) { |
||
$scope.progress.enabled = false; |
||
if (!result.phone_registered) { |
||
ErrorService.showSimpleError('No account', 'Sorry, there is no Telegram account for ' + $scope.credentials.phone_number + '. Please sign up using our mobile apps.'); |
||
return false; |
||
} |
||
|
||
$scope.progress.enabled = true; |
||
MtpApiManager.invokeApi('auth.sendCode', { |
||
phone_number: $scope.credentials.phone_number, |
||
sms_type: 0, |
||
api_id: 2496, |
||
api_hash: '8da85b0d5bfe62527e5b244c209159c3' |
||
}, options).then(function (sentCode) { |
||
$scope.progress.enabled = false; |
||
|
||
$scope.credentials.phone_code_hash = sentCode.phone_code_hash; |
||
$scope.credentials.phone_occupied = sentCode.phone_registered; |
||
$scope.error = {}; |
||
|
||
$scope.callPending.remaining = 60; |
||
callCheck(); |
||
|
||
}, function (error) { |
||
$scope.progress.enabled = false; |
||
console.log('sendCode error', error); |
||
switch (error.type) { |
||
case 'PHONE_NUMBER_INVALID': |
||
$scope.error = {field: 'phone'}; |
||
break; |
||
} |
||
}); |
||
}, function (error) { |
||
$scope.progress.enabled = false; |
||
switch (error.type) { |
||
case 'PHONE_NUMBER_INVALID': |
||
$scope.error = {field: 'phone'}; |
||
break; |
||
|
||
default: |
||
ErrorService.showSimpleError('Unknown error occured', 'Please check your internet connection or install the latest version of Google Chrome browser.'); |
||
} |
||
}); |
||
} |
||
|
||
$scope.logIn = function (forceSignUp) { |
||
var method = 'auth.signIn', params = { |
||
phone_number: $scope.credentials.phone_number, |
||
phone_code_hash: $scope.credentials.phone_code_hash, |
||
phone_code: $scope.credentials.phone_code |
||
}; |
||
if (forceSignUp) { |
||
method = 'auth.signUp'; |
||
angular.extend(params, { |
||
first_name: $scope.credentials.first_name, |
||
last_name: $scope.credentials.last_name |
||
}); |
||
} |
||
|
||
$scope.progress.enabled = true; |
||
MtpApiManager.invokeApi(method, params, options).then(saveAuth, function (error) { |
||
$scope.progress.enabled = false; |
||
if (error.code == 400 && error.type == 'PHONE_NUMBER_UNOCCUPIED') { |
||
return $scope.logIn(true); |
||
} else if (error.code == 400 && error.type == 'PHONE_NUMBER_OCCUPIED') { |
||
return $scope.logIn(false); |
||
} |
||
|
||
|
||
switch (error.type) { |
||
case 'FIRSTNAME_INVALID': |
||
$scope.error = {field: 'first_name'}; |
||
break; |
||
case 'LASTNAME_INVALID': |
||
$scope.error = {field: 'last_name'}; |
||
break; |
||
case 'PHONE_CODE_INVALID': |
||
$scope.error = {field: 'phone_code'}; |
||
break; |
||
} |
||
}); |
||
|
||
}; |
||
}) |
||
|
||
.controller('AppIMController', function ($scope, $location, $routeParams, $modal, $rootScope, $modalStack, MtpApiManager, AppUsersManager, ContactsSelectService) { |
||
|
||
$scope.$on('$routeUpdate', updateCurDialog); |
||
|
||
$scope.$on('history_focus', function (e, peerData) { |
||
$modalStack.dismissAll(); |
||
if (peerData.peerString == $scope.curDialog.peer) { |
||
$scope.$broadcast('ui_history_focus'); |
||
} else { |
||
$location.url('/im?p=' + peerData.peerString); |
||
} |
||
}); |
||
|
||
|
||
$scope.isLoggedIn = true; |
||
$scope.openSettings = function () { |
||
$modal.open({ |
||
templateUrl: 'partials/settings_modal.html', |
||
controller: 'SettingsModalController', |
||
scope: $rootScope.$new(), |
||
windowClass: 'settings_modal_window' |
||
}); |
||
} |
||
|
||
$scope.openContacts = function () { |
||
ContactsSelectService.selectContact().then(function (userID) { |
||
$scope.dialogSelect(AppUsersManager.getUserString(userID)); |
||
}); |
||
} |
||
|
||
$scope.openGroup = function () { |
||
ContactsSelectService.selectContacts().then(function (userIDs) { |
||
|
||
if (userIDs.length == 1) { |
||
$scope.dialogSelect(AppUsersManager.getUserString(userIDs[0])); |
||
} else if (userIDs.length > 1) { |
||
var scope = $rootScope.$new(); |
||
scope.userIDs = userIDs; |
||
|
||
$modal.open({ |
||
templateUrl: 'partials/chat_create_modal.html', |
||
controller: 'ChatCreateModalController', |
||
scope: scope, |
||
windowClass: 'contacts_modal_window' |
||
}); |
||
} |
||
|
||
}); |
||
} |
||
|
||
$scope.dialogSelect = function (peerString) { |
||
$rootScope.$broadcast('history_focus', {peerString: peerString}); |
||
}; |
||
|
||
updateCurDialog(); |
||
|
||
function updateCurDialog() { |
||
$scope.curDialog = { |
||
peer: $routeParams.p || false |
||
}; |
||
} |
||
}) |
||
|
||
.controller('AppImDialogsController', function ($scope, $location, MtpApiManager, AppUsersManager, AppChatsManager, AppMessagesManager, AppPeersManager) { |
||
|
||
// console.log('init controller'); |
||
|
||
$scope.dialogs = []; |
||
$scope.search = {}; |
||
|
||
var offset = 0, |
||
maxID = 0, |
||
hasMore = false; |
||
|
||
MtpApiManager.invokeApi('account.updateStatus', {offline: false}); |
||
$scope.$on('dialogs_need_more', function () { |
||
// console.log('on need more'); |
||
showMoreDialogs(); |
||
}); |
||
|
||
$scope.$on('dialog_unread', function (e, dialog) { |
||
angular.forEach($scope.dialogs, function(curDialog) { |
||
if (curDialog.peerID == dialog.peerID) { |
||
curDialog.unreadCount = dialog.count; |
||
} |
||
}); |
||
}); |
||
|
||
$scope.$on('dialogs_update', function (e, dialog) { |
||
if ($scope.search.query !== undefined && $scope.search.query.length) { |
||
return false; |
||
} |
||
|
||
var pos = false; |
||
angular.forEach($scope.dialogs, function(curDialog, curPos) { |
||
if (curDialog.peerID == dialog.peerID) { |
||
pos = curPos; |
||
} |
||
}); |
||
|
||
var wrappedDialog = AppMessagesManager.wrapForDialog(dialog.top_message, dialog.unread_count); |
||
if (pos !== false) { |
||
var prev = $scope.dialogs.splice(pos, 1); |
||
safeReplaceObject(prev, wrappedDialog); |
||
offset++; |
||
} |
||
$scope.dialogs.unshift(wrappedDialog); |
||
}); |
||
|
||
$scope.$on('dialog_flush', function (e, dialog) { |
||
for (var i = 0; i < $scope.dialogs.length; i++) { |
||
if ($scope.dialogs[i].peerID == dialog.peerID) { |
||
$scope.dialogs.splice(i, 1); |
||
break; |
||
} |
||
} |
||
}); |
||
|
||
$scope.$watch('search.query', loadDialogs); |
||
|
||
function loadDialogs () { |
||
offset = 0; |
||
maxID = 0; |
||
hasMore = false; |
||
|
||
AppMessagesManager.getDialogs($scope.search.query, maxID).then(function (dialogsResult) { |
||
$scope.dialogs = []; |
||
|
||
if (dialogsResult.dialogs.length) { |
||
offset += dialogsResult.dialogs.length; |
||
|
||
maxID = dialogsResult.dialogs[dialogsResult.dialogs.length - 1].top_message; |
||
hasMore = dialogsResult.count === null || offset < dialogsResult.count; |
||
|
||
angular.forEach(dialogsResult.dialogs, function (dialog) { |
||
$scope.dialogs.push(AppMessagesManager.wrapForDialog(dialog.top_message, dialog.unread_count)); |
||
}); |
||
} |
||
|
||
$scope.$broadcast('ui_dialogs_change'); |
||
|
||
if (!$scope.search.query) { |
||
AppMessagesManager.getDialogs('', maxID); |
||
} |
||
|
||
}, function (error) { |
||
if (error.code == 401) { |
||
MtpApiManager.logOut()['finally'](function () { |
||
$location.url('/login'); |
||
}); |
||
} |
||
}); |
||
} |
||
|
||
function showMoreDialogs () { |
||
if (!hasMore || !offset) { |
||
return; |
||
} |
||
|
||
AppMessagesManager.getDialogs($scope.search.query, maxID).then(function (dialogsResult) { |
||
offset += dialogsResult.dialogs.length; |
||
maxID = dialogsResult.dialogs[dialogsResult.dialogs.length - 1].top_message; |
||
hasMore = dialogsResult.count === null || offset < dialogsResult.count; |
||
|
||
angular.forEach(dialogsResult.dialogs, function (dialog) { |
||
$scope.dialogs.push(AppMessagesManager.wrapForDialog(dialog.top_message, dialog.unread_count)); |
||
}); |
||
|
||
$scope.$broadcast('ui_dialogs_append'); |
||
}); |
||
}; |
||
|
||
}) |
||
|
||
.controller('AppImHistoryController', function ($scope, $location, $timeout, $rootScope, MtpApiManager, AppUsersManager, AppChatsManager, AppMessagesManager, AppPeersManager, ApiUpdatesManager, PeersSelectService, IdleManager, StatusManager) { |
||
|
||
$scope.$watch('curDialog.peer', applyDialogSelect); |
||
|
||
ApiUpdatesManager.attach(); |
||
|
||
IdleManager.start(); |
||
StatusManager.start(); |
||
|
||
$scope.history = []; |
||
$scope.historyEmpty = false; |
||
$scope.mediaType = false; |
||
$scope.selectedMsgs = {}; |
||
$scope.selectedCount = 0; |
||
$scope.selectActions = false; |
||
$scope.missedCount = 0; |
||
$scope.typing = {}; |
||
$scope.state = {}; |
||
|
||
$scope.toggleMessage = toggleMessage; |
||
$scope.selectedDelete = selectedDelete; |
||
$scope.selectedForward = selectedForward; |
||
$scope.selectedCancel = selectedCancel; |
||
$scope.selectedFlush = selectedFlush; |
||
$scope.toggleEdit = toggleEdit; |
||
$scope.toggleMedia = toggleMedia; |
||
$scope.showPeerInfo = showPeerInfo; |
||
|
||
var peerID, |
||
offset = 0, |
||
hasMore = false, |
||
maxID = 0, |
||
inputMediaFilters = { |
||
photos: 'inputMessagesFilterPhotos', |
||
video: 'inputMessagesFilterVideo', |
||
documents: 'inputMessagesFilterDocument', |
||
}, |
||
jump = 0; |
||
|
||
function applyDialogSelect (newPeer) { |
||
selectedCancel(); |
||
newPeer = newPeer || $scope.curDialog.peer || ''; |
||
|
||
peerID = AppPeersManager.getPeerID(newPeer); |
||
|
||
$scope.curDialog.peerID = peerID; |
||
$scope.curDialog.inputPeer = AppPeersManager.getInputPeer(newPeer); |
||
$scope.mediaType = false; |
||
|
||
if (peerID) { |
||
updateHistoryPeer(true); |
||
loadHistory(); |
||
} else { |
||
showEmptyHistory(); |
||
} |
||
} |
||
|
||
function updateHistoryPeer(preload) { |
||
var peerData = AppPeersManager.getPeer(peerID); |
||
// console.log('update', preload, peerData); |
||
if (!peerData || peerData.deleted) { |
||
return false; |
||
} |
||
|
||
$scope.history = []; |
||
|
||
$scope.historyPeer = { |
||
id: peerID, |
||
data: peerData, |
||
photo: AppPeersManager.getPeerPhoto(peerID, 'User', 'Group') |
||
}; |
||
|
||
MtpApiManager.getUserID().then(function (id) { |
||
$scope.ownPhoto = AppUsersManager.getUserPhoto(id, 'User'); |
||
}); |
||
|
||
if (preload) { |
||
$scope.typing = {}; |
||
$scope.$broadcast('ui_peer_change'); |
||
$scope.$broadcast('ui_history_change'); |
||
safeReplaceObject($scope.state, {loaded: true}); |
||
} |
||
} |
||
|
||
function showMoreHistory () { |
||
if (!hasMore || !offset) { |
||
return; |
||
} |
||
console.trace('load history'); |
||
|
||
var inputMediaFilter = $scope.mediaType && {_: inputMediaFilters[$scope.mediaType]}, |
||
getMessagesPromise = inputMediaFilter |
||
? AppMessagesManager.getSearch($scope.curDialog.inputPeer, '', inputMediaFilter, maxID) |
||
: AppMessagesManager.getHistory($scope.curDialog.inputPeer, maxID); |
||
|
||
getMessagesPromise.then(function (historyResult) { |
||
offset += historyResult.history.length; |
||
hasMore = historyResult.count === null || offset < historyResult.count; |
||
maxID = historyResult.history[historyResult.history.length - 1]; |
||
|
||
angular.forEach(historyResult.history, function (id) { |
||
$scope.history.unshift(AppMessagesManager.wrapForHistory(id)); |
||
}); |
||
|
||
$scope.$broadcast('ui_history_prepend'); |
||
}, function () { |
||
safeReplaceObject($scope.state, {error: true}); |
||
}); |
||
} |
||
|
||
function loadHistory () { |
||
hasMore = false; |
||
offset = 0; |
||
maxID = 0; |
||
|
||
var curJump = ++jump, |
||
inputMediaFilter = $scope.mediaType && {_: inputMediaFilters[$scope.mediaType]}, |
||
getMessagesPromise = inputMediaFilter |
||
? AppMessagesManager.getSearch($scope.curDialog.inputPeer, '', inputMediaFilter, maxID) |
||
: AppMessagesManager.getHistory($scope.curDialog.inputPeer, maxID); |
||
|
||
$scope.historyEmpty = false; |
||
|
||
getMessagesPromise.then(function (historyResult) { |
||
if (curJump != jump) return; |
||
|
||
offset += historyResult.history.length; |
||
$scope.historyEmpty = !historyResult.count; |
||
|
||
hasMore = historyResult.count === null || offset < historyResult.count; |
||
maxID = historyResult.history[historyResult.history.length - 1]; |
||
|
||
updateHistoryPeer(); |
||
angular.forEach(historyResult.history, function (id) { |
||
$scope.history.push(AppMessagesManager.wrapForHistory(id)); |
||
}); |
||
$scope.history.reverse(); |
||
|
||
if (historyResult.unreadLimit) { |
||
$scope.historyUnread = { |
||
beforeID: historyResult.history[historyResult.unreadLimit - 1], |
||
count: historyResult.unreadLimit |
||
}; |
||
} else { |
||
$scope.historyUnread = {}; |
||
} |
||
|
||
safeReplaceObject($scope.state, {loaded: true}); |
||
|
||
$scope.$broadcast('ui_history_change'); |
||
|
||
AppMessagesManager.readHistory($scope.curDialog.inputPeer); |
||
|
||
}, function () { |
||
safeReplaceObject($scope.state, {error: true}); |
||
}); |
||
} |
||
|
||
function showEmptyHistory () { |
||
safeReplaceObject($scope.state, {notSelected: true}); |
||
$scope.history = []; |
||
|
||
$scope.$broadcast('ui_history_change'); |
||
} |
||
|
||
function toggleMessage (messageID, target) { |
||
if (!$scope.selectActions && !$(target).hasClass('icon-select-tick') && !$(target).hasClass('im_content_message_select_area')) { |
||
return false; |
||
} |
||
if ($scope.selectedMsgs[messageID]) { |
||
delete $scope.selectedMsgs[messageID]; |
||
$scope.selectedCount--; |
||
if (!$scope.selectedCount) { |
||
$scope.selectActions = false; |
||
$scope.$broadcast('ui_panel_update'); |
||
} |
||
} else { |
||
$scope.selectedMsgs[messageID] = true; |
||
$scope.selectedCount++; |
||
if (!$scope.selectActions) { |
||
$scope.selectActions = true; |
||
$scope.$broadcast('ui_panel_update'); |
||
} |
||
} |
||
} |
||
|
||
function selectedCancel () { |
||
$scope.selectedMsgs = {}; |
||
$scope.selectedCount = 0; |
||
$scope.selectActions = false; |
||
$scope.$broadcast('ui_panel_update'); |
||
} |
||
|
||
function selectedFlush () { |
||
if (safeConfirm('Are you sure? This can not be undone!') !== true) { |
||
return false; |
||
} |
||
AppMessagesManager.flushHistory($scope.curDialog.inputPeer).then(function () { |
||
selectedCancel(); |
||
}); |
||
}; |
||
|
||
function selectedDelete () { |
||
if ($scope.selectedCount > 0) { |
||
var selectedMessageIDs = []; |
||
angular.forEach($scope.selectedMsgs, function (t, messageID) { |
||
selectedMessageIDs.push(messageID); |
||
}); |
||
AppMessagesManager.deleteMessages(selectedMessageIDs).then(function () { |
||
selectedCancel(); |
||
}); |
||
} |
||
} |
||
|
||
|
||
function selectedForward () { |
||
if ($scope.selectedCount > 0) { |
||
var selectedMessageIDs = []; |
||
angular.forEach($scope.selectedMsgs, function (t, messageID) { |
||
selectedMessageIDs.push(messageID); |
||
}); |
||
|
||
PeersSelectService.selectPeer().then(function (peerString) { |
||
var inputPeer = AppPeersManager.getInputPeer(peerString); |
||
AppMessagesManager.forwardMessages(selectedMessageIDs, inputPeer).then(function () { |
||
selectedCancel(); |
||
$rootScope.$broadcast('history_focus', {peerString: peerString}); |
||
}); |
||
}); |
||
|
||
} |
||
} |
||
|
||
function toggleEdit () { |
||
if ($scope.selectActions) { |
||
selectedCancel(); |
||
} else { |
||
$scope.selectActions = true; |
||
$scope.$broadcast('ui_panel_update'); |
||
} |
||
} |
||
|
||
function toggleMedia (mediaType) { |
||
if (mediaType) { |
||
$scope.missedCount = 0; |
||
} |
||
$scope.mediaType = mediaType || false; |
||
$scope.history = []; |
||
loadHistory(); |
||
} |
||
|
||
function showPeerInfo () { |
||
if ($scope.curDialog.peerID > 0) { |
||
$rootScope.openUser($scope.curDialog.peerID) |
||
} else if ($scope.curDialog.peerID < 0) { |
||
$rootScope.openChat(-$scope.curDialog.peerID) |
||
} |
||
} |
||
|
||
|
||
var typingTimeouts = {}; |
||
|
||
$scope.$on('history_update', angular.noop); |
||
|
||
$scope.$on('history_append', function (e, addedMessage) { |
||
if (addedMessage.peerID == $scope.curDialog.peerID) { |
||
if ($scope.mediaType) { |
||
$scope.missedCount++; |
||
return; |
||
} |
||
// console.log('append', addedMessage); |
||
// console.trace(); |
||
$scope.history.push(AppMessagesManager.wrapForHistory(addedMessage.messageID)); |
||
$scope.typing = {}; |
||
$scope.$broadcast('ui_history_append', {my: addedMessage.my}); |
||
if (addedMessage.my) { |
||
$scope.historyUnread = {}; |
||
} |
||
|
||
offset++; |
||
|
||
// console.log('append check', $rootScope.idle.isIDLE, addedMessage.peerID, $scope.curDialog.peerID); |
||
if (!$rootScope.idle.isIDLE) { |
||
$timeout(function () { |
||
AppMessagesManager.readHistory($scope.curDialog.inputPeer); |
||
}); |
||
} |
||
} |
||
}); |
||
|
||
$scope.$on('history_delete', function (e, historyUpdate) { |
||
if (historyUpdate.peerID == $scope.curDialog.peerID) { |
||
var newHistory = []; |
||
|
||
for (var i = 0; i < $scope.history.length; i++) { |
||
if (!historyUpdate.msgs[$scope.history[i].id]) { |
||
newHistory.push($scope.history[i]); |
||
} |
||
}; |
||
$scope.history = newHistory; |
||
} |
||
}) |
||
|
||
$scope.$on('dialog_flush', function (e, dialog) { |
||
if (dialog.peerID == $scope.curDialog.peerID) { |
||
$scope.history = []; |
||
} |
||
}); |
||
|
||
$scope.$on('apiUpdate', function (e, update) { |
||
// console.log('on apiUpdate inline', update); |
||
switch (update._) { |
||
case 'updateUserTyping': |
||
if (update.user_id == $scope.curDialog.peerID && AppUsersManager.hasUser(update.user_id)) { |
||
$scope.typing = {user: AppUsersManager.getUser(update.user_id)}; |
||
|
||
$timeout.cancel(typingTimeouts[update.user_id]); |
||
|
||
typingTimeouts[update.user_id] = $timeout(function () { |
||
$scope.typing = {}; |
||
}, 6000); |
||
} |
||
break; |
||
|
||
case 'updateChatUserTyping': |
||
if (-update.chat_id == $scope.curDialog.peerID && AppUsersManager.hasUser(update.user_id)) { |
||
$scope.typing = {user: AppUsersManager.getUser(update.user_id)}; |
||
|
||
$timeout.cancel(typingTimeouts[update.user_id]); |
||
|
||
typingTimeouts[update.user_id] = $timeout(function () { |
||
$scope.typing = {}; |
||
}, 6000); |
||
} |
||
break; |
||
} |
||
}); |
||
|
||
$scope.$on('history_need_more', function () { |
||
showMoreHistory(); |
||
}); |
||
|
||
$rootScope.$watch('idle.isIDLE', function (newVal) { |
||
if (!newVal && $scope.curDialog && $scope.curDialog.peerID) { |
||
AppMessagesManager.readHistory($scope.curDialog.inputPeer); |
||
} |
||
}); |
||
|
||
}) |
||
|
||
.controller('AppImPanelController', function($scope) { |
||
$scope.$on('user_update', angular.noop); |
||
}) |
||
|
||
.controller('AppImSendController', function ($scope, $timeout, MtpApiManager, AppConfigManager, AppPeersManager, AppMessagesManager, ApiUpdatesManager, MtpApiFileManager) { |
||
|
||
$scope.$watch('curDialog.peer', resetDraft); |
||
$scope.$on('user_update', angular.noop); |
||
$scope.$on('ui_typing', onTyping); |
||
|
||
$scope.draftMessage = {text: ''}; |
||
$scope.$watch('draftMessage.text', onMessageChange); |
||
$scope.$watch('draftMessage.files', onFilesSelected); |
||
|
||
|
||
$scope.sendMessage = sendMessage; |
||
|
||
function sendMessage (e) { |
||
$scope.$broadcast('ui_message_before_send'); |
||
|
||
$timeout(function () { |
||
var text = $scope.draftMessage.text; |
||
|
||
if (!angular.isString(text) || !text.length) { |
||
return false; |
||
} |
||
|
||
text = text.replace(/:([a-z0-9\-\+\*_]+?):/gi, function (all, name) { |
||
var utfChar = $.emojiarea.reverseIcons[name]; |
||
if (utfChar !== undefined) { |
||
return utfChar; |
||
} |
||
return all; |
||
}); |
||
|
||
do { |
||
AppMessagesManager.sendText($scope.curDialog.peerID, text.substr(0, 4096)); |
||
text = text.substr(4096); |
||
} while (text.length); |
||
|
||
resetDraft(); |
||
$scope.$broadcast('ui_message_send'); |
||
}); |
||
|
||
return cancelEvent(e); |
||
} |
||
|
||
|
||
function resetDraft (newPeer) { |
||
if (newPeer) { |
||
AppConfigManager.get('draft' + $scope.curDialog.peerID).then(function (draftText) { |
||
// console.log('Restore draft', 'draft' + $scope.curDialog.peerID, draftText); |
||
$scope.draftMessage.text = draftText || ''; |
||
// console.log('send broadcast', $scope.draftMessage); |
||
$scope.$broadcast('ui_peer_draft'); |
||
}); |
||
} else { |
||
// console.log('Reset peer'); |
||
$scope.draftMessage.text = ''; |
||
$scope.$broadcast('ui_peer_draft'); |
||
} |
||
} |
||
|
||
function onMessageChange(newVal) { |
||
// console.log('ctrl text changed', newVal); |
||
// console.trace('ctrl text changed', newVal); |
||
AppMessagesManager.readHistory($scope.curDialog.inputPeer); |
||
|
||
if (newVal && newVal.length) { |
||
var backupDraftObj = {}; |
||
backupDraftObj['draft' + $scope.curDialog.peerID] = newVal; |
||
AppConfigManager.set(backupDraftObj); |
||
// console.log('draft save', backupDraftObj); |
||
} else { |
||
AppConfigManager.remove('draft' + $scope.curDialog.peerID); |
||
// console.log('draft delete', 'draft' + $scope.curDialog.peerID); |
||
} |
||
} |
||
|
||
function onTyping () { |
||
MtpApiManager.invokeApi('messages.setTyping', { |
||
peer: $scope.curDialog.inputPeer, |
||
typing: true |
||
}); |
||
} |
||
|
||
function onFilesSelected (newVal) { |
||
if (!angular.isArray(newVal) || !newVal.length) { |
||
return; |
||
} |
||
|
||
for (var i = 0; i < newVal.length; i++) { |
||
AppMessagesManager.sendFile($scope.curDialog.peerID, newVal[i], { |
||
isMedia: $scope.draftMessage.isMedia |
||
}); |
||
$scope.$broadcast('ui_message_send'); |
||
} |
||
} |
||
|
||
}) |
||
|
||
.controller('PhotoModalController', function ($scope, AppPhotosManager) { |
||
$scope.photo = AppPhotosManager.wrapForFull($scope.photoID); |
||
}) |
||
|
||
.controller('VideoModalController', function ($scope, AppVideoManager) { |
||
$scope.video = AppVideoManager.wrapForFull($scope.videoID); |
||
}) |
||
|
||
.controller('UserModalController', function ($scope, $location, $rootScope, $modalStack, AppUsersManager, NotificationsManager, AppMessagesManager, AppPeersManager) { |
||
$scope.user = AppUsersManager.wrapForFull($scope.userID); |
||
|
||
$scope.settings = {notifications: true}; |
||
|
||
NotificationsManager.getPeerMuted($scope.userID).then(function (muted) { |
||
$scope.settings.notifications = !muted; |
||
|
||
$scope.$watch('settings.notifications', function(newValue, oldValue) { |
||
if (newValue === oldValue) { |
||
return false; |
||
} |
||
NotificationsManager.getPeerSettings($scope.userID).then(function (settings) { |
||
if (newValue) { |
||
settings.mute_until = 0; |
||
} else { |
||
settings.mute_until = 2000000000; |
||
} |
||
NotificationsManager.savePeerSettings($scope.userID, settings); |
||
}); |
||
}); |
||
}); |
||
|
||
|
||
$scope.goToHistory = function () { |
||
$rootScope.$broadcast('history_focus', {peerString: $scope.user.peerString}); |
||
}; |
||
|
||
$scope.flushHistory = function () { |
||
if (safeConfirm('Are you sure? This can not be undone!') !== true) { |
||
return false; |
||
} |
||
AppMessagesManager.flushHistory(AppPeersManager.getInputPeerByID($scope.userID)).then(function () { |
||
$scope.goToHistory(); |
||
}); |
||
}; |
||
}) |
||
|
||
.controller('ChatModalController', function ($scope, $timeout, $rootScope, $modal, AppUsersManager, AppChatsManager, MtpApiManager, MtpApiFileManager, NotificationsManager, AppMessagesManager, AppPeersManager, ApiUpdatesManager, ContactsSelectService, ErrorService) { |
||
|
||
$scope.chatFull = AppChatsManager.wrapForFull($scope.chatID, {}); |
||
|
||
MtpApiManager.invokeApi('messages.getFullChat', { |
||
chat_id: $scope.chatID |
||
}).then(function (result) { |
||
AppChatsManager.saveApiChats(result.chats); |
||
AppUsersManager.saveApiUsers(result.users); |
||
|
||
$scope.chatFull = AppChatsManager.wrapForFull($scope.chatID, result.full_chat); |
||
}); |
||
|
||
$scope.settings = {notifications: true}; |
||
|
||
NotificationsManager.getPeerMuted(-$scope.chatID).then(function (muted) { |
||
$scope.settings.notifications = !muted; |
||
|
||
$scope.$watch('settings.notifications', function(newValue, oldValue) { |
||
if (newValue === oldValue) { |
||
return false; |
||
} |
||
NotificationsManager.getPeerSettings(-$scope.chatID).then(function (settings) { |
||
if (newValue) { |
||
settings.mute_until = 0; |
||
} else { |
||
settings.mute_until = 2000000000; |
||
} |
||
NotificationsManager.savePeerSettings(-$scope.chatID, settings); |
||
}); |
||
}); |
||
}); |
||
|
||
function onStatedMessage (statedMessage) { |
||
AppUsersManager.saveApiUsers(statedMessage.users); |
||
AppChatsManager.saveApiChats(statedMessage.chats); |
||
|
||
if (ApiUpdatesManager.saveSeq(statedMessage.seq)) { |
||
ApiUpdatesManager.saveUpdate({ |
||
_: 'updateNewMessage', |
||
message: statedMessage.message, |
||
pts: statedMessage.pts |
||
}); |
||
} |
||
|
||
$rootScope.$broadcast('history_focus', {peerString: $scope.chatFull.peerString}); |
||
} |
||
|
||
|
||
$scope.leaveGroup = function () { |
||
MtpApiManager.invokeApi('messages.deleteChatUser', { |
||
chat_id: $scope.chatID, |
||
user_id: {_: 'inputUserSelf'} |
||
}).then(onStatedMessage); |
||
}; |
||
|
||
$scope.returnToGroup = function () { |
||
MtpApiManager.invokeApi('messages.addChatUser', { |
||
chat_id: $scope.chatID, |
||
user_id: {_: 'inputUserSelf'} |
||
}).then(onStatedMessage); |
||
}; |
||
|
||
|
||
$scope.inviteToGroup = function () { |
||
var disabled = []; |
||
angular.forEach($scope.chatFull.participants.participants, function(participant){ |
||
disabled.push(participant.user_id); |
||
}); |
||
|
||
ContactsSelectService.selectContacts({disabled: disabled}).then(function (userIDs) { |
||
angular.forEach(userIDs, function (userID) { |
||
MtpApiManager.invokeApi('messages.addChatUser', { |
||
chat_id: $scope.chatID, |
||
user_id: {_: 'inputUserContact', user_id: userID}, |
||
fwd_limit: 100 |
||
}).then(function (addResult) { |
||
AppUsersManager.saveApiUsers(addResult.users); |
||
AppChatsManager.saveApiChats(addResult.chats); |
||
|
||
if (ApiUpdatesManager.saveSeq(addResult.seq)) { |
||
ApiUpdatesManager.saveUpdate({ |
||
_: 'updateNewMessage', |
||
message: addResult.message, |
||
pts: addResult.pts |
||
}); |
||
} |
||
}); |
||
}); |
||
|
||
$rootScope.$broadcast('history_focus', {peerString: $scope.chatFull.peerString}); |
||
}); |
||
}; |
||
|
||
$scope.kickFromGroup = function (userID) { |
||
var user = AppUsersManager.getUser(userID); |
||
|
||
console.log({_: 'inputUserForeign', user_id: userID, access_hash: user.access_hash || '0'}, user); |
||
|
||
MtpApiManager.invokeApi('messages.deleteChatUser', { |
||
chat_id: $scope.chatID, |
||
user_id: {_: 'inputUserForeign', user_id: userID, access_hash: user.access_hash || '0'} |
||
}).then(onStatedMessage); |
||
}; |
||
|
||
|
||
|
||
$scope.flushHistory = function () { |
||
if (safeConfirm('Are you sure? This can not be undone!') !== true) { |
||
return; |
||
} |
||
AppMessagesManager.flushHistory(AppPeersManager.getInputPeerByID(-$scope.chatID)).then(function () { |
||
$rootScope.$broadcast('history_focus', {peerString: $scope.chatFull.peerString}); |
||
}); |
||
|
||
}; |
||
|
||
|
||
$scope.photo = {}; |
||
|
||
$scope.$watch('photo.file', onPhotoSelected); |
||
|
||
function onPhotoSelected (photo) { |
||
if (!photo || !photo.type || photo.type.indexOf('image') !== 0) { |
||
return; |
||
} |
||
$scope.photo.updating = true; |
||
MtpApiFileManager.uploadFile(photo).then(function (inputFile) { |
||
return MtpApiManager.invokeApi('messages.editChatPhoto', { |
||
chat_id: $scope.chatID, |
||
photo: { |
||
_: 'inputChatUploadedPhoto', |
||
file: inputFile, |
||
crop: {_: 'inputPhotoCropAuto'} |
||
} |
||
}).then(function (updateResult) { |
||
onStatedMessage(updateResult); |
||
}, function (error) { |
||
switch (error.code) { |
||
case 400: |
||
ErrorService.showSimpleError('Bad photo', 'The photo is invalid, please select another file.'); |
||
break; |
||
} |
||
}); |
||
})['finally'](function () { |
||
$scope.photo.updating = false; |
||
}); |
||
}; |
||
|
||
$scope.deletePhoto = function () { |
||
$scope.photo.updating = true; |
||
MtpApiManager.invokeApi('messages.editChatPhoto', { |
||
chat_id: $scope.chatID, |
||
photo: {_: 'inputChatPhotoEmpty'} |
||
}).then(function (updateResult) { |
||
onStatedMessage(updateResult); |
||
})['finally'](function () { |
||
$scope.photo.updating = false; |
||
}); |
||
}; |
||
|
||
$scope.editTitle = function () { |
||
var scope = $rootScope.$new(); |
||
scope.chatID = $scope.chatID; |
||
|
||
$modal.open({ |
||
templateUrl: 'partials/chat_edit_modal.html', |
||
controller: 'ChatEditModalController', |
||
scope: scope, |
||
windowClass: 'contacts_modal_window' |
||
}); |
||
} |
||
|
||
}) |
||
|
||
.controller('SettingsModalController', function ($rootScope, $scope, $timeout, AppUsersManager, AppChatsManager, MtpApiManager, AppConfigManager, NotificationsManager, MtpApiFileManager, ApiUpdatesManager, ErrorService) { |
||
|
||
$scope.profile = {}; |
||
|
||
MtpApiManager.getUserID().then(function (id) { |
||
var user = AppUsersManager.getUser(id); |
||
$scope.profile.first_name = user.first_name; |
||
$scope.profile.last_name = user.last_name; |
||
$scope.profile.photo = AppUsersManager.getUserPhoto(id, 'User'); |
||
|
||
$scope.phone = user.phone; |
||
}); |
||
|
||
$scope.notify = {}; |
||
$scope.send = {}; |
||
|
||
$scope.photo = {}; |
||
|
||
$scope.$watch('photo.file', onPhotoSelected); |
||
|
||
function onPhotoSelected (photo) { |
||
if (!photo || !photo.type || photo.type.indexOf('image') !== 0) { |
||
return; |
||
} |
||
$scope.photo.updating = true; |
||
MtpApiFileManager.uploadFile(photo).then(function (inputFile) { |
||
MtpApiManager.invokeApi('photos.uploadProfilePhoto', { |
||
file: inputFile, |
||
caption: '', |
||
geo_point: {_: 'inputGeoPointEmpty'}, |
||
crop: {_: 'inputPhotoCropAuto'} |
||
}).then(function (updateResult) { |
||
AppUsersManager.saveApiUsers(updateResult.users); |
||
MtpApiManager.getUserID().then(function (id) { |
||
ApiUpdatesManager.saveUpdate({ |
||
_: 'updateUserPhoto', |
||
user_id: id, |
||
date: tsNow(true), |
||
photo: AppUsersManager.getUser(id).photo, |
||
previous: true |
||
}); |
||
$scope.profile.photo = AppUsersManager.getUserPhoto(id, 'User'); |
||
}); |
||
}, function (error) { |
||
switch (error.code) { |
||
case 400: |
||
ErrorService.showSimpleError('Bad photo', 'The photo is invalid, please select another file.'); |
||
break; |
||
} |
||
}); |
||
})['finally'](function () { |
||
$scope.photo.updating = false; |
||
}); |
||
}; |
||
|
||
$scope.deletePhoto = function () { |
||
$scope.photo.updating = true; |
||
MtpApiManager.invokeApi('photos.updateProfilePhoto', { |
||
id: {_: 'inputPhotoEmpty'}, |
||
crop: {_: 'inputPhotoCropAuto'} |
||
}).then(function (updateResult) { |
||
MtpApiManager.getUserID().then(function (id) { |
||
ApiUpdatesManager.saveUpdate({ |
||
_: 'updateUserPhoto', |
||
user_id: id, |
||
date: tsNow(true), |
||
photo: updateResult, |
||
previous: true |
||
}); |
||
$scope.profile.photo = AppUsersManager.getUserPhoto(id, 'User'); |
||
}); |
||
})['finally'](function () { |
||
$scope.photo.updating = false; |
||
}); |
||
}; |
||
|
||
AppConfigManager.get('notify_nodesktop', 'notify_nosound', 'send_ctrlenter').then(function (settings) { |
||
$scope.notify.desktop = !settings[0]; |
||
$scope.notify.sound = !settings[1]; |
||
$scope.send.enter = settings[2] ? '' : '1'; |
||
|
||
$scope.$watch('notify.sound', function(newValue, oldValue) { |
||
if (newValue === oldValue) { |
||
return false; |
||
} |
||
if (newValue) { |
||
AppConfigManager.remove('notify_nosound'); |
||
} else { |
||
AppConfigManager.set({notify_nosound: true}); |
||
NotificationsManager.clear(); |
||
} |
||
}); |
||
|
||
$scope.$watch('notify.desktop', function(newValue, oldValue) { |
||
if (newValue === oldValue) { |
||
return false; |
||
} |
||
if (newValue) { |
||
AppConfigManager.remove('notify_nodesktop'); |
||
} else { |
||
AppConfigManager.set({notify_nodesktop: true}); |
||
} |
||
}); |
||
|
||
$scope.$watch('send.enter', function(newValue, oldValue) { |
||
if (newValue === oldValue) { |
||
return false; |
||
} |
||
if (newValue) { |
||
AppConfigManager.remove('send_ctrlenter'); |
||
} else { |
||
AppConfigManager.set({send_ctrlenter: true}); |
||
} |
||
$rootScope.$broadcast('settings_changed'); |
||
}); |
||
}); |
||
|
||
|
||
$scope.error = {}; |
||
$scope.save = function (profileForm) { |
||
MtpApiManager.invokeApi('account.updateProfile', { |
||
first_name: $scope.profile.first_name || '', |
||
last_name: $scope.profile.last_name || '' |
||
}).then(function (user) { |
||
$scope.error = {}; |
||
// console.log($scope.profileForm); |
||
profileForm.$setPristine(); |
||
AppUsersManager.saveApiUser(user); |
||
}, function (error) { |
||
switch (error.type) { |
||
case 'FIRSTNAME_INVALID': |
||
$scope.error = {field: 'first_name'}; |
||
break; |
||
|
||
case 'LASTNAME_INVALID': |
||
$scope.error = {field: 'last_name'}; |
||
break; |
||
|
||
case 'NAME_NOT_MODIFIED': |
||
$scope.error = {}; |
||
break; |
||
} |
||
}); |
||
} |
||
|
||
$scope.logOut = function () { |
||
MtpApiManager.logOut().then(function () { |
||
location.hash = '/login'; |
||
location.reload(); |
||
}); |
||
} |
||
}) |
||
|
||
.controller('ContactsModalController', function ($scope, $modalInstance, AppUsersManager) { |
||
$scope.contacts = []; |
||
$scope.search = {}; |
||
|
||
$scope.selectedContacts = {}; |
||
$scope.disabledContacts = {}; |
||
$scope.selectedCount = 0; |
||
|
||
if ($scope.disabled) { |
||
for (var i = 0; i < $scope.disabled.length; i++) { |
||
$scope.disabledContacts[$scope.disabled[i]] = true; |
||
} |
||
} |
||
|
||
if ($scope.selected) { |
||
for (var i = 0; i < $scope.selected.length; i++) { |
||
if (!$scope.selectedContacts[$scope.selected[i]]) { |
||
$scope.selectedContacts[$scope.selected[i]] = true; |
||
$scope.selectedCount++; |
||
} |
||
} |
||
} |
||
|
||
$scope.$watch('search.query', function (newValue) { |
||
AppUsersManager.getContacts(newValue).then(function (contactsList) { |
||
$scope.contacts = []; |
||
angular.forEach(contactsList, function(userID) { |
||
var contact = { |
||
userID: userID, |
||
user: AppUsersManager.getUser(userID), |
||
userPhoto: AppUsersManager.getUserPhoto(userID, 'User') |
||
} |
||
$scope.contacts.push(contact); |
||
}); |
||
$scope.$broadcast('contacts_change'); |
||
}); |
||
}); |
||
|
||
$scope.contactSelect = function (userID) { |
||
if ($scope.disabledContacts[userID]) { |
||
return false; |
||
} |
||
if (!$scope.multiSelect) { |
||
return $modalInstance.close(userID); |
||
} |
||
if ($scope.selectedContacts[userID]) { |
||
delete $scope.selectedContacts[userID]; |
||
$scope.selectedCount--; |
||
} else { |
||
$scope.selectedContacts[userID] = true; |
||
$scope.selectedCount++; |
||
} |
||
}; |
||
|
||
$scope.submitSelected = function () { |
||
if ($scope.selectedCount > 0) { |
||
var selectedUserIDs = []; |
||
angular.forEach($scope.selectedContacts, function (t, userID) { |
||
selectedUserIDs.push(userID); |
||
}); |
||
return $modalInstance.close(selectedUserIDs); |
||
} |
||
} |
||
|
||
}) |
||
|
||
.controller('PeerSelectController', function ($scope, $modalInstance) { |
||
|
||
$scope.dialogSelect = function (peerString) { |
||
$modalInstance.close(peerString); |
||
}; |
||
|
||
}) |
||
|
||
.controller('ChatCreateModalController', function ($scope, $modalInstance, $rootScope, MtpApiManager, AppUsersManager, AppChatsManager, ApiUpdatesManager) { |
||
$scope.group = {name: ''}; |
||
|
||
$scope.createGroup = function () { |
||
if (!$scope.group.name) { |
||
return; |
||
} |
||
var inputUsers = []; |
||
angular.forEach($scope.userIDs, function(userID) { |
||
inputUsers.push({_: 'inputUserContact', user_id: userID}); |
||
}); |
||
return MtpApiManager.invokeApi('messages.createChat', { |
||
title: $scope.group.name, |
||
users: inputUsers |
||
}).then(function (createdResult) { |
||
AppUsersManager.saveApiUsers(createdResult.users); |
||
AppChatsManager.saveApiChats(createdResult.chats); |
||
|
||
if (ApiUpdatesManager.saveSeq(createdResult.seq)) { |
||
ApiUpdatesManager.saveUpdate({ |
||
_: 'updateNewMessage', |
||
message: createdResult.message, |
||
pts: createdResult.pts |
||
}); |
||
} |
||
|
||
var peerString = AppChatsManager.getChatString(createdResult.message.to_id.chat_id); |
||
$rootScope.$broadcast('history_focus', {peerString: peerString}); |
||
}); |
||
}; |
||
|
||
$scope.back = function () { |
||
$modalInstance.dismiss(); |
||
}; |
||
|
||
}) |
||
|
||
.controller('ChatEditModalController', function ($scope, $modalInstance, $rootScope, MtpApiManager, AppUsersManager, AppChatsManager, ApiUpdatesManager) { |
||
|
||
var chat = AppChatsManager.getChat($scope.chatID); |
||
$scope.group = {name: chat.title}; |
||
|
||
$scope.updateGroup = function () { |
||
if (!$scope.group.name) { |
||
return; |
||
} |
||
if ($scope.group.name == chat.title) { |
||
return $modalInstance.close(); |
||
} |
||
|
||
return MtpApiManager.invokeApi('messages.editChatTitle', { |
||
chat_id: $scope.chatID, |
||
title: $scope.group.name |
||
}).then(function (editResult) { |
||
AppUsersManager.saveApiUsers(editResult.users); |
||
AppChatsManager.saveApiChats(editResult.chats); |
||
|
||
if (ApiUpdatesManager.saveSeq(editResult.seq)) { |
||
ApiUpdatesManager.saveUpdate({ |
||
_: 'updateNewMessage', |
||
message: editResult.message, |
||
pts: editResult.pts |
||
}); |
||
} |
||
|
||
var peerString = AppChatsManager.getChatString($scope.chatID); |
||
$rootScope.$broadcast('history_focus', {peerString: peerString}); |
||
}); |
||
}; |
||
}) |
||
|
||
/*! |
||
* Webogram v0.0.20 - messaging web application for MTProto |
||
* https://github.com/zhukov/webogram |
||
* Copyright (C) 2014 Igor Zhukov <[email protected]> |
||
* https://github.com/zhukov/webogram/blob/master/LICENSE |
||
*/ |
||
|
||
'use strict'; |
||
|
||
/* Filters */ |
||
|
||
angular.module('myApp.filters', []) |
||
|
||
.filter('userName', [function() { |
||
return function (user) { |
||
if (!user || !user.first_name && !user.last_name) { |
||
return 'DELETED'; |
||
} |
||
return user.first_name + ' ' + user.last_name; |
||
} |
||
}]) |
||
|
||
.filter('userFirstName', [function() { |
||
return function (user) { |
||
if (!user || !user.first_name && !user.last_name) { |
||
return 'DELETED'; |
||
} |
||
return user.first_name || user.last_name; |
||
} |
||
}]) |
||
|
||
.filter('userStatus', ['$filter', function($filter) { |
||
return function (user) { |
||
if (!user || !user.status || user.status._ == 'userStatusEmpty') { |
||
return 'offline'; |
||
} |
||
if (user.status._ == 'userStatusOnline') { |
||
return 'online'; |
||
} |
||
|
||
return 'last seen ' + $filter('relativeTime')(user.status.was_online); |
||
} |
||
}]) |
||
|
||
.filter('chatTitle', [function() { |
||
return function (chat) { |
||
if (!chat || !chat.title) { |
||
return 'DELETED'; |
||
} |
||
return chat.title; |
||
} |
||
}]) |
||
|
||
.filter('dateOrTime', ['$filter', function($filter) { |
||
var cachedDates = {}; |
||
|
||
return function (timestamp) { |
||
|
||
if (cachedDates[timestamp]) { |
||
return cachedDates[timestamp]; |
||
} |
||
|
||
var ticks = timestamp * 1000, |
||
diff = Math.abs(tsNow() - ticks), |
||
format = 'HH:mm'; |
||
|
||
if (diff > 518400000) { // 6 days |
||
format = 'shortDate'; |
||
} |
||
else if (diff > 43200000) { // 12 hours |
||
format = 'EEE'; |
||
} |
||
return cachedDates[timestamp] = $filter('date')(ticks, format); |
||
} |
||
}]) |
||
|
||
.filter('duration', [function() { |
||
return function (duration) { |
||
var secs = duration % 60, |
||
mins = Math.floor((duration - secs) / 60.0); |
||
|
||
if (secs < 10) { |
||
secs = '0' + secs; |
||
} |
||
|
||
return mins + ':' + secs; |
||
} |
||
}]) |
||
|
||
.filter('phoneNumber', [function() { |
||
return function (phoneRaw) { |
||
phoneRaw = (phoneRaw || '').replace(/\D/g, ''); |
||
if (phoneRaw.charAt(0) == '7' && phoneRaw.length == 11) { |
||
return '+' + phoneRaw.charAt(0) + ' (' + phoneRaw.substr(1, 3) + ') ' + phoneRaw.substr(4, 3) + '-' + phoneRaw.substr(7, 2) + '-' + phoneRaw.substr(9, 2); |
||
} |
||
return '+' + phoneRaw; |
||
} |
||
}]) |
||
|
||
.filter('formatSize', [function () { |
||
return function (size) { |
||
if (!size) { |
||
return '0'; |
||
} |
||
else if (size < 1024) { |
||
return size + ' b'; |
||
} |
||
else if (size < 1048576) { |
||
return (Math.round(size / 1024 * 10) / 10) + ' Kb'; |
||
} |
||
|
||
return (Math.round(size / 1048576 * 100) / 100) + ' Mb'; |
||
} |
||
}]) |
||
|
||
.filter('formatSizeProgress', ['$filter', function ($filter) { |
||
return function (progress) { |
||
var done = $filter('formatSize')(progress.done), |
||
doneParts = done.split(' '), |
||
total = $filter('formatSize')(progress.total), |
||
totalParts = total.split(' '); |
||
|
||
if (totalParts[1] === doneParts[1]) { |
||
return doneParts[0] + ' of ' + totalParts[0] + ' ' + (doneParts[1] || ''); |
||
} |
||
return done + ' of ' + total; |
||
} |
||
}]) |
||
|
||
.filter('nl2br', [function () { |
||
return function (text) { |
||
return text.replace(/\n/g, '<br/>'); |
||
} |
||
}]) |
||
|
||
.filter('richText', ['$filter', function ($filter) { |
||
return function (text) { |
||
return $filter('linky')(text, '_blank').replace(/\n| /g, '<br/>'); |
||
} |
||
}]) |
||
|
||
.filter('relativeTime', ['$filter', function($filter) { |
||
return function (timestamp) { |
||
var ticks = timestamp * 1000, |
||
diff = Math.abs(tsNow() - ticks); |
||
|
||
if (diff < 60000) { |
||
return 'just now'; |
||
} |
||
if (diff < 3000000) { |
||
return Math.ceil(diff / 60000) + ' minutes ago'; |
||
} |
||
if (diff < 10000000) { |
||
return Math.ceil(diff / 3600000) + ' hours ago'; |
||
} |
||
return $filter('dateOrTime')(timestamp); |
||
} |
||
}]) |
||
|
||
angular.module("myApp.templates", []).run(["$templateCache", function($templateCache) {$templateCache.put("partials/chat_create_modal.html","<div class=\"contacts_modal_wrap\">\n\n <div class=\"modal-header\">\n <a class=\"modal-close-link\" ng-click=\"$close()\">Close</a>\n <h4 class=\"modal-title\">Create Group</h4>\n </div>\n\n <div class=\"modal-body\">\n\n <form ng-submit=\"createGroup()\">\n\n <div class=\"contacts_modal_group_title\">\n <input class=\"form-control\" my-focused type=\"text\" placeholder=\"Group name\" ng-model=\"group.name\"/>\n </div>\n\n <div class=\"contacts_modal_panel clearfix\">\n\n <div class=\"contacts_modal_actions pull-right\">\n <button class=\"btn btn-default\" ng-click=\"$dismiss()\"> Cancel </button>\n\n <button class=\"btn btn-success\" type=\"submit\"> Create </button>\n </div>\n\n </div>\n\n </form>\n\n </div>\n\n</div>"); |
||
$templateCache.put("partials/chat_edit_modal.html","<div class=\"contacts_modal_wrap\">\n\n <div class=\"modal-header\">\n <a class=\"modal-close-link\" ng-click=\"$close()\">Close</a>\n <h4 class=\"modal-title\">Edit Group Title</h4>\n </div>\n\n <div class=\"modal-body\">\n\n <form ng-submit=\"updateGroup()\">\n\n <div class=\"contacts_modal_group_title\">\n <input class=\"form-control\" my-focused type=\"text\" placeholder=\"Group name\" ng-model=\"group.name\"/>\n </div>\n\n <div class=\"contacts_modal_panel clearfix\">\n\n <div class=\"contacts_modal_actions pull-right\">\n <button class=\"btn btn-default\" ng-click=\"$dismiss()\"> Cancel </button>\n\n <button class=\"btn btn-success\" type=\"submit\"> Save </button>\n </div>\n\n </div>\n\n </form>\n\n </div>\n\n</div>"); |
||
$templateCache.put("partials/chat_modal.html","<div class=\"chat_modal_wrap\">\n\n <div class=\"modal-header\">\n <a class=\"modal-close-link\" ng-click=\"$close()\">Close</a>\n <h4 class=\"modal-title\">Group Info</h4>\n </div>\n\n <div class=\"modal-body\">\n\n <div class=\"chat_modal_photo_wrap pull-left\">\n\n <div class=\"chat_modal_photo\">\n <img\n class=\"user_modal_image\"\n my-load-thumb\n thumb=\"chatFull.thumb\"\n />\n <div class=\"chat_modal_photo_change_wrap\" ng-if=\"chatFull.chat._ != \'chatForbidden\' && !chatFull.chat.left\">\n <div ng-if=\"photo.updating\" class=\"chat_modal_photo_loading\">Updating<span my-typing-dots></span></div>\n <div ng-if=\"!photo.updating\">\n <div class=\"chat_modal_photo_update_link\">\n <input my-file-upload type=\"file\" multiple=\"false\" class=\"im_attach_input\" size=\"120\" multiple=\"false\" accept=\"image/x-png, image/png, image/gif, image/jpeg\" />\n Update photo\n </div>\n <a ng-if=\"chatFull.thumb.location\" href=\"\" ng-click=\"deletePhoto()\" class=\"chat_modal_photo_delete_link\">Delete photo</a>\n </div>\n </div>\n </div>\n\n </div>\n\n\n <div class=\"chat_modal_info_wrap clearfix\">\n <h4 class=\"chat_modal_header\">\n <a href=\"\" ng-if=\"chatFull.chat._ != \'chatForbidden\' && !chatFull.chat.left\" ng-click=\"editTitle()\" ng-bind-html=\"chatFull.chat.rTitle\"></a>\n <span ng-if=\"chatFull.chat._ == \'chatForbidden\' || chatFull.chat.left\" ng-bind-html=\"chatFull.chat.rTitle\"></span>\n </h4>\n <p class=\"chat_modal_members_count\" ng-if=\"chatFull.chat.participants_count > 0\">\n <ng-pluralize count=\"chatFull.chat.participants_count\"\n when=\"{\'0\': \'No members\', \'one\': \'1 member\', \'other\': \'{} members\'}\">\n </ng-pluralize>\n </p>\n\n <div class=\"chat_modal_settings_wrap\">\n <div class=\"chat_modal_notifications\">\n Notifications:\n <a ng-click=\"settings.notifications = !settings.notifications\">\n {{settings.notifications ? \'ON\' : \'OFF\'}}\n </a>\n </div>\n\n <div class=\"chat_modal_leave_join\" ng-if=\"chatFull.chat._ != \'chatForbidden\'\">\n <div class=\"chat_modal_leave\" ng-if=\"!chatFull.chat.left\">\n <a href=\"\" ng-click=\"leaveGroup()\">Leave group</a>\n </div>\n <div class=\"chat_modal_leave\" ng-if=\"chatFull.chat.left\">\n <a href=\"\" ng-click=\"returnToGroup()\">Return to group</a>\n </div>\n\n </div>\n </div>\n </div>\n\n <h5 class=\"chat_modal_members_header\">\n <a href=\"\" ng-click=\"inviteToGroup()\" ng-if=\"!chatFull.chat.left && chatFull.participants.participants.length\" class=\"pull-right\">Add participant</a>\n Members\n </h5>\n <div class=\"chat_modal_members_list\">\n\n <div class=\"chat_modal_participant_wrap clearfix\" ng-repeat=\"participant in chatFull.participants.participants | orderBy:\'-user.sortStatus\'\">\n <a ng-if=\"participant.canKick\" ng-click=\"kickFromGroup(participant.user_id)\" class=\"chat_modal_participant_kick pull-right\">Kick</a>\n <a ng-click=\"openUser(participant.user_id)\" class=\"chat_modal_participant_photo pull-left\">\n <img\n class=\"chat_modal_participant_photo\"\n my-load-thumb\n thumb=\"participant.userPhoto\"\n />\n <i class=\"icon status_online\" ng-show=\"participant.user.status._ == \'userStatusOnline\'\"></i>\n </a>\n <div class=\"chat_modal_participant_name\">\n <a ng-click=\"openUser(participant.user.id)\" ng-bind-html=\"participant.user.rFullName\"></a>\n </div>\n <div class=\"chat_modal_participant_status\">{{participant.user | userStatus}}</div>\n </div>\n\n </div>\n\n <div class=\"chat_modal_members_forbidden\" ng-if=\"chatFull.chat._ == \'chatForbidden\' || chatFull.chat.left\">\n Group members list is unavailable.\n </div>\n\n </div>\n\n</div>"); |
||
$templateCache.put("partials/contacts_modal.html","<div class=\"contacts_modal_wrap\">\n\n <div class=\"modal-header\">\n <a class=\"modal-close-link\" ng-click=\"$dismiss()\">Close</a>\n <h4 class=\"modal-title\">Contacts</h4>\n </div>\n\n <div class=\"modal-body\">\n\n <div class=\"contacts_modal_search\">\n <input class=\"form-control contacts_modal_search_field\" my-focused type=\"search\" placeholder=\"Search\" ng-model=\"search.query\"/>\n <a class=\"contacts_modal_search_clear\" ng-click=\"search.query = \'\'\" ng-show=\"search.query.length\"></a>\n </div>\n\n\n <div my-contacts-list class=\"contacts_modal_col\">\n\n <div class=\"contacts_wrap nano\">\n <div class=\"contacts_scrollable_wrap content\">\n\n <ul class=\"contacts_modal_members_list nav nav-pills nav-stacked\">\n\n <li class=\"contacts_modal_contact_wrap clearfix\" ng-repeat=\"contact in contacts | orderBy:\'user.sortName\' track by contact.userID\" ng-class=\"{active: selectedContacts[contact.userID], disabled: disabledContacts[contact.userID]}\">\n <a class=\"contacts_modal_contact\" ng-click=\"contactSelect(contact.userID)\">\n\n <i ng-if=\"multiSelect\" class=\"icon icon-contact-tick\"></i>\n\n <div class=\"contacts_modal_contact_photo pull-left\">\n <img\n class=\"contacts_modal_contact_photo\"\n my-load-thumb\n thumb=\"contact.userPhoto\"\n />\n <i class=\"icon status_online\" ng-show=\"contact.user.status._ == \'userStatusOnline\'\"></i>\n </div>\n\n <div class=\"contacts_modal_contact_name\" ng-bind-html=\"contact.user.rFullName\"></div>\n <div class=\"contacts_modal_contact_status\">{{contact.user | userStatus}}</div>\n\n </a>\n </li>\n\n </ul>\n\n </div>\n </div>\n\n </div>\n\n\n <div ng-if=\"multiSelect\" class=\"contacts_modal_panel\">\n\n <button class=\"btn btn-success btn-block\" ng-class=\"{disabled: !selectedCount}\" ng-disabled=\"!selectedCount\" ng-click=\"submitSelected()\" type=\"submit\">\n Next »\n </button>\n\n </div>\n\n </div>\n\n</div>"); |
||
$templateCache.put("partials/dialog.html","<a class=\"im_dialog\" ng-click=\"dialogSelect(dialogMessage.peerString)\">\n\n <div class=\"im_dialog_meta pull-right text-right\">\n <div class=\"im_dialog_date\">\n {{dialogMessage.date | dateOrTime}}\n </div>\n <span\n class=\"im_dialog_badge badge\"\n ng-show=\"dialogMessage.unreadCount > 0 && !dialogMessage.out\"\n ng-bind=\"dialogMessage.unreadCount\"\n ></span>\n <i\n class=\"im_dialog_unread\"\n ng-show=\"dialogMessage.out && dialogMessage.unread\"\n ></i>\n </div>\n\n <div class=\"im_dialog_photo pull-left\">\n <img\n class=\"im_dialog_photo\"\n my-load-thumb\n thumb=\"dialogMessage.peerPhoto\"\n />\n </div>\n\n <div class=\"im_dialog_message_wrap\">\n\n <div class=\"im_dialog_peer\">\n <span class=\"im_dialog_chat\" ng-if=\"dialogMessage.chatID\">\n <i class=\"icon icon-group\"></i> <span ng-bind-html=\"dialogMessage.peerData.rTitle\"></span>\n </span>\n <span class=\"im_dialog_user\" ng-if=\"dialogMessage.peerID > 0\" ng-bind-html=\"dialogMessage.peerData.rFullName\"></span>\n </div>\n\n <div class=\"im_dialog_message\">\n <span class=\"im_dialog_chat_from_wrap\">\n <span\n class=\"im_dialog_chat_from\"\n ng-if=\"!dialogMessage.out && dialogMessage.chatID\"\n ng-bind-html=\"dialogMessage.fromUser.rFirstName\"\n ></span><span\n class=\"im_dialog_chat_from\"\n ng-if=\"dialogMessage.out\"\n >You</span>{{((dialogMessage.out || dialogMessage.peerID < 0) && (dialogMessage.message.length || dialogMessage.media && dialogMessage.media._ != \'messageMediaEmpty\')) ? \':\' : \'\'}}\n </span>\n\n <span class=\"im_dialog_message_media\" ng-if=\"dialogMessage.media && dialogMessage.media._ != \'messageMediaEmpty\'\" ng-switch=\"dialogMessage.media._\">\n <span ng-switch-when=\"messageMediaPhoto\">Photo</span>\n <span ng-switch-when=\"messageMediaVideo\">Video</span>\n <span ng-switch-when=\"messageMediaDocument\">Document</span>\n <span ng-switch-when=\"messageMediaAudio\">Audio</span>\n <span ng-switch-when=\"messageMediaGeo\">Location</span>\n <span ng-switch-when=\"messageMediaContact\">Contact</span>\n </span>\n\n <span class=\"im_dialog_message_service\" ng-if=\"dialogMessage._ == \'messageService\'\" ng-switch=\"dialogMessage.action._\">\n <span ng-switch-when=\"messageActionChatCreate\"> created the group </span>\n <span ng-switch-when=\"messageActionChatEditTitle\">changed group name</span>\n <span ng-switch-when=\"messageActionChatEditPhoto\">changed group photo</span>\n <span ng-switch-when=\"messageActionChatDeletePhoto\">removed group photo</span>\n\n <span ng-switch-when=\"messageActionChatAddUser\">\n <span ng-if=\"dialogMessage.from_id != dialogMessage.action.user_id\">\n invited <span ng-bind-html=\"dialogMessage.action.user.rFullName\"></span>\n </span>\n <span ng-if=\"dialogMessage.from_id == dialogMessage.action.user_id\">\n returned to group\n </span>\n </span>\n\n <span ng-switch-when=\"messageActionChatDeleteUser\">\n <span ng-if=\"dialogMessage.from_id != dialogMessage.action.user_id\">\n kicked <span ng-bind-html=\"dialogMessage.action.user.rFullName\"></span>\n </span>\n <span ng-if=\"dialogMessage.from_id == dialogMessage.action.user_id\">\n left group\n </span>\n </span>\n </span>\n\n <span class=\"im_dialog_message_text\" ng-if=\"dialogMessage.message.length\" ng-bind-html=\"dialogMessage.richMessage\"></span>\n </div>\n\n </div>\n</a>\n"); |
||
$templateCache.put("partials/error_modal.html","<div class=\"error_modal_wrap\">\n\n <div class=\"modal-header\">\n <a class=\"modal-close-link\" ng-click=\"$close()\">Close</a>\n <h4 class=\"modal-title\">{{title}}</h4>\n </div>\n\n\n <div class=\"modal-body\">\n\n <div class=\"error_modal_description\">\n {{description}}\n </div>\n\n </div>\n\n</div>"); |
||
$templateCache.put("partials/head.html","<div class=\"tg_page_head\">\n <div class=\"navbar navbar-static-top navbar-inverse\" role=\"navigation\">\n <div class=\"container\" ng-init=\"navbarCollapsed = true\">\n <div class=\"navbar-header\">\n <button type=\"button\" class=\"navbar-toggle\" ng-click=\"navbarCollapsed = !navbarCollapsed\">\n <span class=\"sr-only\">Toggle navigation</span>\n <span class=\"icon-bar\"></span>\n <span class=\"icon-bar\"></span>\n <span class=\"icon-bar\"></span>\n </button>\n <a class=\"navbar-brand\" href=\"{{isLoggedIn ? \'#/im\' : \'#/\'}}\"><span class=\"tg_head_logo\"></span><span class=\"tg_head_logo_text\"></span></a>\n <ul class=\"nav navbar-nav navbar-quick-nav\" ng-show=\"curDialog.peer\">\n <li>\n <a href=\"#/im\">\n <i class=\"icon icon-back\"></i> Back\n </a>\n </li>\n </ul>\n </div>\n\n\n <div class=\"navbar-collapse\" collapse=\"navbarCollapsed\">\n\n <ul ng-if=\"offline\" class=\"nav navbar-nav navbar-offline\">\n <li ng-show=\"!offlineConnecting\"><span class=\"navbar-offline-text\">Waiting for network<span my-typing-dots></span></span></li>\n <li ng-show=\"!offlineConnecting\"><a href=\"\" ng-click=\"retryOnline()\">Retry</a></li>\n <li ng-show=\"offlineConnecting\"><span class=\"navbar-offline-text\">Connecting<span my-typing-dots></span></span></li>\n </ul>\n\n <ul ng-if=\"!offline\" class=\"nav navbar-nav navbar-right\">\n <li ng-if=\"isLoggedIn\"><a href=\"\" ng-click=\"openGroup()\">New Group</a></li>\n <li ng-if=\"isLoggedIn\"><a href=\"\" ng-click=\"openContacts()\">Contacts</a></li>\n <li ng-if=\"isLoggedIn\"><a href=\"\" ng-click=\"openSettings()\">Settings</a></li>\n <li><a href=\"https://github.com/zhukov/webogram\" target=\"_blank\">About</a></li>\n </ul>\n\n </div>\n </div>\n </div>\n</div>"); |
||
$templateCache.put("partials/im.html","<div ng-include=\"\'partials/head.html\'\"></div>\n\n<div class=\"im_page_wrap\" ng-class=\"{im_page_peer_not_selected: !curDialog.peer}\">\n\n <div class=\"im_page_split clearfix\">\n\n <div class=\"im_dialogs_col_wrap\" ng-controller=\"AppImDialogsController\">\n <div class=\"im_dialogs_search\">\n <input class=\"form-control im_dialogs_search_field\" type=\"search\" placeholder=\"Search\" ng-model=\"search.query\"/>\n <a class=\"im_dialogs_search_clear\" ng-click=\"search.query = \'\'\" ng-show=\"search.query.length\"></a>\n </div>\n <div my-dialogs-list class=\"im_dialogs_col\">\n <div class=\"im_dialogs_wrap nano\">\n <div class=\"im_dialogs_scrollable_wrap content\">\n <ul class=\"nav nav-pills nav-stacked\">\n <li class=\"im_dialog_wrap\" my-dialog dialog-message=\"dialogMessage\" ng-repeat=\"dialogMessage in dialogs track by dialogMessage.peerID\" ng-class=\"{active: curDialog.peerID == dialogMessage.peerID}\"></li>\n </ul>\n </div>\n </div>\n </div>\n </div>\n\n <div class=\"im_history_col_wrap\" ng-controller=\"AppImHistoryController\">\n <div ng-if=\"state.notSelected\" class=\"im_history_not_selected\">No history to display</div>\n <div ng-show=\"!state.notSelected && !state.loaded\" class=\"im_history_not_selected\">Loading history<span my-typing-dots></span></div>\n\n <div ng-if=\"state.loaded\">\n <div my-history class=\"im_history_col\">\n\n <div class=\"im_history_panel_wrap\">\n\n <div class=\"im_history_panel clearfix\" ng-controller=\"AppImPanelController\">\n <div class=\"im_history_panel_title\">\n\n <a class=\"im_history_panel_info_link pull-right\" ng-click=\"showPeerInfo()\">Info</a>\n <a class=\"im_history_panel_edit_link pull-right\" ng-click=\"toggleEdit()\">Edit</a>\n\n <div class=\"dropdown im_history_panel_media_dropdown pull-right\">\n <a class=\"dropdown-toggle\">Media<i class=\"icon icon-caret\"></i></a>\n <ul class=\"dropdown-menu\">\n <li>\n <a ng-click=\"toggleMedia(\'photos\')\">Photos</a>\n </li>\n <li>\n <a ng-click=\"toggleMedia(\'video\')\">Videos</a>\n </li>\n <li>\n <a ng-click=\"toggleMedia(\'documents\')\">Documents</a>\n </li>\n </ul>\n </div>\n <a ng-if=\"mediaType !== false\" class=\"im_history_panel_return_link pull-right\" ng-click=\"toggleMedia()\">\n Show all messages\n <strong class=\"im_history_panel_return_count\" ng-show=\"missedCount > 0\">+{{missedCount}}</strong>\n </a>\n\n <h4 ng-if=\"mediaType !== false\" ng-switch=\"mediaType\">\n <span ng-switch-when=\"photos\"> Photos </span>\n <span ng-switch-when=\"video\"> Videos </span>\n <span ng-switch-when=\"documents\"> Documents </span>\n </h4>\n\n <h4 ng-if=\"mediaType === false && historyPeer.id < 0\" ng-click=\"showPeerInfo()\">\n <span ng-bind-html=\"historyPeer.data.rTitle\"></span>\n <small class=\"im_chat_users\">\n <ng-pluralize count=\"historyPeer.data.participants_count\"\n when=\"{\'0\': \'No members\', \'one\': \'1 member\', \'other\': \'{} members\'}\">\n </ng-pluralize>\n </small>\n </h4>\n\n <h4 ng-if=\"mediaType === false && historyPeer.id > 0\" ng-click=\"showPeerInfo()\">\n <span ng-bind-html=\"historyPeer.data.rFullName\"></span>\n <small class=\"im_peer_online\">{{historyPeer.data | userStatus}}</small>\n </h4>\n\n </div>\n\n </div>\n\n </div>\n\n <div class=\"im_history_wrap nano\">\n\n <div class=\"im_history_scrollable_wrap content\">\n\n <div class=\"im_history_scrollable\">\n\n <div class=\"im_history\" ng-class=\"{im_history_selectable: selectActions}\">\n <div class=\"im_history_empty\" ng-show=\"historyEmpty && !history.length\">No messages to display</div>\n <div class=\"im_history_messages\">\n <div class=\"im_history_message_wrap\" my-message ng-repeat=\"historyMessage in history\"></div>\n </div>\n </div>\n\n <div class=\"im_history_typing_wrap\">\n <div class=\"im_history_typing\" ng-show=\"typing.user\">\n <strong class=\"im_history_typing_author\" ng-bind-html=\"typing.user.rFullName\"></strong> is typing<span my-typing-dots></span>\n </div>\n </div>\n\n </div>\n\n </div>\n\n </div>\n\n <div class=\"im_bottom_panel_wrap\">\n\n <div class=\"im_edit_panel_wrap clearfix\" ng-show=\"selectActions\" ng-class=\"{im_edit_panel_wrap_loaded: true}\">\n <div class=\"im_edit_panel_border\"></div>\n <a class=\"im_edit_flush_link\" ng-click=\"selectedFlush()\" ng-show=\"historyPeer.id < 0\">\n Clear History\n </a>\n <a class=\"im_edit_flush_link\" ng-click=\"selectedFlush()\" ng-show=\"historyPeer.id > 0\">\n Delete Chat\n </a>\n <a class=\"im_edit_cancel_link\" ng-click=\"selectedCancel()\">\n Cancel\n </a>\n <div class=\"im_edit_selected_actions\">\n <a class=\"btn btn-primary im_edit_forward_btn\" ng-click=\"selectedForward()\">\n Forward <strong class=\"im_selected_count\" ng-show=\"selectedCount > 0\" ng-bind=\"selectedCount\"></strong>\n </a><a class=\"btn btn-danger im_edit_delete_btn\" ng-click=\"selectedDelete()\">\n Delete <strong class=\"im_selected_count\" ng-show=\"selectedCount > 0\" ng-bind=\"selectedCount\"></strong>\n </a>\n </div>\n </div>\n\n <div class=\"im_send_panel_wrap\" ng-hide=\"selectActions\">\n\n <div class=\"im_send_form_wrap1\">\n\n <div class=\"im_send_form_wrap clearfix\" ng-controller=\"AppImSendController\">\n <div class=\"pull-right im_panel_peer_photo\" ng-click=\"showPeerInfo()\">\n <img\n class=\"im_panel_peer_photo\"\n my-load-thumb\n thumb=\"historyPeer.photo\"\n />\n <i class=\"icon im_panel_peer_online\" ng-show=\"historyPeer.id > 0 && historyPeer.data.status._ == \'userStatusOnline\'\"></i>\n </div>\n <div class=\"pull-left im_panel_own_photo\">\n <img\n class=\"im_panel_own_photo\"\n my-load-thumb\n thumb=\"ownPhoto\"\n />\n </div>\n <form my-send-form draft-message=\"draftMessage\" class=\"im_send_form\" ng-submit=\"sendMessage($event)\">\n <div class=\"im_send_dropbox_wrap\"> Drop photos here to send </div>\n <textarea ng-model=\"draftMessage.text\" placeholder=\"Write a message...\" class=\"form-control im_message_field\"></textarea>\n\n <div class=\"im_media_attach pull-right\">\n <input type=\"file\" class=\"im_media_attach_input\" size=\"28\" multiple=\"true\" accept=\"image/*, video/*, audio/*\" />\n <i class=\"icon icon-camera\"></i>\n </div>\n\n <div class=\"im_attach pull-right\">\n <input type=\"file\" class=\"im_attach_input\" size=\"28\" multiple=\"true\" />\n <i class=\"icon icon-paperclip\"></i>\n </div>\n\n\n <div class=\"im_emoji_btn pull-right\">\n <i class=\"icon icon-emoji\"></i>\n </div>\n\n <button type=\"submit\" class=\"btn btn-success im_submit\">Send</button>\n </form>\n </div>\n\n </div>\n\n </div>\n\n </div>\n\n </div>\n </div>\n\n </div>\n\n </div>\n\n\n</div>\n\n<div class=\"im_page_footer\">\n <a class=\"im_page_footer_brand\" target=\"_blank\" href=\"https://github.com/zhukov/webogram\">Telegram alpha</a> by izhukov & toberg\n</div>\n\n<div id=\"notify_sound\"></div>\n\n"); |
||
$templateCache.put("partials/login.html","<div ng-include=\"\'partials/head.html\'\"></div>\n\n\n<div class=\"login_form_wrap\">\n <div class=\"error\" ng-if=\"error.message\">{{ error.message }}</div>\n <form name=\"mySendCodeForm\" ng-if=\"!credentials.phone_code_hash\" ng-submit=\"sendCode()\">\n <h3 class=\"login_form_head\">Sign in</h3>\n <p class=\"login_form_lead\">Please enter your full phone number with country code.</p>\n\n <div class=\"form-group\" ng-class=\"{\'has-error\': error.field == \'phone\'}\">\n <label class=\"control-label\" for=\"phone_number\" ng-if=\"error.field == \'phone\'\">Incorrect phone number</label>\n <input type=\"tel\" class=\"form-control\" name=\"phone_number\" ng-model=\"credentials.phone_number\" placeholder=\"Enter your phone\" required>\n </div>\n <button class=\"btn btn-success btn-block\" ng-class=\"{disabled: progress.enabled}\" ng-disabled=\"progress.enabled\" type=\"submit\">\n {{progress.enabled ? \'Generating keys...\' : \'Next\'}}\n </button>\n </form>\n\n <form name=\"myLoginForm\" ng-if=\"credentials.phone_code_hash\" ng-submit=\"logIn()\">\n <h3 class=\"login_form_head\">{{ credentials.phone_number | phoneNumber }} <small>(<a href=\"#/auth\">edit</a>)</small></h3>\n <p class=\"login_form_lead\">We have sent you a code via SMS.<br/>Please enter it below.</p>\n\n <p class=\"login_form_lead\">\n <span ng-show=\"callPending.remaining > 0\">Telegram will call you in {{callPending.remaining | duration}}</span>\n <span ng-show=\"!callPending.remaining && !callPending.success\">Telegram is calling you</span>\n <span ng-show=\"!callPending.remaining && callPending.success\">Telegram dialed your number</span>\n </p>\n\n <div class=\"form-group\" ng-class=\"{\'has-error\': error.field == \'phone_code\'}\">\n <label class=\"control-label\" for=\"phone_code\" ng-if=\"error.field == \'phone_code\'\">Incorrect SMS code</label>\n <input type=\"number\" maxlength=\"5\" class=\"form-control\" name=\"phone_code\" ng-model=\"credentials.phone_code\" placeholder=\"Enter your code\" required>\n </div>\n\n <button class=\"btn btn-success btn-block\" type=\"submit\" ng-class=\"{disabled: progress.enabled}\" ng-disabled=\"progress.enabled\">\n {{progress.enabled ? \'Checking code...\' : \'Sign in\'}}\n </button>\n </form>\n</div>\n"); |
||
$templateCache.put("partials/message.html","<div class=\"im_message_unread_split\" ng-if=\"historyUnread && historyUnread.beforeID == historyMessage.id\">\n <ng-pluralize count=\"historyUnread.count\"\n when=\"{\'one\': \'1 unread message\', \'other\': \'{} unread messages\'}\">\n </ng-pluralize>\n</div>\n\n<div class=\"im_message_outer_wrap\" ng-class=\"{im_message_selected: selectedMsgs[historyMessage.id]}\" ng-click=\"toggleMessage(historyMessage.id, $event.target)\">\n\n\n <div class=\"im_message_wrap clearfix\">\n\n <div class=\"im_service_message_wrap\" ng-if=\"historyMessage._ == \'messageService\'\">\n <div class=\"im_service_message\">\n\n <a ng-click=\"openUser(historyMessage.from_id)\" class=\"im_message_author\" ng-bind-html=\"historyMessage.fromUser.rFullName\"></a>\n\n <span class=\"im_message_service\" ng-switch=\"historyMessage.action[\'_\']\">\n <span ng-switch-when=\"messageActionChatCreate\">\n created the group «<strong>{{historyMessage.action.title}}</strong>»\n </span>\n <span ng-switch-when=\"messageActionChatEditTitle\">\n changed group name to «<strong>{{historyMessage.action.title}}</strong>»\n </span>\n <span ng-switch-when=\"messageActionChatEditPhoto\">\n changed group photo\n </span>\n <span ng-switch-when=\"messageActionChatDeletePhoto\">\n removed group photo\n </span>\n <span ng-switch-when=\"messageActionChatAddUser\">\n <span ng-if=\"historyMessage.from_id != historyMessage.action.user_id\">\n invited <a ng-click=\"openUser(historyMessage.action.user_id)\" ng-bind-html=\"historyMessage.action.user.rFullName\"></a>\n </span>\n <span ng-if=\"historyMessage.from_id == historyMessage.action.user_id\">\n returned to group\n </span>\n </span>\n <span ng-switch-when=\"messageActionChatDeleteUser\">\n <span ng-if=\"historyMessage.from_id != historyMessage.action.user_id\">\n kicked <a ng-click=\"openUser(historyMessage.action.user_id)\" ng-bind-html=\"historyMessage.action.user.rFullName\"></a>\n </span>\n <span ng-if=\"historyMessage.from_id == historyMessage.action.user_id\">\n left group\n </span>\n </span>\n\n <span ng-switch-default>\n unsupported action {{historyMessage.action}}\n </span>\n </span>\n\n </div>\n\n <a ng-if=\"historyMessage.action._ == \'messageActionChatEditPhoto\'\" class=\"im_service_message_photo_thumb\" href=\"\" ng-click=\"openPhoto(historyMessage.action.photo.id)\">\n <img\n class=\"im_service_message_photo_thumb\"\n my-load-thumb\n thumb=\"historyMessage.action.photo.thumb\"\n width=\"{{historyMessage.action.photo.thumb.width}}\"\n height=\"{{historyMessage.action.photo.thumb.height}}\"\n />\n </a>\n\n </div>\n\n <div class=\"im_content_message_wrap\" ng-if=\"historyMessage._ != \'messageService\'\">\n <div class=\"im_content_message_select_area\">\n <i class=\"icon icon-select-tick\"></i>\n </div>\n\n <a ng-click=\"historyMessage.send()\" ng-if=\"historyMessage.error\">\n <i class=\"icon-message-status icon-message-status-error\" tooltip=\"Try again\"></i>\n </a>\n <i class=\"icon-message-status\" ng-class=\"{\'icon-message-status-unread\': historyMessage.unread, \'icon-message-status-pending\': historyMessage.pending}\" ng-if=\"!historyMessage.error\"></i>\n\n <a ng-click=\"openUser(historyMessage.from_id)\" class=\"im_message_from_photo pull-left\">\n <img\n class=\"im_message_from_photo\"\n my-load-thumb\n thumb=\"historyMessage.fromPhoto\"\n />\n </a>\n <div class=\"im_message_meta pull-right text-right\">\n <span class=\"im_message_date\">{{historyMessage.date | dateOrTime}}</span>\n </div>\n\n <div class=\"im_message_body\">\n\n <a class=\"im_message_author user_color_{{historyMessage.fromPhoto.num}}\" ng-click=\"openUser(historyMessage.from_id)\" ng-bind-html=\"historyMessage.fromUser.rFullName\" ng-if=\"historyMessage.to_id.chat_id > 0\"></a>\n <a class=\"im_message_author\" ng-click=\"openUser(historyMessage.from_id)\" ng-bind-html=\"historyMessage.fromUser.rFirstName\" ng-if=\"!historyMessage.to_id.chat_id\"></a>\n\n\n <div class=\"im_message_fwd_header\" ng-if=\"historyMessage._ == \'messageForwarded\'\">\n Forwarded message from <a class=\"im_message_fwd_author\" ng-click=\"openUser(historyMessage.fwd_from_id)\" ng-bind-html=\"historyMessage.fwdUser.rFirstName\"></a>, <span class=\"im_message_fwd_date\">{{historyMessage.fwd_date | dateOrTime}}</span>\n </div>\n\n <div class=\"im_message_media\" ng-if=\"historyMessage.media && historyMessage.media._ != \'messageMediaEmpty\'\" ng-switch=\"historyMessage.media._\">\n\n <a ng-switch-when=\"messageMediaPhoto\" class=\"im_message_photo_thumb\" href=\"\" ng-click=\"openPhoto(historyMessage.media.photo.id)\" style=\"width: {{historyMessage.media.photo.thumb.width}}px;\">\n <img\n class=\"im_message_photo_thumb\"\n my-load-thumb\n thumb=\"historyMessage.media.photo.thumb\"\n width=\"{{historyMessage.media.photo.thumb.width}}\"\n height=\"{{historyMessage.media.photo.thumb.height}}\"\n />\n </a>\n\n <a ng-switch-when=\"messageMediaVideo\" class=\"im_message_video_thumb\" href=\"\" ng-click=\"openVideo(historyMessage.media.video.id)\" style=\"width: {{historyMessage.media.video.thumb.width}}px;\">\n <img\n class=\"im_message_video_thumb\"\n my-load-thumb\n thumb=\"historyMessage.media.video.thumb\"\n width=\"{{historyMessage.media.video.thumb.width}}\"\n height=\"{{historyMessage.media.video.thumb.height}}\"\n />\n <div class=\"im_message_video_duration_wrap\" style=\"width: {{historyMessage.media.video.thumb.width}}px;\">\n <span class=\"im_message_video_duration pull-right\">{{historyMessage.media.video.duration | duration}}</span>\n <span class=\"glyphicon glyphicon-facetime-video\"></span>\n </div>\n </a>\n\n <div ng-switch-when=\"messageMediaDocument\" class=\"im_message_document\" ng-class=\"{im_message_document_thumbed: !!historyMessage.media.document.thumb}\">\n <a href=\"\" ng-click=\"openDoc(historyMessage.media.document.id, false, historyMessage.media.document.withPreview)\" ng-class=\"{im_message_document_link_disabled: historyMessage.media.document.progress.enabled}\">\n <i class=\"icon icon-document\" ng-if=\"!historyMessage.media.document.thumb\"></i>\n <div class=\"im_message_document_thumb_wrap\" ng-if=\"historyMessage.media.document.thumb\">\n <img\n class=\"im_message_document_thumb\"\n my-load-thumb\n thumb=\"historyMessage.media.document.thumb\"\n width=\"{{historyMessage.media.document.thumb.width}}\"\n height=\"{{historyMessage.media.document.thumb.height}}\"\n />\n </div>\n </a>\n\n <div class=\"im_message_document_info\">\n <div class=\"im_message_document_name_wrap\">\n <span class=\"im_message_document_name\">\n {{historyMessage.media.document.file_name}}\n </span>\n <span class=\"im_message_document_size\" ng-if=\"!historyMessage.media.document.progress.enabled\">\n {{historyMessage.media.document.size | formatSize}}\n </span>\n <span class=\"im_message_document_size\" ng-if=\"historyMessage.media.document.progress.enabled\">\n {{historyMessage.media.document.progress | formatSizeProgress}}\n </span>\n </div>\n <div class=\"im_message_document_actions\" ng-if=\"!historyMessage.media.document.progress.enabled\">\n <a href=\"\" ng-click=\"openDoc(historyMessage.media.document.id)\">Download</a>\n <a href=\"\" ng-click=\"openDoc(historyMessage.media.document.id, false, true)\" ng-if=\"historyMessage.media.document.withPreview\">Open</a>\n </div>\n <div class=\"im_message_download_progress_wrap\" ng-if=\"historyMessage.media.document.progress.enabled\">\n <div class=\"progress tg_down_progress\">\n <div class=\"progress-bar progress-bar-success\" role=\"progressbar\" aria-valuenow=\"{{historyMessage.media.document.progress.percent}}\" aria-valuemin=\"0\" aria-valuemax=\"100\" style=\"width: {{historyMessage.media.document.progress.percent}}%\">\n <span class=\"sr-only\">\n {{historyMessage.media.document.progress.percent}}% Complete (success)\n </span>\n </div>\n </div>\n </div>\n </div>\n </div>\n\n\n <div ng-switch-when=\"messageMediaAudio\" class=\"im_message_document\">\n <a href=\"\" ng-click=\"openAudio(historyMessage.media.audio.id)\" ng-if=\"!historyMessage.media.audio.progress.enabled && !historyMessage.media.audio.url\">\n <i class=\"icon icon-audio\"></i>\n </a>\n <i class=\"icon icon-audio\" ng-if=\"historyMessage.media.audio.progress.enabled || historyMessage.media.audio.url\"></i>\n\n <div class=\"im_message_audio_info\">\n <div class=\"im_message_audio_name_wrap\" ng-if=\"!historyMessage.media.audio.url\">\n <span class=\"im_message_audio_name\">\n Voice message\n </span>\n <span class=\"im_message_audio_duration\" ng-if=\"!historyMessage.media.audio.progress.enabled\">\n {{historyMessage.media.audio.duration | duration}}\n </span>\n <span class=\"im_message_audio_size\" ng-if=\"historyMessage.media.audio.progress.enabled\">\n {{historyMessage.media.audio.progress | formatSizeProgress}}\n </span>\n </div>\n <div class=\"im_message_audio_actions\" ng-if=\"!historyMessage.media.audio.progress.enabled && !historyMessage.media.audio.url\">\n <a href=\"\" ng-click=\"openAudio(historyMessage.media.audio.id)\">Play</a>\n </div>\n <div class=\"im_message_download_progress_wrap\" ng-if=\"historyMessage.media.audio.progress.enabled\">\n <div class=\"progress tg_down_progress\">\n <div class=\"progress-bar progress-bar-success\" role=\"progressbar\" aria-valuenow=\"{{historyMessage.media.audio.progress.percent}}\" aria-valuemin=\"0\" aria-valuemax=\"100\" style=\"width: {{historyMessage.media.audio.progress.percent}}%\">\n <span class=\"sr-only\">\n {{historyMessage.media.audio.progress.percent}}% Complete (success)\n </span>\n </div>\n </div>\n </div>\n <div class=\"im_message_audio_player_wrap\" ng-if=\"historyMessage.media.audio.url\">\n <audio my-audio-autoplay audio=\"historyMessage.media.audio\" controls=\"controls\">\n <source ng-src=\"{{historyMessage.media.audio.url}}\" type=\"audio/mpeg\" />\n <embed hidden=\"true\" autostart=\"true\" loop=\"false\" src=\"{{historyMessage.media.audio.url}}\" />\n </audio>\n </div>\n </div>\n </div>\n\n <a ng-switch-when=\"messageMediaGeo\" my-map-point point=\"historyMessage.media.geo\" class=\"im_message_geopoint\">\n <i class=\"icon icon-geo-point\"></i>\n </a>\n\n <div ng-switch-when=\"messageMediaContact\">\n <a ng-click=\"openUser(historyMessage.media.user.id)\" class=\"im_message_contact_photo pull-left\" ng-if=\"historyMessage.media.user\">\n <img\n class=\"im_message_contact_photo\"\n my-load-thumb\n thumb=\"historyMessage.media.userPhoto\"\n />\n </a>\n <div class=\"im_message_contact_name\"><span class=\"glyphicon glyphicon-user\"></span>\n {{historyMessage.media.first_name}} {{historyMessage.media.last_name}}\n </div>\n <div class=\"im_message_contact_phone\">\n {{historyMessage.media.phone_number}}\n </div>\n </div>\n\n <div ng-switch-when=\"messageMediaPending\" class=\"im_message_upload_file im_message_upload_{{historyMessage.media.type}}\">\n <i class=\"icon icon-{{historyMessage.media.type}}\"></i>\n <div class=\"im_message_document_info\">\n <div class=\"im_message_document_name_wrap\">\n <span class=\"im_message_document_name\">\n {{historyMessage.media.file_name}}\n </span>\n <span class=\"im_message_document_size\" ng-if=\"historyMessage.media.progress\">\n {{historyMessage.media.progress | formatSizeProgress}}\n </span>\n </div>\n <div class=\"im_message_download_progress_wrap\">\n <div class=\"progress tg_down_progress\">\n <div class=\"progress-bar progress-bar-success\" role=\"progressbar\" aria-valuenow=\"{{historyMessage.media.progress.percent}}\" aria-valuemin=\"0\" aria-valuemax=\"100\" style=\"width: {{historyMessage.media.progress.percent}}%\">\n <span class=\"sr-only\">\n {{historyMessage.media.progress.percent}}% Complete (success)\n </span>\n </div>\n </div>\n </div>\n </div>\n </div>\n\n\n </div>\n\n <div class=\"im_message_text\" ng-if=\"historyMessage.message.length\" ng-bind-html=\"historyMessage.richMessage\"></div>\n </div>\n\n </div>\n </div>\n\n</div>\n\n"); |
||
$templateCache.put("partials/peer_select.html","<div class=\"peer_select_modal_wrap\">\n\n <div class=\"modal-header\">\n <a class=\"modal-close-link\" ng-click=\"$close()\">Close</a>\n <h4 class=\"modal-title\">Select conversation</h4>\n </div>\n\n <div class=\"modal-body\">\n\n <div class=\"im_dialogs_modal_col_wrap\" ng-controller=\"AppImDialogsController\">\n <div class=\"im_dialogs_search\">\n <input class=\"form-control im_dialogs_search_field\" type=\"search\" placeholder=\"Search\" ng-model=\"search.query\"/>\n <a class=\"im_dialogs_search_clear\" ng-click=\"search.query = \'\'\" ng-show=\"search.query.length\"></a>\n </div>\n <div my-dialogs-list modal=\"true\" class=\"im_dialogs_modal_col\">\n <div class=\"im_dialogs_wrap nano\">\n <div class=\"im_dialogs_scrollable_wrap content\">\n <ul class=\"nav nav-pills nav-stacked\">\n <li class=\"im_dialog_wrap\" my-dialog dialog-message=\"dialogMessage\" ng-repeat=\"dialogMessage in dialogs track by dialogMessage.peerID\"></li>\n </ul>\n </div>\n </div>\n </div>\n </div>\n\n </div>\n\n</div>"); |
||
$templateCache.put("partials/photo_modal.html","<div class=\"media_modal_wrap photo_modal_wrap\">\n\n <div class=\"modal-body\">\n\n <div class=\"photo_modal_image_wrap\" my-load-full-photo full-photo=\"photo.full\" thumb-location=\"photo.thumb.location\" ng-click=\"$close()\"> </div>\n\n <p class=\"media_modal_info\">From: <span class=\"media_modal_author\" ng-bind-html=\"photo.fromUser.rFullName\" ></span>, {{photo.date | dateOrTime}}</p>\n\n </div>\n\n</div>"); |
||
$templateCache.put("partials/settings_modal.html","<div class=\"settings_modal_wrap\">\n\n <div class=\"modal-header\">\n <a class=\"modal-close-link\" ng-click=\"$close()\">Close</a>\n <h4 class=\"modal-title\">Settings</h4>\n </div>\n\n <div class=\"modal-body\">\n\n <div class=\"clearfix\">\n\n <div class=\"settings_profile_photo_wrap pull-left\">\n\n <div class=\"settings_profile_photo\">\n <img\n class=\"user_modal_image\"\n my-load-thumb\n thumb=\"profile.photo\"\n />\n <div class=\"settings_profile_photo_change_wrap\">\n <div ng-if=\"photo.updating\" class=\"settings_profile_photo_loading\">Updating<span my-typing-dots></span></div>\n <div ng-if=\"!photo.updating\">\n <div class=\"settings_profile_photo_update_link\">\n <input my-file-upload type=\"file\" multiple=\"false\" class=\"im_attach_input\" size=\"120\" multiple=\"false\" accept=\"image/x-png, image/png, image/gif, image/jpeg\" />\n Update photo\n </div>\n <a ng-if=\"profile.photo.location\" href=\"\" ng-click=\"deletePhoto()\" class=\"settings_profile_photo_delete_link\">Delete photo</a>\n </div>\n </div>\n </div>\n\n </div>\n\n <form my-settings-form name=\"profileForm\" class=\"settings_profile_edit_form\">\n\n <div class=\"form-group settings_profile_first_name\" ng-class=\"{\'has-error\': error.field == \'first_name\'}\">\n <label class=\"control-label\" for=\"first_name\">\n <span ng-if=\"error.field == \'first_name\'\">Invalid First Name</span>\n <span ng-if=\"error.field != \'first_name\'\">First Name</span>\n </label>\n <input type=\"text\" class=\"form-control\" name=\"first_name\" ng-model=\"profile.first_name\" required />\n </div>\n\n <div class=\"form-group settings_profile_last_name\" ng-class=\"{\'has-error\': error.field == \'last_name\'}\">\n <label class=\"control-label\" for=\"last_name\">\n <span ng-if=\"error.field == \'last_name\'\">Invalid Last Name</span>\n <span ng-if=\"error.field != \'last_name\'\">Last Name</span>\n </label>\n <input type=\"text\" class=\"form-control\" name=\"last_name\" ng-model=\"profile.last_name\" />\n </div>\n\n <div class=\"settings_profile_save\">\n <button class=\"btn btn-link settings_profile_save_btn\" ng-click=\"save(profileForm)\" ng-disabled=\"profileForm.$invalid || (!profileForm.last_name.$dirty && !profileForm.first_name.$dirty)\">Save</button>\n </div>\n\n </form>\n\n </div>\n\n <form class=\"settings_send_choose_form\">\n <div class=\"radio\">\n <label>\n <input type=\"radio\" value=\"1\" ng-model=\"send.enter\">\n <strong>Enter</strong> - send message, <strong>Shift + Enter</strong> - new line\n </label>\n </div>\n <div class=\"radio\">\n <label>\n <input type=\"radio\" value=\"\" ng-model=\"send.enter\">\n <strong>Ctrl + Enter</strong> - send message, <strong>Enter</strong> - new line\n </label>\n </div>\n </form>\n\n <p>\n <strong>Sound: </strong>\n <a ng-click=\"notify.sound = !notify.sound\">{{notify.sound ? \'ON\' : \'OFF\'}}</a>\n </p>\n\n <p>\n <strong>Desktop Notifications: </strong>\n <a ng-click=\"notify.desktop = !notify.desktop\">{{notify.desktop ? \'ON\' : \'OFF\'}}</a>\n </p>\n\n <p>\n <strong>User: </strong>\n <span class=\"settings_user_phone\">{{phone | phoneNumber}}</span>\n </p>\n\n <p>\n <strong>Version: </strong>\n <span class=\"settings_version\">alpha 0.0.20</span>\n </p>\n\n <hr/>\n\n <div class=\"settings_logout_wrap\">\n <a href=\"\" ng-click=\"logOut()\">Log out</a>\n </div>\n </div>\n</div>\n"); |
||
$templateCache.put("partials/user_modal.html","<div class=\"user_modal_wrap\">\n\n <div class=\"modal-header\">\n <a class=\"modal-close-link\" ng-click=\"$close()\">Close</a>\n <h4 class=\"modal-title\">Info</h4>\n </div>\n\n\n <div class=\"modal-body\">\n\n <div class=\"user_modal_image_wrap pull-left\">\n <img\n class=\"user_modal_image\"\n my-load-thumb\n thumb=\"user.thumb\"\n />\n </div>\n\n <div class=\"user_modal_info_wrap clearfix\">\n <h4 class=\"user_modal_header\">{{user | userName}}</h4>\n <p class=\"user_modal_status\" ng-if=\"user.status\">{{user | userStatus}}</p>\n\n <p class=\"user_modal_phone\" ng-if=\"user.phone\">{{user.phone | phoneNumber}}</p>\n <button class=\"btn btn-primary user_modal_send_btn\" ng-click=\"goToHistory()\">Send message</button>\n </div>\n\n <div class=\"user_modal_settings_wrap\">\n <div class=\"user_modal_notifications\">\n Notifications:\n <a ng-click=\"settings.notifications = !settings.notifications\">\n {{settings.notifications ? \'ON\' : \'OFF\'}}\n </a>\n </div>\n </div>\n\n </div>\n\n</div>"); |
||
$templateCache.put("partials/video_modal.html","<div class=\"media_modal_wrap video_modal_wrap\">\n\n <div class=\"modal-body\">\n\n <div class=\"video_modal_image_wrap\" my-load-video video=\"video\"></div>\n\n <p class=\"media_modal_info\">From: <span class=\"media_modal_author\" ng-bind-html=\"video.fromUser.rFullName\"></span>, {{video.date | dateOrTime}}</p>\n\n </div>\n\n</div>"); |
||
$templateCache.put("partials/welcome.html","<div ng-include=\"\'partials/head.html\'\"></div>\n\n\n<div ng-show=\"showWelcome\">\n\n <div class=\"welcome_logo\"></div>\n\n <div class=\"welcome_box_wrap\">\n <div class=\"welcome_text\">\n <p>Welcome to an unofficial web-client of mobile <strong>Telegram</strong> messenger.</p>\n <p>It is an alpha, which means it is still not 200% secure and functional.</p>\n <p>Visit <a target=\"_blank\" href=\"https://telegram.org/\">telegram.org</a> to learn more.</p>\n </div>\n <a href=\"#/login\" class=\"btn btn-success btn-block\">Start Messaging</a>\n </div>\n\n</div>\n");}]); |
||
/*! |
||
* Webogram v0.0.20 - messaging web application for MTProto |
||
* https://github.com/zhukov/webogram |
||
* Copyright (C) 2014 Igor Zhukov <[email protected]> |
||
* https://github.com/zhukov/webogram/blob/master/LICENSE |
||
*/ |
||
|
||
'use strict'; |
||
|
||
/* Directives */ |
||
|
||
|
||
angular.module('myApp.directives', ['myApp.filters']) |
||
.directive('myDialog', function() { |
||
return { |
||
restrict: 'AE', |
||
scope: true, |
||
translude: false, |
||
templateUrl: 'partials/dialog.html' |
||
}; |
||
}) |
||
|
||
.directive('myMessage', function() { |
||
return { |
||
restrict: 'AE', |
||
scope: true, |
||
translude: false, |
||
templateUrl: 'partials/message.html' |
||
}; |
||
}) |
||
|
||
.directive('myDialogsList', function($window, $timeout) { |
||
|
||
return { |
||
link: link |
||
}; |
||
|
||
|
||
function link (scope, element, attrs) { |
||
var dialogsWrap = $('.im_dialogs_wrap', element)[0], |
||
scrollableWrap = $('.im_dialogs_scrollable_wrap', element)[0], |
||
headWrap = $('.tg_page_head')[0], |
||
footer = $('.im_page_footer')[0], |
||
moreNotified = false; |
||
|
||
onContentLoaded(function () { |
||
$(dialogsWrap).nanoScroller({preventPageScrolling: true, tabIndex: -1, iOSNativeScrolling: true}); |
||
}); |
||
|
||
var updateScroller = function () { |
||
onContentLoaded(function () { |
||
$(dialogsWrap).nanoScroller(); |
||
}); |
||
} |
||
|
||
scope.$on('ui_dialogs_prepend', updateScroller); |
||
|
||
|
||
scope.$on('ui_dialogs_append', function () { |
||
onContentLoaded(function () { |
||
updateScroller(); |
||
moreNotified = false; |
||
}); |
||
}); |
||
|
||
scope.$on('ui_dialogs_change', function () { |
||
onContentLoaded(function () { |
||
updateScroller(); |
||
moreNotified = false; |
||
}); |
||
}); |
||
|
||
$(scrollableWrap).on('scroll', function (e) { |
||
// console.log('scroll', moreNotified); |
||
if (!moreNotified && scrollableWrap.scrollTop >= scrollableWrap.scrollHeight - scrollableWrap.clientHeight - 300) { |
||
// console.log('emit need more'); |
||
scope.$emit('dialogs_need_more'); |
||
moreNotified = true; |
||
} |
||
}); |
||
|
||
|
||
function updateSizes () { |
||
if (attrs.modal) { |
||
$(element).css({ |
||
height: $($window).height() - 200 |
||
}); |
||
updateScroller(); |
||
return; |
||
} |
||
|
||
if (!headWrap || !headWrap.offsetHeight) { |
||
headWrap = $('.tg_page_head')[0]; |
||
} |
||
if (!footer || !footer.offsetHeight) { |
||
footer = $('.im_page_footer')[0]; |
||
} |
||
$(element).css({ |
||
height: $($window).height() - footer.offsetHeight - (headWrap ? headWrap.offsetHeight : 44) - 72 |
||
}); |
||
|
||
updateScroller(); |
||
} |
||
|
||
$($window).on('resize', updateSizes); |
||
|
||
updateSizes(); |
||
setTimeout(updateSizes, 1000); |
||
}; |
||
|
||
}) |
||
|
||
.directive('myContactsList', function($window, $timeout) { |
||
|
||
return { |
||
link: link |
||
}; |
||
|
||
function link (scope, element, attrs) { |
||
var searchWrap = $('.contacts_modal_search')[0], |
||
panelWrap = $('.contacts_modal_panel')[0], |
||
contactsWrap = $('.contacts_wrap', element)[0]; |
||
|
||
onContentLoaded(function () { |
||
$(contactsWrap).nanoScroller({preventPageScrolling: true, tabIndex: -1, iOSNativeScrolling: true}); |
||
updateSizes(); |
||
}); |
||
|
||
function updateSizes () { |
||
$(element).css({ |
||
height: $($window).height() - (panelWrap && panelWrap.offsetHeight || 0) - (searchWrap && searchWrap.offsetHeight || 0) - 200 |
||
}); |
||
$(contactsWrap).nanoScroller(); |
||
} |
||
|
||
$($window).on('resize', updateSizes); |
||
scope.$on('contacts_change', function () { |
||
onContentLoaded(updateSizes) |
||
}); |
||
}; |
||
|
||
}) |
||
|
||
.directive('myHistory', function ($window, $timeout) { |
||
|
||
return { |
||
link: link |
||
}; |
||
|
||
function link (scope, element, attrs) { |
||
var historyWrap = $('.im_history_wrap', element)[0], |
||
historyMessagesEl = $('.im_history_messages', element)[0], |
||
historyEl = $('.im_history', element)[0], |
||
scrollableWrap = $('.im_history_scrollable_wrap', element)[0], |
||
scrollable = $('.im_history_scrollable', element)[0], |
||
panelWrap = $('.im_history_panel_wrap', element)[0], |
||
bottomPanelWrap = $('.im_bottom_panel_wrap', element)[0], |
||
sendFormWrap = $('.im_send_form_wrap', element)[0], |
||
headWrap = $('.tg_page_head')[0], |
||
footer = $('.im_page_footer')[0], |
||
sendForm = $('.im_send_form', element)[0], |
||
moreNotified = false; |
||
|
||
onContentLoaded(function () { |
||
scrollableWrap.scrollTop = scrollableWrap.scrollHeight; |
||
$(historyWrap).nanoScroller({preventPageScrolling: true, tabIndex: -1, iOSNativeScrolling: true}); |
||
}); |
||
|
||
var updateScroller = function (delay) { |
||
$timeout(function () { |
||
if (!$(scrollableWrap).hasClass('im_history_to_bottom')) { |
||
$(historyWrap).nanoScroller(); |
||
} |
||
}, delay || 0); |
||
} |
||
|
||
var transform = false, |
||
trs = ['transform', 'webkitTransform', 'MozTransform', 'msTransform', 'OTransform'], |
||
i = 0; |
||
for (i = 0; i < trs.length; i++) { |
||
if (trs[i] in historyMessagesEl.style) { |
||
transform = trs[i]; |
||
break; |
||
} |
||
} |
||
|
||
var animated = transform ? true : false, |
||
curAnimation = false; |
||
|
||
scope.$on('ui_history_append', function (e, options) { |
||
if (!atBottom && !options.my) { |
||
return; |
||
} |
||
if (animated) { |
||
$(scrollableWrap).stop(); |
||
} else { |
||
$(scrollable).css({bottom: 0}); |
||
$(scrollableWrap).addClass('im_history_to_bottom'); |
||
} |
||
|
||
var wasH = scrollableWrap.scrollHeight; |
||
onContentLoaded(function () { |
||
if (animated) { |
||
curAnimation = true; |
||
$(historyMessagesEl).removeClass('im_history_appending'); |
||
scrollableWrap.scrollTop = scrollableWrap.scrollHeight; |
||
$(historyMessagesEl).css(transform, 'translate(0px, ' + (scrollableWrap.scrollHeight - wasH) + 'px)'); |
||
setTimeout(function () { |
||
$(historyMessagesEl).addClass('im_history_appending'); |
||
$(historyMessagesEl).css(transform, 'translate(0px, 0px)'); |
||
setTimeout(function () { |
||
curAnimation = false; |
||
$(historyMessagesEl).removeClass('im_history_appending'); |
||
updateBottomizer(); |
||
}, 300); |
||
}, 0); |
||
} else { |
||
$(scrollableWrap).removeClass('im_history_to_bottom'); |
||
$(scrollable).css({bottom: ''}); |
||
scrollableWrap.scrollTop = scrollableWrap.scrollHeight; |
||
updateBottomizer(); |
||
} |
||
$(historyWrap).nanoScroller(); |
||
}); |
||
}); |
||
|
||
scope.$on('ui_history_change', function () { |
||
$(scrollableWrap).addClass('im_history_to_bottom'); |
||
$(scrollable).css({bottom: 0}); |
||
onContentLoaded(function () { |
||
$(scrollableWrap).removeClass('im_history_to_bottom'); |
||
$(scrollable).css({bottom: ''}); |
||
updateSizes(true); |
||
|
||
var unreadSplit = $('.im_message_unread_split', scrollableWrap); |
||
if (unreadSplit[0]) { |
||
scrollableWrap.scrollTop = Math.max(0, unreadSplit[0].offsetTop - 52); |
||
atBottom = false; |
||
} else { |
||
scrollableWrap.scrollTop = scrollableWrap.scrollHeight; |
||
} |
||
|
||
updateScroller(); |
||
moreNotified = false; |
||
}); |
||
}); |
||
|
||
scope.$on('ui_history_focus', function () { |
||
if (!atBottom) { |
||
scrollableWrap.scrollTop = scrollableWrap.scrollHeight; |
||
updateScroller(); |
||
atBottom = true; |
||
} |
||
}); |
||
|
||
scope.$on('ui_history_prepend', function () { |
||
var sh = scrollableWrap.scrollHeight, |
||
st = scrollableWrap.scrollTop, |
||
ch = scrollableWrap.clientHeight; |
||
|
||
$(scrollableWrap).addClass('im_history_to_bottom'); |
||
$(scrollable).css({bottom: -(sh - st - ch)}); |
||
|
||
onContentLoaded(function () { |
||
$(scrollableWrap).removeClass('im_history_to_bottom'); |
||
$(scrollable).css({bottom: ''}); |
||
scrollableWrap.scrollTop = st + scrollableWrap.scrollHeight - sh; |
||
|
||
updateScroller(); |
||
moreNotified = false; |
||
|
||
$timeout(function () { |
||
$(scrollableWrap).trigger('scroll'); |
||
}); |
||
}); |
||
}); |
||
|
||
scope.$on('ui_panel_update', function () { |
||
onContentLoaded(function () { |
||
updateSizes(); |
||
scope.$broadcast('ui_message_send'); |
||
|
||
$timeout(function () { |
||
$(scrollableWrap).trigger('scroll'); |
||
}); |
||
}); |
||
}); |
||
|
||
scope.$on('ui_editor_resize', updateSizes); |
||
|
||
var atBottom = true; |
||
$(scrollableWrap).on('scroll', function (e) { |
||
if ($(scrollableWrap).hasClass('im_history_to_bottom')) { |
||
return cancelEvent(e); |
||
} |
||
if (curAnimation) { |
||
return; |
||
} |
||
atBottom = scrollableWrap.scrollTop >= scrollableWrap.scrollHeight - scrollableWrap.clientHeight; |
||
|
||
if (!moreNotified && scrollableWrap.scrollTop <= 300) { |
||
moreNotified = true; |
||
scope.$emit('history_need_more'); |
||
} |
||
}); |
||
|
||
function updateSizes (heightOnly) { |
||
if ($(sendFormWrap).is(':visible')) { |
||
$(sendFormWrap).css({ |
||
height: $(sendForm).height() |
||
}); |
||
} |
||
|
||
if (!headWrap || !headWrap.offsetHeight) { |
||
headWrap = $('.tg_page_head')[0]; |
||
} |
||
if (!footer || !footer.offsetHeight) { |
||
footer = $('.im_page_footer')[0]; |
||
} |
||
var historyH = $($window).height() - panelWrap.offsetHeight - bottomPanelWrap.offsetHeight - (headWrap ? headWrap.offsetHeight : 44) - footer.offsetHeight; |
||
$(historyWrap).css({ |
||
height: historyH |
||
}); |
||
$(historyEl).css({ |
||
minHeight: historyH - 44 |
||
}); |
||
|
||
updateBottomizer(); |
||
|
||
|
||
if (heightOnly == true) return; |
||
if (atBottom) { |
||
onContentLoaded(function () { |
||
scrollableWrap.scrollTop = scrollableWrap.scrollHeight; |
||
updateScroller(); |
||
}); |
||
} |
||
updateScroller(100); |
||
} |
||
|
||
function updateBottomizer () { |
||
$(historyMessagesEl).css({marginTop: 0}); |
||
if (historyMessagesEl.offsetHeight <= scrollableWrap.offsetHeight) { |
||
$(historyMessagesEl).css({marginTop: (scrollableWrap.offsetHeight - historyMessagesEl.offsetHeight - 20 - 44) + 'px'}); |
||
} |
||
$(historyWrap).nanoScroller(); |
||
} |
||
|
||
$($window).on('resize', updateSizes); |
||
|
||
updateSizes(); |
||
onContentLoaded(updateSizes); |
||
} |
||
|
||
}) |
||
|
||
.directive('mySendForm', function ($timeout, AppConfigManager) { |
||
|
||
return { |
||
link: link, |
||
scope: { |
||
draftMessage: '=' |
||
} |
||
}; |
||
|
||
function link (scope, element, attrs) { |
||
var messageField = $('textarea', element)[0], |
||
fileSelects = $('input', element), |
||
dropbox = $('.im_send_dropbox_wrap', element)[0], |
||
emojiButton = $('.im_emoji_btn', element)[0], |
||
editorElement = messageField, |
||
dragStarted, dragTimeout, |
||
emojiArea = $(messageField).emojiarea({button: emojiButton, norealTime: true}), |
||
emojiMenu = $('.emoji-menu', element)[0], |
||
richTextarea = $('.emoji-wysiwyg-editor', element)[0]; |
||
|
||
if (richTextarea) { |
||
editorElement = richTextarea; |
||
$(richTextarea).addClass('form-control'); |
||
$(richTextarea).attr('placeholder', $(messageField).attr('placeholder')); |
||
|
||
var updatePromise; |
||
$(richTextarea).on('keyup', function (e) { |
||
updateHeight(); |
||
|
||
scope.draftMessage.text = richTextarea.innerText; |
||
|
||
$timeout.cancel(updatePromise); |
||
updatePromise = $timeout(updateValue, 1000); |
||
}); |
||
} |
||
|
||
fileSelects.on('change', function () { |
||
var self = this; |
||
scope.$apply(function () { |
||
scope.draftMessage.files = Array.prototype.slice.call(self.files); |
||
scope.draftMessage.isMedia = $(self).hasClass('im_media_attach_input'); |
||
setTimeout(function () { |
||
try { |
||
self.value = ''; |
||
} catch (e) {}; |
||
}, 1000); |
||
}); |
||
}); |
||
|
||
var sendOnEnter = true, |
||
updateSendSettings = function () { |
||
AppConfigManager.get('send_ctrlenter').then(function (sendOnCtrl) { |
||
sendOnEnter = !sendOnCtrl; |
||
}); |
||
}; |
||
|
||
scope.$on('settings_changed', updateSendSettings); |
||
updateSendSettings(); |
||
|
||
$(editorElement).on('keydown', function (e) { |
||
if (richTextarea) { |
||
updateHeight(); |
||
} |
||
|
||
if (e.keyCode == 13) { |
||
var submit = false; |
||
if (sendOnEnter && !e.shiftKey) { |
||
submit = true; |
||
} else if (!sendOnEnter && (e.ctrlKey || e.metaKey)) { |
||
submit = true; |
||
} |
||
|
||
if (submit) { |
||
$(element).trigger('submit'); |
||
return cancelEvent(e); |
||
} |
||
} |
||
|
||
}); |
||
|
||
var lastTyping = 0; |
||
$(editorElement).on('keyup', function (e) { |
||
var now = tsNow(); |
||
if (now - lastTyping < 5000) { |
||
return; |
||
} |
||
lastTyping = now; |
||
scope.$emit('ui_typing'); |
||
}); |
||
|
||
function updateField () { |
||
if (richTextarea) { |
||
$timeout.cancel(updatePromise); |
||
var html = $('<div>').text(scope.draftMessage.text || '').html(); |
||
html = html.replace(/\n/g, '<br/>'); |
||
$(richTextarea).html(html); |
||
updateHeight(); |
||
} |
||
} |
||
|
||
function updateValue () { |
||
if (richTextarea) { |
||
$(richTextarea).trigger('change'); |
||
updateHeight(); |
||
} |
||
} |
||
|
||
var height = richTextarea.offsetHeight; |
||
function updateHeight () { |
||
var newHeight = richTextarea.offsetHeight; |
||
if (height != newHeight) { |
||
height = newHeight; |
||
scope.$emit('ui_editor_resize'); |
||
} |
||
}; |
||
|
||
$('body').on('dragenter dragleave dragover drop', onDragDropEvent); |
||
$(document).on('paste', onPasteEvent); |
||
if (richTextarea) { |
||
$(richTextarea).on('DOMNodeInserted', onPastedImageEvent); |
||
} |
||
|
||
scope.$on('ui_peer_change', focusField); |
||
scope.$on('ui_history_focus', focusField); |
||
scope.$on('ui_history_change', focusField); |
||
scope.$on('ui_message_send', focusField); |
||
scope.$on('ui_peer_draft', updateField); |
||
scope.$on('ui_message_before_send', updateValue); |
||
|
||
|
||
scope.$on('$destroy', function cleanup() { |
||
$('body').off('dragenter dragleave dragover drop', onDragDropEvent); |
||
$(document).off('paste', onPasteEvent); |
||
if (richTextarea) { |
||
$(richTextarea).off('DOMNodeInserted', onPastedImageEvent); |
||
} |
||
}); |
||
|
||
focusField(); |
||
|
||
function focusField () { |
||
onContentLoaded(function () { |
||
editorElement.focus(); |
||
}); |
||
} |
||
|
||
function onPastedImageEvent (e) { |
||
var element = e && e.target; |
||
var src; |
||
if (element && (src = element.src) && src.indexOf('data') === 0) { |
||
element.parentNode.removeChild(element); |
||
src = src.substr(5).split(';'); |
||
var contentType = src[0]; |
||
var base64 = atob(src[1].split(',')[1]); |
||
var array = new Uint8Array(base64.length); |
||
|
||
for (var i = 0; i < base64.length; i++) { |
||
array[i] = base64.charCodeAt(i); |
||
} |
||
|
||
var blob = new Blob([array], {type: contentType}); |
||
|
||
if (safeConfirm('Are you sure to send file(s) from clipboard?')) { |
||
scope.$apply(function () { |
||
scope.draftMessage.files = [blob]; |
||
scope.draftMessage.isMedia = true; |
||
}); |
||
} |
||
} |
||
}; |
||
|
||
function onPasteEvent (e) { |
||
var cData = (e.originalEvent || e).clipboardData, |
||
items = cData && cData.items || [], |
||
files = [], |
||
i; |
||
|
||
for (i = 0; i < items.length; i++) { |
||
if (items[i].kind == 'file') { |
||
files.push(items[i].getAsFile()); |
||
} |
||
} |
||
|
||
if (files.length && safeConfirm('Are you sure to send file(s) from clipboard?')) { |
||
scope.$apply(function () { |
||
scope.draftMessage.files = files; |
||
scope.draftMessage.isMedia = true; |
||
}); |
||
} |
||
} |
||
|
||
function onDragDropEvent(e) { |
||
var dragStateChanged = false; |
||
if (!dragStarted || dragStarted == 1) { |
||
dragStarted = checkDragEvent(e) ? 2 : 1; |
||
dragStateChanged = true; |
||
} |
||
if (dragStarted == 2) { |
||
if (dragTimeout) { |
||
setTimeout(function () { |
||
clearTimeout(dragTimeout); |
||
dragTimeout = false; |
||
}, 0); |
||
} |
||
|
||
if (e.type == 'dragenter' || e.type == 'dragover') { |
||
if (dragStateChanged) { |
||
$(dropbox) |
||
.css({height: $(editorElement).height() + 12, width: $(editorElement).width() + 12}) |
||
.show(); |
||
} |
||
} else { |
||
if (e.type == 'drop') { |
||
scope.$apply(function () { |
||
scope.draftMessage.files = Array.prototype.slice.call(e.originalEvent.dataTransfer.files); |
||
scope.draftMessage.isMedia = true; |
||
}); |
||
} |
||
dragTimeout = setTimeout(function () { |
||
$(dropbox).hide(); |
||
dragStarted = false; |
||
dragTimeout = false; |
||
}, 300); |
||
} |
||
} |
||
|
||
return cancelEvent(e); |
||
}; |
||
} |
||
|
||
}) |
||
|
||
.directive('myLoadThumb', function(MtpApiFileManager) { |
||
|
||
return { |
||
link: link, |
||
scope: { |
||
thumb: '=' |
||
} |
||
}; |
||
|
||
function link (scope, element, attrs) { |
||
var counter = 0; |
||
|
||
var cachedSrc = MtpApiFileManager.getCachedFile( |
||
scope.thumb && |
||
scope.thumb.location && |
||
!scope.thumb.location.empty && |
||
scope.thumb.location |
||
); |
||
|
||
if (cachedSrc) { |
||
element.attr('src', cachedSrc); |
||
} |
||
|
||
scope.$watchCollection('thumb.location', function (newLocation) { |
||
// console.log('new loc', newLocation, arguments); |
||
var counterSaved = ++counter; |
||
if (!newLocation || newLocation.empty) { |
||
element.attr('src', scope.thumb && scope.thumb.placeholder || 'img/blank.gif'); |
||
return; |
||
} |
||
|
||
var cachedSrc = MtpApiFileManager.getCachedFile(newLocation); |
||
if (cachedSrc) { |
||
element.attr('src', cachedSrc); |
||
return; |
||
} |
||
|
||
if (!element.attr('src')) { |
||
element.attr('src', scope.thumb.placeholder || 'img/blank.gif'); |
||
} |
||
|
||
MtpApiFileManager.downloadSmallFile(scope.thumb.location, scope.thumb.size).then(function (url) { |
||
if (counterSaved == counter) { |
||
element.attr('src', url); |
||
} |
||
}, function (e) { |
||
console.log('Download image failed', e, scope.thumb.location); |
||
if (counterSaved == counter) { |
||
element.attr('src', scope.thumb.placeholder || 'img/blank.gif'); |
||
} |
||
}); |
||
}) |
||
|
||
} |
||
|
||
}) |
||
|
||
.directive('myLoadFullPhoto', function(MtpApiFileManager) { |
||
|
||
return { |
||
link: link, |
||
transclude: true, |
||
template: |
||
'<div class="img_fullsize_with_progress_wrap" ng-style="{width: fullPhoto.width + \'px\', height: fullPhoto.height + \'px\'}">\ |
||
<div class="img_fullsize_progress_overlay" ng-show="progress.enabled">\ |
||
<div class="img_fullsize_progress_wrap" ng-style="{width: fullPhoto.width + \'px\', height: fullPhoto.height + \'px\'}">\ |
||
<div class="img_fullsize_progress progress tg_progress">\ |
||
<div class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="{{progress.percent}}" aria-valuemin="0" aria-valuemax="100" style="width: {{progress.percent}}%">\ |
||
<span class="sr-only">{{progress.percent}}% Complete (success)</span>\ |
||
</div>\ |
||
</div>\ |
||
</div>\ |
||
</div>\ |
||
<div class="photo_full_wrap">\ |
||
<a class="photo_modal_image">\ |
||
<img class="photo_modal_image" width="{{fullPhoto.width}}" height="{{fullPhoto.height}}" />\ |
||
</a>\ |
||
</div>\ |
||
<div class="photo_modal_error_wrap" ng-if="error">\ |
||
<div class="photo_modal_error" ng-if="error.html" ng-bind-html="error.html"></div>\ |
||
<div class="photo_modal_error" ng-if="error.text">{{error.text}}</div>\ |
||
</div>\ |
||
</div>', |
||
scope: { |
||
fullPhoto: '=', |
||
thumbLocation: '=' |
||
} |
||
}; |
||
|
||
function link (scope, element, attrs) { |
||
|
||
var imgElement = $('img', element); |
||
|
||
imgElement |
||
.attr('src', MtpApiFileManager.getCachedFile(scope.thumbLocation) || 'img/blank.gif') |
||
.addClass('thumb_blurred') |
||
.addClass('thumb_blur_animation'); |
||
|
||
if (!scope.fullPhoto.location) { |
||
return; |
||
} |
||
|
||
|
||
var apiPromise; |
||
if (scope.fullPhoto.size) { |
||
var inputLocation = { |
||
_: 'inputFileLocation', |
||
volume_id: scope.fullPhoto.location.volume_id, |
||
local_id: scope.fullPhoto.location.local_id, |
||
secret: scope.fullPhoto.location.secret |
||
}; |
||
apiPromise = MtpApiFileManager.downloadFile(scope.fullPhoto.location.dc_id, inputLocation, scope.fullPhoto.size); |
||
} else { |
||
apiPromise = MtpApiFileManager.downloadSmallFile(scope.fullPhoto.location); |
||
} |
||
|
||
scope.progress = {enabled: true, percent: 1}; |
||
|
||
apiPromise.then(function (url) { |
||
scope.progress.enabled = false; |
||
imgElement |
||
.attr('src', url) |
||
.removeClass('thumb_blurred'); |
||
|
||
}, function (e) { |
||
console.log('Download image failed', e, scope.fullPhoto.location); |
||
scope.progress.enabled = false; |
||
|
||
if (e && e.type == 'FS_BROWSER_UNSUPPORTED') { |
||
scope.error = {html: 'Your browser doesn\'t support <a href="https://developer.mozilla.org/en-US/docs/Web/API/LocalFileSystem" target="_blank">LocalFileSystem</a> feature which is needed to display this image.<br/>Please, install <a href="http://google.com/chrome" target="_blank">Google Chrome</a> or use <a href="https://telegram.org/" target="_blank">mobile app</a> instead.'}; |
||
} else { |
||
scope.error = {text: 'Download failed', error: e}; |
||
} |
||
}, function (progress) { |
||
scope.progress.percent = Math.max(1, Math.floor(100 * progress.done / progress.total)); |
||
}); |
||
} |
||
|
||
}) |
||
|
||
|
||
.directive('myLoadVideo', function($sce, MtpApiFileManager) { |
||
|
||
return { |
||
link: link, |
||
transclude: true, |
||
template: |
||
'<div class="img_fullsize_with_progress_wrap" ng-style="{width: video.full.width + \'px\', height: video.full.height + \'px\'}">\ |
||
<div class="img_fullsize_progress_overlay" ng-show="progress.enabled">\ |
||
<div class="img_fullsize_progress_wrap" ng-style="{width: video.full.width + \'px\', height: video.full.height + \'px\'}">\ |
||
<div class="img_fullsize_progress progress tg_progress">\ |
||
<div class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="{{progress.percent}}" aria-valuemin="0" aria-valuemax="100" style="width: {{progress.percent}}%">\ |
||
<span class="sr-only">{{progress.percent}}% Complete (success)</span>\ |
||
</div>\ |
||
</div>\ |
||
</div>\ |
||
</div>\ |
||
<div class="img_fullsize_wrap" ng-if="!player.src">\ |
||
<img\ |
||
class="img_fullsize"\ |
||
my-load-thumb\ |
||
thumb="video.thumb"\ |
||
width="{{video.full.width}}"\ |
||
height="{{video.full.height}}"\ |
||
/>\ |
||
</div>\ |
||
<div class="video_full_player" ng-if="player.src">\ |
||
<embed ng-src="{{player.src}}" width="{{video.full.width}}" height="{{video.full.height}}" autoplay="true" CONTROLLER="TRUE" SHOWCONTROLS="TRUE" controller="true" loop="false" pluginspace="http://www.apple.com/quicktime/" ng-if="player.quicktime"/>\ |
||
<video width="{{video.full.width}}" height="{{video.full.height}}" controls autoplay ng-if="!player.quicktime">\ |
||
<source ng-src="{{player.src}}" type="video/mp4">\ |
||
</video>\ |
||
</div>\ |
||
<div class="video_full_error_wrap" ng-if="error">\ |
||
<div class="video_full_error" ng-if="error.html" ng-bind-html="error.html"></div>\ |
||
<div class="video_full_error" ng-if="error.text">{{error.text}}</div>\ |
||
</div>\ |
||
</div>', |
||
scope: { |
||
video: '=' |
||
} |
||
}; |
||
|
||
function link (scope, element, attrs) { |
||
|
||
scope.progress = {enabled: true, percent: 1}; |
||
scope.player = {}; |
||
|
||
var inputLocation = { |
||
_: 'inputVideoFileLocation', |
||
id: scope.video.id, |
||
access_hash: scope.video.access_hash |
||
}; |
||
|
||
var hasQt = false, i; |
||
if (navigator.plugins) { |
||
for (i = 0; i < navigator.plugins.length; i++) { |
||
if (navigator.plugins[i].name.indexOf('QuickTime') >= 0) { |
||
hasQt = true; |
||
} |
||
} |
||
} |
||
|
||
MtpApiFileManager.downloadFile(scope.video.dc_id, inputLocation, scope.video.size, null, {mime: 'video/mp4'}).then(function (url) { |
||
scope.progress.enabled = false; |
||
// scope.progress = {enabled: true, percent: 50}; |
||
scope.player.hasQuicktime = hasQt; |
||
scope.player.quicktime = false; |
||
scope.player.src = $sce.trustAsResourceUrl(url); |
||
}, function (e) { |
||
console.log('Download video failed', e, scope.video); |
||
scope.progress.enabled = false; |
||
scope.player.src = ''; |
||
|
||
if (e && e.type == 'FS_BROWSER_UNSUPPORTED') { |
||
scope.error = {html: 'Your browser doesn\'t support <a href="https://developer.mozilla.org/en-US/docs/Web/API/LocalFileSystem" target="_blank">LocalFileSystem</a> feature which is needed to play this video.<br/>Please, install <a href="http://google.com/chrome" target="_blank">Google Chrome</a> or use <a href="https://telegram.org/" target="_blank">mobile app</a> instead.'}; |
||
} else { |
||
scope.error = {text: 'Video download failed', error: e}; |
||
} |
||
|
||
}, function (progress) { |
||
scope.progress.percent = Math.max(1, Math.floor(100 * progress.done / progress.total)); |
||
}); |
||
} |
||
|
||
}) |
||
|
||
.directive('myMapPoint', function(ExternalResourcesManager) { |
||
|
||
return { |
||
link: link, |
||
scope: { |
||
point: '=' |
||
} |
||
}; |
||
|
||
function link (scope, element, attrs) { |
||
|
||
var apiKey = 'AIzaSyC32ij28dCa0YzEV_HqbWfIwTZQql-RNS0'; |
||
|
||
var src = 'https://maps.googleapis.com/maps/api/staticmap?sensor=false¢er=' + scope.point['lat'] + ',' + scope.point['long'] + '&zoom=13&size=200x100&scale=2&key=' + apiKey; |
||
|
||
ExternalResourcesManager.downloadImage(src).then(function (url) { |
||
element.append('<img src="' + url + '" width="200" height="100"/>'); |
||
}); |
||
|
||
element.attr('href','https://maps.google.com/?q=' + scope.point['lat'] + ',' + scope.point['long']); |
||
element.attr('target','_blank'); |
||
} |
||
|
||
}) |
||
|
||
|
||
.directive('myTypingDots', function($interval) { |
||
|
||
return { |
||
link: link, |
||
}; |
||
|
||
var interval; |
||
|
||
function link (scope, element, attrs) { |
||
var promise = $interval(function () { |
||
var time = tsNow(), |
||
cnt = 3; |
||
|
||
if (time % 1000 <= 200) { |
||
cnt = 0; |
||
} else if (time % 1000 <= 400) { |
||
cnt = 1; |
||
} else if (time % 1000 <= 600) { |
||
cnt = 2; |
||
} |
||
|
||
var text = '...', |
||
html = text.substr(0, cnt + 1) + (cnt < 2 ? ('<span class="text-invisible">' + text.substr(cnt + 1) + '</span>') : ''); |
||
|
||
element.html(html); |
||
}, 200); |
||
|
||
scope.$on('$destroy', function cleanup() { |
||
$interval.cancel(promise); |
||
}); |
||
} |
||
}) |
||
|
||
.directive('myAudioAutoplay', function() { |
||
|
||
return { |
||
link: link, |
||
scope: { |
||
audio: '=' |
||
} |
||
}; |
||
|
||
function link (scope, element, attrs) { |
||
scope.$watch('audio.autoplay', function (autoplay) { |
||
if (autoplay) { |
||
element.autoplay = true; |
||
element[0].play(); |
||
} else { |
||
element.autoplay = false; |
||
} |
||
}); |
||
} |
||
}) |
||
|
||
.directive('myFocused', function(){ |
||
return { |
||
link: function(scope, element, attrs) { |
||
setTimeout(function () { |
||
element[0].focus(); |
||
}, 100); |
||
} |
||
}; |
||
}) |
||
|
||
.directive('myFileUpload', function(){ |
||
|
||
return { |
||
link: link |
||
}; |
||
|
||
function link(scope, element, attrs) { |
||
element.on('change', function () { |
||
var self = this; |
||
scope.$apply(function () { |
||
scope.photo.file = self.files[0]; |
||
setTimeout(function () { |
||
try { |
||
self.value = ''; |
||
} catch (e) {}; |
||
}, 1000); |
||
}); |
||
}); |
||
}; |
||
});
|