From ac669c97b7f197b3191b1844d184871e5a527259 Mon Sep 17 00:00:00 2001 From: wycats Date: Sat, 31 Jul 2010 01:23:28 -0700 Subject: [PATCH 001/111] Initial handlebars commit and parser. Simple {{}} works. --- js/handlebars.js | 65 +++ js/test/handlebars.js | 13 + js/test/index.html | 20 + js/vendor/jquery.js | 154 ++++++ js/vendor/test/qunit.css | 140 +++++ js/vendor/test/qunit.js | 1128 ++++++++++++++++++++++++++++++++++++++ 6 files changed, 1520 insertions(+) create mode 100644 js/handlebars.js create mode 100644 js/test/handlebars.js create mode 100644 js/test/index.html create mode 100644 js/vendor/jquery.js create mode 100644 js/vendor/test/qunit.css create mode 100644 js/vendor/test/qunit.js diff --git a/js/handlebars.js b/js/handlebars.js new file mode 100644 index 00000000..768e939f --- /dev/null +++ b/js/handlebars.js @@ -0,0 +1,65 @@ +Handlebars = { + compile: function(string) { + var compiler = new Handlebars.Compiler(string); + return compiler.compile(); + } +} + +Handlebars.Compiler = function(string) { + this.string = string; + this.pointer = -1; + this.mustache = false; + this.text = ""; + this.fn = "var out = ''; "; + this.newlines = ""; +} + +Handlebars.Compiler.prototype = { + getChar: function() { + this.pointer++; + return this.string[this.pointer]; + }, + + peek: function(n) { + n = n || 1; + return this.string.slice(this.pointer, this.pointer + n); + }, + + compile: function() { + var chr, mustache; + while(chr = this.getChar()) { + // entering mustache state + if(chr === "{" && this.peek() === "{" && !this.mustache) { + this.fn = this.fn + "out = out + '" + this.text + "'; "; + this.fn = this.fn + this.newlines; + this.newlines = "" + this.text = "" + this.mustache = " "; + this.getChar(); + + // exiting mustache state + } else if(this.mustache && chr === "}" && this.peek() === "}") { + mustache = this.mustache.trim(); + this.fn = this.fn + "out = out + context['" + mustache + "']; "; + this.mustache = false; + this.getChar(); + + // in mustache state + } else if(this.mustache) { + this.mustache = this.mustache + chr; + + // in normal state + } else { + if(chr === "\n") { + this.newlines = this.newlines + "\n"; + chr = "\\n"; + } + this.text = this.text + chr; + } + } + + this.fn = this.fn + "\nreturn out;"; + console.log(this.fn); + return new Function("context", this.fn); + } +} diff --git a/js/test/handlebars.js b/js/test/handlebars.js new file mode 100644 index 00000000..7b98eb9f --- /dev/null +++ b/js/test/handlebars.js @@ -0,0 +1,13 @@ +jQuery(function($) { + + module("basic context"); + + test("compiling with a basic context", function() { + var string = "Goodbye\n{{cruel}}\n{{world}}"; + var template = Handlebars.compile(string); + + result = template({cruel: "cruel", world: "world"}); + equal("Goodbye\ncruel\nworld", result, "it works if all the required keys are provided"); + }); + +}); diff --git a/js/test/index.html b/js/test/index.html new file mode 100644 index 00000000..61486268 --- /dev/null +++ b/js/test/index.html @@ -0,0 +1,20 @@ + + + + + + + + + + +

QUnit example

+

+

+
    + + + + diff --git a/js/vendor/jquery.js b/js/vendor/jquery.js new file mode 100644 index 00000000..7c243080 --- /dev/null +++ b/js/vendor/jquery.js @@ -0,0 +1,154 @@ +/*! + * jQuery JavaScript Library v1.4.2 + * http://jquery.com/ + * + * Copyright 2010, John Resig + * Dual licensed under the MIT or GPL Version 2 licenses. + * http://jquery.org/license + * + * Includes Sizzle.js + * http://sizzlejs.com/ + * Copyright 2010, The Dojo Foundation + * Released under the MIT, BSD, and GPL Licenses. + * + * Date: Sat Feb 13 22:33:48 2010 -0500 + */ +(function(A,w){function ma(){if(!c.isReady){try{s.documentElement.doScroll("left")}catch(a){setTimeout(ma,1);return}c.ready()}}function Qa(a,b){b.src?c.ajax({url:b.src,async:false,dataType:"script"}):c.globalEval(b.text||b.textContent||b.innerHTML||"");b.parentNode&&b.parentNode.removeChild(b)}function X(a,b,d,f,e,j){var i=a.length;if(typeof b==="object"){for(var o in b)X(a,o,b[o],f,e,d);return a}if(d!==w){f=!j&&f&&c.isFunction(d);for(o=0;o)[^>]*$|^#([\w-]+)$/,Ua=/^.[^:#\[\.,]*$/,Va=/\S/, +Wa=/^(\s|\u00A0)+|(\s|\u00A0)+$/g,Xa=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,P=navigator.userAgent,xa=false,Q=[],L,$=Object.prototype.toString,aa=Object.prototype.hasOwnProperty,ba=Array.prototype.push,R=Array.prototype.slice,ya=Array.prototype.indexOf;c.fn=c.prototype={init:function(a,b){var d,f;if(!a)return this;if(a.nodeType){this.context=this[0]=a;this.length=1;return this}if(a==="body"&&!b){this.context=s;this[0]=s.body;this.selector="body";this.length=1;return this}if(typeof a==="string")if((d=Ta.exec(a))&& +(d[1]||!b))if(d[1]){f=b?b.ownerDocument||b:s;if(a=Xa.exec(a))if(c.isPlainObject(b)){a=[s.createElement(a[1])];c.fn.attr.call(a,b,true)}else a=[f.createElement(a[1])];else{a=sa([d[1]],[f]);a=(a.cacheable?a.fragment.cloneNode(true):a.fragment).childNodes}return c.merge(this,a)}else{if(b=s.getElementById(d[2])){if(b.id!==d[2])return T.find(a);this.length=1;this[0]=b}this.context=s;this.selector=a;return this}else if(!b&&/^\w+$/.test(a)){this.selector=a;this.context=s;a=s.getElementsByTagName(a);return c.merge(this, +a)}else return!b||b.jquery?(b||T).find(a):c(b).find(a);else if(c.isFunction(a))return T.ready(a);if(a.selector!==w){this.selector=a.selector;this.context=a.context}return c.makeArray(a,this)},selector:"",jquery:"1.4.2",length:0,size:function(){return this.length},toArray:function(){return R.call(this,0)},get:function(a){return a==null?this.toArray():a<0?this.slice(a)[0]:this[a]},pushStack:function(a,b,d){var f=c();c.isArray(a)?ba.apply(f,a):c.merge(f,a);f.prevObject=this;f.context=this.context;if(b=== +"find")f.selector=this.selector+(this.selector?" ":"")+d;else if(b)f.selector=this.selector+"."+b+"("+d+")";return f},each:function(a,b){return c.each(this,a,b)},ready:function(a){c.bindReady();if(c.isReady)a.call(s,c);else Q&&Q.push(a);return this},eq:function(a){return a===-1?this.slice(a):this.slice(a,+a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(R.apply(this,arguments),"slice",R.call(arguments).join(","))},map:function(a){return this.pushStack(c.map(this, +function(b,d){return a.call(b,d,b)}))},end:function(){return this.prevObject||c(null)},push:ba,sort:[].sort,splice:[].splice};c.fn.init.prototype=c.fn;c.extend=c.fn.extend=function(){var a=arguments[0]||{},b=1,d=arguments.length,f=false,e,j,i,o;if(typeof a==="boolean"){f=a;a=arguments[1]||{};b=2}if(typeof a!=="object"&&!c.isFunction(a))a={};if(d===b){a=this;--b}for(;b
    a"; +var e=d.getElementsByTagName("*"),j=d.getElementsByTagName("a")[0];if(!(!e||!e.length||!j)){c.support={leadingWhitespace:d.firstChild.nodeType===3,tbody:!d.getElementsByTagName("tbody").length,htmlSerialize:!!d.getElementsByTagName("link").length,style:/red/.test(j.getAttribute("style")),hrefNormalized:j.getAttribute("href")==="/a",opacity:/^0.55$/.test(j.style.opacity),cssFloat:!!j.style.cssFloat,checkOn:d.getElementsByTagName("input")[0].value==="on",optSelected:s.createElement("select").appendChild(s.createElement("option")).selected, +parentNode:d.removeChild(d.appendChild(s.createElement("div"))).parentNode===null,deleteExpando:true,checkClone:false,scriptEval:false,noCloneEvent:true,boxModel:null};b.type="text/javascript";try{b.appendChild(s.createTextNode("window."+f+"=1;"))}catch(i){}a.insertBefore(b,a.firstChild);if(A[f]){c.support.scriptEval=true;delete A[f]}try{delete b.test}catch(o){c.support.deleteExpando=false}a.removeChild(b);if(d.attachEvent&&d.fireEvent){d.attachEvent("onclick",function k(){c.support.noCloneEvent= +false;d.detachEvent("onclick",k)});d.cloneNode(true).fireEvent("onclick")}d=s.createElement("div");d.innerHTML="";a=s.createDocumentFragment();a.appendChild(d.firstChild);c.support.checkClone=a.cloneNode(true).cloneNode(true).lastChild.checked;c(function(){var k=s.createElement("div");k.style.width=k.style.paddingLeft="1px";s.body.appendChild(k);c.boxModel=c.support.boxModel=k.offsetWidth===2;s.body.removeChild(k).style.display="none"});a=function(k){var n= +s.createElement("div");k="on"+k;var r=k in n;if(!r){n.setAttribute(k,"return;");r=typeof n[k]==="function"}return r};c.support.submitBubbles=a("submit");c.support.changeBubbles=a("change");a=b=d=e=j=null}})();c.props={"for":"htmlFor","class":"className",readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing",rowspan:"rowSpan",colspan:"colSpan",tabindex:"tabIndex",usemap:"useMap",frameborder:"frameBorder"};var G="jQuery"+J(),Ya=0,za={};c.extend({cache:{},expando:G,noData:{embed:true,object:true, +applet:true},data:function(a,b,d){if(!(a.nodeName&&c.noData[a.nodeName.toLowerCase()])){a=a==A?za:a;var f=a[G],e=c.cache;if(!f&&typeof b==="string"&&d===w)return null;f||(f=++Ya);if(typeof b==="object"){a[G]=f;e[f]=c.extend(true,{},b)}else if(!e[f]){a[G]=f;e[f]={}}a=e[f];if(d!==w)a[b]=d;return typeof b==="string"?a[b]:a}},removeData:function(a,b){if(!(a.nodeName&&c.noData[a.nodeName.toLowerCase()])){a=a==A?za:a;var d=a[G],f=c.cache,e=f[d];if(b){if(e){delete e[b];c.isEmptyObject(e)&&c.removeData(a)}}else{if(c.support.deleteExpando)delete a[c.expando]; +else a.removeAttribute&&a.removeAttribute(c.expando);delete f[d]}}}});c.fn.extend({data:function(a,b){if(typeof a==="undefined"&&this.length)return c.data(this[0]);else if(typeof a==="object")return this.each(function(){c.data(this,a)});var d=a.split(".");d[1]=d[1]?"."+d[1]:"";if(b===w){var f=this.triggerHandler("getData"+d[1]+"!",[d[0]]);if(f===w&&this.length)f=c.data(this[0],a);return f===w&&d[1]?this.data(d[0]):f}else return this.trigger("setData"+d[1]+"!",[d[0],b]).each(function(){c.data(this, +a,b)})},removeData:function(a){return this.each(function(){c.removeData(this,a)})}});c.extend({queue:function(a,b,d){if(a){b=(b||"fx")+"queue";var f=c.data(a,b);if(!d)return f||[];if(!f||c.isArray(d))f=c.data(a,b,c.makeArray(d));else f.push(d);return f}},dequeue:function(a,b){b=b||"fx";var d=c.queue(a,b),f=d.shift();if(f==="inprogress")f=d.shift();if(f){b==="fx"&&d.unshift("inprogress");f.call(a,function(){c.dequeue(a,b)})}}});c.fn.extend({queue:function(a,b){if(typeof a!=="string"){b=a;a="fx"}if(b=== +w)return c.queue(this[0],a);return this.each(function(){var d=c.queue(this,a,b);a==="fx"&&d[0]!=="inprogress"&&c.dequeue(this,a)})},dequeue:function(a){return this.each(function(){c.dequeue(this,a)})},delay:function(a,b){a=c.fx?c.fx.speeds[a]||a:a;b=b||"fx";return this.queue(b,function(){var d=this;setTimeout(function(){c.dequeue(d,b)},a)})},clearQueue:function(a){return this.queue(a||"fx",[])}});var Aa=/[\n\t]/g,ca=/\s+/,Za=/\r/g,$a=/href|src|style/,ab=/(button|input)/i,bb=/(button|input|object|select|textarea)/i, +cb=/^(a|area)$/i,Ba=/radio|checkbox/;c.fn.extend({attr:function(a,b){return X(this,a,b,true,c.attr)},removeAttr:function(a){return this.each(function(){c.attr(this,a,"");this.nodeType===1&&this.removeAttribute(a)})},addClass:function(a){if(c.isFunction(a))return this.each(function(n){var r=c(this);r.addClass(a.call(this,n,r.attr("class")))});if(a&&typeof a==="string")for(var b=(a||"").split(ca),d=0,f=this.length;d-1)return true;return false},val:function(a){if(a===w){var b=this[0];if(b){if(c.nodeName(b,"option"))return(b.attributes.value||{}).specified?b.value:b.text;if(c.nodeName(b,"select")){var d=b.selectedIndex,f=[],e=b.options;b=b.type==="select-one";if(d<0)return null;var j=b?d:0;for(d=b?d+1:e.length;j=0;else if(c.nodeName(this,"select")){var u=c.makeArray(r);c("option",this).each(function(){this.selected= +c.inArray(c(this).val(),u)>=0});if(!u.length)this.selectedIndex=-1}else this.value=r}})}});c.extend({attrFn:{val:true,css:true,html:true,text:true,data:true,width:true,height:true,offset:true},attr:function(a,b,d,f){if(!a||a.nodeType===3||a.nodeType===8)return w;if(f&&b in c.attrFn)return c(a)[b](d);f=a.nodeType!==1||!c.isXMLDoc(a);var e=d!==w;b=f&&c.props[b]||b;if(a.nodeType===1){var j=$a.test(b);if(b in a&&f&&!j){if(e){b==="type"&&ab.test(a.nodeName)&&a.parentNode&&c.error("type property can't be changed"); +a[b]=d}if(c.nodeName(a,"form")&&a.getAttributeNode(b))return a.getAttributeNode(b).nodeValue;if(b==="tabIndex")return(b=a.getAttributeNode("tabIndex"))&&b.specified?b.value:bb.test(a.nodeName)||cb.test(a.nodeName)&&a.href?0:w;return a[b]}if(!c.support.style&&f&&b==="style"){if(e)a.style.cssText=""+d;return a.style.cssText}e&&a.setAttribute(b,""+d);a=!c.support.hrefNormalized&&f&&j?a.getAttribute(b,2):a.getAttribute(b);return a===null?w:a}return c.style(a,b,d)}});var O=/\.(.*)$/,db=function(a){return a.replace(/[^\w\s\.\|`]/g, +function(b){return"\\"+b})};c.event={add:function(a,b,d,f){if(!(a.nodeType===3||a.nodeType===8)){if(a.setInterval&&a!==A&&!a.frameElement)a=A;var e,j;if(d.handler){e=d;d=e.handler}if(!d.guid)d.guid=c.guid++;if(j=c.data(a)){var i=j.events=j.events||{},o=j.handle;if(!o)j.handle=o=function(){return typeof c!=="undefined"&&!c.event.triggered?c.event.handle.apply(o.elem,arguments):w};o.elem=a;b=b.split(" ");for(var k,n=0,r;k=b[n++];){j=e?c.extend({},e):{handler:d,data:f};if(k.indexOf(".")>-1){r=k.split("."); +k=r.shift();j.namespace=r.slice(0).sort().join(".")}else{r=[];j.namespace=""}j.type=k;j.guid=d.guid;var u=i[k],z=c.event.special[k]||{};if(!u){u=i[k]=[];if(!z.setup||z.setup.call(a,f,r,o)===false)if(a.addEventListener)a.addEventListener(k,o,false);else a.attachEvent&&a.attachEvent("on"+k,o)}if(z.add){z.add.call(a,j);if(!j.handler.guid)j.handler.guid=d.guid}u.push(j);c.event.global[k]=true}a=null}}},global:{},remove:function(a,b,d,f){if(!(a.nodeType===3||a.nodeType===8)){var e,j=0,i,o,k,n,r,u,z=c.data(a), +C=z&&z.events;if(z&&C){if(b&&b.type){d=b.handler;b=b.type}if(!b||typeof b==="string"&&b.charAt(0)==="."){b=b||"";for(e in C)c.event.remove(a,e+b)}else{for(b=b.split(" ");e=b[j++];){n=e;i=e.indexOf(".")<0;o=[];if(!i){o=e.split(".");e=o.shift();k=new RegExp("(^|\\.)"+c.map(o.slice(0).sort(),db).join("\\.(?:.*\\.)?")+"(\\.|$)")}if(r=C[e])if(d){n=c.event.special[e]||{};for(B=f||0;B=0){a.type= +e=e.slice(0,-1);a.exclusive=true}if(!d){a.stopPropagation();c.event.global[e]&&c.each(c.cache,function(){this.events&&this.events[e]&&c.event.trigger(a,b,this.handle.elem)})}if(!d||d.nodeType===3||d.nodeType===8)return w;a.result=w;a.target=d;b=c.makeArray(b);b.unshift(a)}a.currentTarget=d;(f=c.data(d,"handle"))&&f.apply(d,b);f=d.parentNode||d.ownerDocument;try{if(!(d&&d.nodeName&&c.noData[d.nodeName.toLowerCase()]))if(d["on"+e]&&d["on"+e].apply(d,b)===false)a.result=false}catch(j){}if(!a.isPropagationStopped()&& +f)c.event.trigger(a,b,f,true);else if(!a.isDefaultPrevented()){f=a.target;var i,o=c.nodeName(f,"a")&&e==="click",k=c.event.special[e]||{};if((!k._default||k._default.call(d,a)===false)&&!o&&!(f&&f.nodeName&&c.noData[f.nodeName.toLowerCase()])){try{if(f[e]){if(i=f["on"+e])f["on"+e]=null;c.event.triggered=true;f[e]()}}catch(n){}if(i)f["on"+e]=i;c.event.triggered=false}}},handle:function(a){var b,d,f,e;a=arguments[0]=c.event.fix(a||A.event);a.currentTarget=this;b=a.type.indexOf(".")<0&&!a.exclusive; +if(!b){d=a.type.split(".");a.type=d.shift();f=new RegExp("(^|\\.)"+d.slice(0).sort().join("\\.(?:.*\\.)?")+"(\\.|$)")}e=c.data(this,"events");d=e[a.type];if(e&&d){d=d.slice(0);e=0;for(var j=d.length;e-1?c.map(a.options,function(f){return f.selected}).join("-"):"";else if(a.nodeName.toLowerCase()==="select")d=a.selectedIndex;return d},fa=function(a,b){var d=a.target,f,e;if(!(!da.test(d.nodeName)||d.readOnly)){f=c.data(d,"_change_data");e=Fa(d);if(a.type!=="focusout"||d.type!=="radio")c.data(d,"_change_data", +e);if(!(f===w||e===f))if(f!=null||e){a.type="change";return c.event.trigger(a,b,d)}}};c.event.special.change={filters:{focusout:fa,click:function(a){var b=a.target,d=b.type;if(d==="radio"||d==="checkbox"||b.nodeName.toLowerCase()==="select")return fa.call(this,a)},keydown:function(a){var b=a.target,d=b.type;if(a.keyCode===13&&b.nodeName.toLowerCase()!=="textarea"||a.keyCode===32&&(d==="checkbox"||d==="radio")||d==="select-multiple")return fa.call(this,a)},beforeactivate:function(a){a=a.target;c.data(a, +"_change_data",Fa(a))}},setup:function(){if(this.type==="file")return false;for(var a in ea)c.event.add(this,a+".specialChange",ea[a]);return da.test(this.nodeName)},teardown:function(){c.event.remove(this,".specialChange");return da.test(this.nodeName)}};ea=c.event.special.change.filters}s.addEventListener&&c.each({focus:"focusin",blur:"focusout"},function(a,b){function d(f){f=c.event.fix(f);f.type=b;return c.event.handle.call(this,f)}c.event.special[b]={setup:function(){this.addEventListener(a, +d,true)},teardown:function(){this.removeEventListener(a,d,true)}}});c.each(["bind","one"],function(a,b){c.fn[b]=function(d,f,e){if(typeof d==="object"){for(var j in d)this[b](j,f,d[j],e);return this}if(c.isFunction(f)){e=f;f=w}var i=b==="one"?c.proxy(e,function(k){c(this).unbind(k,i);return e.apply(this,arguments)}):e;if(d==="unload"&&b!=="one")this.one(d,f,e);else{j=0;for(var o=this.length;j0){y=t;break}}t=t[g]}m[q]=y}}}var f=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g, +e=0,j=Object.prototype.toString,i=false,o=true;[0,0].sort(function(){o=false;return 0});var k=function(g,h,l,m){l=l||[];var q=h=h||s;if(h.nodeType!==1&&h.nodeType!==9)return[];if(!g||typeof g!=="string")return l;for(var p=[],v,t,y,S,H=true,M=x(h),I=g;(f.exec(""),v=f.exec(I))!==null;){I=v[3];p.push(v[1]);if(v[2]){S=v[3];break}}if(p.length>1&&r.exec(g))if(p.length===2&&n.relative[p[0]])t=ga(p[0]+p[1],h);else for(t=n.relative[p[0]]?[h]:k(p.shift(),h);p.length;){g=p.shift();if(n.relative[g])g+=p.shift(); +t=ga(g,t)}else{if(!m&&p.length>1&&h.nodeType===9&&!M&&n.match.ID.test(p[0])&&!n.match.ID.test(p[p.length-1])){v=k.find(p.shift(),h,M);h=v.expr?k.filter(v.expr,v.set)[0]:v.set[0]}if(h){v=m?{expr:p.pop(),set:z(m)}:k.find(p.pop(),p.length===1&&(p[0]==="~"||p[0]==="+")&&h.parentNode?h.parentNode:h,M);t=v.expr?k.filter(v.expr,v.set):v.set;if(p.length>0)y=z(t);else H=false;for(;p.length;){var D=p.pop();v=D;if(n.relative[D])v=p.pop();else D="";if(v==null)v=h;n.relative[D](y,v,M)}}else y=[]}y||(y=t);y||k.error(D|| +g);if(j.call(y)==="[object Array]")if(H)if(h&&h.nodeType===1)for(g=0;y[g]!=null;g++){if(y[g]&&(y[g]===true||y[g].nodeType===1&&E(h,y[g])))l.push(t[g])}else for(g=0;y[g]!=null;g++)y[g]&&y[g].nodeType===1&&l.push(t[g]);else l.push.apply(l,y);else z(y,l);if(S){k(S,q,l,m);k.uniqueSort(l)}return l};k.uniqueSort=function(g){if(B){i=o;g.sort(B);if(i)for(var h=1;h":function(g,h){var l=typeof h==="string";if(l&&!/\W/.test(h)){h=h.toLowerCase();for(var m=0,q=g.length;m=0))l||m.push(v);else if(l)h[p]=false;return false},ID:function(g){return g[1].replace(/\\/g,"")},TAG:function(g){return g[1].toLowerCase()}, +CHILD:function(g){if(g[1]==="nth"){var h=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(g[2]==="even"&&"2n"||g[2]==="odd"&&"2n+1"||!/\D/.test(g[2])&&"0n+"+g[2]||g[2]);g[2]=h[1]+(h[2]||1)-0;g[3]=h[3]-0}g[0]=e++;return g},ATTR:function(g,h,l,m,q,p){h=g[1].replace(/\\/g,"");if(!p&&n.attrMap[h])g[1]=n.attrMap[h];if(g[2]==="~=")g[4]=" "+g[4]+" ";return g},PSEUDO:function(g,h,l,m,q){if(g[1]==="not")if((f.exec(g[3])||"").length>1||/^\w/.test(g[3]))g[3]=k(g[3],null,null,h);else{g=k.filter(g[3],h,l,true^q);l||m.push.apply(m, +g);return false}else if(n.match.POS.test(g[0])||n.match.CHILD.test(g[0]))return true;return g},POS:function(g){g.unshift(true);return g}},filters:{enabled:function(g){return g.disabled===false&&g.type!=="hidden"},disabled:function(g){return g.disabled===true},checked:function(g){return g.checked===true},selected:function(g){return g.selected===true},parent:function(g){return!!g.firstChild},empty:function(g){return!g.firstChild},has:function(g,h,l){return!!k(l[3],g).length},header:function(g){return/h\d/i.test(g.nodeName)}, +text:function(g){return"text"===g.type},radio:function(g){return"radio"===g.type},checkbox:function(g){return"checkbox"===g.type},file:function(g){return"file"===g.type},password:function(g){return"password"===g.type},submit:function(g){return"submit"===g.type},image:function(g){return"image"===g.type},reset:function(g){return"reset"===g.type},button:function(g){return"button"===g.type||g.nodeName.toLowerCase()==="button"},input:function(g){return/input|select|textarea|button/i.test(g.nodeName)}}, +setFilters:{first:function(g,h){return h===0},last:function(g,h,l,m){return h===m.length-1},even:function(g,h){return h%2===0},odd:function(g,h){return h%2===1},lt:function(g,h,l){return hl[3]-0},nth:function(g,h,l){return l[3]-0===h},eq:function(g,h,l){return l[3]-0===h}},filter:{PSEUDO:function(g,h,l,m){var q=h[1],p=n.filters[q];if(p)return p(g,l,h,m);else if(q==="contains")return(g.textContent||g.innerText||a([g])||"").indexOf(h[3])>=0;else if(q==="not"){h= +h[3];l=0;for(m=h.length;l=0}},ID:function(g,h){return g.nodeType===1&&g.getAttribute("id")===h},TAG:function(g,h){return h==="*"&&g.nodeType===1||g.nodeName.toLowerCase()===h},CLASS:function(g,h){return(" "+(g.className||g.getAttribute("class"))+" ").indexOf(h)>-1},ATTR:function(g,h){var l=h[1];g=n.attrHandle[l]?n.attrHandle[l](g):g[l]!=null?g[l]:g.getAttribute(l);l=g+"";var m=h[2];h=h[4];return g==null?m==="!=":m=== +"="?l===h:m==="*="?l.indexOf(h)>=0:m==="~="?(" "+l+" ").indexOf(h)>=0:!h?l&&g!==false:m==="!="?l!==h:m==="^="?l.indexOf(h)===0:m==="$="?l.substr(l.length-h.length)===h:m==="|="?l===h||l.substr(0,h.length+1)===h+"-":false},POS:function(g,h,l,m){var q=n.setFilters[h[2]];if(q)return q(g,l,h,m)}}},r=n.match.POS;for(var u in n.match){n.match[u]=new RegExp(n.match[u].source+/(?![^\[]*\])(?![^\(]*\))/.source);n.leftMatch[u]=new RegExp(/(^(?:.|\r|\n)*?)/.source+n.match[u].source.replace(/\\(\d+)/g,function(g, +h){return"\\"+(h-0+1)}))}var z=function(g,h){g=Array.prototype.slice.call(g,0);if(h){h.push.apply(h,g);return h}return g};try{Array.prototype.slice.call(s.documentElement.childNodes,0)}catch(C){z=function(g,h){h=h||[];if(j.call(g)==="[object Array]")Array.prototype.push.apply(h,g);else if(typeof g.length==="number")for(var l=0,m=g.length;l";var l=s.documentElement;l.insertBefore(g,l.firstChild);if(s.getElementById(h)){n.find.ID=function(m,q,p){if(typeof q.getElementById!=="undefined"&&!p)return(q=q.getElementById(m[1]))?q.id===m[1]||typeof q.getAttributeNode!=="undefined"&& +q.getAttributeNode("id").nodeValue===m[1]?[q]:w:[]};n.filter.ID=function(m,q){var p=typeof m.getAttributeNode!=="undefined"&&m.getAttributeNode("id");return m.nodeType===1&&p&&p.nodeValue===q}}l.removeChild(g);l=g=null})();(function(){var g=s.createElement("div");g.appendChild(s.createComment(""));if(g.getElementsByTagName("*").length>0)n.find.TAG=function(h,l){l=l.getElementsByTagName(h[1]);if(h[1]==="*"){h=[];for(var m=0;l[m];m++)l[m].nodeType===1&&h.push(l[m]);l=h}return l};g.innerHTML=""; +if(g.firstChild&&typeof g.firstChild.getAttribute!=="undefined"&&g.firstChild.getAttribute("href")!=="#")n.attrHandle.href=function(h){return h.getAttribute("href",2)};g=null})();s.querySelectorAll&&function(){var g=k,h=s.createElement("div");h.innerHTML="

    ";if(!(h.querySelectorAll&&h.querySelectorAll(".TEST").length===0)){k=function(m,q,p,v){q=q||s;if(!v&&q.nodeType===9&&!x(q))try{return z(q.querySelectorAll(m),p)}catch(t){}return g(m,q,p,v)};for(var l in g)k[l]=g[l];h=null}}(); +(function(){var g=s.createElement("div");g.innerHTML="
    ";if(!(!g.getElementsByClassName||g.getElementsByClassName("e").length===0)){g.lastChild.className="e";if(g.getElementsByClassName("e").length!==1){n.order.splice(1,0,"CLASS");n.find.CLASS=function(h,l,m){if(typeof l.getElementsByClassName!=="undefined"&&!m)return l.getElementsByClassName(h[1])};g=null}}})();var E=s.compareDocumentPosition?function(g,h){return!!(g.compareDocumentPosition(h)&16)}: +function(g,h){return g!==h&&(g.contains?g.contains(h):true)},x=function(g){return(g=(g?g.ownerDocument||g:0).documentElement)?g.nodeName!=="HTML":false},ga=function(g,h){var l=[],m="",q;for(h=h.nodeType?[h]:h;q=n.match.PSEUDO.exec(g);){m+=q[0];g=g.replace(n.match.PSEUDO,"")}g=n.relative[g]?g+"*":g;q=0;for(var p=h.length;q=0===d})};c.fn.extend({find:function(a){for(var b=this.pushStack("","find",a),d=0,f=0,e=this.length;f0)for(var j=d;j0},closest:function(a,b){if(c.isArray(a)){var d=[],f=this[0],e,j= +{},i;if(f&&a.length){e=0;for(var o=a.length;e-1:c(f).is(e)){d.push({selector:i,elem:f});delete j[i]}}f=f.parentNode}}return d}var k=c.expr.match.POS.test(a)?c(a,b||this.context):null;return this.map(function(n,r){for(;r&&r.ownerDocument&&r!==b;){if(k?k.index(r)>-1:c(r).is(a))return r;r=r.parentNode}return null})},index:function(a){if(!a||typeof a=== +"string")return c.inArray(this[0],a?c(a):this.parent().children());return c.inArray(a.jquery?a[0]:a,this)},add:function(a,b){a=typeof a==="string"?c(a,b||this.context):c.makeArray(a);b=c.merge(this.get(),a);return this.pushStack(qa(a[0])||qa(b[0])?b:c.unique(b))},andSelf:function(){return this.add(this.prevObject)}});c.each({parent:function(a){return(a=a.parentNode)&&a.nodeType!==11?a:null},parents:function(a){return c.dir(a,"parentNode")},parentsUntil:function(a,b,d){return c.dir(a,"parentNode", +d)},next:function(a){return c.nth(a,2,"nextSibling")},prev:function(a){return c.nth(a,2,"previousSibling")},nextAll:function(a){return c.dir(a,"nextSibling")},prevAll:function(a){return c.dir(a,"previousSibling")},nextUntil:function(a,b,d){return c.dir(a,"nextSibling",d)},prevUntil:function(a,b,d){return c.dir(a,"previousSibling",d)},siblings:function(a){return c.sibling(a.parentNode.firstChild,a)},children:function(a){return c.sibling(a.firstChild)},contents:function(a){return c.nodeName(a,"iframe")? +a.contentDocument||a.contentWindow.document:c.makeArray(a.childNodes)}},function(a,b){c.fn[a]=function(d,f){var e=c.map(this,b,d);eb.test(a)||(f=d);if(f&&typeof f==="string")e=c.filter(f,e);e=this.length>1?c.unique(e):e;if((this.length>1||gb.test(f))&&fb.test(a))e=e.reverse();return this.pushStack(e,a,R.call(arguments).join(","))}});c.extend({filter:function(a,b,d){if(d)a=":not("+a+")";return c.find.matches(a,b)},dir:function(a,b,d){var f=[];for(a=a[b];a&&a.nodeType!==9&&(d===w||a.nodeType!==1||!c(a).is(d));){a.nodeType=== +1&&f.push(a);a=a[b]}return f},nth:function(a,b,d){b=b||1;for(var f=0;a;a=a[d])if(a.nodeType===1&&++f===b)break;return a},sibling:function(a,b){for(var d=[];a;a=a.nextSibling)a.nodeType===1&&a!==b&&d.push(a);return d}});var Ja=/ jQuery\d+="(?:\d+|null)"/g,V=/^\s+/,Ka=/(<([\w:]+)[^>]*?)\/>/g,hb=/^(?:area|br|col|embed|hr|img|input|link|meta|param)$/i,La=/<([\w:]+)/,ib=/"},F={option:[1,""],legend:[1,"
    ","
    "],thead:[1,"","
    "],tr:[2,"","
    "],td:[3,"","
    "],col:[2,"","
    "],area:[1,"",""],_default:[0,"",""]};F.optgroup=F.option;F.tbody=F.tfoot=F.colgroup=F.caption=F.thead;F.th=F.td;if(!c.support.htmlSerialize)F._default=[1,"div
    ","
    "];c.fn.extend({text:function(a){if(c.isFunction(a))return this.each(function(b){var d= +c(this);d.text(a.call(this,b,d.text()))});if(typeof a!=="object"&&a!==w)return this.empty().append((this[0]&&this[0].ownerDocument||s).createTextNode(a));return c.text(this)},wrapAll:function(a){if(c.isFunction(a))return this.each(function(d){c(this).wrapAll(a.call(this,d))});if(this[0]){var b=c(a,this[0].ownerDocument).eq(0).clone(true);this[0].parentNode&&b.insertBefore(this[0]);b.map(function(){for(var d=this;d.firstChild&&d.firstChild.nodeType===1;)d=d.firstChild;return d}).append(this)}return this}, +wrapInner:function(a){if(c.isFunction(a))return this.each(function(b){c(this).wrapInner(a.call(this,b))});return this.each(function(){var b=c(this),d=b.contents();d.length?d.wrapAll(a):b.append(a)})},wrap:function(a){return this.each(function(){c(this).wrapAll(a)})},unwrap:function(){return this.parent().each(function(){c.nodeName(this,"body")||c(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,true,function(a){this.nodeType===1&&this.appendChild(a)})}, +prepend:function(){return this.domManip(arguments,true,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,false,function(b){this.parentNode.insertBefore(b,this)});else if(arguments.length){var a=c(arguments[0]);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,false,function(b){this.parentNode.insertBefore(b, +this.nextSibling)});else if(arguments.length){var a=this.pushStack(this,"after",arguments);a.push.apply(a,c(arguments[0]).toArray());return a}},remove:function(a,b){for(var d=0,f;(f=this[d])!=null;d++)if(!a||c.filter(a,[f]).length){if(!b&&f.nodeType===1){c.cleanData(f.getElementsByTagName("*"));c.cleanData([f])}f.parentNode&&f.parentNode.removeChild(f)}return this},empty:function(){for(var a=0,b;(b=this[a])!=null;a++)for(b.nodeType===1&&c.cleanData(b.getElementsByTagName("*"));b.firstChild;)b.removeChild(b.firstChild); +return this},clone:function(a){var b=this.map(function(){if(!c.support.noCloneEvent&&!c.isXMLDoc(this)){var d=this.outerHTML,f=this.ownerDocument;if(!d){d=f.createElement("div");d.appendChild(this.cloneNode(true));d=d.innerHTML}return c.clean([d.replace(Ja,"").replace(/=([^="'>\s]+\/)>/g,'="$1">').replace(V,"")],f)[0]}else return this.cloneNode(true)});if(a===true){ra(this,b);ra(this.find("*"),b.find("*"))}return b},html:function(a){if(a===w)return this[0]&&this[0].nodeType===1?this[0].innerHTML.replace(Ja, +""):null;else if(typeof a==="string"&&!ta.test(a)&&(c.support.leadingWhitespace||!V.test(a))&&!F[(La.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(Ka,Ma);try{for(var b=0,d=this.length;b0||e.cacheable||this.length>1?k.cloneNode(true):k)}o.length&&c.each(o,Qa)}return this}});c.fragments={};c.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){c.fn[a]=function(d){var f=[];d=c(d);var e=this.length===1&&this[0].parentNode;if(e&&e.nodeType===11&&e.childNodes.length===1&&d.length===1){d[b](this[0]); +return this}else{e=0;for(var j=d.length;e0?this.clone(true):this).get();c.fn[b].apply(c(d[e]),i);f=f.concat(i)}return this.pushStack(f,a,d.selector)}}});c.extend({clean:function(a,b,d,f){b=b||s;if(typeof b.createElement==="undefined")b=b.ownerDocument||b[0]&&b[0].ownerDocument||s;for(var e=[],j=0,i;(i=a[j])!=null;j++){if(typeof i==="number")i+="";if(i){if(typeof i==="string"&&!jb.test(i))i=b.createTextNode(i);else if(typeof i==="string"){i=i.replace(Ka,Ma);var o=(La.exec(i)||["", +""])[1].toLowerCase(),k=F[o]||F._default,n=k[0],r=b.createElement("div");for(r.innerHTML=k[1]+i+k[2];n--;)r=r.lastChild;if(!c.support.tbody){n=ib.test(i);o=o==="table"&&!n?r.firstChild&&r.firstChild.childNodes:k[1]===""&&!n?r.childNodes:[];for(k=o.length-1;k>=0;--k)c.nodeName(o[k],"tbody")&&!o[k].childNodes.length&&o[k].parentNode.removeChild(o[k])}!c.support.leadingWhitespace&&V.test(i)&&r.insertBefore(b.createTextNode(V.exec(i)[0]),r.firstChild);i=r.childNodes}if(i.nodeType)e.push(i);else e= +c.merge(e,i)}}if(d)for(j=0;e[j];j++)if(f&&c.nodeName(e[j],"script")&&(!e[j].type||e[j].type.toLowerCase()==="text/javascript"))f.push(e[j].parentNode?e[j].parentNode.removeChild(e[j]):e[j]);else{e[j].nodeType===1&&e.splice.apply(e,[j+1,0].concat(c.makeArray(e[j].getElementsByTagName("script"))));d.appendChild(e[j])}return e},cleanData:function(a){for(var b,d,f=c.cache,e=c.event.special,j=c.support.deleteExpando,i=0,o;(o=a[i])!=null;i++)if(d=o[c.expando]){b=f[d];if(b.events)for(var k in b.events)e[k]? +c.event.remove(o,k):Ca(o,k,b.handle);if(j)delete o[c.expando];else o.removeAttribute&&o.removeAttribute(c.expando);delete f[d]}}});var kb=/z-?index|font-?weight|opacity|zoom|line-?height/i,Na=/alpha\([^)]*\)/,Oa=/opacity=([^)]*)/,ha=/float/i,ia=/-([a-z])/ig,lb=/([A-Z])/g,mb=/^-?\d+(?:px)?$/i,nb=/^-?\d/,ob={position:"absolute",visibility:"hidden",display:"block"},pb=["Left","Right"],qb=["Top","Bottom"],rb=s.defaultView&&s.defaultView.getComputedStyle,Pa=c.support.cssFloat?"cssFloat":"styleFloat",ja= +function(a,b){return b.toUpperCase()};c.fn.css=function(a,b){return X(this,a,b,true,function(d,f,e){if(e===w)return c.curCSS(d,f);if(typeof e==="number"&&!kb.test(f))e+="px";c.style(d,f,e)})};c.extend({style:function(a,b,d){if(!a||a.nodeType===3||a.nodeType===8)return w;if((b==="width"||b==="height")&&parseFloat(d)<0)d=w;var f=a.style||a,e=d!==w;if(!c.support.opacity&&b==="opacity"){if(e){f.zoom=1;b=parseInt(d,10)+""==="NaN"?"":"alpha(opacity="+d*100+")";a=f.filter||c.curCSS(a,"filter")||"";f.filter= +Na.test(a)?a.replace(Na,b):b}return f.filter&&f.filter.indexOf("opacity=")>=0?parseFloat(Oa.exec(f.filter)[1])/100+"":""}if(ha.test(b))b=Pa;b=b.replace(ia,ja);if(e)f[b]=d;return f[b]},css:function(a,b,d,f){if(b==="width"||b==="height"){var e,j=b==="width"?pb:qb;function i(){e=b==="width"?a.offsetWidth:a.offsetHeight;f!=="border"&&c.each(j,function(){f||(e-=parseFloat(c.curCSS(a,"padding"+this,true))||0);if(f==="margin")e+=parseFloat(c.curCSS(a,"margin"+this,true))||0;else e-=parseFloat(c.curCSS(a, +"border"+this+"Width",true))||0})}a.offsetWidth!==0?i():c.swap(a,ob,i);return Math.max(0,Math.round(e))}return c.curCSS(a,b,d)},curCSS:function(a,b,d){var f,e=a.style;if(!c.support.opacity&&b==="opacity"&&a.currentStyle){f=Oa.test(a.currentStyle.filter||"")?parseFloat(RegExp.$1)/100+"":"";return f===""?"1":f}if(ha.test(b))b=Pa;if(!d&&e&&e[b])f=e[b];else if(rb){if(ha.test(b))b="float";b=b.replace(lb,"-$1").toLowerCase();e=a.ownerDocument.defaultView;if(!e)return null;if(a=e.getComputedStyle(a,null))f= +a.getPropertyValue(b);if(b==="opacity"&&f==="")f="1"}else if(a.currentStyle){d=b.replace(ia,ja);f=a.currentStyle[b]||a.currentStyle[d];if(!mb.test(f)&&nb.test(f)){b=e.left;var j=a.runtimeStyle.left;a.runtimeStyle.left=a.currentStyle.left;e.left=d==="fontSize"?"1em":f||0;f=e.pixelLeft+"px";e.left=b;a.runtimeStyle.left=j}}return f},swap:function(a,b,d){var f={};for(var e in b){f[e]=a.style[e];a.style[e]=b[e]}d.call(a);for(e in b)a.style[e]=f[e]}});if(c.expr&&c.expr.filters){c.expr.filters.hidden=function(a){var b= +a.offsetWidth,d=a.offsetHeight,f=a.nodeName.toLowerCase()==="tr";return b===0&&d===0&&!f?true:b>0&&d>0&&!f?false:c.curCSS(a,"display")==="none"};c.expr.filters.visible=function(a){return!c.expr.filters.hidden(a)}}var sb=J(),tb=//gi,ub=/select|textarea/i,vb=/color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week/i,N=/=\?(&|$)/,ka=/\?/,wb=/(\?|&)_=.*?(&|$)/,xb=/^(\w+:)?\/\/([^\/?#]+)/,yb=/%20/g,zb=c.fn.load;c.fn.extend({load:function(a,b,d){if(typeof a!== +"string")return zb.call(this,a);else if(!this.length)return this;var f=a.indexOf(" ");if(f>=0){var e=a.slice(f,a.length);a=a.slice(0,f)}f="GET";if(b)if(c.isFunction(b)){d=b;b=null}else if(typeof b==="object"){b=c.param(b,c.ajaxSettings.traditional);f="POST"}var j=this;c.ajax({url:a,type:f,dataType:"html",data:b,complete:function(i,o){if(o==="success"||o==="notmodified")j.html(e?c("
    ").append(i.responseText.replace(tb,"")).find(e):i.responseText);d&&j.each(d,[i.responseText,o,i])}});return this}, +serialize:function(){return c.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?c.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||ub.test(this.nodeName)||vb.test(this.type))}).map(function(a,b){a=c(this).val();return a==null?null:c.isArray(a)?c.map(a,function(d){return{name:b.name,value:d}}):{name:b.name,value:a}}).get()}});c.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "), +function(a,b){c.fn[b]=function(d){return this.bind(b,d)}});c.extend({get:function(a,b,d,f){if(c.isFunction(b)){f=f||d;d=b;b=null}return c.ajax({type:"GET",url:a,data:b,success:d,dataType:f})},getScript:function(a,b){return c.get(a,null,b,"script")},getJSON:function(a,b,d){return c.get(a,b,d,"json")},post:function(a,b,d,f){if(c.isFunction(b)){f=f||d;d=b;b={}}return c.ajax({type:"POST",url:a,data:b,success:d,dataType:f})},ajaxSetup:function(a){c.extend(c.ajaxSettings,a)},ajaxSettings:{url:location.href, +global:true,type:"GET",contentType:"application/x-www-form-urlencoded",processData:true,async:true,xhr:A.XMLHttpRequest&&(A.location.protocol!=="file:"||!A.ActiveXObject)?function(){return new A.XMLHttpRequest}:function(){try{return new A.ActiveXObject("Microsoft.XMLHTTP")}catch(a){}},accepts:{xml:"application/xml, text/xml",html:"text/html",script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},lastModified:{},etag:{},ajax:function(a){function b(){e.success&& +e.success.call(k,o,i,x);e.global&&f("ajaxSuccess",[x,e])}function d(){e.complete&&e.complete.call(k,x,i);e.global&&f("ajaxComplete",[x,e]);e.global&&!--c.active&&c.event.trigger("ajaxStop")}function f(q,p){(e.context?c(e.context):c.event).trigger(q,p)}var e=c.extend(true,{},c.ajaxSettings,a),j,i,o,k=a&&a.context||e,n=e.type.toUpperCase();if(e.data&&e.processData&&typeof e.data!=="string")e.data=c.param(e.data,e.traditional);if(e.dataType==="jsonp"){if(n==="GET")N.test(e.url)||(e.url+=(ka.test(e.url)? +"&":"?")+(e.jsonp||"callback")+"=?");else if(!e.data||!N.test(e.data))e.data=(e.data?e.data+"&":"")+(e.jsonp||"callback")+"=?";e.dataType="json"}if(e.dataType==="json"&&(e.data&&N.test(e.data)||N.test(e.url))){j=e.jsonpCallback||"jsonp"+sb++;if(e.data)e.data=(e.data+"").replace(N,"="+j+"$1");e.url=e.url.replace(N,"="+j+"$1");e.dataType="script";A[j]=A[j]||function(q){o=q;b();d();A[j]=w;try{delete A[j]}catch(p){}z&&z.removeChild(C)}}if(e.dataType==="script"&&e.cache===null)e.cache=false;if(e.cache=== +false&&n==="GET"){var r=J(),u=e.url.replace(wb,"$1_="+r+"$2");e.url=u+(u===e.url?(ka.test(e.url)?"&":"?")+"_="+r:"")}if(e.data&&n==="GET")e.url+=(ka.test(e.url)?"&":"?")+e.data;e.global&&!c.active++&&c.event.trigger("ajaxStart");r=(r=xb.exec(e.url))&&(r[1]&&r[1]!==location.protocol||r[2]!==location.host);if(e.dataType==="script"&&n==="GET"&&r){var z=s.getElementsByTagName("head")[0]||s.documentElement,C=s.createElement("script");C.src=e.url;if(e.scriptCharset)C.charset=e.scriptCharset;if(!j){var B= +false;C.onload=C.onreadystatechange=function(){if(!B&&(!this.readyState||this.readyState==="loaded"||this.readyState==="complete")){B=true;b();d();C.onload=C.onreadystatechange=null;z&&C.parentNode&&z.removeChild(C)}}}z.insertBefore(C,z.firstChild);return w}var E=false,x=e.xhr();if(x){e.username?x.open(n,e.url,e.async,e.username,e.password):x.open(n,e.url,e.async);try{if(e.data||a&&a.contentType)x.setRequestHeader("Content-Type",e.contentType);if(e.ifModified){c.lastModified[e.url]&&x.setRequestHeader("If-Modified-Since", +c.lastModified[e.url]);c.etag[e.url]&&x.setRequestHeader("If-None-Match",c.etag[e.url])}r||x.setRequestHeader("X-Requested-With","XMLHttpRequest");x.setRequestHeader("Accept",e.dataType&&e.accepts[e.dataType]?e.accepts[e.dataType]+", */*":e.accepts._default)}catch(ga){}if(e.beforeSend&&e.beforeSend.call(k,x,e)===false){e.global&&!--c.active&&c.event.trigger("ajaxStop");x.abort();return false}e.global&&f("ajaxSend",[x,e]);var g=x.onreadystatechange=function(q){if(!x||x.readyState===0||q==="abort"){E|| +d();E=true;if(x)x.onreadystatechange=c.noop}else if(!E&&x&&(x.readyState===4||q==="timeout")){E=true;x.onreadystatechange=c.noop;i=q==="timeout"?"timeout":!c.httpSuccess(x)?"error":e.ifModified&&c.httpNotModified(x,e.url)?"notmodified":"success";var p;if(i==="success")try{o=c.httpData(x,e.dataType,e)}catch(v){i="parsererror";p=v}if(i==="success"||i==="notmodified")j||b();else c.handleError(e,x,i,p);d();q==="timeout"&&x.abort();if(e.async)x=null}};try{var h=x.abort;x.abort=function(){x&&h.call(x); +g("abort")}}catch(l){}e.async&&e.timeout>0&&setTimeout(function(){x&&!E&&g("timeout")},e.timeout);try{x.send(n==="POST"||n==="PUT"||n==="DELETE"?e.data:null)}catch(m){c.handleError(e,x,null,m);d()}e.async||g();return x}},handleError:function(a,b,d,f){if(a.error)a.error.call(a.context||a,b,d,f);if(a.global)(a.context?c(a.context):c.event).trigger("ajaxError",[b,a,f])},active:0,httpSuccess:function(a){try{return!a.status&&location.protocol==="file:"||a.status>=200&&a.status<300||a.status===304||a.status=== +1223||a.status===0}catch(b){}return false},httpNotModified:function(a,b){var d=a.getResponseHeader("Last-Modified"),f=a.getResponseHeader("Etag");if(d)c.lastModified[b]=d;if(f)c.etag[b]=f;return a.status===304||a.status===0},httpData:function(a,b,d){var f=a.getResponseHeader("content-type")||"",e=b==="xml"||!b&&f.indexOf("xml")>=0;a=e?a.responseXML:a.responseText;e&&a.documentElement.nodeName==="parsererror"&&c.error("parsererror");if(d&&d.dataFilter)a=d.dataFilter(a,b);if(typeof a==="string")if(b=== +"json"||!b&&f.indexOf("json")>=0)a=c.parseJSON(a);else if(b==="script"||!b&&f.indexOf("javascript")>=0)c.globalEval(a);return a},param:function(a,b){function d(i,o){if(c.isArray(o))c.each(o,function(k,n){b||/\[\]$/.test(i)?f(i,n):d(i+"["+(typeof n==="object"||c.isArray(n)?k:"")+"]",n)});else!b&&o!=null&&typeof o==="object"?c.each(o,function(k,n){d(i+"["+k+"]",n)}):f(i,o)}function f(i,o){o=c.isFunction(o)?o():o;e[e.length]=encodeURIComponent(i)+"="+encodeURIComponent(o)}var e=[];if(b===w)b=c.ajaxSettings.traditional; +if(c.isArray(a)||a.jquery)c.each(a,function(){f(this.name,this.value)});else for(var j in a)d(j,a[j]);return e.join("&").replace(yb,"+")}});var la={},Ab=/toggle|show|hide/,Bb=/^([+-]=)?([\d+-.]+)(.*)$/,W,va=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]];c.fn.extend({show:function(a,b){if(a||a===0)return this.animate(K("show",3),a,b);else{a=0;for(b=this.length;a").appendTo("body");f=e.css("display");if(f==="none")f="block";e.remove();la[d]=f}c.data(this[a],"olddisplay",f)}}a=0;for(b=this.length;a=0;f--)if(d[f].elem===this){b&&d[f](true);d.splice(f,1)}});b||this.dequeue();return this}});c.each({slideDown:K("show",1),slideUp:K("hide",1),slideToggle:K("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"}},function(a,b){c.fn[a]=function(d,f){return this.animate(b,d,f)}});c.extend({speed:function(a,b,d){var f=a&&typeof a==="object"?a:{complete:d||!d&&b||c.isFunction(a)&&a,duration:a,easing:d&&b||b&&!c.isFunction(b)&&b};f.duration=c.fx.off?0:typeof f.duration=== +"number"?f.duration:c.fx.speeds[f.duration]||c.fx.speeds._default;f.old=f.complete;f.complete=function(){f.queue!==false&&c(this).dequeue();c.isFunction(f.old)&&f.old.call(this)};return f},easing:{linear:function(a,b,d,f){return d+f*a},swing:function(a,b,d,f){return(-Math.cos(a*Math.PI)/2+0.5)*f+d}},timers:[],fx:function(a,b,d){this.options=b;this.elem=a;this.prop=d;if(!b.orig)b.orig={}}});c.fx.prototype={update:function(){this.options.step&&this.options.step.call(this.elem,this.now,this);(c.fx.step[this.prop]|| +c.fx.step._default)(this);if((this.prop==="height"||this.prop==="width")&&this.elem.style)this.elem.style.display="block"},cur:function(a){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null))return this.elem[this.prop];return(a=parseFloat(c.css(this.elem,this.prop,a)))&&a>-10000?a:parseFloat(c.curCSS(this.elem,this.prop))||0},custom:function(a,b,d){function f(j){return e.step(j)}this.startTime=J();this.start=a;this.end=b;this.unit=d||this.unit||"px";this.now=this.start; +this.pos=this.state=0;var e=this;f.elem=this.elem;if(f()&&c.timers.push(f)&&!W)W=setInterval(c.fx.tick,13)},show:function(){this.options.orig[this.prop]=c.style(this.elem,this.prop);this.options.show=true;this.custom(this.prop==="width"||this.prop==="height"?1:0,this.cur());c(this.elem).show()},hide:function(){this.options.orig[this.prop]=c.style(this.elem,this.prop);this.options.hide=true;this.custom(this.cur(),0)},step:function(a){var b=J(),d=true;if(a||b>=this.options.duration+this.startTime){this.now= +this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;for(var f in this.options.curAnim)if(this.options.curAnim[f]!==true)d=false;if(d){if(this.options.display!=null){this.elem.style.overflow=this.options.overflow;a=c.data(this.elem,"olddisplay");this.elem.style.display=a?a:this.options.display;if(c.css(this.elem,"display")==="none")this.elem.style.display="block"}this.options.hide&&c(this.elem).hide();if(this.options.hide||this.options.show)for(var e in this.options.curAnim)c.style(this.elem, +e,this.options.orig[e]);this.options.complete.call(this.elem)}return false}else{e=b-this.startTime;this.state=e/this.options.duration;a=this.options.easing||(c.easing.swing?"swing":"linear");this.pos=c.easing[this.options.specialEasing&&this.options.specialEasing[this.prop]||a](this.state,e,0,1,this.options.duration);this.now=this.start+(this.end-this.start)*this.pos;this.update()}return true}};c.extend(c.fx,{tick:function(){for(var a=c.timers,b=0;b
    "; +a.insertBefore(b,a.firstChild);d=b.firstChild;f=d.firstChild;e=d.nextSibling.firstChild.firstChild;this.doesNotAddBorder=f.offsetTop!==5;this.doesAddBorderForTableAndCells=e.offsetTop===5;f.style.position="fixed";f.style.top="20px";this.supportsFixedPosition=f.offsetTop===20||f.offsetTop===15;f.style.position=f.style.top="";d.style.overflow="hidden";d.style.position="relative";this.subtractsBorderForOverflowNotVisible=f.offsetTop===-5;this.doesNotIncludeMarginInBodyOffset=a.offsetTop!==j;a.removeChild(b); +c.offset.initialize=c.noop},bodyOffset:function(a){var b=a.offsetTop,d=a.offsetLeft;c.offset.initialize();if(c.offset.doesNotIncludeMarginInBodyOffset){b+=parseFloat(c.curCSS(a,"marginTop",true))||0;d+=parseFloat(c.curCSS(a,"marginLeft",true))||0}return{top:b,left:d}},setOffset:function(a,b,d){if(/static/.test(c.curCSS(a,"position")))a.style.position="relative";var f=c(a),e=f.offset(),j=parseInt(c.curCSS(a,"top",true),10)||0,i=parseInt(c.curCSS(a,"left",true),10)||0;if(c.isFunction(b))b=b.call(a, +d,e);d={top:b.top-e.top+j,left:b.left-e.left+i};"using"in b?b.using.call(a,d):f.css(d)}};c.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),d=this.offset(),f=/^body|html$/i.test(b[0].nodeName)?{top:0,left:0}:b.offset();d.top-=parseFloat(c.curCSS(a,"marginTop",true))||0;d.left-=parseFloat(c.curCSS(a,"marginLeft",true))||0;f.top+=parseFloat(c.curCSS(b[0],"borderTopWidth",true))||0;f.left+=parseFloat(c.curCSS(b[0],"borderLeftWidth",true))||0;return{top:d.top- +f.top,left:d.left-f.left}},offsetParent:function(){return this.map(function(){for(var a=this.offsetParent||s.body;a&&!/^body|html$/i.test(a.nodeName)&&c.css(a,"position")==="static";)a=a.offsetParent;return a})}});c.each(["Left","Top"],function(a,b){var d="scroll"+b;c.fn[d]=function(f){var e=this[0],j;if(!e)return null;if(f!==w)return this.each(function(){if(j=wa(this))j.scrollTo(!a?f:c(j).scrollLeft(),a?f:c(j).scrollTop());else this[d]=f});else return(j=wa(e))?"pageXOffset"in j?j[a?"pageYOffset": +"pageXOffset"]:c.support.boxModel&&j.document.documentElement[d]||j.document.body[d]:e[d]}});c.each(["Height","Width"],function(a,b){var d=b.toLowerCase();c.fn["inner"+b]=function(){return this[0]?c.css(this[0],d,false,"padding"):null};c.fn["outer"+b]=function(f){return this[0]?c.css(this[0],d,false,f?"margin":"border"):null};c.fn[d]=function(f){var e=this[0];if(!e)return f==null?null:this;if(c.isFunction(f))return this.each(function(j){var i=c(this);i[d](f.call(this,j,i[d]()))});return"scrollTo"in +e&&e.document?e.document.compatMode==="CSS1Compat"&&e.document.documentElement["client"+b]||e.document.body["client"+b]:e.nodeType===9?Math.max(e.documentElement["client"+b],e.body["scroll"+b],e.documentElement["scroll"+b],e.body["offset"+b],e.documentElement["offset"+b]):f===w?c.css(e,d):this.css(d,typeof f==="string"?f:f+"px")}});A.jQuery=A.$=c})(window); diff --git a/js/vendor/test/qunit.css b/js/vendor/test/qunit.css new file mode 100644 index 00000000..9d525291 --- /dev/null +++ b/js/vendor/test/qunit.css @@ -0,0 +1,140 @@ + +ol#qunit-tests { + font-family:"Helvetica Neue Light", "HelveticaNeue-Light", "Helvetica Neue", Calibri, Helvetica, Arial; + margin:0; + padding:0; + list-style-position:inside; + + font-size: smaller; +} +ol#qunit-tests li{ + padding:0.4em 0.5em 0.4em 2.5em; + border-bottom:1px solid #fff; + font-size:small; + list-style-position:inside; +} +ol#qunit-tests li ol{ + box-shadow: inset 0px 2px 13px #999; + -moz-box-shadow: inset 0px 2px 13px #999; + -webkit-box-shadow: inset 0px 2px 13px #999; + margin-top:0.5em; + margin-left:0; + padding:0.5em; + background-color:#fff; + border-radius:15px; + -moz-border-radius: 15px; + -webkit-border-radius: 15px; +} +ol#qunit-tests li li{ + border-bottom:none; + margin:0.5em; + background-color:#fff; + list-style-position: inside; + padding:0.4em 0.5em 0.4em 0.5em; +} + +ol#qunit-tests li li.pass{ + border-left:26px solid #C6E746; + background-color:#fff; + color:#5E740B; +} +ol#qunit-tests li li.fail{ + border-left:26px solid #EE5757; + background-color:#fff; + color:#710909; +} +ol#qunit-tests li.pass{ + background-color:#D2E0E6; + color:#528CE0; +} +ol#qunit-tests li.fail{ + background-color:#EE5757; + color:#000; +} +ol#qunit-tests li.pass span.test-name{ + color: #366097; +} +ol#qunit-tests li.fail span.test-name{ + color: #000000; +} +ol#qunit-tests li.pass span.module-name{ + +} +ol#qunit-tests li.fail span.module-name{ + color: #000000; +} +ol#qunit-tests li li.fail span.test-actual { + color: #EE5757; +} +ol#qunit-tests li li.pass span.test-expected { + color: #999999; +} +ol#qunit-tests li li.fail span.test-expected { + color: green; +} +ol#qunit-tests li strong { + cursor:pointer; +} +h1#qunit-header{ + background-color:#0d3349; + margin:0; + padding:0.5em 0 0.5em 1em; + color:#fff; + font-family:"Helvetica Neue Light", "HelveticaNeue-Light", "Helvetica Neue", Calibri, Helvetica, Arial; + border-top-right-radius:15px; + border-top-left-radius:15px; + -moz-border-radius-topright:15px; + -moz-border-radius-topleft:15px; + -webkit-border-top-right-radius:15px; + -webkit-border-top-left-radius:15px; + text-shadow: rgba(0, 0, 0, 0.5) 4px 4px 1px; +} +h2#qunit-banner{ + font-family:"Helvetica Neue Light", "HelveticaNeue-Light", "Helvetica Neue", Calibri, Helvetica, Arial; + height:5px; + margin:0; + padding:0; +} +h2#qunit-banner.qunit-pass{ + background-color:#C6E746; +} +h2#qunit-banner.qunit-fail, #qunit-testrunner-toolbar { + background-color:#EE5757; +} +#qunit-testrunner-toolbar { + font-family:"Helvetica Neue Light", "HelveticaNeue-Light", "Helvetica Neue", Calibri, Helvetica, Arial; + padding:0; + /*width:80%;*/ + padding:0em 0 0.5em 2em; + font-size: small; +} +h2#qunit-userAgent { + font-family:"Helvetica Neue Light", "HelveticaNeue-Light", "Helvetica Neue", Calibri, Helvetica, Arial; + background-color:#2b81af; + margin:0; + padding:0; + color:#fff; + font-size: small; + padding:0.5em 0 0.5em 2.5em; + text-shadow: rgba(0, 0, 0, 0.5) 2px 2px 1px; +} +p#qunit-testresult{ + font-family:"Helvetica Neue Light", "HelveticaNeue-Light", "Helvetica Neue", Calibri, Helvetica, Arial; + margin:0; + font-size: small; + color:#2b81af; + border-bottom-right-radius:15px; + border-bottom-left-radius:15px; + -moz-border-radius-bottomright:15px; + -moz-border-radius-bottomleft:15px; + -webkit-border-bottom-right-radius:15px; + -webkit-border-bottom-left-radius:15px; + background-color:#D2E0E6; + padding:0.5em 0.5em 0.5em 2.5em; +} +strong b.fail{ + color:#710909; +} +strong b.pass{ + color:#5E740B; +} \ No newline at end of file diff --git a/js/vendor/test/qunit.js b/js/vendor/test/qunit.js new file mode 100644 index 00000000..8316a667 --- /dev/null +++ b/js/vendor/test/qunit.js @@ -0,0 +1,1128 @@ +/* + * QUnit - A JavaScript Unit Testing Framework + * + * http://docs.jquery.com/QUnit + * + * Copyright (c) 2009 John Resig, Jörn Zaefferer + * Dual licensed under the MIT (MIT-LICENSE.txt) + * and GPL (GPL-LICENSE.txt) licenses. + */ + +(function(window) { + +var QUnit = { + + // Initialize the configuration options + init: function() { + extend(config, { + stats: { all: 0, bad: 0 }, + moduleStats: { all: 0, bad: 0 }, + started: +new Date, + updateRate: 1000, + blocking: false, + autostart: true, + autorun: false, + assertions: [], + filters: [], + queue: [] + }); + + var tests = id("qunit-tests"), + banner = id("qunit-banner"), + result = id("qunit-testresult"); + + if ( tests ) { + tests.innerHTML = ""; + } + + if ( banner ) { + banner.className = ""; + } + + if ( result ) { + result.parentNode.removeChild( result ); + } + }, + + // call on start of module test to prepend name to all tests + module: function(name, testEnvironment) { + config.currentModule = name; + + synchronize(function() { + if ( config.currentModule ) { + QUnit.moduleDone( config.currentModule, config.moduleStats.bad, config.moduleStats.all ); + } + + config.currentModule = name; + config.moduleTestEnvironment = testEnvironment; + config.moduleStats = { all: 0, bad: 0 }; + + QUnit.moduleStart( name, testEnvironment ); + }); + }, + + asyncTest: function(testName, expected, callback) { + if ( arguments.length === 2 ) { + callback = expected; + expected = 0; + } + + QUnit.test(testName, expected, callback, true); + }, + + test: function(testName, expected, callback, async) { + var name = '' + testName + '', testEnvironment, testEnvironmentArg; + + if ( arguments.length === 2 ) { + callback = expected; + expected = null; + } + // is 2nd argument a testEnvironment? + if ( expected && typeof expected === 'object') { + testEnvironmentArg = expected; + expected = null; + } + + if ( config.currentModule ) { + name = '' + config.currentModule + ": " + name; + } + + if ( !validTest(config.currentModule + ": " + testName) ) { + return; + } + + synchronize(function() { + + testEnvironment = extend({ + setup: function() {}, + teardown: function() {} + }, config.moduleTestEnvironment); + if (testEnvironmentArg) { + extend(testEnvironment,testEnvironmentArg); + } + + QUnit.testStart( testName, testEnvironment ); + + // allow utility functions to access the current test environment + QUnit.current_testEnvironment = testEnvironment; + + config.assertions = []; + config.expected = expected; + + var tests = id("qunit-tests"); + if (tests) { + var b = document.createElement("strong"); + b.innerHTML = "Running " + name; + var li = document.createElement("li"); + li.appendChild( b ); + li.id = "current-test-output"; + tests.appendChild( li ) + } + + try { + if ( !config.pollution ) { + saveGlobal(); + } + + testEnvironment.setup.call(testEnvironment); + } catch(e) { + QUnit.ok( false, "Setup failed on " + name + ": " + e.message ); + } + }); + + synchronize(function() { + if ( async ) { + QUnit.stop(); + } + + try { + callback.call(testEnvironment); + } catch(e) { + fail("Test " + name + " died, exception and test follows", e, callback); + QUnit.ok( false, "Died on test #" + (config.assertions.length + 1) + ": " + e.message ); + if( e.stack ) console.error( e.stack ); + // else next test will carry the responsibility + saveGlobal(); + + // Restart the tests if they're blocking + if ( config.blocking ) { + start(); + } + } + }); + + synchronize(function() { + try { + checkPollution(); + testEnvironment.teardown.call(testEnvironment); + } catch(e) { + QUnit.ok( false, "Teardown failed on " + name + ": " + e.message ); + } + }); + + synchronize(function() { + try { + QUnit.reset(); + } catch(e) { + fail("reset() failed, following Test " + name + ", exception and reset fn follows", e, reset); + } + + if ( config.expected && config.expected != config.assertions.length ) { + QUnit.ok( false, "Expected " + config.expected + " assertions, but " + config.assertions.length + " were run" ); + } + + var good = 0, bad = 0, + tests = id("qunit-tests"); + + config.stats.all += config.assertions.length; + config.moduleStats.all += config.assertions.length; + + if ( tests ) { + var ol = document.createElement("ol"); + ol.style.display = "none"; + + for ( var i = 0; i < config.assertions.length; i++ ) { + var assertion = config.assertions[i]; + + var li = document.createElement("li"); + li.className = assertion.result ? "pass" : "fail"; + li.innerHTML = assertion.message || "(no message)"; + ol.appendChild( li ); + + if ( assertion.result ) { + good++; + } else { + bad++; + config.stats.bad++; + config.moduleStats.bad++; + } + } + + var b = document.createElement("strong"); + b.innerHTML = name + " (" + bad + ", " + good + ", " + config.assertions.length + ")"; + + addEvent(b, "click", function() { + var next = b.nextSibling, display = next.style.display; + next.style.display = display === "none" ? "block" : "none"; + }); + + addEvent(b, "dblclick", function(e) { + var target = e && e.target ? e.target : window.event.srcElement; + if ( target.nodeName.toLowerCase() == "span" || target.nodeName.toLowerCase() == "b" ) { + target = target.parentNode; + } + if ( window.location && target.nodeName.toLowerCase() === "strong" ) { + window.location.href = window.location.href.match(/^(.+?)(\?.*)?(\#.*)?$/)[1] + "?" + encodeURIComponent(getText([target]).replace(/\(.+\)$/, "").replace(/(^\s*|\s*$)/g, "")); + } + }); + + var li = id("current-test-output"); + li.id = ""; + li.className = bad ? "fail" : "pass"; + li.removeChild( li.firstChild ); + li.appendChild( b ); + li.appendChild( ol ); + + if ( bad ) { + var toolbar = id("qunit-testrunner-toolbar"); + if ( toolbar ) { + toolbar.style.display = "block"; + id("qunit-filter-pass").disabled = null; + id("qunit-filter-missing").disabled = null; + } + } + + } else { + for ( var i = 0; i < config.assertions.length; i++ ) { + if ( !config.assertions[i].result ) { + bad++; + config.stats.bad++; + config.moduleStats.bad++; + } + } + } + + QUnit.testDone( testName, bad, config.assertions.length ); + + if ( !window.setTimeout && !config.queue.length ) { + done(); + } + }); + + if ( window.setTimeout && !config.doneTimer ) { + config.doneTimer = window.setTimeout(function(){ + if ( !config.queue.length ) { + done(); + } else { + synchronize( done ); + } + }, 13); + } + }, + + /** + * Specify the number of expected assertions to gurantee that failed test (no assertions are run at all) don't slip through. + */ + expect: function(asserts) { + config.expected = asserts; + }, + + /** + * Asserts true. + * @example ok( "asdfasdf".length > 5, "There must be at least 5 chars" ); + */ + ok: function(a, msg) { + msg = escapeHtml(msg); + QUnit.log(a, msg); + + config.assertions.push({ + result: !!a, + message: msg + }); + }, + + /** + * Checks that the first two arguments are equal, with an optional message. + * Prints out both actual and expected values. + * + * Prefered to ok( actual == expected, message ) + * + * @example equal( format("Received {0} bytes.", 2), "Received 2 bytes." ); + * + * @param Object actual + * @param Object expected + * @param String message (optional) + */ + equal: function(actual, expected, message) { + push(expected == actual, actual, expected, message); + }, + + notEqual: function(actual, expected, message) { + push(expected != actual, actual, expected, message); + }, + + deepEqual: function(actual, expected, message) { + push(QUnit.equiv(actual, expected), actual, expected, message); + }, + + notDeepEqual: function(actual, expected, message) { + push(!QUnit.equiv(actual, expected), actual, expected, message); + }, + + strictEqual: function(actual, expected, message) { + push(expected === actual, actual, expected, message); + }, + + notStrictEqual: function(actual, expected, message) { + push(expected !== actual, actual, expected, message); + }, + + start: function() { + // A slight delay, to avoid any current callbacks + if ( window.setTimeout ) { + window.setTimeout(function() { + if ( config.timeout ) { + clearTimeout(config.timeout); + } + + config.blocking = false; + process(); + }, 13); + } else { + config.blocking = false; + process(); + } + }, + + stop: function(timeout) { + config.blocking = true; + + if ( timeout && window.setTimeout ) { + config.timeout = window.setTimeout(function() { + QUnit.ok( false, "Test timed out" ); + QUnit.start(); + }, timeout); + } + }, + + /** + * Resets the test setup. Useful for tests that modify the DOM. + */ + reset: function() { + if ( window.jQuery ) { + jQuery("#main").html( config.fixture ); + jQuery.event.global = {}; + jQuery.ajaxSettings = extend({}, config.ajaxSettings); + } + }, + + /** + * Trigger an event on an element. + * + * @example triggerEvent( document.body, "click" ); + * + * @param DOMElement elem + * @param String type + */ + triggerEvent: function( elem, type, event ) { + if ( document.createEvent ) { + event = document.createEvent("MouseEvents"); + event.initMouseEvent(type, true, true, elem.ownerDocument.defaultView, + 0, 0, 0, 0, 0, false, false, false, false, 0, null); + elem.dispatchEvent( event ); + + } else if ( elem.fireEvent ) { + elem.fireEvent("on"+type); + } + }, + + // Safe object type checking + is: function( type, obj ) { + return Object.prototype.toString.call( obj ) === "[object "+ type +"]"; + }, + + // Logging callbacks + done: function(failures, total) {}, + log: function(result, message) {}, + testStart: function(name, testEnvironment) {}, + testDone: function(name, failures, total) {}, + moduleStart: function(name, testEnvironment) {}, + moduleDone: function(name, failures, total) {} +}; + +// Backwards compatibility, deprecated +QUnit.equals = QUnit.equal; +QUnit.same = QUnit.deepEqual; + +// Maintain internal state +var config = { + // The queue of tests to run + queue: [], + + // block until document ready + blocking: true +}; + +// Load paramaters +(function() { + var location = window.location || { search: "", protocol: "file:" }, + GETParams = location.search.slice(1).split('&'); + + for ( var i = 0; i < GETParams.length; i++ ) { + GETParams[i] = decodeURIComponent( GETParams[i] ); + if ( GETParams[i] === "noglobals" ) { + GETParams.splice( i, 1 ); + i--; + config.noglobals = true; + } else if ( GETParams[i].search('=') > -1 ) { + GETParams.splice( i, 1 ); + i--; + } + } + + // restrict modules/tests by get parameters + config.filters = GETParams; + + // Figure out if we're running the tests from a server or not + QUnit.isLocal = !!(location.protocol === 'file:'); +})(); + +// Expose the API as global variables, unless an 'exports' +// object exists, in that case we assume we're in CommonJS +if ( typeof exports === "undefined" || typeof require === "undefined" ) { + extend(window, QUnit); + window.QUnit = QUnit; +} else { + extend(exports, QUnit); + exports.QUnit = QUnit; +} + +QUnit.config = config; + +if ( typeof document === "undefined" || document.readyState === "complete" ) { + config.autorun = true; +} + +addEvent(window, "load", function() { + // Initialize the config, saving the execution queue + var oldconfig = extend({}, config); + QUnit.init(); + extend(config, oldconfig); + + config.blocking = false; + + var userAgent = id("qunit-userAgent"); + if ( userAgent ) { + userAgent.innerHTML = navigator.userAgent; + } + + var toolbar = id("qunit-testrunner-toolbar"); + if ( toolbar ) { + toolbar.style.display = "none"; + + var filter = document.createElement("input"); + filter.type = "checkbox"; + filter.id = "qunit-filter-pass"; + filter.disabled = true; + addEvent( filter, "click", function() { + var li = document.getElementsByTagName("li"); + for ( var i = 0; i < li.length; i++ ) { + if ( li[i].className.indexOf("pass") > -1 ) { + li[i].style.display = filter.checked ? "none" : ""; + } + } + }); + toolbar.appendChild( filter ); + + var label = document.createElement("label"); + label.setAttribute("for", "qunit-filter-pass"); + label.innerHTML = "Hide passed tests"; + toolbar.appendChild( label ); + + var missing = document.createElement("input"); + missing.type = "checkbox"; + missing.id = "qunit-filter-missing"; + missing.disabled = true; + addEvent( missing, "click", function() { + var li = document.getElementsByTagName("li"); + for ( var i = 0; i < li.length; i++ ) { + if ( li[i].className.indexOf("fail") > -1 && li[i].innerHTML.indexOf('missing test - untested code is broken code') > - 1 ) { + li[i].parentNode.parentNode.style.display = missing.checked ? "none" : "block"; + } + } + }); + toolbar.appendChild( missing ); + + label = document.createElement("label"); + label.setAttribute("for", "qunit-filter-missing"); + label.innerHTML = "Hide missing tests (untested code is broken code)"; + toolbar.appendChild( label ); + } + + var main = id('main'); + if ( main ) { + config.fixture = main.innerHTML; + } + + if ( window.jQuery ) { + config.ajaxSettings = window.jQuery.ajaxSettings; + } + + if (config.autostart) { + QUnit.start(); + } +}); + +function done() { + if ( config.doneTimer && window.clearTimeout ) { + window.clearTimeout( config.doneTimer ); + config.doneTimer = null; + } + + if ( config.queue.length ) { + config.doneTimer = window.setTimeout(function(){ + if ( !config.queue.length ) { + done(); + } else { + synchronize( done ); + } + }, 13); + + return; + } + + config.autorun = true; + + // Log the last module results + if ( config.currentModule ) { + QUnit.moduleDone( config.currentModule, config.moduleStats.bad, config.moduleStats.all ); + } + + var banner = id("qunit-banner"), + tests = id("qunit-tests"), + html = ['Tests completed in ', + +new Date - config.started, ' milliseconds.
    ', + '', config.stats.all - config.stats.bad, ' tests of ', config.stats.all, ' passed, ', config.stats.bad,' failed.'].join(''); + + if ( banner ) { + banner.className = (config.stats.bad ? "qunit-fail" : "qunit-pass"); + } + + if ( tests ) { + var result = id("qunit-testresult"); + + if ( !result ) { + result = document.createElement("p"); + result.id = "qunit-testresult"; + result.className = "result"; + tests.parentNode.insertBefore( result, tests.nextSibling ); + } + + result.innerHTML = html; + } + + QUnit.done( config.stats.bad, config.stats.all ); +} + +function validTest( name ) { + var i = config.filters.length, + run = false; + + if ( !i ) { + return true; + } + + while ( i-- ) { + var filter = config.filters[i], + not = filter.charAt(0) == '!'; + + if ( not ) { + filter = filter.slice(1); + } + + if ( name.indexOf(filter) !== -1 ) { + return !not; + } + + if ( not ) { + run = true; + } + } + + return run; +} + +function escapeHtml(s) { + s = s === null ? "" : s + ""; + return s.replace(/[\&"<>\\]/g, function(s) { + switch(s) { + case "&": return "&"; + case "\\": return "\\\\";; + case '"': return '\"';; + case "<": return "<"; + case ">": return ">"; + default: return s; + } + }); +} + +function push(result, actual, expected, message) { + message = escapeHtml(message) || (result ? "okay" : "failed"); + message = '' + message + ""; + expected = '' + escapeHtml(QUnit.jsDump.parse(expected)) + ""; + actual = '' + escapeHtml(QUnit.jsDump.parse(actual)) + ""; + var output = message + ", expected: " + expected + " result: " + actual; + + // can't use ok, as that would double-escape messages + QUnit.log(result, output); + config.assertions.push({ + result: !!result, + message: output + }); +} + +function synchronize( callback ) { + config.queue.push( callback ); + + if ( config.autorun && !config.blocking ) { + process(); + } +} + +function process() { + var start = (new Date()).getTime(); + + while ( config.queue.length && !config.blocking ) { + if ( config.updateRate <= 0 || (((new Date()).getTime() - start) < config.updateRate) ) { + config.queue.shift()(); + + } else { + setTimeout( process, 13 ); + break; + } + } +} + +function saveGlobal() { + config.pollution = []; + + if ( config.noglobals ) { + for ( var key in window ) { + config.pollution.push( key ); + } + } +} + +function checkPollution( name ) { + var old = config.pollution; + saveGlobal(); + + var newGlobals = diff( old, config.pollution ); + if ( newGlobals.length > 0 ) { + ok( false, "Introduced global variable(s): " + newGlobals.join(", ") ); + config.expected++; + } + + var deletedGlobals = diff( config.pollution, old ); + if ( deletedGlobals.length > 0 ) { + ok( false, "Deleted global variable(s): " + deletedGlobals.join(", ") ); + config.expected++; + } +} + +// returns a new Array with the elements that are in a but not in b +function diff( a, b ) { + var result = a.slice(); + for ( var i = 0; i < result.length; i++ ) { + for ( var j = 0; j < b.length; j++ ) { + if ( result[i] === b[j] ) { + result.splice(i, 1); + i--; + break; + } + } + } + return result; +} + +function fail(message, exception, callback) { + if ( typeof console !== "undefined" && console.error && console.warn ) { + console.error(message); + console.error(exception); + console.warn(callback.toString()); + + } else if ( window.opera && opera.postError ) { + opera.postError(message, exception, callback.toString); + } +} + +function extend(a, b) { + for ( var prop in b ) { + a[prop] = b[prop]; + } + + return a; +} + +function addEvent(elem, type, fn) { + if ( elem.addEventListener ) { + elem.addEventListener( type, fn, false ); + } else if ( elem.attachEvent ) { + elem.attachEvent( "on" + type, fn ); + } else { + fn(); + } +} + +function id(name) { + return !!(typeof document !== "undefined" && document && document.getElementById) && + document.getElementById( name ); +} + +// Test for equality any JavaScript type. +// Discussions and reference: http://philrathe.com/articles/equiv +// Test suites: http://philrathe.com/tests/equiv +// Author: Philippe Rathé +QUnit.equiv = function () { + + var innerEquiv; // the real equiv function + var callers = []; // stack to decide between skip/abort functions + var parents = []; // stack to avoiding loops from circular referencing + + + // Determine what is o. + function hoozit(o) { + if (QUnit.is("String", o)) { + return "string"; + + } else if (QUnit.is("Boolean", o)) { + return "boolean"; + + } else if (QUnit.is("Number", o)) { + + if (isNaN(o)) { + return "nan"; + } else { + return "number"; + } + + } else if (typeof o === "undefined") { + return "undefined"; + + // consider: typeof null === object + } else if (o === null) { + return "null"; + + // consider: typeof [] === object + } else if (QUnit.is( "Array", o)) { + return "array"; + + // consider: typeof new Date() === object + } else if (QUnit.is( "Date", o)) { + return "date"; + + // consider: /./ instanceof Object; + // /./ instanceof RegExp; + // typeof /./ === "function"; // => false in IE and Opera, + // true in FF and Safari + } else if (QUnit.is( "RegExp", o)) { + return "regexp"; + + } else if (typeof o === "object") { + return "object"; + + } else if (QUnit.is( "Function", o)) { + return "function"; + } else { + return undefined; + } + } + + // Call the o related callback with the given arguments. + function bindCallbacks(o, callbacks, args) { + var prop = hoozit(o); + if (prop) { + if (hoozit(callbacks[prop]) === "function") { + return callbacks[prop].apply(callbacks, args); + } else { + return callbacks[prop]; // or undefined + } + } + } + + var callbacks = function () { + + // for string, boolean, number and null + function useStrictEquality(b, a) { + if (b instanceof a.constructor || a instanceof b.constructor) { + // to catch short annotaion VS 'new' annotation of a declaration + // e.g. var i = 1; + // var j = new Number(1); + return a == b; + } else { + return a === b; + } + } + + return { + "string": useStrictEquality, + "boolean": useStrictEquality, + "number": useStrictEquality, + "null": useStrictEquality, + "undefined": useStrictEquality, + + "nan": function (b) { + return isNaN(b); + }, + + "date": function (b, a) { + return hoozit(b) === "date" && a.valueOf() === b.valueOf(); + }, + + "regexp": function (b, a) { + return hoozit(b) === "regexp" && + a.source === b.source && // the regex itself + a.global === b.global && // and its modifers (gmi) ... + a.ignoreCase === b.ignoreCase && + a.multiline === b.multiline; + }, + + // - skip when the property is a method of an instance (OOP) + // - abort otherwise, + // initial === would have catch identical references anyway + "function": function () { + var caller = callers[callers.length - 1]; + return caller !== Object && + typeof caller !== "undefined"; + }, + + "array": function (b, a) { + var i, j, loop; + var len; + + // b could be an object literal here + if ( ! (hoozit(b) === "array")) { + return false; + } + + len = a.length; + if (len !== b.length) { // safe and faster + return false; + } + + //track reference to avoid circular references + parents.push(a); + for (i = 0; i < len; i++) { + loop = false; + for(j=0;j= 0) { + type = "array"; + } else { + type = typeof obj; + } + return type; + }, + separator:function() { + return this.multiline ? this.HTML ? '
    ' : '\n' : this.HTML ? ' ' : ' '; + }, + indent:function( extra ) {// extra can be a number, shortcut for increasing-calling-decreasing + if ( !this.multiline ) + return ''; + var chr = this.indentChar; + if ( this.HTML ) + chr = chr.replace(/\t/g,' ').replace(/ /g,' '); + return Array( this._depth_ + (extra||0) ).join(chr); + }, + up:function( a ) { + this._depth_ += a || 1; + }, + down:function( a ) { + this._depth_ -= a || 1; + }, + setParser:function( name, parser ) { + this.parsers[name] = parser; + }, + // The next 3 are exposed so you can use them + quote:quote, + literal:literal, + join:join, + // + _depth_: 1, + // This is the list of parsers, to modify them, use jsDump.setParser + parsers:{ + window: '[Window]', + document: '[Document]', + error:'[ERROR]', //when no parser is found, shouldn't happen + unknown: '[Unknown]', + 'null':'null', + undefined:'undefined', + 'function':function( fn ) { + var ret = 'function', + name = 'name' in fn ? fn.name : (reName.exec(fn)||[])[1];//functions never have name in IE + if ( name ) + ret += ' ' + name; + ret += '('; + + ret = [ ret, this.parse( fn, 'functionArgs' ), '){'].join(''); + return join( ret, this.parse(fn,'functionCode'), '}' ); + }, + array: array, + nodelist: array, + arguments: array, + object:function( map ) { + var ret = [ ]; + this.up(); + for ( var key in map ) + ret.push( this.parse(key,'key') + ': ' + this.parse(map[key]) ); + this.down(); + return join( '{', ret, '}' ); + }, + node:function( node ) { + var open = this.HTML ? '<' : '<', + close = this.HTML ? '>' : '>'; + + var tag = node.nodeName.toLowerCase(), + ret = open + tag; + + for ( var a in this.DOMAttrs ) { + var val = node[this.DOMAttrs[a]]; + if ( val ) + ret += ' ' + a + '=' + this.parse( val, 'attribute' ); + } + return ret + close + open + '/' + tag + close; + }, + functionArgs:function( fn ) {//function calls it internally, it's the arguments part of the function + var l = fn.length; + if ( !l ) return ''; + + var args = Array(l); + while ( l-- ) + args[l] = String.fromCharCode(97+l);//97 is 'a' + return ' ' + args.join(', ') + ' '; + }, + key:quote, //object calls it internally, the key part of an item in a map + functionCode:'[code]', //function calls it internally, it's the content of the function + attribute:quote, //node calls it internally, it's an html attribute value + string:quote, + date:quote, + regexp:literal, //regex + number:literal, + 'boolean':literal + }, + DOMAttrs:{//attributes to dump from nodes, name=>realName + id:'id', + name:'name', + 'class':'className' + }, + HTML:false,//if true, entities are escaped ( <, >, \t, space and \n ) + indentChar:' ',//indentation unit + multiline:false //if true, items in a collection, are separated by a \n, else just a space. + }; + + return jsDump; +})(); + +// from Sizzle.js +function getText( elems ) { + var ret = "", elem; + + for ( var i = 0; elems[i]; i++ ) { + elem = elems[i]; + + // Get the text from text nodes and CDATA nodes + if ( elem.nodeType === 3 || elem.nodeType === 4 ) { + ret += elem.nodeValue; + + // Traverse everything else, except comment nodes + } else if ( elem.nodeType !== 8 ) { + ret += getText( elem.childNodes ); + } + } + + return ret; +}; + +})(this); From a83e87e5aeb8398be50c44be94649cceed7cc265 Mon Sep 17 00:00:00 2001 From: wycats Date: Sat, 31 Jul 2010 11:51:50 -0700 Subject: [PATCH 002/111] Add support for comments --- js/handlebars.js | 55 +++++++++++++++++++++++++++---------------- js/test/handlebars.js | 8 +++++++ 2 files changed, 43 insertions(+), 20 deletions(-) diff --git a/js/handlebars.js b/js/handlebars.js index 768e939f..4e8c6d4f 100644 --- a/js/handlebars.js +++ b/js/handlebars.js @@ -12,6 +12,7 @@ Handlebars.Compiler = function(string) { this.text = ""; this.fn = "var out = ''; "; this.newlines = ""; + this.comment = false; } Handlebars.Compiler.prototype = { @@ -22,33 +23,18 @@ Handlebars.Compiler.prototype = { peek: function(n) { n = n || 1; - return this.string.slice(this.pointer, this.pointer + n); + var start = this.pointer + 1; + return this.string.slice(start, start + n); }, compile: function() { - var chr, mustache; + var chr; while(chr = this.getChar()) { // entering mustache state if(chr === "{" && this.peek() === "{" && !this.mustache) { - this.fn = this.fn + "out = out + '" + this.text + "'; "; - this.fn = this.fn + this.newlines; - this.newlines = "" - this.text = "" - this.mustache = " "; this.getChar(); + this.parseMustache(); - // exiting mustache state - } else if(this.mustache && chr === "}" && this.peek() === "}") { - mustache = this.mustache.trim(); - this.fn = this.fn + "out = out + context['" + mustache + "']; "; - this.mustache = false; - this.getChar(); - - // in mustache state - } else if(this.mustache) { - this.mustache = this.mustache + chr; - - // in normal state } else { if(chr === "\n") { this.newlines = this.newlines + "\n"; @@ -59,7 +45,36 @@ Handlebars.Compiler.prototype = { } this.fn = this.fn + "\nreturn out;"; - console.log(this.fn); return new Function("context", this.fn); + }, + + parseMustache: function() { + var chr, mustache; + + if(this.peek() === "!") { + this.comment = true; + this.getChar(); + } + + this.fn = this.fn + "out = out + '" + this.text + "'; "; + this.fn = this.fn + this.newlines; + this.newlines = "" + this.text = "" + this.mustache = " "; + + while(chr = this.getChar()) { + if(this.mustache && chr === "}" && this.peek() === "}") { + mustache = this.mustache.trim(); + this.mustache = false; + this.getChar(); + if(this.comment) { this.comment = false; return; } + this.fn = this.fn + "out = out + context['" + mustache + "']; "; + return; + } else if(this.comment) { + ; + } else { + this.mustache = this.mustache + chr; + } + } } } diff --git a/js/test/handlebars.js b/js/test/handlebars.js index 7b98eb9f..23c2ca67 100644 --- a/js/test/handlebars.js +++ b/js/test/handlebars.js @@ -10,4 +10,12 @@ jQuery(function($) { equal("Goodbye\ncruel\nworld", result, "it works if all the required keys are provided"); }); + test("comments", function() { + var string = "{{! Goodbye}}Goodbye\n{{cruel}}\n{{world}}"; + var template = Handlebars.compile(string); + + result = template({cruel: "cruel", world: "world"}); + equal("Goodbye\ncruel\nworld", result, "it works if all the required keys are provided"); + }); + }); From 755f854c50cf13e95021dd92865a9256490e92c3 Mon Sep 17 00:00:00 2001 From: wycats Date: Sat, 31 Jul 2010 12:00:11 -0700 Subject: [PATCH 003/111] Reorganize things and remove unneeded dependency on jQuery --- js/test/handlebars.js | 21 --------------------- {js => lib}/handlebars.js | 0 test/handlebars.js | 17 +++++++++++++++++ {js/test => test}/index.html | 10 +++++----- {js => test}/vendor/jquery.js | 0 {js => test}/vendor/test/qunit.css | 0 {js => test}/vendor/test/qunit.js | 0 7 files changed, 22 insertions(+), 26 deletions(-) delete mode 100644 js/test/handlebars.js rename {js => lib}/handlebars.js (100%) create mode 100644 test/handlebars.js rename {js/test => test}/index.html (60%) rename {js => test}/vendor/jquery.js (100%) rename {js => test}/vendor/test/qunit.css (100%) rename {js => test}/vendor/test/qunit.js (100%) diff --git a/js/test/handlebars.js b/js/test/handlebars.js deleted file mode 100644 index 23c2ca67..00000000 --- a/js/test/handlebars.js +++ /dev/null @@ -1,21 +0,0 @@ -jQuery(function($) { - - module("basic context"); - - test("compiling with a basic context", function() { - var string = "Goodbye\n{{cruel}}\n{{world}}"; - var template = Handlebars.compile(string); - - result = template({cruel: "cruel", world: "world"}); - equal("Goodbye\ncruel\nworld", result, "it works if all the required keys are provided"); - }); - - test("comments", function() { - var string = "{{! Goodbye}}Goodbye\n{{cruel}}\n{{world}}"; - var template = Handlebars.compile(string); - - result = template({cruel: "cruel", world: "world"}); - equal("Goodbye\ncruel\nworld", result, "it works if all the required keys are provided"); - }); - -}); diff --git a/js/handlebars.js b/lib/handlebars.js similarity index 100% rename from js/handlebars.js rename to lib/handlebars.js diff --git a/test/handlebars.js b/test/handlebars.js new file mode 100644 index 00000000..31f950bf --- /dev/null +++ b/test/handlebars.js @@ -0,0 +1,17 @@ +module("basic context"); + +test("compiling with a basic context", function() { + var string = "Goodbye\n{{cruel}}\n{{world}}"; + var template = Handlebars.compile(string); + + result = template({cruel: "cruel", world: "world"}); + equal("Goodbye\ncruel\nworld", result, "it works if all the required keys are provided"); +}); + +test("comments", function() { + var string = "{{! Goodbye}}Goodbye\n{{cruel}}\n{{world}}"; + var template = Handlebars.compile(string); + + result = template({cruel: "cruel", world: "world"}); + equal("Goodbye\ncruel\nworld", result, "it works if all the required keys are provided"); +}); diff --git a/js/test/index.html b/test/index.html similarity index 60% rename from js/test/index.html rename to test/index.html index 61486268..e7c0b57d 100644 --- a/js/test/index.html +++ b/test/index.html @@ -2,11 +2,10 @@ "http://www.w3.org/TR/html4/loose.dtd"> - - - - - + + + +

    QUnit example

    @@ -15,6 +14,7 @@
      + diff --git a/js/vendor/jquery.js b/test/vendor/jquery.js similarity index 100% rename from js/vendor/jquery.js rename to test/vendor/jquery.js diff --git a/js/vendor/test/qunit.css b/test/vendor/test/qunit.css similarity index 100% rename from js/vendor/test/qunit.css rename to test/vendor/test/qunit.css diff --git a/js/vendor/test/qunit.js b/test/vendor/test/qunit.js similarity index 100% rename from js/vendor/test/qunit.js rename to test/vendor/test/qunit.js From 8714a581e9a875c2b40cafad39c1b6a4561e5d08 Mon Sep 17 00:00:00 2001 From: wycats Date: Sat, 31 Jul 2010 18:26:26 -0700 Subject: [PATCH 004/111] First pass at getting booleans working --- lib/handlebars.js | 99 ++++++++++++++++++++++++++++++++++++++-------- test/handlebars.js | 19 +++++++-- 2 files changed, 97 insertions(+), 21 deletions(-) diff --git a/lib/handlebars.js b/lib/handlebars.js index 4e8c6d4f..f38e4139 100644 --- a/lib/handlebars.js +++ b/lib/handlebars.js @@ -1,7 +1,12 @@ Handlebars = { compile: function(string) { var compiler = new Handlebars.Compiler(string); - return compiler.compile(); + var result = compiler.compile(); + return new Function("context", result); + }, + + isFunction: function(fn) { + return toString.call(fn) === "[object Function]"; } } @@ -10,15 +15,31 @@ Handlebars.Compiler = function(string) { this.pointer = -1; this.mustache = false; this.text = ""; - this.fn = "var out = ''; "; + this.fn = "var out = ''; var lookup; "; this.newlines = ""; this.comment = false; } +Handlebars.catchAll = function(object, fn) { + var ret = ""; + + if(object === true) { + return fn(this); + } else if(object === false) { + return ""; + } else if(toString.call(object) === "[object Array]") { + for(var i=0, j=object.length; i Date: Sun, 1 Aug 2010 03:18:41 -0700 Subject: [PATCH 005/111] Add fallback hash (useful for a helper Hash). * available globally per top-level function regardless of iteration --- lib/handlebars.js | 31 +++++++++------ test/handlebars.js | 99 +++++++++++++++++++++++++++++++++++++++------- 2 files changed, 104 insertions(+), 26 deletions(-) diff --git a/lib/handlebars.js b/lib/handlebars.js index f38e4139..32b11250 100644 --- a/lib/handlebars.js +++ b/lib/handlebars.js @@ -2,7 +2,7 @@ Handlebars = { compile: function(string) { var compiler = new Handlebars.Compiler(string); var result = compiler.compile(); - return new Function("context", result); + return new Function("context", "fallback", "fallback = fallback || {}; " + result); }, isFunction: function(fn) { @@ -20,7 +20,7 @@ Handlebars.Compiler = function(string) { this.comment = false; } -Handlebars.catchAll = function(object, fn) { +Handlebars.helperMissing = function(object, fn) { var ret = ""; if(object === true) { @@ -74,17 +74,21 @@ Handlebars.Compiler.prototype = { if(this.text) { this.fn = this.fn + "out = out + '" + this.text + "'; "; this.fn = this.fn + this.newlines; - this.newlines = "" - this.text = "" + this.newlines = ""; + this.text = ""; } }, addExpression: function(mustache) { - this.fn = this.fn + "out = out + context['" + mustache + "']; "; + this.fn += "out = out + " + this.lookupFor(mustache) + "; "; + }, + + lookupFor: function(param) { + return param ? "( context['" + param + "'] || fallback['" + param + "'] )" : "context"; }, parseMustache: function() { - var chr, mustache; + var chr, part, mustache, param; var next = this.peek(); @@ -101,7 +105,10 @@ Handlebars.Compiler.prototype = { while(chr = this.getChar()) { if(this.mustache && chr === "}" && this.peek() === "}") { - mustache = this.mustache.trim(); + var parts = this.mustache.trim().split(/\s+/); + mustache = parts[0]; + param = this.lookupFor(parts[1]); + this.mustache = false; this.getChar(); if(this.comment) { @@ -110,13 +117,15 @@ Handlebars.Compiler.prototype = { } else if(this.openBlock) { var compiler = new Handlebars.Compiler(this.string.slice(this.pointer + 1, -1)); - // compile with a custom EOF instruction + // sub-compile with a custom EOF instruction var result = compiler.compile(function(compiler) { if(compiler.peek(mustache.length + 5) === "{{/" + mustache + "}}") { compiler.getChar(mustache.length + 5); return true; } }); + + // move the pointer forward the amount of characters handled by the sub-compiler this.pointer += compiler.pointer + 1; // each function made internally needs a unique IDs. These are locals, so they @@ -124,9 +133,9 @@ Handlebars.Compiler.prototype = { var fnId = "fn" + this.pointer.toString(); this.fn += "var " + fnId + " = function(context) {" + result + "}; "; - this.fn += "lookup = context['" + mustache + "']; "; - this.fn += "if(Handlebars.isFunction(lookup)) out = out + " + fnId + "(lookup); " - this.fn += "else if(typeof lookup !== 'undefined') out = out + Handlebars.catchAll(lookup, " + fnId + "); " + this.fn += "lookup = " + this.lookupFor(mustache) + "; "; + this.fn += "if(Handlebars.isFunction(lookup)) out = out + lookup.call(" + param + ", " + fnId + "); " + this.fn += "else if(typeof lookup !== 'undefined') out = out + Handlebars.helperMissing.call(" + param + ", lookup, " + fnId + "); " this.openBlock = false; return; diff --git a/test/handlebars.js b/test/handlebars.js index 5ad9267d..1ce2dc4a 100644 --- a/test/handlebars.js +++ b/test/handlebars.js @@ -1,28 +1,97 @@ module("basic context"); -test("compiling with a basic context", function() { - var string = "Goodbye\n{{cruel}}\n{{world}}!"; +var shouldCompileTo = function(string, hash, result, message) { var template = Handlebars.compile(string); + var params = toString.call(hash) === "[object Array]" ? hash : [hash, undefined]; + equal(template.apply(this, params), result, message); +} - result = template({cruel: "cruel", world: "world"}); - equal(result, "Goodbye\ncruel\nworld!", "it works if all the required keys are provided"); +test("compiling with a basic context", function() { + shouldCompileTo("Goodbye\n{{cruel}}\n{{world}}!", {cruel: "cruel", world: "world"}, "Goodbye\ncruel\nworld!", + "It works if all the required keys are provided"); }); test("comments", function() { - var string = "{{! Goodbye}}Goodbye\n{{cruel}}\n{{world}}!"; - var template = Handlebars.compile(string); - - result = template({cruel: "cruel", world: "world"}); - equal("Goodbye\ncruel\nworld!", result, "it works if all the required keys are provided"); + shouldCompileTo("{{! Goodbye}}Goodbye\n{{cruel}}\n{{world}}!", + {cruel: "cruel", world: "world"}, "Goodbye\ncruel\nworld!", + "comments are ignored"); }); test("boolean", function() { - var string = "{{#goodbye}}GOODBYE {{/goodbye}}cruel {{world}}!" + var string = "{{#goodbye}}GOODBYE {{/goodbye}}cruel {{world}}!"; + shouldCompileTo(string, {goodbye: true, world: "world"}, "GOODBYE cruel world!", + "booleans show the contents when true"); + + shouldCompileTo(string, {goodbye: false, world: "world"}, "cruel world!", + "booleans do not show the contents when false"); +}); + +module("blocks"); + +test("array", function() { + var string = "{{#goodbyes}}{{text}}! {{/goodbyes}}cruel {{world}}!" + var hash = {goodbyes: [{text: "goodbye"}, {text: "Goodbye"}, {text: "GOODBYE"}], world: "world"}; + shouldCompileTo(string, hash, "goodbye! Goodbye! GOODBYE! cruel world!", + "Arrays iterate over the contents when not empty"); + + shouldCompileTo(string, {goodbyes: [], world: "world"}, "cruel world!", + "Arrays ignore the contents when empty"); +}); + +test("nested iteration", function() { + +}); + +test("block helper", function() { + var string = "{{#goodbyes}}{{text}}! {{/goodbyes}}cruel {{world}}!"; var template = Handlebars.compile(string); - result = template({goodbye: true, world: "world"}); - equal("GOODBYE cruel world!", result, "booleans work when true"); - - result = template({goodbye: false, world: "world"}); - equal("cruel world!", result, "booleans work when true"); + result = template({goodbyes: function(fn) { return fn({text: "GOODBYE"}); }, world: "world"}); + equal(result, "GOODBYE! cruel world!"); }); + +test("block helper staying in the same context", function() { + var string = "{{#form}}

      {{name}}

      {{/form}}" + var template = Handlebars.compile(string); + + result = template({form: function(fn) { return "
      " + fn(this) + "
      " }, name: "Yehuda"}); + equal(result, "

      Yehuda

      "); +}); + +test("block helper passing a new context", function() { + var string = "{{#form yehuda}}

      {{name}}

      {{/form}}" + var template = Handlebars.compile(string); + + result = template({form: function(fn) { return "
      " + fn(this) + "
      " }, yehuda: {name: "Yehuda"}}); + equal(result, "

      Yehuda

      "); +}); + +test("nested block helpers", function() { + var string = "{{#form yehuda}}

      {{name}}

      {{#link}}Hello{{/link}}{{/form}}" + var template = Handlebars.compile(string); + + result = template({form: function(fn) { return "
      " + fn(this) + "
      " }, yehuda: {name: "Yehuda", link: function(fn) { return "" + fn(this) + ""; }}}); + equal(result, "

      Yehuda

      Hello
      "); +}); + +module("fallback hash"); + +test("providing a fallback hash", function() { + shouldCompileTo("Goodbye {{cruel}} {{world}}!", [{cruel: "cruel"}, {world: "world"}], "Goodbye cruel world!", + "Fallback hash is available"); + + shouldCompileTo("Goodbye {{#iter}}{{cruel}} {{world}}{{/iter}}!", [{iter: [{cruel: "cruel"}]}, {world: "world"}], + "Goodbye cruel world!", "Fallback hash is available inside other blocks"); +}); + +test("in cases of conflict, the explicit hash wins", function() { + +}); + +test("the fallback hash is available is nested contexts", function() { + +}); + +module("partials"); + + From acfef657d47a488bf385e3498306b8f9f0c22ed2 Mon Sep 17 00:00:00 2001 From: Alan Johnson Date: Mon, 2 Aug 2010 23:29:37 -0400 Subject: [PATCH 006/111] Added basic nested context lookups and context stack. --- lib/handlebars.js | 18 ++++++++++++++++-- test/handlebars.js | 7 +++++++ 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/lib/handlebars.js b/lib/handlebars.js index 32b11250..9ab40fcf 100644 --- a/lib/handlebars.js +++ b/lib/handlebars.js @@ -2,7 +2,7 @@ Handlebars = { compile: function(string) { var compiler = new Handlebars.Compiler(string); var result = compiler.compile(); - return new Function("context", "fallback", "fallback = fallback || {}; " + result); + return new Function("context", "fallback", "fallback = fallback || {}; stack = [];" + result); }, isFunction: function(fn) { @@ -84,7 +84,19 @@ Handlebars.Compiler.prototype = { }, lookupFor: function(param) { - return param ? "( context['" + param + "'] || fallback['" + param + "'] )" : "context"; + if (!param) { + return "context"; + } + + var parts = param.split("../"); + param = parts[parts.length - 1]; + depth = parts.length - 1; + + if (depth > 0) { + return "( stack[stack.length - " + depth + "]['" + param + "'] )"; + } else { + return "( context['" + param + "'] || fallback['" + param + "'] )"; + } }, parseMustache: function() { @@ -133,9 +145,11 @@ Handlebars.Compiler.prototype = { var fnId = "fn" + this.pointer.toString(); this.fn += "var " + fnId + " = function(context) {" + result + "}; "; + this.fn += "stack.push(context);" this.fn += "lookup = " + this.lookupFor(mustache) + "; "; this.fn += "if(Handlebars.isFunction(lookup)) out = out + lookup.call(" + param + ", " + fnId + "); " this.fn += "else if(typeof lookup !== 'undefined') out = out + Handlebars.helperMissing.call(" + param + ", lookup, " + fnId + "); " + this.fn += "stack.pop(context);" this.openBlock = false; return; diff --git a/test/handlebars.js b/test/handlebars.js index 1ce2dc4a..b5d3ce0e 100644 --- a/test/handlebars.js +++ b/test/handlebars.js @@ -42,6 +42,13 @@ test("nested iteration", function() { }); +test("block with complex lookup", function() { + var string = "{{#goodbyes}}{{text}} cruel {{../name}}! {{/goodbyes}}" + var hash = {name: "Alan", goodbyes: [{text: "goodbye"}, {text: "Goodbye"}, {text: "GOODBYE"}]}; + + shouldCompileTo(string, hash, "goodbye cruel Alan! Goodbye cruel Alan! GOODBYE cruel Alan! "); +}); + test("block helper", function() { var string = "{{#goodbyes}}{{text}}! {{/goodbyes}}cruel {{world}}!"; var template = Handlebars.compile(string); From edb6b238d8c59c5e7b41db01d3b7a16d9162ccff Mon Sep 17 00:00:00 2001 From: Alan Johnson Date: Mon, 2 Aug 2010 23:44:06 -0400 Subject: [PATCH 007/111] Set stack to not be global. --- lib/handlebars.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/handlebars.js b/lib/handlebars.js index 9ab40fcf..71a5e9aa 100644 --- a/lib/handlebars.js +++ b/lib/handlebars.js @@ -2,7 +2,7 @@ Handlebars = { compile: function(string) { var compiler = new Handlebars.Compiler(string); var result = compiler.compile(); - return new Function("context", "fallback", "fallback = fallback || {}; stack = [];" + result); + return new Function("context", "fallback", "fallback = fallback || {}; var stack = [];" + result); }, isFunction: function(fn) { From 7e036fb95213d4ddd6adaae796fce0e636ed60da Mon Sep 17 00:00:00 2001 From: Alan Johnson Date: Tue, 3 Aug 2010 00:05:24 -0400 Subject: [PATCH 008/111] Working on test for ../../omg --- lib/handlebars.js | 1 + test/handlebars.js | 10 +++++++++- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/lib/handlebars.js b/lib/handlebars.js index 71a5e9aa..882ba515 100644 --- a/lib/handlebars.js +++ b/lib/handlebars.js @@ -142,6 +142,7 @@ Handlebars.Compiler.prototype = { // each function made internally needs a unique IDs. These are locals, so they // don't need to be globally unique, just per compiler + console.log("In block " + mustache); var fnId = "fn" + this.pointer.toString(); this.fn += "var " + fnId + " = function(context) {" + result + "}; "; diff --git a/test/handlebars.js b/test/handlebars.js index b5d3ce0e..774d693d 100644 --- a/test/handlebars.js +++ b/test/handlebars.js @@ -46,7 +46,15 @@ test("block with complex lookup", function() { var string = "{{#goodbyes}}{{text}} cruel {{../name}}! {{/goodbyes}}" var hash = {name: "Alan", goodbyes: [{text: "goodbye"}, {text: "Goodbye"}, {text: "GOODBYE"}]}; - shouldCompileTo(string, hash, "goodbye cruel Alan! Goodbye cruel Alan! GOODBYE cruel Alan! "); + shouldCompileTo(string, hash, "goodbye cruel Alan! Goodbye cruel Alan! GOODBYE cruel Alan! ", + "Templates can access variables in contexts up the stack with relative path syntax"); +}); + +test("block with deep nested complex lookup", function() { + var string = "{{#outer}}Goodbye {{#inner}}cruel {{../../omg}}{{/inner}}{{/outer}}"; + var hash = {omg: "OMG!", outer: { inner: { text: "goodbye" } } }; + + shouldCompileTo(string, hash, "Goodbye cruel OMG!"); }); test("block helper", function() { From 135e7c34cdf6bde362ff096506d3c8cb6e06f93c Mon Sep 17 00:00:00 2001 From: Alan Johnson Date: Tue, 3 Aug 2010 01:43:35 -0400 Subject: [PATCH 009/111] Got more deeply neested context references working and tested. --- lib/handlebars.js | 12 +++++++----- test/handlebars.js | 2 +- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/lib/handlebars.js b/lib/handlebars.js index 882ba515..13ed02e9 100644 --- a/lib/handlebars.js +++ b/lib/handlebars.js @@ -2,6 +2,7 @@ Handlebars = { compile: function(string) { var compiler = new Handlebars.Compiler(string); var result = compiler.compile(); + console.log(compiler.fn); return new Function("context", "fallback", "fallback = fallback || {}; var stack = [];" + result); }, @@ -33,6 +34,7 @@ Handlebars.helperMissing = function(object, fn) { } return ret; } + console.log("HERE"); }; Handlebars.Compiler.prototype = { @@ -127,6 +129,8 @@ Handlebars.Compiler.prototype = { this.comment = false; return; } else if(this.openBlock) { + // set up the stack before the new compiler starts + this.fn += "stack.push(context);"; var compiler = new Handlebars.Compiler(this.string.slice(this.pointer + 1, -1)); // sub-compile with a custom EOF instruction @@ -142,16 +146,14 @@ Handlebars.Compiler.prototype = { // each function made internally needs a unique IDs. These are locals, so they // don't need to be globally unique, just per compiler - console.log("In block " + mustache); var fnId = "fn" + this.pointer.toString(); this.fn += "var " + fnId + " = function(context) {" + result + "}; "; - this.fn += "stack.push(context);" this.fn += "lookup = " + this.lookupFor(mustache) + "; "; - this.fn += "if(Handlebars.isFunction(lookup)) out = out + lookup.call(" + param + ", " + fnId + "); " - this.fn += "else if(typeof lookup !== 'undefined') out = out + Handlebars.helperMissing.call(" + param + ", lookup, " + fnId + "); " - this.fn += "stack.pop(context);" + this.fn += "if(Handlebars.isFunction(lookup)) out = out + lookup.call(" + param + ", " + fnId + "); "; + this.fn += "else if(typeof lookup !== 'undefined') out = out + Handlebars.helperMissing.call(" + param + ", lookup, " + fnId + "); "; + this.fn += "stack.pop();"; this.openBlock = false; return; } else { diff --git a/test/handlebars.js b/test/handlebars.js index 774d693d..01bdf1d1 100644 --- a/test/handlebars.js +++ b/test/handlebars.js @@ -52,7 +52,7 @@ test("block with complex lookup", function() { test("block with deep nested complex lookup", function() { var string = "{{#outer}}Goodbye {{#inner}}cruel {{../../omg}}{{/inner}}{{/outer}}"; - var hash = {omg: "OMG!", outer: { inner: { text: "goodbye" } } }; + var hash = {omg: "OMG!", outer: [{ inner: [{ text: "goodbye" }] }] }; shouldCompileTo(string, hash, "Goodbye cruel OMG!"); }); From 5d08ed629d957b5d9794780ee21aa4feee542624 Mon Sep 17 00:00:00 2001 From: Alan Johnson Date: Tue, 3 Aug 2010 01:59:39 -0400 Subject: [PATCH 010/111] Got accessing data in nested objects working using parent/child syntax. --- lib/handlebars.js | 11 +++++++---- test/handlebars.js | 5 +++++ 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/lib/handlebars.js b/lib/handlebars.js index 13ed02e9..b6408bd3 100644 --- a/lib/handlebars.js +++ b/lib/handlebars.js @@ -2,7 +2,6 @@ Handlebars = { compile: function(string) { var compiler = new Handlebars.Compiler(string); var result = compiler.compile(); - console.log(compiler.fn); return new Function("context", "fallback", "fallback = fallback || {}; var stack = [];" + result); }, @@ -34,7 +33,6 @@ Handlebars.helperMissing = function(object, fn) { } return ret; } - console.log("HERE"); }; Handlebars.Compiler.prototype = { @@ -93,11 +91,16 @@ Handlebars.Compiler.prototype = { var parts = param.split("../"); param = parts[parts.length - 1]; depth = parts.length - 1; + parts = param.split("/"); + var paramExpr = ""; + for (var i = 0; i < parts.length; i++) { + paramExpr += "['" + parts[i] + "']"; + } if (depth > 0) { - return "( stack[stack.length - " + depth + "]['" + param + "'] )"; + return "( stack[stack.length - " + depth + "]" + paramExpr + ")"; } else { - return "( context['" + param + "'] || fallback['" + param + "'] )"; + return "( context" + paramExpr + " || fallback " + paramExpr + " )"; } }, diff --git a/test/handlebars.js b/test/handlebars.js index 01bdf1d1..8e4c6c44 100644 --- a/test/handlebars.js +++ b/test/handlebars.js @@ -26,6 +26,11 @@ test("boolean", function() { "booleans do not show the contents when false"); }); +test("nested paths", function() { + shouldCompileTo("Goodbye {{alan/expression}} world!", {alan: {expression: "beautiful"}}, + "Goodbye beautiful world!", "Nested paths access nested objects"); +}); + module("blocks"); test("array", function() { From 327744afaffcf80a4c4d2241f8125697d46bc893 Mon Sep 17 00:00:00 2001 From: Alan Johnson Date: Tue, 3 Aug 2010 22:49:36 -0400 Subject: [PATCH 011/111] Added parse errors for trying to jump out of context after moving into context in path expressions. --- lib/handlebars.js | 27 ++++++++++++++++++++++----- test/handlebars.js | 13 +++++++++++++ 2 files changed, 35 insertions(+), 5 deletions(-) diff --git a/lib/handlebars.js b/lib/handlebars.js index b6408bd3..5878fcad 100644 --- a/lib/handlebars.js +++ b/lib/handlebars.js @@ -20,6 +20,10 @@ Handlebars.Compiler = function(string) { this.comment = false; } +Handlebars.ParseError = function(message) { + this.message = message; +} + Handlebars.helperMissing = function(object, fn) { var ret = ""; @@ -88,13 +92,26 @@ Handlebars.Compiler.prototype = { return "context"; } - var parts = param.split("../"); - param = parts[parts.length - 1]; - depth = parts.length - 1; - parts = param.split("/"); + var parts = param.split("/"); + var readDepth = false; + var depth = 0; var paramExpr = ""; for (var i = 0; i < parts.length; i++) { - paramExpr += "['" + parts[i] + "']"; + switch(parts[i]) { + case "..": + if (readDepth) { + throw new Handlebars.ParseError("Cannot jump out of context after moving into a context."); + } else { + depth += 1; + } + break; + case ".": + throw new HandleBars.ParseError("'.' is not supported in path expressions.") + break; + default: + readDepth = true; + paramExpr += "['" + parts[i] + "']"; + } } if (depth > 0) { diff --git a/test/handlebars.js b/test/handlebars.js index 8e4c6c44..9cd6db13 100644 --- a/test/handlebars.js +++ b/test/handlebars.js @@ -31,6 +31,19 @@ test("nested paths", function() { "Goodbye beautiful world!", "Nested paths access nested objects"); }); +test("dumb nested paths", function() { + var string = "{{#goodbyes}}{{../name/../name}}{{/goodbyes}}"; + var caught = false; + try { + Handlebars.compile("{{#goodbyes}}{{../name/../name}}{{/goodbyes}}"); + } catch (e) { + if (e instanceof Handlebars.ParseError) { + caught = true; + } + } + equals(caught, true, "Jumping out of context (..) doesn't work after moving into context."); +}); + module("blocks"); test("array", function() { From 45696849986dafaa347d5a3effc975cad96a5e6a Mon Sep 17 00:00:00 2001 From: Alan Johnson Date: Tue, 3 Aug 2010 23:26:40 -0400 Subject: [PATCH 012/111] Updated the path parsing in lookupFor to be a bit smarter and added parse errors for some of the more tricky ones. --- lib/handlebars.js | 2 +- test/handlebars.js | 11 ++++++++--- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/lib/handlebars.js b/lib/handlebars.js index 5878fcad..73a035d9 100644 --- a/lib/handlebars.js +++ b/lib/handlebars.js @@ -106,7 +106,7 @@ Handlebars.Compiler.prototype = { } break; case ".": - throw new HandleBars.ParseError("'.' is not supported in path expressions.") + // do nothing - using .'s is pretty dumb, but it's also basically free for us to support break; default: readDepth = true; diff --git a/test/handlebars.js b/test/handlebars.js index 9cd6db13..f3620f79 100644 --- a/test/handlebars.js +++ b/test/handlebars.js @@ -31,8 +31,7 @@ test("nested paths", function() { "Goodbye beautiful world!", "Nested paths access nested objects"); }); -test("dumb nested paths", function() { - var string = "{{#goodbyes}}{{../name/../name}}{{/goodbyes}}"; +test("bad idea nested paths", function() { var caught = false; try { Handlebars.compile("{{#goodbyes}}{{../name/../name}}{{/goodbyes}}"); @@ -41,9 +40,14 @@ test("dumb nested paths", function() { caught = true; } } - equals(caught, true, "Jumping out of context (..) doesn't work after moving into context."); + equals(caught, true, "Cannot jump (..) into previous context after moving into context."); + + var string = "{{#goodbyes}}{{.././world}} {{/goodbyes}}"; + var hash = {goodbyes: [{text: "goodbye"}, {text: "Goodbye"}, {text: "GOODBYE"}], world: "world"}; + shouldCompileTo(string, hash, "world world world ", "Same context (.) is ignored in paths"); }); + module("blocks"); test("array", function() { @@ -54,6 +58,7 @@ test("array", function() { shouldCompileTo(string, {goodbyes: [], world: "world"}, "cruel world!", "Arrays ignore the contents when empty"); + }); test("nested iteration", function() { From 54838cd90c19bd0b466b1f49fdf5eb16d45c75d3 Mon Sep 17 00:00:00 2001 From: Alan Johnson Date: Wed, 4 Aug 2010 21:54:57 -0400 Subject: [PATCH 013/111] Added support for this keyword in paths. --- lib/handlebars.js | 2 ++ test/handlebars.js | 10 ++++++++++ 2 files changed, 12 insertions(+) diff --git a/lib/handlebars.js b/lib/handlebars.js index 73a035d9..a1efa288 100644 --- a/lib/handlebars.js +++ b/lib/handlebars.js @@ -107,6 +107,8 @@ Handlebars.Compiler.prototype = { break; case ".": // do nothing - using .'s is pretty dumb, but it's also basically free for us to support + case "this": + // if we do nothing you'll end up sticking in the same context break; default: readDepth = true; diff --git a/test/handlebars.js b/test/handlebars.js index f3620f79..15c231c6 100644 --- a/test/handlebars.js +++ b/test/handlebars.js @@ -47,6 +47,16 @@ test("bad idea nested paths", function() { shouldCompileTo(string, hash, "world world world ", "Same context (.) is ignored in paths"); }); +test("this keyword in paths", function() { + var string = "{{#goodbyes}}{{this}}{{/goodbyes}}"; + var hash = {goodbyes: ["goodbye", "Goodbye", "GOODBYE"]}; + shouldCompileTo(string, hash, "goodbyeGoodbyeGOODBYE", + "This keyword in paths evaluates to current context"); + + string = "{{#hellos}}{{this/text}}{{/hellos}}" + hash = {hellos: [{text: "hello"}, {text: "Hello"}, {text: "HELLO"}]}; + shouldCompileTo(string, hash, "helloHelloHELLO", "This keyword evaluates in more complex paths"); +}); module("blocks"); From 4950beea1c8d20f37cc876a0c73b05cab8e92111 Mon Sep 17 00:00:00 2001 From: Alan Johnson Date: Wed, 4 Aug 2010 22:18:40 -0400 Subject: [PATCH 014/111] Made path parser reusable so that we can use it inside of __get__. --- lib/handlebars.js | 66 +++++++++++++++++++++++++++++----------------- test/handlebars.js | 10 +++++++ 2 files changed, 52 insertions(+), 24 deletions(-) diff --git a/lib/handlebars.js b/lib/handlebars.js index a1efa288..b4f3654c 100644 --- a/lib/handlebars.js +++ b/lib/handlebars.js @@ -24,6 +24,40 @@ Handlebars.ParseError = function(message) { this.message = message; } +// Returns a two element array containing the numbers of contexts to back up the stack and +// the properties to dig into on the current context +Handlebars.parsePath = function(path) { + if (path == null) { + return [0, []]; + } + + var parts = path.split("/"); + var readDepth = false; + var depth = 0; + var dig = []; + for (var i = 0; i < parts.length; i++) { + switch(parts[i]) { + case "..": + if (readDepth) { + throw new Handlebars.ParseError("Cannot jump out of context after moving into a context."); + } else { + depth += 1; + } + break; + case ".": + // do nothing - using .'s is pretty dumb, but it's also basically free for us to support + case "this": + // if we do nothing you'll end up sticking in the same context + break; + default: + readDepth = true; + dig.push(parts[i]); + } + } + + return [depth, dig]; +} + Handlebars.helperMissing = function(object, fn) { var ret = ""; @@ -88,37 +122,21 @@ Handlebars.Compiler.prototype = { }, lookupFor: function(param) { - if (!param) { - return "context"; - } + var parsed = Handlebars.parsePath(param); + var depth = parsed[0]; + var parts = parsed[1]; + console.log(depth) - var parts = param.split("/"); - var readDepth = false; - var depth = 0; var paramExpr = ""; - for (var i = 0; i < parts.length; i++) { - switch(parts[i]) { - case "..": - if (readDepth) { - throw new Handlebars.ParseError("Cannot jump out of context after moving into a context."); - } else { - depth += 1; - } - break; - case ".": - // do nothing - using .'s is pretty dumb, but it's also basically free for us to support - case "this": - // if we do nothing you'll end up sticking in the same context - break; - default: - readDepth = true; - paramExpr += "['" + parts[i] + "']"; - } + for(var i = 0; i < parts.length; i++) { + paramExpr += "['" + parts[i] + "']"; } if (depth > 0) { + console.log(depth + ", " + paramExpr); return "( stack[stack.length - " + depth + "]" + paramExpr + ")"; } else { + console.log(paramExpr); return "( context" + paramExpr + " || fallback " + paramExpr + " )"; } }, diff --git a/test/handlebars.js b/test/handlebars.js index 15c231c6..26ad2bbc 100644 --- a/test/handlebars.js +++ b/test/handlebars.js @@ -83,6 +83,16 @@ test("block with complex lookup", function() { "Templates can access variables in contexts up the stack with relative path syntax"); }); +test("helper with complex lookup", function() { + var string = "{{#goodbyes}}{{link}}{{/goodbyes}}" + var hash = {prefix: "/root", goodbyes: [{text: "Goodbye", link: "goodbye"}]}; + var fallback = {link: function() { + return "" + this.text + "" + }}; + shouldCompileTo(string, [hash, fallback], "Goodbye") +}); + + test("block with deep nested complex lookup", function() { var string = "{{#outer}}Goodbye {{#inner}}cruel {{../../omg}}{{/inner}}{{/outer}}"; var hash = {omg: "OMG!", outer: [{ inner: [{ text: "goodbye" }] }] }; From 21d779bb54405344be75a6aaeca03740b3e7588a Mon Sep 17 00:00:00 2001 From: Alan Johnson Date: Wed, 4 Aug 2010 23:40:15 -0400 Subject: [PATCH 015/111] Got rid of failing test. I'll take another stab some other time. --- test/handlebars.js | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/test/handlebars.js b/test/handlebars.js index 26ad2bbc..15c231c6 100644 --- a/test/handlebars.js +++ b/test/handlebars.js @@ -83,16 +83,6 @@ test("block with complex lookup", function() { "Templates can access variables in contexts up the stack with relative path syntax"); }); -test("helper with complex lookup", function() { - var string = "{{#goodbyes}}{{link}}{{/goodbyes}}" - var hash = {prefix: "/root", goodbyes: [{text: "Goodbye", link: "goodbye"}]}; - var fallback = {link: function() { - return "" + this.text + "" - }}; - shouldCompileTo(string, [hash, fallback], "Goodbye") -}); - - test("block with deep nested complex lookup", function() { var string = "{{#outer}}Goodbye {{#inner}}cruel {{../../omg}}{{/inner}}{{/outer}}"; var hash = {omg: "OMG!", outer: [{ inner: [{ text: "goodbye" }] }] }; From 03d06fa70a37308dfbfb0980524f93d63549ead3 Mon Sep 17 00:00:00 2001 From: Alan Johnson Date: Thu, 5 Aug 2010 23:41:24 -0400 Subject: [PATCH 016/111] Got rid of some debugging output. --- lib/handlebars.js | 3 --- test/handlebars.js | 5 +++++ 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/lib/handlebars.js b/lib/handlebars.js index b4f3654c..2cde0ce2 100644 --- a/lib/handlebars.js +++ b/lib/handlebars.js @@ -125,7 +125,6 @@ Handlebars.Compiler.prototype = { var parsed = Handlebars.parsePath(param); var depth = parsed[0]; var parts = parsed[1]; - console.log(depth) var paramExpr = ""; for(var i = 0; i < parts.length; i++) { @@ -133,10 +132,8 @@ Handlebars.Compiler.prototype = { } if (depth > 0) { - console.log(depth + ", " + paramExpr); return "( stack[stack.length - " + depth + "]" + paramExpr + ")"; } else { - console.log(paramExpr); return "( context" + paramExpr + " || fallback " + paramExpr + " )"; } }, diff --git a/test/handlebars.js b/test/handlebars.js index 15c231c6..9fcc0d6b 100644 --- a/test/handlebars.js +++ b/test/handlebars.js @@ -26,6 +26,11 @@ test("boolean", function() { "booleans do not show the contents when false"); }); +test("functions", function() { + shouldCompileTo("{{awesome}}", {awesome: function() { return "Awesome"; }}, "Awesome", + "functions are called and render their output"); +}); + test("nested paths", function() { shouldCompileTo("Goodbye {{alan/expression}} world!", {alan: {expression: "beautiful"}}, "Goodbye beautiful world!", "Nested paths access nested objects"); From 28d699233a70e46485d3f0c8e1f8cdf77c632823 Mon Sep 17 00:00:00 2001 From: Alan Johnson Date: Thu, 5 Aug 2010 23:59:59 -0400 Subject: [PATCH 017/111] Added support for expressions that reference functions. --- lib/handlebars.js | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/lib/handlebars.js b/lib/handlebars.js index 2cde0ce2..69717044 100644 --- a/lib/handlebars.js +++ b/lib/handlebars.js @@ -2,6 +2,7 @@ Handlebars = { compile: function(string) { var compiler = new Handlebars.Compiler(string); var result = compiler.compile(); + console.log(result); return new Function("context", "fallback", "fallback = fallback || {}; var stack = [];" + result); }, @@ -118,7 +119,8 @@ Handlebars.Compiler.prototype = { }, addExpression: function(mustache) { - this.fn += "out = out + " + this.lookupFor(mustache) + "; "; + var expr = this.lookupFor(mustache); + this.fn += "out = out + (Handlebars.isFunction(" + expr + ") ? " + expr + "() : " + expr + "); "; }, lookupFor: function(param) { From 13ceb010ba9f4bcace8a57da67897ae0f08bef8c Mon Sep 17 00:00:00 2001 From: Alan Johnson Date: Fri, 6 Aug 2010 00:34:03 -0400 Subject: [PATCH 018/111] Using this.__get__ inside of functions called as expressions now works. --- lib/handlebars.js | 40 +++++++++++++++++++++++++++++++--------- test/handlebars.js | 19 ++++++++++++++++++- 2 files changed, 49 insertions(+), 10 deletions(-) diff --git a/lib/handlebars.js b/lib/handlebars.js index 69717044..8bbde587 100644 --- a/lib/handlebars.js +++ b/lib/handlebars.js @@ -2,7 +2,6 @@ Handlebars = { compile: function(string) { var compiler = new Handlebars.Compiler(string); var result = compiler.compile(); - console.log(result); return new Function("context", "fallback", "fallback = fallback || {}; var stack = [];" + result); }, @@ -19,11 +18,34 @@ Handlebars.Compiler = function(string) { this.fn = "var out = ''; var lookup; "; this.newlines = ""; this.comment = false; -} +}; Handlebars.ParseError = function(message) { this.message = message; -} +}; + +Handlebars.Context = function(stack) { + this.__stack__ = stack; + this.__get__ = function(path) { + var context = this; + var parsedPath = Handlebars.parsePath(path); + var depth = parsedPath[0]; + var parts = parsedPath[1]; + if (depth > 0) { + context = this.__stack__[stack.length - depth]; + } + + for (var i = 0; i < parts.length; i++) { + context = context[parts[i]]; + } + + return context; + }; +}; +Handlebars.buildContext = function(context, stack) { + Handlebars.Context.prototype = context; + return new Handlebars.Context(stack); +}; // Returns a two element array containing the numbers of contexts to back up the stack and // the properties to dig into on the current context @@ -57,7 +79,7 @@ Handlebars.parsePath = function(path) { } return [depth, dig]; -} +}; Handlebars.helperMissing = function(object, fn) { var ret = ""; @@ -120,7 +142,8 @@ Handlebars.Compiler.prototype = { addExpression: function(mustache) { var expr = this.lookupFor(mustache); - this.fn += "out = out + (Handlebars.isFunction(" + expr + ") ? " + expr + "() : " + expr + "); "; + this.fn += "if (Handlebars.isFunction(" + expr + ")) out = out + " + expr + ".call(Handlebars.buildContext(context, stack)); "; + this.fn += "else if(typeof " + expr + "!== 'undefined') out = out + " + expr + "; "; }, lookupFor: function(param) { @@ -186,11 +209,11 @@ Handlebars.Compiler.prototype = { // each function made internally needs a unique IDs. These are locals, so they // don't need to be globally unique, just per compiler var fnId = "fn" + this.pointer.toString(); - + this.fn += "var proxy = Handlebars.buildContext(" + param + ", stack);"; this.fn += "var " + fnId + " = function(context) {" + result + "}; "; this.fn += "lookup = " + this.lookupFor(mustache) + "; "; - this.fn += "if(Handlebars.isFunction(lookup)) out = out + lookup.call(" + param + ", " + fnId + "); "; - this.fn += "else if(typeof lookup !== 'undefined') out = out + Handlebars.helperMissing.call(" + param + ", lookup, " + fnId + "); "; + this.fn += "if(Handlebars.isFunction(lookup)) out = out + lookup.call(proxy, " + fnId + "); "; + this.fn += "else if(typeof lookup !== 'undefined') out = out + Handlebars.helperMissing.call(proxy, lookup, " + fnId + "); "; this.fn += "stack.pop();"; this.openBlock = false; @@ -207,4 +230,3 @@ Handlebars.Compiler.prototype = { } } } - diff --git a/test/handlebars.js b/test/handlebars.js index 9fcc0d6b..199bbf68 100644 --- a/test/handlebars.js +++ b/test/handlebars.js @@ -88,6 +88,15 @@ test("block with complex lookup", function() { "Templates can access variables in contexts up the stack with relative path syntax"); }); +test("helper with complex lookup", function() { + var string = "{{#goodbyes}}{{link}}{{/goodbyes}}" + var hash = {prefix: "/root", goodbyes: [{text: "Goodbye", url: "goodbye"}]}; + var fallback = {link: function() { + return "" + this.text + "" + }}; + shouldCompileTo(string, [hash, fallback], "Goodbye") +}); + test("block with deep nested complex lookup", function() { var string = "{{#outer}}Goodbye {{#inner}}cruel {{../../omg}}{{/inner}}{{/outer}}"; var hash = {omg: "OMG!", outer: [{ inner: [{ text: "goodbye" }] }] }; @@ -107,7 +116,7 @@ test("block helper staying in the same context", function() { var string = "{{#form}}

      {{name}}

      {{/form}}" var template = Handlebars.compile(string); - result = template({form: function(fn) { return "
      " + fn(this) + "
      " }, name: "Yehuda"}); + result = template({form: function(fn) { console.log(fn); return "
      " + fn(this) + "
      " }, name: "Yehuda"}); equal(result, "

      Yehuda

      "); }); @@ -119,6 +128,14 @@ test("block helper passing a new context", function() { equal(result, "

      Yehuda

      "); }); +test("block helper passing a complex path context", function() { + var string = "{{#form yehuda/cat}}

      {{name}}

      {{/form}}" + var template = Handlebars.compile(string); + + result = template({form: function(fn) { return "
      " + fn(this) + "
      " }, yehuda: {name: "Yehuda", cat: {name: "Harold"}}}); + equal(result, "

      Harold

      "); +}); + test("nested block helpers", function() { var string = "{{#form yehuda}}

      {{name}}

      {{#link}}Hello{{/link}}{{/form}}" var template = Handlebars.compile(string); From ccbb241ac9039501caf3f1982effd71d98f5f11f Mon Sep 17 00:00:00 2001 From: Alan Johnson Date: Fri, 6 Aug 2010 00:36:02 -0400 Subject: [PATCH 019/111] Took out a console.log that was hanging around. --- test/handlebars.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/handlebars.js b/test/handlebars.js index 199bbf68..c5060545 100644 --- a/test/handlebars.js +++ b/test/handlebars.js @@ -116,7 +116,7 @@ test("block helper staying in the same context", function() { var string = "{{#form}}

      {{name}}

      {{/form}}" var template = Handlebars.compile(string); - result = template({form: function(fn) { console.log(fn); return "
      " + fn(this) + "
      " }, name: "Yehuda"}); + result = template({form: function(fn) { return "
      " + fn(this) + "
      " }, name: "Yehuda"}); equal(result, "

      Yehuda

      "); }); From e373f08bd16cbce5ba3a85956cb7eb97d7c9b805 Mon Sep 17 00:00:00 2001 From: Alan Johnson Date: Sat, 7 Aug 2010 16:23:01 -0400 Subject: [PATCH 020/111] Bit of cleanup on the context code. --- lib/handlebars.js | 41 +++++++++++++++++++++-------------------- 1 file changed, 21 insertions(+), 20 deletions(-) diff --git a/lib/handlebars.js b/lib/handlebars.js index 8bbde587..776aa3d5 100644 --- a/lib/handlebars.js +++ b/lib/handlebars.js @@ -24,27 +24,28 @@ Handlebars.ParseError = function(message) { this.message = message; }; -Handlebars.Context = function(stack) { - this.__stack__ = stack; - this.__get__ = function(path) { - var context = this; - var parsedPath = Handlebars.parsePath(path); - var depth = parsedPath[0]; - var parts = parsedPath[1]; - if (depth > 0) { - context = this.__stack__[stack.length - depth]; - } - - for (var i = 0; i < parts.length; i++) { - context = context[parts[i]]; - } - - return context; - }; -}; Handlebars.buildContext = function(context, stack) { - Handlebars.Context.prototype = context; - return new Handlebars.Context(stack); + contextWrapper = function(stack) { + this.__stack__ = stack; + this.__get__ = function(path) { + var context = this; + var parsedPath = Handlebars.parsePath(path); + var depth = parsedPath[0]; + var parts = parsedPath[1]; + if (depth > 0) { + context = this.__stack__[stack.length - depth]; + } + + for (var i = 0; i < parts.length; i++) { + context = context[parts[i]]; + } + + return context; + }; + } + + contextWrapper.prototype = context; + return new contextWrapper(stack); }; // Returns a two element array containing the numbers of contexts to back up the stack and From a9dfa3605c3370d0a1fa5b90b162ba158c62e90b Mon Sep 17 00:00:00 2001 From: Alan Johnson Date: Sat, 7 Aug 2010 21:46:41 -0400 Subject: [PATCH 021/111] Refactored some stuff. --- lib/handlebars.js | 115 +++++++++++++++++++++++----------------------- 1 file changed, 58 insertions(+), 57 deletions(-) diff --git a/lib/handlebars.js b/lib/handlebars.js index 776aa3d5..e456112b 100644 --- a/lib/handlebars.js +++ b/lib/handlebars.js @@ -7,6 +7,64 @@ Handlebars = { isFunction: function(fn) { return toString.call(fn) === "[object Function]"; + }, + + buildContext: function(context, stack) { + var contextWrapper = function(stack) { + this.__stack__ = stack; + this.__get__ = function(path) { + var context = this; + var parsedPath = Handlebars.parsePath(path); + var depth = parsedPath[0]; + var parts = parsedPath[1]; + if (depth > 0) { + context = this.__stack__[stack.length - depth]; + } + + for (var i = 0; i < parts.length; i++) { + context = context[parts[i]]; + } + + return context; + }; + }; + + contextWrapper.prototype = context; + return new contextWrapper(stack); + }, + + // Returns a two element array containing the numbers of contexts to back up the stack and + // the properties to dig into on the current context + parsePath: function(path) { + if (path == null) { + return [0, []]; + } + + var parts = path.split("/"); + var readDepth = false; + var depth = 0; + var dig = []; + for (var i = 0; i < parts.length; i++) { + switch(parts[i]) { + case "..": + if (readDepth) { + throw new Handlebars.ParseError("Cannot jump out of context after moving into a context."); + } else { + depth += 1; + } + break; + case ".": + // do nothing - using .'s is pretty dumb, but it's also basically free for us to support + case "this": + // if we do nothing you'll end up sticking in the same context + break; + default: + readDepth = true; + dig.push(parts[i]); + } + } + + return [depth, dig]; } } @@ -24,63 +82,6 @@ Handlebars.ParseError = function(message) { this.message = message; }; -Handlebars.buildContext = function(context, stack) { - contextWrapper = function(stack) { - this.__stack__ = stack; - this.__get__ = function(path) { - var context = this; - var parsedPath = Handlebars.parsePath(path); - var depth = parsedPath[0]; - var parts = parsedPath[1]; - if (depth > 0) { - context = this.__stack__[stack.length - depth]; - } - - for (var i = 0; i < parts.length; i++) { - context = context[parts[i]]; - } - - return context; - }; - } - - contextWrapper.prototype = context; - return new contextWrapper(stack); -}; - -// Returns a two element array containing the numbers of contexts to back up the stack and -// the properties to dig into on the current context -Handlebars.parsePath = function(path) { - if (path == null) { - return [0, []]; - } - - var parts = path.split("/"); - var readDepth = false; - var depth = 0; - var dig = []; - for (var i = 0; i < parts.length; i++) { - switch(parts[i]) { - case "..": - if (readDepth) { - throw new Handlebars.ParseError("Cannot jump out of context after moving into a context."); - } else { - depth += 1; - } - break; - case ".": - // do nothing - using .'s is pretty dumb, but it's also basically free for us to support - case "this": - // if we do nothing you'll end up sticking in the same context - break; - default: - readDepth = true; - dig.push(parts[i]); - } - } - - return [depth, dig]; -}; Handlebars.helperMissing = function(object, fn) { var ret = ""; From c907e80d15ec20a1fc77d3dcb139d9e4d7e7e0b7 Mon Sep 17 00:00:00 2001 From: wycats Date: Sat, 7 Aug 2010 19:27:10 -0700 Subject: [PATCH 022/111] Add a comment and reorganize a few things --- lib/handlebars.js | 63 +++++++++++++++++++++++++---------------------- 1 file changed, 34 insertions(+), 29 deletions(-) diff --git a/lib/handlebars.js b/lib/handlebars.js index e456112b..e3e6b18b 100644 --- a/lib/handlebars.js +++ b/lib/handlebars.js @@ -35,6 +35,8 @@ Handlebars = { // Returns a two element array containing the numbers of contexts to back up the stack and // the properties to dig into on the current context + // + // For example, if the path is "../../alan/name", the result will be [2, ["alan", "name"]]. parsePath: function(path) { if (path == null) { return [0, []]; @@ -44,7 +46,7 @@ Handlebars = { var readDepth = false; var depth = 0; var dig = []; - for (var i = 0; i < parts.length; i++) { + for (var i = 0, j = parts.length; i < j; i++) { switch(parts[i]) { case "..": if (readDepth) { @@ -165,6 +167,35 @@ Handlebars.Compiler.prototype = { } }, + addBlock: function(mustache, param, parts) { + // set up the stack before the new compiler starts + this.fn += "stack.push(context);"; + var compiler = new Handlebars.Compiler(this.string.slice(this.pointer + 1, -1)); + + // sub-compile with a custom EOF instruction + var result = compiler.compile(function(compiler) { + if(compiler.peek(mustache.length + 5) === "{{/" + mustache + "}}") { + compiler.getChar(mustache.length + 5); + return true; + } + }); + + // move the pointer forward the amount of characters handled by the sub-compiler + this.pointer += compiler.pointer + 1; + + // each function made internally needs a unique IDs. These are locals, so they + // don't need to be globally unique, just per compiler + var fnId = "fn" + this.pointer.toString(); + this.fn += "var proxy = Handlebars.buildContext(" + param + ", stack);"; + this.fn += "var " + fnId + " = function(context) {" + result + "}; "; + this.fn += "lookup = " + this.lookupFor(mustache) + "; "; + this.fn += "if(Handlebars.isFunction(lookup)) out = out + lookup.call(proxy, " + fnId + "); "; + this.fn += "else if(typeof lookup !== 'undefined') out = out + Handlebars.helperMissing.call(proxy, lookup, " + fnId + "); "; + + this.fn += "stack.pop();"; + this.openBlock = false; + }, + parseMustache: function() { var chr, part, mustache, param; @@ -193,36 +224,10 @@ Handlebars.Compiler.prototype = { this.comment = false; return; } else if(this.openBlock) { - // set up the stack before the new compiler starts - this.fn += "stack.push(context);"; - var compiler = new Handlebars.Compiler(this.string.slice(this.pointer + 1, -1)); - - // sub-compile with a custom EOF instruction - var result = compiler.compile(function(compiler) { - if(compiler.peek(mustache.length + 5) === "{{/" + mustache + "}}") { - compiler.getChar(mustache.length + 5); - return true; - } - }); - - // move the pointer forward the amount of characters handled by the sub-compiler - this.pointer += compiler.pointer + 1; - - // each function made internally needs a unique IDs. These are locals, so they - // don't need to be globally unique, just per compiler - var fnId = "fn" + this.pointer.toString(); - this.fn += "var proxy = Handlebars.buildContext(" + param + ", stack);"; - this.fn += "var " + fnId + " = function(context) {" + result + "}; "; - this.fn += "lookup = " + this.lookupFor(mustache) + "; "; - this.fn += "if(Handlebars.isFunction(lookup)) out = out + lookup.call(proxy, " + fnId + "); "; - this.fn += "else if(typeof lookup !== 'undefined') out = out + Handlebars.helperMissing.call(proxy, lookup, " + fnId + "); "; - - this.fn += "stack.pop();"; - this.openBlock = false; + this.addBlock(mustache, param, parts) return; } else { - this.addExpression(mustache); - return; + return this.addExpression(mustache); } } else if(this.comment) { ; From 630978c15df82d33623ebb5005faee8fc63a74ca Mon Sep 17 00:00:00 2001 From: wycats Date: Sat, 7 Aug 2010 19:48:49 -0700 Subject: [PATCH 023/111] Added TODO before 1.0 --- TODO.markdown | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 TODO.markdown diff --git a/TODO.markdown b/TODO.markdown new file mode 100644 index 00000000..e69de29b From 5459b0ee3a98205eaf40ca6936e275123105bbb2 Mon Sep 17 00:00:00 2001 From: wycats Date: Sat, 7 Aug 2010 19:50:24 -0700 Subject: [PATCH 024/111] For real this time --- TODO.markdown | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/TODO.markdown b/TODO.markdown index e69de29b..af7c5126 100644 --- a/TODO.markdown +++ b/TODO.markdown @@ -0,0 +1,10 @@ +* Partials (fallback.partials hash) +* Inverse sections... +* ...and {{#foo}}...{{^}}...{{/foo}} +* data-binding for simple {{}} +* try not to hardcode the data-binding strategy (make it pluggable) +* data-binding for simple block helpers +* data-binding for iteration-style block helpers +* escaping +* README +* Rationale (how it's different from mustache, and why) From a74794ba8d12f1f649e57b1e41c2a84208e811c2 Mon Sep 17 00:00:00 2001 From: Alan Johnson Date: Sun, 8 Aug 2010 00:14:03 -0400 Subject: [PATCH 025/111] Got escaping working, as well as avoiding escaping with {{{ --- lib/handlebars.js | 50 ++++++++++++++++++++++++++++++++++++++++++++-- test/handlebars.js | 10 +++++++++- 2 files changed, 57 insertions(+), 3 deletions(-) diff --git a/lib/handlebars.js b/lib/handlebars.js index e3e6b18b..30c2154d 100644 --- a/lib/handlebars.js +++ b/lib/handlebars.js @@ -9,6 +9,33 @@ Handlebars = { return toString.call(fn) === "[object Function]"; }, + escape: function(string) { + if (string === null) { + string = ""; + } + + return string.replace(/&(?!\w+;)|["\\<>]/g, function(str) { + switch(str) { + case "&": + return "&"; + break; + case '"': + return "\""; + case "\\": + return "\\\\"; + break; + case "<": + return "<"; + break; + case ">": + return ">"; + break; + default: + return str; + } + }); + }, + buildContext: function(context, stack) { var contextWrapper = function(stack) { this.__stack__ = stack; @@ -78,6 +105,7 @@ Handlebars.Compiler = function(string) { this.fn = "var out = ''; var lookup; "; this.newlines = ""; this.comment = false; + this.escaped = true; }; Handlebars.ParseError = function(message) { @@ -146,8 +174,13 @@ Handlebars.Compiler.prototype = { addExpression: function(mustache) { var expr = this.lookupFor(mustache); - this.fn += "if (Handlebars.isFunction(" + expr + ")) out = out + " + expr + ".call(Handlebars.buildContext(context, stack)); "; - this.fn += "else if(typeof " + expr + "!== 'undefined') out = out + " + expr + "; "; + var escapeCall = "("; + if (this.escaped) { + escapeCall = "Handlebars.escape("; + } + + this.fn += "if (Handlebars.isFunction(" + expr + ")) out = out + " + escapeCall + expr + ".call(Handlebars.buildContext(context, stack))); "; + this.fn += "else if(typeof " + expr + "!== 'undefined') out = out + " + escapeCall + expr + ");"; }, lookupFor: function(param) { @@ -207,6 +240,9 @@ Handlebars.Compiler.prototype = { } else if(next === "#") { this.openBlock = true; this.getChar(); + } else if(next === "{") { + this.escaped = false; + this.getChar(); } this.addText(); @@ -219,7 +255,15 @@ Handlebars.Compiler.prototype = { param = this.lookupFor(parts[1]); this.mustache = false; + + // finish reading off the close of the handlebars this.getChar(); + // {{{expression}} is techically valid, but if we started with {{{ we'll try to read + // }}} off of the close of the handlebars + if (!this.escaped && this.peek() === "}") { + this.getChar(); + } + if(this.comment) { this.comment = false; return; @@ -229,6 +273,8 @@ Handlebars.Compiler.prototype = { } else { return this.addExpression(mustache); } + + this.escaped = false; } else if(this.comment) { ; } else { diff --git a/test/handlebars.js b/test/handlebars.js index c5060545..6a92a6d7 100644 --- a/test/handlebars.js +++ b/test/handlebars.js @@ -26,6 +26,14 @@ test("boolean", function() { "booleans do not show the contents when false"); }); +test("escaping", function() { + shouldCompileTo("{{awesome}}", {awesome: "&\"\\<>"}, '&\"\\\\<>', + "by default expressions should be escaped"); + + shouldCompileTo("{{{awesome}}}", {awesome: "&\"\\<>"}, '&\"\\<>', + "expressions with 3 handlebars aren't escaped"); +}); + test("functions", function() { shouldCompileTo("{{awesome}}", {awesome: function() { return "Awesome"; }}, "Awesome", "functions are called and render their output"); @@ -89,7 +97,7 @@ test("block with complex lookup", function() { }); test("helper with complex lookup", function() { - var string = "{{#goodbyes}}{{link}}{{/goodbyes}}" + var string = "{{#goodbyes}}{{{link}}}{{/goodbyes}}" var hash = {prefix: "/root", goodbyes: [{text: "Goodbye", url: "goodbye"}]}; var fallback = {link: function() { return "" + this.text + "" From 8a1dd118af299ff02e15249c5413508f99efbc4c Mon Sep 17 00:00:00 2001 From: Alan Johnson Date: Sun, 8 Aug 2010 00:25:55 -0400 Subject: [PATCH 026/111] Realized I goofed in one spot. Fixed\! --- lib/handlebars.js | 2 +- test/handlebars.js | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/lib/handlebars.js b/lib/handlebars.js index 30c2154d..b3d0b908 100644 --- a/lib/handlebars.js +++ b/lib/handlebars.js @@ -274,7 +274,7 @@ Handlebars.Compiler.prototype = { return this.addExpression(mustache); } - this.escaped = false; + this.escaped = true; } else if(this.comment) { ; } else { diff --git a/test/handlebars.js b/test/handlebars.js index 6a92a6d7..b835f2d1 100644 --- a/test/handlebars.js +++ b/test/handlebars.js @@ -27,11 +27,11 @@ test("boolean", function() { }); test("escaping", function() { - shouldCompileTo("{{awesome}}", {awesome: "&\"\\<>"}, '&\"\\\\<>', - "by default expressions should be escaped"); - - shouldCompileTo("{{{awesome}}}", {awesome: "&\"\\<>"}, '&\"\\<>', + shouldCompileTo("{{{awesome}}}", {awesome: "&\"\\<>"}, '&\"\\<>', "expressions with 3 handlebars aren't escaped"); + + shouldCompileTo("{{awesome}}", {awesome: "&\"\\<>"}, '&\"\\\\<>', + "by default expressions should be escaped"); }); test("functions", function() { From d5d06c71f055a10b4ed5f534151209f61ee6faf2 Mon Sep 17 00:00:00 2001 From: Alan Johnson Date: Sun, 8 Aug 2010 16:34:19 -0400 Subject: [PATCH 027/111] Added ability to specify unescaped items with &. --- lib/handlebars.js | 2 +- test/handlebars.js | 3 +++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/lib/handlebars.js b/lib/handlebars.js index b3d0b908..852e418b 100644 --- a/lib/handlebars.js +++ b/lib/handlebars.js @@ -240,7 +240,7 @@ Handlebars.Compiler.prototype = { } else if(next === "#") { this.openBlock = true; this.getChar(); - } else if(next === "{") { + } else if(next === "{" || next === "&") { this.escaped = false; this.getChar(); } diff --git a/test/handlebars.js b/test/handlebars.js index b835f2d1..6584b665 100644 --- a/test/handlebars.js +++ b/test/handlebars.js @@ -32,6 +32,9 @@ test("escaping", function() { shouldCompileTo("{{awesome}}", {awesome: "&\"\\<>"}, '&\"\\\\<>', "by default expressions should be escaped"); + + shouldCompileTo("{{&awesome}}", {awesome: "&\"\\<>"}, '&\"\\<>', + "expressions with {{& handlebars aren't escaped"); }); test("functions", function() { From 792251f6c9bf79e0999a3749831b75e5277f0d45 Mon Sep 17 00:00:00 2001 From: Alan Johnson Date: Sun, 8 Aug 2010 17:56:35 -0400 Subject: [PATCH 028/111] Added the new safestring type and a test for its implementation. --- lib/handlebars.js | 7 +++++++ test/handlebars.js | 6 ++++++ 2 files changed, 13 insertions(+) diff --git a/lib/handlebars.js b/lib/handlebars.js index 852e418b..3cfaf5ef 100644 --- a/lib/handlebars.js +++ b/lib/handlebars.js @@ -112,6 +112,13 @@ Handlebars.ParseError = function(message) { this.message = message; }; +// Build out our basic SafeString type +Handlebars.SafeString = function(string) { + this.string = string; +} +Handlebars.SafeString.prototype.toString = function() { + return this.string.toString(); +} Handlebars.helperMissing = function(object, fn) { var ret = ""; diff --git a/test/handlebars.js b/test/handlebars.js index 6584b665..f012c0c7 100644 --- a/test/handlebars.js +++ b/test/handlebars.js @@ -175,4 +175,10 @@ test("the fallback hash is available is nested contexts", function() { module("partials"); +module("safestring"); +test("constructing a safestring from a string and checking its type", function() { + var safe = new Handlebars.SafeString("testing 1, 2, 3"); + ok(safe instanceof Handlebars.SafeString, "SafeString is an instance of Handlebars.SafeString"); + equal(safe, "testing 1, 2, 3", "SafeString is equivalent to its underlying string"); +}); From cd4d0453f206450b0092cbbbf388f2425ba0e840 Mon Sep 17 00:00:00 2001 From: Alan Johnson Date: Sun, 8 Aug 2010 18:01:42 -0400 Subject: [PATCH 029/111] Tested that safestrings don't get escaped. --- lib/handlebars.js | 6 +++++- test/handlebars.js | 7 +++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/lib/handlebars.js b/lib/handlebars.js index 3cfaf5ef..5594ac18 100644 --- a/lib/handlebars.js +++ b/lib/handlebars.js @@ -10,7 +10,11 @@ Handlebars = { }, escape: function(string) { - if (string === null) { + // don't escape SafeStrings, since they're already safe + if (string instanceof Handlebars.SafeString) { + return string.toString(); + } + else if (string === null) { string = ""; } diff --git a/test/handlebars.js b/test/handlebars.js index f012c0c7..4c9e3a1d 100644 --- a/test/handlebars.js +++ b/test/handlebars.js @@ -35,6 +35,13 @@ test("escaping", function() { shouldCompileTo("{{&awesome}}", {awesome: "&\"\\<>"}, '&\"\\<>', "expressions with {{& handlebars aren't escaped"); + +}); + +test("functions returning safestrings shouldn't be escaped", function() { + var hash = {awesome: function() { return new Handlebars.SafeString("&\"\\<>"); }}; + shouldCompileTo("{{awesome}}", hash, '&\"\\<>', + "functions returning safestrings aren't escaped"); }); test("functions", function() { From be56661af1cc89ae0fec7268f8b36253a776e584 Mon Sep 17 00:00:00 2001 From: Alan Johnson Date: Sun, 8 Aug 2010 18:02:32 -0400 Subject: [PATCH 030/111] Took escaping off of the TODO list. --- TODO.markdown | 1 - 1 file changed, 1 deletion(-) diff --git a/TODO.markdown b/TODO.markdown index af7c5126..6ec32f50 100644 --- a/TODO.markdown +++ b/TODO.markdown @@ -5,6 +5,5 @@ * try not to hardcode the data-binding strategy (make it pluggable) * data-binding for simple block helpers * data-binding for iteration-style block helpers -* escaping * README * Rationale (how it's different from mustache, and why) From 4f1d6e92bd2ec1d2ec8d5de51042f688ae38f9cc Mon Sep 17 00:00:00 2001 From: Alan Johnson Date: Thu, 12 Aug 2010 21:29:19 -0400 Subject: [PATCH 031/111] Added partials. --- lib/handlebars.js | 15 ++++++++++++++- test/handlebars.js | 16 ++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/lib/handlebars.js b/lib/handlebars.js index 5594ac18..e3ea7415 100644 --- a/lib/handlebars.js +++ b/lib/handlebars.js @@ -2,7 +2,7 @@ Handlebars = { compile: function(string) { var compiler = new Handlebars.Compiler(string); var result = compiler.compile(); - return new Function("context", "fallback", "fallback = fallback || {}; var stack = [];" + result); + return new Function("context", "fallback", "fallback = fallback || {}; var stack = [];var partials = {};" + result); }, isFunction: function(fn) { @@ -110,6 +110,7 @@ Handlebars.Compiler = function(string) { this.newlines = ""; this.comment = false; this.escaped = true; + this.partial = false; }; Handlebars.ParseError = function(message) { @@ -240,6 +241,12 @@ Handlebars.Compiler.prototype = { this.openBlock = false; }, + addPartial: function(mustache, param) { + // either used a cached copy of the partial or compile a new one + this.fn += "if (typeof partials['" + mustache + "'] === 'undefined') partials['" + mustache + "'] = Handlebars.compile(fallback['partials']['" + mustache + "']);"; + this.fn += "out = out + partials['" + mustache + "'](" + param + ", fallback);"; + }, + parseMustache: function() { var chr, part, mustache, param; @@ -251,6 +258,9 @@ Handlebars.Compiler.prototype = { } else if(next === "#") { this.openBlock = true; this.getChar(); + } else if (next === ">") { + this.partial = true; + this.getChar(); } else if(next === "{" || next === "&") { this.escaped = false; this.getChar(); @@ -278,6 +288,9 @@ Handlebars.Compiler.prototype = { if(this.comment) { this.comment = false; return; + } else if (this.partial) { + this.addPartial(mustache, param) + return; } else if(this.openBlock) { this.addBlock(mustache, param, parts) return; diff --git a/test/handlebars.js b/test/handlebars.js index 4c9e3a1d..9fcb6b7e 100644 --- a/test/handlebars.js +++ b/test/handlebars.js @@ -182,6 +182,22 @@ test("the fallback hash is available is nested contexts", function() { module("partials"); +test("basic partials", function() { + var string = "Dudes: {{#dudes}}{{> dude}}{{/dudes}}"; + var partial = "{{name}} ({{url}}) "; + var hash = {dudes: [{name: "Yehuda", url: "http://yehuda"}, {name: "Alan", url: "http://alan"}]}; + shouldCompileTo(string, [hash, {partials: {dude: partial}}], "Dudes: Yehuda (http://yehuda) Alan (http://alan) ", + "Basic partials output based on current context."); +}); + +test("partials with context", function() { + var string = "Dudes: {{> dude dudes}}"; + var partial = "{{#this}}{{name}} ({{url}}) {{/this}}"; + var hash = {dudes: [{name: "Yehuda", url: "http://yehuda"}, {name: "Alan", url: "http://alan"}]}; + shouldCompileTo(string, [hash, {partials: {dude: partial}}], "Dudes: Yehuda (http://yehuda) Alan (http://alan) ", + "Partials can be passed a context"); +}); + module("safestring"); test("constructing a safestring from a string and checking its type", function() { From ab757858a220cb20570d87d870431f15e6e51ee0 Mon Sep 17 00:00:00 2001 From: Alan Johnson Date: Thu, 12 Aug 2010 21:29:50 -0400 Subject: [PATCH 032/111] Marked partials off of the list. --- TODO.markdown | 1 - 1 file changed, 1 deletion(-) diff --git a/TODO.markdown b/TODO.markdown index 6ec32f50..68e76436 100644 --- a/TODO.markdown +++ b/TODO.markdown @@ -1,4 +1,3 @@ -* Partials (fallback.partials hash) * Inverse sections... * ...and {{#foo}}...{{^}}...{{/foo}} * data-binding for simple {{}} From 57aadef7c1eba4a90f84ec48ee37949c72ae28d5 Mon Sep 17 00:00:00 2001 From: Alan Johnson Date: Thu, 12 Aug 2010 22:46:20 -0400 Subject: [PATCH 033/111] Added test for a partial inside of a partial. --- lib/handlebars.js | 2 ++ test/handlebars.js | 8 ++++++++ 2 files changed, 10 insertions(+) diff --git a/lib/handlebars.js b/lib/handlebars.js index e3ea7415..8741a3da 100644 --- a/lib/handlebars.js +++ b/lib/handlebars.js @@ -2,6 +2,8 @@ Handlebars = { compile: function(string) { var compiler = new Handlebars.Compiler(string); var result = compiler.compile(); + console.log("Template: " + string); + console.log("Code: " + result); return new Function("context", "fallback", "fallback = fallback || {}; var stack = [];var partials = {};" + result); }, diff --git a/test/handlebars.js b/test/handlebars.js index 9fcb6b7e..13659c4a 100644 --- a/test/handlebars.js +++ b/test/handlebars.js @@ -198,6 +198,14 @@ test("partials with context", function() { "Partials can be passed a context"); }); +test("partial in a partial", function() { + var string = "Dudes: {{#dudes}}{{> dude}}{{/dudes}}"; + var dude = "{{name}} {{> url}} "; + var url = "{{url}}"; + var hash = {dudes: [{name: "Yehuda", url: "http://yehuda"}, {name: "Alan", url: "http://alan"}]}; + shouldCompileTo(string, [hash, {partials: {dude: dude, url: url}}], "Dudes: Yehuda http://yehuda Alan http://alan ", "Partials are rendered inside of other partials"); +}); + module("safestring"); test("constructing a safestring from a string and checking its type", function() { From ad6a53e2774785de02319a302c074ebfcca6764e Mon Sep 17 00:00:00 2001 From: Alan Johnson Date: Thu, 12 Aug 2010 23:12:26 -0400 Subject: [PATCH 034/111] Got escaping of text working, I think. --- lib/handlebars.js | 18 +++++++++++++----- test/handlebars.js | 7 ++++++- 2 files changed, 19 insertions(+), 6 deletions(-) diff --git a/lib/handlebars.js b/lib/handlebars.js index 8741a3da..77a59491 100644 --- a/lib/handlebars.js +++ b/lib/handlebars.js @@ -2,8 +2,6 @@ Handlebars = { compile: function(string) { var compiler = new Handlebars.Compiler(string); var result = compiler.compile(); - console.log("Template: " + string); - console.log("Code: " + result); return new Function("context", "fallback", "fallback = fallback || {}; var stack = [];var partials = {};" + result); }, @@ -11,7 +9,16 @@ Handlebars = { return toString.call(fn) === "[object Function]"; }, - escape: function(string) { + escapeText: function(string) { + string = string.replace("'", "\\'"); + if (string.slice(-1) == "\\") { + string = string + "\\"; + } + + return string; + }, + + escapeExpression: function(string) { // don't escape SafeStrings, since they're already safe if (string instanceof Handlebars.SafeString) { return string.toString(); @@ -179,7 +186,8 @@ Handlebars.Compiler.prototype = { addText: function() { if(this.text) { - this.fn = this.fn + "out = out + '" + this.text + "'; "; + console.log("out = out + '" + Handlebars.escapeText(this.text) + "'; "); + this.fn = this.fn + "out = out + \"" + Handlebars.escapeText(this.text) + "\"; "; this.fn = this.fn + this.newlines; this.newlines = ""; this.text = ""; @@ -190,7 +198,7 @@ Handlebars.Compiler.prototype = { var expr = this.lookupFor(mustache); var escapeCall = "("; if (this.escaped) { - escapeCall = "Handlebars.escape("; + escapeCall = "Handlebars.escapeExpression("; } this.fn += "if (Handlebars.isFunction(" + expr + ")) out = out + " + escapeCall + expr + ".call(Handlebars.buildContext(context, stack))); "; diff --git a/test/handlebars.js b/test/handlebars.js index 13659c4a..3c23f5ce 100644 --- a/test/handlebars.js +++ b/test/handlebars.js @@ -26,7 +26,12 @@ test("boolean", function() { "booleans do not show the contents when false"); }); -test("escaping", function() { +test("escaping text", function() { + shouldCompileTo("Awesome's", {}, "Awesome's", "text is escaped so that it doesn't get caught on single quotes"); + shouldCompileTo("Awesome\\", {}, "Awesome\\", "text is escaped so that the closing quote can't be ignored"); +}); + +test("escaping expressions", function() { shouldCompileTo("{{{awesome}}}", {awesome: "&\"\\<>"}, '&\"\\<>', "expressions with 3 handlebars aren't escaped"); From 5bd5d4eed4dc7adca6929cc107a7b63fcaf7e09d Mon Sep 17 00:00:00 2001 From: Alan Johnson Date: Thu, 12 Aug 2010 23:13:04 -0400 Subject: [PATCH 035/111] Fixed up an errant console.log. --- lib/handlebars.js | 1 - 1 file changed, 1 deletion(-) diff --git a/lib/handlebars.js b/lib/handlebars.js index 77a59491..9b5ce0c6 100644 --- a/lib/handlebars.js +++ b/lib/handlebars.js @@ -186,7 +186,6 @@ Handlebars.Compiler.prototype = { addText: function() { if(this.text) { - console.log("out = out + '" + Handlebars.escapeText(this.text) + "'; "); this.fn = this.fn + "out = out + \"" + Handlebars.escapeText(this.text) + "\"; "; this.fn = this.fn + this.newlines; this.newlines = ""; From 467024d1e2c3e03724a18be8311069db59ff031c Mon Sep 17 00:00:00 2001 From: Alan Johnson Date: Thu, 12 Aug 2010 23:15:01 -0400 Subject: [PATCH 036/111] FTiny test tweak - quoted href of a link in one of the test templates, just because it was bugging me. --- test/handlebars.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/handlebars.js b/test/handlebars.js index 3c23f5ce..a394f3b9 100644 --- a/test/handlebars.js +++ b/test/handlebars.js @@ -206,9 +206,9 @@ test("partials with context", function() { test("partial in a partial", function() { var string = "Dudes: {{#dudes}}{{> dude}}{{/dudes}}"; var dude = "{{name}} {{> url}} "; - var url = "{{url}}"; + var url = "{{url}}"; var hash = {dudes: [{name: "Yehuda", url: "http://yehuda"}, {name: "Alan", url: "http://alan"}]}; - shouldCompileTo(string, [hash, {partials: {dude: dude, url: url}}], "Dudes: Yehuda http://yehuda Alan http://alan ", "Partials are rendered inside of other partials"); + shouldCompileTo(string, [hash, {partials: {dude: dude, url: url}}], "Dudes: Yehuda http://yehuda Alan http://alan ", "Partials are rendered inside of other partials"); }); module("safestring"); From f0bb7b578a7300520f09cee3d13477a2657a12b7 Mon Sep 17 00:00:00 2001 From: Alan Johnson Date: Fri, 13 Aug 2010 04:57:39 -0700 Subject: [PATCH 037/111] --- TODO.markdown | 3 +++ 1 file changed, 3 insertions(+) diff --git a/TODO.markdown b/TODO.markdown index 68e76436..b62ee6e8 100644 --- a/TODO.markdown +++ b/TODO.markdown @@ -6,3 +6,6 @@ * data-binding for iteration-style block helpers * README * Rationale (how it's different from mustache, and why) + +* Partials +* ... Get compiled partial cache to be used when partials are called inside of partials. From 135147173bb2db003ff4d8c2583d717e316d8cf4 Mon Sep 17 00:00:00 2001 From: Alan Johnson Date: Sun, 15 Aug 2010 16:10:26 -0400 Subject: [PATCH 038/111] Write tests for inverted sections. --- test/handlebars.js | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/test/handlebars.js b/test/handlebars.js index a394f3b9..1b2d19df 100644 --- a/test/handlebars.js +++ b/test/handlebars.js @@ -86,6 +86,32 @@ test("this keyword in paths", function() { shouldCompileTo(string, hash, "helloHelloHELLO", "This keyword evaluates in more complex paths"); }); +module("inverted sections"); + +test("inverted sections with unset value", function() { + var string = "{{#goodbyes}}{{this}}{{/goodbyes}}{{^goodbyes}}Right On!{{/goodbyes}}"; + var hash = {}; + shouldCompileTo(string, hash, "Right On!", "Inverted section rendered when value isn't set."); +}); + +test("inverted section with false value", function() { + var string = "{{#goodbyes}}{{this}}{{/goodbyes}}{{^goodbyes}}Right On!{{/goodbyes}}"; + var hash = {goodbyes: false}; + shouldCompileTo(string, hash, "Right On!", "Inverted section rendered when value is false."); +}); + +test("inverted section with empty set", function() { + var string = "{{#goodbyes}}{{this}}{{/goodbyes}}{{^goodbyes}}Right On!{{/goodbyes}}"; + var hash = {goodbyes: []}; + shouldCompileTo(string, hash, "Right On!", "Inverted section rendered when value is empty set."); +}); + +test("inverted section using result of function call", function() { + var string = "{{#goodbyes}}{{this}}{{/goodbyes}}{{^goodbyes}}Right On!{{/goodbyes}}"; + var hash = {goodbyes: function() { return false; }} + shouldCompileTo(string, hash, "Right On!", "Inverted section rendered when result of function in expression is false."); +}); + module("blocks"); test("array", function() { From a04a8e792b7c3723b591adb660d9cc8680f592ad Mon Sep 17 00:00:00 2001 From: Alan Johnson Date: Sun, 15 Aug 2010 16:21:49 -0400 Subject: [PATCH 039/111] Got partials to cache inside of fallback/partials itself and added an exception for when partials aren't defined. --- lib/handlebars.js | 11 ++++++----- test/handlebars.js | 15 ++++++++++++++- 2 files changed, 20 insertions(+), 6 deletions(-) diff --git a/lib/handlebars.js b/lib/handlebars.js index 9b5ce0c6..80e1de0b 100644 --- a/lib/handlebars.js +++ b/lib/handlebars.js @@ -2,7 +2,7 @@ Handlebars = { compile: function(string) { var compiler = new Handlebars.Compiler(string); var result = compiler.compile(); - return new Function("context", "fallback", "fallback = fallback || {}; var stack = [];var partials = {};" + result); + return new Function("context", "fallback", "fallback = fallback || {}; var stack = [];" + result); }, isFunction: function(fn) { @@ -90,7 +90,7 @@ Handlebars = { switch(parts[i]) { case "..": if (readDepth) { - throw new Handlebars.ParseError("Cannot jump out of context after moving into a context."); + throw new Handlebars.Exception("Cannot jump out of context after moving into a context."); } else { depth += 1; } @@ -122,7 +122,7 @@ Handlebars.Compiler = function(string) { this.partial = false; }; -Handlebars.ParseError = function(message) { +Handlebars.Exception = function(message) { this.message = message; }; @@ -252,8 +252,9 @@ Handlebars.Compiler.prototype = { addPartial: function(mustache, param) { // either used a cached copy of the partial or compile a new one - this.fn += "if (typeof partials['" + mustache + "'] === 'undefined') partials['" + mustache + "'] = Handlebars.compile(fallback['partials']['" + mustache + "']);"; - this.fn += "out = out + partials['" + mustache + "'](" + param + ", fallback);"; + this.fn += "if (typeof fallback['partials'] === 'undefined' || typeof fallback['partials']['" + mustache + "'] === 'undefined') throw new Handlebars.Exception('Attempted to render undefined partial: " + mustache + "');"; + this.fn += "if (!Handlebars.isFunction(fallback['partials']['" + mustache + "'])) fallback['partials']['" + mustache + "'] = Handlebars.compile(fallback['partials']['" + mustache + "']);"; + this.fn += "out = out + fallback['partials']['" + mustache + "'](" + param + ", fallback);"; }, parseMustache: function() { diff --git a/test/handlebars.js b/test/handlebars.js index a394f3b9..36421004 100644 --- a/test/handlebars.js +++ b/test/handlebars.js @@ -64,7 +64,7 @@ test("bad idea nested paths", function() { try { Handlebars.compile("{{#goodbyes}}{{../name/../name}}{{/goodbyes}}"); } catch (e) { - if (e instanceof Handlebars.ParseError) { + if (e instanceof Handlebars.Exception) { caught = true; } } @@ -211,6 +211,19 @@ test("partial in a partial", function() { shouldCompileTo(string, [hash, {partials: {dude: dude, url: url}}], "Dudes: Yehuda http://yehuda Alan http://alan ", "Partials are rendered inside of other partials"); }); +test("rendering undefined partial throws an exception", function() { + var caught = false; + try { + var template = Handlebars.compile("{{> whatever}}"); + template(); + } catch (e) { + if (e instanceof Handlebars.Exception) { + caught = true; + } + } + equals(caught, true); +}); + module("safestring"); test("constructing a safestring from a string and checking its type", function() { From dc318908d302c36d3142a5bfff11b517c53b211e Mon Sep 17 00:00:00 2001 From: Alan Johnson Date: Sun, 15 Aug 2010 16:22:39 -0400 Subject: [PATCH 040/111] Updated TODO. --- TODO.markdown | 3 --- 1 file changed, 3 deletions(-) diff --git a/TODO.markdown b/TODO.markdown index b62ee6e8..68e76436 100644 --- a/TODO.markdown +++ b/TODO.markdown @@ -6,6 +6,3 @@ * data-binding for iteration-style block helpers * README * Rationale (how it's different from mustache, and why) - -* Partials -* ... Get compiled partial cache to be used when partials are called inside of partials. From 2a112fe07feac88441a6baad2dcedb2b1aa2c594 Mon Sep 17 00:00:00 2001 From: Alan Johnson Date: Tue, 17 Aug 2010 00:46:04 -0400 Subject: [PATCH 041/111] Made progress on inverted sections. Functions almost work now, and expressions aren't far behind. --- TODO.markdown | 2 ++ lib/handlebars.js | 49 ++++++++++++++++++++++++++++++++++++++++++++--- 2 files changed, 48 insertions(+), 3 deletions(-) diff --git a/TODO.markdown b/TODO.markdown index 68e76436..acc297ff 100644 --- a/TODO.markdown +++ b/TODO.markdown @@ -6,3 +6,5 @@ * data-binding for iteration-style block helpers * README * Rationale (how it's different from mustache, and why) + +* Refactor blocks/inverted sections so shared code isn't copied and pasted diff --git a/lib/handlebars.js b/lib/handlebars.js index 80e1de0b..351673bb 100644 --- a/lib/handlebars.js +++ b/lib/handlebars.js @@ -107,6 +107,18 @@ Handlebars = { } return [depth, dig]; + }, + + isEmpty: function(value) { + if (typeof object === "undefined") { + return true; + } else if (!object) { + return true; + } else if(toString.call(object) === "[object Array]" && object.length == 0) { + return true; + } else { + return false; + } } } @@ -120,6 +132,7 @@ Handlebars.Compiler = function(string) { this.comment = false; this.escaped = true; this.partial = false; + this.inverted = false; }; Handlebars.Exception = function(message) { @@ -204,6 +217,23 @@ Handlebars.Compiler.prototype = { this.fn += "else if(typeof " + expr + "!== 'undefined') out = out + " + escapeCall + expr + ");"; }, + addInvertedSection: function(mustache) { + var result = this.compileToEndOfBlock(mustache); + + + // each function made internally needs a unique IDs. These are locals, so they + // don't need to be globally unique, just per compiler + var fnId = "fn" + this.pointer.toString(); + this.fn += "var proxy = Handlebars.buildContext(context, stack);"; + this.fn += "var " + fnId + " = function(context) {" + result + "}; "; + this.fn += "lookup = " + this.lookupFor(mustache) + "; "; + this.fn += "if(Handlebars.isFunction(lookup) && Handlebars.isEmpty(lookup())) out = out + " + fnId + "(proxy);"; + console.log(this.fn); + + this.openBlock = false; + this.inverted = false; + }, + lookupFor: function(param) { var parsed = Handlebars.parsePath(param); var depth = parsed[0]; @@ -221,9 +251,7 @@ Handlebars.Compiler.prototype = { } }, - addBlock: function(mustache, param, parts) { - // set up the stack before the new compiler starts - this.fn += "stack.push(context);"; + compileToEndOfBlock: function(mustache) { var compiler = new Handlebars.Compiler(this.string.slice(this.pointer + 1, -1)); // sub-compile with a custom EOF instruction @@ -237,6 +265,14 @@ Handlebars.Compiler.prototype = { // move the pointer forward the amount of characters handled by the sub-compiler this.pointer += compiler.pointer + 1; + return result; + }, + + addBlock: function(mustache, param, parts) { + // set up the stack before the new compiler starts + this.fn += "stack.push(context);"; + var result = this.compileToEndOfBlock(mustache); + // each function made internally needs a unique IDs. These are locals, so they // don't need to be globally unique, just per compiler var fnId = "fn" + this.pointer.toString(); @@ -271,6 +307,10 @@ Handlebars.Compiler.prototype = { } else if (next === ">") { this.partial = true; this.getChar(); + } else if (next === "^") { + this.inverted = true; + this.openBlock = true; + this.getChar(); } else if(next === "{" || next === "&") { this.escaped = false; this.getChar(); @@ -301,6 +341,9 @@ Handlebars.Compiler.prototype = { } else if (this.partial) { this.addPartial(mustache, param) return; + } else if (this.inverted) { + this.addInvertedSection(mustache); + return; } else if(this.openBlock) { this.addBlock(mustache, param, parts) return; From a9c875e0a9429f5699c45eb7f4fc1bea0a37062d Mon Sep 17 00:00:00 2001 From: Alan Johnson Date: Wed, 18 Aug 2010 20:57:02 -0400 Subject: [PATCH 042/111] Got basic inverted sections working. --- lib/handlebars.js | 30 ++++++++++++++++++++---------- test/handlebars.js | 2 +- 2 files changed, 21 insertions(+), 11 deletions(-) diff --git a/lib/handlebars.js b/lib/handlebars.js index 351673bb..2f3b8981 100644 --- a/lib/handlebars.js +++ b/lib/handlebars.js @@ -110,16 +110,28 @@ Handlebars = { }, isEmpty: function(value) { - if (typeof object === "undefined") { + if (typeof value === "undefined") { return true; - } else if (!object) { + } else if (!value) { return true; - } else if(toString.call(object) === "[object Array]" && object.length == 0) { + } else if(toString.call(value) === "[object Array]" && value.length == 0) { return true; } else { return false; } - } + }, + + // Escapes output and converts empty values to empty strings + filterOutput: function(value, escape) { + + if (Handlebars.isEmpty(value)) { + return ""; + } else if (escape) { + return Handlebars.escapeExpression(value); + } else { + return value; + } + }, } Handlebars.Compiler = function(string) { @@ -208,13 +220,10 @@ Handlebars.Compiler.prototype = { addExpression: function(mustache) { var expr = this.lookupFor(mustache); - var escapeCall = "("; - if (this.escaped) { - escapeCall = "Handlebars.escapeExpression("; - } - this.fn += "if (Handlebars.isFunction(" + expr + ")) out = out + " + escapeCall + expr + ".call(Handlebars.buildContext(context, stack))); "; - this.fn += "else if(typeof " + expr + "!== 'undefined') out = out + " + escapeCall + expr + ");"; + this.fn += "if (Handlebars.isFunction(" + expr + ")) out = out + Handlebars.filterOutput(" + expr + ".call(Handlebars.buildContext(context, stack)), " + this.escaped + "); "; + this.fn += "else if(typeof " + expr + "!== 'undefined') out = out + Handlebars.filterOutput(" + expr + ", " + this.escaped + ");"; + console.log(this.fn); }, addInvertedSection: function(mustache) { @@ -228,6 +237,7 @@ Handlebars.Compiler.prototype = { this.fn += "var " + fnId + " = function(context) {" + result + "}; "; this.fn += "lookup = " + this.lookupFor(mustache) + "; "; this.fn += "if(Handlebars.isFunction(lookup) && Handlebars.isEmpty(lookup())) out = out + " + fnId + "(proxy);"; + this.fn += "else if (Handlebars.isEmpty(lookup)) out = out + " + fnId + "(proxy);"; console.log(this.fn); this.openBlock = false; diff --git a/test/handlebars.js b/test/handlebars.js index 0d635bab..83d374cf 100644 --- a/test/handlebars.js +++ b/test/handlebars.js @@ -107,7 +107,7 @@ test("inverted section with empty set", function() { }); test("inverted section using result of function call", function() { - var string = "{{#goodbyes}}{{this}}{{/goodbyes}}{{^goodbyes}}Right On!{{/goodbyes}}"; + var string = "{{goodbyes}}{{^goodbyes}}Right On!{{/goodbyes}}"; var hash = {goodbyes: function() { return false; }} shouldCompileTo(string, hash, "Right On!", "Inverted section rendered when result of function in expression is false."); }); From 598f333085e4c5c147b9029f36fd43b1e162d39f Mon Sep 17 00:00:00 2001 From: Alan Johnson Date: Wed, 18 Aug 2010 20:57:42 -0400 Subject: [PATCH 043/111] Got rid of some debugging output. --- lib/handlebars.js | 2 -- 1 file changed, 2 deletions(-) diff --git a/lib/handlebars.js b/lib/handlebars.js index 2f3b8981..96069151 100644 --- a/lib/handlebars.js +++ b/lib/handlebars.js @@ -223,7 +223,6 @@ Handlebars.Compiler.prototype = { this.fn += "if (Handlebars.isFunction(" + expr + ")) out = out + Handlebars.filterOutput(" + expr + ".call(Handlebars.buildContext(context, stack)), " + this.escaped + "); "; this.fn += "else if(typeof " + expr + "!== 'undefined') out = out + Handlebars.filterOutput(" + expr + ", " + this.escaped + ");"; - console.log(this.fn); }, addInvertedSection: function(mustache) { @@ -238,7 +237,6 @@ Handlebars.Compiler.prototype = { this.fn += "lookup = " + this.lookupFor(mustache) + "; "; this.fn += "if(Handlebars.isFunction(lookup) && Handlebars.isEmpty(lookup())) out = out + " + fnId + "(proxy);"; this.fn += "else if (Handlebars.isEmpty(lookup)) out = out + " + fnId + "(proxy);"; - console.log(this.fn); this.openBlock = false; this.inverted = false; From fa9603f1215ffcd4f295464e8e0dbec6ea56c7da Mon Sep 17 00:00:00 2001 From: Alan Johnson Date: Mon, 23 Aug 2010 22:02:30 -0400 Subject: [PATCH 044/111] Got test case for inverted sections written up. --- test/handlebars.js | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/test/handlebars.js b/test/handlebars.js index 83d374cf..d514041f 100644 --- a/test/handlebars.js +++ b/test/handlebars.js @@ -2,6 +2,7 @@ module("basic context"); var shouldCompileTo = function(string, hash, result, message) { var template = Handlebars.compile(string); + console.log(template); var params = toString.call(hash) === "[object Array]" ? hash : [hash, undefined]; equal(template.apply(this, params), result, message); } @@ -193,6 +194,31 @@ test("nested block helpers", function() { equal(result, "

      Yehuda

      Hello
      "); }); +test("block inverted sections", function() { + var string = "{{#list people}}{{name}}{{^}}Nobody's here{{/list}}" + var list = function(fn) { + if (this.length > 0) { + var out = "
        "; + for(var i = 0,j=this.length; i < j; i++) { + out += "
      • "; + out += fn(this[i]); + out += "
      • "; + } + out += "
      "; + return out; + } + }; + + list.not = function(fn) { + return "

      " + fn(this) + "

      "; + }; + var hash = {list: list, people: [{name: "Alan"}, {name: "Yehuda"}]}; + + // the meaning here may be kind of hard to catch, but list.not is always called, + // so we should see the output of both + shouldCompileTo(string, hash, "
      • Alan
      • Yehuda

      Nobody's here

      ", "Not is called when block inverted section is encountered."); +}); + module("fallback hash"); test("providing a fallback hash", function() { From 222e810190319fae039e0e582fe73a6ec13ecd04 Mon Sep 17 00:00:00 2001 From: Alan Johnson Date: Fri, 3 Sep 2010 08:41:32 -0500 Subject: [PATCH 045/111] Got inverted blocks working. --- lib/handlebars.js | 36 ++++++++++++++++++++++++++++-------- 1 file changed, 28 insertions(+), 8 deletions(-) diff --git a/lib/handlebars.js b/lib/handlebars.js index 96069151..c91a26b0 100644 --- a/lib/handlebars.js +++ b/lib/handlebars.js @@ -1,7 +1,9 @@ Handlebars = { compile: function(string) { var compiler = new Handlebars.Compiler(string); - var result = compiler.compile(); + compiler.compile(); + var result = compiler.fn; + console.log(result); return new Function("context", "fallback", "fallback = fallback || {}; var stack = [];" + result); }, @@ -145,6 +147,8 @@ Handlebars.Compiler = function(string) { this.escaped = true; this.partial = false; this.inverted = false; + this.endCondition = null; + this.continueInverted = false; }; Handlebars.Exception = function(message) { @@ -202,11 +206,18 @@ Handlebars.Compiler.prototype = { this.text = this.text + chr; } - if(endCondition && endCondition(this)) { break }; + if (endCondition && this.peek(5) == "{{^}}") { + this.continueInverted = true; + this.getChar(5); + break; + } + else if(endCondition && endCondition(this)) { break }; } this.addText(); - return this.fn + "return out;"; + this.fn += "return out;"; + + return; }, addText: function() { @@ -226,8 +237,8 @@ Handlebars.Compiler.prototype = { }, addInvertedSection: function(mustache) { - var result = this.compileToEndOfBlock(mustache); - + var compiler = this.compileToEndOfBlock(mustache); + var result = compiler.fn; // each function made internally needs a unique IDs. These are locals, so they // don't need to be globally unique, just per compiler @@ -263,7 +274,7 @@ Handlebars.Compiler.prototype = { var compiler = new Handlebars.Compiler(this.string.slice(this.pointer + 1, -1)); // sub-compile with a custom EOF instruction - var result = compiler.compile(function(compiler) { + compiler.compile(function(compiler) { if(compiler.peek(mustache.length + 5) === "{{/" + mustache + "}}") { compiler.getChar(mustache.length + 5); return true; @@ -273,13 +284,14 @@ Handlebars.Compiler.prototype = { // move the pointer forward the amount of characters handled by the sub-compiler this.pointer += compiler.pointer + 1; - return result; + return compiler; }, addBlock: function(mustache, param, parts) { // set up the stack before the new compiler starts this.fn += "stack.push(context);"; - var result = this.compileToEndOfBlock(mustache); + var compiler = this.compileToEndOfBlock(mustache); + var result = compiler.fn; // each function made internally needs a unique IDs. These are locals, so they // don't need to be globally unique, just per compiler @@ -290,6 +302,14 @@ Handlebars.Compiler.prototype = { this.fn += "if(Handlebars.isFunction(lookup)) out = out + lookup.call(proxy, " + fnId + "); "; this.fn += "else if(typeof lookup !== 'undefined') out = out + Handlebars.helperMissing.call(proxy, lookup, " + fnId + "); "; + if (compiler.continueInverted) { + var invertedCompiler = this.compileToEndOfBlock(mustache); + this.fn += "if (Handlebars.isFunction(lookup.not)) {"; + this.fn += " var " + fnId + "Not = function(context) { " + invertedCompiler.fn + " };"; + this.fn += " out = out + lookup.not.call(proxy, " + fnId + "Not);"; + this.fn += "}"; + } + this.fn += "stack.pop();"; this.openBlock = false; }, From 88e975d2b23163ab0c9e06aa70015aa93ed82dfa Mon Sep 17 00:00:00 2001 From: Alan Johnson Date: Fri, 3 Sep 2010 23:11:29 -0500 Subject: [PATCH 046/111] Got performance test stuff started. --- lib/handlebars.js | 20 +-- test/mustache-0.3.0.js | 324 +++++++++++++++++++++++++++++++++++++++++ test/perf.html | 19 +++ test/perf.js | 46 ++++++ 4 files changed, 399 insertions(+), 10 deletions(-) create mode 100755 test/mustache-0.3.0.js create mode 100644 test/perf.html create mode 100644 test/perf.js diff --git a/lib/handlebars.js b/lib/handlebars.js index c91a26b0..ea9d6a06 100644 --- a/lib/handlebars.js +++ b/lib/handlebars.js @@ -2,9 +2,7 @@ Handlebars = { compile: function(string) { var compiler = new Handlebars.Compiler(string); compiler.compile(); - var result = compiler.fn; - console.log(result); - return new Function("context", "fallback", "fallback = fallback || {}; var stack = [];" + result); + return new Function("context", "fallback", "fallback = fallback || {}; var stack = [];" + compiler.fn); }, isFunction: function(fn) { @@ -175,7 +173,9 @@ Handlebars.helperMissing = function(object, fn) { ret = ret + fn(object[i]); } return ret; - } + } else { + return fn(object); + } }; Handlebars.Compiler.prototype = { @@ -243,11 +243,10 @@ Handlebars.Compiler.prototype = { // each function made internally needs a unique IDs. These are locals, so they // don't need to be globally unique, just per compiler var fnId = "fn" + this.pointer.toString(); - this.fn += "var proxy = Handlebars.buildContext(context, stack);"; this.fn += "var " + fnId + " = function(context) {" + result + "}; "; this.fn += "lookup = " + this.lookupFor(mustache) + "; "; - this.fn += "if(Handlebars.isFunction(lookup) && Handlebars.isEmpty(lookup())) out = out + " + fnId + "(proxy);"; - this.fn += "else if (Handlebars.isEmpty(lookup)) out = out + " + fnId + "(proxy);"; + this.fn += "if(Handlebars.isFunction(lookup) && Handlebars.isEmpty(lookup())) out = out + " + fnId + "(context);"; + this.fn += "else if (Handlebars.isEmpty(lookup)) out = out + " + fnId + "(context);"; this.openBlock = false; this.inverted = false; @@ -300,7 +299,7 @@ Handlebars.Compiler.prototype = { this.fn += "var " + fnId + " = function(context) {" + result + "}; "; this.fn += "lookup = " + this.lookupFor(mustache) + "; "; this.fn += "if(Handlebars.isFunction(lookup)) out = out + lookup.call(proxy, " + fnId + "); "; - this.fn += "else if(typeof lookup !== 'undefined') out = out + Handlebars.helperMissing.call(proxy, lookup, " + fnId + "); "; + this.fn += "else if(typeof lookup !== 'undefined') { out = out + Handlebars.helperMissing.call(proxy, lookup, " + fnId + "); }"; if (compiler.continueInverted) { var invertedCompiler = this.compileToEndOfBlock(mustache); @@ -317,8 +316,9 @@ Handlebars.Compiler.prototype = { addPartial: function(mustache, param) { // either used a cached copy of the partial or compile a new one this.fn += "if (typeof fallback['partials'] === 'undefined' || typeof fallback['partials']['" + mustache + "'] === 'undefined') throw new Handlebars.Exception('Attempted to render undefined partial: " + mustache + "');"; - this.fn += "if (!Handlebars.isFunction(fallback['partials']['" + mustache + "'])) fallback['partials']['" + mustache + "'] = Handlebars.compile(fallback['partials']['" + mustache + "']);"; - this.fn += "out = out + fallback['partials']['" + mustache + "'](" + param + ", fallback);"; + this.fn += "if (typeof fallback['compiledPartials'] === 'undefined') fallback['compiledPartials'] = [];"; + this.fn += "if (!Handlebars.isFunction(fallback['compiledPartials']['" + mustache + "'])) fallback['compiledPartials']['" + mustache + "'] = Handlebars.compile(fallback['partials']['" + mustache + "']);"; + this.fn += "out = out + fallback['compiledPartials']['" + mustache + "'](" + param + ", fallback);"; }, parseMustache: function() { diff --git a/test/mustache-0.3.0.js b/test/mustache-0.3.0.js new file mode 100755 index 00000000..0996227a --- /dev/null +++ b/test/mustache-0.3.0.js @@ -0,0 +1,324 @@ +/* + mustache.js — Logic-less templates in JavaScript + + See http://mustache.github.com/ for more info. +*/ + +var Mustache = function() { + var Renderer = function() {}; + + Renderer.prototype = { + otag: "{{", + ctag: "}}", + pragmas: {}, + buffer: [], + pragmas_implemented: { + "IMPLICIT-ITERATOR": true + }, + context: {}, + + render: function(template, context, partials, in_recursion) { + // reset buffer & set context + if(!in_recursion) { + this.context = context; + this.buffer = []; // TODO: make this non-lazy + } + + // fail fast + if(!this.includes("", template)) { + if(in_recursion) { + return template; + } else { + this.send(template); + return; + } + } + + template = this.render_pragmas(template); + var html = this.render_section(template, context, partials); + if(in_recursion) { + return this.render_tags(html, context, partials, in_recursion); + } + + this.render_tags(html, context, partials, in_recursion); + }, + + /* + Sends parsed lines + */ + send: function(line) { + if(line != "") { + this.buffer.push(line); + } + }, + + /* + Looks for %PRAGMAS + */ + render_pragmas: function(template) { + // no pragmas + if(!this.includes("%", template)) { + return template; + } + + var that = this; + var regex = new RegExp(this.otag + "%([\\w-]+) ?([\\w]+=[\\w]+)?" + + this.ctag); + return template.replace(regex, function(match, pragma, options) { + if(!that.pragmas_implemented[pragma]) { + throw({message: + "This implementation of mustache doesn't understand the '" + + pragma + "' pragma"}); + } + that.pragmas[pragma] = {}; + if(options) { + var opts = options.split("="); + that.pragmas[pragma][opts[0]] = opts[1]; + } + return ""; + // ignore unknown pragmas silently + }); + }, + + /* + Tries to find a partial in the curent scope and render it + */ + render_partial: function(name, context, partials) { + name = this.trim(name); + if(!partials || partials[name] === undefined) { + throw({message: "unknown_partial '" + name + "'"}); + } + if(typeof(context[name]) != "object") { + return this.render(partials[name], context, partials, true); + } + return this.render(partials[name], context[name], partials, true); + }, + + /* + Renders inverted (^) and normal (#) sections + */ + render_section: function(template, context, partials) { + if(!this.includes("#", template) && !this.includes("^", template)) { + return template; + } + + var that = this; + // CSW - Added "+?" so it finds the tighest bound, not the widest + var regex = new RegExp(this.otag + "(\\^|\\#)\\s*(.+)\\s*" + this.ctag + + "\n*([\\s\\S]+?)" + this.otag + "\\/\\s*\\2\\s*" + this.ctag + + "\\s*", "mg"); + + // for each {{#foo}}{{/foo}} section do... + return template.replace(regex, function(match, type, name, content) { + var value = that.find(name, context); + if(type == "^") { // inverted section + if(!value || that.is_array(value) && value.length === 0) { + // false or empty list, render it + return that.render(content, context, partials, true); + } else { + return ""; + } + } else if(type == "#") { // normal section + if(that.is_array(value)) { // Enumerable, Let's loop! + return that.map(value, function(row) { + return that.render(content, that.create_context(row), + partials, true); + }).join(""); + } else if(that.is_object(value)) { // Object, Use it as subcontext! + return that.render(content, that.create_context(value), + partials, true); + } else if(typeof value === "function") { + // higher order section + return value.call(context, content, function(text) { + return that.render(text, context, partials, true); + }); + } else if(value) { // boolean section + return that.render(content, context, partials, true); + } else { + return ""; + } + } + }); + }, + + /* + Replace {{foo}} and friends with values from our view + */ + render_tags: function(template, context, partials, in_recursion) { + // tit for tat + var that = this; + + var new_regex = function() { + return new RegExp(that.otag + "(=|!|>|\\{|%)?([^\\/#\\^]+?)\\1?" + + that.ctag + "+", "g"); + }; + + var regex = new_regex(); + var tag_replace_callback = function(match, operator, name) { + switch(operator) { + case "!": // ignore comments + return ""; + case "=": // set new delimiters, rebuild the replace regexp + that.set_delimiters(name); + regex = new_regex(); + return ""; + case ">": // render partial + return that.render_partial(name, context, partials); + case "{": // the triple mustache is unescaped + return that.find(name, context); + default: // escape the value + return that.escape(that.find(name, context)); + } + }; + var lines = template.split("\n"); + for(var i = 0; i < lines.length; i++) { + lines[i] = lines[i].replace(regex, tag_replace_callback, this); + if(!in_recursion) { + this.send(lines[i]); + } + } + + if(in_recursion) { + return lines.join("\n"); + } + }, + + set_delimiters: function(delimiters) { + var dels = delimiters.split(" "); + this.otag = this.escape_regex(dels[0]); + this.ctag = this.escape_regex(dels[1]); + }, + + escape_regex: function(text) { + // thank you Simon Willison + if(!arguments.callee.sRE) { + var specials = [ + '/', '.', '*', '+', '?', '|', + '(', ')', '[', ']', '{', '}', '\\' + ]; + arguments.callee.sRE = new RegExp( + '(\\' + specials.join('|\\') + ')', 'g' + ); + } + return text.replace(arguments.callee.sRE, '\\$1'); + }, + + /* + find `name` in current `context`. That is find me a value + from the view object + */ + find: function(name, context) { + name = this.trim(name); + + // Checks whether a value is thruthy or false or 0 + function is_kinda_truthy(bool) { + return bool === false || bool === 0 || bool; + } + + var value; + if(is_kinda_truthy(context[name])) { + value = context[name]; + } else if(is_kinda_truthy(this.context[name])) { + value = this.context[name]; + } + + if(typeof value === "function") { + return value.apply(context); + } + if(value !== undefined) { + return value; + } + // silently ignore unkown variables + return ""; + }, + + // Utility methods + + /* includes tag */ + includes: function(needle, haystack) { + return haystack.indexOf(this.otag + needle) != -1; + }, + + /* + Does away with nasty characters + */ + escape: function(s) { + s = String(s === null ? "" : s); + return s.replace(/&(?!\w+;)|["<>\\]/g, function(s) { + switch(s) { + case "&": return "&"; + case "\\": return "\\\\"; + case '"': return '\"'; + case "<": return "<"; + case ">": return ">"; + default: return s; + } + }); + }, + + // by @langalex, support for arrays of strings + create_context: function(_context) { + if(this.is_object(_context)) { + return _context; + } else { + var iterator = "."; + if(this.pragmas["IMPLICIT-ITERATOR"]) { + iterator = this.pragmas["IMPLICIT-ITERATOR"].iterator; + } + var ctx = {}; + ctx[iterator] = _context; + return ctx; + } + }, + + is_object: function(a) { + return a && typeof a == "object"; + }, + + is_array: function(a) { + return Object.prototype.toString.call(a) === '[object Array]'; + }, + + /* + Gets rid of leading and trailing whitespace + */ + trim: function(s) { + return s.replace(/^\s*|\s*$/g, ""); + }, + + /* + Why, why, why? Because IE. Cry, cry cry. + */ + map: function(array, fn) { + if (typeof array.map == "function") { + return array.map(fn); + } else { + var r = []; + var l = array.length; + for(var i = 0; i < l; i++) { + r.push(fn(array[i])); + } + return r; + } + } + }; + + return({ + name: "mustache.js", + version: "0.3.0", + + /* + Turns a template and view into HTML + */ + to_html: function(template, view, partials, send_fun) { + var renderer = new Renderer(); + if(send_fun) { + renderer.send = send_fun; + } + renderer.render(template, view, partials); + if(!send_fun) { + return renderer.buffer.join("\n"); + } + } + }); +}(); diff --git a/test/perf.html b/test/perf.html new file mode 100644 index 00000000..e74fd19c --- /dev/null +++ b/test/perf.html @@ -0,0 +1,19 @@ + + + + + + + + + +

      Performance Testing

      +

      +

      +
        + + + + diff --git a/test/perf.js b/test/perf.js new file mode 100644 index 00000000..963c11f7 --- /dev/null +++ b/test/perf.js @@ -0,0 +1,46 @@ +function perfTest(test) { + var testStart = new Date().getTime(); + + // run the test 1000 times so we can get a happy average + for (var i = 0; i < 1000; i++) { + test(); + } + + var testEnd = new Date().getTime(); + return (testEnd-testStart)/1000; +} + +function perfCompare(test1, test2) { + var result1 = perfTest(test1); + var result2 = perfTest(test2); + + console.log("Result 1: " + result1 + ", Result 2: " + result2 + ", Difference: " + + (result1 - result2)); +} + + +// set up the templates +var tmpl = "This is the story of guys who work on a project\n" + + "called {{project}}. Their names were {{#people}}{{firstName}} and {{/people}}\n" + + "they both enjoyed working on {{project}}.\n\n" + + "{{#people}}\n" + + "{{>personPet}}\n" + + "{{/people}}"; +var partials = { + personPet: "{{firstName}} {{lastName}} {{#pet}} owned a {{species}}. Its name was {{name}}.{{/pet}}{{^pet}}didn't own a pet.{{/pet}}" +}; +var data = { + project: "Handlebars", + people: [ + { firstName: "Yehuda", lastName: "Katz" }, + { firstName: "Alan", lastName: "Johnson", pet: { species: "cat", name: "Luke" } } + ] +} + +var test1 = function() { + Handlebars.compile(tmpl)(data, {partials: partials}); +} +var test2 = function() { + Mustache.to_html(tmpl, data, partials); +} +perfCompare(test1, test2); From 57455e23fd11accb24824d4328afd0c157208361 Mon Sep 17 00:00:00 2001 From: Alan Johnson Date: Sun, 5 Sep 2010 03:44:04 -0400 Subject: [PATCH 047/111] Added basic performance test. --- lib/handlebars.js | 2 +- test/handlebars.js | 1 - test/perf.html | 2 +- test/perf.js | 67 +++++++++++++++++++++++++++++++++++++--------- 4 files changed, 57 insertions(+), 15 deletions(-) diff --git a/lib/handlebars.js b/lib/handlebars.js index ea9d6a06..7768570b 100644 --- a/lib/handlebars.js +++ b/lib/handlebars.js @@ -131,7 +131,7 @@ Handlebars = { } else { return value; } - }, + } } Handlebars.Compiler = function(string) { diff --git a/test/handlebars.js b/test/handlebars.js index d514041f..eeaa692e 100644 --- a/test/handlebars.js +++ b/test/handlebars.js @@ -2,7 +2,6 @@ module("basic context"); var shouldCompileTo = function(string, hash, result, message) { var template = Handlebars.compile(string); - console.log(template); var params = toString.call(hash) === "[object Array]" ? hash : [hash, undefined]; equal(template.apply(this, params), result, message); } diff --git a/test/perf.html b/test/perf.html index e74fd19c..8c0ece48 100644 --- a/test/perf.html +++ b/test/perf.html @@ -12,7 +12,7 @@

          -