[Pkg-javascript-commits] [list.js] 01/05: Imported Upstream version 1.1.1~dfsg1
Alexandre Viau
aviau at moszumanska.debian.org
Wed Dec 30 02:58:18 UTC 2015
This is an automated email from the git hooks/post-receive script.
aviau pushed a commit to branch master
in repository list.js.
commit 17180e6cbaadd0cf97f4c4e12721f8950e01d0ba
Author: aviau <alexandre at alexandreviau.net>
Date: Tue Dec 29 21:24:54 2015 -0500
Imported Upstream version 1.1.1~dfsg1
---
.gitignore | 5 +
Gruntfile.js | 101 +
History.md | 84 +
README.md | 88 +
bower.json | 28 +
component.json | 44 +
index.js | 226 ++
package.json | 29 +
src/add-async.js | 15 +
src/filter.js | 29 +
src/item.js | 54 +
src/parse.js | 45 +
src/search.js | 119 +
src/sort.js | 101 +
src/templater.js | 96 +
test/fixtures.js | 56 +
test/index.html | 56 +
test/mocha.js | 5341 +++++++++++++++++++++++++++++++++++++++++++
test/test.add-get-remove.js | 97 +
test/test.buttons.js | 191 ++
test/test.create.js | 89 +
test/test.defaults.js | 65 +
test/test.filter.js | 101 +
test/test.item.js | 146 ++
test/test.off.js | 39 +
test/test.on.js | 123 +
test/test.parse.js | 48 +
test/test.search-filter.js | 66 +
test/test.search.js | 114 +
test/test.show.js | 208 ++
test/test.sort.js | 320 +++
test/test.trigger.js | 21 +
32 files changed, 8145 insertions(+)
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..3a2312e
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,5 @@
+.DS_Store
+lab/
+components
+build
+node_modules
diff --git a/Gruntfile.js b/Gruntfile.js
new file mode 100644
index 0000000..4871881
--- /dev/null
+++ b/Gruntfile.js
@@ -0,0 +1,101 @@
+module.exports = function(grunt) {
+ "use strict";
+
+ grunt.initConfig({
+ pkg: require("./package.json"),
+ watch: {
+ scripts: {
+ files: ['{,*/}*.js', '*.js', 'test/*.html', 'test/*.js'],
+ tasks: ['default'],
+ options: {
+ spawn: false,
+ },
+ },
+ },
+ shell: {
+ install: {
+ command: 'component install --dev',
+ options: {
+ stderr: true
+ }
+ },
+ build: {
+ command: 'component build --dev',
+ options: {
+ stderr: true
+ }
+ },
+ standalone: {
+ command: 'component build --standalone List -n list.standalone'
+ },
+ mkdir: {
+ command: 'mkdir -p dist'
+ },
+ move: {
+ command: 'mv build/list.standalone.js dist/list.js'
+ },
+ remove: {
+ command: 'rm -fr build components dist'
+ }
+ },
+ jshint: {
+ code: {
+ src: ['Gruntfile.js', '*.js', 'src/*.js'],
+ options: {
+ expr: true,
+ multistr: false,
+ globals: {
+ module: true
+ }
+ }
+ },
+ tests: {
+ src: ['test/(*|!mocha).js'],
+ options: {
+ expr: true,
+ multistr: true,
+ globals: {
+ jQuery: true,
+ module: true
+ }
+ }
+ }
+ },
+ uglify: {
+ target: {
+ files: {
+ 'dist/list.min.js': ['dist/list.js']
+ }
+ }
+ },
+ mocha: {
+ cool: {
+ src: [ 'test/index.html' ],
+ options: {
+ run: true,
+ timeout: 10000,
+ bail: false,
+ log: true,
+ reporter: 'Nyan',
+ mocha: {
+ ignoreLeaks: false
+ }
+ }
+ }
+ }
+ });
+
+ grunt.loadNpmTasks("grunt-contrib-watch");
+ grunt.loadNpmTasks('grunt-shell');
+ grunt.loadNpmTasks('grunt-contrib-uglify');
+ grunt.loadNpmTasks('grunt-contrib-jshint');
+ grunt.loadNpmTasks('grunt-mocha');
+
+ grunt.registerTask('default', ['jshint:code', 'jshint:tests', 'shell:install', 'shell:build']);
+ grunt.registerTask('dist', ['default', 'shell:standalone', 'shell:mkdir', 'shell:move', 'uglify']);
+ grunt.registerTask('clean', ['shell:remove']);
+
+ grunt.registerTask('test', ['mocha']);
+
+ return grunt;
+};
diff --git a/History.md b/History.md
new file mode 100644
index 0000000..83c8652
--- /dev/null
+++ b/History.md
@@ -0,0 +1,84 @@
+# Changelog
+
+### 2014-02-03: 1.1.1
+- *[Bugfix]* Update `javve/events` version which fixes critical bugs in Safari for PC and PhantomJS (which makes the command line tests work again).
+- *[Bugfix]* Clear search when clicking in the HTML5 clear button.
+- *[Misc]* Add History.md file for changelog instead of having it at Listjs.com.
+
+### 2014-02-03: 1.1.0
+- *[Change]* The sorting API is update so it looks like this `listObj.sort('name', { order: "asc "})` and `listObj.sort('name', { order: "desc "})` instead or `listObj.sort('name', { desc: true/false })`.
+- *[Feature]* Added support for default sort function `new List('id', { sortFunction: function(itemA, itemB) { .. }})</
+- *[Feature]* Adding `data-order="asc/desc"` to a sort button makes that button only sort `asc` or `desc`, ie no to
+- *[Bugfix]* Fix `grunt watch` bug.
+- *[Bugfix]* Remove sorting when searching and filtering.
+- *[Bugfix]* Fix sorting and search when using pagiation plugin
+
+
+### 2014-01-17: 1.0.2
+- *[Bugfix]* Fix error that broke the lib in IE8.
+
+### 2013-11-12: 1.0.0
+- *[Feature]* Add more events and enable to add them on initialization.
+- *[Feature]* Add support for Component.js, Bower, RequireJS and CommonJS
+- *[Feature]* Make it possible to remove event handlers by `.off('event', handler)`
+- *[Improvement]* Many new tests
+- *[Improvement]* Paging plugin default classes and structure now correspons to <a href="http://twitter.github.com/bootstrap/components.html#pagination">Twitter Bootstraps pagination</a>.
+- *[Improvement]* Make sorting case-insensitive (thanks @thomasklemm)
+- *[Improvement]* Add item._values for direct access to a items values. Simplifies debugging. Note: Always use item.values() when interacting with the values.
+- *[Bugfix]* `.add(items, callbak)` with `callback` set does no longer add an extra item.
+- *[Bugfix]* `templater.set()` no longer is called twice in a `templater.get()` call.
+- *[Bugfix]* Fix error when trying to sort `undefined,null,etc` values.
+- *[Bugfix]* Fix error when trying to search `undefined,null,etc` values.
+- *[Bugfix]* Fix issue #51, problems with filters/search + paging.
+- *[Misc]* Almost completely rewritten codebase and started using <a href="https://github.com/component/component">Component</a>
+- *[Misc]* Moved the website into another repo called <a href="https://github.com/javve/list-website">list-website</a>
+- *[Misc]* Add documentation for searching in specific columns.
+- *[Change]* `listObj.get('valueName', value)` does now always returns an array. Previously it return an object if only one item matched and null if no match was found.
+- *[Change]* The default sort order is now `asc` instead of `desc`.
+- *[Change]* Syntax for searching in specific columns are now `.search('val', [ 'columnName', 'columnName2' ])` instead of `.search('val', { columnName: true, columnName2: true })`.
+- *[Change]* Move plugins into seperated repos: <a href="https://github.com/javve/list.pagination.js">github.com/javve/list.pagination.js</a> and <a href="https://github.com/javve/list.fuzzysearch.js">github.com/javve/list.fuzzysearch.js</a>
+- *[Change]* Plugin initiation have changed. See <a href="/docs/plugins">getting started with plugins
+
+
+### 2012-04-24: 0.2.1
+- Fuzzy Search plugin, `.filter()` changes and bug fixes *[Read more »](http://jonnystromberg.com/listjs-0-2-1-release-notes/)*
+
+### 2012-01-23: 0.2.0
+- Lots of updates and interesting features. *[Read more »](http://jonnystromberg.com/listjs-0-2-0-plugins-paging/)*
+
+### 2011-12-15: 0.1.4
+- `.filters()`, `.sort()` and `.search()` now deped on each other. If the list is filtered and then there is a search, the items hidden by the filters will stay hidden etc.
+- `.filter()` is the only way to reset filter. `.filter(false)` does not work anymore.
+
+### 2011-11-29: 0.1.3 release
+- Added function `.clear()` that removes all items from the list
+- Changed the sort function to be based on `data-sort` instead of `rel`
+- When sorting one category, all sort-related classes will be removed from the other sort buttons
+- Updated `.sort(valueName, sortFunction)` to `.sort(valueName, options)`, se more info in the documentation
+
+### 2011-11-16: 0.1.2 release
+- Sorting is now indicated by class `asc` or `desc` at sorting buttons
+- Added three new small helper functions `hasClass(element, class)`, `addClass(element, class)</
+ and `removeClass(element, class)`</li>
+
+### 2011-10-20: 0.1.1 release
+- Added possibility to reverse sort the list
+
+### 2011-10-18: 0.1 release
+- Examples at Listjs.com works in IE7,8,9 (IE6 is not tested, should work)
+- More documentation
+- Misc bug fixes
+
+### 2011-10-15 Final alpha 0.3 release
+- More documentation
+- Only show 200 items at same time, huge speed increase
+- Misc bug fixes
+
+### 2011-08-08 Alpha 0.2 release
+- Added asynchronous item adding
+- Added asynchronous list indexing
+- Improved (but incomplete) documentation
+- Bugfixes and improved helper functions
+- Show helper functions non-minified
+
+### 2011-07-25 Alpha 0.1 release
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..5122699
--- /dev/null
+++ b/README.md
@@ -0,0 +1,88 @@
+# List.js
+Perfect library for adding **search**, **sort**, **filters** and **flexibility** to
+**tables**, **lists** and various HTML elements. Built to be invisible and work on existing HTML.
+Really simple and easy to use!
+
+[![Donate](https://s3.amazonaws.com/listjs/donate-coffee.png)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=M7ZGHV75VSD2E)
+
+### Core idea
+- Simple and invisible
+- Easy to apply to existing HTML
+- No dependencies
+- Fast
+- Small
+- Handle thousands of items
+
+### Features
+- Works both lists, tables and almost anything else. E.g. `<div>`,`<ul>`,`<table>`, etc.
+- Search [Read more ›](http://listjs.com/docs/list-api#search)
+- Sort [Read more ›](http://listjs.com/docs/list-api#sort)
+- Filter [Read more ›](http://listjs.com/docs/list-api#filter)
+- Simple templating system that adds possibility to add, edit, remove items [Read more ›](http://listjs.com/docs/list-api#add)
+- Plugins [Read more ›](http://listjs.com/docs/plugins)
+- Support for Chrome, Safari, Firefox, IE6+
+
+### Demo / Examples
+- [Existing list](http://listjs.com/examples/existing-list)
+- [Existing list + add](http://listjs.com/examples/existing-list-add)
+- [New list](http://listjs.com/examples/new-list)
+- [Add, get, remove](http://listjs.com/examples/add-get-remove)
+- [Fuzzy search](http://listjs.com/examples/fuzzy-search)
+- [Pagination](http://listjs.com/examples/pagination)
+
+## Documentation
+- [Getting started](http://listjs.com/docs)
+- [Options](http://listjs.com/docs/options)
+- [List API](http://listjs.com/docs/list-api)
+- [Item API](http://listjs.com/docs/item-api)
+- [Changelog](http://listjs.com/overview/changelog)
+
+### Plugins
+- [Introduction](http://listjs.com/docs/plugins)
+- [Pagination](http://listjs.com/docs/plugins/pagination)
+- [Fuzzy search](http://listjs.com/docs/plugins/fuzzysearch)
+- [Build your own](http://listjs.com/docs/plugins/build)
+
+### Known issues
+- Sorting fails with some UTF8 characters. Example: `åä`, thinking that `ä` is before `å`.
+- Tables row items can't be created with the `{ item: '<html>' }`-method.
+
+
+## Contributors
+* [javve](https://github.com/javve) / [Jonny Strömberg](http://jonnystromberg.com)
+* [lusentis](https://github.com/lusentis) / [Simone Lusenti](http://www.plasticpanda.com)
+* [dancrew32](https://github.com/dancrew32) / [Dan Masquelier](http://danmasq.com)
+* [himynameisjonas](https://github.com/himynameisjonas) / [Jonas Forsberg](http://jonasforsberg.se)
+* [LuukvE](https://github.com/LuukvE) [Luuk van Egeraat](http://luukvanegeraat.com/)
+* [endorama](https://github.com/endorama) / Edoardo Tenani
+* [sprynmr](https://github.com/sprynmr) / Bob Spryn
+* [francescolaffi](https://github.com/francescolaffi)
+* [ryantanner](https://github.com/ryantanner)
+* [idlefella](https://github.com/idlefella)
+* [julienbechade](https://github.com/julienbechade) / [Julien Béchade/](http://julienbechade.com/)
+* [matthewheston](https://github.com/matthewheston)
+* [gvido](https://github.com/gvido) / Gvido Glazers
+* [karlwestin](https://github.com/karlwestin) / [Karl Westin](http://karlwestin.com)
+* [joakin](https://github.com/joakin) / [Joaquin](http://chimeces.com/)
+* [dancrew32](https://github.com/dancrew32) / [Dan Masquelier](http://danmasq.com/)
+* [jkeyes](https://github.com/jkeyes) / [John Keyes](http://keyes.ie/)
+* [samosad](https://github.com/samosad) / Alexey Tabakman
+* [Page-](https://github.com/Page-)
+
+Built with [Component](https://github.com/component/component) which is created by [TJ Holowaychuk](https://github.com/visionmedia).
+
+### Want to contribute?
+- Read more at [listjs.com/overview/contribute](http://listjs.com/overview/contribute)
+
+### Creator
+| | Jonny Strömberg [@javve](http://twitter.com/javve) |
+| ------------- | ------------- |
+| ![Image of Jonny](http://listjs.com/images/graphics/javve.jpg) | I hope you like the lib. I’ve put a lot of hours into it! Feel free to follow me on [Twitter](http://twitter.com/javve) for news and [donate a coffee](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=M7ZGHV75VSD2E) for good karma ;)
+
+
+## License (MIT)
+
+Copyright (c) 2012 Jonny Strömberg <[jonny.stromberg at gmail.com](jonny.stromberg at gmail.com)>
+[http://jonnystromberg.com](http://jonnystromberg.com)
+
+[![Views in the last 24 hours](https://sourcegraph.com/api/repos/github.com/javve/list.js/counters/views-24h.png)](https://sourcegraph.com/github.com/javve/list.js)
diff --git a/bower.json b/bower.json
new file mode 100644
index 0000000..62b7cd7
--- /dev/null
+++ b/bower.json
@@ -0,0 +1,28 @@
+{
+ "name": "list.js",
+ "main": "dist/list.js",
+ "version": "1.1.1",
+ "homepage": "http://listjs.com",
+ "authors": [
+ "Jonny Strömberg <jonny.stromberg at gmail.com>"
+ ],
+ "description": "Add search, sort and flexibility to plain HTML lists or tables with cross-browser native JavaScript.",
+ "keywords": [
+ "list",
+ "search",
+ "sort",
+ "table",
+ "dom",
+ "html",
+ "ui"
+ ],
+ "license": "MIT",
+ "ignore": [
+ "**/.*",
+ "node_modules",
+ "bower_components",
+ "components",
+ "test",
+ "tests"
+ ]
+}
diff --git a/component.json b/component.json
new file mode 100644
index 0000000..8ad451f
--- /dev/null
+++ b/component.json
@@ -0,0 +1,44 @@
+{
+ "name": "list.js",
+ "repo": "javve/list.js",
+ "version": "1.1.1",
+ "description": "Add search, sort and flexibility to plain HTML lists or tables with cross-browser native JavaScript.",
+ "keywords": [
+ "list",
+ "search",
+ "sort",
+ "table",
+ "dom",
+ "html",
+ "ui"
+ ],
+ "scripts": [
+ "index.js",
+ "src/search.js",
+ "src/sort.js",
+ "src/item.js",
+ "src/templater.js",
+ "src/filter.js",
+ "src/add-async.js",
+ "src/parse.js"
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "component/classes": "*",
+ "segmentio/extend": "*",
+ "component/indexof": "*",
+ "javve/events": "*",
+ "javve/get-by-class": "*",
+ "javve/get-attribute": "*",
+ "javve/natural-sort": "*",
+ "javve/to-string": "*",
+ "component/type": "*"
+ },
+ "development": {
+ "visionmedia/mocha": "*",
+ "techjacker/expect.js": "*",
+ "component/jquery": "1.9.1"
+ },
+ "twitter": "javve",
+ "remotes": []
+}
diff --git a/index.js b/index.js
new file mode 100644
index 0000000..05d3192
--- /dev/null
+++ b/index.js
@@ -0,0 +1,226 @@
+/*
+ListJS with beta 1.0.0
+By Jonny Strömberg (www.jonnystromberg.com, www.listjs.com)
+*/
+(function( window, undefined ) {
+"use strict";
+
+var document = window.document,
+ getByClass = require('get-by-class'),
+ extend = require('extend'),
+ indexOf = require('indexof');
+
+var List = function(id, options, values) {
+
+ var self = this,
+ init,
+ Item = require('./src/item')(self),
+ addAsync = require('./src/add-async')(self),
+ parse = require('./src/parse')(self);
+
+ init = {
+ start: function() {
+ self.listClass = "list";
+ self.searchClass = "search";
+ self.sortClass = "sort";
+ self.page = 200;
+ self.i = 1;
+ self.items = [];
+ self.visibleItems = [];
+ self.matchingItems = [];
+ self.searched = false;
+ self.filtered = false;
+ self.handlers = { 'updated': [] };
+ self.plugins = {};
+ self.helpers = {
+ getByClass: getByClass,
+ extend: extend,
+ indexOf: indexOf
+ };
+
+ extend(self, options);
+
+ self.listContainer = (typeof(id) === 'string') ? document.getElementById(id) : id;
+ if (!self.listContainer) { return; }
+ self.list = getByClass(self.listContainer, self.listClass, true);
+
+ self.templater = require('./src/templater')(self);
+ self.search = require('./src/search')(self);
+ self.filter = require('./src/filter')(self);
+ self.sort = require('./src/sort')(self);
+
+ this.items();
+ self.update();
+ this.plugins();
+ },
+ items: function() {
+ parse(self.list);
+ if (values !== undefined) {
+ self.add(values);
+ }
+ },
+ plugins: function() {
+ for (var i = 0; i < self.plugins.length; i++) {
+ var plugin = self.plugins[i];
+ self[plugin.name] = plugin;
+ plugin.init(self);
+ }
+ }
+ };
+
+
+ /*
+ * Add object to list
+ */
+ this.add = function(values, callback) {
+ if (callback) {
+ addAsync(values, callback);
+ return;
+ }
+ var added = [],
+ notCreate = false;
+ if (values[0] === undefined){
+ values = [values];
+ }
+ for (var i = 0, il = values.length; i < il; i++) {
+ var item = null;
+ if (values[i] instanceof Item) {
+ item = values[i];
+ item.reload();
+ } else {
+ notCreate = (self.items.length > self.page) ? true : false;
+ item = new Item(values[i], undefined, notCreate);
+ }
+ self.items.push(item);
+ added.push(item);
+ }
+ self.update();
+ return added;
+ };
+
+ this.show = function(i, page) {
+ this.i = i;
+ this.page = page;
+ self.update();
+ return self;
+ };
+
+ /* Removes object from list.
+ * Loops through the list and removes objects where
+ * property "valuename" === value
+ */
+ this.remove = function(valueName, value, options) {
+ var found = 0;
+ for (var i = 0, il = self.items.length; i < il; i++) {
+ if (self.items[i].values()[valueName] == value) {
+ self.templater.remove(self.items[i], options);
+ self.items.splice(i,1);
+ il--;
+ i--;
+ found++;
+ }
+ }
+ self.update();
+ return found;
+ };
+
+ /* Gets the objects in the list which
+ * property "valueName" === value
+ */
+ this.get = function(valueName, value) {
+ var matchedItems = [];
+ for (var i = 0, il = self.items.length; i < il; i++) {
+ var item = self.items[i];
+ if (item.values()[valueName] == value) {
+ matchedItems.push(item);
+ }
+ }
+ return matchedItems;
+ };
+
+ /*
+ * Get size of the list
+ */
+ this.size = function() {
+ return self.items.length;
+ };
+
+ /*
+ * Removes all items from the list
+ */
+ this.clear = function() {
+ self.templater.clear();
+ self.items = [];
+ return self;
+ };
+
+ this.on = function(event, callback) {
+ self.handlers[event].push(callback);
+ return self;
+ };
+
+ this.off = function(event, callback) {
+ var e = self.handlers[event];
+ var index = indexOf(e, callback);
+ if (index > -1) {
+ e.splice(index, 1);
+ }
+ return self;
+ };
+
+ this.trigger = function(event) {
+ var i = self.handlers[event].length;
+ while(i--) {
+ self.handlers[event][i](self);
+ }
+ return self;
+ };
+
+ this.reset = {
+ filter: function() {
+ var is = self.items,
+ il = is.length;
+ while (il--) {
+ is[il].filtered = false;
+ }
+ return self;
+ },
+ search: function() {
+ var is = self.items,
+ il = is.length;
+ while (il--) {
+ is[il].found = false;
+ }
+ return self;
+ }
+ };
+
+ this.update = function() {
+ var is = self.items,
+ il = is.length;
+
+ self.visibleItems = [];
+ self.matchingItems = [];
+ self.templater.clear();
+ for (var i = 0; i < il; i++) {
+ if (is[i].matching() && ((self.matchingItems.length+1) >= self.i && self.visibleItems.length < self.page)) {
+ is[i].show();
+ self.visibleItems.push(is[i]);
+ self.matchingItems.push(is[i]);
+ } else if (is[i].matching()) {
+ self.matchingItems.push(is[i]);
+ is[i].hide();
+ } else {
+ is[i].hide();
+ }
+ }
+ self.trigger('updated');
+ return self;
+ };
+
+ init.start();
+};
+
+module.exports = List;
+
+})(window);
diff --git a/package.json b/package.json
new file mode 100644
index 0000000..81c4504
--- /dev/null
+++ b/package.json
@@ -0,0 +1,29 @@
+{
+ "name": "list.js",
+ "version": "1.1.1",
+ "description": "Component package manager consuming git repositories",
+ "keywords": [
+ "list",
+ "search",
+ "sort",
+ "table",
+ "dom",
+ "html",
+ "ui"
+ ],
+ "author": "Jonny Strömberg <jonny.stromberg at gmail.com>",
+ "repository": "git://github.com/javve/list.js.git",
+ "dependencies": {},
+ "devDependencies": {
+ "grunt": "~0.4.1",
+ "grunt-shell": "~0.5.0",
+ "grunt-contrib-watch": "~0.5.3",
+ "grunt-contrib-uglify": "~0.2.7",
+ "grunt-contrib-jshint": "~0.7.1",
+ "grunt-mocha": "~0.4.1"
+ },
+ "main": "index",
+ "engines": {
+ "node": ">= 0.10.21"
+ }
+}
diff --git a/src/add-async.js b/src/add-async.js
new file mode 100644
index 0000000..432333b
--- /dev/null
+++ b/src/add-async.js
@@ -0,0 +1,15 @@
+module.exports = function(list) {
+ return function(values, callback, items) {
+ var valuesToAdd = values.splice(0, 100);
+ items = items || [];
+ items = items.concat(list.add(valuesToAdd));
+ if (values.length > 0) {
+ setTimeout(function() {
+ addAsync(values, callback, items);
+ }, 10);
+ } else {
+ list.update();
+ callback(items);
+ }
+ };
+};
\ No newline at end of file
diff --git a/src/filter.js b/src/filter.js
new file mode 100644
index 0000000..df6b2f0
--- /dev/null
+++ b/src/filter.js
@@ -0,0 +1,29 @@
+module.exports = function(list) {
+
+ // Add handlers
+ list.handlers.filterStart = list.handlers.filterStart || [];
+ list.handlers.filterComplete = list.handlers.filterComplete || [];
+
+ return function(filterFunction) {
+ list.trigger('filterStart');
+ list.i = 1; // Reset paging
+ list.reset.filter();
+ if (filterFunction === undefined) {
+ list.filtered = false;
+ } else {
+ list.filtered = true;
+ var is = list.items;
+ for (var i = 0, il = is.length; i < il; i++) {
+ var item = is[i];
+ if (filterFunction(item)) {
+ item.filtered = true;
+ } else {
+ item.filtered = false;
+ }
+ }
+ }
+ list.update();
+ list.trigger('filterComplete');
+ return list.visibleItems;
+ };
+};
diff --git a/src/item.js b/src/item.js
new file mode 100644
index 0000000..307a914
--- /dev/null
+++ b/src/item.js
@@ -0,0 +1,54 @@
+module.exports = function(list) {
+ return function(initValues, element, notCreate) {
+ var item = this;
+
+ this._values = {};
+
+ this.found = false; // Show if list.searched == true and this.found == true
+ this.filtered = false;// Show if list.filtered == true and this.filtered == true
+
+ var init = function(initValues, element, notCreate) {
+ if (element === undefined) {
+ if (notCreate) {
+ item.values(initValues, notCreate);
+ } else {
+ item.values(initValues);
+ }
+ } else {
+ item.elm = element;
+ var values = list.templater.get(item, initValues);
+ item.values(values);
+ }
+ };
+ this.values = function(newValues, notCreate) {
+ if (newValues !== undefined) {
+ for(var name in newValues) {
+ item._values[name] = newValues[name];
+ }
+ if (notCreate !== true) {
+ list.templater.set(item, item.values());
+ }
+ } else {
+ return item._values;
+ }
+ };
+ this.show = function() {
+ list.templater.show(item);
+ };
+ this.hide = function() {
+ list.templater.hide(item);
+ };
+ this.matching = function() {
+ return (
+ (list.filtered && list.searched && item.found && item.filtered) ||
+ (list.filtered && !list.searched && item.filtered) ||
+ (!list.filtered && list.searched && item.found) ||
+ (!list.filtered && !list.searched)
+ );
+ };
+ this.visible = function() {
+ return (item.elm.parentNode == list.list) ? true : false;
+ };
+ init(initValues, element, notCreate);
+ };
+};
diff --git a/src/parse.js b/src/parse.js
new file mode 100644
index 0000000..cb39cf3
--- /dev/null
+++ b/src/parse.js
@@ -0,0 +1,45 @@
+module.exports = function(list) {
+
+ var Item = require('./item')(list);
+
+ var getChildren = function(parent) {
+ var nodes = parent.childNodes,
+ items = [];
+ for (var i = 0, il = nodes.length; i < il; i++) {
+ // Only textnodes have a data attribute
+ if (nodes[i].data === undefined) {
+ items.push(nodes[i]);
+ }
+ }
+ return items;
+ };
+
+ var parse = function(itemElements, valueNames) {
+ for (var i = 0, il = itemElements.length; i < il; i++) {
+ list.items.push(new Item(valueNames, itemElements[i]));
+ }
+ };
+ var parseAsync = function(itemElements, valueNames) {
+ var itemsToIndex = itemElements.splice(0, 100); // TODO: If < 100 items, what happens in IE etc?
+ parse(itemsToIndex, valueNames);
+ if (itemElements.length > 0) {
+ setTimeout(function() {
+ init.items.indexAsync(itemElements, valueNames);
+ }, 10);
+ } else {
+ list.update();
+ // TODO: Add indexed callback
+ }
+ };
+
+ return function() {
+ var itemsToIndex = getChildren(list.list),
+ valueNames = list.valueNames;
+
+ if (list.indexAsync) {
+ parseAsync(itemsToIndex, valueNames);
+ } else {
+ parse(itemsToIndex, valueNames);
+ }
+ };
+};
diff --git a/src/search.js b/src/search.js
new file mode 100644
index 0000000..f3434fa
--- /dev/null
+++ b/src/search.js
@@ -0,0 +1,119 @@
+var events = require('events'),
+ getByClass = require('get-by-class'),
+ toString = require('to-string');
+
+module.exports = function(list) {
+ var item,
+ text,
+ columns,
+ searchString,
+ customSearch;
+
+ var prepare = {
+ resetList: function() {
+ list.i = 1;
+ list.templater.clear();
+ customSearch = undefined;
+ },
+ setOptions: function(args) {
+ if (args.length == 2 && args[1] instanceof Array) {
+ columns = args[1];
+ } else if (args.length == 2 && typeof(args[1]) == "function") {
+ customSearch = args[1];
+ } else if (args.length == 3) {
+ columns = args[1];
+ customSearch = args[2];
+ }
+ },
+ setColumns: function() {
+ columns = (columns === undefined) ? prepare.toArray(list.items[0].values()) : columns;
+ },
+ setSearchString: function(s) {
+ s = toString(s).toLowerCase();
+ s = s.replace(/[-[\]{}()*+?.,\\^$|#]/g, "\\$&"); // Escape regular expression characters
+ searchString = s;
+ },
+ toArray: function(values) {
+ var tmpColumn = [];
+ for (var name in values) {
+ tmpColumn.push(name);
+ }
+ return tmpColumn;
+ }
+ };
+ var search = {
+ list: function() {
+ for (var k = 0, kl = list.items.length; k < kl; k++) {
+ search.item(list.items[k]);
+ }
+ },
+ item: function(item) {
+ item.found = false;
+ for (var j = 0, jl = columns.length; j < jl; j++) {
+ if (search.values(item.values(), columns[j])) {
+ item.found = true;
+ return;
+ }
+ }
+ },
+ values: function(values, column) {
+ if (values.hasOwnProperty(column)) {
+ text = toString(values[column]).toLowerCase();
+ if ((searchString !== "") && (text.search(searchString) > -1)) {
+ return true;
+ }
+ }
+ return false;
+ },
+ reset: function() {
+ list.reset.search();
+ list.searched = false;
+ }
+ };
+
+ var searchMethod = function(str) {
+ list.trigger('searchStart');
+
+ prepare.resetList();
+ prepare.setSearchString(str);
+ prepare.setOptions(arguments); // str, cols|searchFunction, searchFunction
+ prepare.setColumns();
+
+ if (searchString === "" ) {
+ search.reset();
+ } else {
+ list.searched = true;
+ if (customSearch) {
+ customSearch(searchString, columns);
+ } else {
+ search.list();
+ }
+ }
+
+ list.update();
+ list.trigger('searchComplete');
+ return list.visibleItems;
+ };
+
+ list.handlers.searchStart = list.handlers.searchStart || [];
+ list.handlers.searchComplete = list.handlers.searchComplete || [];
+
+ events.bind(getByClass(list.listContainer, list.searchClass), 'keyup', function(e) {
+ var target = e.target || e.srcElement, // IE have srcElement
+ alreadyCleared = (target.value === "" && !list.searched);
+ if (!alreadyCleared) { // If oninput already have resetted the list, do nothing
+ searchMethod(target.value);
+ }
+ });
+
+ // Used to detect click on HTML5 clear button
+ events.bind(getByClass(list.listContainer, list.searchClass), 'input', function(e) {
+ var target = e.target || e.srcElement;
+ if (target.value === "") {
+ searchMethod('');
+ }
+ });
+
+ list.helpers.toString = toString;
+ return searchMethod;
+};
diff --git a/src/sort.js b/src/sort.js
new file mode 100644
index 0000000..3373012
--- /dev/null
+++ b/src/sort.js
@@ -0,0 +1,101 @@
+var naturalSort = require('natural-sort'),
+ classes = require('classes'),
+ events = require('events'),
+ getByClass = require('get-by-class'),
+ getAttribute = require('get-attribute');
+
+module.exports = function(list) {
+ list.sortFunction = list.sortFunction || function(itemA, itemB, options) {
+ options.desc = options.order == "desc" ? true : false; // Natural sort uses this format
+ return naturalSort(itemA.values()[options.valueName], itemB.values()[options.valueName], options);
+ };
+
+ var buttons = {
+ els: undefined,
+ clear: function() {
+ for (var i = 0, il = buttons.els.length; i < il; i++) {
+ classes(buttons.els[i]).remove('asc');
+ classes(buttons.els[i]).remove('desc');
+ }
+ },
+ getOrder: function(btn) {
+ var predefinedOrder = getAttribute(btn, 'data-order');
+ if (predefinedOrder == "asc" || predefinedOrder == "desc") {
+ return predefinedOrder;
+ } else if (classes(btn).has('desc')) {
+ return "asc";
+ } else if (classes(btn).has('asc')) {
+ return "desc";
+ } else {
+ return "asc";
+ }
+ },
+ getInSensitive: function(btn, options) {
+ var insensitive = getAttribute(btn, 'data-insensitive');
+ if (insensitive === "true") {
+ options.insensitive = true;
+ } else {
+ options.insensitive = false;
+ }
+ },
+ setOrder: function(options) {
+ for (var i = 0, il = buttons.els.length; i < il; i++) {
+ var btn = buttons.els[i];
+ if (getAttribute(btn, 'data-sort') !== options.valueName) {
+ continue;
+ }
+ var predefinedOrder = getAttribute(btn, 'data-order');
+ if (predefinedOrder == "asc" || predefinedOrder == "desc") {
+ if (predefinedOrder == options.order) {
+ classes(btn).add(options.order);
+ }
+ } else {
+ classes(btn).add(options.order);
+ }
+ }
+ }
+ };
+ var sort = function() {
+ list.trigger('sortStart');
+ options = {};
+
+ var target = arguments[0].currentTarget || arguments[0].srcElement || undefined;
+
+ if (target) {
+ options.valueName = getAttribute(target, 'data-sort');
+ buttons.getInSensitive(target, options);
+ options.order = buttons.getOrder(target);
+ } else {
+ options = arguments[1] || options;
+ options.valueName = arguments[0];
+ options.order = options.order || "asc";
+ options.insensitive = (typeof options.insensitive == "undefined") ? true : options.insensitive;
+ }
+ buttons.clear();
+ buttons.setOrder(options);
+
+ options.sortFunction = options.sortFunction || list.sortFunction;
+ list.items.sort(function(a, b) {
+ return options.sortFunction(a, b, options);
+ });
+ list.update();
+ list.trigger('sortComplete');
+ };
+
+ // Add handlers
+ list.handlers.sortStart = list.handlers.sortStart || [];
+ list.handlers.sortComplete = list.handlers.sortComplete || [];
+
+ buttons.els = getByClass(list.listContainer, list.sortClass);
+ events.bind(buttons.els, 'click', sort);
+ list.on('searchStart', buttons.clear);
+ list.on('filterStart', buttons.clear);
+
+ // Helpers
+ list.helpers.classes = classes;
+ list.helpers.naturalSort = naturalSort;
+ list.helpers.events = events;
+ list.helpers.getAttribute = getAttribute;
+
+ return sort;
+};
diff --git a/src/templater.js b/src/templater.js
new file mode 100644
index 0000000..29b8d02
--- /dev/null
+++ b/src/templater.js
@@ -0,0 +1,96 @@
+var getByClass = require('get-by-class');
+
+var Templater = function(list) {
+ var itemSource = getItemSource(list.item),
+ templater = this;
+
+ function getItemSource(item) {
+ if (item === undefined) {
+ var nodes = list.list.childNodes,
+ items = [];
+
+ for (var i = 0, il = nodes.length; i < il; i++) {
+ // Only textnodes have a data attribute
+ if (nodes[i].data === undefined) {
+ return nodes[i];
+ }
+ }
+ return null;
+ } else if (item.indexOf("<") !== -1) { // Try create html element of list, do not work for tables!!
+ var div = document.createElement('div');
+ div.innerHTML = item;
+ return div.firstChild;
+ } else {
+ return document.getElementById(list.item);
+ }
+ }
+
+ /* Get values from element */
+ this.get = function(item, valueNames) {
+ templater.create(item);
+ var values = {};
+ for(var i = 0, il = valueNames.length; i < il; i++) {
+ var elm = getByClass(item.elm, valueNames[i], true);
+ values[valueNames[i]] = elm ? elm.innerHTML : "";
+ }
+ return values;
+ };
+
+ /* Sets values at element */
+ this.set = function(item, values) {
+ if (!templater.create(item)) {
+ for(var v in values) {
+ if (values.hasOwnProperty(v)) {
+ // TODO speed up if possible
+ var elm = getByClass(item.elm, v, true);
+ if (elm) {
+ /* src attribute for image tag & text for other tags */
+ if (elm.tagName === "IMG" && values[v] !== "") {
+ elm.src = values[v];
+ } else {
+ elm.innerHTML = values[v];
+ }
+ }
+ }
+ }
+ }
+ };
+
+ this.create = function(item) {
+ if (item.elm !== undefined) {
+ return false;
+ }
+ /* If item source does not exists, use the first item in list as
+ source for new items */
+ var newItem = itemSource.cloneNode(true);
+ newItem.removeAttribute('id');
+ item.elm = newItem;
+ templater.set(item, item.values());
+ return true;
+ };
+ this.remove = function(item) {
+ list.list.removeChild(item.elm);
+ };
+ this.show = function(item) {
+ templater.create(item);
+ list.list.appendChild(item.elm);
+ };
+ this.hide = function(item) {
+ if (item.elm !== undefined && item.elm.parentNode === list.list) {
+ list.list.removeChild(item.elm);
+ }
+ };
+ this.clear = function() {
+ /* .innerHTML = ''; fucks up IE */
+ if (list.list.hasChildNodes()) {
+ while (list.list.childNodes.length >= 1)
+ {
+ list.list.removeChild(list.list.firstChild);
+ }
+ }
+ };
+};
+
+module.exports = function(list) {
+ return new Templater(list);
+};
diff --git a/test/fixtures.js b/test/fixtures.js
new file mode 100644
index 0000000..79f5190
--- /dev/null
+++ b/test/fixtures.js
@@ -0,0 +1,56 @@
+var fixture = {
+ list: function(valueNames, items) {
+ var listHtml = $('<div id="list"><ul class="list"></ul></div>'),
+ item = "";
+
+ item = "<li>";
+ for (var i = 0; i < valueNames.length; i++) {
+ item += '<span class="'+valueNames[i]+'"</span>';
+ }
+ item += "</li>";
+
+ $(document.body).append(listHtml);
+
+ items = items || [];
+
+ return new List('list', {
+ valueNames: valueNames,
+ item: item
+ }, items);
+ },
+ removeList: function() {
+ $('#list').remove();
+ },
+ jonny: {
+ name: "Jonny Strömberg",
+ born: '1986'
+ },
+ martina: {
+ name: "Martina Elm",
+ born: '1986'
+ },
+ angelica: {
+ name: "Angelica Abraham",
+ born: '1986'
+ },
+ sebastian: {
+ name: "Sebastian Höglund",
+ born: '1989'
+ },
+ imma: {
+ name: "Imma Grafström",
+ born: '1953'
+ },
+ hasse: {
+ name: "Hasse Strömberg",
+ born: '1955'
+ }
+};
+fixture.all = [
+ fixture.jonny,
+ fixture.martina,
+ fixture.angelica,
+ fixture.sebastian,
+ fixture.imma,
+ fixture.hasse
+];
\ No newline at end of file
diff --git a/test/index.html b/test/index.html
new file mode 100755
index 0000000..e5dfce5
--- /dev/null
+++ b/test/index.html
@@ -0,0 +1,56 @@
+<html>
+<head>
+ <meta charset="utf-8">
+ <title>List.js Mocha Tests</title>
+ <link rel="stylesheet" href="../build/build.css" />
+ <style>
+ #list,
+ #parse-list,
+ .list {
+ margin-left:-1000px;
+ }
+ </style>
+</head>
+<body>
+
+ <div id="mocha"></div>
+ <script src="../build/build.js"></script>
+ <script src="mocha.js"></script> <!-- this specific version is needed for grunt-mocha (wtf...) -->
+
+ <script>
+ List = require('list.js');
+ $ = require('jquery');
+
+ if (navigator.userAgent.indexOf('PhantomJS') < 0) {
+ // This version is needed to not get "Out of stack space" error in IE
+ require('mocha');
+ }
+
+ mocha.setup('bdd');
+ expect = require('expect.js');
+ </script>
+
+ <script src="fixtures.js"></script>
+ <script src="test.defaults.js"></script>
+ <script src="test.create.js"></script>
+ <script src="test.add-get-remove.js"></script>
+ <script src="test.item.js"></script>
+ <script src="test.filter.js"></script>
+ <script src="test.search.js"></script>
+ <script src="test.search-filter.js"></script>
+ <script src="test.show.js"></script>
+ <script src="test.on.js"></script>
+ <script src="test.off.js"></script>
+ <script src="test.trigger.js"></script>
+
+ <script src="test.sort.js"></script>
+ <script src="test.buttons.js"></script>
+ <script src="test.parse.js"></script>
+
+ <script>
+ if (navigator.userAgent.indexOf('PhantomJS') < 0) {
+ mocha.run();
+ }
+ </script>
+</body>
+</html>
diff --git a/test/mocha.js b/test/mocha.js
new file mode 100644
index 0000000..03f263d
--- /dev/null
+++ b/test/mocha.js
@@ -0,0 +1,5341 @@
+;(function(){
+
+
+// CommonJS require()
+
+function require(p){
+ var path = require.resolve(p)
+ , mod = require.modules[path];
+ if (!mod) throw new Error('failed to require "' + p + '"');
+ if (!mod.exports) {
+ mod.exports = {};
+ mod.call(mod.exports, mod, mod.exports, require.relative(path));
+ }
+ return mod.exports;
+ }
+
+require.modules = {};
+
+require.resolve = function (path){
+ var orig = path
+ , reg = path + '.js'
+ , index = path + '/index.js';
+ return require.modules[reg] && reg
+ || require.modules[index] && index
+ || orig;
+ };
+
+require.register = function (path, fn){
+ require.modules[path] = fn;
+ };
+
+require.relative = function (parent) {
+ return function(p){
+ if ('.' != p.charAt(0)) return require(p);
+
+ var path = parent.split('/')
+ , segs = p.split('/');
+ path.pop();
+
+ for (var i = 0; i < segs.length; i++) {
+ var seg = segs[i];
+ if ('..' == seg) path.pop();
+ else if ('.' != seg) path.push(seg);
+ }
+
+ return require(path.join('/'));
+ };
+ };
+
+
+require.register("browser/debug.js", function(module, exports, require){
+
+module.exports = function(type){
+ return function(){
+
+ }
+};
+}); // module: browser/debug.js
+
+require.register("browser/diff.js", function(module, exports, require){
+/* See license.txt for terms of usage */
+
+/*
+ * Text diff implementation.
+ *
+ * This library supports the following APIS:
+ * JsDiff.diffChars: Character by character diff
+ * JsDiff.diffWords: Word (as defined by \b regex) diff which ignores whitespace
+ * JsDiff.diffLines: Line based diff
+ *
+ * JsDiff.diffCss: Diff targeted at CSS content
+ *
+ * These methods are based on the implementation proposed in
+ * "An O(ND) Difference Algorithm and its Variations" (Myers, 1986).
+ * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.4.6927
+ */
+var JsDiff = (function() {
+ function clonePath(path) {
+ return { newPos: path.newPos, components: path.components.slice(0) };
+ }
+ function removeEmpty(array) {
+ var ret = [];
+ for (var i = 0; i < array.length; i++) {
+ if (array[i]) {
+ ret.push(array[i]);
+ }
+ }
+ return ret;
+ }
+ function escapeHTML(s) {
+ var n = s;
+ n = n.replace(/&/g, "&");
+ n = n.replace(/</g, "<");
+ n = n.replace(/>/g, ">");
+ n = n.replace(/"/g, """);
+
+ return n;
+ }
+
+
+ var fbDiff = function(ignoreWhitespace) {
+ this.ignoreWhitespace = ignoreWhitespace;
+ };
+ fbDiff.prototype = {
+ diff: function(oldString, newString) {
+ // Handle the identity case (this is due to unrolling editLength == 0
+ if (newString == oldString) {
+ return [{ value: newString }];
+ }
+ if (!newString) {
+ return [{ value: oldString, removed: true }];
+ }
+ if (!oldString) {
+ return [{ value: newString, added: true }];
+ }
+
+ newString = this.tokenize(newString);
+ oldString = this.tokenize(oldString);
+
+ var newLen = newString.length, oldLen = oldString.length;
+ var maxEditLength = newLen + oldLen;
+ var bestPath = [{ newPos: -1, components: [] }];
+
+ // Seed editLength = 0
+ var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0);
+ if (bestPath[0].newPos+1 >= newLen && oldPos+1 >= oldLen) {
+ return bestPath[0].components;
+ }
+
+ for (var editLength = 1; editLength <= maxEditLength; editLength++) {
+ for (var diagonalPath = -1*editLength; diagonalPath <= editLength; diagonalPath+=2) {
+ var basePath;
+ var addPath = bestPath[diagonalPath-1],
+ removePath = bestPath[diagonalPath+1];
+ oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
+ if (addPath) {
+ // No one else is going to attempt to use this value, clear it
+ bestPath[diagonalPath-1] = undefined;
+ }
+
+ var canAdd = addPath && addPath.newPos+1 < newLen;
+ var canRemove = removePath && 0 <= oldPos && oldPos < oldLen;
+ if (!canAdd && !canRemove) {
+ bestPath[diagonalPath] = undefined;
+ continue;
+ }
+
+ // Select the diagonal that we want to branch from. We select the prior
+ // path whose position in the new string is the farthest from the origin
+ // and does not pass the bounds of the diff graph
+ if (!canAdd || (canRemove && addPath.newPos < removePath.newPos)) {
+ basePath = clonePath(removePath);
+ this.pushComponent(basePath.components, oldString[oldPos], undefined, true);
+ } else {
+ basePath = clonePath(addPath);
+ basePath.newPos++;
+ this.pushComponent(basePath.components, newString[basePath.newPos], true, undefined);
+ }
+
+ var oldPos = this.extractCommon(basePath, newString, oldString, diagonalPath);
+
+ if (basePath.newPos+1 >= newLen && oldPos+1 >= oldLen) {
+ return basePath.components;
+ } else {
+ bestPath[diagonalPath] = basePath;
+ }
+ }
+ }
+ },
+
+ pushComponent: function(components, value, added, removed) {
+ var last = components[components.length-1];
+ if (last && last.added === added && last.removed === removed) {
+ // We need to clone here as the component clone operation is just
+ // as shallow array clone
+ components[components.length-1] =
+ {value: this.join(last.value, value), added: added, removed: removed };
+ } else {
+ components.push({value: value, added: added, removed: removed });
+ }
+ },
+ extractCommon: function(basePath, newString, oldString, diagonalPath) {
+ var newLen = newString.length,
+ oldLen = oldString.length,
+ newPos = basePath.newPos,
+ oldPos = newPos - diagonalPath;
+ while (newPos+1 < newLen && oldPos+1 < oldLen && this.equals(newString[newPos+1], oldString[oldPos+1])) {
+ newPos++;
+ oldPos++;
+
+ this.pushComponent(basePath.components, newString[newPos], undefined, undefined);
+ }
+ basePath.newPos = newPos;
+ return oldPos;
+ },
+
+ equals: function(left, right) {
+ var reWhitespace = /\S/;
+ if (this.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right)) {
+ return true;
+ } else {
+ return left == right;
+ }
+ },
+ join: function(left, right) {
+ return left + right;
+ },
+ tokenize: function(value) {
+ return value;
+ }
+ };
+
+ var CharDiff = new fbDiff();
+
+ var WordDiff = new fbDiff(true);
+ WordDiff.tokenize = function(value) {
+ return removeEmpty(value.split(/(\s+|\b)/));
+ };
+
+ var CssDiff = new fbDiff(true);
+ CssDiff.tokenize = function(value) {
+ return removeEmpty(value.split(/([{}:;,]|\s+)/));
+ };
+
+ var LineDiff = new fbDiff();
+ LineDiff.tokenize = function(value) {
+ return value.split(/^/m);
+ };
+
+ return {
+ diffChars: function(oldStr, newStr) { return CharDiff.diff(oldStr, newStr); },
+ diffWords: function(oldStr, newStr) { return WordDiff.diff(oldStr, newStr); },
+ diffLines: function(oldStr, newStr) { return LineDiff.diff(oldStr, newStr); },
+
+ diffCss: function(oldStr, newStr) { return CssDiff.diff(oldStr, newStr); },
+
+ createPatch: function(fileName, oldStr, newStr, oldHeader, newHeader) {
+ var ret = [];
+
+ ret.push("Index: " + fileName);
+ ret.push("===================================================================");
+ ret.push("--- " + fileName + (typeof oldHeader === "undefined" ? "" : "\t" + oldHeader));
+ ret.push("+++ " + fileName + (typeof newHeader === "undefined" ? "" : "\t" + newHeader));
+
+ var diff = LineDiff.diff(oldStr, newStr);
+ if (!diff[diff.length-1].value) {
+ diff.pop(); // Remove trailing newline add
+ }
+ diff.push({value: "", lines: []}); // Append an empty value to make cleanup easier
+
+ function contextLines(lines) {
+ return lines.map(function(entry) { return ' ' + entry; });
+ }
+ function eofNL(curRange, i, current) {
+ var last = diff[diff.length-2],
+ isLast = i === diff.length-2,
+ isLastOfType = i === diff.length-3 && (current.added === !last.added || current.removed === !last.removed);
+
+ // Figure out if this is the last line for the given file and missing NL
+ if (!/\n$/.test(current.value) && (isLast || isLastOfType)) {
+ curRange.push('\\ No newline at end of file');
+ }
+ }
+
+ var oldRangeStart = 0, newRangeStart = 0, curRange = [],
+ oldLine = 1, newLine = 1;
+ for (var i = 0; i < diff.length; i++) {
+ var current = diff[i],
+ lines = current.lines || current.value.replace(/\n$/, "").split("\n");
+ current.lines = lines;
+
+ if (current.added || current.removed) {
+ if (!oldRangeStart) {
+ var prev = diff[i-1];
+ oldRangeStart = oldLine;
+ newRangeStart = newLine;
+
+ if (prev) {
+ curRange = contextLines(prev.lines.slice(-4));
+ oldRangeStart -= curRange.length;
+ newRangeStart -= curRange.length;
+ }
+ }
+ curRange.push.apply(curRange, lines.map(function(entry) { return (current.added?"+":"-") + entry; }));
+ eofNL(curRange, i, current);
+
+ if (current.added) {
+ newLine += lines.length;
+ } else {
+ oldLine += lines.length;
+ }
+ } else {
+ if (oldRangeStart) {
+ // Close out any changes that have been output (or join overlapping)
+ if (lines.length <= 8 && i < diff.length-2) {
+ // Overlapping
+ curRange.push.apply(curRange, contextLines(lines));
+ } else {
+ // end the range and output
+ var contextSize = Math.min(lines.length, 4);
+ ret.push(
+ "@@ -" + oldRangeStart + "," + (oldLine-oldRangeStart+contextSize)
+ + " +" + newRangeStart + "," + (newLine-newRangeStart+contextSize)
+ + " @@");
+ ret.push.apply(ret, curRange);
+ ret.push.apply(ret, contextLines(lines.slice(0, contextSize)));
+ if (lines.length <= 4) {
+ eofNL(ret, i, current);
+ }
+
+ oldRangeStart = 0; newRangeStart = 0; curRange = [];
+ }
+ }
+ oldLine += lines.length;
+ newLine += lines.length;
+ }
+ }
+
+ return ret.join('\n') + '\n';
+ },
+
+ convertChangesToXML: function(changes){
+ var ret = [];
+ for ( var i = 0; i < changes.length; i++) {
+ var change = changes[i];
+ if (change.added) {
+ ret.push("<ins>");
+ } else if (change.removed) {
+ ret.push("<del>");
+ }
+
+ ret.push(escapeHTML(change.value));
+
+ if (change.added) {
+ ret.push("</ins>");
+ } else if (change.removed) {
+ ret.push("</del>");
+ }
+ }
+ return ret.join("");
+ }
+ };
+})();
+
+if (typeof module !== "undefined") {
+ module.exports = JsDiff;
+}
+
+}); // module: browser/diff.js
+
+require.register("browser/events.js", function(module, exports, require){
+
+/**
+ * Module exports.
+ */
+
+exports.EventEmitter = EventEmitter;
+
+/**
+ * Check if `obj` is an array.
+ */
+
+function isArray(obj) {
+ return '[object Array]' == {}.toString.call(obj);
+}
+
+/**
+ * Event emitter constructor.
+ *
+ * @api public
+ */
+
+function EventEmitter(){};
+
+/**
+ * Adds a listener.
+ *
+ * @api public
+ */
+
+EventEmitter.prototype.on = function (name, fn) {
+ if (!this.$events) {
+ this.$events = {};
+ }
+
+ if (!this.$events[name]) {
+ this.$events[name] = fn;
+ } else if (isArray(this.$events[name])) {
+ this.$events[name].push(fn);
+ } else {
+ this.$events[name] = [this.$events[name], fn];
+ }
+
+ return this;
+};
+
+EventEmitter.prototype.addListener = EventEmitter.prototype.on;
+
+/**
+ * Adds a volatile listener.
+ *
+ * @api public
+ */
+
+EventEmitter.prototype.once = function (name, fn) {
+ var self = this;
+
+ function on () {
+ self.removeListener(name, on);
+ fn.apply(this, arguments);
+ };
+
+ on.listener = fn;
+ this.on(name, on);
+
+ return this;
+};
+
+/**
+ * Removes a listener.
+ *
+ * @api public
+ */
+
+EventEmitter.prototype.removeListener = function (name, fn) {
+ if (this.$events && this.$events[name]) {
+ var list = this.$events[name];
+
+ if (isArray(list)) {
+ var pos = -1;
+
+ for (var i = 0, l = list.length; i < l; i++) {
+ if (list[i] === fn || (list[i].listener && list[i].listener === fn)) {
+ pos = i;
+ break;
+ }
+ }
+
+ if (pos < 0) {
+ return this;
+ }
+
+ list.splice(pos, 1);
+
+ if (!list.length) {
+ delete this.$events[name];
+ }
+ } else if (list === fn || (list.listener && list.listener === fn)) {
+ delete this.$events[name];
+ }
+ }
+
+ return this;
+};
+
+/**
+ * Removes all listeners for an event.
+ *
+ * @api public
+ */
+
+EventEmitter.prototype.removeAllListeners = function (name) {
+ if (name === undefined) {
+ this.$events = {};
+ return this;
+ }
+
+ if (this.$events && this.$events[name]) {
+ this.$events[name] = null;
+ }
+
+ return this;
+};
+
+/**
+ * Gets all listeners for a certain event.
+ *
+ * @api public
+ */
+
+EventEmitter.prototype.listeners = function (name) {
+ if (!this.$events) {
+ this.$events = {};
+ }
+
+ if (!this.$events[name]) {
+ this.$events[name] = [];
+ }
+
+ if (!isArray(this.$events[name])) {
+ this.$events[name] = [this.$events[name]];
+ }
+
+ return this.$events[name];
+};
+
+/**
+ * Emits an event.
+ *
+ * @api public
+ */
+
+EventEmitter.prototype.emit = function (name) {
+ if (!this.$events) {
+ return false;
+ }
+
+ var handler = this.$events[name];
+
+ if (!handler) {
+ return false;
+ }
+
+ var args = [].slice.call(arguments, 1);
+
+ if ('function' == typeof handler) {
+ handler.apply(this, args);
+ } else if (isArray(handler)) {
+ var listeners = handler.slice();
+
+ for (var i = 0, l = listeners.length; i < l; i++) {
+ listeners[i].apply(this, args);
+ }
+ } else {
+ return false;
+ }
+
+ return true;
+};
+}); // module: browser/events.js
+
+require.register("browser/fs.js", function(module, exports, require){
+
+}); // module: browser/fs.js
+
+require.register("browser/path.js", function(module, exports, require){
+
+}); // module: browser/path.js
+
+require.register("browser/progress.js", function(module, exports, require){
+
+/**
+ * Expose `Progress`.
+ */
+
+module.exports = Progress;
+
+/**
+ * Initialize a new `Progress` indicator.
+ */
+
+function Progress() {
+ this.percent = 0;
+ this.size(0);
+ this.fontSize(11);
+ this.font('helvetica, arial, sans-serif');
+}
+
+/**
+ * Set progress size to `n`.
+ *
+ * @param {Number} n
+ * @return {Progress} for chaining
+ * @api public
+ */
+
+Progress.prototype.size = function(n){
+ this._size = n;
+ return this;
+};
+
+/**
+ * Set text to `str`.
+ *
+ * @param {String} str
+ * @return {Progress} for chaining
+ * @api public
+ */
+
+Progress.prototype.text = function(str){
+ this._text = str;
+ return this;
+};
+
+/**
+ * Set font size to `n`.
+ *
+ * @param {Number} n
+ * @return {Progress} for chaining
+ * @api public
+ */
+
+Progress.prototype.fontSize = function(n){
+ this._fontSize = n;
+ return this;
+};
+
+/**
+ * Set font `family`.
+ *
+ * @param {String} family
+ * @return {Progress} for chaining
+ */
+
+Progress.prototype.font = function(family){
+ this._font = family;
+ return this;
+};
+
+/**
+ * Update percentage to `n`.
+ *
+ * @param {Number} n
+ * @return {Progress} for chaining
+ */
+
+Progress.prototype.update = function(n){
+ this.percent = n;
+ return this;
+};
+
+/**
+ * Draw on `ctx`.
+ *
+ * @param {CanvasRenderingContext2d} ctx
+ * @return {Progress} for chaining
+ */
+
+Progress.prototype.draw = function(ctx){
+ var percent = Math.min(this.percent, 100)
+ , size = this._size
+ , half = size / 2
+ , x = half
+ , y = half
+ , rad = half - 1
+ , fontSize = this._fontSize;
+
+ ctx.font = fontSize + 'px ' + this._font;
+
+ var angle = Math.PI * 2 * (percent / 100);
+ ctx.clearRect(0, 0, size, size);
+
+ // outer circle
+ ctx.strokeStyle = '#9f9f9f';
+ ctx.beginPath();
+ ctx.arc(x, y, rad, 0, angle, false);
+ ctx.stroke();
+
+ // inner circle
+ ctx.strokeStyle = '#eee';
+ ctx.beginPath();
+ ctx.arc(x, y, rad - 1, 0, angle, true);
+ ctx.stroke();
+
+ // text
+ var text = this._text || (percent | 0) + '%'
+ , w = ctx.measureText(text).width;
+
+ ctx.fillText(
+ text
+ , x - w / 2 + 1
+ , y + fontSize / 2 - 1);
+
+ return this;
+};
+
+}); // module: browser/progress.js
+
+require.register("browser/tty.js", function(module, exports, require){
+
+exports.isatty = function(){
+ return true;
+};
+
+exports.getWindowSize = function(){
+ return [window.innerHeight, window.innerWidth];
+};
+}); // module: browser/tty.js
+
+require.register("context.js", function(module, exports, require){
+
+/**
+ * Expose `Context`.
+ */
+
+module.exports = Context;
+
+/**
+ * Initialize a new `Context`.
+ *
+ * @api private
+ */
+
+function Context(){}
+
+/**
+ * Set or get the context `Runnable` to `runnable`.
+ *
+ * @param {Runnable} runnable
+ * @return {Context}
+ * @api private
+ */
+
+Context.prototype.runnable = function(runnable){
+ if (0 == arguments.length) return this._runnable;
+ this.test = this._runnable = runnable;
+ return this;
+};
+
+/**
+ * Set test timeout `ms`.
+ *
+ * @param {Number} ms
+ * @return {Context} self
+ * @api private
+ */
+
+Context.prototype.timeout = function(ms){
+ this.runnable().timeout(ms);
+ return this;
+};
+
+/**
+ * Set test slowness threshold `ms`.
+ *
+ * @param {Number} ms
+ * @return {Context} self
+ * @api private
+ */
+
+Context.prototype.slow = function(ms){
+ this.runnable().slow(ms);
+ return this;
+};
+
+/**
+ * Inspect the context void of `._runnable`.
+ *
+ * @return {String}
+ * @api private
+ */
+
+Context.prototype.inspect = function(){
+ return JSON.stringify(this, function(key, val){
+ if ('_runnable' == key) return;
+ if ('test' == key) return;
+ return val;
+ }, 2);
+};
+
+}); // module: context.js
+
+require.register("hook.js", function(module, exports, require){
+
+/**
+ * Module dependencies.
+ */
+
+var Runnable = require('./runnable');
+
+/**
+ * Expose `Hook`.
+ */
+
+module.exports = Hook;
+
+/**
+ * Initialize a new `Hook` with the given `title` and callback `fn`.
+ *
+ * @param {String} title
+ * @param {Function} fn
+ * @api private
+ */
+
+function Hook(title, fn) {
+ Runnable.call(this, title, fn);
+ this.type = 'hook';
+}
+
+/**
+ * Inherit from `Runnable.prototype`.
+ */
+
+function F(){};
+F.prototype = Runnable.prototype;
+Hook.prototype = new F;
+Hook.prototype.constructor = Hook;
+
+
+/**
+ * Get or set the test `err`.
+ *
+ * @param {Error} err
+ * @return {Error}
+ * @api public
+ */
+
+Hook.prototype.error = function(err){
+ if (0 == arguments.length) {
+ var err = this._error;
+ this._error = null;
+ return err;
+ }
+
+ this._error = err;
+};
+
+
+}); // module: hook.js
+
+require.register("interfaces/bdd.js", function(module, exports, require){
+
+/**
+ * Module dependencies.
+ */
+
+var Suite = require('../suite')
+ , Test = require('../test');
+
+/**
+ * BDD-style interface:
+ *
+ * describe('Array', function(){
+ * describe('#indexOf()', function(){
+ * it('should return -1 when not present', function(){
+ *
+ * });
+ *
+ * it('should return the index when present', function(){
+ *
+ * });
+ * });
+ * });
+ *
+ */
+
+module.exports = function(suite){
+ var suites = [suite];
+
+ suite.on('pre-require', function(context, file, mocha){
+
+ /**
+ * Execute before running tests.
+ */
+
+ context.before = function(fn){
+ suites[0].beforeAll(fn);
+ };
+
+ /**
+ * Execute after running tests.
+ */
+
+ context.after = function(fn){
+ suites[0].afterAll(fn);
+ };
+
+ /**
+ * Execute before each test case.
+ */
+
+ context.beforeEach = function(fn){
+ suites[0].beforeEach(fn);
+ };
+
+ /**
+ * Execute after each test case.
+ */
+
+ context.afterEach = function(fn){
+ suites[0].afterEach(fn);
+ };
+
+ /**
+ * Describe a "suite" with the given `title`
+ * and callback `fn` containing nested suites
+ * and/or tests.
+ */
+
+ context.describe = context.context = function(title, fn){
+ var suite = Suite.create(suites[0], title);
+ suites.unshift(suite);
+ fn.call(suite);
+ suites.shift();
+ return suite;
+ };
+
+ /**
+ * Pending describe.
+ */
+
+ context.xdescribe =
+ context.xcontext =
+ context.describe.skip = function(title, fn){
+ var suite = Suite.create(suites[0], title);
+ suite.pending = true;
+ suites.unshift(suite);
+ fn.call(suite);
+ suites.shift();
+ };
+
+ /**
+ * Exclusive suite.
+ */
+
+ context.describe.only = function(title, fn){
+ var suite = context.describe(title, fn);
+ mocha.grep(suite.fullTitle());
+ };
+
+ /**
+ * Describe a specification or test-case
+ * with the given `title` and callback `fn`
+ * acting as a thunk.
+ */
+
+ context.it = context.specify = function(title, fn){
+ var suite = suites[0];
+ if (suite.pending) var fn = null;
+ var test = new Test(title, fn);
+ suite.addTest(test);
+ return test;
+ };
+
+ /**
+ * Exclusive test-case.
+ */
+
+ context.it.only = function(title, fn){
+ var test = context.it(title, fn);
+ mocha.grep(test.fullTitle());
+ };
+
+ /**
+ * Pending test case.
+ */
+
+ context.xit =
+ context.xspecify =
+ context.it.skip = function(title){
+ context.it(title);
+ };
+ });
+};
+
+}); // module: interfaces/bdd.js
+
+require.register("interfaces/exports.js", function(module, exports, require){
+
+/**
+ * Module dependencies.
+ */
+
+var Suite = require('../suite')
+ , Test = require('../test');
+
+/**
+ * TDD-style interface:
+ *
+ * exports.Array = {
+ * '#indexOf()': {
+ * 'should return -1 when the value is not present': function(){
+ *
+ * },
+ *
+ * 'should return the correct index when the value is present': function(){
+ *
+ * }
+ * }
+ * };
+ *
+ */
+
+module.exports = function(suite){
+ var suites = [suite];
+
+ suite.on('require', visit);
+
+ function visit(obj) {
+ var suite;
+ for (var key in obj) {
+ if ('function' == typeof obj[key]) {
+ var fn = obj[key];
+ switch (key) {
+ case 'before':
+ suites[0].beforeAll(fn);
+ break;
+ case 'after':
+ suites[0].afterAll(fn);
+ break;
+ case 'beforeEach':
+ suites[0].beforeEach(fn);
+ break;
+ case 'afterEach':
+ suites[0].afterEach(fn);
+ break;
+ default:
+ suites[0].addTest(new Test(key, fn));
+ }
+ } else {
+ var suite = Suite.create(suites[0], key);
+ suites.unshift(suite);
+ visit(obj[key]);
+ suites.shift();
+ }
+ }
+ }
+};
+}); // module: interfaces/exports.js
+
+require.register("interfaces/index.js", function(module, exports, require){
+
+exports.bdd = require('./bdd');
+exports.tdd = require('./tdd');
+exports.qunit = require('./qunit');
+exports.exports = require('./exports');
+
+}); // module: interfaces/index.js
+
+require.register("interfaces/qunit.js", function(module, exports, require){
+
+/**
+ * Module dependencies.
+ */
+
+var Suite = require('../suite')
+ , Test = require('../test');
+
+/**
+ * QUnit-style interface:
+ *
+ * suite('Array');
+ *
+ * test('#length', function(){
+ * var arr = [1,2,3];
+ * ok(arr.length == 3);
+ * });
+ *
+ * test('#indexOf()', function(){
+ * var arr = [1,2,3];
+ * ok(arr.indexOf(1) == 0);
+ * ok(arr.indexOf(2) == 1);
+ * ok(arr.indexOf(3) == 2);
+ * });
+ *
+ * suite('String');
+ *
+ * test('#length', function(){
+ * ok('foo'.length == 3);
+ * });
+ *
+ */
+
+module.exports = function(suite){
+ var suites = [suite];
+
+ suite.on('pre-require', function(context){
+
+ /**
+ * Execute before running tests.
+ */
+
+ context.before = function(fn){
+ suites[0].beforeAll(fn);
+ };
+
+ /**
+ * Execute after running tests.
+ */
+
+ context.after = function(fn){
+ suites[0].afterAll(fn);
+ };
+
+ /**
+ * Execute before each test case.
+ */
+
+ context.beforeEach = function(fn){
+ suites[0].beforeEach(fn);
+ };
+
+ /**
+ * Execute after each test case.
+ */
+
+ context.afterEach = function(fn){
+ suites[0].afterEach(fn);
+ };
+
+ /**
+ * Describe a "suite" with the given `title`.
+ */
+
+ context.suite = function(title){
+ if (suites.length > 1) suites.shift();
+ var suite = Suite.create(suites[0], title);
+ suites.unshift(suite);
+ };
+
+ /**
+ * Describe a specification or test-case
+ * with the given `title` and callback `fn`
+ * acting as a thunk.
+ */
+
+ context.test = function(title, fn){
+ suites[0].addTest(new Test(title, fn));
+ };
+ });
+};
+
+}); // module: interfaces/qunit.js
+
+require.register("interfaces/tdd.js", function(module, exports, require){
+
+/**
+ * Module dependencies.
+ */
+
+var Suite = require('../suite')
+ , Test = require('../test');
+
+/**
+ * TDD-style interface:
+ *
+ * suite('Array', function(){
+ * suite('#indexOf()', function(){
+ * suiteSetup(function(){
+ *
+ * });
+ *
+ * test('should return -1 when not present', function(){
+ *
+ * });
+ *
+ * test('should return the index when present', function(){
+ *
+ * });
+ *
+ * suiteTeardown(function(){
+ *
+ * });
+ * });
+ * });
+ *
+ */
+
+module.exports = function(suite){
+ var suites = [suite];
+
+ suite.on('pre-require', function(context, file, mocha){
+
+ /**
+ * Execute before each test case.
+ */
+
+ context.setup = function(fn){
+ suites[0].beforeEach(fn);
+ };
+
+ /**
+ * Execute after each test case.
+ */
+
+ context.teardown = function(fn){
+ suites[0].afterEach(fn);
+ };
+
+ /**
+ * Execute before the suite.
+ */
+
+ context.suiteSetup = function(fn){
+ suites[0].beforeAll(fn);
+ };
+
+ /**
+ * Execute after the suite.
+ */
+
+ context.suiteTeardown = function(fn){
+ suites[0].afterAll(fn);
+ };
+
+ /**
+ * Describe a "suite" with the given `title`
+ * and callback `fn` containing nested suites
+ * and/or tests.
+ */
+
+ context.suite = function(title, fn){
+ var suite = Suite.create(suites[0], title);
+ suites.unshift(suite);
+ fn.call(suite);
+ suites.shift();
+ return suite;
+ };
+
+ /**
+ * Exclusive test-case.
+ */
+
+ context.suite.only = function(title, fn){
+ var suite = context.suite(title, fn);
+ mocha.grep(suite.fullTitle());
+ };
+
+ /**
+ * Describe a specification or test-case
+ * with the given `title` and callback `fn`
+ * acting as a thunk.
+ */
+
+ context.test = function(title, fn){
+ var test = new Test(title, fn);
+ suites[0].addTest(test);
+ return test;
+ };
+
+ /**
+ * Exclusive test-case.
+ */
+
+ context.test.only = function(title, fn){
+ var test = context.test(title, fn);
+ mocha.grep(test.fullTitle());
+ };
+
+ /**
+ * Pending test case.
+ */
+
+ context.test.skip = function(title){
+ context.test(title);
+ };
+ });
+};
+
+}); // module: interfaces/tdd.js
+
+require.register("mocha.js", function(module, exports, require){
+/*!
+ * mocha
+ * Copyright(c) 2011 TJ Holowaychuk <tj at vision-media.ca>
+ * MIT Licensed
+ */
+
+/**
+ * Module dependencies.
+ */
+
+var path = require('browser/path')
+ , utils = require('./utils');
+
+/**
+ * Expose `Mocha`.
+ */
+
+exports = module.exports = Mocha;
+
+/**
+ * Expose internals.
+ */
+
+exports.utils = utils;
+exports.interfaces = require('./interfaces');
+exports.reporters = require('./reporters');
+exports.Runnable = require('./runnable');
+exports.Context = require('./context');
+exports.Runner = require('./runner');
+exports.Suite = require('./suite');
+exports.Hook = require('./hook');
+exports.Test = require('./test');
+
+/**
+ * Return image `name` path.
+ *
+ * @param {String} name
+ * @return {String}
+ * @api private
+ */
+
+function image(name) {
+ return __dirname + '/../images/' + name + '.png';
+}
+
+/**
+ * Setup mocha with `options`.
+ *
+ * Options:
+ *
+ * - `ui` name "bdd", "tdd", "exports" etc
+ * - `reporter` reporter instance, defaults to `mocha.reporters.Dot`
+ * - `globals` array of accepted globals
+ * - `timeout` timeout in milliseconds
+ * - `bail` bail on the first test failure
+ * - `slow` milliseconds to wait before considering a test slow
+ * - `ignoreLeaks` ignore global leaks
+ * - `grep` string or regexp to filter tests with
+ *
+ * @param {Object} options
+ * @api public
+ */
+
+function Mocha(options) {
+ options = options || {};
+ this.files = [];
+ this.options = options;
+ this.grep(options.grep);
+ this.suite = new exports.Suite('', new exports.Context);
+ this.ui(options.ui);
+ this.bail(options.bail);
+ this.reporter(options.reporter);
+ if (options.timeout) this.timeout(options.timeout);
+ if (options.slow) this.slow(options.slow);
+}
+
+/**
+ * Enable or disable bailing on the first failure.
+ *
+ * @param {Boolean} [bail]
+ * @api public
+ */
+
+Mocha.prototype.bail = function(bail){
+ if (0 == arguments.length) bail = true;
+ this.suite.bail(bail);
+ return this;
+};
+
+/**
+ * Add test `file`.
+ *
+ * @param {String} file
+ * @api public
+ */
+
+Mocha.prototype.addFile = function(file){
+ this.files.push(file);
+ return this;
+};
+
+/**
+ * Set reporter to `reporter`, defaults to "dot".
+ *
+ * @param {String|Function} reporter name or constructor
+ * @api public
+ */
+
+Mocha.prototype.reporter = function(reporter){
+ if ('function' == typeof reporter) {
+ this._reporter = reporter;
+ } else {
+ reporter = reporter || 'dot';
+ try {
+ this._reporter = require('./reporters/' + reporter);
+ } catch (err) {
+ this._reporter = require(reporter);
+ }
+ if (!this._reporter) throw new Error('invalid reporter "' + reporter + '"');
+ }
+ return this;
+};
+
+/**
+ * Set test UI `name`, defaults to "bdd".
+ *
+ * @param {String} bdd
+ * @api public
+ */
+
+Mocha.prototype.ui = function(name){
+ name = name || 'bdd';
+ this._ui = exports.interfaces[name];
+ if (!this._ui) throw new Error('invalid interface "' + name + '"');
+ this._ui = this._ui(this.suite);
+ return this;
+};
+
+/**
+ * Load registered files.
+ *
+ * @api private
+ */
+
+Mocha.prototype.loadFiles = function(fn){
+ var self = this;
+ var suite = this.suite;
+ var pending = this.files.length;
+ this.files.forEach(function(file){
+ file = path.resolve(file);
+ suite.emit('pre-require', global, file, self);
+ suite.emit('require', require(file), file, self);
+ suite.emit('post-require', global, file, self);
+ --pending || (fn && fn());
+ });
+};
+
+/**
+ * Enable growl support.
+ *
+ * @api private
+ */
+
+Mocha.prototype._growl = function(runner, reporter) {
+ var notify = require('growl');
+
+ runner.on('end', function(){
+ var stats = reporter.stats;
+ if (stats.failures) {
+ var msg = stats.failures + ' of ' + runner.total + ' tests failed';
+ notify(msg, { name: 'mocha', title: 'Failed', image: image('error') });
+ } else {
+ notify(stats.passes + ' tests passed in ' + stats.duration + 'ms', {
+ name: 'mocha'
+ , title: 'Passed'
+ , image: image('ok')
+ });
+ }
+ });
+};
+
+/**
+ * Add regexp to grep, if `re` is a string it is escaped.
+ *
+ * @param {RegExp|String} re
+ * @return {Mocha}
+ * @api public
+ */
+
+Mocha.prototype.grep = function(re){
+ this.options.grep = 'string' == typeof re
+ ? new RegExp(utils.escapeRegexp(re))
+ : re;
+ return this;
+};
+
+/**
+ * Invert `.grep()` matches.
+ *
+ * @return {Mocha}
+ * @api public
+ */
+
+Mocha.prototype.invert = function(){
+ this.options.invert = true;
+ return this;
+};
+
+/**
+ * Ignore global leaks.
+ *
+ * @return {Mocha}
+ * @api public
+ */
+
+Mocha.prototype.ignoreLeaks = function(){
+ this.options.ignoreLeaks = true;
+ return this;
+};
+
+/**
+ * Enable global leak checking.
+ *
+ * @return {Mocha}
+ * @api public
+ */
+
+Mocha.prototype.checkLeaks = function(){
+ this.options.ignoreLeaks = false;
+ return this;
+};
+
+/**
+ * Enable growl support.
+ *
+ * @return {Mocha}
+ * @api public
+ */
+
+Mocha.prototype.growl = function(){
+ this.options.growl = true;
+ return this;
+};
+
+/**
+ * Ignore `globals` array or string.
+ *
+ * @param {Array|String} globals
+ * @return {Mocha}
+ * @api public
+ */
+
+Mocha.prototype.globals = function(globals){
+ this.options.globals = (this.options.globals || []).concat(globals);
+ return this;
+};
+
+/**
+ * Set the timeout in milliseconds.
+ *
+ * @param {Number} timeout
+ * @return {Mocha}
+ * @api public
+ */
+
+Mocha.prototype.timeout = function(timeout){
+ this.suite.timeout(timeout);
+ return this;
+};
+
+/**
+ * Set slowness threshold in milliseconds.
+ *
+ * @param {Number} slow
+ * @return {Mocha}
+ * @api public
+ */
+
+Mocha.prototype.slow = function(slow){
+ this.suite.slow(slow);
+ return this;
+};
+
+/**
+ * Makes all tests async (accepting a callback)
+ *
+ * @return {Mocha}
+ * @api public
+ */
+
+Mocha.prototype.asyncOnly = function(){
+ this.options.asyncOnly = true;
+ return this;
+};
+
+/**
+ * Run tests and invoke `fn()` when complete.
+ *
+ * @param {Function} fn
+ * @return {Runner}
+ * @api public
+ */
+
+Mocha.prototype.run = function(fn){
+ if (this.files.length) this.loadFiles();
+ var suite = this.suite;
+ var options = this.options;
+ var runner = new exports.Runner(suite);
+ var reporter = new this._reporter(runner);
+ runner.ignoreLeaks = options.ignoreLeaks;
+ runner.asyncOnly = options.asyncOnly;
+ if (options.grep) runner.grep(options.grep, options.invert);
+ if (options.globals) runner.globals(options.globals);
+ if (options.growl) this._growl(runner, reporter);
+ return runner.run(fn);
+};
+
+}); // module: mocha.js
+
+require.register("ms.js", function(module, exports, require){
+
+/**
+ * Helpers.
+ */
+
+var s = 1000;
+var m = s * 60;
+var h = m * 60;
+var d = h * 24;
+
+/**
+ * Parse or format the given `val`.
+ *
+ * @param {String|Number} val
+ * @return {String|Number}
+ * @api public
+ */
+
+module.exports = function(val){
+ if ('string' == typeof val) return parse(val);
+ return format(val);
+}
+
+/**
+ * Parse the given `str` and return milliseconds.
+ *
+ * @param {String} str
+ * @return {Number}
+ * @api private
+ */
+
+function parse(str) {
+ var m = /^((?:\d+)?\.?\d+) *(ms|seconds?|s|minutes?|m|hours?|h|days?|d|years?|y)?$/i.exec(str);
+ if (!m) return;
+ var n = parseFloat(m[1]);
+ var type = (m[2] || 'ms').toLowerCase();
+ switch (type) {
+ case 'years':
+ case 'year':
+ case 'y':
+ return n * 31557600000;
+ case 'days':
+ case 'day':
+ case 'd':
+ return n * 86400000;
+ case 'hours':
+ case 'hour':
+ case 'h':
+ return n * 3600000;
+ case 'minutes':
+ case 'minute':
+ case 'm':
+ return n * 60000;
+ case 'seconds':
+ case 'second':
+ case 's':
+ return n * 1000;
+ case 'ms':
+ return n;
+ }
+}
+
+/**
+ * Format the given `ms`.
+ *
+ * @param {Number} ms
+ * @return {String}
+ * @api public
+ */
+
+function format(ms) {
+ if (ms == d) return Math.round(ms / d) + ' day';
+ if (ms > d) return Math.round(ms / d) + ' days';
+ if (ms == h) return Math.round(ms / h) + ' hour';
+ if (ms > h) return Math.round(ms / h) + ' hours';
+ if (ms == m) return Math.round(ms / m) + ' minute';
+ if (ms > m) return Math.round(ms / m) + ' minutes';
+ if (ms == s) return Math.round(ms / s) + ' second';
+ if (ms > s) return Math.round(ms / s) + ' seconds';
+ return ms + ' ms';
+}
+}); // module: ms.js
+
+require.register("reporters/base.js", function(module, exports, require){
+
+/**
+ * Module dependencies.
+ */
+
+var tty = require('browser/tty')
+ , diff = require('browser/diff')
+ , ms = require('../ms');
+
+/**
+ * Save timer references to avoid Sinon interfering (see GH-237).
+ */
+
+var Date = global.Date
+ , setTimeout = global.setTimeout
+ , setInterval = global.setInterval
+ , clearTimeout = global.clearTimeout
+ , clearInterval = global.clearInterval;
+
+/**
+ * Check if both stdio streams are associated with a tty.
+ */
+
+var isatty = tty.isatty(1) && tty.isatty(2);
+
+/**
+ * Expose `Base`.
+ */
+
+exports = module.exports = Base;
+
+/**
+ * Enable coloring by default.
+ */
+
+exports.useColors = isatty;
+
+/**
+ * Default color map.
+ */
+
+exports.colors = {
+ 'pass': 90
+ , 'fail': 31
+ , 'bright pass': 92
+ , 'bright fail': 91
+ , 'bright yellow': 93
+ , 'pending': 36
+ , 'suite': 0
+ , 'error title': 0
+ , 'error message': 31
+ , 'error stack': 90
+ , 'checkmark': 32
+ , 'fast': 90
+ , 'medium': 33
+ , 'slow': 31
+ , 'green': 32
+ , 'light': 90
+ , 'diff gutter': 90
+ , 'diff added': 42
+ , 'diff removed': 41
+};
+
+/**
+ * Default symbol map.
+ */
+
+exports.symbols = {
+ ok: '✓',
+ err: '✖',
+ dot: '․'
+};
+
+// With node.js on Windows: use symbols available in terminal default fonts
+if ('win32' == process.platform) {
+ exports.symbols.ok = '\u221A';
+ exports.symbols.err = '\u00D7';
+ exports.symbols.dot = '.';
+}
+
+/**
+ * Color `str` with the given `type`,
+ * allowing colors to be disabled,
+ * as well as user-defined color
+ * schemes.
+ *
+ * @param {String} type
+ * @param {String} str
+ * @return {String}
+ * @api private
+ */
+
+var color = exports.color = function(type, str) {
+ if (!exports.useColors) return str;
+ return '\u001b[' + exports.colors[type] + 'm' + str + '\u001b[0m';
+};
+
+/**
+ * Expose term window size, with some
+ * defaults for when stderr is not a tty.
+ */
+
+exports.window = {
+ width: isatty
+ ? process.stdout.getWindowSize
+ ? process.stdout.getWindowSize(1)[0]
+ : tty.getWindowSize()[1]
+ : 75
+};
+
+/**
+ * Expose some basic cursor interactions
+ * that are common among reporters.
+ */
+
+exports.cursor = {
+ hide: function(){
+ process.stdout.write('\u001b[?25l');
+ },
+
+ show: function(){
+ process.stdout.write('\u001b[?25h');
+ },
+
+ deleteLine: function(){
+ process.stdout.write('\u001b[2K');
+ },
+
+ beginningOfLine: function(){
+ process.stdout.write('\u001b[0G');
+ },
+
+ CR: function(){
+ exports.cursor.deleteLine();
+ exports.cursor.beginningOfLine();
+ }
+};
+
+/**
+ * Outut the given `failures` as a list.
+ *
+ * @param {Array} failures
+ * @api public
+ */
+
+exports.list = function(failures){
+ console.error();
+ failures.forEach(function(test, i){
+ // format
+ var fmt = color('error title', ' %s) %s:\n')
+ + color('error message', ' %s')
+ + color('error stack', '\n%s\n');
+
+ // msg
+ var err = test.err
+ , message = err.message || ''
+ , stack = err.stack || message
+ , index = stack.indexOf(message) + message.length
+ , msg = stack.slice(0, index)
+ , actual = err.actual
+ , expected = err.expected
+ , escape = true;
+
+ // explicitly show diff
+ if (err.showDiff) {
+ escape = false;
+ err.actual = actual = JSON.stringify(actual, null, 2);
+ err.expected = expected = JSON.stringify(expected, null, 2);
+ }
+
+ // actual / expected diff
+ if ('string' == typeof actual && 'string' == typeof expected) {
+ var len = Math.max(actual.length, expected.length);
+
+ if (len < 20) msg = errorDiff(err, 'Chars', escape);
+ else msg = errorDiff(err, 'Words', escape);
+
+ // linenos
+ var lines = msg.split('\n');
+ if (lines.length > 4) {
+ var width = String(lines.length).length;
+ msg = lines.map(function(str, i){
+ return pad(++i, width) + ' |' + ' ' + str;
+ }).join('\n');
+ }
+
+ // legend
+ msg = '\n'
+ + color('diff removed', 'actual')
+ + ' '
+ + color('diff added', 'expected')
+ + '\n\n'
+ + msg
+ + '\n';
+
+ // indent
+ msg = msg.replace(/^/gm, ' ');
+
+ fmt = color('error title', ' %s) %s:\n%s')
+ + color('error stack', '\n%s\n');
+ }
+
+ // indent stack trace without msg
+ stack = stack.slice(index ? index + 1 : index)
+ .replace(/^/gm, ' ');
+
+ console.error(fmt, (i + 1), test.fullTitle(), msg, stack);
+ });
+};
+
+/**
+ * Initialize a new `Base` reporter.
+ *
+ * All other reporters generally
+ * inherit from this reporter, providing
+ * stats such as test duration, number
+ * of tests passed / failed etc.
+ *
+ * @param {Runner} runner
+ * @api public
+ */
+
+function Base(runner) {
+ var self = this
+ , stats = this.stats = { suites: 0, tests: 0, passes: 0, pending: 0, failures: 0 }
+ , failures = this.failures = [];
+
+ if (!runner) return;
+ this.runner = runner;
+
+ runner.stats = stats;
+
+ runner.on('start', function(){
+ stats.start = new Date;
+ });
+
+ runner.on('suite', function(suite){
+ stats.suites = stats.suites || 0;
+ suite.root || stats.suites++;
+ });
+
+ runner.on('test end', function(test){
+ stats.tests = stats.tests || 0;
+ stats.tests++;
+ });
+
+ runner.on('pass', function(test){
+ stats.passes = stats.passes || 0;
+
+ var medium = test.slow() / 2;
+ test.speed = test.duration > test.slow()
+ ? 'slow'
+ : test.duration > medium
+ ? 'medium'
+ : 'fast';
+
+ stats.passes++;
+ });
+
+ runner.on('fail', function(test, err){
+ stats.failures = stats.failures || 0;
+ stats.failures++;
+ test.err = err;
+ failures.push(test);
+ });
+
+ runner.on('end', function(){
+ stats.end = new Date;
+ stats.duration = new Date - stats.start;
+ });
+
+ runner.on('pending', function(){
+ stats.pending++;
+ });
+}
+
+/**
+ * Output common epilogue used by many of
+ * the bundled reporters.
+ *
+ * @api public
+ */
+
+Base.prototype.epilogue = function(){
+ var stats = this.stats
+ , fmt
+ , tests;
+
+ console.log();
+
+ function pluralize(n) {
+ return 1 == n ? 'test' : 'tests';
+ }
+
+ // failure
+ if (stats.failures) {
+ fmt = color('bright fail', ' ' + exports.symbols.err)
+ + color('fail', ' %d of %d %s failed')
+ + color('light', ':')
+
+ console.error(fmt,
+ stats.failures,
+ this.runner.total,
+ pluralize(this.runner.total));
+
+ Base.list(this.failures);
+ console.error();
+ return;
+ }
+
+ // pass
+ fmt = color('bright pass', ' ')
+ + color('green', ' %d %s complete')
+ + color('light', ' (%s)');
+
+ console.log(fmt,
+ stats.tests || 0,
+ pluralize(stats.tests),
+ ms(stats.duration));
+
+ // pending
+ if (stats.pending) {
+ fmt = color('pending', ' ')
+ + color('pending', ' %d %s pending');
+
+ console.log(fmt, stats.pending, pluralize(stats.pending));
+ }
+
+ console.log();
+};
+
+/**
+ * Pad the given `str` to `len`.
+ *
+ * @param {String} str
+ * @param {String} len
+ * @return {String}
+ * @api private
+ */
+
+function pad(str, len) {
+ str = String(str);
+ return Array(len - str.length + 1).join(' ') + str;
+}
+
+/**
+ * Return a character diff for `err`.
+ *
+ * @param {Error} err
+ * @return {String}
+ * @api private
+ */
+
+function errorDiff(err, type, escape) {
+ return diff['diff' + type](err.actual, err.expected).map(function(str){
+ if (escape) {
+ str.value = str.value
+ .replace(/\t/g, '<tab>')
+ .replace(/\r/g, '<CR>')
+ .replace(/\n/g, '<LF>\n');
+ }
+ if (str.added) return colorLines('diff added', str.value);
+ if (str.removed) return colorLines('diff removed', str.value);
+ return str.value;
+ }).join('');
+}
+
+/**
+ * Color lines for `str`, using the color `name`.
+ *
+ * @param {String} name
+ * @param {String} str
+ * @return {String}
+ * @api private
+ */
+
+function colorLines(name, str) {
+ return str.split('\n').map(function(str){
+ return color(name, str);
+ }).join('\n');
+}
+
+}); // module: reporters/base.js
+
+require.register("reporters/doc.js", function(module, exports, require){
+
+/**
+ * Module dependencies.
+ */
+
+var Base = require('./base')
+ , utils = require('../utils');
+
+/**
+ * Expose `Doc`.
+ */
+
+exports = module.exports = Doc;
+
+/**
+ * Initialize a new `Doc` reporter.
+ *
+ * @param {Runner} runner
+ * @api public
+ */
+
+function Doc(runner) {
+ Base.call(this, runner);
+
+ var self = this
+ , stats = this.stats
+ , total = runner.total
+ , indents = 2;
+
+ function indent() {
+ return Array(indents).join(' ');
+ }
+
+ runner.on('suite', function(suite){
+ if (suite.root) return;
+ ++indents;
+ console.log('%s<section class="suite">', indent());
+ ++indents;
+ console.log('%s<h1>%s</h1>', indent(), utils.escape(suite.title));
+ console.log('%s<dl>', indent());
+ });
+
+ runner.on('suite end', function(suite){
+ if (suite.root) return;
+ console.log('%s</dl>', indent());
+ --indents;
+ console.log('%s</section>', indent());
+ --indents;
+ });
+
+ runner.on('pass', function(test){
+ console.log('%s <dt>%s</dt>', indent(), utils.escape(test.title));
+ var code = utils.escape(utils.clean(test.fn.toString()));
+ console.log('%s <dd><pre><code>%s</code></pre></dd>', indent(), code);
+ });
+}
+
+}); // module: reporters/doc.js
+
+require.register("reporters/dot.js", function(module, exports, require){
+
+/**
+ * Module dependencies.
+ */
+
+var Base = require('./base')
+ , color = Base.color;
+
+/**
+ * Expose `Dot`.
+ */
+
+exports = module.exports = Dot;
+
+/**
+ * Initialize a new `Dot` matrix test reporter.
+ *
+ * @param {Runner} runner
+ * @api public
+ */
+
+function Dot(runner) {
+ Base.call(this, runner);
+
+ var self = this
+ , stats = this.stats
+ , width = Base.window.width * .75 | 0
+ , n = 0;
+
+ runner.on('start', function(){
+ process.stdout.write('\n ');
+ });
+
+ runner.on('pending', function(test){
+ process.stdout.write(color('pending', Base.symbols.dot));
+ });
+
+ runner.on('pass', function(test){
+ if (++n % width == 0) process.stdout.write('\n ');
+ if ('slow' == test.speed) {
+ process.stdout.write(color('bright yellow', Base.symbols.dot));
+ } else {
+ process.stdout.write(color(test.speed, Base.symbols.dot));
+ }
+ });
+
+ runner.on('fail', function(test, err){
+ if (++n % width == 0) process.stdout.write('\n ');
+ process.stdout.write(color('fail', Base.symbols.dot));
+ });
+
+ runner.on('end', function(){
+ console.log();
+ self.epilogue();
+ });
+}
+
+/**
+ * Inherit from `Base.prototype`.
+ */
+
+function F(){};
+F.prototype = Base.prototype;
+Dot.prototype = new F;
+Dot.prototype.constructor = Dot;
+
+}); // module: reporters/dot.js
+
+require.register("reporters/html-cov.js", function(module, exports, require){
+
+/**
+ * Module dependencies.
+ */
+
+var JSONCov = require('./json-cov')
+ , fs = require('browser/fs');
+
+/**
+ * Expose `HTMLCov`.
+ */
+
+exports = module.exports = HTMLCov;
+
+/**
+ * Initialize a new `JsCoverage` reporter.
+ *
+ * @param {Runner} runner
+ * @api public
+ */
+
+function HTMLCov(runner) {
+ var jade = require('jade')
+ , file = __dirname + '/templates/coverage.jade'
+ , str = fs.readFileSync(file, 'utf8')
+ , fn = jade.compile(str, { filename: file })
+ , self = this;
+
+ JSONCov.call(this, runner, false);
+
+ runner.on('end', function(){
+ process.stdout.write(fn({
+ cov: self.cov
+ , coverageClass: coverageClass
+ }));
+ });
+}
+
+/**
+ * Return coverage class for `n`.
+ *
+ * @return {String}
+ * @api private
+ */
+
+function coverageClass(n) {
+ if (n >= 75) return 'high';
+ if (n >= 50) return 'medium';
+ if (n >= 25) return 'low';
+ return 'terrible';
+}
+}); // module: reporters/html-cov.js
+
+require.register("reporters/html.js", function(module, exports, require){
+
+/**
+ * Module dependencies.
+ */
+
+var Base = require('./base')
+ , utils = require('../utils')
+ , Progress = require('../browser/progress')
+ , escape = utils.escape;
+
+/**
+ * Save timer references to avoid Sinon interfering (see GH-237).
+ */
+
+var Date = global.Date
+ , setTimeout = global.setTimeout
+ , setInterval = global.setInterval
+ , clearTimeout = global.clearTimeout
+ , clearInterval = global.clearInterval;
+
+/**
+ * Expose `Doc`.
+ */
+
+exports = module.exports = HTML;
+
+/**
+ * Stats template.
+ */
+
+var statsTemplate = '<ul id="mocha-stats">'
+ + '<li class="progress"><canvas width="40" height="40"></canvas></li>'
+ + '<li class="passes"><a href="#">passes:</a> <em>0</em></li>'
+ + '<li class="failures"><a href="#">failures:</a> <em>0</em></li>'
+ + '<li class="duration">duration: <em>0</em>s</li>'
+ + '</ul>';
+
+/**
+ * Initialize a new `Doc` reporter.
+ *
+ * @param {Runner} runner
+ * @api public
+ */
+
+function HTML(runner, root) {
+ Base.call(this, runner);
+
+ var self = this
+ , stats = this.stats
+ , total = runner.total
+ , stat = fragment(statsTemplate)
+ , items = stat.getElementsByTagName('li')
+ , passes = items[1].getElementsByTagName('em')[0]
+ , passesLink = items[1].getElementsByTagName('a')[0]
+ , failures = items[2].getElementsByTagName('em')[0]
+ , failuresLink = items[2].getElementsByTagName('a')[0]
+ , duration = items[3].getElementsByTagName('em')[0]
+ , canvas = stat.getElementsByTagName('canvas')[0]
+ , report = fragment('<ul id="mocha-report"></ul>')
+ , stack = [report]
+ , progress
+ , ctx
+
+ root = root || document.getElementById('mocha');
+
+ if (canvas.getContext) {
+ var ratio = window.devicePixelRatio || 1;
+ canvas.style.width = canvas.width;
+ canvas.style.height = canvas.height;
+ canvas.width *= ratio;
+ canvas.height *= ratio;
+ ctx = canvas.getContext('2d');
+ ctx.scale(ratio, ratio);
+ progress = new Progress;
+ }
+
+ if (!root) return error('#mocha div missing, add it to your document');
+
+ // pass toggle
+ on(passesLink, 'click', function(){
+ unhide();
+ var name = /pass/.test(report.className) ? '' : ' pass';
+ report.className = report.className.replace(/fail|pass/g, '') + name;
+ if (report.className.trim()) hideSuitesWithout('test pass');
+ });
+
+ // failure toggle
+ on(failuresLink, 'click', function(){
+ unhide();
+ var name = /fail/.test(report.className) ? '' : ' fail';
+ report.className = report.className.replace(/fail|pass/g, '') + name;
+ if (report.className.trim()) hideSuitesWithout('test fail');
+ });
+
+ root.appendChild(stat);
+ root.appendChild(report);
+
+ if (progress) progress.size(40);
+
+ runner.on('suite', function(suite){
+ if (suite.root) return;
+
+ // suite
+ var url = '?grep=' + encodeURIComponent(suite.fullTitle());
+ var el = fragment('<li class="suite"><h1><a href="%s">%s</a></h1></li>', url, escape(suite.title));
+
+ // container
+ stack[0].appendChild(el);
+ stack.unshift(document.createElement('ul'));
+ el.appendChild(stack[0]);
+ });
+
+ runner.on('suite end', function(suite){
+ if (suite.root) return;
+ stack.shift();
+ });
+
+ runner.on('fail', function(test, err){
+ if ('hook' == test.type) runner.emit('test end', test);
+ });
+
+ runner.on('test end', function(test){
+ window.scrollTo(0, document.body.scrollHeight);
+
+ // TODO: add to stats
+ var percent = stats.tests / this.total * 100 | 0;
+ if (progress) progress.update(percent).draw(ctx);
+
+ // update stats
+ var ms = new Date - stats.start;
+ text(passes, stats.passes);
+ text(failures, stats.failures);
+ text(duration, (ms / 1000).toFixed(2));
+
+ // test
+ if ('passed' == test.state) {
+ var el = fragment('<li class="test pass %e"><h2>%e<span class="duration">%ems</span> <a href="?grep=%e" class="replay">‣</a></h2></li>', test.speed, test.title, test.duration, encodeURIComponent(test.fullTitle()));
+ } else if (test.pending) {
+ var el = fragment('<li class="test pass pending"><h2>%e</h2></li>', test.title);
+ } else {
+ var el = fragment('<li class="test fail"><h2>%e <a href="?grep=%e" class="replay">‣</a></h2></li>', test.title, encodeURIComponent(test.fullTitle()));
+ var str = test.err.stack || test.err.toString();
+
+ // FF / Opera do not add the message
+ if (!~str.indexOf(test.err.message)) {
+ str = test.err.message + '\n' + str;
+ }
+
+ // <=IE7 stringifies to [Object Error]. Since it can be overloaded, we
+ // check for the result of the stringifying.
+ if ('[object Error]' == str) str = test.err.message;
+
+ // Safari doesn't give you a stack. Let's at least provide a source line.
+ if (!test.err.stack && test.err.sourceURL && test.err.line !== undefined) {
+ str += "\n(" + test.err.sourceURL + ":" + test.err.line + ")";
+ }
+
+ el.appendChild(fragment('<pre class="error">%e</pre>', str));
+ }
+
+ // toggle code
+ // TODO: defer
+ if (!test.pending) {
+ var h2 = el.getElementsByTagName('h2')[0];
+
+ on(h2, 'click', function(){
+ pre.style.display = 'none' == pre.style.display
+ ? 'block'
+ : 'none';
+ });
+
+ var pre = fragment('<pre><code>%e</code></pre>', utils.clean(test.fn.toString()));
+ el.appendChild(pre);
+ pre.style.display = 'none';
+ }
+
+ // Don't call .appendChild if #mocha-report was already .shift()'ed off the stack.
+ if (stack[0]) stack[0].appendChild(el);
+ });
+}
+
+/**
+ * Display error `msg`.
+ */
+
+function error(msg) {
+ document.body.appendChild(fragment('<div id="mocha-error">%s</div>', msg));
+}
+
+/**
+ * Return a DOM fragment from `html`.
+ */
+
+function fragment(html) {
+ var args = arguments
+ , div = document.createElement('div')
+ , i = 1;
+
+ div.innerHTML = html.replace(/%([se])/g, function(_, type){
+ switch (type) {
+ case 's': return String(args[i++]);
+ case 'e': return escape(args[i++]);
+ }
+ });
+
+ return div.firstChild;
+}
+
+/**
+ * Check for suites that do not have elements
+ * with `classname`, and hide them.
+ */
+
+function hideSuitesWithout(classname) {
+ var suites = document.getElementsByClassName('suite');
+ for (var i = 0; i < suites.length; i++) {
+ var els = suites[i].getElementsByClassName(classname);
+ if (0 == els.length) suites[i].className += ' hidden';
+ }
+}
+
+/**
+ * Unhide .hidden suites.
+ */
+
+function unhide() {
+ var els = document.getElementsByClassName('suite hidden');
+ for (var i = 0; i < els.length; ++i) {
+ els[i].className = els[i].className.replace('suite hidden', 'suite');
+ }
+}
+
+/**
+ * Set `el` text to `str`.
+ */
+
+function text(el, str) {
+ if (el.textContent) {
+ el.textContent = str;
+ } else {
+ el.innerText = str;
+ }
+}
+
+/**
+ * Listen on `event` with callback `fn`.
+ */
+
+function on(el, event, fn) {
+ if (el.addEventListener) {
+ el.addEventListener(event, fn, false);
+ } else {
+ el.attachEvent('on' + event, fn);
+ }
+}
+
+}); // module: reporters/html.js
+
+require.register("reporters/index.js", function(module, exports, require){
+
+exports.Base = require('./base');
+exports.Dot = require('./dot');
+exports.Doc = require('./doc');
+exports.TAP = require('./tap');
+exports.JSON = require('./json');
+exports.HTML = require('./html');
+exports.List = require('./list');
+exports.Min = require('./min');
+exports.Spec = require('./spec');
+exports.Nyan = require('./nyan');
+exports.XUnit = require('./xunit');
+exports.Markdown = require('./markdown');
+exports.Progress = require('./progress');
+exports.Landing = require('./landing');
+exports.JSONCov = require('./json-cov');
+exports.HTMLCov = require('./html-cov');
+exports.JSONStream = require('./json-stream');
+exports.Teamcity = require('./teamcity');
+
+}); // module: reporters/index.js
+
+require.register("reporters/json-cov.js", function(module, exports, require){
+
+/**
+ * Module dependencies.
+ */
+
+var Base = require('./base');
+
+/**
+ * Expose `JSONCov`.
+ */
+
+exports = module.exports = JSONCov;
+
+/**
+ * Initialize a new `JsCoverage` reporter.
+ *
+ * @param {Runner} runner
+ * @param {Boolean} output
+ * @api public
+ */
+
+function JSONCov(runner, output) {
+ var self = this
+ , output = 1 == arguments.length ? true : output;
+
+ Base.call(this, runner);
+
+ var tests = []
+ , failures = []
+ , passes = [];
+
+ runner.on('test end', function(test){
+ tests.push(test);
+ });
+
+ runner.on('pass', function(test){
+ passes.push(test);
+ });
+
+ runner.on('fail', function(test){
+ failures.push(test);
+ });
+
+ runner.on('end', function(){
+ var cov = global._$jscoverage || {};
+ var result = self.cov = map(cov);
+ result.stats = self.stats;
+ result.tests = tests.map(clean);
+ result.failures = failures.map(clean);
+ result.passes = passes.map(clean);
+ if (!output) return;
+ process.stdout.write(JSON.stringify(result, null, 2 ));
+ });
+}
+
+/**
+ * Map jscoverage data to a JSON structure
+ * suitable for reporting.
+ *
+ * @param {Object} cov
+ * @return {Object}
+ * @api private
+ */
+
+function map(cov) {
+ var ret = {
+ instrumentation: 'node-jscoverage'
+ , sloc: 0
+ , hits: 0
+ , misses: 0
+ , coverage: 0
+ , files: []
+ };
+
+ for (var filename in cov) {
+ var data = coverage(filename, cov[filename]);
+ ret.files.push(data);
+ ret.hits += data.hits;
+ ret.misses += data.misses;
+ ret.sloc += data.sloc;
+ }
+
+ ret.files.sort(function(a, b) {
+ return a.filename.localeCompare(b.filename);
+ });
+
+ if (ret.sloc > 0) {
+ ret.coverage = (ret.hits / ret.sloc) * 100;
+ }
+
+ return ret;
+};
+
+/**
+ * Map jscoverage data for a single source file
+ * to a JSON structure suitable for reporting.
+ *
+ * @param {String} filename name of the source file
+ * @param {Object} data jscoverage coverage data
+ * @return {Object}
+ * @api private
+ */
+
+function coverage(filename, data) {
+ var ret = {
+ filename: filename,
+ coverage: 0,
+ hits: 0,
+ misses: 0,
+ sloc: 0,
+ source: {}
+ };
+
+ data.source.forEach(function(line, num){
+ num++;
+
+ if (data[num] === 0) {
+ ret.misses++;
+ ret.sloc++;
+ } else if (data[num] !== undefined) {
+ ret.hits++;
+ ret.sloc++;
+ }
+
+ ret.source[num] = {
+ source: line
+ , coverage: data[num] === undefined
+ ? ''
+ : data[num]
+ };
+ });
+
+ ret.coverage = ret.hits / ret.sloc * 100;
+
+ return ret;
+}
+
+/**
+ * Return a plain-object representation of `test`
+ * free of cyclic properties etc.
+ *
+ * @param {Object} test
+ * @return {Object}
+ * @api private
+ */
+
+function clean(test) {
+ return {
+ title: test.title
+ , fullTitle: test.fullTitle()
+ , duration: test.duration
+ }
+}
+
+}); // module: reporters/json-cov.js
+
+require.register("reporters/json-stream.js", function(module, exports, require){
+
+/**
+ * Module dependencies.
+ */
+
+var Base = require('./base')
+ , color = Base.color;
+
+/**
+ * Expose `List`.
+ */
+
+exports = module.exports = List;
+
+/**
+ * Initialize a new `List` test reporter.
+ *
+ * @param {Runner} runner
+ * @api public
+ */
+
+function List(runner) {
+ Base.call(this, runner);
+
+ var self = this
+ , stats = this.stats
+ , total = runner.total;
+
+ runner.on('start', function(){
+ console.log(JSON.stringify(['start', { total: total }]));
+ });
+
+ runner.on('pass', function(test){
+ console.log(JSON.stringify(['pass', clean(test)]));
+ });
+
+ runner.on('fail', function(test, err){
+ console.log(JSON.stringify(['fail', clean(test)]));
+ });
+
+ runner.on('end', function(){
+ process.stdout.write(JSON.stringify(['end', self.stats]));
+ });
+}
+
+/**
+ * Return a plain-object representation of `test`
+ * free of cyclic properties etc.
+ *
+ * @param {Object} test
+ * @return {Object}
+ * @api private
+ */
+
+function clean(test) {
+ return {
+ title: test.title
+ , fullTitle: test.fullTitle()
+ , duration: test.duration
+ }
+}
+}); // module: reporters/json-stream.js
+
+require.register("reporters/json.js", function(module, exports, require){
+
+/**
+ * Module dependencies.
+ */
+
+var Base = require('./base')
+ , cursor = Base.cursor
+ , color = Base.color;
+
+/**
+ * Expose `JSON`.
+ */
+
+exports = module.exports = JSONReporter;
+
+/**
+ * Initialize a new `JSON` reporter.
+ *
+ * @param {Runner} runner
+ * @api public
+ */
+
+function JSONReporter(runner) {
+ var self = this;
+ Base.call(this, runner);
+
+ var tests = []
+ , failures = []
+ , passes = [];
+
+ runner.on('test end', function(test){
+ tests.push(test);
+ });
+
+ runner.on('pass', function(test){
+ passes.push(test);
+ });
+
+ runner.on('fail', function(test){
+ failures.push(test);
+ });
+
+ runner.on('end', function(){
+ var obj = {
+ stats: self.stats
+ , tests: tests.map(clean)
+ , failures: failures.map(clean)
+ , passes: passes.map(clean)
+ };
+
+ process.stdout.write(JSON.stringify(obj, null, 2));
+ });
+}
+
+/**
+ * Return a plain-object representation of `test`
+ * free of cyclic properties etc.
+ *
+ * @param {Object} test
+ * @return {Object}
+ * @api private
+ */
+
+function clean(test) {
+ return {
+ title: test.title
+ , fullTitle: test.fullTitle()
+ , duration: test.duration
+ }
+}
+}); // module: reporters/json.js
+
+require.register("reporters/landing.js", function(module, exports, require){
+
+/**
+ * Module dependencies.
+ */
+
+var Base = require('./base')
+ , cursor = Base.cursor
+ , color = Base.color;
+
+/**
+ * Expose `Landing`.
+ */
+
+exports = module.exports = Landing;
+
+/**
+ * Airplane color.
+ */
+
+Base.colors.plane = 0;
+
+/**
+ * Airplane crash color.
+ */
+
+Base.colors['plane crash'] = 31;
+
+/**
+ * Runway color.
+ */
+
+Base.colors.runway = 90;
+
+/**
+ * Initialize a new `Landing` reporter.
+ *
+ * @param {Runner} runner
+ * @api public
+ */
+
+function Landing(runner) {
+ Base.call(this, runner);
+
+ var self = this
+ , stats = this.stats
+ , width = Base.window.width * .75 | 0
+ , total = runner.total
+ , stream = process.stdout
+ , plane = color('plane', '✈')
+ , crashed = -1
+ , n = 0;
+
+ function runway() {
+ var buf = Array(width).join('-');
+ return ' ' + color('runway', buf);
+ }
+
+ runner.on('start', function(){
+ stream.write('\n ');
+ cursor.hide();
+ });
+
+ runner.on('test end', function(test){
+ // check if the plane crashed
+ var col = -1 == crashed
+ ? width * ++n / total | 0
+ : crashed;
+
+ // show the crash
+ if ('failed' == test.state) {
+ plane = color('plane crash', '✈');
+ crashed = col;
+ }
+
+ // render landing strip
+ stream.write('\u001b[4F\n\n');
+ stream.write(runway());
+ stream.write('\n ');
+ stream.write(color('runway', Array(col).join('⋅')));
+ stream.write(plane)
+ stream.write(color('runway', Array(width - col).join('⋅') + '\n'));
+ stream.write(runway());
+ stream.write('\u001b[0m');
+ });
+
+ runner.on('end', function(){
+ cursor.show();
+ console.log();
+ self.epilogue();
+ });
+}
+
+/**
+ * Inherit from `Base.prototype`.
+ */
+
+function F(){};
+F.prototype = Base.prototype;
+Landing.prototype = new F;
+Landing.prototype.constructor = Landing;
+
+}); // module: reporters/landing.js
+
+require.register("reporters/list.js", function(module, exports, require){
+
+/**
+ * Module dependencies.
+ */
+
+var Base = require('./base')
+ , cursor = Base.cursor
+ , color = Base.color;
+
+/**
+ * Expose `List`.
+ */
+
+exports = module.exports = List;
+
+/**
+ * Initialize a new `List` test reporter.
+ *
+ * @param {Runner} runner
+ * @api public
+ */
+
+function List(runner) {
+ Base.call(this, runner);
+
+ var self = this
+ , stats = this.stats
+ , n = 0;
+
+ runner.on('start', function(){
+ console.log();
+ });
+
+ runner.on('test', function(test){
+ process.stdout.write(color('pass', ' ' + test.fullTitle() + ': '));
+ });
+
+ runner.on('pending', function(test){
+ var fmt = color('checkmark', ' -')
+ + color('pending', ' %s');
+ console.log(fmt, test.fullTitle());
+ });
+
+ runner.on('pass', function(test){
+ var fmt = color('checkmark', ' '+Base.symbols.dot)
+ + color('pass', ' %s: ')
+ + color(test.speed, '%dms');
+ cursor.CR();
+ console.log(fmt, test.fullTitle(), test.duration);
+ });
+
+ runner.on('fail', function(test, err){
+ cursor.CR();
+ console.log(color('fail', ' %d) %s'), ++n, test.fullTitle());
+ });
+
+ runner.on('end', self.epilogue.bind(self));
+}
+
+/**
+ * Inherit from `Base.prototype`.
+ */
+
+function F(){};
+F.prototype = Base.prototype;
+List.prototype = new F;
+List.prototype.constructor = List;
+
+
+}); // module: reporters/list.js
+
+require.register("reporters/markdown.js", function(module, exports, require){
+/**
+ * Module dependencies.
+ */
+
+var Base = require('./base')
+ , utils = require('../utils');
+
+/**
+ * Expose `Markdown`.
+ */
+
+exports = module.exports = Markdown;
+
+/**
+ * Initialize a new `Markdown` reporter.
+ *
+ * @param {Runner} runner
+ * @api public
+ */
+
+function Markdown(runner) {
+ Base.call(this, runner);
+
+ var self = this
+ , stats = this.stats
+ , level = 0
+ , buf = '';
+
+ function title(str) {
+ return Array(level).join('#') + ' ' + str;
+ }
+
+ function indent() {
+ return Array(level).join(' ');
+ }
+
+ function mapTOC(suite, obj) {
+ var ret = obj;
+ obj = obj[suite.title] = obj[suite.title] || { suite: suite };
+ suite.suites.forEach(function(suite){
+ mapTOC(suite, obj);
+ });
+ return ret;
+ }
+
+ function stringifyTOC(obj, level) {
+ ++level;
+ var buf = '';
+ var link;
+ for (var key in obj) {
+ if ('suite' == key) continue;
+ if (key) link = ' - [' + key + '](#' + utils.slug(obj[key].suite.fullTitle()) + ')\n';
+ if (key) buf += Array(level).join(' ') + link;
+ buf += stringifyTOC(obj[key], level);
+ }
+ --level;
+ return buf;
+ }
+
+ function generateTOC(suite) {
+ var obj = mapTOC(suite, {});
+ return stringifyTOC(obj, 0);
+ }
+
+ generateTOC(runner.suite);
+
+ runner.on('suite', function(suite){
+ ++level;
+ var slug = utils.slug(suite.fullTitle());
+ buf += '<a name="' + slug + '"></a>' + '\n';
+ buf += title(suite.title) + '\n';
+ });
+
+ runner.on('suite end', function(suite){
+ --level;
+ });
+
+ runner.on('pass', function(test){
+ var code = utils.clean(test.fn.toString());
+ buf += test.title + '.\n';
+ buf += '\n```js\n';
+ buf += code + '\n';
+ buf += '```\n\n';
+ });
+
+ runner.on('end', function(){
+ process.stdout.write('# TOC\n');
+ process.stdout.write(generateTOC(runner.suite));
+ process.stdout.write(buf);
+ });
+}
+}); // module: reporters/markdown.js
+
+require.register("reporters/min.js", function(module, exports, require){
+
+/**
+ * Module dependencies.
+ */
+
+var Base = require('./base');
+
+/**
+ * Expose `Min`.
+ */
+
+exports = module.exports = Min;
+
+/**
+ * Initialize a new `Min` minimal test reporter (best used with --watch).
+ *
+ * @param {Runner} runner
+ * @api public
+ */
+
+function Min(runner) {
+ Base.call(this, runner);
+
+ runner.on('start', function(){
+ // clear screen
+ process.stdout.write('\u001b[2J');
+ // set cursor position
+ process.stdout.write('\u001b[1;3H');
+ });
+
+ runner.on('end', this.epilogue.bind(this));
+}
+
+/**
+ * Inherit from `Base.prototype`.
+ */
+
+function F(){};
+F.prototype = Base.prototype;
+Min.prototype = new F;
+Min.prototype.constructor = Min;
+
+}); // module: reporters/min.js
+
+require.register("reporters/nyan.js", function(module, exports, require){
+
+/**
+ * Module dependencies.
+ */
+
+var Base = require('./base')
+ , color = Base.color;
+
+/**
+ * Expose `Dot`.
+ */
+
+exports = module.exports = NyanCat;
+
+/**
+ * Initialize a new `Dot` matrix test reporter.
+ *
+ * @param {Runner} runner
+ * @api public
+ */
+
+function NyanCat(runner) {
+ Base.call(this, runner);
+
+ var self = this
+ , stats = this.stats
+ , width = Base.window.width * .75 | 0
+ , rainbowColors = this.rainbowColors = self.generateColors()
+ , colorIndex = this.colorIndex = 0
+ , numerOfLines = this.numberOfLines = 4
+ , trajectories = this.trajectories = [[], [], [], []]
+ , nyanCatWidth = this.nyanCatWidth = 11
+ , trajectoryWidthMax = this.trajectoryWidthMax = (width - nyanCatWidth)
+ , scoreboardWidth = this.scoreboardWidth = 5
+ , tick = this.tick = 0
+ , n = 0;
+
+ runner.on('start', function(){
+ Base.cursor.hide();
+ self.draw('start');
+ });
+
+ runner.on('pending', function(test){
+ self.draw('pending');
+ });
+
+ runner.on('pass', function(test){
+ self.draw('pass');
+ });
+
+ runner.on('fail', function(test, err){
+ self.draw('fail');
+ });
+
+ runner.on('end', function(){
+ Base.cursor.show();
+ for (var i = 0; i < self.numberOfLines; i++) write('\n');
+ self.epilogue();
+ });
+}
+
+/**
+ * Draw the nyan cat with runner `status`.
+ *
+ * @param {String} status
+ * @api private
+ */
+
+NyanCat.prototype.draw = function(status){
+ this.appendRainbow();
+ this.drawScoreboard();
+ this.drawRainbow();
+ this.drawNyanCat(status);
+ this.tick = !this.tick;
+};
+
+/**
+ * Draw the "scoreboard" showing the number
+ * of passes, failures and pending tests.
+ *
+ * @api private
+ */
+
+NyanCat.prototype.drawScoreboard = function(){
+ var stats = this.stats;
+ var colors = Base.colors;
+
+ function draw(color, n) {
+ write(' ');
+ write('\u001b[' + color + 'm' + n + '\u001b[0m');
+ write('\n');
+ }
+
+ draw(colors.green, stats.passes);
+ draw(colors.fail, stats.failures);
+ draw(colors.pending, stats.pending);
+ write('\n');
+
+ this.cursorUp(this.numberOfLines);
+};
+
+/**
+ * Append the rainbow.
+ *
+ * @api private
+ */
+
+NyanCat.prototype.appendRainbow = function(){
+ var segment = this.tick ? '_' : '-';
+ var rainbowified = this.rainbowify(segment);
+
+ for (var index = 0; index < this.numberOfLines; index++) {
+ var trajectory = this.trajectories[index];
+ if (trajectory.length >= this.trajectoryWidthMax) trajectory.shift();
+ trajectory.push(rainbowified);
+ }
+};
+
+/**
+ * Draw the rainbow.
+ *
+ * @api private
+ */
+
+NyanCat.prototype.drawRainbow = function(){
+ var self = this;
+
+ this.trajectories.forEach(function(line, index) {
+ write('\u001b[' + self.scoreboardWidth + 'C');
+ write(line.join(''));
+ write('\n');
+ });
+
+ this.cursorUp(this.numberOfLines);
+};
+
+/**
+ * Draw the nyan cat with `status`.
+ *
+ * @param {String} status
+ * @api private
+ */
+
+NyanCat.prototype.drawNyanCat = function(status) {
+ var self = this;
+ var startWidth = this.scoreboardWidth + this.trajectories[0].length;
+
+ [0, 1, 2, 3].forEach(function(index) {
+ write('\u001b[' + startWidth + 'C');
+
+ switch (index) {
+ case 0:
+ write('_,------,');
+ write('\n');
+ break;
+ case 1:
+ var padding = self.tick ? ' ' : ' ';
+ write('_|' + padding + '/\\_/\\ ');
+ write('\n');
+ break;
+ case 2:
+ var padding = self.tick ? '_' : '__';
+ var tail = self.tick ? '~' : '^';
+ var face;
+ switch (status) {
+ case 'pass':
+ face = '( ^ .^)';
+ break;
+ case 'fail':
+ face = '( o .o)';
+ break;
+ default:
+ face = '( - .-)';
+ }
+ write(tail + '|' + padding + face + ' ');
+ write('\n');
+ break;
+ case 3:
+ var padding = self.tick ? ' ' : ' ';
+ write(padding + '"" "" ');
+ write('\n');
+ break;
+ }
+ });
+
+ this.cursorUp(this.numberOfLines);
+};
+
+/**
+ * Move cursor up `n`.
+ *
+ * @param {Number} n
+ * @api private
+ */
+
+NyanCat.prototype.cursorUp = function(n) {
+ write('\u001b[' + n + 'A');
+};
+
+/**
+ * Move cursor down `n`.
+ *
+ * @param {Number} n
+ * @api private
+ */
+
+NyanCat.prototype.cursorDown = function(n) {
+ write('\u001b[' + n + 'B');
+};
+
+/**
+ * Generate rainbow colors.
+ *
+ * @return {Array}
+ * @api private
+ */
+
+NyanCat.prototype.generateColors = function(){
+ var colors = [];
+
+ for (var i = 0; i < (6 * 7); i++) {
+ var pi3 = Math.floor(Math.PI / 3);
+ var n = (i * (1.0 / 6));
+ var r = Math.floor(3 * Math.sin(n) + 3);
+ var g = Math.floor(3 * Math.sin(n + 2 * pi3) + 3);
+ var b = Math.floor(3 * Math.sin(n + 4 * pi3) + 3);
+ colors.push(36 * r + 6 * g + b + 16);
+ }
+
+ return colors;
+};
+
+/**
+ * Apply rainbow to the given `str`.
+ *
+ * @param {String} str
+ * @return {String}
+ * @api private
+ */
+
+NyanCat.prototype.rainbowify = function(str){
+ var color = this.rainbowColors[this.colorIndex % this.rainbowColors.length];
+ this.colorIndex += 1;
+ return '\u001b[38;5;' + color + 'm' + str + '\u001b[0m';
+};
+
+/**
+ * Stdout helper.
+ */
+
+function write(string) {
+ process.stdout.write(string);
+}
+
+/**
+ * Inherit from `Base.prototype`.
+ */
+
+function F(){};
+F.prototype = Base.prototype;
+NyanCat.prototype = new F;
+NyanCat.prototype.constructor = NyanCat;
+
+
+}); // module: reporters/nyan.js
+
+require.register("reporters/progress.js", function(module, exports, require){
+
+/**
+ * Module dependencies.
+ */
+
+var Base = require('./base')
+ , cursor = Base.cursor
+ , color = Base.color;
+
+/**
+ * Expose `Progress`.
+ */
+
+exports = module.exports = Progress;
+
+/**
+ * General progress bar color.
+ */
+
+Base.colors.progress = 90;
+
+/**
+ * Initialize a new `Progress` bar test reporter.
+ *
+ * @param {Runner} runner
+ * @param {Object} options
+ * @api public
+ */
+
+function Progress(runner, options) {
+ Base.call(this, runner);
+
+ var self = this
+ , options = options || {}
+ , stats = this.stats
+ , width = Base.window.width * .50 | 0
+ , total = runner.total
+ , complete = 0
+ , max = Math.max;
+
+ // default chars
+ options.open = options.open || '[';
+ options.complete = options.complete || '▬';
+ options.incomplete = options.incomplete || Base.symbols.dot;
+ options.close = options.close || ']';
+ options.verbose = false;
+
+ // tests started
+ runner.on('start', function(){
+ console.log();
+ cursor.hide();
+ });
+
+ // tests complete
+ runner.on('test end', function(){
+ complete++;
+ var incomplete = total - complete
+ , percent = complete / total
+ , n = width * percent | 0
+ , i = width - n;
+
+ cursor.CR();
+ process.stdout.write('\u001b[J');
+ process.stdout.write(color('progress', ' ' + options.open));
+ process.stdout.write(Array(n).join(options.complete));
+ process.stdout.write(Array(i).join(options.incomplete));
+ process.stdout.write(color('progress', options.close));
+ if (options.verbose) {
+ process.stdout.write(color('progress', ' ' + complete + ' of ' + total));
+ }
+ });
+
+ // tests are complete, output some stats
+ // and the failures if any
+ runner.on('end', function(){
+ cursor.show();
+ console.log();
+ self.epilogue();
+ });
+}
+
+/**
+ * Inherit from `Base.prototype`.
+ */
+
+function F(){};
+F.prototype = Base.prototype;
+Progress.prototype = new F;
+Progress.prototype.constructor = Progress;
+
+
+}); // module: reporters/progress.js
+
+require.register("reporters/spec.js", function(module, exports, require){
+
+/**
+ * Module dependencies.
+ */
+
+var Base = require('./base')
+ , cursor = Base.cursor
+ , color = Base.color;
+
+/**
+ * Expose `Spec`.
+ */
+
+exports = module.exports = Spec;
+
+/**
+ * Initialize a new `Spec` test reporter.
+ *
+ * @param {Runner} runner
+ * @api public
+ */
+
+function Spec(runner) {
+ Base.call(this, runner);
+
+ var self = this
+ , stats = this.stats
+ , indents = 0
+ , n = 0;
+
+ function indent() {
+ return Array(indents).join(' ')
+ }
+
+ runner.on('start', function(){
+ console.log();
+ });
+
+ runner.on('suite', function(suite){
+ ++indents;
+ console.log(color('suite', '%s%s'), indent(), suite.title);
+ });
+
+ runner.on('suite end', function(suite){
+ --indents;
+ if (1 == indents) console.log();
+ });
+
+ runner.on('test', function(test){
+ process.stdout.write(indent() + color('pass', ' ◦ ' + test.title + ': '));
+ });
+
+ runner.on('pending', function(test){
+ var fmt = indent() + color('pending', ' - %s');
+ console.log(fmt, test.title);
+ });
+
+ runner.on('pass', function(test){
+ if ('fast' == test.speed) {
+ var fmt = indent()
+ + color('checkmark', ' ' + Base.symbols.ok)
+ + color('pass', ' %s ');
+ cursor.CR();
+ console.log(fmt, test.title);
+ } else {
+ var fmt = indent()
+ + color('checkmark', ' ' + Base.symbols.ok)
+ + color('pass', ' %s ')
+ + color(test.speed, '(%dms)');
+ cursor.CR();
+ console.log(fmt, test.title, test.duration);
+ }
+ });
+
+ runner.on('fail', function(test, err){
+ cursor.CR();
+ console.log(indent() + color('fail', ' %d) %s'), ++n, test.title);
+ });
+
+ runner.on('end', self.epilogue.bind(self));
+}
+
+/**
+ * Inherit from `Base.prototype`.
+ */
+
+function F(){};
+F.prototype = Base.prototype;
+Spec.prototype = new F;
+Spec.prototype.constructor = Spec;
+
+
+}); // module: reporters/spec.js
+
+require.register("reporters/tap.js", function(module, exports, require){
+
+/**
+ * Module dependencies.
+ */
+
+var Base = require('./base')
+ , cursor = Base.cursor
+ , color = Base.color;
+
+/**
+ * Expose `TAP`.
+ */
+
+exports = module.exports = TAP;
+
+/**
+ * Initialize a new `TAP` reporter.
+ *
+ * @param {Runner} runner
+ * @api public
+ */
+
+function TAP(runner) {
+ Base.call(this, runner);
+
+ var self = this
+ , stats = this.stats
+ , n = 1
+ , passes = 0
+ , failures = 0;
+
+ runner.on('start', function(){
+ var total = runner.grepTotal(runner.suite);
+ console.log('%d..%d', 1, total);
+ });
+
+ runner.on('test end', function(){
+ ++n;
+ });
+
+ runner.on('pending', function(test){
+ console.log('ok %d %s # SKIP -', n, title(test));
+ });
+
+ runner.on('pass', function(test){
+ passes++;
+ console.log('ok %d %s', n, title(test));
+ });
+
+ runner.on('fail', function(test, err){
+ failures++;
+ console.log('not ok %d %s', n, title(test));
+ if (err.stack) console.log(err.stack.replace(/^/gm, ' '));
+ });
+
+ runner.on('end', function(){
+ console.log('# tests ' + (passes + failures));
+ console.log('# pass ' + passes);
+ console.log('# fail ' + failures);
+ });
+}
+
+/**
+ * Return a TAP-safe title of `test`
+ *
+ * @param {Object} test
+ * @return {String}
+ * @api private
+ */
+
+function title(test) {
+ return test.fullTitle().replace(/#/g, '');
+}
+
+}); // module: reporters/tap.js
+
+require.register("reporters/teamcity.js", function(module, exports, require){
+
+/**
+ * Module dependencies.
+ */
+
+var Base = require('./base');
+
+/**
+ * Expose `Teamcity`.
+ */
+
+exports = module.exports = Teamcity;
+
+/**
+ * Initialize a new `Teamcity` reporter.
+ *
+ * @param {Runner} runner
+ * @api public
+ */
+
+function Teamcity(runner) {
+ Base.call(this, runner);
+ var stats = this.stats;
+
+ runner.on('start', function() {
+ console.log("##teamcity[testSuiteStarted name='mocha.suite']");
+ });
+
+ runner.on('test', function(test) {
+ console.log("##teamcity[testStarted name='" + escape(test.fullTitle()) + "']");
+ });
+
+ runner.on('fail', function(test, err) {
+ console.log("##teamcity[testFailed name='" + escape(test.fullTitle()) + "' message='" + escape(err.message) + "']");
+ });
+
+ runner.on('pending', function(test) {
+ console.log("##teamcity[testIgnored name='" + escape(test.fullTitle()) + "' message='pending']");
+ });
+
+ runner.on('test end', function(test) {
+ console.log("##teamcity[testFinished name='" + escape(test.fullTitle()) + "' duration='" + test.duration + "']");
+ });
+
+ runner.on('end', function() {
+ console.log("##teamcity[testSuiteFinished name='mocha.suite' duration='" + stats.duration + "']");
+ });
+}
+
+/**
+ * Escape the given `str`.
+ */
+
+function escape(str) {
+ return str
+ .replace(/\|/g, "||")
+ .replace(/\n/g, "|n")
+ .replace(/\r/g, "|r")
+ .replace(/\[/g, "|[")
+ .replace(/\]/g, "|]")
+ .replace(/\u0085/g, "|x")
+ .replace(/\u2028/g, "|l")
+ .replace(/\u2029/g, "|p")
+ .replace(/'/g, "|'");
+}
+
+}); // module: reporters/teamcity.js
+
+require.register("reporters/xunit.js", function(module, exports, require){
+
+/**
+ * Module dependencies.
+ */
+
+var Base = require('./base')
+ , utils = require('../utils')
+ , escape = utils.escape;
+
+/**
+ * Save timer references to avoid Sinon interfering (see GH-237).
+ */
+
+var Date = global.Date
+ , setTimeout = global.setTimeout
+ , setInterval = global.setInterval
+ , clearTimeout = global.clearTimeout
+ , clearInterval = global.clearInterval;
+
+/**
+ * Expose `XUnit`.
+ */
+
+exports = module.exports = XUnit;
+
+/**
+ * Initialize a new `XUnit` reporter.
+ *
+ * @param {Runner} runner
+ * @api public
+ */
+
+function XUnit(runner) {
+ Base.call(this, runner);
+ var stats = this.stats
+ , tests = []
+ , self = this;
+
+ runner.on('pass', function(test){
+ tests.push(test);
+ });
+
+ runner.on('fail', function(test){
+ tests.push(test);
+ });
+
+ runner.on('end', function(){
+ console.log(tag('testsuite', {
+ name: 'Mocha Tests'
+ , tests: stats.tests
+ , failures: stats.failures
+ , errors: stats.failures
+ , skip: stats.tests - stats.failures - stats.passes
+ , timestamp: (new Date).toUTCString()
+ , time: stats.duration / 1000
+ }, false));
+
+ tests.forEach(test);
+ console.log('</testsuite>');
+ });
+}
+
+/**
+ * Inherit from `Base.prototype`.
+ */
+
+function F(){};
+F.prototype = Base.prototype;
+XUnit.prototype = new F;
+XUnit.prototype.constructor = XUnit;
+
+
+/**
+ * Output tag for the given `test.`
+ */
+
+function test(test) {
+ var attrs = {
+ classname: test.parent.fullTitle()
+ , name: test.title
+ , time: test.duration / 1000
+ };
+
+ if ('failed' == test.state) {
+ var err = test.err;
+ attrs.message = escape(err.message);
+ console.log(tag('testcase', attrs, false, tag('failure', attrs, false, cdata(err.stack))));
+ } else if (test.pending) {
+ console.log(tag('testcase', attrs, false, tag('skipped', {}, true)));
+ } else {
+ console.log(tag('testcase', attrs, true) );
+ }
+}
+
+/**
+ * HTML tag helper.
+ */
+
+function tag(name, attrs, close, content) {
+ var end = close ? '/>' : '>'
+ , pairs = []
+ , tag;
+
+ for (var key in attrs) {
+ pairs.push(key + '="' + escape(attrs[key]) + '"');
+ }
+
+ tag = '<' + name + (pairs.length ? ' ' + pairs.join(' ') : '') + end;
+ if (content) tag += content + '</' + name + end;
+ return tag;
+}
+
+/**
+ * Return cdata escaped CDATA `str`.
+ */
+
+function cdata(str) {
+ return '<![CDATA[' + escape(str) + ']]>';
+}
+
+}); // module: reporters/xunit.js
+
+require.register("runnable.js", function(module, exports, require){
+
+/**
+ * Module dependencies.
+ */
+
+var EventEmitter = require('browser/events').EventEmitter
+ , debug = require('browser/debug')('mocha:runnable')
+ , milliseconds = require('./ms');
+
+/**
+ * Save timer references to avoid Sinon interfering (see GH-237).
+ */
+
+var Date = global.Date
+ , setTimeout = global.setTimeout
+ , setInterval = global.setInterval
+ , clearTimeout = global.clearTimeout
+ , clearInterval = global.clearInterval;
+
+/**
+ * Object#toString().
+ */
+
+var toString = Object.prototype.toString;
+
+/**
+ * Expose `Runnable`.
+ */
+
+module.exports = Runnable;
+
+/**
+ * Initialize a new `Runnable` with the given `title` and callback `fn`.
+ *
+ * @param {String} title
+ * @param {Function} fn
+ * @api private
+ */
+
+function Runnable(title, fn) {
+ this.title = title;
+ this.fn = fn;
+ this.async = fn && fn.length;
+ this.sync = ! this.async;
+ this._timeout = 2000;
+ this._slow = 75;
+ this.timedOut = false;
+}
+
+/**
+ * Inherit from `EventEmitter.prototype`.
+ */
+
+function F(){};
+F.prototype = EventEmitter.prototype;
+Runnable.prototype = new F;
+Runnable.prototype.constructor = Runnable;
+
+
+/**
+ * Set & get timeout `ms`.
+ *
+ * @param {Number|String} ms
+ * @return {Runnable|Number} ms or self
+ * @api private
+ */
+
+Runnable.prototype.timeout = function(ms){
+ if (0 == arguments.length) return this._timeout;
+ if ('string' == typeof ms) ms = milliseconds(ms);
+ debug('timeout %d', ms);
+ this._timeout = ms;
+ if (this.timer) this.resetTimeout();
+ return this;
+};
+
+/**
+ * Set & get slow `ms`.
+ *
+ * @param {Number|String} ms
+ * @return {Runnable|Number} ms or self
+ * @api private
+ */
+
+Runnable.prototype.slow = function(ms){
+ if (0 === arguments.length) return this._slow;
+ if ('string' == typeof ms) ms = milliseconds(ms);
+ debug('timeout %d', ms);
+ this._slow = ms;
+ return this;
+};
+
+/**
+ * Return the full title generated by recursively
+ * concatenating the parent's full title.
+ *
+ * @return {String}
+ * @api public
+ */
+
+Runnable.prototype.fullTitle = function(){
+ return this.parent.fullTitle() + ' ' + this.title;
+};
+
+/**
+ * Clear the timeout.
+ *
+ * @api private
+ */
+
+Runnable.prototype.clearTimeout = function(){
+ clearTimeout(this.timer);
+};
+
+/**
+ * Inspect the runnable void of private properties.
+ *
+ * @return {String}
+ * @api private
+ */
+
+Runnable.prototype.inspect = function(){
+ return JSON.stringify(this, function(key, val){
+ if ('_' == key[0]) return;
+ if ('parent' == key) return '#<Suite>';
+ if ('ctx' == key) return '#<Context>';
+ return val;
+ }, 2);
+};
+
+/**
+ * Reset the timeout.
+ *
+ * @api private
+ */
+
+Runnable.prototype.resetTimeout = function(){
+ var self = this
+ , ms = this.timeout();
+
+ this.clearTimeout();
+ if (ms) {
+ this.timer = setTimeout(function(){
+ self.callback(new Error('timeout of ' + ms + 'ms exceeded'));
+ self.timedOut = true;
+ }, ms);
+ }
+};
+
+/**
+ * Run the test and invoke `fn(err)`.
+ *
+ * @param {Function} fn
+ * @api private
+ */
+
+Runnable.prototype.run = function(fn){
+ var self = this
+ , ms = this.timeout()
+ , start = new Date
+ , ctx = this.ctx
+ , finished
+ , emitted;
+
+ if (ctx) ctx.runnable(this);
+
+ // timeout
+ if (this.async) {
+ if (ms) {
+ this.timer = setTimeout(function(){
+ done(new Error('timeout of ' + ms + 'ms exceeded'));
+ self.timedOut = true;
+ }, ms);
+ }
+ }
+
+ // called multiple times
+ function multiple(err) {
+ if (emitted) return;
+ emitted = true;
+ self.emit('error', err || new Error('done() called multiple times'));
+ }
+
+ // finished
+ function done(err) {
+ if (self.timedOut) return;
+ if (finished) return multiple(err);
+ self.clearTimeout();
+ self.duration = new Date - start;
+ finished = true;
+ fn(err);
+ }
+
+ // for .resetTimeout()
+ this.callback = done;
+
+ // async
+ if (this.async) {
+ try {
+ this.fn.call(ctx, function(err){
+ if (err instanceof Error || toString.call(err) === "[object Error]") return done(err);
+ if (null != err) return done(new Error('done() invoked with non-Error: ' + err));
+ done();
+ });
+ } catch (err) {
+ done(err);
+ }
+ return;
+ }
+
+ if (this.asyncOnly) {
+ return done(new Error('--async-only option in use without declaring `done()`'));
+ }
+
+ // sync
+ try {
+ if (!this.pending) this.fn.call(ctx);
+ this.duration = new Date - start;
+ fn();
+ } catch (err) {
+ fn(err);
+ }
+};
+
+}); // module: runnable.js
+
+require.register("runner.js", function(module, exports, require){
+
+/**
+ * Module dependencies.
+ */
+
+var EventEmitter = require('browser/events').EventEmitter
+ , debug = require('browser/debug')('mocha:runner')
+ , Test = require('./test')
+ , utils = require('./utils')
+ , filter = utils.filter
+ , keys = utils.keys
+ , noop = function(){}
+ , immediately = global.setImmediate || process.nextTick;
+
+/**
+ * Non-enumerable globals.
+ */
+
+var globals = [
+ 'setTimeout',
+ 'clearTimeout',
+ 'setInterval',
+ 'clearInterval',
+ 'XMLHttpRequest',
+ 'Date'
+];
+
+/**
+ * Expose `Runner`.
+ */
+
+module.exports = Runner;
+
+/**
+ * Initialize a `Runner` for the given `suite`.
+ *
+ * Events:
+ *
+ * - `start` execution started
+ * - `end` execution complete
+ * - `suite` (suite) test suite execution started
+ * - `suite end` (suite) all tests (and sub-suites) have finished
+ * - `test` (test) test execution started
+ * - `test end` (test) test completed
+ * - `hook` (hook) hook execution started
+ * - `hook end` (hook) hook complete
+ * - `pass` (test) test passed
+ * - `fail` (test, err) test failed
+ *
+ * @api public
+ */
+
+function Runner(suite) {
+ var self = this;
+ this._globals = [];
+ this.suite = suite;
+ this.total = suite.total();
+ this.failures = 0;
+ this.on('test end', function(test){ self.checkGlobals(test); });
+ this.on('hook end', function(hook){ self.checkGlobals(hook); });
+ this.grep(/.*/);
+ this.globals(this.globalProps().concat(['errno']));
+}
+
+/**
+ * Inherit from `EventEmitter.prototype`.
+ */
+
+function F(){};
+F.prototype = EventEmitter.prototype;
+Runner.prototype = new F;
+Runner.prototype.constructor = Runner;
+
+
+/**
+ * Run tests with full titles matching `re`. Updates runner.total
+ * with number of tests matched.
+ *
+ * @param {RegExp} re
+ * @param {Boolean} invert
+ * @return {Runner} for chaining
+ * @api public
+ */
+
+Runner.prototype.grep = function(re, invert){
+ debug('grep %s', re);
+ this._grep = re;
+ this._invert = invert;
+ this.total = this.grepTotal(this.suite);
+ return this;
+};
+
+/**
+ * Returns the number of tests matching the grep search for the
+ * given suite.
+ *
+ * @param {Suite} suite
+ * @return {Number}
+ * @api public
+ */
+
+Runner.prototype.grepTotal = function(suite) {
+ var self = this;
+ var total = 0;
+
+ suite.eachTest(function(test){
+ var match = self._grep.test(test.fullTitle());
+ if (self._invert) match = !match;
+ if (match) total++;
+ });
+
+ return total;
+};
+
+/**
+ * Return a list of global properties.
+ *
+ * @return {Array}
+ * @api private
+ */
+
+Runner.prototype.globalProps = function() {
+ var props = utils.keys(global);
+
+ // non-enumerables
+ for (var i = 0; i < globals.length; ++i) {
+ if (~utils.indexOf(props, globals[i])) continue;
+ props.push(globals[i]);
+ }
+
+ return props;
+};
+
+/**
+ * Allow the given `arr` of globals.
+ *
+ * @param {Array} arr
+ * @return {Runner} for chaining
+ * @api public
+ */
+
+Runner.prototype.globals = function(arr){
+ if (0 == arguments.length) return this._globals;
+ debug('globals %j', arr);
+ utils.forEach(arr, function(arr){
+ this._globals.push(arr);
+ }, this);
+ return this;
+};
+
+/**
+ * Check for global variable leaks.
+ *
+ * @api private
+ */
+
+Runner.prototype.checkGlobals = function(test){
+ if (this.ignoreLeaks) return;
+ var ok = this._globals;
+ var globals = this.globalProps();
+ var isNode = process.kill;
+ var leaks;
+
+ // check length - 2 ('errno' and 'location' globals)
+ if (isNode && 1 == ok.length - globals.length) return
+ else if (2 == ok.length - globals.length) return;
+
+ leaks = filterLeaks(ok, globals);
+ this._globals = this._globals.concat(leaks);
+
+ if (leaks.length > 1) {
+ this.fail(test, new Error('global leaks detected: ' + leaks.join(', ') + ''));
+ } else if (leaks.length) {
+ this.fail(test, new Error('global leak detected: ' + leaks[0]));
+ }
+};
+
+/**
+ * Fail the given `test`.
+ *
+ * @param {Test} test
+ * @param {Error} err
+ * @api private
+ */
+
+Runner.prototype.fail = function(test, err){
+ ++this.failures;
+ test.state = 'failed';
+
+ if ('string' == typeof err) {
+ err = new Error('the string "' + err + '" was thrown, throw an Error :)');
+ }
+
+ this.emit('fail', test, err);
+};
+
+/**
+ * Fail the given `hook` with `err`.
+ *
+ * Hook failures (currently) hard-end due
+ * to that fact that a failing hook will
+ * surely cause subsequent tests to fail,
+ * causing jumbled reporting.
+ *
+ * @param {Hook} hook
+ * @param {Error} err
+ * @api private
+ */
+
+Runner.prototype.failHook = function(hook, err){
+ this.fail(hook, err);
+ this.emit('end');
+};
+
+/**
+ * Run hook `name` callbacks and then invoke `fn()`.
+ *
+ * @param {String} name
+ * @param {Function} function
+ * @api private
+ */
+
+Runner.prototype.hook = function(name, fn){
+ var suite = this.suite
+ , hooks = suite['_' + name]
+ , self = this
+ , timer;
+
+ function next(i) {
+ var hook = hooks[i];
+ if (!hook) return fn();
+ self.currentRunnable = hook;
+
+ self.emit('hook', hook);
+
+ hook.on('error', function(err){
+ self.failHook(hook, err);
+ });
+
+ hook.run(function(err){
+ hook.removeAllListeners('error');
+ var testError = hook.error();
+ if (testError) self.fail(self.test, testError);
+ if (err) return self.failHook(hook, err);
+ self.emit('hook end', hook);
+ next(++i);
+ });
+ }
+
+ immediately(function(){
+ next(0);
+ });
+};
+
+/**
+ * Run hook `name` for the given array of `suites`
+ * in order, and callback `fn(err)`.
+ *
+ * @param {String} name
+ * @param {Array} suites
+ * @param {Function} fn
+ * @api private
+ */
+
+Runner.prototype.hooks = function(name, suites, fn){
+ var self = this
+ , orig = this.suite;
+
+ function next(suite) {
+ self.suite = suite;
+
+ if (!suite) {
+ self.suite = orig;
+ return fn();
+ }
+
+ self.hook(name, function(err){
+ if (err) {
+ self.suite = orig;
+ return fn(err);
+ }
+
+ next(suites.pop());
+ });
+ }
+
+ next(suites.pop());
+};
+
+/**
+ * Run hooks from the top level down.
+ *
+ * @param {String} name
+ * @param {Function} fn
+ * @api private
+ */
+
+Runner.prototype.hookUp = function(name, fn){
+ var suites = [this.suite].concat(this.parents()).reverse();
+ this.hooks(name, suites, fn);
+};
+
+/**
+ * Run hooks from the bottom up.
+ *
+ * @param {String} name
+ * @param {Function} fn
+ * @api private
+ */
+
+Runner.prototype.hookDown = function(name, fn){
+ var suites = [this.suite].concat(this.parents());
+ this.hooks(name, suites, fn);
+};
+
+/**
+ * Return an array of parent Suites from
+ * closest to furthest.
+ *
+ * @return {Array}
+ * @api private
+ */
+
+Runner.prototype.parents = function(){
+ var suite = this.suite
+ , suites = [];
+ while (suite = suite.parent) suites.push(suite);
+ return suites;
+};
+
+/**
+ * Run the current test and callback `fn(err)`.
+ *
+ * @param {Function} fn
+ * @api private
+ */
+
+Runner.prototype.runTest = function(fn){
+ var test = this.test
+ , self = this;
+
+ if (this.asyncOnly) test.asyncOnly = true;
+
+ try {
+ test.on('error', function(err){
+ self.fail(test, err);
+ });
+ test.run(fn);
+ } catch (err) {
+ fn(err);
+ }
+};
+
+/**
+ * Run tests in the given `suite` and invoke
+ * the callback `fn()` when complete.
+ *
+ * @param {Suite} suite
+ * @param {Function} fn
+ * @api private
+ */
+
+Runner.prototype.runTests = function(suite, fn){
+ var self = this
+ , tests = suite.tests.slice()
+ , test;
+
+ function next(err) {
+ // if we bail after first err
+ if (self.failures && suite._bail) return fn();
+
+ // next test
+ test = tests.shift();
+
+ // all done
+ if (!test) return fn();
+
+ // grep
+ var match = self._grep.test(test.fullTitle());
+ if (self._invert) match = !match;
+ if (!match) return next();
+
+ // pending
+ if (test.pending) {
+ self.emit('pending', test);
+ self.emit('test end', test);
+ return next();
+ }
+
+ // execute test and hook(s)
+ self.emit('test', self.test = test);
+ self.hookDown('beforeEach', function(){
+ self.currentRunnable = self.test;
+ self.runTest(function(err){
+ test = self.test;
+
+ if (err) {
+ self.fail(test, err);
+ self.emit('test end', test);
+ return self.hookUp('afterEach', next);
+ }
+
+ test.state = 'passed';
+ self.emit('pass', test);
+ self.emit('test end', test);
+ self.hookUp('afterEach', next);
+ });
+ });
+ }
+
+ this.next = next;
+ next();
+};
+
+/**
+ * Run the given `suite` and invoke the
+ * callback `fn()` when complete.
+ *
+ * @param {Suite} suite
+ * @param {Function} fn
+ * @api private
+ */
+
+Runner.prototype.runSuite = function(suite, fn){
+ var total = this.grepTotal(suite)
+ , self = this
+ , i = 0;
+
+ debug('run suite %s', suite.fullTitle());
+
+ if (!total) return fn();
+
+ this.emit('suite', this.suite = suite);
+
+ function next() {
+ var curr = suite.suites[i++];
+ if (!curr) return done();
+ self.runSuite(curr, next);
+ }
+
+ function done() {
+ self.suite = suite;
+ self.hook('afterAll', function(){
+ self.emit('suite end', suite);
+ fn();
+ });
+ }
+
+ this.hook('beforeAll', function(){
+ self.runTests(suite, next);
+ });
+};
+
+/**
+ * Handle uncaught exceptions.
+ *
+ * @param {Error} err
+ * @api private
+ */
+
+Runner.prototype.uncaught = function(err){
+ debug('uncaught exception %s', err.message);
+ var runnable = this.currentRunnable;
+ if (!runnable || 'failed' == runnable.state) return;
+ runnable.clearTimeout();
+ err.uncaught = true;
+ this.fail(runnable, err);
+
+ // recover from test
+ if ('test' == runnable.type) {
+ this.emit('test end', runnable);
+ this.hookUp('afterEach', this.next);
+ return;
+ }
+
+ // bail on hooks
+ this.emit('end');
+};
+
+/**
+ * Run the root suite and invoke `fn(failures)`
+ * on completion.
+ *
+ * @param {Function} fn
+ * @return {Runner} for chaining
+ * @api public
+ */
+
+Runner.prototype.run = function(fn){
+ var self = this
+ , fn = fn || function(){};
+
+ function uncaught(err){
+ self.uncaught(err);
+ }
+
+ debug('start');
+
+ // callback
+ this.on('end', function(){
+ debug('end');
+ process.removeListener('uncaughtException', uncaught);
+ fn(self.failures);
+ });
+
+ // run suites
+ this.emit('start');
+ this.runSuite(this.suite, function(){
+ debug('finished running');
+ self.emit('end');
+ });
+
+ // uncaught exception
+ process.on('uncaughtException', uncaught);
+
+ return this;
+};
+
+/**
+ * Filter leaks with the given globals flagged as `ok`.
+ *
+ * @param {Array} ok
+ * @param {Array} globals
+ * @return {Array}
+ * @api private
+ */
+
+function filterLeaks(ok, globals) {
+ return filter(globals, function(key){
+ var matched = filter(ok, function(ok){
+ if (~ok.indexOf('*')) return 0 == key.indexOf(ok.split('*')[0]);
+ // Opera and IE expose global variables for HTML element IDs (issue #243)
+ if (/^mocha-/.test(key)) return true;
+ return key == ok;
+ });
+ return matched.length == 0 && (!global.navigator || 'onerror' !== key);
+ });
+}
+
+}); // module: runner.js
+
+require.register("suite.js", function(module, exports, require){
+
+/**
+ * Module dependencies.
+ */
+
+var EventEmitter = require('browser/events').EventEmitter
+ , debug = require('browser/debug')('mocha:suite')
+ , milliseconds = require('./ms')
+ , utils = require('./utils')
+ , Hook = require('./hook');
+
+/**
+ * Expose `Suite`.
+ */
+
+exports = module.exports = Suite;
+
+/**
+ * Create a new `Suite` with the given `title`
+ * and parent `Suite`. When a suite with the
+ * same title is already present, that suite
+ * is returned to provide nicer reporter
+ * and more flexible meta-testing.
+ *
+ * @param {Suite} parent
+ * @param {String} title
+ * @return {Suite}
+ * @api public
+ */
+
+exports.create = function(parent, title){
+ var suite = new Suite(title, parent.ctx);
+ suite.parent = parent;
+ if (parent.pending) suite.pending = true;
+ title = suite.fullTitle();
+ parent.addSuite(suite);
+ return suite;
+};
+
+/**
+ * Initialize a new `Suite` with the given
+ * `title` and `ctx`.
+ *
+ * @param {String} title
+ * @param {Context} ctx
+ * @api private
+ */
+
+function Suite(title, ctx) {
+ this.title = title;
+ this.ctx = ctx;
+ this.suites = [];
+ this.tests = [];
+ this.pending = false;
+ this._beforeEach = [];
+ this._beforeAll = [];
+ this._afterEach = [];
+ this._afterAll = [];
+ this.root = !title;
+ this._timeout = 2000;
+ this._slow = 75;
+ this._bail = false;
+}
+
+/**
+ * Inherit from `EventEmitter.prototype`.
+ */
+
+function F(){};
+F.prototype = EventEmitter.prototype;
+Suite.prototype = new F;
+Suite.prototype.constructor = Suite;
+
+
+/**
+ * Return a clone of this `Suite`.
+ *
+ * @return {Suite}
+ * @api private
+ */
+
+Suite.prototype.clone = function(){
+ var suite = new Suite(this.title);
+ debug('clone');
+ suite.ctx = this.ctx;
+ suite.timeout(this.timeout());
+ suite.slow(this.slow());
+ suite.bail(this.bail());
+ return suite;
+};
+
+/**
+ * Set timeout `ms` or short-hand such as "2s".
+ *
+ * @param {Number|String} ms
+ * @return {Suite|Number} for chaining
+ * @api private
+ */
+
+Suite.prototype.timeout = function(ms){
+ if (0 == arguments.length) return this._timeout;
+ if ('string' == typeof ms) ms = milliseconds(ms);
+ debug('timeout %d', ms);
+ this._timeout = parseInt(ms, 10);
+ return this;
+};
+
+/**
+ * Set slow `ms` or short-hand such as "2s".
+ *
+ * @param {Number|String} ms
+ * @return {Suite|Number} for chaining
+ * @api private
+ */
+
+Suite.prototype.slow = function(ms){
+ if (0 === arguments.length) return this._slow;
+ if ('string' == typeof ms) ms = milliseconds(ms);
+ debug('slow %d', ms);
+ this._slow = ms;
+ return this;
+};
+
+/**
+ * Sets whether to bail after first error.
+ *
+ * @parma {Boolean} bail
+ * @return {Suite|Number} for chaining
+ * @api private
+ */
+
+Suite.prototype.bail = function(bail){
+ if (0 == arguments.length) return this._bail;
+ debug('bail %s', bail);
+ this._bail = bail;
+ return this;
+};
+
+/**
+ * Run `fn(test[, done])` before running tests.
+ *
+ * @param {Function} fn
+ * @return {Suite} for chaining
+ * @api private
+ */
+
+Suite.prototype.beforeAll = function(fn){
+ if (this.pending) return this;
+ var hook = new Hook('"before all" hook', fn);
+ hook.parent = this;
+ hook.timeout(this.timeout());
+ hook.slow(this.slow());
+ hook.ctx = this.ctx;
+ this._beforeAll.push(hook);
+ this.emit('beforeAll', hook);
+ return this;
+};
+
+/**
+ * Run `fn(test[, done])` after running tests.
+ *
+ * @param {Function} fn
+ * @return {Suite} for chaining
+ * @api private
+ */
+
+Suite.prototype.afterAll = function(fn){
+ if (this.pending) return this;
+ var hook = new Hook('"after all" hook', fn);
+ hook.parent = this;
+ hook.timeout(this.timeout());
+ hook.slow(this.slow());
+ hook.ctx = this.ctx;
+ this._afterAll.push(hook);
+ this.emit('afterAll', hook);
+ return this;
+};
+
+/**
+ * Run `fn(test[, done])` before each test case.
+ *
+ * @param {Function} fn
+ * @return {Suite} for chaining
+ * @api private
+ */
+
+Suite.prototype.beforeEach = function(fn){
+ if (this.pending) return this;
+ var hook = new Hook('"before each" hook', fn);
+ hook.parent = this;
+ hook.timeout(this.timeout());
+ hook.slow(this.slow());
+ hook.ctx = this.ctx;
+ this._beforeEach.push(hook);
+ this.emit('beforeEach', hook);
+ return this;
+};
+
+/**
+ * Run `fn(test[, done])` after each test case.
+ *
+ * @param {Function} fn
+ * @return {Suite} for chaining
+ * @api private
+ */
+
+Suite.prototype.afterEach = function(fn){
+ if (this.pending) return this;
+ var hook = new Hook('"after each" hook', fn);
+ hook.parent = this;
+ hook.timeout(this.timeout());
+ hook.slow(this.slow());
+ hook.ctx = this.ctx;
+ this._afterEach.push(hook);
+ this.emit('afterEach', hook);
+ return this;
+};
+
+/**
+ * Add a test `suite`.
+ *
+ * @param {Suite} suite
+ * @return {Suite} for chaining
+ * @api private
+ */
+
+Suite.prototype.addSuite = function(suite){
+ suite.parent = this;
+ suite.timeout(this.timeout());
+ suite.slow(this.slow());
+ suite.bail(this.bail());
+ this.suites.push(suite);
+ this.emit('suite', suite);
+ return this;
+};
+
+/**
+ * Add a `test` to this suite.
+ *
+ * @param {Test} test
+ * @return {Suite} for chaining
+ * @api private
+ */
+
+Suite.prototype.addTest = function(test){
+ test.parent = this;
+ test.timeout(this.timeout());
+ test.slow(this.slow());
+ test.ctx = this.ctx;
+ this.tests.push(test);
+ this.emit('test', test);
+ return this;
+};
+
+/**
+ * Return the full title generated by recursively
+ * concatenating the parent's full title.
+ *
+ * @return {String}
+ * @api public
+ */
+
+Suite.prototype.fullTitle = function(){
+ if (this.parent) {
+ var full = this.parent.fullTitle();
+ if (full) return full + ' ' + this.title;
+ }
+ return this.title;
+};
+
+/**
+ * Return the total number of tests.
+ *
+ * @return {Number}
+ * @api public
+ */
+
+Suite.prototype.total = function(){
+ return utils.reduce(this.suites, function(sum, suite){
+ return sum + suite.total();
+ }, 0) + this.tests.length;
+};
+
+/**
+ * Iterates through each suite recursively to find
+ * all tests. Applies a function in the format
+ * `fn(test)`.
+ *
+ * @param {Function} fn
+ * @return {Suite}
+ * @api private
+ */
+
+Suite.prototype.eachTest = function(fn){
+ utils.forEach(this.tests, fn);
+ utils.forEach(this.suites, function(suite){
+ suite.eachTest(fn);
+ });
+ return this;
+};
+
+}); // module: suite.js
+
+require.register("test.js", function(module, exports, require){
+
+/**
+ * Module dependencies.
+ */
+
+var Runnable = require('./runnable');
+
+/**
+ * Expose `Test`.
+ */
+
+module.exports = Test;
+
+/**
+ * Initialize a new `Test` with the given `title` and callback `fn`.
+ *
+ * @param {String} title
+ * @param {Function} fn
+ * @api private
+ */
+
+function Test(title, fn) {
+ Runnable.call(this, title, fn);
+ this.pending = !fn;
+ this.type = 'test';
+}
+
+/**
+ * Inherit from `Runnable.prototype`.
+ */
+
+function F(){};
+F.prototype = Runnable.prototype;
+Test.prototype = new F;
+Test.prototype.constructor = Test;
+
+
+}); // module: test.js
+
+require.register("utils.js", function(module, exports, require){
+
+/**
+ * Module dependencies.
+ */
+
+var fs = require('browser/fs')
+ , path = require('browser/path')
+ , join = path.join
+ , debug = require('browser/debug')('mocha:watch');
+
+/**
+ * Ignored directories.
+ */
+
+var ignore = ['node_modules', '.git'];
+
+/**
+ * Escape special characters in the given string of html.
+ *
+ * @param {String} html
+ * @return {String}
+ * @api private
+ */
+
+exports.escape = function(html){
+ return String(html)
+ .replace(/&/g, '&')
+ .replace(/"/g, '"')
+ .replace(/</g, '<')
+ .replace(/>/g, '>');
+};
+
+/**
+ * Array#forEach (<=IE8)
+ *
+ * @param {Array} array
+ * @param {Function} fn
+ * @param {Object} scope
+ * @api private
+ */
+
+exports.forEach = function(arr, fn, scope){
+ for (var i = 0, l = arr.length; i < l; i++)
+ fn.call(scope, arr[i], i);
+};
+
+/**
+ * Array#indexOf (<=IE8)
+ *
+ * @parma {Array} arr
+ * @param {Object} obj to find index of
+ * @param {Number} start
+ * @api private
+ */
+
+exports.indexOf = function(arr, obj, start){
+ for (var i = start || 0, l = arr.length; i < l; i++) {
+ if (arr[i] === obj)
+ return i;
+ }
+ return -1;
+};
+
+/**
+ * Array#reduce (<=IE8)
+ *
+ * @param {Array} array
+ * @param {Function} fn
+ * @param {Object} initial value
+ * @api private
+ */
+
+exports.reduce = function(arr, fn, val){
+ var rval = val;
+
+ for (var i = 0, l = arr.length; i < l; i++) {
+ rval = fn(rval, arr[i], i, arr);
+ }
+
+ return rval;
+};
+
+/**
+ * Array#filter (<=IE8)
+ *
+ * @param {Array} array
+ * @param {Function} fn
+ * @api private
+ */
+
+exports.filter = function(arr, fn){
+ var ret = [];
+
+ for (var i = 0, l = arr.length; i < l; i++) {
+ var val = arr[i];
+ if (fn(val, i, arr)) ret.push(val);
+ }
+
+ return ret;
+};
+
+/**
+ * Object.keys (<=IE8)
+ *
+ * @param {Object} obj
+ * @return {Array} keys
+ * @api private
+ */
+
+exports.keys = Object.keys || function(obj) {
+ var keys = []
+ , has = Object.prototype.hasOwnProperty // for `window` on <=IE8
+
+ for (var key in obj) {
+ if (has.call(obj, key)) {
+ keys.push(key);
+ }
+ }
+
+ return keys;
+};
+
+/**
+ * Watch the given `files` for changes
+ * and invoke `fn(file)` on modification.
+ *
+ * @param {Array} files
+ * @param {Function} fn
+ * @api private
+ */
+
+exports.watch = function(files, fn){
+ var options = { interval: 100 };
+ files.forEach(function(file){
+ debug('file %s', file);
+ fs.watchFile(file, options, function(curr, prev){
+ if (prev.mtime < curr.mtime) fn(file);
+ });
+ });
+};
+
+/**
+ * Ignored files.
+ */
+
+function ignored(path){
+ return !~ignore.indexOf(path);
+}
+
+/**
+ * Lookup files in the given `dir`.
+ *
+ * @return {Array}
+ * @api private
+ */
+
+exports.files = function(dir, ret){
+ ret = ret || [];
+
+ fs.readdirSync(dir)
+ .filter(ignored)
+ .forEach(function(path){
+ path = join(dir, path);
+ if (fs.statSync(path).isDirectory()) {
+ exports.files(path, ret);
+ } else if (path.match(/\.(js|coffee)$/)) {
+ ret.push(path);
+ }
+ });
+
+ return ret;
+};
+
+/**
+ * Compute a slug from the given `str`.
+ *
+ * @param {String} str
+ * @return {String}
+ * @api private
+ */
+
+exports.slug = function(str){
+ return str
+ .toLowerCase()
+ .replace(/ +/g, '-')
+ .replace(/[^-\w]/g, '');
+};
+
+/**
+ * Strip the function definition from `str`,
+ * and re-indent for pre whitespace.
+ */
+
+exports.clean = function(str) {
+ str = str
+ .replace(/^function *\(.*\) *{/, '')
+ .replace(/\s+\}$/, '');
+
+ var spaces = str.match(/^\n?( *)/)[1].length
+ , re = new RegExp('^ {' + spaces + '}', 'gm');
+
+ str = str.replace(re, '');
+
+ return exports.trim(str);
+};
+
+/**
+ * Escape regular expression characters in `str`.
+ *
+ * @param {String} str
+ * @return {String}
+ * @api private
+ */
+
+exports.escapeRegexp = function(str){
+ return str.replace(/[-\\^$*+?.()|[\]{}]/g, "\\$&");
+};
+
+/**
+ * Trim the given `str`.
+ *
+ * @param {String} str
+ * @return {String}
+ * @api private
+ */
+
+exports.trim = function(str){
+ return str.replace(/^\s+|\s+$/g, '');
+};
+
+/**
+ * Parse the given `qs`.
+ *
+ * @param {String} qs
+ * @return {Object}
+ * @api private
+ */
+
+exports.parseQuery = function(qs){
+ return exports.reduce(qs.replace('?', '').split('&'), function(obj, pair){
+ var i = pair.indexOf('=')
+ , key = pair.slice(0, i)
+ , val = pair.slice(++i);
+
+ obj[key] = decodeURIComponent(val);
+ return obj;
+ }, {});
+};
+
+/**
+ * Highlight the given string of `js`.
+ *
+ * @param {String} js
+ * @return {String}
+ * @api private
+ */
+
+function highlight(js) {
+ return js
+ .replace(/</g, '<')
+ .replace(/>/g, '>')
+ .replace(/\/\/(.*)/gm, '<span class="comment">//$1</span>')
+ .replace(/('.*?')/gm, '<span class="string">$1</span>')
+ .replace(/(\d+\.\d+)/gm, '<span class="number">$1</span>')
+ .replace(/(\d+)/gm, '<span class="number">$1</span>')
+ .replace(/\bnew *(\w+)/gm, '<span class="keyword">new</span> <span class="init">$1</span>')
+ .replace(/\b(function|new|throw|return|var|if|else)\b/gm, '<span class="keyword">$1</span>')
+}
+
+/**
+ * Highlight the contents of tag `name`.
+ *
+ * @param {String} name
+ * @api private
+ */
+
+exports.highlightTags = function(name) {
+ var code = document.getElementsByTagName(name);
+ for (var i = 0, len = code.length; i < len; ++i) {
+ code[i].innerHTML = highlight(code[i].innerHTML);
+ }
+};
+
+}); // module: utils.js
+/**
+ * Node shims.
+ *
+ * These are meant only to allow
+ * mocha.js to run untouched, not
+ * to allow running node code in
+ * the browser.
+ */
+
+process = {};
+process.exit = function(status){};
+process.stdout = {};
+global = window;
+
+/**
+ * next tick implementation.
+ */
+
+process.nextTick = (function(){
+ // postMessage behaves badly on IE8
+ if (window.ActiveXObject || !window.postMessage) {
+ return function(fn){ fn() };
+ }
+
+ // based on setZeroTimeout by David Baron
+ // - http://dbaron.org/log/20100309-faster-timeouts
+ var timeouts = []
+ , name = 'mocha-zero-timeout'
+
+ window.addEventListener('message', function(e){
+ if (e.source == window && e.data == name) {
+ if (e.stopPropagation) e.stopPropagation();
+ if (timeouts.length) timeouts.shift()();
+ }
+ }, true);
+
+ return function(fn){
+ timeouts.push(fn);
+ window.postMessage(name, '*');
+ }
+})();
+
+/**
+ * Remove uncaughtException listener.
+ */
+
+process.removeListener = function(e){
+ if ('uncaughtException' == e) {
+ window.onerror = null;
+ }
+};
+
+/**
+ * Implements uncaughtException listener.
+ */
+
+process.on = function(e, fn){
+ if ('uncaughtException' == e) {
+ window.onerror = function(err, url, line){
+ fn(new Error(err + ' (' + url + ':' + line + ')'));
+ };
+ }
+};
+
+// boot
+;(function(){
+
+ /**
+ * Expose mocha.
+ */
+
+ var Mocha = window.Mocha = require('mocha'),
+ mocha = window.mocha = new Mocha({ reporter: 'html' });
+
+ /**
+ * Override ui to ensure that the ui functions are initialized.
+ * Normally this would happen in Mocha.prototype.loadFiles.
+ */
+
+ mocha.ui = function(ui){
+ Mocha.prototype.ui.call(this, ui);
+ this.suite.emit('pre-require', window, null, this);
+ return this;
+ };
+
+ /**
+ * Setup mocha with the given setting options.
+ */
+
+ mocha.setup = function(opts){
+ if ('string' == typeof opts) opts = { ui: opts };
+ for (var opt in opts) this[opt](opts[opt]);
+ return this;
+ };
+
+ /**
+ * Run mocha, returning the Runner.
+ */
+
+ mocha.run = function(fn){
+ var options = mocha.options;
+ mocha.globals('location');
+
+ var query = Mocha.utils.parseQuery(window.location.search || '');
+ if (query.grep) mocha.grep(query.grep);
+ if (query.invert) mocha.invert();
+
+ return Mocha.prototype.run.call(mocha, function(){
+ Mocha.utils.highlightTags('code');
+ if (fn) fn();
+ });
+ };
+})();
+})();
diff --git a/test/test.add-get-remove.js b/test/test.add-get-remove.js
new file mode 100644
index 0000000..4840298
--- /dev/null
+++ b/test/test.add-get-remove.js
@@ -0,0 +1,97 @@
+describe('Add, get, remove', function() {
+
+ var list;
+
+ before(function() {
+ list = fixture.list(['name'], [ { name: "Jonny" } ]);
+ });
+
+ after(function() {
+ fixture.removeList();
+ });
+
+ afterEach(function() {
+ list.clear();
+ list.add({ name: "Jonny" });
+ });
+
+ describe('Add', function() {
+ it('should add one item', function() {
+ list.add({ name: 'Jonas' });
+ expect(list.items.length).to.equal(2);
+ });
+ it('should add two items', function() {
+ list.add([
+ { name: 'Martina' },
+ { name: 'Angelica' }
+ ]);
+ expect(list.items.length).to.equal(3);
+ });
+ it('should add async items', function(done) {
+ list.add([
+ { name: 'Sven' }
+ ], function() {
+ expect(list.items.length).to.equal(2);
+ done();
+ });
+ });
+ it('should add async items to empty list', function(done) {
+ list.clear();
+ list.add([
+ { name: 'Sven' }
+ ], function() {
+ expect(list.items.length).to.equal(1);
+ done();
+ });
+ });
+ });
+
+ describe('Get', function() {
+ it('should return array with one item', function() {
+ var items = list.get('name', 'Jonny');
+ expect(items[0].values().name).to.equal('Jonny');
+ });
+ it('should return empty array', function() {
+ var items = list.get('name', 'jonny');
+ expect(items.length).to.be.zero;
+ });
+ it('should return two items', function() {
+ list.add({ name: 'Jonny' });
+ var items = list.get('name', 'Jonny');
+ expect(items.length).to.equal(2);
+ expect(items[0].values().name).to.equal('Jonny');
+ expect(items[1].values().name).to.equal('Jonny');
+ });
+ });
+
+ describe('Remove', function() {
+ it('should remove one item', function() {
+ list.add({ name: "Jonas" });
+ expect(list.items.length).to.equal(2);
+ var count = list.remove('name', 'Jonas');
+ expect(count).to.equal(1);
+ expect(list.items.length).to.equal(1);
+ });
+ it('should not remove anything due to case sensitivity', function() {
+ var count = list.remove('name', 'jonny');
+ expect(count).to.be.equal(0);
+ expect(list.items.length).to.equal(1);
+ });
+
+ it('should remove eight items', function() {
+ list.add({ name: 'Jonny' });
+ list.add({ name: 'Jonny' });
+ list.add({ name: 'Sven' });
+ list.add({ name: 'Jonny' });
+ list.add({ name: 'Jonny' });
+ list.add({ name: 'Jonny' });
+ list.add({ name: 'Jonas' });
+ list.add({ name: 'Jonny' });
+ list.add({ name: 'Jonny' });
+ expect(list.items.length).to.equal(10);
+ var count = list.remove('name', 'Jonny');
+ expect(count).to.equal(8);
+ expect(list.items.length).to.equal(2);
+ });
+ });
+});
diff --git a/test/test.buttons.js b/test/test.buttons.js
new file mode 100644
index 0000000..012167e
--- /dev/null
+++ b/test/test.buttons.js
@@ -0,0 +1,191 @@
+function fireKeyup(el) {
+ if (document.createEvent) {
+ var evObj;
+ if (window.KeyEvent) {
+ evObj = document.createEvent('KeyEvents');
+ evObj.initKeyEvent('keyup', true, true, window, false, false, false, false, 13, 0);
+ } else {
+ evObj = document.createEvent('UIEvents');
+ evObj.initUIEvent('keyup', true, true, window, 1);
+ }
+ el.dispatchEvent(evObj);
+ } else if( document.createEventObject ) {
+ el.fireEvent('onkeyup');
+ } else {
+ // IE 5.0, seriously? :)
+ }
+}
+
+// http://stackoverflow.com/questions/5658849/whats-the-equivalent-of-jquerys-trigger-method-without-jquery
+function fireClick(el) {
+ var evt;
+ if (document.createEvent) {
+ evt = document.createEvent("MouseEvents");
+ evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
+ }
+ (evt) ? el.dispatchEvent(evt) : (el.click && el.click());
+}
+
+describe('Button', function() {
+
+ var list;
+
+ beforeEach(function() {
+ $('body').append($('<div id="parse-list">\
+ <input class="search" />\
+ <span class="sort" id="sort-name" data-sort="name">Sort name</span>\
+ <span class="sort" id="sort-name-asc" data-sort="name" data-order="asc">Sort name asc</span>\
+ <span class="sort" id="sort-name-desc" data-sort="name" data-order="desc">Sort name desc</span>\
+ <div class="list">\
+ <div><span class="name">Jonny</span><span class="born">1986</span></div>\
+ <div><span class="name">Jocke</span><span class="born">1985</span></div>\
+ </div>\
+ </div>'));
+
+ list = new List('parse-list', {
+ valueNames: ['name', 'born']
+ });
+ });
+
+ afterEach(function() {
+ $('#parse-list').remove();
+ });
+
+ describe('Sort', function() {
+ it('should trigger sortStart', function(done) {
+ list.on('sortComplete', function() {
+ done();
+ });
+ fireClick($('#sort-name')[0]);
+ });
+ it('should trigger sortComplete', function(done) {
+ list.on('sortComplete', function() {
+ done();
+ });
+ fireClick($('#sort-name')[0]);
+ });
+
+ it('should switch sorting order when clicking multiple times', function(done) {
+ this.timeout(5000);
+ var sortRun = 0;
+ list.on('sortComplete', function() {
+ sortRun++;
+ if (sortRun == 1) {
+ expect($('#sort-name').hasClass('asc')).to.be(true);
+ expect($('#sort-name').hasClass('desc')).to.be(false);
+ setTimeout(function() {
+ fireClick($('#sort-name')[0]);
+ }, 50);
+ } else if (sortRun == 2) {
+ expect($('#sort-name').hasClass('asc')).to.be(false);
+ expect($('#sort-name').hasClass('desc')).to.be(true);
+ setTimeout(function() {
+ fireClick($('#sort-name')[0]);
+ }, 50);
+ } else if (sortRun == 3) {
+ expect($('#sort-name').hasClass('asc')).to.be(true);
+ expect($('#sort-name').hasClass('desc')).to.be(false);
+ done();
+ }
+ });
+ expect($('#sort-name').hasClass('asc')).to.be(false);
+ expect($('#sort-name').hasClass('desc')).to.be(false);
+ fireClick($('#sort-name')[0]);
+ });
+
+ it('should sort with predefined order', function(done) {
+ this.timeout(10000);
+ var sortRun = 0;
+ list.on('sortComplete', function() {
+ sortRun++;
+ if (sortRun == 1) {
+ expect($('#sort-name').hasClass('asc')).to.be(true);
+ expect($('#sort-name').hasClass('desc')).to.be(false);
+ expect($('#sort-name-asc').hasClass('asc')).to.be(true);
+ expect($('#sort-name-asc').hasClass('desc')).to.be(false);
+ expect($('#sort-name-desc').hasClass('asc')).to.be(false);
+ expect($('#sort-name-desc').hasClass('desc')).to.be(false);
+ setTimeout(function() {
+ fireClick($('#sort-name-asc')[0]);
+ }, 50);
+ } else if (sortRun == 2) {
+ expect($('#sort-name').hasClass('asc')).to.be(true);
+ expect($('#sort-name').hasClass('desc')).to.be(false);
+ expect($('#sort-name-asc').hasClass('asc')).to.be(true);
+ expect($('#sort-name-asc').hasClass('desc')).to.be(false);
+ expect($('#sort-name-desc').hasClass('asc')).to.be(false);
+ expect($('#sort-name-desc').hasClass('desc')).to.be(false);
+ setTimeout(function() {
+ fireClick($('#sort-name-asc')[0]);
+ }, 50);
+ } else if (sortRun == 3) {
+ expect($('#sort-name').hasClass('asc')).to.be(true);
+ expect($('#sort-name').hasClass('desc')).to.be(false);
+ expect($('#sort-name-asc').hasClass('asc')).to.be(true);
+ expect($('#sort-name-asc').hasClass('desc')).to.be(false);
+ expect($('#sort-name-desc').hasClass('asc')).to.be(false);
+ expect($('#sort-name-desc').hasClass('desc')).to.be(false);
+ setTimeout(function() {
+ fireClick($('#sort-name-desc')[0]);
+ }, 50);
+ } else if (sortRun == 4) {
+ expect($('#sort-name').hasClass('asc')).to.be(false);
+ expect($('#sort-name').hasClass('desc')).to.be(true);
+ expect($('#sort-name-asc').hasClass('asc')).to.be(false);
+ expect($('#sort-name-asc').hasClass('desc')).to.be(false);
+ expect($('#sort-name-desc').hasClass('asc')).to.be(false);
+ expect($('#sort-name-desc').hasClass('desc')).to.be(true);
+ setTimeout(function() {
+ fireClick($('#sort-name-desc')[0]);
+ }, 50);
+ } else if (sortRun == 5) {
+ expect($('#sort-name').hasClass('asc')).to.be(false);
+ expect($('#sort-name').hasClass('desc')).to.be(true);
+ expect($('#sort-name-asc').hasClass('asc')).to.be(false);
+ expect($('#sort-name-asc').hasClass('desc')).to.be(false);
+ expect($('#sort-name-desc').hasClass('asc')).to.be(false);
+ expect($('#sort-name-desc').hasClass('desc')).to.be(true);
+ done();
+ }
+ });
+ expect($('#sort-name').hasClass('asc')).to.be(false);
+ expect($('#sort-name').hasClass('desc')).to.be(false);
+ expect($('#sort-name-asc').hasClass('asc')).to.be(false);
+ expect($('#sort-name-asc').hasClass('desc')).to.be(false);
+ expect($('#sort-name-desc').hasClass('asc')).to.be(false);
+ expect($('#sort-name-desc').hasClass('desc')).to.be(false);
+ fireClick($('#sort-name-asc')[0]);
+ });
+
+ it('buttons should change class when sorting programmatically', function(done) {
+ list.on('sortComplete', function() {
+ expect($('#sort-name').hasClass('asc')).to.be(true);
+ expect($('#sort-name').hasClass('desc')).to.be(false);
+ expect($('#sort-name-asc').hasClass('asc')).to.be(true);
+ expect($('#sort-name-asc').hasClass('desc')).to.be(false);
+ expect($('#sort-name-desc').hasClass('asc')).to.be(false);
+ expect($('#sort-name-desc').hasClass('desc')).to.be(false);
+ done();
+ });
+ list.sort('name', { order: "asc" });
+ })
+ });
+
+
+ describe('Search', function() {
+ it('should trigger searchStart', function(done) {
+ list.on('searchStart', function() {
+ done();
+ });
+ $('#parse-list .search').val('jon');
+ fireKeyup($('#parse-list .search')[0]);
+ });
+ it('should trigger searchComplete', function(done) {
+ list.on('searchComplete', function() {
+ done();
+ });
+ $('#parse-list .search').val('jon');
+ fireKeyup($('#parse-list .search')[0]);
+ });
+ });
+});
diff --git a/test/test.create.js b/test/test.create.js
new file mode 100644
index 0000000..3d3cf37
--- /dev/null
+++ b/test/test.create.js
@@ -0,0 +1,89 @@
+describe('Create', function() {
+
+ describe('With HTML items', function() {
+ var listEl = $('<div id="list">\
+ <ul class="list">\
+ <li><span class="name">Jonny</span></li>\
+ </ul>\
+ </div>');
+
+ $(document.body).append(listEl);
+
+ var list = new List('list', { valueNames: ['name'] });
+
+ it('should contain one item', function() {
+ expect(list.items.length).to.equal(1);
+ expect(listEl.find('li').size()).to.equal(1);
+ });
+
+ it('should contain two items', function() {
+ list.add({ name: 'Jonas' });
+ expect(list.items.length).to.equal(2);
+ expect(listEl.find('li').size()).to.equal(2);
+ });
+
+ listEl.remove();
+ });
+
+ describe('Without items and with string template', function() {
+ var listEl = $('<div id="list">\
+ <ul class="list"></ul>\
+ </div>');
+
+ $(document.body).append(listEl);
+
+ var list = new List('list', {
+ valueNames: ['name'],
+ item: '<li><span class="name"></span></li>'
+ }, [
+ { name: 'Jonny' }
+ ]);
+
+ it('should contain one item', function() {
+ expect(list.items.length).to.equal(1);
+ expect(listEl.find('li').size()).to.equal(1);
+ });
+
+ it('should contain two items', function() {
+ list.add({ name: 'Jonas' });
+ expect(list.items.length).to.equal(2);
+ expect(listEl.find('li').size()).to.equal(2);
+ });
+
+ listEl.remove();
+ });
+
+ describe('Without items and with HTML template', function() {
+ var listEl = $('<div id="list">\
+ <ul class="list"></ul>\
+ </div>');
+
+ var templateEl = $('<li id="template-item"><span class="name"></span></li>');
+
+ $(document.body).append(listEl);
+ $(document.body).append(templateEl);
+
+ var list = new List('list', {
+ valueNames: ['name'],
+ item: 'template-item'
+ }, [
+ { name: 'Jonny' }
+ ]);
+
+ it('should contain one item', function() {
+ expect(list.items.length).to.equal(1);
+ expect(listEl.find('li').size()).to.equal(1);
+ });
+
+ it('should contain two items', function() {
+ list.add({ name: 'Jonas' });
+ expect(list.items.length).to.equal(2);
+ expect(listEl.find('li').size()).to.equal(2);
+ });
+
+ listEl.remove();
+ templateEl.remove();
+ });
+
+
+});
\ No newline at end of file
diff --git a/test/test.defaults.js b/test/test.defaults.js
new file mode 100644
index 0000000..7908551
--- /dev/null
+++ b/test/test.defaults.js
@@ -0,0 +1,65 @@
+describe('Defaults', function() {
+ var list;
+
+ before(function() {
+ list = fixture.list(['name'], [ { name: 'Jonny' }]);
+ });
+
+ after(function() {
+ fixture.removeList();
+ });
+
+ it('should have all default attributes', function() {
+ expect(list.items).to.be.an('array');
+ expect(list.visibleItems).to.be.an('array');
+ expect(list.matchingItems).to.be.an('array');
+
+ expect(list.handlers.updated).to.be.an('array');
+ expect(list.handlers.searchStart).to.be.an('array');
+ expect(list.handlers.searchComplete).to.be.an('array');
+ expect(list.handlers.sortStart).to.be.an('array');
+ expect(list.handlers.sortComplete).to.be.an('array');
+ expect(list.handlers.filterStart).to.be.an('array');
+ expect(list.handlers.filterComplete).to.be.an('array');
+
+ expect(list.searched).to.be(false);
+ expect(list.filtered).to.be(false);
+ expect(list.i).to.equal(1);
+ expect(list.page).to.equal(200);
+ expect(list.listClass).to.equal('list');
+ expect(list.sortClass).to.equal('sort');
+ expect(list.searchClass).to.equal('search');
+ expect(list.page).to.equal(200);
+ });
+
+ it('should have the right elements', function() {
+ expect(list.list).to.equal($('.list')[0]);
+ expect(list.listContainer).to.equal($('#list')[0]);
+ });
+
+ it('should have all default methods', function() {
+ expect(list.add).to.be.a('function');
+ expect(list.remove).to.be.a('function');
+ expect(list.get).to.be.a('function');
+ expect(list.sort).to.be.a('function');
+ expect(list.search).to.be.a('function');
+ expect(list.clear).to.be.a('function');
+ expect(list.filter).to.be.a('function');
+ expect(list.size).to.be.a('function');
+ expect(list.show).to.be.a('function');
+ expect(list.update).to.be.a('function');
+ expect(list.on).to.be.a('function');
+ });
+
+ it('should have all helper methods', function() {
+ expect(list.helpers.classes).to.be.a('function');
+ expect(list.helpers.getAttribute).to.be.a('function');
+ expect(list.helpers.getByClass).to.be.a('function');
+ expect(list.helpers.naturalSort).to.be.a('function');
+ expect(list.helpers.events.bind).to.be.a('function');
+ expect(list.helpers.events.unbind).to.be.a('function');
+ expect(list.helpers.extend).to.be.a('function');
+ expect(list.helpers.indexOf).to.be.a('function');
+ expect(list.helpers.toString).to.be.a('function');
+ });
+});
diff --git a/test/test.filter.js b/test/test.filter.js
new file mode 100644
index 0000000..21e693d
--- /dev/null
+++ b/test/test.filter.js
@@ -0,0 +1,101 @@
+describe('Filter', function() {
+
+ var list, jonny, martina, angelica, sebastian, imma, hasse;
+
+ before(function() {
+ list = fixture.list(['name', 'born'], fixture.all);
+ jonny = list.get('name', 'Jonny Strömberg')[0];
+ martina = list.get('name', 'Martina Elm')[0];
+ angelica = list.get('name', 'Angelica Abraham')[0];
+ sebastian = list.get('name', 'Sebastian Höglund')[0];
+ imma = list.get('name', 'Imma Grafström')[0];
+ hasse = list.get('name', 'Hasse Strömberg')[0];
+ });
+
+ after(function() {
+ fixture.removeList();
+ });
+
+ afterEach(function() {
+ list.filter();
+ list.show(1, 200);
+ });
+
+ describe('Basics', function() {
+ it('should return everyone born after 1988', function() {
+ var result = list.filter(function(item) {
+ return (item.values().born > 1988);
+ });
+ expect(result.length).to.equal(1);
+ expect(result[0]).to.eql(sebastian);
+ });
+ it('should return everyone born 1986', function() {
+ var result = list.filter(function(item) {
+ return (item.values().born == 1986);
+ });
+ expect(result.length).to.equal(3);
+ for (var i = 0; i < result.length; i++) {
+ expect(result[i].values().born).to.equal('1986');
+ }
+ });
+ });
+
+ describe('Show and pages', function() {
+ it('should return the visible items', function() {
+ list.show(1,2);
+ var result = list.filter(function(item) {
+ return (item.values().born > 1985);
+ });
+ expect(result).to.eql(list.visibleItems);
+ });
+
+ it('should return be 2 visible items and 3 matching', function() {
+ list.show(1,2);
+ var result = list.filter(function(item) {
+ return (item.values().born > 1985);
+ });
+ expect(result.length).to.equal(2);
+ expect(list.visibleItems.length).to.equal(2);
+ expect(list.matchingItems.length).to.equal(4);
+ });
+
+ describe('Specific items', function() {
+ beforeEach(function() {
+ list.show(1,2);
+ var result = list.filter(function(item) {
+ return (item.values().born > 1985);
+ });
+ });
+ it('should match jonny', function() {
+ expect(jonny.matching()).to.be(true);
+ expect(jonny.filtered).to.be(true);
+ expect(jonny.visible()).to.be(true);
+ });
+ it('should match martina', function() {
+ expect(martina.matching()).to.be(true);
+ expect(martina.filtered).to.be(true);
+ expect(martina.visible()).to.be(true);
+ });
+ it('should match but not show angelica', function() {
+ expect(angelica.matching()).to.be(true);
+ expect(angelica.filtered).to.be(true);
+ expect(angelica.visible()).to.be(false);
+ });
+ it('should match but not show sebastian', function() {
+ expect(sebastian.matching()).to.be(true);
+ expect(sebastian.filtered).to.be(true);
+ expect(sebastian.visible()).to.be(false);
+ });
+ it('should not match imma', function() {
+ expect(imma.matching()).to.be(false);
+ expect(imma.filtered).to.be(false);
+ expect(imma.visible()).to.be(false);
+ });
+ it('should not match hasse', function() {
+ expect(hasse.matching()).to.be(false);
+ expect(hasse.filtered).to.be(false);
+ expect(hasse.visible()).to.be(false);
+ });
+ });
+ });
+});
diff --git a/test/test.item.js b/test/test.item.js
new file mode 100644
index 0000000..b025ba0
--- /dev/null
+++ b/test/test.item.js
@@ -0,0 +1,146 @@
+describe('Item', function() {
+
+ var list, item;
+
+ before(function() {
+ list = fixture.list(['name', 'born', 'doin'], [{
+ name: "Jonny",
+ born: "1986",
+ doin: "Living the dream"
+ }]);
+ item = list.get('name', 'Jonny')[0];
+ });
+
+
+ beforeEach(function() {
+ list.search();
+ list.filter();
+ list.show(1,200);
+ });
+
+ after(function() {
+ fixture.removeList();
+ });
+
+ describe('Defaults', function() {
+ it('should have all default attributes', function() {
+ expect(item.found).to.be(false);
+ expect(item.filtered).to.be(false);
+ });
+
+ it('should have the right elements', function() {
+ expect(item.elm).to.equal($('#list li')[0]);
+ });
+
+ it('should have all default methods', function() {
+ expect(item.hide).to.be.a('function');
+ expect(item.show).to.be.a('function');
+ expect(item.values).to.be.a('function');
+ expect(item.matching).to.be.a('function');
+ expect(item.visible).to.be.a('function');
+ });
+ });
+
+ describe('Values()', function() {
+ it('should have the right values', function() {
+ expect(item.values()).to.eql({
+ name: 'Jonny',
+ born: '1986',
+ doin: 'Living the dream'
+ });
+ });
+ it('should be able to change one value', function() {
+ expect(item.values().name).to.be.equal('Jonny');
+ item.values({ name: 'Egon' });
+ expect(item.values().name).to.be.equal('Egon');
+ });
+ it('should be able to change many value', function() {
+ expect(item.values()).to.eql({
+ name: 'Egon',
+ born: '1986',
+ doin: 'Living the dream'
+ });
+ item.values({
+ name: 'Sven',
+ born: '1801',
+ doin: 'Is dead'
+ });
+ expect(item.values()).to.eql({
+ name: 'Sven',
+ born: '1801',
+ doin: 'Is dead'
+ });
+ });
+ });
+
+ describe('Hide, show, visible', function() {
+ it('should be hidden', function() {
+ expect($('#list li').size()).to.equal(1);
+ item.hide();
+ expect(item.visible()).to.be(false);
+ expect($('#list li').size()).to.equal(0);
+ });
+ it('should be visible', function() {
+ item.hide();
+ expect($('#list li').size()).to.equal(0);
+ item.show();
+ expect(item.visible()).to.be(true);
+ expect($('#list li').size()).to.equal(1);
+ });
+ });
+
+ describe('Matching, found, filtered', function() {
+ describe('Searching', function() {
+ it('should not be visible, match, found or filtered', function() {
+ list.search('Fredrik');
+ expect(item.matching()).to.be(false);
+ expect(item.found).to.be(false);
+ expect(item.filtered).to.be(false);
+ expect(item.visible()).to.be(false);
+ });
+ it('should be visble, match and found but not filterd', function() {
+ var result = list.search('Sven');
+ expect(item.matching()).to.be(true);
+ expect(item.found).to.be(true);
+ expect(item.filtered).to.be(false);
+ expect(item.visible()).to.be(true);
+ });
+ it('reset: should be visible and matching but not found or filtered', function() {
+ list.search();
+ expect(item.matching()).to.be(true);
+ expect(item.found).to.be(false);
+ expect(item.filtered).to.be(false);
+ expect(item.visible()).to.be(true);
+ });
+ });
+ describe('Filtering', function() {
+ it('should not be visble, match, found or filtered', function() {
+ list.filter(function(item) {
+ return (item.values().name == "Fredrik");
+ });
+ expect(item.matching()).to.be(false);
+ expect(item.found).to.be(false);
+ expect(item.filtered).to.be(false);
+ expect(item.visible()).to.be(false);
+ });
+ it('should be visble, match and filtered but not found', function() {
+ list.filter(function(item) {
+ return (item.values().name == "Sven");
+ });
+ expect(item.matching()).to.be(true);
+ expect(item.found).to.be(false);
+ expect(item.filtered).to.be(true);
+ expect(item.visible()).to.be(true);
+ });
+ it('reset: should be visble and match but not filtered or found', function() {
+ list.filter();
+ expect(item.matching()).to.be(true);
+ expect(item.found).to.be(false);
+ expect(item.filtered).to.be(false);
+ expect(item.visible()).to.be(true);
+ });
+ });
+ });
+
+ fixture.removeList();
+});
diff --git a/test/test.off.js b/test/test.off.js
new file mode 100644
index 0000000..b8bad4e
--- /dev/null
+++ b/test/test.off.js
@@ -0,0 +1,39 @@
+describe('Off', function() {
+
+ var list;
+
+ before(function() {
+ list = fixture.list(['name', 'born'], fixture.all);
+ });
+
+ after(function() {
+ fixture.removeList();
+ });
+
+ describe('General', function() {
+ it('should be remove added handler', function(done) {
+ var updated = function(list) {
+ expect(list.handlers.updated.length).to.equal(1);
+ list.off('updated', updated);
+ expect(list.handlers.updated.length).to.equal(0);
+ done();
+ };
+ list.on('updated', updated);
+ list.search('jonny');
+ });
+
+ it('should not remove unnamed handlers', function(done) {
+ var searchComplete = function(list) {
+ expect(list.handlers.searchComplete.length).to.equal(3);
+ list.off('searchComplete', function() {});
+ list.off('searchComplete', searchComplete);
+ expect(list.handlers.searchComplete.length).to.equal(2);
+ done();
+ };
+ list.on('searchComplete', function() {});
+ list.on('searchComplete', searchComplete);
+ list.on('searchComplete', function() {});
+ list.search('jonny');
+ });
+ });
+});
diff --git a/test/test.on.js b/test/test.on.js
new file mode 100644
index 0000000..b170254
--- /dev/null
+++ b/test/test.on.js
@@ -0,0 +1,123 @@
+describe('On', function() {
+
+ var list;
+
+ beforeEach(function() {
+ list = fixture.list(['name', 'born'], fixture.all);
+ });
+
+ afterEach(function() {
+ fixture.removeList();
+ });
+
+ describe('Updated', function() {
+ it('should be triggered after search', function(done) {
+ list.on('updated', function(list) {
+ done();
+ });
+ list.search('jonny');
+ });
+ it('should be triggered after sort', function(done) {
+ list.on('updated', function(list) {
+ done();
+ });
+ list.sort('name');
+ });
+ it('should be triggered after filter', function(done) {
+ list.on('updated', function(list) {
+ done();
+ });
+ list.filter(function() {
+ return true;
+ });
+ });
+ it('should be triggered after show', function(done) {
+ list.on('updated', function(list) {
+ done();
+ });
+ list.show(1,10);
+ });
+
+ it('should be triggered after add', function(done) {
+ list.on('updated', function(list) {
+ done();
+ });
+ list.add({ name: 'Hej' });
+ });
+ it('should be triggered after remove', function(done) {
+ list.on('updated', function(list) {
+ done();
+ });
+ list.remove('name', 'Jonny');
+ });
+ });
+
+ describe('Multiple handlers', function() {
+ it('should be trigger both handlers', function(done) {
+ var done1 = false,
+ done2 = false,
+ isDone = function() {
+ if (done1 && done2) {
+ done();
+ }
+ };
+
+ list.on('updated', function(list) {
+ done1 = true;
+ isDone();
+ });
+ list.on('updated', function(list) {
+ done2 = true;
+ isDone();
+ });
+ list.search('jonny');
+ });
+ });
+
+ describe('Search', function() {
+ it('should be triggered before and after search', function(done) {
+ var done1 = false;
+ list.on('searchStart', function(list) {
+ done1 = true;
+ });
+ list.on('searchComplete', function(list) {
+ if (done1) {
+ done();
+ }
+ });
+ list.search('jonny');
+ });
+ });
+
+ describe('Sort', function() {
+ it('should be triggered before and after sort', function(done) {
+ var done1 = false;
+ list.on('sortStart', function(list) {
+ done1 = true;
+ });
+ list.on('sortComplete', function(list) {
+ if (done1) {
+ done();
+ }
+ });
+ list.sort('name');
+ });
+ });
+
+ describe('Filter', function() {
+ it('should be triggered before and after filter', function(done) {
+ var done1 = false;
+ list.on('filterStart', function(list) {
+ done1 = true;
+ });
+ list.on('filterComplete', function(list) {
+ if (done1) {
+ done();
+ }
+ });
+ list.filter(function() {
+ return true;
+ });
+ });
+ });
+});
diff --git a/test/test.parse.js b/test/test.parse.js
new file mode 100644
index 0000000..463099f
--- /dev/null
+++ b/test/test.parse.js
@@ -0,0 +1,48 @@
+describe('Parse', function() {
+
+ var list;
+
+ before(function() {
+ $('body').append($('<div id="parse-list">\
+ <div class="list">\
+ <div><span class="name">Jonny</span><span class="born">1986</span></div>\
+ <div><span class="name">Jocke</span><span class="born">1985</span></div>\
+ </div>\
+ </div>'));
+
+ list = new List('parse-list', {
+ valueNames: ['name', 'born']
+ });
+ });
+
+ after(function() {
+ $('#parse-list').remove();
+ });
+
+ describe('Parse', function() {
+ it('should have two items', function() {
+ expect(list.items.length).to.equal(2);
+ expect(list.items[0].values().name).to.equal("Jonny");
+ expect(list.items[1].values().name).to.equal("Jocke");
+ });
+ it('should add item to parsed list', function() {
+ list.add({ name: "Sven", born: 1950 });
+ expect(list.items.length).to.equal(3);
+ expect(list.items[0].values().name).to.equal("Jonny");
+ expect(list.items[1].values().name).to.equal("Jocke");
+ expect(list.items[2].values().name).to.equal("Sven");
+ expect(list.items[0].values().born).to.equal("1986");
+ expect(list.items[2].values().born).to.equal(1950);
+ var el = $($('#parse-list').find('.list div')[2]);
+ expect(el.find('span').size()).to.equal(2);
+ expect(el.find('span.name').text()).to.equal('Sven');
+ expect(el.find('span.born').text()).to.equal('1950');
+ });
+ it('should parsed value always be string while added could be number', function() {
+ expect(list.items[0].values().born).to.equal("1986");
+ expect(list.items[0].values().born).not.to.equal(1986);
+ expect(list.items[2].values().born).not.to.equal("1950");
+ expect(list.items[2].values().born).to.equal(1950);
+ });
+ });
+});
diff --git a/test/test.search-filter.js b/test/test.search-filter.js
new file mode 100644
index 0000000..c0643e3
--- /dev/null
+++ b/test/test.search-filter.js
@@ -0,0 +1,66 @@
+describe('Search and filter', function() {
+
+ var list, jonny, martina, angelica, sebastian, imma, hasse;
+
+ before(function() {
+ list = fixture.list(['name', 'born'], fixture.all);
+
+ jonny = list.get('name', 'Jonny Strömberg')[0];
+ martina = list.get('name', 'Martina Elm')[0];
+ angelica = list.get('name', 'Angelica Abraham')[0];
+ sebastian = list.get('name', 'Sebastian Höglund')[0];
+ imma = list.get('name', 'Imma Grafström')[0];
+ hasse = list.get('name', 'Hasse Strömberg')[0];
+ });
+
+ after(function() {
+ fixture.removeList();
+ });
+
+ afterEach(function() {
+ list.search();
+ list.filter();
+ });
+
+ describe('Search with filter', function() {
+ it('should find everyone born 1986', function() {
+ list.filter(function(item) {
+ return (item.values().born == '1986');
+ });
+ expect(list.matchingItems.length).to.equal(3);
+ expect(jonny.matching()).to.be(true);
+ expect(martina.matching()).to.be(true);
+ expect(angelica.matching()).to.be(true);
+ expect(sebastian.matching()).to.be(false);
+ expect(imma.matching()).to.be(false);
+ expect(hasse.matching()).to.be(false);
+ });
+ it('should find everyone born 1986 and containes "ö"', function() {
+ list.filter(function(item) {
+ return (item.values().born == '1986');
+ });
+ list.search('ö');
+ expect(list.matchingItems.length).to.equal(1);
+ expect(jonny.matching()).to.be(true);
+ expect(martina.matching()).to.be(false);
+ expect(angelica.matching()).to.be(false);
+ expect(sebastian.matching()).to.be(false);
+ expect(imma.matching()).to.be(false);
+ expect(hasse.matching()).to.be(false);
+ });
+ it('should find everyone with a "ö"', function() {
+ list.filter(function(item) {
+ return (item.values().born == '1986');
+ });
+ list.search('ö');
+ list.filter();
+ expect(list.matchingItems.length).to.equal(4);
+ expect(jonny.matching()).to.be(true);
+ expect(martina.matching()).to.be(false);
+ expect(angelica.matching()).to.be(false);
+ expect(sebastian.matching()).to.be(true);
+ expect(imma.matching()).to.be(true);
+ expect(hasse.matching()).to.be(true);
+ });
+ });
+});
diff --git a/test/test.search.js b/test/test.search.js
new file mode 100644
index 0000000..69426e9
--- /dev/null
+++ b/test/test.search.js
@@ -0,0 +1,114 @@
+describe('Search', function() {
+
+ var list, jonny, martina, angelica, sebastian, imma, hasse;
+
+ beforeEach(function() {
+ list = fixture.list(['name', 'born'], fixture.all);
+
+ jonny = list.get('name', 'Jonny Strömberg')[0];
+ martina = list.get('name', 'Martina Elm')[0];
+ angelica = list.get('name', 'Angelica Abraham')[0];
+ sebastian = list.get('name', 'Sebastian Höglund')[0];
+ imma = list.get('name', 'Imma Grafström')[0];
+ hasse = list.get('name', 'Hasse Strömberg')[0];
+ });
+
+ afterEach(function() {
+ fixture.removeList();
+ });
+
+ describe('Case-sensitive', function() {
+ it('should not be case-sensitive', function() {
+ var result = list.search('jonny');
+ expect(result.length).to.equal(1);
+ expect(result[0]).to.eql(jonny);
+ });
+ });
+
+ describe('Number of results', function() {
+ it('should find jonny, martina, angelice', function() {
+ var result = list.search('1986');
+ expect(result.length).to.equal(3); // 3!!
+ expect(jonny.matching()).to.be(true);
+ expect(martina.matching()).to.be(true);
+ expect(angelica.matching()).to.be(true);
+ expect(sebastian.matching()).to.be(false);
+ expect(imma.matching()).to.be(false);
+ expect(hasse.matching()).to.be(false);
+ });
+ it('should find all with utf-8 char ö', function() {
+ var result = list.search('ö');
+ expect(result.length).to.equal(4); // 4!!
+ expect(jonny.matching()).to.be(true);
+ expect(martina.matching()).to.be(false);
+ expect(angelica.matching()).to.be(false);
+ expect(sebastian.matching()).to.be(true);
+ expect(imma.matching()).to.be(true);
+ expect(hasse.matching()).to.be(true);
+ });
+ it('should not break with weird searches', function() {
+ expect(list.search).withArgs(undefined).to.not.throwException();
+ expect(list.search).withArgs(null).to.not.throwException();
+ expect(list.search).withArgs(0).to.not.throwException();
+ expect(list.search).withArgs(function() {}).to.not.throwException();
+ expect(list.search).withArgs({ foo: "bar" }).to.not.throwException();
+ });
+ it('should not break with weird values', function() {
+ jonny.values({ name: undefined });
+ martina.values({ name: null });
+ angelica.values({ name: 0 });
+ sebastian.values({ name: function() {} });
+ imma.values({ name: { foo: "bar" } });
+
+ expect(list.search).withArgs("jonny").to.not.throwException();
+ expect(list.search).withArgs(undefined).to.not.throwException();
+ expect(list.search).withArgs(null).to.not.throwException();
+ expect(list.search).withArgs(0).to.not.throwException();
+ expect(list.search).withArgs(function() {}).to.not.throwException();
+ expect(list.search).withArgs({ foo: "bar" }).to.not.throwException();
+ });
+ });
+
+ describe('Specfic columns', function() {
+ it('should find match in column', function() {
+ var result = list.search('jonny', [ 'name' ]);
+ expect(result.length).to.equal(1);
+ expect(result[0]).to.eql(jonny);
+ });
+ it('should not find match in column', function() {
+ var result = list.search('jonny', [ 'born' ]);
+ expect(result.length).to.equal(0);
+ });
+ it('should find match in column', function() {
+ var result = list.search('jonny', [ 'name' ]);
+ expect(result.length).to.equal(1);
+ expect(result[0]).to.eql(jonny);
+ });
+ it('should not find match in column', function() {
+ var result = list.search('jonny', [ 'born' ]);
+ expect(result.length).to.equal(0);
+ });
+ it('should work with columns that does not exist', function() {
+ var result = list.search('jonny', [ 'pet' ]);
+ expect(result.length).to.equal(0);
+ });
+ });
+
+ describe('Custom search function', function() {
+ var customSearchFunction = function(searchString, columns) {
+ for (var k = 0, kl = list.items.length; k < kl; k++) {
+ if (list.items[k].values().born > 1985) {
+ list.items[k].found = true;
+ }
+ }
+ };
+ it('should use custom function in third argument', function() {
+ var result = list.search('jonny', [ 'name' ], customSearchFunction);
+ expect(result.length).to.equal(4);
+ });
+ it('should use custom function in second argument', function() {
+ var result = list.search('jonny', customSearchFunction);
+ expect(result.length).to.equal(4);
+ });
+ });
+});
diff --git a/test/test.show.js b/test/test.show.js
new file mode 100644
index 0000000..23261ca
--- /dev/null
+++ b/test/test.show.js
@@ -0,0 +1,208 @@
+describe('Show', function() {
+
+ var list, a, b, c, d, e, f;
+
+ before(function() {
+ list = fixture.list(['id'], [
+ { id: "1", id2: "a" },
+ { id: "2", id2: "a" },
+ { id: "3", id2: "b" },
+ { id: "4", id2: "b" },
+ { id: "5", id2: "bc" },
+ { id: "6", id2: "bc" }
+ ]);
+ a = list.get('id', '1')[0];
+ b = list.get('id', '2')[0];
+ c = list.get('id', '3')[0];
+ d = list.get('id', '4')[0];
+ e = list.get('id', '5')[0];
+ f = list.get('id', '6')[0];
+ });
+
+ after(function() {
+ fixture.removeList();
+ });
+
+ afterEach(function() {
+ list.filter();
+ list.show(1, 200);
+ });
+
+ describe('Basics', function() {
+ it('should be 1, 2', function() {
+ list.show(1,2);
+ expect(list.visibleItems.length).to.equal(2);
+ expect(a.visible()).to.be(true);
+ expect(b.visible()).to.be(true);
+ expect(c.visible()).to.be(false);
+ expect(d.visible()).to.be(false);
+ expect(e.visible()).to.be(false);
+ expect(f.visible()).to.be(false);
+ });
+ it('should show item 6', function() {
+ list.show(6,2);
+ expect(list.visibleItems.length).to.equal(1);
+ expect(a.visible()).to.be(false);
+ expect(b.visible()).to.be(false);
+ expect(c.visible()).to.be(false);
+ expect(d.visible()).to.be(false);
+ expect(e.visible()).to.be(false);
+ expect(f.visible()).to.be(true);
+ });
+ it('should show item 1, 2, 3, 4, 5, 6', function() {
+ list.show(1,200);
+ expect(list.visibleItems.length).to.equal(6);
+ expect(a.visible()).to.be(true);
+ expect(b.visible()).to.be(true);
+ expect(c.visible()).to.be(true);
+ expect(d.visible()).to.be(true);
+ expect(e.visible()).to.be(true);
+ expect(f.visible()).to.be(true);
+ });
+ it('should show item 3, 4, 5', function() {
+ list.show(3,3);
+ expect(list.visibleItems.length).to.equal(3);
+ expect(a.visible()).to.be(false);
+ expect(b.visible()).to.be(false);
+ expect(c.visible()).to.be(true);
+ expect(d.visible()).to.be(true);
+ expect(e.visible()).to.be(true);
+ expect(f.visible()).to.be(false);
+ });
+ it('should show item 5, 6', function() {
+ list.show(5,3);
+ expect(list.visibleItems.length).to.equal(2);
+ expect(a.visible()).to.be(false);
+ expect(b.visible()).to.be(false);
+ expect(c.visible()).to.be(false);
+ expect(d.visible()).to.be(false);
+ expect(e.visible()).to.be(true);
+ expect(f.visible()).to.be(true);
+ });
+ });
+
+ describe('Search', function() {
+ afterEach(function() {
+ list.search();
+ });
+ it('should show 3, 4', function() {
+ list.search('b');
+ list.show(1,2);
+ expect(list.visibleItems.length).to.equal(2);
+ expect(a.visible()).to.be(false);
+ expect(b.visible()).to.be(false);
+ expect(c.visible()).to.be(true);
+ expect(d.visible()).to.be(true);
+ expect(e.visible()).to.be(false);
+ expect(f.visible()).to.be(false);
+ });
+ it('should show item 3,4,5,6', function() {
+ list.search('b');
+ list.show(1,4);
+ expect(list.visibleItems.length).to.equal(4);
+ expect(a.visible()).to.be(false);
+ expect(b.visible()).to.be(false);
+ expect(c.visible()).to.be(true);
+ expect(d.visible()).to.be(true);
+ expect(e.visible()).to.be(true);
+ expect(f.visible()).to.be(true);
+ });
+ it('should not show any items but match two', function() {
+ list.search('a');
+ list.show(3,2);
+ expect(list.visibleItems.length).to.equal(0);
+ expect(list.matchingItems.length).to.equal(2);
+ expect(a.visible()).to.be(false);
+ expect(b.visible()).to.be(false);
+ expect(c.visible()).to.be(false);
+ expect(d.visible()).to.be(false);
+ expect(e.visible()).to.be(false);
+ expect(f.visible()).to.be(false);
+ });
+ });
+
+ describe('Filter', function() {
+ afterEach(function() {
+ list.filter();
+ });
+ it('should show 3, 4', function() {
+ list.filter(function(item) {
+ return (item.values().id2 == 'b');
+ });
+ list.show(1,2);
+ expect(list.visibleItems.length).to.equal(2);
+ expect(list.matchingItems.length).to.equal(2);
+ expect(a.visible()).to.be(false);
+ expect(b.visible()).to.be(false);
+ expect(c.visible()).to.be(true);
+ expect(d.visible()).to.be(true);
+ expect(e.visible()).to.be(false);
+ expect(f.visible()).to.be(false);
+ });
+ it('should show item 3,4,5,6', function() {
+ list.filter(function(item) {
+ return (item.values().id2 == 'bc');
+ });
+ list.show(1,4);
+ expect(list.visibleItems.length).to.equal(2);
+ expect(list.matchingItems.length).to.equal(2);
+ expect(a.visible()).to.be(false);
+ expect(b.visible()).to.be(false);
+ expect(c.visible()).to.be(false);
+ expect(d.visible()).to.be(false);
+ expect(e.visible()).to.be(true);
+ expect(f.visible()).to.be(true);
+ });
+ it('should not show any items but match two', function() {
+ list.filter(function(item) {
+ return (item.values().id2 == 'b');
+ });
+ list.show(3,2);
+ expect(list.visibleItems.length).to.equal(0);
+ expect(list.matchingItems.length).to.equal(2);
+ expect(a.visible()).to.be(false);
+ expect(b.visible()).to.be(false);
+ expect(c.visible()).to.be(false);
+ expect(d.visible()).to.be(false);
+ expect(e.visible()).to.be(false);
+ expect(f.visible()).to.be(false);
+ });
+ });
+
+ describe('Filter and search', function() {
+ afterEach(function() {
+ list.filter();
+ });
+ it('should show 4, 5', function() {
+ list.show(1,2);
+ list.filter(function(item) {
+ return (item.values().id > '3');
+ });
+ list.search('b');
+ expect(list.visibleItems.length).to.equal(2);
+ expect(list.matchingItems.length).to.equal(3);
+ expect(a.visible()).to.be(false);
+ expect(b.visible()).to.be(false);
+ expect(c.visible()).to.be(false);
+ expect(d.visible()).to.be(true);
+ expect(e.visible()).to.be(true);
+ expect(f.visible()).to.be(false);
+ });
+ it('should show 5, 6', function() {
+ list.show(1,2);
+ list.filter(function(item) {
+ return (item.values().id > '3');
+ });
+ list.search('b');
+ list.show(2,2);
+ expect(list.visibleItems.length).to.equal(2);
+ expect(list.matchingItems.length).to.equal(3);
+ expect(a.visible()).to.be(false);
+ expect(b.visible()).to.be(false);
+ expect(c.visible()).to.be(false);
+ expect(d.visible()).to.be(false);
+ expect(e.visible()).to.be(true);
+ expect(f.visible()).to.be(true);
+ });
+ });
+});
diff --git a/test/test.sort.js b/test/test.sort.js
new file mode 100644
index 0000000..8450b7e
--- /dev/null
+++ b/test/test.sort.js
@@ -0,0 +1,320 @@
+describe('Sort', function() {
+
+ var list, i1, i2, i3, i4, i5, i6;
+
+ beforeEach(function() {
+ list = fixture.list(['id'], [
+ { id: "1", val: "" },
+ { id: "2", val: "" },
+ { id: "3", val: "" },
+ { id: "4", val: "" },
+ { id: "5", val: "" },
+ { id: "6", val: "" }
+ ]);
+ i1 = list.get('id', '1')[0];
+ i2 = list.get('id', '2')[0];
+ i3 = list.get('id', '3')[0];
+ i4 = list.get('id', '4')[0];
+ i5 = list.get('id', '5')[0];
+ i6 = list.get('id', '6')[0];
+ });
+
+ afterEach(function() {
+ fixture.removeList();
+ });
+
+ describe('Basics', function() {
+ it('should sort letters asc', function() {
+ i1.values({ val: "b" });
+ i2.values({ val: "a" });
+ i3.values({ val: "c" });
+ i4.values({ val: "z" });
+ i5.values({ val: "s" });
+ i6.values({ val: "y" });
+ list.sort('val');
+ expect(list.items[0].values().val).to.be.equal("a");
+ expect(list.items[1].values().val).to.be.equal("b");
+ expect(list.items[2].values().val).to.be.equal("c");
+ expect(list.items[3].values().val).to.be.equal("s");
+ expect(list.items[4].values().val).to.be.equal("y");
+ expect(list.items[5].values().val).to.be.equal("z");
+ });
+ it('should sort letters desc', function() {
+ i1.values({ val: "b" });
+ i2.values({ val: "a" });
+ i3.values({ val: "c" });
+ i4.values({ val: "z" });
+ i5.values({ val: "s" });
+ i6.values({ val: "y" });
+ list.sort('val', { order: "desc" });
+ expect(list.items[0].values().val).to.be.equal("z");
+ expect(list.items[1].values().val).to.be.equal("y");
+ expect(list.items[2].values().val).to.be.equal("s");
+ expect(list.items[3].values().val).to.be.equal("c");
+ expect(list.items[4].values().val).to.be.equal("b");
+ expect(list.items[5].values().val).to.be.equal("a");
+ });
+ it('should fail to sort åäö desc (becomes äåö)', function() {
+ i1.values({ val: "a" });
+ i2.values({ val: "å" });
+ i3.values({ val: "ä" });
+ i4.values({ val: "ö" });
+ i5.values({ val: "o" });
+ i6.values({ val: "s" });
+ list.sort('val');
+ expect(list.items[0].values().val).to.be.equal("a");
+ expect(list.items[1].values().val).to.be.equal("o");
+ expect(list.items[2].values().val).to.be.equal("s");
+ expect(list.items[3].values().val).to.be.equal("ä");
+ expect(list.items[4].values().val).to.be.equal("å");
+ expect(list.items[5].values().val).to.be.equal("ö");
+ });
+ it('should fail to sort åäö asc (becomes öåä)', function() {
+ i1.values({ val: "a" });
+ i2.values({ val: "å" });
+ i3.values({ val: "ä" });
+ i4.values({ val: "ö" });
+ i5.values({ val: "o" });
+ i6.values({ val: "s" });
+ list.sort('val', { order: "desc" });
+ expect(list.items[0].values().val).to.be.equal("ö");
+ expect(list.items[1].values().val).to.be.equal("å");
+ expect(list.items[2].values().val).to.be.equal("ä");
+ expect(list.items[3].values().val).to.be.equal("s");
+ expect(list.items[4].values().val).to.be.equal("o");
+ expect(list.items[5].values().val).to.be.equal("a");
+ });
+ it('should handle case-insensitive by default', function() {
+ i1.values({ val: "e" });
+ i2.values({ val: "b" });
+ i4.values({ val: "F" });
+ i3.values({ val: "D" });
+ i5.values({ val: "A" });
+ i6.values({ val: "C" });
+ list.sort('val');
+ expect(list.items[0].values().val).to.be.equal("A");
+ expect(list.items[1].values().val).to.be.equal("b");
+ expect(list.items[2].values().val).to.be.equal("C");
+ expect(list.items[3].values().val).to.be.equal("D");
+ expect(list.items[4].values().val).to.be.equal("e");
+ expect(list.items[5].values().val).to.be.equal("F");
+ });
+ it('should disable insensitive', function() {
+ i1.values({ val: "e" });
+ i2.values({ val: "b" });
+ i4.values({ val: "F" });
+ i3.values({ val: "D" });
+ i5.values({ val: "A" });
+ i6.values({ val: "C" });
+ list.sort('val', { insensitive: false });
+ expect(list.items[0].values().val).to.be.equal("A");
+ expect(list.items[1].values().val).to.be.equal("C");
+ expect(list.items[2].values().val).to.be.equal("D");
+ expect(list.items[3].values().val).to.be.equal("F");
+ expect(list.items[4].values().val).to.be.equal("b");
+ expect(list.items[5].values().val).to.be.equal("e");
+ });
+ it('should sort dates', function() {
+ i1.values({ val: "10/12/2008" });
+ i2.values({ val: "10/11/2008" });
+ i3.values({ val: "10/11/2007" });
+ i4.values({ val: "10/12/2009" });
+ i5.values({ val: "4/01/2007" });
+ i6.values({ val: "10/12/2006" });
+ list.sort('val', { order: "asc" });
+ expect(list.items[0].values().val).to.be.equal("10/12/2006");
+ expect(list.items[1].values().val).to.be.equal("4/01/2007");
+ expect(list.items[2].values().val).to.be.equal("10/11/2007");
+ expect(list.items[3].values().val).to.be.equal("10/11/2008");
+ expect(list.items[4].values().val).to.be.equal("10/12/2008");
+ expect(list.items[5].values().val).to.be.equal("10/12/2009");
+ });
+ it('should sort file names', function() {
+ i1.values({ val: "car.mov" });
+ i2.values({ val: "01alpha.sgi" });
+ i3.values({ val: "001alpha.sgi" });
+ i4.values({ val: "my.string_41299.tif" });
+ i5.values({ val: "0003.zip" });
+ i6.values({ val: "0002.asp" });
+ list.sort('val', { order: "asc" });
+ expect(list.items[0].values().val).to.be.equal("0002.asp");
+ expect(list.items[1].values().val).to.be.equal("0003.zip");
+ expect(list.items[2].values().val).to.be.equal("001alpha.sgi");
+ expect(list.items[3].values().val).to.be.equal("01alpha.sgi");
+ expect(list.items[4].values().val).to.be.equal("car.mov");
+ expect(list.items[5].values().val).to.be.equal("my.string_41299.tif");
+ });
+ it('should sort floates', function() {
+ i1.values({ val: "10.0401" });
+ i2.values({ val: "10.022" });
+ i3.values({ val: "10.021999" });
+ i4.values({ val: "11.231" });
+ i5.values({ val: "0003.123" });
+ i6.values({ val: "09.2123" });
+ list.sort('val', { order: "asc" });
+ expect(list.items[0].values().val).to.be.equal("0003.123");
+ expect(list.items[1].values().val).to.be.equal("09.2123");
+ expect(list.items[2].values().val).to.be.equal("10.021999");
+ expect(list.items[3].values().val).to.be.equal("10.022");
+ expect(list.items[4].values().val).to.be.equal("10.0401");
+ expect(list.items[5].values().val).to.be.equal("11.231");
+ });
+ it('should sort IP addresses', function() {
+ i1.values({ val: "192.168.1.1" });
+ i2.values({ val: "192.168.0.100" });
+ i3.values({ val: "192.168.0.1" });
+ i4.values({ val: "192.168.1.3" });
+ i5.values({ val: "127.0.0.1" });
+ i6.values({ val: "192.168.1.2" });
+ list.sort('val', { order: "asc" });
+ expect(list.items[0].values().val).to.be.equal("127.0.0.1");
+ expect(list.items[1].values().val).to.be.equal("192.168.0.1");
+ expect(list.items[2].values().val).to.be.equal("192.168.0.100");
+ expect(list.items[3].values().val).to.be.equal("192.168.1.1");
+ expect(list.items[4].values().val).to.be.equal("192.168.1.2");
+ expect(list.items[5].values().val).to.be.equal("192.168.1.3");
+ });
+ it('should not break with weird values', function() {
+ i1.values({ val: undefined });
+ i2.values({ val: null });
+ i3.values({ val: 0 });
+ i4.values({ val: function() {} });
+ i5.values({ val: { foo: "bar" } });
+
+ expect(list.sort).withArgs('val').to.not.throwException();
+ expect(list.sort).withArgs('val').to.not.throwException();
+ expect(list.sort).withArgs('val').to.not.throwException();
+ expect(list.sort).withArgs('val').to.not.throwException();
+ expect(list.sort).withArgs('val').to.not.throwException();
+ expect(list.sort).withArgs('val').to.not.throwException();
+ });
+ /*
+ it('should show how random values are sorted', function() {
+ list.add({ id: '7', val: "" });
+ list.add({ id: '8', val: "" });
+ list.add({ id: '9', val: "" });
+ list.add({ id: '10', val: "" });
+ list.add({ id: '11', val: "" });
+ list.add({ id: '12', val: "" });
+
+ var i7 = list.get('id', '7')[0],
+ i8 = list.get('id', '8')[0],
+ i9 = list.get('id', '9')[0],
+ i10 = list.get('id', '10')[0],
+ i11 = list.get('id', '11')[0],
+ i12 = list.get('id', '12')[0];
+
+ i1.values({ val: undefined });
+ i2.values({ val: "" });
+ i3.values({ val: null });
+ i4.values({ val: "a" });
+ i5.values({ val: "0" });
+ i6.values({ val: true });
+ i7.values({ val: 0 });
+ i8.values({ val: "z" });
+ i9.values({ val: "!" });
+ i10.values({ val: "?" });
+ i11.values({ val: 100 });
+ i12.values({ val: false });
+
+ list.sort('val', { order: "asc" });
+ list.sort('val', { order: "desc" });
+ list.sort('val', { order: "asc" });
+
+ expect(list.items[0].values().val).to.be.equal("");
+ expect(list.items[1].values().val).to.be.equal("0");
+ expect(list.items[2].values().val).to.be.equal(0);
+ expect(list.items[3].values().val).to.be.equal(100);
+ expect(list.items[4].values().val).to.be.equal("!");
+ expect(list.items[5].values().val).to.be.equal("?");
+ expect(list.items[6].values().val).to.be.equal("a");
+ expect(list.items[7].values().val).to.be.equal(false);
+ expect(list.items[8].values().val).to.be.equal(null);
+ expect(list.items[9].values().val).to.be.equal(true);
+ expect(list.items[10].values().val).to.be.equal(undefined);
+ expect(list.items[11].values().val).to.be.equal("z");
+ });
+
+ it('should handle space and zero the same for desc and asc (random)', function() {
+ list.clear();
+ list.add({ val: "" });
+ list.add({ val: "0" });
+ list.add({ val: 0 });
+
+ list.sort('val', { order: "asc" });
+ expect(list.items[0].values().val).to.be.equal("");
+ expect(list.items[1].values().val).to.be.equal("0");
+ expect(list.items[2].values().val).to.be.equal(0);
+ list.sort('val', { order: "desc" });
+ expect(list.items[0].values().val).to.be.equal("");
+ expect(list.items[1].values().val).to.be.equal("0");
+ expect(list.items[2].values().val).to.be.equal(0);
+ list.sort('val', { order: "asc" });
+ expect(list.items[0].values().val).to.be.equal("");
+ expect(list.items[1].values().val).to.be.equal("0");
+ expect(list.items[2].values().val).to.be.equal(0);
+ });
+ */
+ });
+
+ describe('Custom sort function', function() {
+ it('should use custom sort option', function() {
+ i1.values({ val: "<input value='b' />" });
+ i2.values({ val: "<input value='a' />" });
+ i3.values({ val: "<input value='c' />" });
+ i4.values({ val: "<input value='z' />" });
+ i5.values({ val: "<input value='s' />" });
+ i6.values({ val: "<input value='y' />" });
+ list.sort('val', {
+ sortFunction: function(itemA, itemB, options) {
+ options.desc = false;
+ return list.helpers.naturalSort($(itemA.values()[options.valueName]).val(), $(itemB.values()[options.valueName]).val(), options);
+ }
+ });
+ expect(list.items[0].values().val).to.be.equal("<input value='a' />");
+ expect(list.items[1].values().val).to.be.equal("<input value='b' />");
+ expect(list.items[2].values().val).to.be.equal("<input value='c' />");
+ expect(list.items[3].values().val).to.be.equal("<input value='s' />");
+ expect(list.items[4].values().val).to.be.equal("<input value='y' />");
+ expect(list.items[5].values().val).to.be.equal("<input value='z' />");
+ });
+ it('should use default custom sort function', function() {
+ list.sortFunction = function(itemA, itemB, options) {
+ options.desc = false;
+ return list.helpers.naturalSort($(itemA.values()[options.valueName]).val(), $(itemB.values()[options.valueName]).val(), options);
+ };
+ i1.values({ val: "<input value='b' />" });
+ i2.values({ val: "<input value='a' />" });
+ i3.values({ val: "<input value='c' />" });
+ i4.values({ val: "<input value='z' />" });
+ i5.values({ val: "<input value='s' />" });
+ i6.values({ val: "<input value='y' />" });
+ list.sort('val');
+ expect(list.items[0].values().val).to.be.equal("<input value='a' />");
+ expect(list.items[1].values().val).to.be.equal("<input value='b' />");
+ expect(list.items[2].values().val).to.be.equal("<input value='c' />");
+ expect(list.items[3].values().val).to.be.equal("<input value='s' />");
+ expect(list.items[4].values().val).to.be.equal("<input value='y' />");
+ expect(list.items[5].values().val).to.be.equal("<input value='z' />");
+ });
+ it('should use default custom sort function with options', function() {
+ list.sortFunction = function(itemA, itemB, options) {
+ options.desc = true;
+ return list.helpers.naturalSort($(itemA.values()[options.valueName]).val(), $(itemB.values()[options.valueName]).val(), options);
+ };
+ i1.values({ val: "<input value='b' />" });
+ i2.values({ val: "<input value='a' />" });
+ i3.values({ val: "<input value='c' />" });
+ i4.values({ val: "<input value='z' />" });
+ i5.values({ val: "<input value='s' />" });
+ i6.values({ val: "<input value='y' />" });
+ list.sort('val', { order: "desc"});
+ expect(list.items[0].values().val).to.be.equal("<input value='z' />");
+ expect(list.items[1].values().val).to.be.equal("<input value='y' />");
+ expect(list.items[2].values().val).to.be.equal("<input value='s' />");
+ expect(list.items[3].values().val).to.be.equal("<input value='c' />");
+ expect(list.items[4].values().val).to.be.equal("<input value='b' />");
+ expect(list.items[5].values().val).to.be.equal("<input value='a' />");
+ });
+ });
+});
diff --git a/test/test.trigger.js b/test/test.trigger.js
new file mode 100644
index 0000000..c51ecff
--- /dev/null
+++ b/test/test.trigger.js
@@ -0,0 +1,21 @@
+describe('Trigger', function() {
+
+ var list;
+
+ before(function() {
+ list = fixture.list(['name', 'born'], fixture.all);
+ });
+
+ after(function() {
+ fixture.removeList();
+ });
+
+ describe('General', function() {
+ it('should be triggered by searchComplete', function(done) {
+ list.on('searchComplete', function() {
+ done();
+ });
+ list.trigger('searchComplete');
+ });
+ });
+});
\ No newline at end of file
--
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/pkg-javascript/list.js.git
More information about the Pkg-javascript-commits
mailing list