├── README.md
├── esprima.js
├── falafel.js
├── index.html
├── jquery-tipsy.js
├── jquery.js
├── require.js
├── slowmo
├── attr-mangler.js
├── attr.js
├── loop-inserter.js
├── scope-mangler.js
└── scope.js
├── test
├── all-tests.js
├── define-tests.js
├── index.html
├── qunit.css
├── qunit.js
├── test-attr-mangler.js
├── test-attr.js
├── test-loop-inserter.js
├── test-scope-mangler.js
└── test-scope.js
└── tipsy.css
/README.md:
--------------------------------------------------------------------------------
1 | SlomoJS is an attempt to make learning JavaScript and computational thinking easier by making the execution of JS code more transparent.
2 |
3 | Traditionally, this is accomplished by peppering code with `console.log` statements and/or using a debugger. However, the former approach requires lots of extra code, and the latter approach presents novice users with a complex modal user interface.
4 |
5 | With libraries like [esprima][] and [falafel][], however, we can monitor the execution of JS to do things in-browser that only debuggers are traditionally capable of. This allows us to potentially create innovative new solutions provide significant insight to the execution of running code without the hassles associated with traditional approaches--and without the need for users to install custom software.
6 |
7 | ## Design Notes
8 |
9 | I originally wanted to use [Popcorn][] to generate a movie of the user's code being executed, but given [Edward Tufte][]'s belief that it's usually better to have information adjacent in space rather than stacked in time--which is yet another problem with traditional debuggers--I decided to make the visualization purely spatial, rather than temporal.
10 |
11 | ## Implementation Notes
12 |
13 | Infinite loops are prevented by mangling the user's code to check running time at the beginning of each iteration of a loop, and throwing an exception if it's taking too long.
14 |
15 | Lots of things can still be made more transparent. Getting/setting the attributes of objects, for instance.
16 |
17 | The mangling being done by the code disables some JS semantics. All variables must be formally declared in a `var` statement, for instance, and function declarations are automatically converted to `var` statements with function expression initializers. [Hoisting][] is also broken.
18 |
19 | [esprima]: http://esprima.org/
20 | [falafel]: https://github.com/substack/node-falafel
21 | [Popcorn]: http://popcornjs.org/
22 | [Edward Tufte]: https://www.edwardtufte.com/tufte/
23 | [Hoisting]: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Statements/var#var_hoisting
24 |
--------------------------------------------------------------------------------
/falafel.js:
--------------------------------------------------------------------------------
1 | define(function(require, exports, module) {
2 | var parse = require('esprima').parse;
3 |
4 | module.exports = function (src, opts, fn) {
5 | if (typeof opts === 'function') {
6 | fn = opts;
7 | opts = {};
8 | }
9 | if (typeof src === 'object') {
10 | opts = src;
11 | src = opts.source;
12 | delete opts.source;
13 | }
14 | src = src || opts.source;
15 | opts.range = true;
16 | if (typeof src !== 'string') src = String(src);
17 |
18 | var ast = parse(src, opts);
19 |
20 | var result = {
21 | chunks : src.split(''),
22 | toString : function () { return result.chunks.join('') },
23 | inspect : function () { return result.toString() }
24 | };
25 | var index = 0;
26 |
27 | (function walk (node, parent) {
28 | insertHelpers(node, parent, result.chunks);
29 |
30 | Object.keys(node).forEach(function (key) {
31 | if (key === 'parent') return;
32 |
33 | var child = node[key];
34 | if (Array.isArray(child)) {
35 | child.forEach(function (c) {
36 | if (c && typeof c.type === 'string') {
37 | walk(c, node);
38 | }
39 | });
40 | }
41 | else if (child && typeof child.type === 'string') {
42 | insertHelpers(child, node, result.chunks);
43 | walk(child, node);
44 | }
45 | });
46 | fn(node);
47 | })(ast, undefined);
48 |
49 | return result;
50 | };
51 |
52 | function insertHelpers (node, parent, chunks) {
53 | if (!node.range) return;
54 |
55 | node.parent = parent;
56 |
57 | node.source = function () {
58 | return chunks.slice(
59 | node.range[0], node.range[1]
60 | ).join('');
61 | };
62 |
63 | if (node.update && typeof node.update === 'object') {
64 | var prev = node.update;
65 | Object.keys(prev).forEach(function (key) {
66 | update[key] = prev[key];
67 | });
68 | node.update = update;
69 | }
70 | else {
71 | node.update = update;
72 | }
73 |
74 | function update (s) {
75 | chunks[node.range[0]] = s;
76 | for (var i = node.range[0] + 1; i < node.range[1]; i++) {
77 | chunks[i] = '';
78 | }
79 | };
80 | }
81 | });
--------------------------------------------------------------------------------
/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
137 |
SlowmoJS
138 |
139 | SlowmoJS
140 | Javascript in Slow Motion.
141 |
144 | Link to this code
145 |
146 |
156 |
157 |
479 |
--------------------------------------------------------------------------------
/jquery-tipsy.js:
--------------------------------------------------------------------------------
1 | // tipsy, facebook style tooltips for jquery
2 | // version 1.0.0a
3 | // (c) 2008-2010 jason frame [jason@onehackoranother.com]
4 | // released under the MIT license
5 |
6 | (function($) {
7 |
8 | function maybeCall(thing, ctx) {
9 | return (typeof thing == 'function') ? (thing.call(ctx)) : thing;
10 | };
11 |
12 | function isElementInDOM(ele) {
13 | while (ele = ele.parentNode) {
14 | if (ele == document) return true;
15 | }
16 | return false;
17 | };
18 |
19 | function Tipsy(element, options) {
20 | this.$element = $(element);
21 | this.options = options;
22 | this.enabled = true;
23 | this.fixTitle();
24 | };
25 |
26 | Tipsy.prototype = {
27 | show: function() {
28 | var title = this.getTitle();
29 | if (title && this.enabled) {
30 | var $tip = this.tip();
31 |
32 | $tip.find('.tipsy-inner')[this.options.html ? 'html' : 'text'](title);
33 | $tip[0].className = 'tipsy'; // reset classname in case of dynamic gravity
34 | $tip.remove().css({top: 0, left: 0, visibility: 'hidden', display: 'block'}).prependTo(document.body);
35 |
36 | var pos = $.extend({}, this.$element.offset(), {
37 | width: this.$element[0].offsetWidth,
38 | height: this.$element[0].offsetHeight
39 | });
40 |
41 | var actualWidth = $tip[0].offsetWidth,
42 | actualHeight = $tip[0].offsetHeight,
43 | gravity = maybeCall(this.options.gravity, this.$element[0]);
44 |
45 | var tp;
46 | switch (gravity.charAt(0)) {
47 | case 'n':
48 | tp = {top: pos.top + pos.height + this.options.offset, left: pos.left + pos.width / 2 - actualWidth / 2};
49 | break;
50 | case 's':
51 | tp = {top: pos.top - actualHeight - this.options.offset, left: pos.left + pos.width / 2 - actualWidth / 2};
52 | break;
53 | case 'e':
54 | tp = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth - this.options.offset};
55 | break;
56 | case 'w':
57 | tp = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width + this.options.offset};
58 | break;
59 | }
60 |
61 | if (gravity.length == 2) {
62 | if (gravity.charAt(1) == 'w') {
63 | tp.left = pos.left + pos.width / 2 - 15;
64 | } else {
65 | tp.left = pos.left + pos.width / 2 - actualWidth + 15;
66 | }
67 | }
68 |
69 | $tip.css(tp).addClass('tipsy-' + gravity);
70 | $tip.find('.tipsy-arrow')[0].className = 'tipsy-arrow tipsy-arrow-' + gravity.charAt(0);
71 | if (this.options.className) {
72 | $tip.addClass(maybeCall(this.options.className, this.$element[0]));
73 | }
74 |
75 | if (this.options.fade) {
76 | $tip.stop().css({opacity: 0, display: 'block', visibility: 'visible'}).animate({opacity: this.options.opacity});
77 | } else {
78 | $tip.css({visibility: 'visible', opacity: this.options.opacity});
79 | }
80 | }
81 | },
82 |
83 | hide: function() {
84 | if (this.options.fade) {
85 | this.tip().stop().fadeOut(function() { $(this).remove(); });
86 | } else {
87 | this.tip().remove();
88 | }
89 | },
90 |
91 | fixTitle: function() {
92 | var $e = this.$element;
93 | if ($e.attr('title') || typeof($e.attr('original-title')) != 'string') {
94 | $e.attr('original-title', $e.attr('title') || '').removeAttr('title');
95 | }
96 | },
97 |
98 | getTitle: function() {
99 | var title, $e = this.$element, o = this.options;
100 | this.fixTitle();
101 | var title, o = this.options;
102 | if (typeof o.title == 'string') {
103 | title = $e.attr(o.title == 'title' ? 'original-title' : o.title);
104 | } else if (typeof o.title == 'function') {
105 | title = o.title.call($e[0]);
106 | }
107 | title = ('' + title).replace(/(^\s*|\s*$)/, "");
108 | return title || o.fallback;
109 | },
110 |
111 | tip: function() {
112 | if (!this.$tip) {
113 | this.$tip = $('
').html('
');
114 | this.$tip.data('tipsy-pointee', this.$element[0]);
115 | }
116 | return this.$tip;
117 | },
118 |
119 | validate: function() {
120 | if (!this.$element[0].parentNode) {
121 | this.hide();
122 | this.$element = null;
123 | this.options = null;
124 | }
125 | },
126 |
127 | enable: function() { this.enabled = true; },
128 | disable: function() { this.enabled = false; },
129 | toggleEnabled: function() { this.enabled = !this.enabled; }
130 | };
131 |
132 | $.fn.tipsy = function(options) {
133 |
134 | if (options === true) {
135 | return this.data('tipsy');
136 | } else if (typeof options == 'string') {
137 | var tipsy = this.data('tipsy');
138 | if (tipsy) tipsy[options]();
139 | return this;
140 | }
141 |
142 | options = $.extend({}, $.fn.tipsy.defaults, options);
143 |
144 | function get(ele) {
145 | var tipsy = $.data(ele, 'tipsy');
146 | if (!tipsy) {
147 | tipsy = new Tipsy(ele, $.fn.tipsy.elementOptions(ele, options));
148 | $.data(ele, 'tipsy', tipsy);
149 | }
150 | return tipsy;
151 | }
152 |
153 | function enter() {
154 | var tipsy = get(this);
155 | tipsy.hoverState = 'in';
156 | if (options.delayIn == 0) {
157 | tipsy.show();
158 | } else {
159 | tipsy.fixTitle();
160 | setTimeout(function() { if (tipsy.hoverState == 'in') tipsy.show(); }, options.delayIn);
161 | }
162 | };
163 |
164 | function leave() {
165 | var tipsy = get(this);
166 | tipsy.hoverState = 'out';
167 | if (options.delayOut == 0) {
168 | tipsy.hide();
169 | } else {
170 | setTimeout(function() { if (tipsy.hoverState == 'out') tipsy.hide(); }, options.delayOut);
171 | }
172 | };
173 |
174 | if (!options.live) this.each(function() { get(this); });
175 |
176 | if (options.trigger != 'manual') {
177 | var binder = options.live ? 'live' : 'bind',
178 | eventIn = options.trigger == 'hover' ? 'mouseenter' : 'focus',
179 | eventOut = options.trigger == 'hover' ? 'mouseleave' : 'blur';
180 | this[binder](eventIn, enter)[binder](eventOut, leave);
181 | }
182 |
183 | return this;
184 |
185 | };
186 |
187 | $.fn.tipsy.defaults = {
188 | className: null,
189 | delayIn: 0,
190 | delayOut: 0,
191 | fade: false,
192 | fallback: '',
193 | gravity: 'n',
194 | html: false,
195 | live: false,
196 | offset: 0,
197 | opacity: 0.8,
198 | title: 'title',
199 | trigger: 'hover'
200 | };
201 |
202 | $.fn.tipsy.revalidate = function() {
203 | $('.tipsy').each(function() {
204 | var pointee = $.data(this, 'tipsy-pointee');
205 | if (!pointee || !isElementInDOM(pointee)) {
206 | $(this).remove();
207 | }
208 | });
209 | };
210 |
211 | // Overwrite this method to provide options on a per-element basis.
212 | // For example, you could store the gravity in a 'tipsy-gravity' attribute:
213 | // return $.extend({}, options, {gravity: $(ele).attr('tipsy-gravity') || 'n' });
214 | // (remember - do not modify 'options' in place!)
215 | $.fn.tipsy.elementOptions = function(ele, options) {
216 | return $.metadata ? $.extend({}, options, $(ele).metadata()) : options;
217 | };
218 |
219 | $.fn.tipsy.autoNS = function() {
220 | return $(this).offset().top > ($(document).scrollTop() + $(window).height() / 2) ? 's' : 'n';
221 | };
222 |
223 | $.fn.tipsy.autoWE = function() {
224 | return $(this).offset().left > ($(document).scrollLeft() + $(window).width() / 2) ? 'e' : 'w';
225 | };
226 |
227 | /**
228 | * yields a closure of the supplied parameters, producing a function that takes
229 | * no arguments and is suitable for use as an autogravity function like so:
230 | *
231 | * @param margin (int) - distance from the viewable region edge that an
232 | * element should be before setting its tooltip's gravity to be away
233 | * from that edge.
234 | * @param prefer (string, e.g. 'n', 'sw', 'w') - the direction to prefer
235 | * if there are no viewable region edges effecting the tooltip's
236 | * gravity. It will try to vary from this minimally, for example,
237 | * if 'sw' is preferred and an element is near the right viewable
238 | * region edge, but not the top edge, it will set the gravity for
239 | * that element's tooltip to be 'se', preserving the southern
240 | * component.
241 | */
242 | $.fn.tipsy.autoBounds = function(margin, prefer) {
243 | return function() {
244 | var dir = {ns: prefer[0], ew: (prefer.length > 1 ? prefer[1] : false)},
245 | boundTop = $(document).scrollTop() + margin,
246 | boundLeft = $(document).scrollLeft() + margin,
247 | $this = $(this);
248 |
249 | if ($this.offset().top < boundTop) dir.ns = 'n';
250 | if ($this.offset().left < boundLeft) dir.ew = 'w';
251 | if ($(window).width() + $(document).scrollLeft() - $this.offset().left < margin) dir.ew = 'e';
252 | if ($(window).height() + $(document).scrollTop() - $this.offset().top < margin) dir.ns = 's';
253 |
254 | return dir.ns + (dir.ew ? dir.ew : '');
255 | }
256 | };
257 |
258 | })(jQuery);
259 |
--------------------------------------------------------------------------------
/require.js:
--------------------------------------------------------------------------------
1 | /*
2 | RequireJS 2.1.0 Copyright (c) 2010-2012, The Dojo Foundation All Rights Reserved.
3 | Available via the MIT or new BSD license.
4 | see: http://github.com/jrburke/requirejs for details
5 | */
6 | var requirejs,require,define;
7 | (function(U){function D(b){return M.call(b)==="[object Function]"}function E(b){return M.call(b)==="[object Array]"}function s(b,c){if(b){var d;for(d=0;d-1;d-=1)if(b[d]&&c(b[d],d,b))break}}function F(b,c){for(var d in b)if(b.hasOwnProperty(d)&&c(b[d],d))break}function J(b,c,d,h){c&&F(c,function(c,j){if(d||!G.call(b,j))h&&typeof c!=="string"?(b[j]||(b[j]={}),J(b[j],c,d,h)):b[j]=c});return b}function q(b,c){return function(){return c.apply(b,
8 | arguments)}}function V(b){if(!b)return b;var c=U;s(b.split("."),function(b){c=c[b]});return c}function H(b,c,d,h){c=Error(c+"\nhttp://requirejs.org/docs/errors.html#"+b);c.requireType=b;c.requireModules=h;if(d)c.originalError=d;return c}function aa(){if(I&&I.readyState==="interactive")return I;N(document.getElementsByTagName("script"),function(b){if(b.readyState==="interactive")return I=b});return I}var h,r,u,y,p,A,I,B,W,X,ba=/(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg,ca=/[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g,
9 | Y=/\.js$/,da=/^\.\//;r=Object.prototype;var M=r.toString,G=r.hasOwnProperty,ea=Array.prototype.splice,v=!!(typeof window!=="undefined"&&navigator&&document),Z=!v&&typeof importScripts!=="undefined",fa=v&&navigator.platform==="PLAYSTATION 3"?/^complete$/:/^(complete|loaded)$/,Q=typeof opera!=="undefined"&&opera.toString()==="[object Opera]",w={},n={},O=[],K=!1;if(typeof define==="undefined"){if(typeof requirejs!=="undefined"){if(D(requirejs))return;n=requirejs;requirejs=void 0}typeof require!=="undefined"&&
10 | !D(require)&&(n=require,require=void 0);h=requirejs=function(b,c,d,t){var g,j="_";!E(b)&&typeof b!=="string"&&(g=b,E(c)?(b=c,c=d,d=t):b=[]);if(g&&g.context)j=g.context;(t=w[j])||(t=w[j]=h.s.newContext(j));g&&t.configure(g);return t.require(b,c,d)};h.config=function(b){return h(b)};h.nextTick=typeof setTimeout!=="undefined"?function(b){setTimeout(b,4)}:function(b){b()};require||(require=h);h.version="2.1.0";h.jsExtRegExp=/^\/|:|\?|\.js$/;h.isBrowser=v;r=h.s={contexts:w,newContext:function(b){function c(a,
11 | f,x){var e,b,k,c,d,i,g,h=f&&f.split("/");e=h;var j=m.map,l=j&&j["*"];if(a&&a.charAt(0)===".")if(f){e=m.pkgs[f]?h=[f]:h.slice(0,h.length-1);f=a=e.concat(a.split("/"));for(e=0;f[e];e+=1)if(b=f[e],b===".")f.splice(e,1),e-=1;else if(b==="..")if(e===1&&(f[2]===".."||f[0]===".."))break;else e>0&&(f.splice(e-1,2),e-=2);e=m.pkgs[f=a[0]];a=a.join("/");e&&a===f+"/"+e.main&&(a=f)}else a.indexOf("./")===0&&(a=a.substring(2));if(x&&(h||l)&&j){f=a.split("/");for(e=f.length;e>0;e-=1){k=f.slice(0,e).join("/");if(h)for(b=
12 | h.length;b>0;b-=1)if(x=j[h.slice(0,b).join("/")])if(x=x[k]){c=x;d=e;break}if(c)break;!i&&l&&l[k]&&(i=l[k],g=e)}!c&&i&&(c=i,d=g);c&&(f.splice(0,d,c),a=f.join("/"))}return a}function d(a){v&&s(document.getElementsByTagName("script"),function(f){if(f.getAttribute("data-requiremodule")===a&&f.getAttribute("data-requirecontext")===i.contextName)return f.parentNode.removeChild(f),!0})}function t(a){var f=m.paths[a];if(f&&E(f)&&f.length>1)return d(a),f.shift(),i.require.undef(a),i.require([a]),!0}function g(a){var f,
13 | b=a?a.indexOf("!"):-1;b>-1&&(f=a.substring(0,b),a=a.substring(b+1,a.length));return[f,a]}function j(a,f,b,e){var $,k,d=null,h=f?f.name:null,j=a,m=!0,l="";a||(m=!1,a="_@r"+(M+=1));a=g(a);d=a[0];a=a[1];d&&(d=c(d,h,e),k=o[d]);a&&(d?l=k&&k.normalize?k.normalize(a,function(a){return c(a,h,e)}):c(a,h,e):(l=c(a,h,e),a=g(l),d=a[0],l=a[1],b=!0,$=i.nameToUrl(l)));b=d&&!k&&!b?"_unnormalized"+(N+=1):"";return{prefix:d,name:l,parentMap:f,unnormalized:!!b,url:$,originalName:j,isDefine:m,id:(d?d+"!"+l:l)+b}}function n(a){var f=
14 | a.id,b=l[f];b||(b=l[f]=new i.Module(a));return b}function p(a,f,b){var e=a.id,c=l[e];if(G.call(o,e)&&(!c||c.defineEmitComplete))f==="defined"&&b(o[e]);else n(a).on(f,b)}function z(a,f){var b=a.requireModules,e=!1;if(f)f(a);else if(s(b,function(f){if(f=l[f])f.error=a,f.events.error&&(e=!0,f.emit("error",a))}),!e)h.onError(a)}function r(){O.length&&(ea.apply(C,[C.length-1,0].concat(O)),O=[])}function u(a,f,b){var e=a.map.id;a.error?a.emit("error",a.error):(f[e]=!0,s(a.depMaps,function(e,k){var c=e.id,
15 | d=l[c];d&&!a.depMatched[k]&&!b[c]&&(f[c]?(a.defineDep(k,o[c]),a.check()):u(d,f,b))}),b[e]=!0)}function w(){var a,f,b,e,c=(b=m.waitSeconds*1E3)&&i.startTime+b<(new Date).getTime(),k=[],h=[],g=!1,j=!0;if(!B){B=!0;F(l,function(b){a=b.map;f=a.id;if(b.enabled&&(a.isDefine||h.push(b),!b.error))if(!b.inited&&c)t(f)?g=e=!0:(k.push(f),d(f));else if(!b.inited&&b.fetched&&a.isDefine&&(g=!0,!a.prefix))return j=!1});if(c&&k.length)return b=H("timeout","Load timeout for modules: "+k,null,k),b.contextName=i.contextName,
16 | z(b);j&&s(h,function(a){u(a,{},{})});if((!c||e)&&g)if((v||Z)&&!R)R=setTimeout(function(){R=0;w()},50);B=!1}}function y(a){n(j(a[0],null,!0)).init(a[1],a[2])}function A(a){var a=a.currentTarget||a.srcElement,b=i.onScriptLoad;a.detachEvent&&!Q?a.detachEvent("onreadystatechange",b):a.removeEventListener("load",b,!1);b=i.onScriptError;a.detachEvent&&!Q||a.removeEventListener("error",b,!1);return{node:a,id:a&&a.getAttribute("data-requiremodule")}}var B,S,i,L,R,m={waitSeconds:7,baseUrl:"./",paths:{},pkgs:{},
17 | shim:{}},l={},T={},C=[],o={},P={},M=1,N=1;L={require:function(a){return a.require?a.require:a.require=i.makeRequire(a.map)},exports:function(a){a.usingExports=!0;if(a.map.isDefine)return a.exports?a.exports:a.exports=o[a.map.id]={}},module:function(a){return a.module?a.module:a.module={id:a.map.id,uri:a.map.url,config:function(){return m.config&&m.config[a.map.id]||{}},exports:o[a.map.id]}}};S=function(a){this.events=T[a.id]||{};this.map=a;this.shim=m.shim[a.id];this.depExports=[];this.depMaps=[];
18 | this.depMatched=[];this.pluginMaps={};this.depCount=0};S.prototype={init:function(a,b,c,e){e=e||{};if(!this.inited){this.factory=b;if(c)this.on("error",c);else this.events.error&&(c=q(this,function(a){this.emit("error",a)}));this.depMaps=a&&a.slice(0);this.errback=c;this.inited=!0;this.ignore=e.ignore;e.enabled||this.enabled?this.enable():this.check()}},defineDep:function(a,b){this.depMatched[a]||(this.depMatched[a]=!0,this.depCount-=1,this.depExports[a]=b)},fetch:function(){if(!this.fetched){this.fetched=
19 | !0;i.startTime=(new Date).getTime();var a=this.map;if(this.shim)i.makeRequire(this.map,{enableBuildCallback:!0})(this.shim.deps||[],q(this,function(){return a.prefix?this.callPlugin():this.load()}));else return a.prefix?this.callPlugin():this.load()}},load:function(){var a=this.map.url;P[a]||(P[a]=!0,i.load(this.map.id,a))},check:function(){if(this.enabled&&!this.enabling){var a,b,c=this.map.id;b=this.depExports;var e=this.exports,d=this.factory;if(this.inited)if(this.error)this.emit("error",this.error);
20 | else{if(!this.defining){this.defining=!0;if(this.depCount<1&&!this.defined){if(D(d)){if(this.events.error)try{e=i.execCb(c,d,b,e)}catch(k){a=k}else e=i.execCb(c,d,b,e);if(this.map.isDefine)if((b=this.module)&&b.exports!==void 0&&b.exports!==this.exports)e=b.exports;else if(e===void 0&&this.usingExports)e=this.exports;if(a)return a.requireMap=this.map,a.requireModules=[this.map.id],a.requireType="define",z(this.error=a)}else e=d;this.exports=e;if(this.map.isDefine&&!this.ignore&&(o[c]=e,h.onResourceLoad))h.onResourceLoad(i,
21 | this.map,this.depMaps);delete l[c];this.defined=!0}this.defining=!1;if(this.defined&&!this.defineEmitted)this.defineEmitted=!0,this.emit("defined",this.exports),this.defineEmitComplete=!0}}else this.fetch()}},callPlugin:function(){var a=this.map,b=a.id,d=j(a.prefix);this.depMaps.push(d);p(d,"defined",q(this,function(e){var d,k;k=this.map.name;var x=this.map.parentMap?this.map.parentMap.name:null,g=i.makeRequire(a.parentMap,{enableBuildCallback:!0,skipMap:!0});if(this.map.unnormalized){if(e.normalize&&
22 | (k=e.normalize(k,function(a){return c(a,x,!0)})||""),e=j(a.prefix+"!"+k,this.map.parentMap),p(e,"defined",q(this,function(a){this.init([],function(){return a},null,{enabled:!0,ignore:!0})})),k=l[e.id]){this.depMaps.push(e);if(this.events.error)k.on("error",q(this,function(a){this.emit("error",a)}));k.enable()}}else d=q(this,function(a){this.init([],function(){return a},null,{enabled:!0})}),d.error=q(this,function(a){this.inited=!0;this.error=a;a.requireModules=[b];F(l,function(a){a.map.id.indexOf(b+
23 | "_unnormalized")===0&&delete l[a.map.id]});z(a)}),d.fromText=q(this,function(b,e){var f=a.name,c=j(f),k=K;e&&(b=e);k&&(K=!1);n(c);try{h.exec(b)}catch(x){throw Error("fromText eval for "+f+" failed: "+x);}k&&(K=!0);this.depMaps.push(c);i.completeLoad(f);g([f],d)}),e.load(a.name,g,d,m)}));i.enable(d,this);this.pluginMaps[d.id]=d},enable:function(){this.enabling=this.enabled=!0;s(this.depMaps,q(this,function(a,b){var c,e;if(typeof a==="string"){a=j(a,this.map.isDefine?this.map:this.map.parentMap,!1,
24 | !this.skipMap);this.depMaps[b]=a;if(c=L[a.id]){this.depExports[b]=c(this);return}this.depCount+=1;p(a,"defined",q(this,function(a){this.defineDep(b,a);this.check()}));this.errback&&p(a,"error",this.errback)}c=a.id;e=l[c];!L[c]&&e&&!e.enabled&&i.enable(a,this)}));F(this.pluginMaps,q(this,function(a){var b=l[a.id];b&&!b.enabled&&i.enable(a,this)}));this.enabling=!1;this.check()},on:function(a,b){var c=this.events[a];c||(c=this.events[a]=[]);c.push(b)},emit:function(a,b){s(this.events[a],function(a){a(b)});
25 | a==="error"&&delete this.events[a]}};i={config:m,contextName:b,registry:l,defined:o,urlFetched:P,defQueue:C,Module:S,makeModuleMap:j,nextTick:h.nextTick,configure:function(a){a.baseUrl&&a.baseUrl.charAt(a.baseUrl.length-1)!=="/"&&(a.baseUrl+="/");var b=m.pkgs,c=m.shim,e=m.paths,d=m.map;J(m,a,!0);m.paths=J(e,a.paths,!0);if(a.map)m.map=J(d||{},a.map,!0,!0);if(a.shim)F(a.shim,function(a,b){E(a)&&(a={deps:a});if(a.exports&&!a.exportsFn)a.exportsFn=i.makeShimExports(a);c[b]=a}),m.shim=c;if(a.packages)s(a.packages,
26 | function(a){a=typeof a==="string"?{name:a}:a;b[a.name]={name:a.name,location:a.location||a.name,main:(a.main||"main").replace(da,"").replace(Y,"")}}),m.pkgs=b;F(l,function(a,b){if(!a.inited&&!a.map.unnormalized)a.map=j(b)});if(a.deps||a.callback)i.require(a.deps||[],a.callback)},makeShimExports:function(a){return function(){var b;a.init&&(b=a.init.apply(U,arguments));return b||V(a.exports)}},makeRequire:function(a,f){function d(e,c,k){var g,m;if(f.enableBuildCallback&&c&&D(c))c.__requireJsBuild=!0;
27 | if(typeof e==="string"){if(D(c))return z(H("requireargs","Invalid require call"),k);if(a&&L[e])return L[e](l[a.id]);if(h.get)return h.get(i,e,a);g=j(e,a,!1,!0);g=g.id;return!G.call(o,g)?z(H("notloaded",'Module name "'+g+'" has not been loaded yet for context: '+b+(a?"":". Use require([])"))):o[g]}for(r();C.length;)if(g=C.shift(),g[0]===null)return z(H("mismatch","Mismatched anonymous define() module: "+g[g.length-1]));else y(g);i.nextTick(function(){m=n(j(null,a));m.skipMap=f.skipMap;m.init(e,c,k,
28 | {enabled:!0});w()});return d}f=f||{};J(d,{isBrowser:v,toUrl:function(b){var f=b.lastIndexOf("."),d=null;f!==-1&&(d=b.substring(f,b.length),b=b.substring(0,f));return i.nameToUrl(c(b,a&&a.id,!0),d)},defined:function(b){b=j(b,a,!1,!0).id;return G.call(o,b)},specified:function(b){b=j(b,a,!1,!0).id;return G.call(o,b)||G.call(l,b)}});if(!a)d.undef=function(b){r();var c=j(b,a,!0),f=l[b];delete o[b];delete P[c.url];delete T[b];if(f){if(f.events.defined)T[b]=f.events;delete l[b]}};return d},enable:function(a){l[a.id]&&
29 | n(a).enable()},completeLoad:function(a){var b,c,e=m.shim[a]||{},d=e.exports;for(r();C.length;){c=C.shift();if(c[0]===null){c[0]=a;if(b)break;b=!0}else c[0]===a&&(b=!0);y(c)}c=l[a];if(!b&&!o[a]&&c&&!c.inited)if(m.enforceDefine&&(!d||!V(d)))if(t(a))return;else return z(H("nodefine","No define call for "+a,null,[a]));else y([a,e.deps||[],e.exportsFn]);w()},nameToUrl:function(a,b){var c,e,d,g,i,j;if(h.jsExtRegExp.test(a))g=a+(b||"");else{c=m.paths;e=m.pkgs;g=a.split("/");for(i=g.length;i>0;i-=1)if(j=
30 | g.slice(0,i).join("/"),d=e[j],j=c[j]){E(j)&&(j=j[0]);g.splice(0,i,j);break}else if(d){c=a===d.name?d.location+"/"+d.main:d.location;g.splice(0,i,c);break}g=g.join("/");g+=b||(/\?/.test(g)?"":".js");g=(g.charAt(0)==="/"||g.match(/^[\w\+\.\-]+:/)?"":m.baseUrl)+g}return m.urlArgs?g+((g.indexOf("?")===-1?"?":"&")+m.urlArgs):g},load:function(a,b){h.load(i,a,b)},execCb:function(a,b,c,d){return b.apply(d,c)},onScriptLoad:function(a){if(a.type==="load"||fa.test((a.currentTarget||a.srcElement).readyState))I=
31 | null,a=A(a),i.completeLoad(a.id)},onScriptError:function(a){var b=A(a);if(!t(b.id))return z(H("scripterror","Script error",a,[b.id]))}};i.require=i.makeRequire();return i}};h({});s(["toUrl","undef","defined","specified"],function(b){h[b]=function(){var c=w._;return c.require[b].apply(c,arguments)}});if(v&&(u=r.head=document.getElementsByTagName("head")[0],y=document.getElementsByTagName("base")[0]))u=r.head=y.parentNode;h.onError=function(b){throw b;};h.load=function(b,c,d){var h=b&&b.config||{},
32 | g;if(v)return g=h.xhtml?document.createElementNS("http://www.w3.org/1999/xhtml","html:script"):document.createElement("script"),g.type=h.scriptType||"text/javascript",g.charset="utf-8",g.async=!0,g.setAttribute("data-requirecontext",b.contextName),g.setAttribute("data-requiremodule",c),g.attachEvent&&!(g.attachEvent.toString&&g.attachEvent.toString().indexOf("[native code")<0)&&!Q?(K=!0,g.attachEvent("onreadystatechange",b.onScriptLoad)):(g.addEventListener("load",b.onScriptLoad,!1),g.addEventListener("error",
33 | b.onScriptError,!1)),g.src=d,B=g,y?u.insertBefore(g,y):u.appendChild(g),B=null,g;else Z&&(importScripts(d),b.completeLoad(c))};v&&N(document.getElementsByTagName("script"),function(b){if(!u)u=b.parentNode;if(p=b.getAttribute("data-main")){if(!n.baseUrl)A=p.split("/"),W=A.pop(),X=A.length?A.join("/")+"/":"./",n.baseUrl=X,p=W;p=p.replace(Y,"");n.deps=n.deps?n.deps.concat(p):[p];return!0}});define=function(b,c,d){var h,g;typeof b!=="string"&&(d=c,c=b,b=null);E(c)||(d=c,c=[]);!c.length&&D(d)&&d.length&&
34 | (d.toString().replace(ba,"").replace(ca,function(b,d){c.push(d)}),c=(d.length===1?["require"]:["require","exports","module"]).concat(c));if(K&&(h=B||aa()))b||(b=h.getAttribute("data-requiremodule")),g=w[h.getAttribute("data-requirecontext")];(g?g.defQueue:O).push([b,c,d])};define.amd={jQuery:!0};h.exec=function(b){return eval(b)};h(n)}})(this);
35 |
--------------------------------------------------------------------------------
/slowmo/attr-mangler.js:
--------------------------------------------------------------------------------
1 | define(function() {
2 | function propertyAsString(node) {
3 | if ((!node.computed && node.property.type == 'Identifier'))
4 | return JSON.stringify(node.property.source());
5 | return node.property.source();
6 | }
7 |
8 | return function AttrMangler(node) {
9 | if (node.type == 'CallExpression' &&
10 | node.callee.type == 'MemberExpression') {
11 | var callArgs = node.arguments.map(function(arg) {
12 | return arg.source();
13 | }).join(', ');
14 | node.update('attr.call(' + node.callee.object.source() + ', ' +
15 | propertyAsString(node.callee) + ', ' +
16 | '[' + callArgs + '], ' +
17 | JSON.stringify(node.range) + ')');
18 | }
19 | if (node.type == 'AssignmentExpression' &&
20 | node.left.type == 'MemberExpression')
21 | node.update('attr.assign(' + node.left.object.source() + ', ' +
22 | propertyAsString(node.left) + ', ' +
23 | JSON.stringify(node.operator) + ', ' +
24 | node.right.source() + ', ' +
25 | JSON.stringify(node.range) + ')');
26 | if (node.type == 'UpdateExpression' &&
27 | node.argument.type == 'MemberExpression')
28 | node.update('attr.update(' + node.argument.object.source() + ', ' +
29 | propertyAsString(node.argument) + ', ' +
30 | JSON.stringify(node.operator) + ', ' +
31 | node.prefix + ', ' +
32 | JSON.stringify(node.range) + ')');
33 | if (node.type == 'MemberExpression') {
34 | if (node.parent.type == 'CallExpression' &&
35 | node.parent.callee === node)
36 | return;
37 | if (node.parent.type == 'AssignmentExpression' &&
38 | node.parent.left === node)
39 | return;
40 | if (node.parent.type == 'UpdateExpression' &&
41 | node.parent.argument === node)
42 | return;
43 | node.update('attr.get(' + node.object.source() + ', ' +
44 | propertyAsString(node) + ', ' +
45 | JSON.stringify(node.range) + ')');
46 | }
47 | };
48 | });
49 |
--------------------------------------------------------------------------------
/slowmo/attr.js:
--------------------------------------------------------------------------------
1 | define(function() {
2 | function Attr(log) {
3 | this.log = log;
4 | }
5 |
6 | Attr.prototype = {
7 | call: function(obj, prop, args, range) {
8 | this.log("call", obj, prop, args, range);
9 | return obj[prop].apply(obj, args);
10 | },
11 | get: function(obj, prop, range) {
12 | this.log("get", obj, prop, range);
13 | return obj[prop];
14 | },
15 | update: function(obj, prop, operator, prefix, range) {
16 | var oldValue = obj[prop];
17 | eval('obj[prop]' + operator);
18 | this.log("update", obj, prop, operator, prefix, oldValue, range);
19 | return prefix ? obj[prop] : oldValue;
20 | },
21 | assign: function(obj, prop, operator, value, range) {
22 | var oldValue = obj[prop];
23 | eval('obj[prop] ' + operator + ' value')
24 | this.log("assign", obj, prop, operator, oldValue, range);
25 | return value;
26 | }
27 | };
28 |
29 | return Attr;
30 | });
31 |
--------------------------------------------------------------------------------
/slowmo/loop-inserter.js:
--------------------------------------------------------------------------------
1 | define(function() {
2 | function defaultInserter(name) {
3 | return function(node) {
4 | return name + "();"
5 | }
6 | }
7 |
8 | return function LoopInserter(fn) {
9 | if (typeof(fn) == "string")
10 | fn = defaultInserter(fn);
11 |
12 | return function(node) {
13 | if (node.type == 'WhileStatement' ||
14 | node.type == 'ForStatement' ||
15 | node.type == 'DoWhileStatement') {
16 | node.body.update('{ ' + fn(node) + node.body.source() + ' }');
17 | return true;
18 | }
19 | return false;
20 | };
21 | };
22 | });
23 |
--------------------------------------------------------------------------------
/slowmo/scope-mangler.js:
--------------------------------------------------------------------------------
1 | define(function(require, module, exports) {
2 | function range(node) {
3 | if (!node) return "null";
4 | return JSON.stringify(node.range);
5 | }
6 |
7 | function makeDeclareCode(name, value, node) {
8 | if (value === null)
9 | value = "undefined";
10 | if (value && typeof(value) == "object")
11 | value = value.source();
12 | return 'scope.declare(' + JSON.stringify(name) + ', ' + value + ', ' +
13 | range(node) + ')';
14 | }
15 |
16 | function convertFunctionExpression(node) {
17 | var preamble = [makeDeclareCode("arguments", "arguments", null)];
18 | for (var i = 0; i < node.params.length; i++) {
19 | preamble.push(makeDeclareCode(node.params[i].name,
20 | "arguments[" + i + "]",
21 | node.params[i]));
22 | }
23 | var name = node.id && node.id.name || '';
24 | if (name) {
25 | preamble.push(makeDeclareCode(name, name, node.id));
26 | } else {
27 | if (node.parent.type == "VariableDeclarator")
28 | name = node.parent.id.name;
29 | if (node.parent.type == "Property" &&
30 | node.parent.key.type == "Identifier")
31 | name = node.parent.key.name;
32 | }
33 | return "(function(prevScope) { return function " +
34 | name + "() { " +
35 | "var scope = new Scope(prevScope, " +
36 | JSON.stringify(name) + ", " + range(node) + ");" +
37 | preamble.join(';') + '; try { ' +
38 | node.body.source().slice(1, -1) + "; } " +
39 | "finally { scope.leave(); } }})(scope)";
40 | }
41 |
42 | function convertForInStatement(node) {
43 | var id;
44 | var stmts = [];
45 | if (node.left.type == 'VariableDeclaration') {
46 | id = node.left.declarations[0].id;
47 | stmts.push(makeDeclareCode(id.name, "undefined", id));
48 | } else {
49 | id = node.left;
50 | }
51 | stmts.push('for (var val in ' + node.right.source() + ') {' +
52 | 'scope.assign(' + JSON.stringify(id.name) + ', "=", ' +
53 | 'val, ' + range(id) + '); ' +
54 | node.body.source().slice(1, -1) + '}');
55 | node.update('(function() {' + stmts.join('; ') + '})' +
56 | '.apply(this, arguments);');
57 | }
58 |
59 | return function ScopeMangler(node) {
60 | if (node.type == 'ForInStatement')
61 | return convertForInStatement(node);
62 |
63 | if (node.type == 'VariableDeclaration') {
64 | if (node.parent.type === 'ForInStatement' &&
65 | node.parent.left === node)
66 | return;
67 |
68 | var decls = [];
69 | node.declarations.forEach(function(decl) {
70 | decls.push(makeDeclareCode(decl.id.name, decl.init, decl));
71 | });
72 |
73 | var parentIsFor = node.parent.type === "ForStatement";
74 | var separator = parentIsFor ? " || " : " ; ";
75 | var newCode = decls.join(separator);
76 | if (!parentIsFor)
77 | newCode += ';'
78 | return node.update(newCode);
79 | }
80 |
81 | if (node.type == "AssignmentExpression") {
82 | if (node.left.type == "Identifier") {
83 | return node.update('scope.assign(' + JSON.stringify(node.left.name) +
84 | ', ' + JSON.stringify(node.operator) + ', ' +
85 | node.right.source() + ', ' + range(node) + ')');
86 | }
87 | }
88 |
89 | if (node.type == "UpdateExpression") {
90 | if (node.argument.type == "Identifier") {
91 | return node.update("scope.update(" +
92 | JSON.stringify(node.argument.name) +
93 | ", " + JSON.stringify(node.operator) + ", " +
94 | node.prefix + ", " + range(node) + ")");
95 | }
96 | }
97 |
98 | if (node.type == "FunctionDeclaration") {
99 | node.update("scope.declare(" + JSON.stringify(node.id.name) + ", " +
100 | convertFunctionExpression(node) + ", " +
101 | range(node) + ");");
102 | return;
103 | }
104 |
105 | if (node.type == "FunctionExpression") {
106 | return node.update(convertFunctionExpression(node));
107 | }
108 |
109 | if (node.type == "UnaryExpression" &&
110 | node.operator == "typeof" &&
111 | node.argument.type == "Identifier")
112 | return node.update("scope.getTypeOf(" +
113 | JSON.stringify(node.argument.name) + ", " +
114 | range(node) + ")");
115 |
116 | if (node.type == "Identifier") {
117 | if (node.parent.type == "ForInStatement" &&
118 | node.parent.left === node)
119 | return;
120 |
121 | if (node.parent.type == "UnaryExpression" &&
122 | node.parent.operator == "typeof")
123 | return;
124 |
125 | if (node.parent.type == "FunctionDeclaration" ||
126 | node.parent.type == "FunctionExpression")
127 | return;
128 | if (node.parent.type == "Property" &&
129 | node.parent.key === node) {
130 | return;
131 | }
132 | if (node.parent.type == "VariableDeclarator" &&
133 | node.parent.id === node) {
134 | return;
135 | }
136 | if (node.parent.type == "MemberExpression" &&
137 | node.parent.computed == false &&
138 | node.parent.object !== node) {
139 | return;
140 | }
141 | node.update('(scope.get(' + JSON.stringify(node.name) + ', ' +
142 | range(node) + '))');
143 | }
144 | };
145 | });
146 |
--------------------------------------------------------------------------------
/slowmo/scope.js:
--------------------------------------------------------------------------------
1 | define(function() {
2 | function noVariableError(name) {
3 | var err = new Error("no variable called " + name);
4 | err.range = arguments[arguments.length - 1];
5 | throw err;
6 | }
7 |
8 | var nullScope = {
9 | assign: noVariableError,
10 | update: noVariableError,
11 | get: noVariableError,
12 | getTypeOf: function(name, range) { return "undefined"; },
13 | log: function() {}
14 | };
15 |
16 | function Scope(prev, name, range, log) {
17 | this.prev = prev || nullScope;
18 | this.name = name;
19 | this.log = log || this.prev.log;
20 | this.vars = {};
21 | this.range = range;
22 | this.declRanges = {};
23 | this.log("enter");
24 | }
25 |
26 | Scope.prototype = {
27 | assign: function(name, operator, value, range) {
28 | if (name in this.vars) {
29 | var oldValue = this.vars[name];
30 | eval("this.vars[name] " + operator + " value");
31 | this.log("assign", name, operator, value, oldValue, range);
32 | return this.vars[name];
33 | }
34 | return this.prev.assign(name, operator, value, range);
35 | },
36 | update: function(name, operator, prefix, range) {
37 | if (name in this.vars) {
38 | var oldValue = this.vars[name];
39 | eval("this.vars[name]" + operator);
40 | this.log("update", name, operator, prefix, oldValue, range);
41 | return prefix ? this.vars[name] : oldValue;
42 | }
43 | return this.prev.update(name, operator, prefix, range);
44 | },
45 | declare: function(name, value, range) {
46 | this.vars[name] = value;
47 | this.declRanges[name] = range;
48 | this.log("declare", name, value, range);
49 | return value;
50 | },
51 | getTypeOf: function(name, range) {
52 | if (name in this.vars) {
53 | this.log("getTypeOf", name, this.vars[name], range);
54 | return typeof this.vars[name];
55 | }
56 | return this.prev.getTypeOf(name, range);
57 | },
58 | get: function(name, range) {
59 | if (name in this.vars) {
60 | this.log("get", name, this.vars[name], range);
61 | return this.vars[name];
62 | }
63 | return this.prev.get(name, range);
64 | },
65 | leave: function() {
66 | this.log("leave");
67 | }
68 | };
69 |
70 | Scope.logToConsole = function() {
71 | var args = ["SCOPE:" + this.name];
72 | args = args.concat(Array.prototype.slice.call(arguments));
73 | if (window.console)
74 | console.log.apply(console, args);
75 | };
76 |
77 | return Scope;
78 | });
79 |
--------------------------------------------------------------------------------
/test/all-tests.js:
--------------------------------------------------------------------------------
1 | defineTests.combine([
2 | "test/test-loop-inserter",
3 | "test/test-scope-mangler",
4 | "test/test-scope",
5 | "test/test-attr-mangler",
6 | "test/test-attr"
7 | ]);
--------------------------------------------------------------------------------
/test/define-tests.js:
--------------------------------------------------------------------------------
1 | // Because we're using requirejs to asynchronously load tests,
2 | // we need to have manual control over the running of tests.
3 | QUnit.config.autostart = false;
4 |
5 | // We want to "lazily" define tests so that the order of their
6 | // definition isn't arbitrarily determined by requirejs. This way,
7 | // the test results will always be reported in the same order, which
8 | // makes reading test results across multiple page reloads much
9 | // easier.
10 | //
11 | // Note that this has NOTHING to do with the order of
12 | // actual test execution--our tests should always be isolated from
13 | // each other so that the order QUnit chooses to run them in
14 | // doesn't matter.
15 | function defineTests(deps, fn) {
16 | define(deps, function() {
17 | var injectedDeps = arguments;
18 | return function describeTests() {
19 | fn.apply(this, injectedDeps);
20 | };
21 | });
22 | }
23 |
24 | // String together a bunch of defineTests-based modules into a
25 | // single one.
26 | defineTests.combine = function(deps) {
27 | define(deps, function() {
28 | var args = Array.prototype.slice.call(arguments);
29 | return function describeManyTests() {
30 | args.forEach(function(describeTests) {
31 | describeTests();
32 | });
33 | };
34 | });
35 | };
36 |
37 | // Run the given list of defineTests-based modules.
38 | defineTests.run = function(deps) {
39 | require(deps, function() {
40 | var args = Array.prototype.slice.call(arguments);
41 | args.forEach(function(describeTests) {
42 | describeTests();
43 | });
44 |
45 | if (QUnit.config.blocking)
46 | QUnit.config.autostart = true;
47 | else
48 | QUnit.start();
49 | });
50 | };
51 |
--------------------------------------------------------------------------------
/test/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | SlomoJS Test Suite
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
24 |
25 |
45 |
46 |
47 |
--------------------------------------------------------------------------------
/test/qunit.css:
--------------------------------------------------------------------------------
1 | /**
2 | * QUnit v1.6.0pre - A JavaScript Unit Testing Framework
3 | *
4 | * http://docs.jquery.com/QUnit
5 | *
6 | * Copyright (c) 2012 John Resig, Jörn Zaefferer
7 | * Dual licensed under the MIT (MIT-LICENSE.txt)
8 | * or GPL (GPL-LICENSE.txt) licenses.
9 | */
10 |
11 | /** Font Family and Sizes */
12 |
13 | #qunit-tests, #qunit-header, #qunit-banner, #qunit-testrunner-toolbar, #qunit-userAgent, #qunit-testresult {
14 | font-family: "Helvetica Neue Light", "HelveticaNeue-Light", "Helvetica Neue", Calibri, Helvetica, Arial, sans-serif;
15 | }
16 |
17 | #qunit-testrunner-toolbar, #qunit-userAgent, #qunit-testresult, #qunit-tests li { font-size: small; }
18 | #qunit-tests { font-size: smaller; }
19 |
20 |
21 | /** Resets */
22 |
23 | #qunit-tests, #qunit-tests ol, #qunit-header, #qunit-banner, #qunit-userAgent, #qunit-testresult {
24 | margin: 0;
25 | padding: 0;
26 | }
27 |
28 |
29 | /** Header */
30 |
31 | #qunit-header {
32 | padding: 0.5em 0 0.5em 1em;
33 |
34 | color: #8699a4;
35 | background-color: #0d3349;
36 |
37 | font-size: 1.5em;
38 | line-height: 1em;
39 | font-weight: normal;
40 |
41 | border-radius: 15px 15px 0 0;
42 | -moz-border-radius: 15px 15px 0 0;
43 | -webkit-border-top-right-radius: 15px;
44 | -webkit-border-top-left-radius: 15px;
45 | }
46 |
47 | #qunit-header a {
48 | text-decoration: none;
49 | color: #c2ccd1;
50 | }
51 |
52 | #qunit-header a:hover,
53 | #qunit-header a:focus {
54 | color: #fff;
55 | }
56 |
57 | #qunit-header label {
58 | display: inline-block;
59 | }
60 |
61 | #qunit-banner {
62 | height: 5px;
63 | }
64 |
65 | #qunit-testrunner-toolbar {
66 | padding: 0.5em 0 0.5em 2em;
67 | color: #5E740B;
68 | background-color: #eee;
69 | }
70 |
71 | #qunit-userAgent {
72 | padding: 0.5em 0 0.5em 2.5em;
73 | background-color: #2b81af;
74 | color: #fff;
75 | text-shadow: rgba(0, 0, 0, 0.5) 2px 2px 1px;
76 | }
77 |
78 |
79 | /** Tests: Pass/Fail */
80 |
81 | #qunit-tests {
82 | list-style-position: inside;
83 | }
84 |
85 | #qunit-tests li {
86 | padding: 0.4em 0.5em 0.4em 2.5em;
87 | border-bottom: 1px solid #fff;
88 | list-style-position: inside;
89 | }
90 |
91 | #qunit-tests.hidepass li.pass, #qunit-tests.hidepass li.running {
92 | display: none;
93 | }
94 |
95 | #qunit-tests li strong {
96 | cursor: pointer;
97 | }
98 |
99 | #qunit-tests li a {
100 | padding: 0.5em;
101 | color: #c2ccd1;
102 | text-decoration: none;
103 | }
104 | #qunit-tests li a:hover,
105 | #qunit-tests li a:focus {
106 | color: #000;
107 | }
108 |
109 | #qunit-tests ol {
110 | margin-top: 0.5em;
111 | padding: 0.5em;
112 |
113 | background-color: #fff;
114 |
115 | border-radius: 15px;
116 | -moz-border-radius: 15px;
117 | -webkit-border-radius: 15px;
118 |
119 | box-shadow: inset 0px 2px 13px #999;
120 | -moz-box-shadow: inset 0px 2px 13px #999;
121 | -webkit-box-shadow: inset 0px 2px 13px #999;
122 | }
123 |
124 | #qunit-tests table {
125 | border-collapse: collapse;
126 | margin-top: .2em;
127 | }
128 |
129 | #qunit-tests th {
130 | text-align: right;
131 | vertical-align: top;
132 | padding: 0 .5em 0 0;
133 | }
134 |
135 | #qunit-tests td {
136 | vertical-align: top;
137 | }
138 |
139 | #qunit-tests pre {
140 | margin: 0;
141 | white-space: pre-wrap;
142 | word-wrap: break-word;
143 | }
144 |
145 | #qunit-tests del {
146 | background-color: #e0f2be;
147 | color: #374e0c;
148 | text-decoration: none;
149 | }
150 |
151 | #qunit-tests ins {
152 | background-color: #ffcaca;
153 | color: #500;
154 | text-decoration: none;
155 | }
156 |
157 | /*** Test Counts */
158 |
159 | #qunit-tests b.counts { color: black; }
160 | #qunit-tests b.passed { color: #5E740B; }
161 | #qunit-tests b.failed { color: #710909; }
162 |
163 | #qunit-tests li li {
164 | margin: 0.5em;
165 | padding: 0.4em 0.5em 0.4em 0.5em;
166 | background-color: #fff;
167 | border-bottom: none;
168 | list-style-position: inside;
169 | }
170 |
171 | /*** Passing Styles */
172 |
173 | #qunit-tests li li.pass {
174 | color: #5E740B;
175 | background-color: #fff;
176 | border-left: 26px solid #C6E746;
177 | }
178 |
179 | #qunit-tests .pass { color: #528CE0; background-color: #D2E0E6; }
180 | #qunit-tests .pass .test-name { color: #366097; }
181 |
182 | #qunit-tests .pass .test-actual,
183 | #qunit-tests .pass .test-expected { color: #999999; }
184 |
185 | #qunit-banner.qunit-pass { background-color: #C6E746; }
186 |
187 | /*** Failing Styles */
188 |
189 | #qunit-tests li li.fail {
190 | color: #710909;
191 | background-color: #fff;
192 | border-left: 26px solid #EE5757;
193 | white-space: pre;
194 | }
195 |
196 | #qunit-tests > li:last-child {
197 | border-radius: 0 0 15px 15px;
198 | -moz-border-radius: 0 0 15px 15px;
199 | -webkit-border-bottom-right-radius: 15px;
200 | -webkit-border-bottom-left-radius: 15px;
201 | }
202 |
203 | #qunit-tests .fail { color: #000000; background-color: #EE5757; }
204 | #qunit-tests .fail .test-name,
205 | #qunit-tests .fail .module-name { color: #000000; }
206 |
207 | #qunit-tests .fail .test-actual { color: #EE5757; }
208 | #qunit-tests .fail .test-expected { color: green; }
209 |
210 | #qunit-banner.qunit-fail { background-color: #EE5757; }
211 |
212 |
213 | /** Result */
214 |
215 | #qunit-testresult {
216 | padding: 0.5em 0.5em 0.5em 2.5em;
217 |
218 | color: #2b81af;
219 | background-color: #D2E0E6;
220 |
221 | border-bottom: 1px solid white;
222 | }
223 | #qunit-testresult .module-name {
224 | font-weight: bold;
225 | }
226 |
227 | /** Fixture */
228 |
229 | #qunit-fixture {
230 | position: absolute;
231 | top: -10000px;
232 | left: -10000px;
233 | width: 1000px;
234 | height: 1000px;
235 | }
236 |
--------------------------------------------------------------------------------
/test/qunit.js:
--------------------------------------------------------------------------------
1 | /**
2 | * QUnit v1.6.0pre - A JavaScript Unit Testing Framework
3 | *
4 | * http://docs.jquery.com/QUnit
5 | *
6 | * Copyright (c) 2012 John Resig, Jörn Zaefferer
7 | * Dual licensed under the MIT (MIT-LICENSE.txt)
8 | * or GPL (GPL-LICENSE.txt) licenses.
9 | */
10 |
11 | (function(window) {
12 |
13 | var defined = {
14 | setTimeout: typeof window.setTimeout !== "undefined",
15 | sessionStorage: (function() {
16 | var x = "qunit-test-string";
17 | try {
18 | sessionStorage.setItem(x, x);
19 | sessionStorage.removeItem(x);
20 | return true;
21 | } catch(e) {
22 | return false;
23 | }
24 | }())
25 | };
26 |
27 | var testId = 0,
28 | toString = Object.prototype.toString,
29 | hasOwn = Object.prototype.hasOwnProperty;
30 |
31 | var Test = function(name, testName, expected, async, callback) {
32 | this.name = name;
33 | this.testName = testName;
34 | this.expected = expected;
35 | this.async = async;
36 | this.callback = callback;
37 | this.assertions = [];
38 | };
39 | Test.prototype = {
40 | init: function() {
41 | var tests = id("qunit-tests");
42 | if (tests) {
43 | var b = document.createElement("strong");
44 | b.innerHTML = "Running " + this.name;
45 | var li = document.createElement("li");
46 | li.appendChild( b );
47 | li.className = "running";
48 | li.id = this.id = "test-output" + testId++;
49 | tests.appendChild( li );
50 | }
51 | },
52 | setup: function() {
53 | if (this.module != config.previousModule) {
54 | if ( config.previousModule ) {
55 | runLoggingCallbacks('moduleDone', QUnit, {
56 | name: config.previousModule,
57 | failed: config.moduleStats.bad,
58 | passed: config.moduleStats.all - config.moduleStats.bad,
59 | total: config.moduleStats.all
60 | } );
61 | }
62 | config.previousModule = this.module;
63 | config.moduleStats = { all: 0, bad: 0 };
64 | runLoggingCallbacks( 'moduleStart', QUnit, {
65 | name: this.module
66 | } );
67 | } else if (config.autorun) {
68 | runLoggingCallbacks( 'moduleStart', QUnit, {
69 | name: this.module
70 | } );
71 | }
72 |
73 | config.current = this;
74 | this.testEnvironment = extend({
75 | setup: function() {},
76 | teardown: function() {}
77 | }, this.moduleTestEnvironment);
78 |
79 | runLoggingCallbacks( 'testStart', QUnit, {
80 | name: this.testName,
81 | module: this.module
82 | });
83 |
84 | // allow utility functions to access the current test environment
85 | // TODO why??
86 | QUnit.current_testEnvironment = this.testEnvironment;
87 |
88 | if ( !config.pollution ) {
89 | saveGlobal();
90 | }
91 | if ( config.notrycatch ) {
92 | this.testEnvironment.setup.call(this.testEnvironment);
93 | return;
94 | }
95 | try {
96 | this.testEnvironment.setup.call(this.testEnvironment);
97 | } catch(e) {
98 | QUnit.pushFailure( "Setup failed on " + this.testName + ": " + e.message, extractStacktrace( e, 1 ) );
99 | }
100 | },
101 | run: function() {
102 | config.current = this;
103 |
104 | var running = id("qunit-testresult");
105 |
106 | if ( running ) {
107 | running.innerHTML = "Running: " + this.name;
108 | }
109 |
110 | if ( this.async ) {
111 | QUnit.stop();
112 | }
113 |
114 | if ( config.notrycatch ) {
115 | this.callback.call(this.testEnvironment);
116 | return;
117 | }
118 | try {
119 | this.callback.call(this.testEnvironment);
120 | } catch(e) {
121 | QUnit.pushFailure( "Died on test #" + (this.assertions.length + 1) + ": " + e.message, extractStacktrace( e, 1 ) );
122 | // else next test will carry the responsibility
123 | saveGlobal();
124 |
125 | // Restart the tests if they're blocking
126 | if ( config.blocking ) {
127 | QUnit.start();
128 | }
129 | }
130 | },
131 | teardown: function() {
132 | config.current = this;
133 | if ( config.notrycatch ) {
134 | this.testEnvironment.teardown.call(this.testEnvironment);
135 | return;
136 | } else {
137 | try {
138 | this.testEnvironment.teardown.call(this.testEnvironment);
139 | } catch(e) {
140 | QUnit.pushFailure( "Teardown failed on " + this.testName + ": " + e.message, extractStacktrace( e, 1 ) );
141 | }
142 | }
143 | checkPollution();
144 | },
145 | finish: function() {
146 | config.current = this;
147 | if ( this.expected != null && this.expected != this.assertions.length ) {
148 | QUnit.pushFailure( "Expected " + this.expected + " assertions, but " + this.assertions.length + " were run" );
149 | } else if ( this.expected == null && !this.assertions.length ) {
150 | QUnit.pushFailure( "Expected at least one assertion, but none were run - call expect(0) to accept zero assertions." );
151 | }
152 |
153 | var good = 0, bad = 0,
154 | li, i,
155 | tests = id("qunit-tests");
156 |
157 | config.stats.all += this.assertions.length;
158 | config.moduleStats.all += this.assertions.length;
159 |
160 | if ( tests ) {
161 | var ol = document.createElement("ol");
162 |
163 | for ( i = 0; i < this.assertions.length; i++ ) {
164 | var assertion = this.assertions[i];
165 |
166 | li = document.createElement("li");
167 | li.className = assertion.result ? "pass" : "fail";
168 | li.innerHTML = assertion.message || (assertion.result ? "okay" : "failed");
169 | ol.appendChild( li );
170 |
171 | if ( assertion.result ) {
172 | good++;
173 | } else {
174 | bad++;
175 | config.stats.bad++;
176 | config.moduleStats.bad++;
177 | }
178 | }
179 |
180 | // store result when possible
181 | if ( QUnit.config.reorder && defined.sessionStorage ) {
182 | if (bad) {
183 | sessionStorage.setItem("qunit-test-" + this.module + "-" + this.testName, bad);
184 | } else {
185 | sessionStorage.removeItem("qunit-test-" + this.module + "-" + this.testName);
186 | }
187 | }
188 |
189 | if (bad === 0) {
190 | ol.style.display = "none";
191 | }
192 |
193 | var b = document.createElement("strong");
194 | b.innerHTML = this.name + " (" + bad + " , " + good + " , " + this.assertions.length + ") ";
195 |
196 | var a = document.createElement("a");
197 | a.innerHTML = "Rerun";
198 | a.href = QUnit.url({ filter: getText([b]).replace(/\([^)]+\)$/, "").replace(/(^\s*|\s*$)/g, "") });
199 |
200 | addEvent(b, "click", function() {
201 | var next = b.nextSibling.nextSibling,
202 | display = next.style.display;
203 | next.style.display = display === "none" ? "block" : "none";
204 | });
205 |
206 | addEvent(b, "dblclick", function(e) {
207 | var target = e && e.target ? e.target : window.event.srcElement;
208 | if ( target.nodeName.toLowerCase() == "span" || target.nodeName.toLowerCase() == "b" ) {
209 | target = target.parentNode;
210 | }
211 | if ( window.location && target.nodeName.toLowerCase() === "strong" ) {
212 | window.location = QUnit.url({ filter: getText([target]).replace(/\([^)]+\)$/, "").replace(/(^\s*|\s*$)/g, "") });
213 | }
214 | });
215 |
216 | li = id(this.id);
217 | li.className = bad ? "fail" : "pass";
218 | li.removeChild( li.firstChild );
219 | li.appendChild( b );
220 | li.appendChild( a );
221 | li.appendChild( ol );
222 |
223 | } else {
224 | for ( i = 0; i < this.assertions.length; i++ ) {
225 | if ( !this.assertions[i].result ) {
226 | bad++;
227 | config.stats.bad++;
228 | config.moduleStats.bad++;
229 | }
230 | }
231 | }
232 |
233 | QUnit.reset();
234 |
235 | runLoggingCallbacks( 'testDone', QUnit, {
236 | name: this.testName,
237 | module: this.module,
238 | failed: bad,
239 | passed: this.assertions.length - bad,
240 | total: this.assertions.length
241 | } );
242 | },
243 |
244 | queue: function() {
245 | var test = this;
246 | synchronize(function() {
247 | test.init();
248 | });
249 | function run() {
250 | // each of these can by async
251 | synchronize(function() {
252 | test.setup();
253 | });
254 | synchronize(function() {
255 | test.run();
256 | });
257 | synchronize(function() {
258 | test.teardown();
259 | });
260 | synchronize(function() {
261 | test.finish();
262 | });
263 | }
264 | // defer when previous test run passed, if storage is available
265 | var bad = QUnit.config.reorder && defined.sessionStorage && +sessionStorage.getItem("qunit-test-" + this.module + "-" + this.testName);
266 | if (bad) {
267 | run();
268 | } else {
269 | synchronize(run, true);
270 | }
271 | }
272 |
273 | };
274 |
275 | var QUnit = {
276 |
277 | // call on start of module test to prepend name to all tests
278 | module: function(name, testEnvironment) {
279 | config.currentModule = name;
280 | config.currentModuleTestEnviroment = testEnvironment;
281 | },
282 |
283 | asyncTest: function(testName, expected, callback) {
284 | if ( arguments.length === 2 ) {
285 | callback = expected;
286 | expected = null;
287 | }
288 |
289 | QUnit.test(testName, expected, callback, true);
290 | },
291 |
292 | test: function(testName, expected, callback, async) {
293 | var name = '' + escapeInnerText(testName) + ' ';
294 |
295 | if ( arguments.length === 2 ) {
296 | callback = expected;
297 | expected = null;
298 | }
299 |
300 | if ( config.currentModule ) {
301 | name = '' + config.currentModule + " : " + name;
302 | }
303 |
304 | if ( !validTest(config.currentModule + ": " + testName) ) {
305 | return;
306 | }
307 |
308 | var test = new Test(name, testName, expected, async, callback);
309 | test.module = config.currentModule;
310 | test.moduleTestEnvironment = config.currentModuleTestEnviroment;
311 | test.queue();
312 | },
313 |
314 | // Specify the number of expected assertions to gurantee that failed test (no assertions are run at all) don't slip through.
315 | expect: function(asserts) {
316 | config.current.expected = asserts;
317 | },
318 |
319 | // Asserts true.
320 | // @example ok( "asdfasdf".length > 5, "There must be at least 5 chars" );
321 | ok: function(result, msg) {
322 | if (!config.current) {
323 | throw new Error("ok() assertion outside test context, was " + sourceFromStacktrace(2));
324 | }
325 | result = !!result;
326 | var details = {
327 | result: result,
328 | message: msg
329 | };
330 | msg = escapeInnerText(msg || (result ? "okay" : "failed"));
331 | if ( !result ) {
332 | var source = sourceFromStacktrace(2);
333 | if (source) {
334 | details.source = source;
335 | msg += 'Source: ' + escapeInnerText(source) + '
';
336 | }
337 | }
338 | runLoggingCallbacks( 'log', QUnit, details );
339 | config.current.assertions.push({
340 | result: result,
341 | message: msg
342 | });
343 | },
344 |
345 | // Checks that the first two arguments are equal, with an optional message. Prints out both actual and expected values.
346 | // @example equal( format("Received {0} bytes.", 2), "Received 2 bytes." );
347 | equal: function(actual, expected, message) {
348 | QUnit.push(expected == actual, actual, expected, message);
349 | },
350 |
351 | notEqual: function(actual, expected, message) {
352 | QUnit.push(expected != actual, actual, expected, message);
353 | },
354 |
355 | deepEqual: function(actual, expected, message) {
356 | QUnit.push(QUnit.equiv(actual, expected), actual, expected, message);
357 | },
358 |
359 | notDeepEqual: function(actual, expected, message) {
360 | QUnit.push(!QUnit.equiv(actual, expected), actual, expected, message);
361 | },
362 |
363 | strictEqual: function(actual, expected, message) {
364 | QUnit.push(expected === actual, actual, expected, message);
365 | },
366 |
367 | notStrictEqual: function(actual, expected, message) {
368 | QUnit.push(expected !== actual, actual, expected, message);
369 | },
370 |
371 | raises: function(block, expected, message) {
372 | var actual, ok = false;
373 |
374 | if (typeof expected === 'string') {
375 | message = expected;
376 | expected = null;
377 | }
378 |
379 | try {
380 | block.call(config.current.testEnvironment);
381 | } catch (e) {
382 | actual = e;
383 | }
384 |
385 | if (actual) {
386 | // we don't want to validate thrown error
387 | if (!expected) {
388 | ok = true;
389 | // expected is a regexp
390 | } else if (QUnit.objectType(expected) === "regexp") {
391 | ok = expected.test(actual);
392 | // expected is a constructor
393 | } else if (actual instanceof expected) {
394 | ok = true;
395 | // expected is a validation function which returns true is validation passed
396 | } else if (expected.call({}, actual) === true) {
397 | ok = true;
398 | }
399 | }
400 |
401 | QUnit.ok(ok, message);
402 | },
403 |
404 | start: function(count) {
405 | config.semaphore -= count || 1;
406 | if (config.semaphore > 0) {
407 | // don't start until equal number of stop-calls
408 | return;
409 | }
410 | if (config.semaphore < 0) {
411 | // ignore if start is called more often then stop
412 | config.semaphore = 0;
413 | }
414 | // A slight delay, to avoid any current callbacks
415 | if ( defined.setTimeout ) {
416 | window.setTimeout(function() {
417 | if (config.semaphore > 0) {
418 | return;
419 | }
420 | if ( config.timeout ) {
421 | clearTimeout(config.timeout);
422 | }
423 |
424 | config.blocking = false;
425 | process(true);
426 | }, 13);
427 | } else {
428 | config.blocking = false;
429 | process(true);
430 | }
431 | },
432 |
433 | stop: function(count) {
434 | config.semaphore += count || 1;
435 | config.blocking = true;
436 |
437 | if ( config.testTimeout && defined.setTimeout ) {
438 | clearTimeout(config.timeout);
439 | config.timeout = window.setTimeout(function() {
440 | QUnit.ok( false, "Test timed out" );
441 | config.semaphore = 1;
442 | QUnit.start();
443 | }, config.testTimeout);
444 | }
445 | }
446 | };
447 |
448 | //We want access to the constructor's prototype
449 | (function() {
450 | function F(){}
451 | F.prototype = QUnit;
452 | QUnit = new F();
453 | //Make F QUnit's constructor so that we can add to the prototype later
454 | QUnit.constructor = F;
455 | }());
456 |
457 | // deprecated; still export them to window to provide clear error messages
458 | // next step: remove entirely
459 | QUnit.equals = function() {
460 | QUnit.push(false, false, false, "QUnit.equals has been deprecated since 2009 (e88049a0), use QUnit.equal instead");
461 | };
462 | QUnit.same = function() {
463 | QUnit.push(false, false, false, "QUnit.same has been deprecated since 2009 (e88049a0), use QUnit.deepEqual instead");
464 | };
465 |
466 | // Maintain internal state
467 | var config = {
468 | // The queue of tests to run
469 | queue: [],
470 |
471 | // block until document ready
472 | blocking: true,
473 |
474 | // when enabled, show only failing tests
475 | // gets persisted through sessionStorage and can be changed in UI via checkbox
476 | hidepassed: false,
477 |
478 | // by default, run previously failed tests first
479 | // very useful in combination with "Hide passed tests" checked
480 | reorder: true,
481 |
482 | // by default, modify document.title when suite is done
483 | altertitle: true,
484 |
485 | urlConfig: ['noglobals', 'notrycatch'],
486 |
487 | //logging callback queues
488 | begin: [],
489 | done: [],
490 | log: [],
491 | testStart: [],
492 | testDone: [],
493 | moduleStart: [],
494 | moduleDone: []
495 | };
496 |
497 | // Load paramaters
498 | (function() {
499 | var location = window.location || { search: "", protocol: "file:" },
500 | params = location.search.slice( 1 ).split( "&" ),
501 | length = params.length,
502 | urlParams = {},
503 | current;
504 |
505 | if ( params[ 0 ] ) {
506 | for ( var i = 0; i < length; i++ ) {
507 | current = params[ i ].split( "=" );
508 | current[ 0 ] = decodeURIComponent( current[ 0 ] );
509 | // allow just a key to turn on a flag, e.g., test.html?noglobals
510 | current[ 1 ] = current[ 1 ] ? decodeURIComponent( current[ 1 ] ) : true;
511 | urlParams[ current[ 0 ] ] = current[ 1 ];
512 | }
513 | }
514 |
515 | QUnit.urlParams = urlParams;
516 | config.filter = urlParams.filter;
517 |
518 | // Figure out if we're running the tests from a server or not
519 | QUnit.isLocal = location.protocol === 'file:';
520 | }());
521 |
522 | // Expose the API as global variables, unless an 'exports'
523 | // object exists, in that case we assume we're in CommonJS - export everything at the end
524 | if ( typeof exports === "undefined" || typeof require === "undefined" ) {
525 | extend(window, QUnit);
526 | window.QUnit = QUnit;
527 | }
528 |
529 | // define these after exposing globals to keep them in these QUnit namespace only
530 | extend(QUnit, {
531 | config: config,
532 |
533 | // Initialize the configuration options
534 | init: function() {
535 | extend(config, {
536 | stats: { all: 0, bad: 0 },
537 | moduleStats: { all: 0, bad: 0 },
538 | started: +new Date(),
539 | updateRate: 1000,
540 | blocking: false,
541 | autostart: true,
542 | autorun: false,
543 | filter: "",
544 | queue: [],
545 | semaphore: 0
546 | });
547 |
548 | var qunit = id( "qunit" );
549 | if ( qunit ) {
550 | qunit.innerHTML =
551 | '' +
552 | ' ' +
553 | '
' +
554 | ' ' +
555 | ' ';
556 | }
557 |
558 | var tests = id( "qunit-tests" ),
559 | banner = id( "qunit-banner" ),
560 | result = id( "qunit-testresult" );
561 |
562 | if ( tests ) {
563 | tests.innerHTML = "";
564 | }
565 |
566 | if ( banner ) {
567 | banner.className = "";
568 | }
569 |
570 | if ( result ) {
571 | result.parentNode.removeChild( result );
572 | }
573 |
574 | if ( tests ) {
575 | result = document.createElement( "p" );
576 | result.id = "qunit-testresult";
577 | result.className = "result";
578 | tests.parentNode.insertBefore( result, tests );
579 | result.innerHTML = 'Running... ';
580 | }
581 | },
582 |
583 | // Resets the test setup. Useful for tests that modify the DOM.
584 | // If jQuery is available, uses jQuery's html(), otherwise just innerHTML.
585 | reset: function() {
586 | if ( window.jQuery ) {
587 | jQuery( "#qunit-fixture" ).html( config.fixture );
588 | } else {
589 | var main = id( 'qunit-fixture' );
590 | if ( main ) {
591 | main.innerHTML = config.fixture;
592 | }
593 | }
594 | },
595 |
596 | // Trigger an event on an element.
597 | // @example triggerEvent( document.body, "click" );
598 | triggerEvent: function( elem, type, event ) {
599 | if ( document.createEvent ) {
600 | event = document.createEvent("MouseEvents");
601 | event.initMouseEvent(type, true, true, elem.ownerDocument.defaultView,
602 | 0, 0, 0, 0, 0, false, false, false, false, 0, null);
603 | elem.dispatchEvent( event );
604 |
605 | } else if ( elem.fireEvent ) {
606 | elem.fireEvent("on"+type);
607 | }
608 | },
609 |
610 | // Safe object type checking
611 | is: function( type, obj ) {
612 | return QUnit.objectType( obj ) == type;
613 | },
614 |
615 | objectType: function( obj ) {
616 | if (typeof obj === "undefined") {
617 | return "undefined";
618 |
619 | // consider: typeof null === object
620 | }
621 | if (obj === null) {
622 | return "null";
623 | }
624 |
625 | var type = toString.call( obj ).match(/^\[object\s(.*)\]$/)[1] || '';
626 |
627 | switch (type) {
628 | case 'Number':
629 | if (isNaN(obj)) {
630 | return "nan";
631 | }
632 | return "number";
633 | case 'String':
634 | case 'Boolean':
635 | case 'Array':
636 | case 'Date':
637 | case 'RegExp':
638 | case 'Function':
639 | return type.toLowerCase();
640 | }
641 | if (typeof obj === "object") {
642 | return "object";
643 | }
644 | return undefined;
645 | },
646 |
647 | push: function(result, actual, expected, message) {
648 | if (!config.current) {
649 | throw new Error("assertion outside test context, was " + sourceFromStacktrace());
650 | }
651 | var details = {
652 | result: result,
653 | message: message,
654 | actual: actual,
655 | expected: expected
656 | };
657 |
658 | message = escapeInnerText(message) || (result ? "okay" : "failed");
659 | message = '' + message + " ";
660 | var output = message;
661 | if (!result) {
662 | expected = escapeInnerText(QUnit.jsDump.parse(expected));
663 | actual = escapeInnerText(QUnit.jsDump.parse(actual));
664 | output += 'Expected: ' + expected + ' ';
665 | if (actual != expected) {
666 | output += 'Result: ' + actual + ' ';
667 | output += 'Diff: ' + QUnit.diff(expected, actual) +' ';
668 | }
669 | var source = sourceFromStacktrace();
670 | if (source) {
671 | details.source = source;
672 | output += 'Source: ' + escapeInnerText(source) + ' ';
673 | }
674 | output += "
";
675 | }
676 |
677 | runLoggingCallbacks( 'log', QUnit, details );
678 |
679 | config.current.assertions.push({
680 | result: !!result,
681 | message: output
682 | });
683 | },
684 |
685 | pushFailure: function(message, source) {
686 | var details = {
687 | result: false,
688 | message: message
689 | };
690 | var output = escapeInnerText(message);
691 | if (source) {
692 | details.source = source;
693 | output += 'Source: ' + escapeInnerText(source) + '
';
694 | }
695 | runLoggingCallbacks( 'log', QUnit, details );
696 | config.current.assertions.push({
697 | result: false,
698 | message: output
699 | });
700 | },
701 |
702 | url: function( params ) {
703 | params = extend( extend( {}, QUnit.urlParams ), params );
704 | var querystring = "?",
705 | key;
706 | for ( key in params ) {
707 | if ( !hasOwn.call( params, key ) ) {
708 | continue;
709 | }
710 | querystring += encodeURIComponent( key ) + "=" +
711 | encodeURIComponent( params[ key ] ) + "&";
712 | }
713 | return window.location.pathname + querystring.slice( 0, -1 );
714 | },
715 |
716 | extend: extend,
717 | id: id,
718 | addEvent: addEvent
719 | });
720 |
721 | //QUnit.constructor is set to the empty F() above so that we can add to it's prototype later
722 | //Doing this allows us to tell if the following methods have been overwritten on the actual
723 | //QUnit object, which is a deprecated way of using the callbacks.
724 | extend(QUnit.constructor.prototype, {
725 | // Logging callbacks; all receive a single argument with the listed properties
726 | // run test/logs.html for any related changes
727 | begin: registerLoggingCallback('begin'),
728 | // done: { failed, passed, total, runtime }
729 | done: registerLoggingCallback('done'),
730 | // log: { result, actual, expected, message }
731 | log: registerLoggingCallback('log'),
732 | // testStart: { name }
733 | testStart: registerLoggingCallback('testStart'),
734 | // testDone: { name, failed, passed, total }
735 | testDone: registerLoggingCallback('testDone'),
736 | // moduleStart: { name }
737 | moduleStart: registerLoggingCallback('moduleStart'),
738 | // moduleDone: { name, failed, passed, total }
739 | moduleDone: registerLoggingCallback('moduleDone')
740 | });
741 |
742 | if ( typeof document === "undefined" || document.readyState === "complete" ) {
743 | config.autorun = true;
744 | }
745 |
746 | QUnit.load = function() {
747 | runLoggingCallbacks( 'begin', QUnit, {} );
748 |
749 | // Initialize the config, saving the execution queue
750 | var oldconfig = extend({}, config);
751 | QUnit.init();
752 | extend(config, oldconfig);
753 |
754 | config.blocking = false;
755 |
756 | var urlConfigHtml = '', len = config.urlConfig.length;
757 | for ( var i = 0, val; i < len; i++ ) {
758 | val = config.urlConfig[i];
759 | config[val] = QUnit.urlParams[val];
760 | urlConfigHtml += ' ' + val + ' ';
761 | }
762 |
763 | var userAgent = id("qunit-userAgent");
764 | if ( userAgent ) {
765 | userAgent.innerHTML = navigator.userAgent;
766 | }
767 | var banner = id("qunit-header");
768 | if ( banner ) {
769 | banner.innerHTML = ' ' + banner.innerHTML + ' ' + urlConfigHtml;
770 | addEvent( banner, "change", function( event ) {
771 | var params = {};
772 | params[ event.target.name ] = event.target.checked ? true : undefined;
773 | window.location = QUnit.url( params );
774 | });
775 | }
776 |
777 | var toolbar = id("qunit-testrunner-toolbar");
778 | if ( toolbar ) {
779 | var filter = document.createElement("input");
780 | filter.type = "checkbox";
781 | filter.id = "qunit-filter-pass";
782 | addEvent( filter, "click", function() {
783 | var ol = document.getElementById("qunit-tests");
784 | if ( filter.checked ) {
785 | ol.className = ol.className + " hidepass";
786 | } else {
787 | var tmp = " " + ol.className.replace( /[\n\t\r]/g, " " ) + " ";
788 | ol.className = tmp.replace(/ hidepass /, " ");
789 | }
790 | if ( defined.sessionStorage ) {
791 | if (filter.checked) {
792 | sessionStorage.setItem("qunit-filter-passed-tests", "true");
793 | } else {
794 | sessionStorage.removeItem("qunit-filter-passed-tests");
795 | }
796 | }
797 | });
798 | if ( config.hidepassed || defined.sessionStorage && sessionStorage.getItem("qunit-filter-passed-tests") ) {
799 | filter.checked = true;
800 | var ol = document.getElementById("qunit-tests");
801 | ol.className = ol.className + " hidepass";
802 | }
803 | toolbar.appendChild( filter );
804 |
805 | var label = document.createElement("label");
806 | label.setAttribute("for", "qunit-filter-pass");
807 | label.innerHTML = "Hide passed tests";
808 | toolbar.appendChild( label );
809 | }
810 |
811 | var main = id('qunit-fixture');
812 | if ( main ) {
813 | config.fixture = main.innerHTML;
814 | }
815 |
816 | if (config.autostart) {
817 | QUnit.start();
818 | }
819 | };
820 |
821 | addEvent(window, "load", QUnit.load);
822 |
823 | // addEvent(window, "error") gives us a useless event object
824 | window.onerror = function( message, file, line ) {
825 | if ( QUnit.config.current ) {
826 | QUnit.pushFailure( message, file + ":" + line );
827 | } else {
828 | QUnit.test( "global failure", function() {
829 | QUnit.pushFailure( message, file + ":" + line );
830 | });
831 | }
832 | };
833 |
834 | function done() {
835 | config.autorun = true;
836 |
837 | // Log the last module results
838 | if ( config.currentModule ) {
839 | runLoggingCallbacks( 'moduleDone', QUnit, {
840 | name: config.currentModule,
841 | failed: config.moduleStats.bad,
842 | passed: config.moduleStats.all - config.moduleStats.bad,
843 | total: config.moduleStats.all
844 | } );
845 | }
846 |
847 | var banner = id("qunit-banner"),
848 | tests = id("qunit-tests"),
849 | runtime = +new Date() - config.started,
850 | passed = config.stats.all - config.stats.bad,
851 | html = [
852 | 'Tests completed in ',
853 | runtime,
854 | ' milliseconds. ',
855 | '',
856 | passed,
857 | ' tests of ',
858 | config.stats.all,
859 | ' passed, ',
860 | config.stats.bad,
861 | ' failed.'
862 | ].join('');
863 |
864 | if ( banner ) {
865 | banner.className = (config.stats.bad ? "qunit-fail" : "qunit-pass");
866 | }
867 |
868 | if ( tests ) {
869 | id( "qunit-testresult" ).innerHTML = html;
870 | }
871 |
872 | if ( config.altertitle && typeof document !== "undefined" && document.title ) {
873 | // show ✖ for good, ✔ for bad suite result in title
874 | // use escape sequences in case file gets loaded with non-utf-8-charset
875 | document.title = [
876 | (config.stats.bad ? "\u2716" : "\u2714"),
877 | document.title.replace(/^[\u2714\u2716] /i, "")
878 | ].join(" ");
879 | }
880 |
881 | // clear own sessionStorage items if all tests passed
882 | if ( config.reorder && defined.sessionStorage && config.stats.bad === 0 ) {
883 | var key;
884 | for ( var i = 0; i < sessionStorage.length; i++ ) {
885 | key = sessionStorage.key( i++ );
886 | if ( key.indexOf("qunit-test-") === 0 ) {
887 | sessionStorage.removeItem( key );
888 | }
889 | }
890 | }
891 |
892 | runLoggingCallbacks( 'done', QUnit, {
893 | failed: config.stats.bad,
894 | passed: passed,
895 | total: config.stats.all,
896 | runtime: runtime
897 | } );
898 | }
899 |
900 | function validTest( name ) {
901 | var filter = config.filter,
902 | run = false;
903 |
904 | if ( !filter ) {
905 | return true;
906 | }
907 |
908 | var not = filter.charAt( 0 ) === "!";
909 | if ( not ) {
910 | filter = filter.slice( 1 );
911 | }
912 |
913 | if ( name.indexOf( filter ) !== -1 ) {
914 | return !not;
915 | }
916 |
917 | if ( not ) {
918 | run = true;
919 | }
920 |
921 | return run;
922 | }
923 |
924 | // so far supports only Firefox, Chrome and Opera (buggy), Safari (for real exceptions)
925 | // Later Safari and IE10 are supposed to support error.stack as well
926 | // See also https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error/Stack
927 | function extractStacktrace( e, offset ) {
928 | offset = offset || 3;
929 | if (e.stacktrace) {
930 | // Opera
931 | return e.stacktrace.split("\n")[offset + 3];
932 | } else if (e.stack) {
933 | // Firefox, Chrome
934 | var stack = e.stack.split("\n");
935 | if (/^error$/i.test(stack[0])) {
936 | stack.shift();
937 | }
938 | return stack[offset];
939 | } else if (e.sourceURL) {
940 | // Safari, PhantomJS
941 | // hopefully one day Safari provides actual stacktraces
942 | // exclude useless self-reference for generated Error objects
943 | if ( /qunit.js$/.test( e.sourceURL ) ) {
944 | return;
945 | }
946 | // for actual exceptions, this is useful
947 | return e.sourceURL + ":" + e.line;
948 | }
949 | }
950 | function sourceFromStacktrace(offset) {
951 | try {
952 | throw new Error();
953 | } catch ( e ) {
954 | return extractStacktrace( e, offset );
955 | }
956 | }
957 |
958 | function escapeInnerText(s) {
959 | if (!s) {
960 | return "";
961 | }
962 | s = s + "";
963 | return s.replace(/[\&<>]/g, function(s) {
964 | switch(s) {
965 | case "&": return "&";
966 | case "<": return "<";
967 | case ">": return ">";
968 | default: return s;
969 | }
970 | });
971 | }
972 |
973 | function synchronize( callback, last ) {
974 | config.queue.push( callback );
975 |
976 | if ( config.autorun && !config.blocking ) {
977 | process(last);
978 | }
979 | }
980 |
981 | function process( last ) {
982 | function next() {
983 | process( last );
984 | }
985 | var start = new Date().getTime();
986 | config.depth = config.depth ? config.depth + 1 : 1;
987 |
988 | while ( config.queue.length && !config.blocking ) {
989 | if ( !defined.setTimeout || config.updateRate <= 0 || ( ( new Date().getTime() - start ) < config.updateRate ) ) {
990 | config.queue.shift()();
991 | } else {
992 | window.setTimeout( next, 13 );
993 | break;
994 | }
995 | }
996 | config.depth--;
997 | if ( last && !config.blocking && !config.queue.length && config.depth === 0 ) {
998 | done();
999 | }
1000 | }
1001 |
1002 | function saveGlobal() {
1003 | config.pollution = [];
1004 |
1005 | if ( config.noglobals ) {
1006 | for ( var key in window ) {
1007 | if ( !hasOwn.call( window, key ) ) {
1008 | continue;
1009 | }
1010 | config.pollution.push( key );
1011 | }
1012 | }
1013 | }
1014 |
1015 | function checkPollution( name ) {
1016 | var old = config.pollution;
1017 | saveGlobal();
1018 |
1019 | var newGlobals = diff( config.pollution, old );
1020 | if ( newGlobals.length > 0 ) {
1021 | QUnit.pushFailure( "Introduced global variable(s): " + newGlobals.join(", ") );
1022 | }
1023 |
1024 | var deletedGlobals = diff( old, config.pollution );
1025 | if ( deletedGlobals.length > 0 ) {
1026 | QUnit.pushFailure( "Deleted global variable(s): " + deletedGlobals.join(", ") );
1027 | }
1028 | }
1029 |
1030 | // returns a new Array with the elements that are in a but not in b
1031 | function diff( a, b ) {
1032 | var result = a.slice();
1033 | for ( var i = 0; i < result.length; i++ ) {
1034 | for ( var j = 0; j < b.length; j++ ) {
1035 | if ( result[i] === b[j] ) {
1036 | result.splice(i, 1);
1037 | i--;
1038 | break;
1039 | }
1040 | }
1041 | }
1042 | return result;
1043 | }
1044 |
1045 | function extend(a, b) {
1046 | for ( var prop in b ) {
1047 | if ( b[prop] === undefined ) {
1048 | delete a[prop];
1049 |
1050 | // Avoid "Member not found" error in IE8 caused by setting window.constructor
1051 | } else if ( prop !== "constructor" || a !== window ) {
1052 | a[prop] = b[prop];
1053 | }
1054 | }
1055 |
1056 | return a;
1057 | }
1058 |
1059 | function addEvent(elem, type, fn) {
1060 | if ( elem.addEventListener ) {
1061 | elem.addEventListener( type, fn, false );
1062 | } else if ( elem.attachEvent ) {
1063 | elem.attachEvent( "on" + type, fn );
1064 | } else {
1065 | fn();
1066 | }
1067 | }
1068 |
1069 | function id(name) {
1070 | return !!(typeof document !== "undefined" && document && document.getElementById) &&
1071 | document.getElementById( name );
1072 | }
1073 |
1074 | function registerLoggingCallback(key){
1075 | return function(callback){
1076 | config[key].push( callback );
1077 | };
1078 | }
1079 |
1080 | // Supports deprecated method of completely overwriting logging callbacks
1081 | function runLoggingCallbacks(key, scope, args) {
1082 | //debugger;
1083 | var callbacks;
1084 | if ( QUnit.hasOwnProperty(key) ) {
1085 | QUnit[key].call(scope, args);
1086 | } else {
1087 | callbacks = config[key];
1088 | for( var i = 0; i < callbacks.length; i++ ) {
1089 | callbacks[i].call( scope, args );
1090 | }
1091 | }
1092 | }
1093 |
1094 | // Test for equality any JavaScript type.
1095 | // Author: Philippe Rathé
1096 | QUnit.equiv = (function() {
1097 |
1098 | var innerEquiv; // the real equiv function
1099 | var callers = []; // stack to decide between skip/abort functions
1100 | var parents = []; // stack to avoiding loops from circular referencing
1101 |
1102 | // Call the o related callback with the given arguments.
1103 | function bindCallbacks(o, callbacks, args) {
1104 | var prop = QUnit.objectType(o);
1105 | if (prop) {
1106 | if (QUnit.objectType(callbacks[prop]) === "function") {
1107 | return callbacks[prop].apply(callbacks, args);
1108 | } else {
1109 | return callbacks[prop]; // or undefined
1110 | }
1111 | }
1112 | }
1113 |
1114 | var getProto = Object.getPrototypeOf || function (obj) {
1115 | return obj.__proto__;
1116 | };
1117 |
1118 | var callbacks = (function () {
1119 |
1120 | // for string, boolean, number and null
1121 | function useStrictEquality(b, a) {
1122 | if (b instanceof a.constructor || a instanceof b.constructor) {
1123 | // to catch short annotaion VS 'new' annotation of a
1124 | // declaration
1125 | // e.g. var i = 1;
1126 | // var j = new Number(1);
1127 | return a == b;
1128 | } else {
1129 | return a === b;
1130 | }
1131 | }
1132 |
1133 | return {
1134 | "string" : useStrictEquality,
1135 | "boolean" : useStrictEquality,
1136 | "number" : useStrictEquality,
1137 | "null" : useStrictEquality,
1138 | "undefined" : useStrictEquality,
1139 |
1140 | "nan" : function(b) {
1141 | return isNaN(b);
1142 | },
1143 |
1144 | "date" : function(b, a) {
1145 | return QUnit.objectType(b) === "date" && a.valueOf() === b.valueOf();
1146 | },
1147 |
1148 | "regexp" : function(b, a) {
1149 | return QUnit.objectType(b) === "regexp" &&
1150 | // the regex itself
1151 | a.source === b.source &&
1152 | // and its modifers
1153 | a.global === b.global &&
1154 | // (gmi) ...
1155 | a.ignoreCase === b.ignoreCase &&
1156 | a.multiline === b.multiline;
1157 | },
1158 |
1159 | // - skip when the property is a method of an instance (OOP)
1160 | // - abort otherwise,
1161 | // initial === would have catch identical references anyway
1162 | "function" : function() {
1163 | var caller = callers[callers.length - 1];
1164 | return caller !== Object && typeof caller !== "undefined";
1165 | },
1166 |
1167 | "array" : function(b, a) {
1168 | var i, j, loop;
1169 | var len;
1170 |
1171 | // b could be an object literal here
1172 | if (QUnit.objectType(b) !== "array") {
1173 | return false;
1174 | }
1175 |
1176 | len = a.length;
1177 | if (len !== b.length) { // safe and faster
1178 | return false;
1179 | }
1180 |
1181 | // track reference to avoid circular references
1182 | parents.push(a);
1183 | for (i = 0; i < len; i++) {
1184 | loop = false;
1185 | for (j = 0; j < parents.length; j++) {
1186 | if (parents[j] === a[i]) {
1187 | loop = true;// dont rewalk array
1188 | }
1189 | }
1190 | if (!loop && !innerEquiv(a[i], b[i])) {
1191 | parents.pop();
1192 | return false;
1193 | }
1194 | }
1195 | parents.pop();
1196 | return true;
1197 | },
1198 |
1199 | "object" : function(b, a) {
1200 | var i, j, loop;
1201 | var eq = true; // unless we can proove it
1202 | var aProperties = [], bProperties = []; // collection of
1203 | // strings
1204 |
1205 | // comparing constructors is more strict than using
1206 | // instanceof
1207 | if (a.constructor !== b.constructor) {
1208 | // Allow objects with no prototype to be equivalent to
1209 | // objects with Object as their constructor.
1210 | if (!((getProto(a) === null && getProto(b) === Object.prototype) ||
1211 | (getProto(b) === null && getProto(a) === Object.prototype)))
1212 | {
1213 | return false;
1214 | }
1215 | }
1216 |
1217 | // stack constructor before traversing properties
1218 | callers.push(a.constructor);
1219 | // track reference to avoid circular references
1220 | parents.push(a);
1221 |
1222 | for (i in a) { // be strict: don't ensures hasOwnProperty
1223 | // and go deep
1224 | loop = false;
1225 | for (j = 0; j < parents.length; j++) {
1226 | if (parents[j] === a[i]) {
1227 | // don't go down the same path twice
1228 | loop = true;
1229 | }
1230 | }
1231 | aProperties.push(i); // collect a's properties
1232 |
1233 | if (!loop && !innerEquiv(a[i], b[i])) {
1234 | eq = false;
1235 | break;
1236 | }
1237 | }
1238 |
1239 | callers.pop(); // unstack, we are done
1240 | parents.pop();
1241 |
1242 | for (i in b) {
1243 | bProperties.push(i); // collect b's properties
1244 | }
1245 |
1246 | // Ensures identical properties name
1247 | return eq && innerEquiv(aProperties.sort(), bProperties.sort());
1248 | }
1249 | };
1250 | }());
1251 |
1252 | innerEquiv = function() { // can take multiple arguments
1253 | var args = Array.prototype.slice.apply(arguments);
1254 | if (args.length < 2) {
1255 | return true; // end transition
1256 | }
1257 |
1258 | return (function(a, b) {
1259 | if (a === b) {
1260 | return true; // catch the most you can
1261 | } else if (a === null || b === null || typeof a === "undefined" ||
1262 | typeof b === "undefined" ||
1263 | QUnit.objectType(a) !== QUnit.objectType(b)) {
1264 | return false; // don't lose time with error prone cases
1265 | } else {
1266 | return bindCallbacks(a, callbacks, [ b, a ]);
1267 | }
1268 |
1269 | // apply transition with (1..n) arguments
1270 | }(args[0], args[1]) && arguments.callee.apply(this, args.splice(1, args.length - 1)));
1271 | };
1272 |
1273 | return innerEquiv;
1274 |
1275 | }());
1276 |
1277 | /**
1278 | * jsDump Copyright (c) 2008 Ariel Flesler - aflesler(at)gmail(dot)com |
1279 | * http://flesler.blogspot.com Licensed under BSD
1280 | * (http://www.opensource.org/licenses/bsd-license.php) Date: 5/15/2008
1281 | *
1282 | * @projectDescription Advanced and extensible data dumping for Javascript.
1283 | * @version 1.0.0
1284 | * @author Ariel Flesler
1285 | * @link {http://flesler.blogspot.com/2008/05/jsdump-pretty-dump-of-any-javascript.html}
1286 | */
1287 | QUnit.jsDump = (function() {
1288 | function quote( str ) {
1289 | return '"' + str.toString().replace(/"/g, '\\"') + '"';
1290 | }
1291 | function literal( o ) {
1292 | return o + '';
1293 | }
1294 | function join( pre, arr, post ) {
1295 | var s = jsDump.separator(),
1296 | base = jsDump.indent(),
1297 | inner = jsDump.indent(1);
1298 | if ( arr.join ) {
1299 | arr = arr.join( ',' + s + inner );
1300 | }
1301 | if ( !arr ) {
1302 | return pre + post;
1303 | }
1304 | return [ pre, inner + arr, base + post ].join(s);
1305 | }
1306 | function array( arr, stack ) {
1307 | var i = arr.length, ret = new Array(i);
1308 | this.up();
1309 | while ( i-- ) {
1310 | ret[i] = this.parse( arr[i] , undefined , stack);
1311 | }
1312 | this.down();
1313 | return join( '[', ret, ']' );
1314 | }
1315 |
1316 | var reName = /^function (\w+)/;
1317 |
1318 | var jsDump = {
1319 | parse: function( obj, type, stack ) { //type is used mostly internally, you can fix a (custom)type in advance
1320 | stack = stack || [ ];
1321 | var parser = this.parsers[ type || this.typeOf(obj) ];
1322 | type = typeof parser;
1323 | var inStack = inArray(obj, stack);
1324 | if (inStack != -1) {
1325 | return 'recursion('+(inStack - stack.length)+')';
1326 | }
1327 | //else
1328 | if (type == 'function') {
1329 | stack.push(obj);
1330 | var res = parser.call( this, obj, stack );
1331 | stack.pop();
1332 | return res;
1333 | }
1334 | // else
1335 | return (type == 'string') ? parser : this.parsers.error;
1336 | },
1337 | typeOf: function( obj ) {
1338 | var type;
1339 | if ( obj === null ) {
1340 | type = "null";
1341 | } else if (typeof obj === "undefined") {
1342 | type = "undefined";
1343 | } else if (QUnit.is("RegExp", obj)) {
1344 | type = "regexp";
1345 | } else if (QUnit.is("Date", obj)) {
1346 | type = "date";
1347 | } else if (QUnit.is("Function", obj)) {
1348 | type = "function";
1349 | } else if (typeof obj.setInterval !== undefined && typeof obj.document !== "undefined" && typeof obj.nodeType === "undefined") {
1350 | type = "window";
1351 | } else if (obj.nodeType === 9) {
1352 | type = "document";
1353 | } else if (obj.nodeType) {
1354 | type = "node";
1355 | } else if (
1356 | // native arrays
1357 | toString.call( obj ) === "[object Array]" ||
1358 | // NodeList objects
1359 | ( typeof obj.length === "number" && typeof obj.item !== "undefined" && ( obj.length ? obj.item(0) === obj[0] : ( obj.item( 0 ) === null && typeof obj[0] === "undefined" ) ) )
1360 | ) {
1361 | type = "array";
1362 | } else {
1363 | type = typeof obj;
1364 | }
1365 | return type;
1366 | },
1367 | separator: function() {
1368 | return this.multiline ? this.HTML ? ' ' : '\n' : this.HTML ? ' ' : ' ';
1369 | },
1370 | indent: function( extra ) {// extra can be a number, shortcut for increasing-calling-decreasing
1371 | if ( !this.multiline ) {
1372 | return '';
1373 | }
1374 | var chr = this.indentChar;
1375 | if ( this.HTML ) {
1376 | chr = chr.replace(/\t/g,' ').replace(/ /g,' ');
1377 | }
1378 | return new Array( this._depth_ + (extra||0) ).join(chr);
1379 | },
1380 | up: function( a ) {
1381 | this._depth_ += a || 1;
1382 | },
1383 | down: function( a ) {
1384 | this._depth_ -= a || 1;
1385 | },
1386 | setParser: function( name, parser ) {
1387 | this.parsers[name] = parser;
1388 | },
1389 | // The next 3 are exposed so you can use them
1390 | quote: quote,
1391 | literal: literal,
1392 | join: join,
1393 | //
1394 | _depth_: 1,
1395 | // This is the list of parsers, to modify them, use jsDump.setParser
1396 | parsers: {
1397 | window: '[Window]',
1398 | document: '[Document]',
1399 | error: '[ERROR]', //when no parser is found, shouldn't happen
1400 | unknown: '[Unknown]',
1401 | 'null': 'null',
1402 | 'undefined': 'undefined',
1403 | 'function': function( fn ) {
1404 | var ret = 'function',
1405 | name = 'name' in fn ? fn.name : (reName.exec(fn)||[])[1];//functions never have name in IE
1406 | if ( name ) {
1407 | ret += ' ' + name;
1408 | }
1409 | ret += '(';
1410 |
1411 | ret = [ ret, QUnit.jsDump.parse( fn, 'functionArgs' ), '){'].join('');
1412 | return join( ret, QUnit.jsDump.parse(fn,'functionCode'), '}' );
1413 | },
1414 | array: array,
1415 | nodelist: array,
1416 | 'arguments': array,
1417 | object: function( map, stack ) {
1418 | var ret = [ ], keys, key, val, i;
1419 | QUnit.jsDump.up();
1420 | if (Object.keys) {
1421 | keys = Object.keys( map );
1422 | } else {
1423 | keys = [];
1424 | for (key in map) { keys.push( key ); }
1425 | }
1426 | keys.sort();
1427 | for (i = 0; i < keys.length; i++) {
1428 | key = keys[ i ];
1429 | val = map[ key ];
1430 | ret.push( QUnit.jsDump.parse( key, 'key' ) + ': ' + QUnit.jsDump.parse( val, undefined, stack ) );
1431 | }
1432 | QUnit.jsDump.down();
1433 | return join( '{', ret, '}' );
1434 | },
1435 | node: function( node ) {
1436 | var open = QUnit.jsDump.HTML ? '<' : '<',
1437 | close = QUnit.jsDump.HTML ? '>' : '>';
1438 |
1439 | var tag = node.nodeName.toLowerCase(),
1440 | ret = open + tag;
1441 |
1442 | for ( var a in QUnit.jsDump.DOMAttrs ) {
1443 | var val = node[QUnit.jsDump.DOMAttrs[a]];
1444 | if ( val ) {
1445 | ret += ' ' + a + '=' + QUnit.jsDump.parse( val, 'attribute' );
1446 | }
1447 | }
1448 | return ret + close + open + '/' + tag + close;
1449 | },
1450 | functionArgs: function( fn ) {//function calls it internally, it's the arguments part of the function
1451 | var l = fn.length;
1452 | if ( !l ) {
1453 | return '';
1454 | }
1455 |
1456 | var args = new Array(l);
1457 | while ( l-- ) {
1458 | args[l] = String.fromCharCode(97+l);//97 is 'a'
1459 | }
1460 | return ' ' + args.join(', ') + ' ';
1461 | },
1462 | key: quote, //object calls it internally, the key part of an item in a map
1463 | functionCode: '[code]', //function calls it internally, it's the content of the function
1464 | attribute: quote, //node calls it internally, it's an html attribute value
1465 | string: quote,
1466 | date: quote,
1467 | regexp: literal, //regex
1468 | number: literal,
1469 | 'boolean': literal
1470 | },
1471 | DOMAttrs:{//attributes to dump from nodes, name=>realName
1472 | id:'id',
1473 | name:'name',
1474 | 'class':'className'
1475 | },
1476 | HTML:false,//if true, entities are escaped ( <, >, \t, space and \n )
1477 | indentChar:' ',//indentation unit
1478 | multiline:true //if true, items in a collection, are separated by a \n, else just a space.
1479 | };
1480 |
1481 | return jsDump;
1482 | }());
1483 |
1484 | // from Sizzle.js
1485 | function getText( elems ) {
1486 | var ret = "", elem;
1487 |
1488 | for ( var i = 0; elems[i]; i++ ) {
1489 | elem = elems[i];
1490 |
1491 | // Get the text from text nodes and CDATA nodes
1492 | if ( elem.nodeType === 3 || elem.nodeType === 4 ) {
1493 | ret += elem.nodeValue;
1494 |
1495 | // Traverse everything else, except comment nodes
1496 | } else if ( elem.nodeType !== 8 ) {
1497 | ret += getText( elem.childNodes );
1498 | }
1499 | }
1500 |
1501 | return ret;
1502 | }
1503 |
1504 | //from jquery.js
1505 | function inArray( elem, array ) {
1506 | if ( array.indexOf ) {
1507 | return array.indexOf( elem );
1508 | }
1509 |
1510 | for ( var i = 0, length = array.length; i < length; i++ ) {
1511 | if ( array[ i ] === elem ) {
1512 | return i;
1513 | }
1514 | }
1515 |
1516 | return -1;
1517 | }
1518 |
1519 | /*
1520 | * Javascript Diff Algorithm
1521 | * By John Resig (http://ejohn.org/)
1522 | * Modified by Chu Alan "sprite"
1523 | *
1524 | * Released under the MIT license.
1525 | *
1526 | * More Info:
1527 | * http://ejohn.org/projects/javascript-diff-algorithm/
1528 | *
1529 | * Usage: QUnit.diff(expected, actual)
1530 | *
1531 | * QUnit.diff("the quick brown fox jumped over", "the quick fox jumps over") == "the quick brown fox jumped jumps over"
1532 | */
1533 | QUnit.diff = (function() {
1534 | function diff(o, n) {
1535 | var ns = {};
1536 | var os = {};
1537 | var i;
1538 |
1539 | for (i = 0; i < n.length; i++) {
1540 | if (ns[n[i]] == null) {
1541 | ns[n[i]] = {
1542 | rows: [],
1543 | o: null
1544 | };
1545 | }
1546 | ns[n[i]].rows.push(i);
1547 | }
1548 |
1549 | for (i = 0; i < o.length; i++) {
1550 | if (os[o[i]] == null) {
1551 | os[o[i]] = {
1552 | rows: [],
1553 | n: null
1554 | };
1555 | }
1556 | os[o[i]].rows.push(i);
1557 | }
1558 |
1559 | for (i in ns) {
1560 | if ( !hasOwn.call( ns, i ) ) {
1561 | continue;
1562 | }
1563 | if (ns[i].rows.length == 1 && typeof(os[i]) != "undefined" && os[i].rows.length == 1) {
1564 | n[ns[i].rows[0]] = {
1565 | text: n[ns[i].rows[0]],
1566 | row: os[i].rows[0]
1567 | };
1568 | o[os[i].rows[0]] = {
1569 | text: o[os[i].rows[0]],
1570 | row: ns[i].rows[0]
1571 | };
1572 | }
1573 | }
1574 |
1575 | for (i = 0; i < n.length - 1; i++) {
1576 | if (n[i].text != null && n[i + 1].text == null && n[i].row + 1 < o.length && o[n[i].row + 1].text == null &&
1577 | n[i + 1] == o[n[i].row + 1]) {
1578 | n[i + 1] = {
1579 | text: n[i + 1],
1580 | row: n[i].row + 1
1581 | };
1582 | o[n[i].row + 1] = {
1583 | text: o[n[i].row + 1],
1584 | row: i + 1
1585 | };
1586 | }
1587 | }
1588 |
1589 | for (i = n.length - 1; i > 0; i--) {
1590 | if (n[i].text != null && n[i - 1].text == null && n[i].row > 0 && o[n[i].row - 1].text == null &&
1591 | n[i - 1] == o[n[i].row - 1]) {
1592 | n[i - 1] = {
1593 | text: n[i - 1],
1594 | row: n[i].row - 1
1595 | };
1596 | o[n[i].row - 1] = {
1597 | text: o[n[i].row - 1],
1598 | row: i - 1
1599 | };
1600 | }
1601 | }
1602 |
1603 | return {
1604 | o: o,
1605 | n: n
1606 | };
1607 | }
1608 |
1609 | return function(o, n) {
1610 | o = o.replace(/\s+$/, '');
1611 | n = n.replace(/\s+$/, '');
1612 | var out = diff(o === "" ? [] : o.split(/\s+/), n === "" ? [] : n.split(/\s+/));
1613 |
1614 | var str = "";
1615 | var i;
1616 |
1617 | var oSpace = o.match(/\s+/g);
1618 | if (oSpace == null) {
1619 | oSpace = [" "];
1620 | }
1621 | else {
1622 | oSpace.push(" ");
1623 | }
1624 | var nSpace = n.match(/\s+/g);
1625 | if (nSpace == null) {
1626 | nSpace = [" "];
1627 | }
1628 | else {
1629 | nSpace.push(" ");
1630 | }
1631 |
1632 | if (out.n.length === 0) {
1633 | for (i = 0; i < out.o.length; i++) {
1634 | str += '' + out.o[i] + oSpace[i] + "";
1635 | }
1636 | }
1637 | else {
1638 | if (out.n[0].text == null) {
1639 | for (n = 0; n < out.o.length && out.o[n].text == null; n++) {
1640 | str += '' + out.o[n] + oSpace[n] + "";
1641 | }
1642 | }
1643 |
1644 | for (i = 0; i < out.n.length; i++) {
1645 | if (out.n[i].text == null) {
1646 | str += '' + out.n[i] + nSpace[i] + " ";
1647 | }
1648 | else {
1649 | var pre = "";
1650 |
1651 | for (n = out.n[i].row + 1; n < out.o.length && out.o[n].text == null; n++) {
1652 | pre += '' + out.o[n] + oSpace[n] + "";
1653 | }
1654 | str += " " + out.n[i].text + nSpace[i] + pre;
1655 | }
1656 | }
1657 | }
1658 |
1659 | return str;
1660 | };
1661 | }());
1662 |
1663 | // for CommonJS enviroments, export everything
1664 | if ( typeof exports !== "undefined" || typeof require !== "undefined" ) {
1665 | extend(exports, QUnit);
1666 | }
1667 |
1668 | // get at whatever the global object is, like window in browsers
1669 | }( (function() {return this;}.call()) ));
1670 |
--------------------------------------------------------------------------------
/test/test-attr-mangler.js:
--------------------------------------------------------------------------------
1 | defineTests([
2 | "falafel",
3 | "slowmo/attr-mangler"
4 | ], function(falafel, AttrMangler) {
5 | var code, log, rangeLog;
6 | var attr = {
7 | get: function(obj, prop, range) {
8 | log.push(["get", obj, prop]);
9 | rangeLog.push(code.slice.apply(code, range));
10 | return obj[prop];
11 | },
12 | update: function(obj, prop, operator, prefix, range) {
13 | log.push(["update", obj, prop, operator, prefix]);
14 | rangeLog.push(code.slice.apply(code, range));
15 | return obj[prop] + 1;
16 | },
17 | assign: function(obj, prop, operator, value, range) {
18 | log.push(["assign", obj, prop, operator, value]);
19 | rangeLog.push(code.slice.apply(code, range));
20 | return value;
21 | }
22 | };
23 |
24 | module("attr-mangler", {
25 | setup: function() {
26 | log = [];
27 | rangeLog = [];
28 | }
29 | });
30 |
31 | test("get works w/ computed properties", function() {
32 | var a = {b: "value"};
33 | var foo = "b";
34 | code = "a[foo];";
35 | var mangled = falafel(code, AttrMangler).toString();
36 | equal(eval(mangled), "value");
37 | deepEqual(log, [["get", a, foo]]);
38 | deepEqual(rangeLog, ['a[foo]']);
39 | });
40 |
41 | test("get works w/ non-computed properties", function() {
42 | var a = {b: "value"};
43 | code = "a.b;";
44 | var mangled = falafel(code, AttrMangler).toString();
45 | equal(eval(mangled), "value");
46 | deepEqual(log, [["get", a, "b"]]);
47 | deepEqual(rangeLog, ['a.b']);
48 | });
49 |
50 | test("update works w/ computed properties", function() {
51 | var a = {b: 5};
52 | var foo = "b";
53 | code = "++a[foo];";
54 | var mangled = falafel(code, AttrMangler).toString();
55 | equal(eval(mangled), 6);
56 | deepEqual(log, [["update", a, foo, "++", true]]);
57 | deepEqual(rangeLog, ['++a[foo]']);
58 | });
59 |
60 | test("update works w/ non-computed properties", function() {
61 | var a = {b: 5};
62 | code = "++a.b;";
63 | var mangled = falafel(code, AttrMangler).toString();
64 | equal(eval(mangled), 6);
65 | deepEqual(log, [["update", a, "b", "++", true]]);
66 | deepEqual(rangeLog, ['++a.b']);
67 | });
68 |
69 | test("assignment works w/ computed properties", function() {
70 | var a = {};
71 | code = "a['b'] = 3;";
72 | var mangled = falafel(code, AttrMangler).toString();
73 | equal(eval(mangled), 3);
74 | deepEqual(log, [["assign", a, "b", "=", 3]]);
75 | deepEqual(rangeLog, ["a['b'] = 3"]);
76 | });
77 |
78 | test("assignment works w/ non-computed properties", function() {
79 | var a = {};
80 | code = "a.b = 3;";
81 | var mangled = falafel(code, AttrMangler).toString();
82 | equal(eval(mangled), 3);
83 | deepEqual(log, [["assign", a, "b", "=", 3]]);
84 | deepEqual(rangeLog, ["a.b = 3"]);
85 | });
86 | });
87 |
--------------------------------------------------------------------------------
/test/test-attr.js:
--------------------------------------------------------------------------------
1 | defineTests([
2 | "falafel",
3 | "slowmo/attr-mangler",
4 | "slowmo/attr"
5 | ], function(falafel, AttrMangler, Attr) {
6 | module("attr");
7 |
8 | function attrTest(options) {
9 | var code = options.code;
10 | var result = options.result;
11 |
12 | if (Array.isArray(code))
13 | code = code.join('\n');
14 |
15 | return function() {
16 | var mangled = falafel(code, AttrMangler).toString();
17 | var attr = new Attr(function log() {});
18 |
19 | deepEqual(eval(mangled), options.result,
20 | "eval of " + JSON.stringify(code) + " should be " +
21 | JSON.stringify(result));
22 | }
23 | }
24 |
25 | test("array prototype methods should work", attrTest({
26 | code: "[1,2,3].map(function(n) { return 'hi' + n; });",
27 | result: ['hi1', 'hi2', 'hi3']
28 | }));
29 | });
30 |
--------------------------------------------------------------------------------
/test/test-loop-inserter.js:
--------------------------------------------------------------------------------
1 | defineTests([
2 | "falafel",
3 | "slowmo/loop-inserter"
4 | ], function(falafel, LoopInserter) {
5 | module("loop-inserter");
6 |
7 | function testLoop(code) {
8 | var checkCalled = 0;
9 | var check = function() {
10 | checkCalled++;
11 | };
12 | var mangled = falafel(code, LoopInserter("check")).toString();
13 |
14 | eval(mangled);
15 | equal(checkCalled, 3, "check() is called 3 times");
16 | equal(i, 3, "i is 3");
17 | }
18 |
19 | test("works with for loops", function() {
20 | testLoop("for (var i = 0; i < 3; i++) {}");
21 | });
22 |
23 | test("works w/ for loops w/ empty conditions", function() {
24 | testLoop("for (var i = 0;; i++) { if (i >= 2) { i++; break;} }");
25 | });
26 |
27 | test("works with while loops", function() {
28 | testLoop("var i = 0; while (i < 3) { i++; }");
29 | });
30 |
31 | test("works with do..while loops", function() {
32 | testLoop("var i = 0; do { i++; } while (i < 3)");
33 | });
34 |
35 | test("can take a function w/ node as arg", function() {
36 | var log = [];
37 | var logLoop = function(range) {
38 | log.push(range);
39 | };
40 | var code = "/* */ for (var i = 0; i < 1; i++) {}";
41 | var mangled = falafel(code, LoopInserter(function(node) {
42 | return "logLoop(" + JSON.stringify(node.range) + ");";
43 | })).toString();
44 |
45 | eval(mangled);
46 | deepEqual(log, [[6, 36]]);
47 | });
48 | });
49 |
--------------------------------------------------------------------------------
/test/test-scope-mangler.js:
--------------------------------------------------------------------------------
1 | defineTests([
2 | "falafel",
3 | "slowmo/scope-mangler"
4 | ], function(falafel, ScopeMangler) {
5 | module("scope-mangler");
6 |
7 | function declTest(code, expectedDecls) {
8 | var decls = [];
9 | var scope = {
10 | declare: function(name, value, range) {
11 | var slice = range ? code.slice.apply(code, range) : null;
12 | decls.push([name, value, slice]);
13 | },
14 | leave: function() {}
15 | };
16 | var Scope = function(prev, name, range) {
17 | equal(typeof(name), "string", "scope name is string: " + name);
18 | ok(Array.isArray(range) && range.length == 2,
19 | "range is passed to scope constructor");
20 | return scope;
21 | };
22 | var mangled = falafel(code, ScopeMangler).toString();
23 | var retval = eval(mangled);
24 | if (typeof(expectedDecls) == "function") {
25 | expectedDecls(decls);
26 | return retval;
27 | }
28 | deepEqual(decls, expectedDecls,
29 | "var declarations are as expected for " + code);
30 | return retval;
31 | }
32 |
33 | function isUnchanged(code) {
34 | var mangled = falafel(code, ScopeMangler).toString();
35 | equal(code, mangled, "mangled code is same as original");
36 | eval(mangled);
37 | ok(true, "evals w/o throwing");
38 | }
39 |
40 | test("constructors still work", function() {
41 | function Thing(x) { this.x = x; }
42 | Thing.prototype = {
43 | bleh: 20
44 | };
45 | var code = "new Foo(5)";
46 | var scope = {
47 | get: function(name, range) {
48 | return Thing;
49 | }
50 | };
51 | var mangled = falafel(code, ScopeMangler).toString();
52 | var retval = eval(mangled);
53 | ok(retval instanceof Thing);
54 | equal(retval.x, 5);
55 | equal(retval.bleh, 20);
56 | });
57 |
58 | test("var decls return undefined", function() {
59 | var retval = declTest("var i = 1;", [["i", 1, "i = 1"]]);
60 | deepEqual(retval, undefined, "var decls always return undefined");
61 | });
62 |
63 | test("function decls are converted to var decls", function() {
64 | var retval = declTest("function foo(x) {}\n(1);", function(decls) {
65 | equal(decls.length, 1);
66 | equal(decls[0][0], "foo");
67 | equal(typeof decls[0][1], "function");
68 | equal(decls[0][2], "function foo(x) {}");
69 | });
70 | equal(retval, 1);
71 | });
72 |
73 | test("function args are converted to decls", function() {
74 | declTest("(function(x) {})(1);", [["arguments", {"0": 1}, null],
75 | ["x", 1, "x"]]);
76 | declTest("(function(x) {})();", [["arguments", {}, null],
77 | ["x", undefined, "x"]]);
78 | });
79 |
80 | test("function names are part of their scopes", function() {
81 | declTest("(function foo() {})();", function(expectedDecls) {
82 | equal(expectedDecls[1][0], "foo", "decl exists");
83 | equal(expectedDecls[1][2], "foo",
84 | "decl origin in code should be the function name");
85 | });
86 | });
87 |
88 | test("var decls w/ initializers work", function() {
89 | declTest("var i = 1;", [["i", 1, "i = 1"]]);
90 | });
91 |
92 | test("var decls w/o initializers work", function() {
93 | declTest("var i;", [["i", undefined, "i"]]);
94 | });
95 |
96 | test("var decls w/ commas work", function() {
97 | declTest("var i, j = 2;", [["i", undefined, "i"], ["j", 2, "j = 2"]]);
98 | });
99 |
100 | test("var decls w/ commas work with value first", function() {
101 | declTest("var i = 3, j = 2;", [["i", 3, "i = 3"], ["j", 2, "j = 2"]]);
102 | });
103 |
104 | test("multiple var decls work", function() {
105 | declTest("var i; var j = 2;",
106 | [["i", undefined, "i"], ["j", 2, "j = 2"]]);
107 | });
108 |
109 | test("var decls w/o semicolons afterwards work", function() {
110 | declTest("var a = 1\n1+2;", [["a", 1, "a = 1"]]);
111 | });
112 |
113 | test("var decls in for loops work", function() {
114 | declTest("for (var i = 0; false; i++) {}", [["i", 0, "i = 0"]]);
115 | });
116 |
117 | test("property names in object literals stay intact", function() {
118 | isUnchanged("({x: 3});");
119 | });
120 |
121 | test("property names in member expressions stay intact", function() {
122 | isUnchanged('"blarg".length;');
123 | });
124 |
125 | test("update expressions work", function() {
126 | var code = "a++;";
127 | var expectedUpdates = [["a", "++", false, "a++"]];
128 | var expectedRetval = 50;
129 |
130 | var updates = [];
131 | var scope = {
132 | update: function(name, operator, prefix, range) {
133 | var slice = code.slice.apply(code, range);
134 | updates.push([name, operator, prefix, slice]);
135 | return expectedRetval;
136 | }
137 | };
138 | var mangled = falafel(code, ScopeMangler).toString();
139 | deepEqual(eval(mangled), expectedRetval,
140 | "return value of " + code + " is " + expectedRetval);
141 | deepEqual(updates, expectedUpdates,
142 | "updates are as expected for " + code);
143 | });
144 |
145 | test("assignment expressions work", function() {
146 | var code = "a = 50;";
147 | var expectedAssignments = [["a", "=", 50, "a = 50"]];
148 | var expectedRetval = 50;
149 |
150 | var assignments = [];
151 | var scope = {
152 | assign: function(name, operator, value, range) {
153 | var slice = code.slice.apply(code, range);
154 | assignments.push([name, operator, value, slice]);
155 | return value;
156 | }
157 | };
158 | var mangled = falafel(code, ScopeMangler).toString();
159 | deepEqual(eval(mangled), expectedRetval,
160 | "return value of " + code + " is " + expectedRetval);
161 | deepEqual(assignments, expectedAssignments,
162 | "assignments are as expected for " + code);
163 | });
164 |
165 | test("typeof works", function() {
166 | var code = " typeof foo;";
167 | var scope = {
168 | getTypeOf: function(name, range) {
169 | equal(name, "foo");
170 | deepEqual(code.slice.apply(code, range), "typeof foo");
171 | return "superthingy";
172 | }
173 | };
174 | var mangled = falafel(code, ScopeMangler).toString();
175 | var result = eval(mangled);
176 | deepEqual(result, "superthingy");
177 | });
178 |
179 | test("scopes are chained", function() {
180 | var code = "(function foo() { return (function bar() {})() })()";
181 | var scopes = [];
182 | var scopeLeaves = [];
183 | var Scope = function Scope(prev, name, range) {
184 | scopes.push({
185 | previous: prev && prev.name,
186 | name: name,
187 | code: code.slice.apply(code, range)
188 | });
189 | return {
190 | name: name,
191 | declare: function() {},
192 | leave: function() {
193 | scopeLeaves.push(name);
194 | }
195 | };
196 | };
197 | var scope = Scope(null, "GLOBAL", [0, code.length]);
198 | var mangled = falafel(code, ScopeMangler).toString();
199 | eval(mangled);
200 | deepEqual(scopes, [
201 | {
202 | "name": "GLOBAL",
203 | "previous": null,
204 | "code": code
205 | },
206 | {
207 | "name": "foo",
208 | "previous": "GLOBAL",
209 | "code": "function foo() { return (function bar() {})() }"
210 | },
211 | {
212 | "name": "bar",
213 | "previous": "foo",
214 | "code": "function bar() {}"
215 | }
216 | ]);
217 | deepEqual(scopeLeaves, ["bar", "foo"],
218 | "scope.leave() is called in expected order");
219 | });
220 | });
221 |
--------------------------------------------------------------------------------
/test/test-scope.js:
--------------------------------------------------------------------------------
1 | defineTests([
2 | "falafel",
3 | "slowmo/scope-mangler",
4 | "slowmo/scope"
5 | ], function(falafel, ScopeMangler, Scope) {
6 | module("scope");
7 |
8 | function scopeTest(options) {
9 | var code = options.code;
10 | var result = options.result;
11 |
12 | if (Array.isArray(code))
13 | code = code.join('\n');
14 |
15 | return function() {
16 | var mangled = falafel(code, ScopeMangler).toString();
17 | var scope = new Scope(null, "GLOBAL");
18 |
19 | equal(eval(mangled), options.result,
20 | "eval of " + JSON.stringify(code) + " should be " +
21 | JSON.stringify(result));
22 | }
23 | }
24 |
25 | test("for loops should work", scopeTest({
26 | code: 'var a = ""; for (var v = 0; v < 3; v++) { a += v; } a',
27 | result: "012"
28 | }));
29 |
30 | test("'this' should work in for-each loops", scopeTest({
31 | code: [
32 | 'var obj = {a: ""};',
33 | '(function() { for (var v in [1,2,3]) { this.a += v; } }).call(obj);',
34 | 'obj.a'
35 | ],
36 | result: "012"
37 | }));
38 |
39 | test("for-each loops w/ var decls in left should work", scopeTest({
40 | code: 'var a = ""; for (var v in [1,2,3]) { a+= v; } a',
41 | result: "012"
42 | }));
43 |
44 | test("for-each loops should work", scopeTest({
45 | code: 'var v, a = ""; for (v in [1,2,3]) { a+= v; } a',
46 | result: "012"
47 | }));
48 |
49 | test("typeof should work with undeclared vars", scopeTest({
50 | code: "typeof foo",
51 | result: "undefined"
52 | }));
53 |
54 | test("arguments.callee should work", scopeTest({
55 | code: ["(function(i) {",
56 | " return i < 3 ? i : i * arguments.callee(i - 1)",
57 | "})(4)"],
58 | result: 24
59 | }));
60 |
61 | test("recursive function expressions should work", scopeTest({
62 | code: ["(function fac(i) {",
63 | " return i < 3 ? i : i * fac(i - 1)",
64 | "})(4)"],
65 | result: 24
66 | }));
67 | });
68 |
--------------------------------------------------------------------------------
/tipsy.css:
--------------------------------------------------------------------------------
1 | .tipsy { font-size: 10px; position: absolute; padding: 5px; z-index: 100000; }
2 | .tipsy-inner { background-color: #000; color: #FFF; max-width: 200px; padding: 5px 8px 4px 8px; text-align: center; }
3 |
4 | /* Rounded corners */
5 | .tipsy-inner { border-radius: 3px; -moz-border-radius: 3px; -webkit-border-radius: 3px; }
6 |
7 | /* Uncomment for shadow */
8 | /*.tipsy-inner { box-shadow: 0 0 5px #000000; -webkit-box-shadow: 0 0 5px #000000; -moz-box-shadow: 0 0 5px #000000; }*/
9 |
10 | .tipsy-arrow { position: absolute; width: 0; height: 0; line-height: 0; border: 5px dashed #000; }
11 |
12 | /* Rules to colour arrows */
13 | .tipsy-arrow-n { border-bottom-color: #000; }
14 | .tipsy-arrow-s { border-top-color: #000; }
15 | .tipsy-arrow-e { border-left-color: #000; }
16 | .tipsy-arrow-w { border-right-color: #000; }
17 |
18 | .tipsy-n .tipsy-arrow { top: 0px; left: 50%; margin-left: -5px; border-bottom-style: solid; border-top: none; border-left-color: transparent; border-right-color: transparent; }
19 | .tipsy-nw .tipsy-arrow { top: 0; left: 10px; border-bottom-style: solid; border-top: none; border-left-color: transparent; border-right-color: transparent;}
20 | .tipsy-ne .tipsy-arrow { top: 0; right: 10px; border-bottom-style: solid; border-top: none; border-left-color: transparent; border-right-color: transparent;}
21 | .tipsy-s .tipsy-arrow { bottom: 0; left: 50%; margin-left: -5px; border-top-style: solid; border-bottom: none; border-left-color: transparent; border-right-color: transparent; }
22 | .tipsy-sw .tipsy-arrow { bottom: 0; left: 10px; border-top-style: solid; border-bottom: none; border-left-color: transparent; border-right-color: transparent; }
23 | .tipsy-se .tipsy-arrow { bottom: 0; right: 10px; border-top-style: solid; border-bottom: none; border-left-color: transparent; border-right-color: transparent; }
24 | .tipsy-e .tipsy-arrow { right: 0; top: 50%; margin-top: -5px; border-left-style: solid; border-right: none; border-top-color: transparent; border-bottom-color: transparent; }
25 | .tipsy-w .tipsy-arrow { left: 0; top: 50%; margin-top: -5px; border-right-style: solid; border-left: none; border-top-color: transparent; border-bottom-color: transparent; }
26 |
--------------------------------------------------------------------------------