From cc71b745c3c821f5e012a363ae3267252a81fddb Mon Sep 17 00:00:00 2001 From: Misko Hevery Date: Mon, 15 Mar 2010 14:36:50 -0700 Subject: [PATCH] added resources; removed compiled code --- .gitignore | 2 + angular-minified.js | 104 - angular.js | 4087 ----------------- example/memoryLeak.html | 47 +- jsTestDriver.conf | 2 +- .../{jasmine-0.10.0.js => jasmine-0.10.1.js} | 57 +- src/Angular.js | 54 +- src/Resource.js | 117 + src/Scope.js | 32 +- test/AngularSpec.js | 36 +- test/ResourceSpec.js | 159 + test/testabilityPatch.js | 7 +- 12 files changed, 451 insertions(+), 4253 deletions(-) delete mode 100644 angular-minified.js delete mode 100644 angular.js rename lib/jasmine/{jasmine-0.10.0.js => jasmine-0.10.1.js} (97%) create mode 100644 src/Resource.js create mode 100644 test/ResourceSpec.js diff --git a/.gitignore b/.gitignore index 90a1eea4..02403a60 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,4 @@ angular-minified.map externs.js +angular.js +angular-minified.js diff --git a/angular-minified.js b/angular-minified.js deleted file mode 100644 index 2056d81f..00000000 --- a/angular-minified.js +++ /dev/null @@ -1,104 +0,0 @@ -function G(){return function(){}}function L(p){return function(){return p}} -(function(p,x){function n(){}function M(a,b,c){var d=p.console;switch(arguments.length){case 1:d.log(a);break;case 2:d.log(a,b);break;default:d.log(a,b,c);break}}function aa(a,b,c){var d=p.console;switch(arguments.length){case 1:d.error(a);break;case 2:d.error(a,b);break;default:d.error(a,b,c);break}}function ia(a,b){var c=x.createElement("div");c.className=a;for(var d=a="",e=0;e/g,">")}function La(a){if(!a||!a.replace)return a;return a.replace(//g,">").replace(/\"/g,""")}function Ma(a,b){if(!a)throw"Missing this";if(!_.isFunction(b))throw"Missing function";return function(){return b.apply(a,arguments)}}function la(a){var b=x.createElement("div"); -b.appendChild(a);var c=b.innerHTML;b.removeChild(a);return c}function W(a){var b=(""+a).toLowerCase();if(b=="f"||b=="0"||b=="false"||b=="no")a=false;return!!a}function X(a,b){for(var c in a){var d=b[c],e=typeof d;if(e=="undefined")b[c]=N(v(a[c]));else e=="object"&&d.constructor!=array&&c.substring(0,1)!="$"&&X(a[c],d)}}function ma(a){this.location=a;this.delay=25;this.setTimeout=function(b,c){p.setTimeout(b,c)};this.Ka=function(b){return b};this.N=a.href}function Na(){var a=k.fn;a.scope=function(){for(var b= -this;b&&b.get(0);){var c=b.data("scope");if(c)return c;b=b.parent()}return null};a.controller=function(){return this.data("controller")||R.Kb}}function Oa(a){if(a.Gc=="console"&&!Q){Q=x.createElement("div");Q.id="ng-console";x.getElementsByTagName("body")[0].appendChild(Q);M=function(){ia("ng-console-info",arguments)};console.error=function(){ia("ng-console-error",arguments)}}}function ba(a,b){var c={};o(b,function(d,e){c[e]=_(d).bind(a)});return c}function Pa(a,b){var c=new na(b.server,b.database), -d=new t(a[0],c,h,b.location,b);d.sa.push(b.Nc);c=new S(a.find("body"),b.server,b.database);var e=b.database=="$MEMORY"?new ca(p):new oa(b.server,k.getScript);e=new pa(e,new qa(a.find("body")),function(){d.d()});var f=new ra(e,c),g="/data/"+b.database,h=new Y(function(l,q){e.P("POST",g,l,q)},f,d.anchor);d.l=h;d.sa.push(function(){h.W()});var i=new u({$anchor:d.anchor,$updateView:_(d.d).bind(d),$config:b,$invalidWidgets:[],$console:p.console,$datastore:ba(h,{load:h.load,loadMany:h.ma,loadOrCreate:h.Na, -loadAll:h.Ma,save:h.save,remove:h.remove,flush:h.W,query:h.Va,entity:h.G,entities:h.entities,documentCountsByUser:h.Bb,userDocumentIdsByEntity:h.sc,join:h.join}),$save:function(l){h.mc(i.j,l,d.anchor)},$window:p,$uid:function(){return""+(new Date).getTime()},$users:f},"ROOT");a.data("scope",i);d.G(i);d.compile();c.bind();(new z(a)).bind();var j=_(ba(i,{set:i.i,get:i.get,eval:i.eval})).extend({init:function(){b.location.listen(_(d.gc).bind(d));d.Sa();d.Fb();d.d();return j},element:a[0],updateView:_(d.d).bind(d), -config:b});return j}function H(a,b,c){var d=_.last(b);o(c,function(e){d[e]=_[e]});m[a]=m[a]||{};o(b,function(e){B(m[a],e)})}function t(a,b,c,d,e){this.F=a;this.location=d;this.l=c;this.anchor={};this.xc=b;this.vb=e||{};this.sa=[]}function S(a,b,c){this.hb=a;this.fa=b;this.ka=c;this.lb=p;this.H=[]}function Y(a,b,c){this.post=a;this.$a=b;this.K=[];this.ha={$collections:this.K};this.anchor=c;this.S=[]}function T(a,b){return{format:a,parse:b||a}}function sa(a){return""+a}function v(a,b){var c=[];da(c, -a,b?"\n ":null,_([]));return c.join("")}function N(a){try{var b=new E(a,true),c=b.da();b.L();return c()}catch(d){aa("fromJson error: ",a,d);throw d;}}function da(a,b,c,d){if(typeof b=="object"){if(d.include(b)){a.push("RECURSION");return}d.push(b)}var e=typeof b;if(b===null)a.push("null");else if(e==="function")return;else if(e==="boolean")a.push(""+b);else if(e==="number")isNaN(b)?a.push("null"):a.push(""+b);else if(e==="string")return a.push(m.String.quoteUnicode(b));else if(e==="object")if(b instanceof -Array){a.push("[");var f=b.length;e=false;for(var g=0;g>2;c=(c&3)<<4|d>>4;g=(d&15)<<2|e>>6;h=e&63;if(isNaN(d))g=h=64;else if(isNaN(e))h=64;b=b+this.B.charAt(f)+this.B.charAt(c)+this.B.charAt(g)+this.B.charAt(h)}return b},Hc:function(a){var b="",c,d,e,f,g,h=0;for(a=a.replace(/[^A-Za-z0-9\+\/\=]/g,"");h>4;d=(d&15)<<4|f>>2;e=(f&3)<<6|g;b+=String.fromCharCode(c);if(f!=64)b+=String.fromCharCode(d);if(g!=64)b+=String.fromCharCode(e)}return b=fa.jb(b)},kb:function(a){a=a.replace(/\r\n/g,"\n");for(var b="",c=0;c127&&d<2048)b+=String.fromCharCode(d>>6|192);else{b+=String.fromCharCode(d>>12|224);b+=String.fromCharCode(d>>6&63|128)}b+=String.fromCharCode(d&63|128)}}return b},jb:function(a){for(var b="",c=0,d=c1=c2= -0;c191&&d<224){c2=a.charCodeAt(c+1);b+=String.fromCharCode((d&31)<<6|c2&63);c+=2}else{c2=a.charCodeAt(c+1);c3=a.charCodeAt(c+2);b+=String.fromCharCode((d&15)<<12|(c2&63)<<6|c3&63);c+=3}}return b}};if(typeof x.getAttribute=="undefined")x.getAttribute=G();if(typeof Node=="undefined")Node={ELEMENT_NODE:1,ATTRIBUTE_NODE:2,TEXT_NODE:3,CDATA_SECTION_NODE:4,ENTITY_REFERENCE_NODE:5,ENTITY_NODE:6,PROCESSING_INSTRUCTION_NODE:7, -COMMENT_NODE:8,DOCUMENT_NODE:9,DOCUMENT_TYPE_NODE:10,DOCUMENT_FRAGMENT_NODE:11,NOTATION_NODE:12};p.console||(p.console={log:n,error:n});var Q,V,k=p.jQuery||p.$,o=_.each,B=_.extend,Ha=_.identity,m=p.angular||(p.angular={}),ga=m.validator||(m.validator={}),r=m.filter||(m.filter={}),ha=m.formatter||(m.formatter={}),P=m.callbacks||(m.callbacks={});m.alert||(m.alert=function(){M(arguments);p.alert.apply(p,arguments)});var Ia=Ia||function(a){return k(a).is(":visible")};ma.prototype={Pb:function(a){this.Ka= -a},watch:function(){var a=this;function b(){if(a.N!==a.location.href){var c=a.location.hash.match(/^#\$iframe_notify=(.*)$/);if(c){a.N.match(/#/)||(a.N+="#");a.location.href=a.N;c="_iframe_notify_"+c[1];var d=P[c];delete P[c];try{(d||n)()}catch(e){alert(e)}}else{a.Ka(a.location.href);a.N=a.location.href}}a.setTimeout(b,a.delay)}b()},i:function(a){var b=this.location.href;b.match(/#/)||(b+="#");if(b!=a)this.location.href=a;this.Kc=a},get:function(){return p.location.href}};m.startUrlWatcher=function(){var a= -new ma(p.location);a.watch();return ba(a,{listen:a.Pb,set:a.i,get:a.get})};m.compile=function(a,b){k=p.jQuery;V=k.browser.msie;b=_({onUpdateView:n,server:"",location:{get:n,set:n,listen:n}}).extend(b||{});Oa(b);Na();return Pa(k(a),b)};var J={typeOf:function(a){if(a===null)return"null";var b=typeof a;if(b=="object"){if(a instanceof Array)return"array";if(a instanceof Date)return"date";if(a.nodeType==1)return"element"}return b}},Z={},Ja={includeIf:function(a,b,c){var d=_.indexOf(a,b);if(c)d==-1&&a.push(b); -else a.splice(d,1);return a},sum:function(a,b){b=m.Function.compile(b);for(var c=0,d=0;d=0&&a.splice(c,1);return b},find:function(a,b,c){if(b){var d=m.Function.compile(b);_.detect(a,function(e){if(d(e)){c=e;return true}});return c}},findById:function(a,b){return m.zc.find(a,function(c){return c.bb==b},null)},filter:function(a,b){var c=[];c.tb=function(j){for(var l=0;l-1;case "object":for(var q in j)if(q.charAt(0)!=="$"&&e(j[q],l))return true;return false;case "array":for(q=0;q=0&&a.splice(d,1);a.unshift((c?"-":"+")+b);return a},orderByDirection:function(a,b,c,d){c=c||"ng-ascend";d=d||"ng-descend";a=a[0]||"";var e=true;if(a.charAt(0)=="-"){a=a.substring(1);e=false}else if(a.charAt(0)=="+")a=a.substring(1);return a==b?e?c:d:""},merge:function(a, -b,c){var d=a[b];if(!d){d={};a[b]=d}X(c,d);return a}},Qa={quote:function(a){return'"'+a.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\f/g,"\\f").replace(/\r/g,"\\r").replace(/\t/g,"\\t").replace(/\v/g,"\\v")+'"'},quoteUnicode:function(a){a=m.String.quote(a);for(var b=[],c=0;c-1;){c1||t.M(a[0])!==null};t.M=function(a){return(a=a.replace(/\n/gm," ").match(/^\{\{(.*)\}\}$/))?a[1]:null};t.prototype={hc:function(a){var b={};a.replace(/(?:^|&)([^&=]*)=?([^&]*)/g, -function(c,d,e){if(d)b[decodeURIComponent(d)]=decodeURIComponent(e)});return b},Sa:function(){var a=this,b=this.location.get()||"",c=b.indexOf("#");if(!(c<0)){b=this.hc(b.substring(c+1));o(a.anchor,function(d,e){delete a.anchor[e]});o(b,function(d,e){a.anchor[e]=d})}},gc:function(){this.Sa();this.d()},qc:function(){var a=this.location.get()||"",b=a.indexOf("#");if(b>-1)a=a.substring(0,b);a+="#";b="";for(var c in this.anchor){var d=this.anchor[c];if(typeof d==="undefined"||d===null)delete this.anchor[c]; -else{a+=b+encodeURIComponent(c);if(d!==true)a+="="+encodeURIComponent(d);b="&"}}this.location.set(a);return a},d:function(){(new Date).getTime();var a=k(this.F).scope();a.ub();a.d();(new Date).getTime();this.qc();o(this.sa,function(b){b()})},U:function(a){var b=k(this.F),c=b.find(a);if(b.is(a))c=c.andSelf();return c},Fb:function(){this.U("[ng-init]").each(function(){var a=k(this),b=a.scope();try{b.eval(a.attr("ng-init"))}catch(c){alert("EVAL ERROR:\n"+a.attr("ng-init")+"\n"+v(c,true))}})},G:function(a){var b= -this;this.U("[ng-entity]").attr("ng-watch",function(){try{var c=k(this);return a.G(c.attr("ng-entity"),b.l)+(c.attr("ng-watch")||"")}catch(d){M(d);alert(d)}})},compile:function(){var a=k(this.F);if(this.vb.autoSubmit){var b=this.U(":submit").not("[ng-action]");b.attr("ng-action","$save()");b.not(":disabled").not("ng-bind-attr").attr("ng-bind-attr",'{disabled:"{{$invalidWidgets}}"}')}this.Ta(this.F)(this.F,a.scope(),"");this.U("a[ng-action]").live("click",function(){var c=k(this),d=c.scope();try{d.eval(c.attr("ng-action")); -c.removeAttr("ng-error");c.removeClass("ng-exception")}catch(e){c.addClass("ng-exception");c.attr("ng-error",v(e,true))}d.get("$updateView")();return false})},pc:function(a,b,c){b=b.concat();var d=b.pop(),e=t.ba(a.nodeValue);if(e.length>1||t.M(e[0])){var f=a.parentNode;if(ja(f)){f.setAttribute("ng-bind-template",a.nodeValue);c.push({path:b,b:function(l){return new O(l,l.getAttribute("ng-bind-template"))}})}else for(var g=0;g2&&a.setAttribute("ng-bind-attr",d)}a.getAttribute||M(a);var j=a.getAttribute("ng-repeat");if(j){a.removeAttribute("ng-repeat");var l=this.Ta(a);d=x.createComment("ng-repeat: "+ -j);e=a.parentNode;e.insertBefore(d,a);e.removeChild(a);function q(w,A,y){var K=k(a).clone();K.css("display","");K.attr("ng-repeat-index",""+y);K.data("scope",w);l(K[0],w,A+y+":");return K}c.push({path:b,b:function(w,A,y){return new Ga(k(w),j,q,y)}})}else{a.getAttribute("ng-eval")&&c.push({path:b,b:this.Zb});a.getAttribute("ng-bind")&&c.push({path:b,b:this.Ra});a.getAttribute("ng-bind-attr")&&c.push({path:b,b:this.Vb});a.getAttribute("ng-hide")&&c.push({path:b,b:this.$b});a.getAttribute("ng-show")&& -c.push({path:b,b:this.ac});a.getAttribute("ng-class")&&c.push({path:b,b:this.Wb});a.getAttribute("ng-class-odd")&&c.push({path:b,b:this.Yb});a.getAttribute("ng-class-even")&&c.push({path:b,b:this.Xb});a.getAttribute("ng-style")&&c.push({path:b,b:this.bc});a.getAttribute("ng-watch")&&c.push({path:b,b:this.cc});d=a.nodeName;if(d=="INPUT"||d=="TEXTAREA"||d=="SELECT"||d=="BUTTON"){var C=this;c.push({path:b,b:function(w,A,y){w.name=y+w.name.split(":").pop();return C.xc.wb(k(w),A)}})}if(d=="OPTION")if(!k("')};B(U.prototype,{cancel:n,complete:n,httpStatus:function(a){alert("httpStatus:"+this.J+" status:"+a)},ioError:function(){alert("ioError:"+this.J)},open:function(){alert("open:"+this.J)},progress:n,securityError:function(){alert("securityError:"+this.J)},uploadCompleteData:function(a){a=N(a);a.url=this.ya+"/"+a.id+"/"+a.text;this.view.find("input").attr("checked",true);var b=this.view.scope();this.value=a;this.e(b);this.value=null},select:function(a,b){this.name=a;this.view.find("a").text(a).attr("href", -a);this.view.find("span").text(m.filter.bytes(b));this.upload()},e:function(a){var b=this.view.find("input").attr("checked")?this.value:null;if(this.c===b)return false;else{a.i(this.J,b);return true}},d:function(a){if((a=a.get(this.J))&&this.value!==a){this.value=a;this.view.find("a").attr("href",this.value.url).text(this.value.text);this.view.find("span").text(m.filter.bytes(this.value.size))}this.view.find("input").attr("checked",!!a)},upload:function(){this.name&&this.rc.uploadFile(this.ya)}}); -R.prototype={e:L(true),d:n};R.Kb=new R;var Sa=R;ta.prototype={e:function(a){var b=this.A.parse(this.view.value);if(this.c===b)return false;else{a.q(this.exp,b);this.c=b;return true}},d:function(a){var b=this.view,c=a.get(this.exp);if(typeof c==="undefined"){c=this.w;a.q(this.exp,c)}c=c?c:"";if(!_(this.c).isEqual(c)){b.value=this.A.format(c);this.c=c}var d=false;b.removeAttribute("ng-error");if(this.lc)d=!(c&&$.trim(""+c).length>0);var e=d?"Required Value":null;if(!d&&this.Q&&c){e=a.uc(this.Q,c,b); -d=!!e}if(this.Ja!==e){this.Ja=d;if(e&&Ia(b)){b.setAttribute("ng-error",e);a.Sb(this)}k(b).toggleClass("ng-validation-error",d)}}};ua.prototype={e:function(a){var b=this.view;b=b.checked?b.value:"";b=this.A.parse(b);b=this.A.format(b);if(this.c===b)return false;else{a.q(this.exp,this.A.parse(b));this.c=b;return true}},d:function(a){var b=this.view,c=a.eval(this.exp);if(typeof c==="undefined"){c=this.w;a.q(this.exp,c)}b.checked=this.A.parse(b.value)==c}};va.prototype={e:function(a){if(this.view.selectedIndex< -0)a.q(this.exp,null);else{var b=this.view.value;if(this.c===b)return false;else{a.q(this.exp,b);this.c=b;return true}}},d:function(a){var b=this.view,c=a.get(this.exp);if(typeof c==="undefined"){c=this.w;a.q(this.exp,c)}if(c!==this.c){b.value=c?c:"";this.c=c}}};wa.prototype={selected:function(){for(var a=[],b=this.view.options,c=0;cj;--b)this.children.pop().element.remove();if(g&&g.element[0].nodeName==="OPTION")if(b=k(g.element[0].parentNode).data("controller")){b.c=undefined;b.d(a)}})}};z.va="mouseleave mouseout click dblclick keypress keyup";z.fc=function(){z.pa();var a=k(this);a.bind(z.va,z.pa);var b=a.position(),c=x.documentElement,d=(self.innerWidth||c&&c.clientWidth||x.body.clientWidth)- -b.left;c=a.hasClass("ng-exception")?"EXCEPTION:":"Validation error...";a=a.attr("ng-error");d=d>375?"left":"right";c=k("
"+c+"
"+a+"
");k("body").append(c);if(d==="left")a=b.left+this.offsetWidth+11;else{a=b.left-315;c.find(".ng-arrow-right").css({left:301})}c.css({left:a+"px",top:b.top-3+"px"});return true};z.pa=function(){k("#ng-callout").unbind(z.va,z.pa).remove(); -return true};z.prototype={bind:function(){this.F.find(".ng-validation-error,.ng-exception").live("mouseover",z.fc)}};qa.prototype={za:G(),Ca:G()};ea.cb='
loading....
';ea.prototype={za:function(){if(this.ea===0)(this.Oa=this.Oa||this.body.append(ea.cb).find("#ng-loading")).show();this.ea++},Ca:function(){this.ea--;this.ea===0&&this.Oa.hide("fold")}}})(window,document); diff --git a/angular.js b/angular.js deleted file mode 100644 index da3301dd..00000000 --- a/angular.js +++ /dev/null @@ -1,4087 +0,0 @@ -/** - * The MIT License - * - * Copyright (c) 2010 Adam Abrons and Misko Hevery http://getangular.com - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -(function(window, document){ -/** -* -* Base64 encode / decode -* http://www.webtoolkit.info/ -* -**/ - -var Base64 = { - - // private property - _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=", - - // public method for encoding - encode : function (input) { - var output = ""; - var chr1, chr2, chr3, enc1, enc2, enc3, enc4; - var i = 0; - - input = Base64._utf8_encode(input); - - while (i < input.length) { - - chr1 = input.charCodeAt(i++); - chr2 = input.charCodeAt(i++); - chr3 = input.charCodeAt(i++); - - enc1 = chr1 >> 2; - enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); - enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); - enc4 = chr3 & 63; - - if (isNaN(chr2)) { - enc3 = enc4 = 64; - } else if (isNaN(chr3)) { - enc4 = 64; - } - - output = output + - this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) + - this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4); - - } - - return output; - }, - - // public method for decoding - decode : function (input) { - var output = ""; - var chr1, chr2, chr3; - var enc1, enc2, enc3, enc4; - var i = 0; - - input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ""); - - while (i < input.length) { - - enc1 = this._keyStr.indexOf(input.charAt(i++)); - enc2 = this._keyStr.indexOf(input.charAt(i++)); - enc3 = this._keyStr.indexOf(input.charAt(i++)); - enc4 = this._keyStr.indexOf(input.charAt(i++)); - - chr1 = (enc1 << 2) | (enc2 >> 4); - chr2 = ((enc2 & 15) << 4) | (enc3 >> 2); - chr3 = ((enc3 & 3) << 6) | enc4; - - output = output + String.fromCharCode(chr1); - - if (enc3 != 64) { - output = output + String.fromCharCode(chr2); - } - if (enc4 != 64) { - output = output + String.fromCharCode(chr3); - } - - } - - output = Base64._utf8_decode(output); - - return output; - - }, - - // private method for UTF-8 encoding - _utf8_encode : function (string) { - string = string.replace(/\r\n/g,"\n"); - var utftext = ""; - - for (var n = 0; n < string.length; n++) { - - var c = string.charCodeAt(n); - - if (c < 128) { - utftext += String.fromCharCode(c); - } - else if((c > 127) && (c < 2048)) { - utftext += String.fromCharCode((c >> 6) | 192); - utftext += String.fromCharCode((c & 63) | 128); - } - else { - utftext += String.fromCharCode((c >> 12) | 224); - utftext += String.fromCharCode(((c >> 6) & 63) | 128); - utftext += String.fromCharCode((c & 63) | 128); - } - - } - - return utftext; - }, - - // private method for UTF-8 decoding - _utf8_decode : function (utftext) { - var string = ""; - var i = 0; - var c = c1 = c2 = 0; - - while ( i < utftext.length ) { - - c = utftext.charCodeAt(i); - - if (c < 128) { - string += String.fromCharCode(c); - i++; - } - else if((c > 191) && (c < 224)) { - c2 = utftext.charCodeAt(i+1); - string += String.fromCharCode(((c & 31) << 6) | (c2 & 63)); - i += 2; - } - else { - c2 = utftext.charCodeAt(i+1); - c3 = utftext.charCodeAt(i+2); - string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)); - i += 3; - } - - } - - return string; - } - -};if (typeof document.getAttribute == 'undefined') - document.getAttribute = function() {}; -if (typeof Node == 'undefined') { - Node = { - ELEMENT_NODE : 1, - ATTRIBUTE_NODE : 2, - TEXT_NODE : 3, - CDATA_SECTION_NODE : 4, - ENTITY_REFERENCE_NODE : 5, - ENTITY_NODE : 6, - PROCESSING_INSTRUCTION_NODE : 7, - COMMENT_NODE : 8, - DOCUMENT_NODE : 9, - DOCUMENT_TYPE_NODE : 10, - DOCUMENT_FRAGMENT_NODE : 11, - NOTATION_NODE : 12 - }; -} - -function noop() {} -if (!window['console']) window['console']={'log':noop, 'error':noop}; - -var consoleNode, msie, - jQuery = window['jQuery'] || window['$'], // weirdness to make IE happy - foreach = _.each, - extend = _.extend, - identity = _.identity, - angular = window['angular'] || (window['angular'] = {}), - angularValidator = angular['validator'] || (angular['validator'] = {}), - angularFilter = angular['filter'] || (angular['filter'] = {}), - angularFormatter = angular['formatter'] || (angular['formatter'] = {}), - angularCallbacks = angular['callbacks'] || (angular['callbacks'] = {}), - angularAlert = angular['alert'] || (angular['alert'] = function(){ - log(arguments); window.alert.apply(window, arguments); - }); - -var isVisible = isVisible || function (element) { - return jQuery(element).is(":visible"); -} - -function log(a, b, c){ - var console = window['console']; - switch(arguments.length) { - case 1: - console['log'](a); - break; - case 2: - console['log'](a, b); - break; - default: - console['log'](a, b, c); - break; - } -} - -function error(a, b, c){ - var console = window['console']; - switch(arguments.length) { - case 1: - console['error'](a); - break; - case 2: - console['error'](a, b); - break; - default: - console['error'](a, b, c); - break; - } -} - -function consoleLog(level, objs) { - var log = document.createElement("div"); - log.className = level; - var msg = ""; - var sep = ""; - for ( var i = 0; i < objs.length; i++) { - var obj = objs[i]; - msg += sep + (typeof obj == 'string' ? obj : toJson(obj)); - sep = " "; - } - log.appendChild(document.createTextNode(msg)); - consoleNode.appendChild(log); -} - -function isNode(inp) { - return inp && - inp.tagName && - inp.nodeName && - inp.ownerDocument && - inp.removeAttribute; -} - -function isLeafNode (node) { - switch (node.nodeName) { - case "OPTION": - case "PRE": - case "TITLE": - return true; - default: - return false; - } -} - -function setHtml(node, html) { - if (isLeafNode(node)) { - if (msie) { - node.innerText = html; - } else { - node.textContent = html; - } - } else { - node.innerHTML = html; - } -} - -function escapeHtml(html) { - if (!html || !html.replace) - return html; - return html. - replace(/&/g, '&'). - replace(//g, '>'); -} - -function escapeAttr(html) { - if (!html || !html.replace) - return html; - return html.replace(//g, '>').replace(/\"/g, - '"'); -} - -function bind(_this, _function) { - if (!_this) - throw "Missing this"; - if (!_.isFunction(_function)) - throw "Missing function"; - return function() { - return _function.apply(_this, arguments); - }; -} - -function outerHTML(node) { - var temp = document.createElement('div'); - temp.appendChild(node); - var outerHTML = temp.innerHTML; - temp.removeChild(node); - return outerHTML; -} - -function trim(str) { - return str.replace(/^ */, '').replace(/ *$/, ''); -} - -function toBoolean(value) { - var v = ("" + value).toLowerCase(); - if (v == 'f' || v == '0' || v == 'false' || v == 'no') - value = false; - return !!value; -} - -function merge(src, dst) { - for ( var key in src) { - var value = dst[key]; - var type = typeof value; - if (type == 'undefined') { - dst[key] = fromJson(toJson(src[key])); - } else if (type == 'object' && value.constructor != array && - key.substring(0, 1) != "$") { - merge(src[key], value); - } - } -} - -// //////////////////////////// -// UrlWatcher -// //////////////////////////// - -function UrlWatcher(location) { - this.location = location; - this.delay = 25; - this.setTimeout = function(fn, delay) { - window.setTimeout(fn, delay); - }; - this.listener = function(url) { - return url; - }; - this.expectedUrl = location.href; -} - -UrlWatcher.prototype = { - listen: function(fn){ - this.listener = fn; - }, - watch: function() { - var self = this; - var pull = function() { - if (self.expectedUrl !== self.location.href) { - var notify = self.location.hash.match(/^#\$iframe_notify=(.*)$/); - if (notify) { - if (!self.expectedUrl.match(/#/)) { - self.expectedUrl += "#"; - } - self.location.href = self.expectedUrl; - var id = '_iframe_notify_' + notify[1]; - var notifyFn = angularCallbacks[id]; - delete angularCallbacks[id]; - try { - (notifyFn||noop)(); - } catch (e) { - alert(e); - } - } else { - self.listener(self.location.href); - self.expectedUrl = self.location.href; - } - } - self.setTimeout(pull, self.delay); - }; - pull(); - }, - - set: function(url) { - var existingURL = this.location.href; - if (!existingURL.match(/#/)) - existingURL += '#'; - if (existingURL != url) - this.location.href = url; - this.existingURL = url; - }, - - get: function() { - return window.location.href; - } -}; - -///////////////////////////////////////////////// -function configureJQueryPlugins() { - var fn = jQuery['fn']; - fn['scope'] = function() { - var element = this; - while (element && element.get(0)) { - var scope = element.data("scope"); - if (scope) - return scope; - element = element.parent(); - } - return null; - }; - fn['controller'] = function() { - return this.data('controller') || NullController.instance; - }; -} - -function configureLogging(config) { - if (config.debug == 'console' && !consoleNode) { - consoleNode = document.createElement("div"); - consoleNode.id = 'ng-console'; - document.getElementsByTagName('body')[0].appendChild(consoleNode); - log = function() { - consoleLog('ng-console-info', arguments); - }; - console.error = function() { - consoleLog('ng-console-error', arguments); - }; - } -} - -function exposeMethods(obj, methods){ - var bound = {}; - foreach(methods, function(fn, name){ - bound[name] = _(fn).bind(obj); - }); - return bound; -} - -function wireAngular(element, config) { - var widgetFactory = new WidgetFactory(config['server'], config['database']); - var binder = new Binder(element[0], widgetFactory, datastore, config['location'], config); - binder.updateListeners.push(config.onUpdateView); - var controlBar = new ControlBar(element.find('body'), config['server'], config['database']); - var onUpdate = function(){binder.updateView();}; - var server = config['database'] =="$MEMORY" ? - new FrameServer(window) : - new Server(config['server'], jQuery['getScript']); - server = new VisualServer(server, new NullStatus(element.find('body')), onUpdate); - var users = new Users(server, controlBar); - var databasePath = '/data/' + config['database']; - var post = function(request, callback){ - server.request("POST", databasePath, request, callback); - }; - var datastore = new DataStore(post, users, binder.anchor); - binder.datastore = datastore; - binder.updateListeners.push(function(){datastore.flush();}); - var scope = new Scope({ - '$anchor' : binder.anchor, - '$updateView': _(binder.updateView).bind(binder), - '$config' : config, - '$invalidWidgets': [], - '$console' : window.console, - '$datastore' : exposeMethods(datastore, { - 'load': datastore.load, - 'loadMany': datastore.loadMany, - 'loadOrCreate': datastore.loadOrCreate, - 'loadAll': datastore.loadAll, - 'save': datastore.save, - 'remove': datastore.remove, - 'flush': datastore.flush, - 'query': datastore.query, - 'entity': datastore.entity, - 'entities': datastore.entities, - 'documentCountsByUser': datastore.documentCountsByUser, - 'userDocumentIdsByEntity': datastore.userDocumentIdsByEntity, - 'join': datastore.join - }), - '$save' : function(callback) { - datastore.saveScope(scope.state, callback, binder.anchor); - }, - '$window' : window, - '$uid' : function() { - return "" + new Date().getTime(); - }, - '$users' : users - }, "ROOT"); - - element.data('scope', scope); - binder.entity(scope); - binder.compile(); - controlBar.bind(); - - //TODO: remove this code - new PopUp(element).bind(); - - var self = _(exposeMethods(scope, { - 'set': scope.set, - 'get': scope.get, - 'eval': scope.eval - })).extend({ - 'init':function(){ - config['location']['listen'](_(binder.onUrlChange).bind(binder)); - binder.parseAnchor(); - binder.executeInit(); - binder.updateView(); - return self; - }, - 'element':element[0], - 'updateView': _(binder.updateView).bind(binder), - 'config':config - }); - return self; -} - -angular['startUrlWatcher'] = function(){ - var watcher = new UrlWatcher(window['location']); - watcher.watch(); - return exposeMethods(watcher, {'listen':watcher.listen, 'set':watcher.set, 'get':watcher.get}); -}; - -angular['compile'] = function(element, config) { - jQuery = window['jQuery']; - msie = jQuery['browser']['msie']; - config = _({ - 'onUpdateView': noop, - 'server': "", - 'location': {'get':noop, 'set':noop, 'listen':noop} - }).extend(config||{}); - - configureLogging(config); - configureJQueryPlugins(); - - return wireAngular(jQuery(element), config); -}; -var angularGlobal = { - 'typeOf':function(obj){ - if (obj === null) return "null"; - var type = typeof obj; - if (type == "object") { - if (obj instanceof Array) return "array"; - if (obj instanceof Date) return "date"; - if (obj.nodeType == 1) return "element"; - } - return type; - } -}; - -var angularCollection = {}; -var angularObject = {}; -var angularArray = { - 'includeIf':function(array, value, condition) { - var index = _.indexOf(array, value); - if (condition) { - if (index == -1) - array.push(value); - } else { - array.splice(index, 1); - } - return array; - }, - 'sum':function(array, expression) { - var fn = angular['Function']['compile'](expression); - var sum = 0; - for (var i = 0; i < array.length; i++) { - var value = 1 * fn(array[i]); - if (!isNaN(value)){ - sum += value; - } - } - return sum; - }, - 'remove':function(array, value) { - var index = _.indexOf(array, value); - if (index >=0) - array.splice(index, 1); - return value; - }, - 'find':function(array, condition, defaultValue) { - if (!condition) return undefined; - var fn = angular['Function']['compile'](condition); - _.detect(array, function($){ - if (fn($)){ - defaultValue = $; - return true; - } - }); - return defaultValue; - }, - 'findById':function(array, id) { - return angular.Array.find(array, function($){return $.$id == id;}, null); - }, - 'filter':function(array, expression) { - var predicates = []; - predicates.check = function(value) { - for (var j = 0; j < predicates.length; j++) { - if(!predicates[j](value)) { - return false; - } - } - return true; - }; - var getter = Scope.getter; - var search = function(obj, text){ - if (text.charAt(0) === '!') { - return !search(obj, text.substr(1)); - } - switch (typeof obj) { - case "boolean": - case "number": - case "string": - return ('' + obj).toLowerCase().indexOf(text) > -1; - case "object": - for ( var objKey in obj) { - if (objKey.charAt(0) !== '$' && search(obj[objKey], text)) { - return true; - } - } - 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": - expression = {$:expression}; - case "object": - for (var key in expression) { - if (key == '$') { - (function(){ - var text = (''+expression[key]).toLowerCase(); - if (!text) return; - predicates.push(function(value) { - return search(value, text); - }); - })(); - } else { - (function(){ - var path = key; - var text = (''+expression[key]).toLowerCase(); - if (!text) return; - predicates.push(function(value) { - return search(getter(value, path), text); - }); - })(); - } - } - 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; - }, - 'add':function(array, value) { - array.push(_.isUndefined(value)? {} : value); - return array; - }, - 'count':function(array, condition) { - if (!condition) return array.length; - var fn = angular['Function']['compile'](condition); - return _.reduce(array, 0, function(count, $){return count + (fn($)?1:0);}); - }, - 'orderBy':function(array, expression, descend) { - function reverse(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(); - if (t1 == "string") v2 = v2.toLowerCase(); - if (v1 === v2) return 0; - return v1 < v2 ? -1 : 1; - } else { - return t1 < t2 ? -1 : 1; - } - } - expression = _.isArray(expression) ? expression: [expression]; - expression = _.map(expression, function($){ - var descending = false; - if (typeof $ == "string" && ($.charAt(0) == '+' || $.charAt(0) == '-')) { - descending = $.charAt(0) == '-'; - $ = $.substring(1); - } - var get = $ ? angular['Function']['compile']($) : _.identity; - return reverse(function(a,b){ - return compare(get(a),get(b)); - }, descending); - }); - var comparator = function(o1, o2){ - for ( var i = 0; i < expression.length; i++) { - var comp = expression[i](o1, o2); - if (comp !== 0) return comp; - } - return 0; - }; - return _.clone(array).sort(reverse(comparator, descend)); - }, - 'orderByToggle':function(predicate, attribute) { - var STRIP = /^([+|-])?(.*)/; - var ascending = false; - var index = -1; - _.detect(predicate, function($, i){ - if ($ == attribute) { - ascending = true; - index = i; - return true; - } - if (($.charAt(0)=='+'||$.charAt(0)=='-') && $.substring(1) == attribute) { - ascending = $.charAt(0) == '+'; - index = i; - return true; - } - }); - if (index >= 0) { - predicate.splice(index, 1); - } - predicate.unshift((ascending ? "-" : "+") + attribute); - return predicate; - }, - 'orderByDirection':function(predicate, attribute, ascend, descend) { - ascend = ascend || 'ng-ascend'; - descend = descend || 'ng-descend'; - var att = predicate[0] || ''; - var direction = true; - if (att.charAt(0) == '-') { - att = att.substring(1); - direction = false; - } else if(att.charAt(0) == '+') { - att = att.substring(1); - } - return att == attribute ? (direction ? ascend : descend) : ""; - }, - 'merge':function(array, index, mergeValue) { - var value = array[index]; - if (!value) { - value = {}; - array[index] = value; - } - merge(mergeValue, value); - return array; - } -}; - -var angularString = { - 'quote':function(string) { - return '"' + string.replace(/\\/g, '\\\\'). - replace(/"/g, '\\"'). - replace(/\n/g, '\\n'). - replace(/\f/g, '\\f'). - replace(/\r/g, '\\r'). - replace(/\t/g, '\\t'). - replace(/\v/g, '\\v') + - '"'; - }, - 'quoteUnicode':function(string) { - var str = angular['String']['quote'](string); - var chars = []; - for ( var i = 0; i < str.length; i++) { - var ch = str.charCodeAt(i); - if (ch < 128) { - chars.push(str.charAt(i)); - } else { - var encode = "000" + ch.toString(16); - chars.push("\\u" + encode.substring(encode.length - 4)); - } - } - return chars.join(''); - }, - 'toDate':function(string){ - var match; - if (typeof string == 'string' && - (match = string.match(/^(\d\d\d\d)-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)Z$/))){ - var date = new Date(0); - date.setUTCFullYear(match[1], match[2] - 1, match[3]); - date.setUTCHours(match[4], match[5], match[6], 0); - return date; - } - return string; - } -}; - -var angularDate = { - 'toString':function(date){ - function pad(n) { return n < 10 ? "0" + n : n; } - return (date.getUTCFullYear()) + '-' + - pad(date.getUTCMonth() + 1) + '-' + - pad(date.getUTCDate()) + 'T' + - pad(date.getUTCHours()) + ':' + - pad(date.getUTCMinutes()) + ':' + - pad(date.getUTCSeconds()) + 'Z'; - } - }; - -var angularFunction = { - 'compile':function(expression) { - if (_.isFunction(expression)){ - return expression; - } else if (expression){ - var scope = new Scope(); - return function($) { - scope.state = $; - return scope.eval(expression); - }; - } else { - return function($){return $;}; - } - } -}; - -function defineApi(dst, chain, underscoreNames){ - var lastChain = _.last(chain); - foreach(underscoreNames, function(name){ - lastChain[name] = _[name]; - }); - angular[dst] = angular[dst] || {}; - foreach(chain, function(parent){ - extend(angular[dst], parent); - }); -} -defineApi('Global', [angularGlobal], - ['extend', 'clone','isEqual', - 'isElement', 'isArray', 'isFunction', 'isUndefined']); -defineApi('Collection', [angularGlobal, angularCollection], - ['each', 'map', 'reduce', 'reduceRight', 'detect', - 'select', 'reject', 'all', 'any', 'include', - 'invoke', 'pluck', 'max', 'min', 'sortBy', - 'sortedIndex', 'toArray', 'size']); -defineApi('Array', [angularGlobal, angularCollection, angularArray], - ['first', 'last', 'compact', 'flatten', 'without', - 'uniq', 'intersect', 'zip', 'indexOf', 'lastIndexOf']); -defineApi('Object', [angularGlobal, angularCollection, angularObject], - ['keys', 'values']); -defineApi('String', [angularGlobal, angularString], []); -defineApi('Date', [angularGlobal, angularDate], []); -//IE bug -angular['Date']['toString'] = angularDate['toString']; -defineApi('Function', [angularGlobal, angularCollection, angularFunction], - ['bind', 'bindAll', 'delay', 'defer', 'wrap', 'compose']); -function Binder(doc, widgetFactory, datastore, location, config) { - this.doc = doc; - this.location = location; - this.datastore = datastore; - this.anchor = {}; - this.widgetFactory = widgetFactory; - this.config = config || {}; - this.updateListeners = []; -} - -Binder.parseBindings = function(string) { - var results = []; - var lastIndex = 0; - var index; - while((index = string.indexOf('{{', lastIndex)) > -1) { - if (lastIndex < index) - results.push(string.substr(lastIndex, index - lastIndex)); - lastIndex = index; - - index = string.indexOf('}}', index); - index = index < 0 ? string.length : index + 2; - - results.push(string.substr(lastIndex, index - lastIndex)); - lastIndex = index; - } - if (lastIndex != string.length) - results.push(string.substr(lastIndex, string.length - lastIndex)); - return results.length === 0 ? [ string ] : results; -}; - -Binder.hasBinding = function(string) { - var bindings = Binder.parseBindings(string); - return bindings.length > 1 || Binder.binding(bindings[0]) !== null; -}; - -Binder.binding = function(string) { - var binding = string.replace(/\n/gm, ' ').match(/^\{\{(.*)\}\}$/); - return binding ? binding[1] : null; -}; - - -Binder.prototype = { - parseQueryString: function(query) { - var params = {}; - query.replace(/(?:^|&)([^&=]*)=?([^&]*)/g, - function (match, left, right) { - if (left) params[decodeURIComponent(left)] = decodeURIComponent(right); - }); - return params; - }, - - parseAnchor: function() { - var self = this, url = this.location['get']() || ""; - - var anchorIndex = url.indexOf('#'); - if (anchorIndex < 0) return; - var anchor = url.substring(anchorIndex + 1); - - var anchorQuery = this.parseQueryString(anchor); - foreach(self.anchor, function(newValue, key) { - delete self.anchor[key]; - }); - foreach(anchorQuery, function(newValue, key) { - self.anchor[key] = newValue; - }); - }, - - onUrlChange: function() { - this.parseAnchor(); - this.updateView(); - }, - - updateAnchor: function() { - var url = this.location['get']() || ""; - var anchorIndex = url.indexOf('#'); - if (anchorIndex > -1) - url = url.substring(0, anchorIndex); - url += "#"; - var sep = ''; - for (var key in this.anchor) { - var value = this.anchor[key]; - if (typeof value === 'undefined' || value === null) { - delete this.anchor[key]; - } else { - url += sep + encodeURIComponent(key); - if (value !== true) - url += "=" + encodeURIComponent(value); - sep = '&'; - } - } - this.location['set'](url); - return url; - }, - - updateView: function() { - var start = new Date().getTime(); - var scope = jQuery(this.doc).scope(); - scope.clearInvalid(); - scope.updateView(); - var end = new Date().getTime(); - this.updateAnchor(); - foreach(this.updateListeners, function(fn) {fn();}); - }, - - docFindWithSelf: function(exp){ - var doc = jQuery(this.doc); - var selection = doc.find(exp); - if (doc.is(exp)){ - selection = selection.andSelf(); - } - return selection; - }, - - executeInit: function() { - this.docFindWithSelf("[ng-init]").each(function() { - var jThis = jQuery(this); - var scope = jThis.scope(); - try { - scope.eval(jThis.attr('ng-init')); - } catch (e) { - alert("EVAL ERROR:\n" + jThis.attr('ng-init') + '\n' + toJson(e, true)); - } - }); - }, - - entity: function (scope) { - var self = this; - this.docFindWithSelf("[ng-entity]").attr("ng-watch", function() { - try { - var jNode = jQuery(this); - var decl = scope.entity(jNode.attr("ng-entity"), self.datastore); - return decl + (jNode.attr('ng-watch') || ""); - } catch (e) { - log(e); - alert(e); - } - }); - }, - - compile: function() { - var jNode = jQuery(this.doc); - if (this.config['autoSubmit']) { - var submits = this.docFindWithSelf(":submit").not("[ng-action]"); - submits.attr("ng-action", "$save()"); - submits.not(":disabled").not("ng-bind-attr").attr("ng-bind-attr", '{disabled:"{{$invalidWidgets}}"}'); - } - this.precompile(this.doc)(this.doc, jNode.scope(), ""); - this.docFindWithSelf("a[ng-action]").live('click', function (event) { - var jNode = jQuery(this); - var scope = jNode.scope(); - try { - scope.eval(jNode.attr('ng-action')); - jNode.removeAttr('ng-error'); - jNode.removeClass("ng-exception"); - } catch (e) { - jNode.addClass("ng-exception"); - jNode.attr('ng-error', toJson(e, true)); - } - scope.get('$updateView')(); - return false; - }); - }, - - translateBinding: function(node, parentPath, factories) { - var path = parentPath.concat(); - var offset = path.pop(); - var parts = Binder.parseBindings(node.nodeValue); - if (parts.length > 1 || Binder.binding(parts[0])) { - var parent = node.parentNode; - if (isLeafNode(parent)) { - parent.setAttribute('ng-bind-template', node.nodeValue); - factories.push({path:path, fn:function(node, scope, prefix) { - return new BindUpdater(node, node.getAttribute('ng-bind-template')); - }}); - } else { - for (var i = 0; i < parts.length; i++) { - var part = parts[i]; - var binding = Binder.binding(part); - var newNode; - if (binding) { - newNode = document.createElement("span"); - var jNewNode = jQuery(newNode); - jNewNode.attr("ng-bind", binding); - if (i === 0) { - factories.push({path:path.concat(offset + i), fn:this.ng_bind}); - } - } else if (msie && part.charAt(0) == ' ') { - newNode = document.createElement("span"); - newNode.innerHTML = ' ' + part.substring(1); - } else { - newNode = document.createTextNode(part); - } - parent.insertBefore(newNode, node); - } - } - parent.removeChild(node); - } - }, - - precompile: function(root) { - var factories = []; - this.precompileNode(root, [], factories); - return function (template, scope, prefix) { - var len = factories.length; - for (var i = 0; i < len; i++) { - var factory = factories[i]; - var node = template; - var path = factory.path; - for (var j = 0; j < path.length; j++) { - node = node.childNodes[path[j]]; - } - try { - scope.addWidget(factory.fn(node, scope, prefix)); - } catch (e) { - alert(e); - } - } - }; - }, - - precompileNode: function(node, path, factories) { - var nodeType = node.nodeType; - if (nodeType == Node.TEXT_NODE) { - this.translateBinding(node, path, factories); - return; - } else if (nodeType != Node.ELEMENT_NODE && nodeType != Node.DOCUMENT_NODE) { - return; - } - - if (!node.getAttribute) return; - var nonBindable = node.getAttribute('ng-non-bindable'); - if (nonBindable || nonBindable === "") return; - - var attributes = node.attributes; - if (attributes) { - var bindings = node.getAttribute('ng-bind-attr'); - node.removeAttribute('ng-bind-attr'); - bindings = bindings ? fromJson(bindings) : {}; - var attrLen = attributes.length; - for (var i = 0; i < attrLen; i++) { - var attr = attributes[i]; - var attrName = attr.name; - // http://www.glennjones.net/Post/809/getAttributehrefbug.htm - var attrValue = msie && attrName == 'href' ? - decodeURI(node.getAttribute(attrName, 2)) : attr.value; - if (Binder.hasBinding(attrValue)) { - bindings[attrName] = attrValue; - } - } - var json = toJson(bindings); - if (json.length > 2) { - node.setAttribute("ng-bind-attr", json); - } - } - - if (!node.getAttribute) log(node); - var repeaterExpression = node.getAttribute('ng-repeat'); - if (repeaterExpression) { - node.removeAttribute('ng-repeat'); - var precompiled = this.precompile(node); - var view = document.createComment("ng-repeat: " + repeaterExpression); - var parentNode = node.parentNode; - parentNode.insertBefore(view, node); - parentNode.removeChild(node); - function template(childScope, prefix, i) { - var clone = jQuery(node).clone(); - clone.css('display', ''); - clone.attr('ng-repeat-index', "" + i); - clone.data('scope', childScope); - precompiled(clone[0], childScope, prefix + i + ":"); - return clone; - } - factories.push({path:path, fn:function(node, scope, prefix) { - return new RepeaterUpdater(jQuery(node), repeaterExpression, template, prefix); - }}); - return; - } - - if (node.getAttribute('ng-eval')) factories.push({path:path, fn:this.ng_eval}); - if (node.getAttribute('ng-bind')) factories.push({path:path, fn:this.ng_bind}); - if (node.getAttribute('ng-bind-attr')) factories.push({path:path, fn:this.ng_bind_attr}); - if (node.getAttribute('ng-hide')) factories.push({path:path, fn:this.ng_hide}); - if (node.getAttribute('ng-show')) factories.push({path:path, fn:this.ng_show}); - if (node.getAttribute('ng-class')) factories.push({path:path, fn:this.ng_class}); - if (node.getAttribute('ng-class-odd')) factories.push({path:path, fn:this.ng_class_odd}); - if (node.getAttribute('ng-class-even')) factories.push({path:path, fn:this.ng_class_even}); - if (node.getAttribute('ng-style')) factories.push({path:path, fn:this.ng_style}); - if (node.getAttribute('ng-watch')) factories.push({path:path, fn:this.ng_watch}); - var nodeName = node.nodeName; - if ((nodeName == 'INPUT' ) || - nodeName == 'TEXTAREA' || - nodeName == 'SELECT' || - nodeName == 'BUTTON') { - var self = this; - factories.push({path:path, fn:function(node, scope, prefix) { - node.name = prefix + node.name.split(":").pop(); - return self.widgetFactory.createController(jQuery(node), scope); - }}); - } - if (nodeName == 'OPTION') { - var html = jQuery('' + - '' + - '' + - '' + - ''); -}; - -extend(FileController.prototype, { - 'cancel': noop, - 'complete': noop, - 'httpStatus': function(status) { - alert("httpStatus:" + this.scopeName + " status:" + status); - }, - 'ioError': function() { - alert("ioError:" + this.scopeName); - }, - 'open': function() { - alert("open:" + this.scopeName); - }, - 'progress':noop, - 'securityError': function() { - alert("securityError:" + this.scopeName); - }, - 'uploadCompleteData': function(data) { - var value = fromJson(data); - value.url = this.attachmentsPath + '/' + value.id + '/' + value.text; - this.view.find("input").attr('checked', true); - var scope = this.view.scope(); - this.value = value; - this.updateModel(scope); - this.value = null; - }, - 'select': function(name, size, type) { - this.name = name; - this.view.find("a").text(name).attr('href', name); - this.view.find("span").text(angular['filter']['bytes'](size)); - this.upload(); - }, - - updateModel: function(scope) { - var isChecked = this.view.find("input").attr('checked'); - var value = isChecked ? this.value : null; - if (this.lastValue === value) { - return false; - } else { - scope.set(this.scopeName, value); - return true; - } - }, - - updateView: function(scope) { - var modelValue = scope.get(this.scopeName); - if (modelValue && this.value !== modelValue) { - this.value = modelValue; - this.view.find("a"). - attr("href", this.value.url). - text(this.value.text); - this.view.find("span").text(angular['filter']['bytes'](this.value.size)); - } - this.view.find("input").attr('checked', !!modelValue); - }, - - upload: function() { - if (this.name) { - this.uploader['uploadFile'](this.attachmentsPath); - } - } -}); - -/////////////////////// -// NullController -/////////////////////// -function NullController(view) {this.view = view;}; -NullController.prototype = { - updateModel: function() { return true; }, - updateView: noop -}; -NullController.instance = new NullController(); - - -/////////////////////// -// ButtonController -/////////////////////// -var ButtonController = NullController; - -/////////////////////// -// TextController -/////////////////////// -function TextController(view, exp, formatter) { - this.view = view; - this.formatter = formatter; - this.exp = exp; - this.validator = view.getAttribute('ng-validate'); - this.required = typeof view.attributes['ng-required'] != "undefined"; - this.lastErrorText = null; - this.lastValue = undefined; - this.initialValue = this.formatter['parse'](view.value); - var widget = view.getAttribute('ng-widget'); - if (widget === 'datepicker') { - jQuery(view).datepicker(); - } -}; - -TextController.prototype = { - updateModel: function(scope) { - var value = this.formatter['parse'](this.view.value); - if (this.lastValue === value) { - return false; - } else { - scope.setEval(this.exp, value); - this.lastValue = value; - return true; - } - }, - - updateView: function(scope) { - var view = this.view; - var value = scope.get(this.exp); - if (typeof value === "undefined") { - value = this.initialValue; - scope.setEval(this.exp, value); - } - value = value ? value : ''; - if (!_(this.lastValue).isEqual(value)) { - view.value = this.formatter['format'](value); - this.lastValue = value; - } - - var isValidationError = false; - view.removeAttribute('ng-error'); - if (this.required) { - isValidationError = !(value && $.trim("" + value).length > 0); - } - var errorText = isValidationError ? "Required Value" : null; - if (!isValidationError && this.validator && value) { - errorText = scope.validate(this.validator, value, view); - isValidationError = !!errorText; - } - if (this.lastErrorText !== errorText) { - this.lastErrorText = isValidationError; - if (errorText && isVisible(view)) { - view.setAttribute('ng-error', errorText); - scope.markInvalid(this); - } - jQuery(view).toggleClass('ng-validation-error', isValidationError); - } - } -}; - -/////////////////////// -// CheckboxController -/////////////////////// -function CheckboxController(view, exp, formatter) { - this.view = view; - this.exp = exp; - this.lastValue = undefined; - this.formatter = formatter; - this.initialValue = this.formatter['parse'](view.checked ? view.value : ""); -}; - -CheckboxController.prototype = { - updateModel: function(scope) { - var input = this.view; - var value = input.checked ? input.value : ''; - value = this.formatter['parse'](value); - value = this.formatter['format'](value); - if (this.lastValue === value) { - return false; - } else { - scope.setEval(this.exp, this.formatter['parse'](value)); - this.lastValue = value; - return true; - } - }, - - updateView: function(scope) { - var input = this.view; - var value = scope.eval(this.exp); - if (typeof value === "undefined") { - value = this.initialValue; - scope.setEval(this.exp, value); - } - input.checked = this.formatter['parse'](input.value) == value; - } -}; - -/////////////////////// -// SelectController -/////////////////////// -function SelectController(view, exp) { - this.view = view; - this.exp = exp; - this.lastValue = undefined; - this.initialValue = view.value; -}; - -SelectController.prototype = { - updateModel: function(scope) { - var input = this.view; - if (input.selectedIndex < 0) { - scope.setEval(this.exp, null); - } else { - var value = this.view.value; - if (this.lastValue === value) { - return false; - } else { - scope.setEval(this.exp, value); - this.lastValue = value; - return true; - } - } - }, - - updateView: function(scope) { - var input = this.view; - var value = scope.get(this.exp); - if (typeof value === 'undefined') { - value = this.initialValue; - scope.setEval(this.exp, value); - } - if (value !== this.lastValue) { - input.value = value ? value : ""; - this.lastValue = value; - } - } -}; - -/////////////////////// -// MultiSelectController -/////////////////////// -function MultiSelectController(view, exp) { - this.view = view; - this.exp = exp; - this.lastValue = undefined; - this.initialValue = this.selected(); -}; - -MultiSelectController.prototype = { - selected: function () { - var value = []; - var options = this.view.options; - for ( var i = 0; i < options.length; i++) { - var option = options[i]; - if (option.selected) { - value.push(option.value); - } - } - return value; - }, - - updateModel: function(scope) { - var value = this.selected(); - // TODO: This is wrong! no caching going on here as we are always comparing arrays - if (this.lastValue === value) { - return false; - } else { - scope.setEval(this.exp, value); - this.lastValue = value; - return true; - } - }, - - updateView: function(scope) { - var input = this.view; - var selected = scope.get(this.exp); - if (typeof selected === "undefined") { - selected = this.initialValue; - scope.setEval(this.exp, selected); - } - if (selected !== this.lastValue) { - var options = input.options; - for ( var i = 0; i < options.length; i++) { - var option = options[i]; - option.selected = _.include(selected, option.value); - } - this.lastValue = selected; - } - } -}; - -/////////////////////// -// RadioController -/////////////////////// -function RadioController(view, exp) { - this.view = view; - this.exp = exp; - this.lastChecked = undefined; - this.lastValue = undefined; - this.inputValue = view.value; - this.initialValue = view.checked ? view.value : null; -}; - -RadioController.prototype = { - updateModel: function(scope) { - var input = this.view; - if (this.lastChecked) { - return false; - } else { - input.checked = true; - this.lastValue = scope.setEval(this.exp, this.inputValue); - this.lastChecked = true; - return true; - } - }, - - updateView: function(scope) { - var input = this.view; - var value = scope.get(this.exp); - if (this.initialValue && typeof value === "undefined") { - value = this.initialValue; - scope.setEval(this.exp, value); - } - if (this.lastValue != value) { - this.lastChecked = input.checked = this.inputValue == (''+value); - this.lastValue = value; - } - } -}; - -/////////////////////// -//ElementController -/////////////////////// -function BindUpdater(view, exp) { - this.view = view; - this.exp = Binder.parseBindings(exp); - this.hasError = false; -}; - -BindUpdater.toText = function(obj) { - var e = escapeHtml; - switch(typeof obj) { - case "string": - case "boolean": - case "number": - return e(obj); - case "function": - return BindUpdater.toText(obj()); - case "object": - if (isNode(obj)) { - return outerHTML(obj); - } else if (obj instanceof angular.filter.Meta) { - switch(typeof obj.html) { - case "string": - case "number": - return obj.html; - case "function": - return obj.html(); - case "object": - if (isNode(obj.html)) - return outerHTML(obj.html); - default: - break; - } - switch(typeof obj.text) { - case "string": - case "number": - return e(obj.text); - case "function": - return e(obj.text()); - default: - break; - } - } - if (obj === null) - return ""; - return e(toJson(obj, true)); - default: - return ""; - } -}; - -BindUpdater.prototype = { - updateModel: noop, - updateView: function(scope) { - var html = []; - var parts = this.exp; - var length = parts.length; - for(var i=0; i iteratorCounter; --r) { - this.children.pop().element.remove(); - } - // Special case for option in select - if (child && child.element[0].nodeName === "OPTION") { - var select = jQuery(child.element[0].parentNode); - var cntl = select.data('controller'); - if (cntl) { - cntl.lastValue = undefined; - cntl.updateView(scope); - } - } - }); - } -}; - -////////////////////////////////// -// PopUp -////////////////////////////////// - -function PopUp(doc) { - this.doc = doc; -}; - -PopUp.OUT_EVENT = "mouseleave mouseout click dblclick keypress keyup"; - -PopUp.onOver = function(e) { - PopUp.onOut(); - var jNode = jQuery(this); - jNode.bind(PopUp.OUT_EVENT, PopUp.onOut); - var position = jNode.position(); - var de = document.documentElement; - var w = self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth; - var hasArea = w - position.left; - var width = 300; - var title = jNode.hasClass("ng-exception") ? "EXCEPTION:" : "Validation error..."; - var msg = jNode.attr("ng-error"); - - var x; - var arrowPos = hasArea>(width+75) ? "left" : "right"; - var tip = jQuery( - "
" + - "
" + - "
"+title+"
" + - "
"+msg+"
" + - "
"); - jQuery("body").append(tip); - if(arrowPos === 'left'){ - x = position.left + this.offsetWidth + 11; - }else{ - x = position.left - (width + 15); - tip.find('.ng-arrow-right').css({left:width+1}); - } - - tip.css({left: x+"px", top: (position.top - 3)+"px"}); - return true; -}; - -PopUp.onOut = function() { - jQuery('#ng-callout'). - unbind(PopUp.OUT_EVENT, PopUp.onOut). - remove(); - return true; -}; - -PopUp.prototype = { - bind: function () { - var self = this; - this.doc.find('.ng-validation-error,.ng-exception'). - live("mouseover", PopUp.onOver); - } -}; - -////////////////////////////////// -// Status -////////////////////////////////// - -function NullStatus(body) { -}; - -NullStatus.prototype = { - beginRequest:function(){}, - endRequest:function(){} -}; - -function Status(body) { - this.requestCount = 0; - this.body = body; -}; - -Status.DOM ='
loading....
'; - -Status.prototype = { - beginRequest: function () { - if (this.requestCount === 0) { - (this.loader = this.loader || this.body.append(Status.DOM).find("#ng-loading")).show(); - } - this.requestCount++; - }, - - endRequest: function () { - this.requestCount--; - if (this.requestCount === 0) { - this.loader.hide("fold"); - } - } -}; -})(window, document); \ No newline at end of file diff --git a/example/memoryLeak.html b/example/memoryLeak.html index 35169da8..bdfe3faf 100644 --- a/example/memoryLeak.html +++ b/example/memoryLeak.html @@ -6,17 +6,50 @@ - Filter: - + + +
diff --git a/jsTestDriver.conf b/jsTestDriver.conf index 8b36e7d4..c048a294 100644 --- a/jsTestDriver.conf +++ b/jsTestDriver.conf @@ -1,7 +1,7 @@ server: http://localhost:9876 load: - - lib/jasmine/jasmine-0.10.0.js + - lib/jasmine/jasmine-0.10.1.js - lib/jasmine-jstd-adapter/JasmineAdapter.js - lib/webtoolkit/webtoolkit.base64.js - lib/jquery/jquery-1.4.js diff --git a/lib/jasmine/jasmine-0.10.0.js b/lib/jasmine/jasmine-0.10.1.js similarity index 97% rename from lib/jasmine/jasmine-0.10.0.js rename to lib/jasmine/jasmine-0.10.1.js index bb7547e8..f9bd7d6f 100644 --- a/lib/jasmine/jasmine-0.10.0.js +++ b/lib/jasmine/jasmine-0.10.1.js @@ -15,7 +15,7 @@ jasmine.unimplementedMethod_ = function() { /** * Use jasmine.undefined instead of undefined, since undefined 0) { for (var i = 0; i < matcherArgs.length; i++) { if (i > 0) message += ","; @@ -1204,31 +1216,32 @@ jasmine.Matchers.prototype.wasNotCalled = function() { * */ jasmine.Matchers.prototype.wasCalledWith = function() { + var expectedArgs = jasmine.util.argsToArray(arguments); if (!jasmine.isSpy(this.actual)) { throw new Error('Expected a spy, but got ' + jasmine.Matchers.pp(this.actual) + '.'); } - this.message = function() { if (this.actual.callCount == 0) { - return "Expected spy to have been called with " + jasmine.pp(arguments) + " but it was never called."; + return "Expected spy to have been called with " + jasmine.pp(expectedArgs) + " but it was never called."; } else { - return "Expected spy to have been called with " + jasmine.pp(arguments) + " but was called with " + jasmine.pp(this.actual.argsForCall); + return "Expected spy to have been called with " + jasmine.pp(expectedArgs) + " but was called with " + jasmine.pp(this.actual.argsForCall); } }; - return this.env.contains_(this.actual.argsForCall, jasmine.util.argsToArray(arguments)); + return this.env.contains_(this.actual.argsForCall, expectedArgs); }; jasmine.Matchers.prototype.wasNotCalledWith = function() { + var expectedArgs = jasmine.util.argsToArray(arguments); if (!jasmine.isSpy(this.actual)) { throw new Error('Expected a spy, but got ' + jasmine.Matchers.pp(this.actual) + '.'); } this.message = function() { - return "Expected spy not to have been called with " + jasmine.pp(arguments) + " but it was"; + return "Expected spy not to have been called with " + jasmine.pp(expectedArgs) + " but it was"; }; - return !this.env.contains_(this.actual.argsForCall, jasmine.util.argsToArray(arguments)); + return !this.env.contains_(this.actual.argsForCall, expectedArgs); }; /** @@ -1818,7 +1831,9 @@ jasmine.Spec.prototype.addMatcherResult = function(result) { }; jasmine.Spec.prototype.expect = function(actual) { - return new (this.getMatchersClass_())(this.env, actual, this); + var positive = new (this.getMatchersClass_())(this.env, actual, this); + positive.not = new (this.getMatchersClass_())(this.env, actual, this, true); + return positive; }; jasmine.Spec.prototype.waits = function(timeout) { @@ -2256,6 +2271,6 @@ window.clearInterval = function(timeoutKey) { jasmine.version_= { "major": 0, "minor": 10, - "build": 0, - "revision": 1261768736 + "build": 1, + "revision": 1267503060 }; diff --git a/src/Angular.js b/src/Angular.js index 6cb3f602..9b3634be 100644 --- a/src/Angular.js +++ b/src/Angular.js @@ -20,22 +20,23 @@ if (typeof Node == 'undefined') { function noop() {} if (!window['console']) window['console']={'log':noop, 'error':noop}; -var consoleNode, msie, +var consoleNode, msie, jQuery = window['jQuery'] || window['$'], // weirdness to make IE happy foreach = _.each, extend = _.extend, identity = _.identity, - angular = window['angular'] || (window['angular'] = {}), - angularValidator = angular['validator'] || (angular['validator'] = {}), - angularFilter = angular['filter'] || (angular['filter'] = {}), - angularFormatter = angular['formatter'] || (angular['formatter'] = {}), + angular = window['angular'] || (window['angular'] = {}), + angularValidator = angular['validator'] || (angular['validator'] = {}), + angularFilter = angular['filter'] || (angular['filter'] = {}), + angularFormatter = angular['formatter'] || (angular['formatter'] = {}), angularCallbacks = angular['callbacks'] || (angular['callbacks'] = {}), angularAlert = angular['alert'] || (angular['alert'] = function(){ - log(arguments); window.alert.apply(window, arguments); + log(arguments); window.alert.apply(window, arguments); }); +angular['copy'] = copy; var isVisible = isVisible || function (element) { - return jQuery(element).is(":visible"); + return jQuery(element).is(":visible"); } function log(a, b, c){ @@ -101,6 +102,29 @@ function isLeafNode (node) { } } +function copy(source, destination){ + if (!destination) { + if (!source) { + return source; + } else if (_.isArray(source)) { + return copy(source, []); + } else { + return copy(source, {}); + } + } else { + if (_.isArray(source)) { + while(destination.length) { + destination.pop(); + } + } else { + _(destination).each(function(value, key){ + delete destination[key]; + }); + } + return $.extend(true, destination, source); + } +}; + function setHtml(node, html) { if (isLeafNode(node)) { if (msie) { @@ -218,7 +242,7 @@ UrlWatcher.prototype = { }; pull(); }, - + set: function(url) { var existingURL = this.location.href; if (!existingURL.match(/#/)) @@ -227,7 +251,7 @@ UrlWatcher.prototype = { this.location.href = url; this.existingURL = url; }, - + get: function() { return window.location.href; } @@ -326,10 +350,10 @@ function wireAngular(element, config) { binder.entity(scope); binder.compile(); controlBar.bind(); - + //TODO: remove this code new PopUp(element).bind(); - + var self = _(exposeMethods(scope, { 'set': scope.set, 'get': scope.get, @@ -338,8 +362,8 @@ function wireAngular(element, config) { 'init':function(){ config['location']['listen'](_(binder.onUrlChange).bind(binder)); binder.parseAnchor(); - binder.executeInit(); - binder.updateView(); + binder.executeInit(); + binder.updateView(); return self; }, 'element':element[0], @@ -349,7 +373,7 @@ function wireAngular(element, config) { return self; } -angular['startUrlWatcher'] = function(){ +angular['startUrlWatcher'] = function(){ var watcher = new UrlWatcher(window['location']); watcher.watch(); return exposeMethods(watcher, {'listen':watcher.listen, 'set':watcher.set, 'get':watcher.get}); @@ -366,6 +390,6 @@ angular['compile'] = function(element, config) { configureLogging(config); configureJQueryPlugins(); - + return wireAngular(jQuery(element), config); }; diff --git a/src/Resource.js b/src/Resource.js new file mode 100644 index 00000000..c0c6d220 --- /dev/null +++ b/src/Resource.js @@ -0,0 +1,117 @@ +function Route(template, defaults) { + this.template = template = template + '#'; + this.defaults = defaults || {}; + var urlParams = this.urlParams = {}; + foreach(template.split(/\W/), function(param){ + if (param && template.match(new RegExp(":" + param + "\\W"))) { + urlParams[param] = true; + } + }); +} + +Route.prototype = { + url: function(params) { + var path = []; + var self = this; + var url = this.template; + params = params || {}; + foreach(this.urlParams, function(value, urlParam){ + var value = params[urlParam] || self.defaults[urlParam] || ""; + url = url.replace(new RegExp(":" + urlParam + "(\\W)"), value + "$1"); + }); + url = url.replace(/\/?#$/, ''); + var query = []; + foreach(params, function(value, key){ + if (!self.urlParams[key]) { + query.push(encodeURI(key) + '=' + encodeURI(value)); + } + }); + return url + (query.length ? '?' + query.join('&') : ''); + } +}; + +function ResourceFactory(xhr) { + this.xhr = xhr; +} + +ResourceFactory.DEFAULT_ACTIONS = { + 'get': {method:'GET'}, + 'save': {method:'POST'}, + 'query': {method:'GET', isArray:true}, + 'remove': {method:'DELETE'}, + 'delete': {method:'DELETE'} +}; + +ResourceFactory.prototype = { + route: function(url, idPaths, actions){ + var self = this; + var route = new Route(url); + actions = $.extend({}, ResourceFactory.DEFAULT_ACTIONS, actions); + function extractIds(data){ + var ids = {}; + foreach(idPaths, function(path, id){ + ids[id] = Scope.getter(data, path); + }); + return ids; + } + + function Resource(value){ + copy(value || {}, this); + }; + + foreach(actions, function(action, name){ + var isGet = action.method == 'GET'; + var isPost = action.method == 'POST'; + Resource[name] = function (a1, a2, a3) { + var params = {}; + var data; + var callback = noop; + switch(arguments.length) { + case 3: callback = a3; + case 2: + if (typeof a2 == 'function') { + callback = a2; + } else { + params = a1; + data = a2; + break; + } + case 1: if (isPost) data = a1; else params = a1; break; + case 0: break; + default: + throw "Expected between 0-3 arguments [params, data, callback], got " + arguments.length + " arguments." + } + + var value = action.isArray ? [] : new Resource(data); + self.xhr.method(action.method, route.url($.extend({}, action.params || {}, extractIds(data), params)), data, function(response) { + if (action.isArray) { + foreach(response, function(item){ + value.push(new Resource(item)); + }); + } else { + copy(response, value); + } + (callback||noop)(value); + }); + return value; + }; + + if (!isGet) { + Resource.prototype['$' + name] = function(a1, a2){ + var params = {}; + var callback = noop; + switch(arguments.length) { + case 2: params = a1, callback = a2; + case 1: if (typeof a1 == 'function') callback = a1; else params = a1; + case 0: break; + default: + throw "Expected between 1-3 arguments [params, data, callback], got " + arguments.length + " arguments." + } + Resource[name](params, this, callback); + }; + } + }); + return Resource; + } +}; + diff --git a/src/Scope.js b/src/Scope.js index 4de57dd2..daf4b36c 100644 --- a/src/Scope.js +++ b/src/Scope.js @@ -53,11 +53,11 @@ Scope.prototype = { }); }); }, - + addWidget: function(controller) { if (controller) this.widgets.push(controller); }, - + isProperty: function(exp) { for ( var i = 0; i < exp.length; i++) { var ch = exp.charAt(i); @@ -67,12 +67,12 @@ Scope.prototype = { } return true; }, - + get: function(path) { // log('SCOPE.get', path, Scope.getter(this.state, path)); return Scope.getter(this.state, path); }, - + set: function(path, value) { // log('SCOPE.set', path, value); var element = path.split('.'); @@ -89,11 +89,11 @@ Scope.prototype = { instance[element.shift()] = value; return value; }, - + setEval: function(expressionText, value) { this.eval(expressionText + "=" + toJson(value)); }, - + eval: function(expressionText, context) { // log('Scope.eval', expressionText); var expression = Scope.expressionCache[expressionText]; @@ -108,7 +108,7 @@ Scope.prototype = { context.self = this.state; return expression(context); }, - + //TODO: Refactor. This function needs to be an execution closure for widgets // move to widgets // remove expression, just have inner closure. @@ -126,8 +126,8 @@ Scope.prototype = { } return true; } catch (e){ - error('Eval Widget Error:', e); var jsonError = toJson(e, true); + error('Eval Widget Error:', jsonError); widget.hasError = true; jQuery(widget.view). addClass('ng-exception'). @@ -138,7 +138,7 @@ Scope.prototype = { return false; } }, - + validate: function(expressionText, value, element) { var expression = Scope.expressionCache[expressionText]; if (!expression) { @@ -148,21 +148,21 @@ Scope.prototype = { var self = {scope:this, self:this.state, '$element':element}; return expression(self)(self, value); }, - + entity: function(entityDeclaration, datastore) { var expression = new Parser(entityDeclaration).entityDeclaration(); return expression({scope:this, datastore:datastore}); }, - + clearInvalid: function() { var invalid = this.state['$invalidWidgets']; while(invalid.length > 0) {invalid.pop();} }, - + markInvalid: function(widget) { this.state['$invalidWidgets'].push(widget); }, - + watch: function(declaration) { var self = this; new Parser(declaration).watch()({ @@ -178,7 +178,7 @@ Scope.prototype = { } }); }, - + addWatchListener: function(watchExpression, listener) { var watcher = this.watchListeners[watchExpression]; if (!watcher) { @@ -187,7 +187,7 @@ Scope.prototype = { } watcher.listeners.push(listener); }, - + fireWatchers: function() { var self = this; var fired = false; @@ -203,4 +203,4 @@ Scope.prototype = { }); return fired; } -}; \ No newline at end of file +}; diff --git a/test/AngularSpec.js b/test/AngularSpec.js index 65a32279..043f7bf3 100644 --- a/test/AngularSpec.js +++ b/test/AngularSpec.js @@ -7,4 +7,38 @@ describe('Angular', function(){ scope.updateView(); expect(onUpdateView).wasCalled(); }); -}); \ No newline at end of file +}); + +describe("copy", function(){ + it("should return same object", function (){ + var obj = {}; + var arr = []; + assertSame(obj, copy({}, obj)); + assertSame(arr, copy([], arr)); + }); + + it("should copy array", function(){ + var src = [1, {name:"value"}]; + var dst = [{key:"v"}]; + assertSame(dst, copy(src, dst)); + assertEquals([1, {name:"value"}], dst); + assertEquals({name:"value"}, dst[1]); + assertNotSame(src[1], dst[1]); + }); + + it('should copy empty array', function() { + var src = []; + var dst = [{key: "v"}]; + assertEquals([], copy(src, dst)); + assertEquals([], dst); + }); + + it("should copy object", function(){ + var src = {a:{name:"value"}}; + var dst = {b:{key:"v"}}; + assertSame(dst, copy(src, dst)); + assertEquals({a:{name:"value"}}, dst); + assertEquals(src.a, dst.a); + assertNotSame(src.a, dst.a); + }); +}); diff --git a/test/ResourceSpec.js b/test/ResourceSpec.js new file mode 100644 index 00000000..562d6500 --- /dev/null +++ b/test/ResourceSpec.js @@ -0,0 +1,159 @@ +function MockXHR(){ + this.expectations = { + 'GET': {}, + 'POST': {}, + 'DELETE': {} + }; + this.queue = []; +} +MockXHR.prototype = { + method: function(verb, url, data, callback) { + if (verb == 'POST') + url += '|' + angular.toJson(data); + var response = this.expectations[verb][url]; + if (!response) + throw "No expectation for " + verb + " on '" + url + "'."; + this.queue.push(function(){ + callback(response); + }); + }, + + expectGET: function(url) { + var self = this; + return { + respond: function(response){ + self.expectations.GET[url] = response; + } + }; + }, + + expectDELETE: function(url) { + var self = this; + return { + respond: function(response){ + self.expectations.DELETE[url] = response; + } + }; + }, + + expectPOST: function(url) { + var self = this; + return { + data: function(data){ + return { + respond: function(response){ + self.expectations.POST[url + '|' + angular.toJson(data)] = response; + } + }; + } + }; + }, + + flush: function(){ + while(this.queue.length) { + this.queue.shift()(); + } + } +}; + +describe("resource", function() { + var xhr, resource, CreditCard, callback; + + beforeEach(function(){ + xhr = new MockXHR(); + resource = new ResourceFactory(xhr); + CreditCard = resource.route('/CreditCard/:id:verb', {id:'id.key'}, { + charge:{ + method:'POST', + params:{verb:'!charge'} + } + }); + callback = jasmine.createSpy(); + }); + + it("should build resource", function(){ + expect(typeof CreditCard).toBe('function'); + expect(typeof CreditCard.get).toBe('function'); + expect(typeof CreditCard.save).toBe('function'); + expect(typeof CreditCard.remove).toBe('function'); + expect(typeof CreditCard['delete']).toBe('function'); + expect(typeof CreditCard.query).toBe('function'); + }); + + it("should create resource", function(){ + xhr.expectPOST('/CreditCard').data({name:'misko'}).respond({id:123, name:'misko'}); + + var cc = CreditCard.save({name:'misko'}, callback); + nakedExpect(cc).toEqual({name:'misko'}); + expect(callback).wasNotCalled(); + xhr.flush(); + nakedExpect(cc).toEqual({id:123, name:'misko'}); + expect(callback).wasCalledWith(cc); + }); + + it("should read resource", function(){ + xhr.expectGET("/CreditCard/123").respond({id:123, number:'9876'}); + var cc = CreditCard.get({id:123}, callback); + expect(cc instanceof CreditCard).toBeTruthy(); + nakedExpect(cc).toEqual({}); + expect(callback).wasNotCalled(); + xhr.flush(); + nakedExpect(cc).toEqual({id:123, number:'9876'}); + expect(callback).wasCalledWith(cc); + }); + + it("should update resource", function(){ + xhr.expectPOST('/CreditCard/123').data({id:{key:123}, name:'misko'}).respond({id:{key:123}, name:'rama'}); + + var cc = CreditCard.save({id:{key:123}, name:'misko'}, callback); + nakedExpect(cc).toEqual({id:{key:123}, name:'misko'}); + expect(callback).wasNotCalled(); + xhr.flush(); + nakedExpect(cc).toEqual({id:{key:123}, name:'rama'}); + expect(callback).wasCalledWith(cc); + }); + + it("should query resource", function(){ + xhr.expectGET("/CreditCard?key=value").respond([{id:1}, {id:2}]); + + var ccs = CreditCard.query({key:'value'}, callback); + expect(ccs).toEqual([]); + expect(callback).wasNotCalled(); + xhr.flush(); + nakedExpect(ccs).toEqual([{id:1}, {id:2}]); + expect(callback).wasCalledWith(ccs); + }); + + it('should delete resource', function(){ + xhr.expectDELETE("/CreditCard/123").respond({}); + + CreditCard.remove({id:123}, callback); + expect(callback).wasNotCalled(); + xhr.flush(); + nakedExpect(callback.mostRecentCall.args).toEqual([{}]); + }); + + it('should post charge verb', function(){ + xhr.expectPOST('/CreditCard/123!charge?amount=10').data({auth:'abc'}).respond({success:'ok'}); + + CreditCard.charge({id:123, amount:10},{auth:'abc'}, callback); + }); + + it('should create on save', function(){ + xhr.expectPOST('/CreditCard').data({name:'misko'}).respond({id:123}); + var cc = new CreditCard(); + expect(cc.$get).not.toBeDefined(); + expect(cc.$query).not.toBeDefined(); + expect(cc.$remove).toBeDefined(); + expect(cc.$save).toBeDefined(); + + cc.name = 'misko'; + cc.$save(callback); + nakedExpect(cc).toEqual({name:'misko'}); + xhr.flush(); + nakedExpect(cc).toEqual({id:123}); + expect(callback).wasCalledWith(cc); + }); + + +}); diff --git a/test/testabilityPatch.js b/test/testabilityPatch.js index 293553da..e7ebb386 100644 --- a/test/testabilityPatch.js +++ b/test/testabilityPatch.js @@ -10,6 +10,11 @@ msie = jQuery.browser.msie; function noop(){} jstd = jstestdriver; +dump = _(jstd.console.log).bind(jstd.console); + +function nakedExpect(obj) { + return expect(angular.fromJson(angular.toJson(obj))); +}; swfobject = { createSwf:function() { @@ -137,4 +142,4 @@ function assertThrows(error, fn){ } log = noop; -error = noop; \ No newline at end of file +error = noop;