< arguments.length; i++) {
+ var child = arguments[i];
+
+ if (typeof child === 'string') {
+ el.appendChild(document.createTextNode(child));
+ } else {
+ if (child) {
+ el.appendChild(child);
+ }
+ }
+ }
+
+ for (var attr in attrs) {
+ if (attr == "className") {
+ el[attr] = attrs[attr];
+ } else {
+ el.setAttribute(attr, attrs[attr]);
+ }
+ }
+
+ return el;
+};
+
+jasmine.HtmlReporterHelpers.getSpecStatus = function(child) {
+ var results = child.results();
+ var status = results.passed() ? 'passed' : 'failed';
+ if (results.skipped) {
+ status = 'skipped';
+ }
+
+ return status;
+};
+
+jasmine.HtmlReporterHelpers.appendToSummary = function(child, childElement) {
+ var parentDiv = this.dom.summary;
+ var parentSuite = (typeof child.parentSuite == 'undefined') ? 'suite' : 'parentSuite';
+ var parent = child[parentSuite];
+
+ if (parent) {
+ if (typeof this.views.suites[parent.id] == 'undefined') {
+ this.views.suites[parent.id] = new jasmine.HtmlReporter.SuiteView(parent, this.dom, this.views);
+ }
+ parentDiv = this.views.suites[parent.id].element;
+ }
+
+ parentDiv.appendChild(childElement);
+};
+
+
+jasmine.HtmlReporterHelpers.addHelpers = function(ctor) {
+ for(var fn in jasmine.HtmlReporterHelpers) {
+ ctor.prototype[fn] = jasmine.HtmlReporterHelpers[fn];
+ }
+};
+
+jasmine.HtmlReporter = function(_doc) {
+ var self = this;
+ var doc = _doc || window.document;
+
+ var reporterView;
+
+ var dom = {};
+
+ // Jasmine Reporter Public Interface
+ self.logRunningSpecs = false;
+
+ self.reportRunnerStarting = function(runner) {
+ var specs = runner.specs() || [];
+
+ if (specs.length == 0) {
+ return;
+ }
+
+ createReporterDom(runner.env.versionString());
+ doc.body.appendChild(dom.reporter);
+ setExceptionHandling();
+
+ reporterView = new jasmine.HtmlReporter.ReporterView(dom);
+ reporterView.addSpecs(specs, self.specFilter);
+ };
+
+ self.reportRunnerResults = function(runner) {
+ reporterView && reporterView.complete();
+ };
+
+ self.reportSuiteResults = function(suite) {
+ reporterView.suiteComplete(suite);
+ };
+
+ self.reportSpecStarting = function(spec) {
+ if (self.logRunningSpecs) {
+ self.log('>> Jasmine Running ' + spec.suite.description + ' ' + spec.description + '...');
+ }
+ };
+
+ self.reportSpecResults = function(spec) {
+ reporterView.specComplete(spec);
+ };
+
+ self.log = function() {
+ var console = jasmine.getGlobal().console;
+ if (console && console.log) {
+ if (console.log.apply) {
+ console.log.apply(console, arguments);
+ } else {
+ console.log(arguments); // ie fix: console.log.apply doesn't exist on ie
+ }
+ }
+ };
+
+ self.specFilter = function(spec) {
+ if (!focusedSpecName()) {
+ return true;
+ }
+
+ return spec.getFullName().indexOf(focusedSpecName()) === 0;
+ };
+
+ return self;
+
+ function focusedSpecName() {
+ var specName;
+
+ (function memoizeFocusedSpec() {
+ if (specName) {
+ return;
+ }
+
+ var paramMap = [];
+ var params = jasmine.HtmlReporter.parameters(doc);
+
+ for (var i = 0; i < params.length; i++) {
+ var p = params[i].split('=');
+ paramMap[decodeURIComponent(p[0])] = decodeURIComponent(p[1]);
+ }
+
+ specName = paramMap.spec;
+ })();
+
+ return specName;
+ }
+
+ function createReporterDom(version) {
+ dom.reporter = self.createDom('div', { id: 'HTMLReporter', className: 'jasmine_reporter' },
+ dom.banner = self.createDom('div', { className: 'banner' },
+ self.createDom('span', { className: 'title' }, "Jasmine "),
+ self.createDom('span', { className: 'version' }, version)),
+
+ dom.symbolSummary = self.createDom('ul', {className: 'symbolSummary'}),
+ dom.alert = self.createDom('div', {className: 'alert'},
+ self.createDom('span', { className: 'exceptions' },
+ self.createDom('label', { className: 'label', 'for': 'no_try_catch' }, 'No try/catch'),
+ self.createDom('input', { id: 'no_try_catch', type: 'checkbox' }))),
+ dom.results = self.createDom('div', {className: 'results'},
+ dom.summary = self.createDom('div', { className: 'summary' }),
+ dom.details = self.createDom('div', { id: 'details' }))
+ );
+ }
+
+ function noTryCatch() {
+ return window.location.search.match(/catch=false/);
+ }
+
+ function searchWithCatch() {
+ var params = jasmine.HtmlReporter.parameters(window.document);
+ var removed = false;
+ var i = 0;
+
+ while (!removed && i < params.length) {
+ if (params[i].match(/catch=/)) {
+ params.splice(i, 1);
+ removed = true;
+ }
+ i++;
+ }
+ if (jasmine.CATCH_EXCEPTIONS) {
+ params.push("catch=false");
+ }
+
+ return params.join("&");
+ }
+
+ function setExceptionHandling() {
+ var chxCatch = document.getElementById('no_try_catch');
+
+ if (noTryCatch()) {
+ chxCatch.setAttribute('checked', true);
+ jasmine.CATCH_EXCEPTIONS = false;
+ }
+ chxCatch.onclick = function() {
+ window.location.search = searchWithCatch();
+ };
+ }
+};
+jasmine.HtmlReporter.parameters = function(doc) {
+ var paramStr = doc.location.search.substring(1);
+ var params = [];
+
+ if (paramStr.length > 0) {
+ params = paramStr.split('&');
+ }
+ return params;
+}
+jasmine.HtmlReporter.sectionLink = function(sectionName) {
+ var link = '?';
+ var params = [];
+
+ if (sectionName) {
+ params.push('spec=' + encodeURIComponent(sectionName));
+ }
+ if (!jasmine.CATCH_EXCEPTIONS) {
+ params.push("catch=false");
+ }
+ if (params.length > 0) {
+ link += params.join("&");
+ }
+
+ return link;
+};
+jasmine.HtmlReporterHelpers.addHelpers(jasmine.HtmlReporter);
+jasmine.HtmlReporter.ReporterView = function(dom) {
+ this.startedAt = new Date();
+ this.runningSpecCount = 0;
+ this.completeSpecCount = 0;
+ this.passedCount = 0;
+ this.failedCount = 0;
+ this.skippedCount = 0;
+
+ this.createResultsMenu = function() {
+ this.resultsMenu = this.createDom('span', {className: 'resultsMenu bar'},
+ this.summaryMenuItem = this.createDom('a', {className: 'summaryMenuItem', href: "#"}, '0 specs'),
+ ' | ',
+ this.detailsMenuItem = this.createDom('a', {className: 'detailsMenuItem', href: "#"}, '0 failing'));
+
+ this.summaryMenuItem.onclick = function() {
+ dom.reporter.className = dom.reporter.className.replace(/ showDetails/g, '');
+ };
+
+ this.detailsMenuItem.onclick = function() {
+ showDetails();
+ };
+ };
+
+ this.addSpecs = function(specs, specFilter) {
+ this.totalSpecCount = specs.length;
+
+ this.views = {
+ specs: {},
+ suites: {}
+ };
+
+ for (var i = 0; i < specs.length; i++) {
+ var spec = specs[i];
+ this.views.specs[spec.id] = new jasmine.HtmlReporter.SpecView(spec, dom, this.views);
+ if (specFilter(spec)) {
+ this.runningSpecCount++;
+ }
+ }
+ };
+
+ this.specComplete = function(spec) {
+ this.completeSpecCount++;
+
+ if (isUndefined(this.views.specs[spec.id])) {
+ this.views.specs[spec.id] = new jasmine.HtmlReporter.SpecView(spec, dom);
+ }
+
+ var specView = this.views.specs[spec.id];
+
+ switch (specView.status()) {
+ case 'passed':
+ this.passedCount++;
+ break;
+
+ case 'failed':
+ this.failedCount++;
+ break;
+
+ case 'skipped':
+ this.skippedCount++;
+ break;
+ }
+
+ specView.refresh();
+ this.refresh();
+ };
+
+ this.suiteComplete = function(suite) {
+ var suiteView = this.views.suites[suite.id];
+ if (isUndefined(suiteView)) {
+ return;
+ }
+ suiteView.refresh();
+ };
+
+ this.refresh = function() {
+
+ if (isUndefined(this.resultsMenu)) {
+ this.createResultsMenu();
+ }
+
+ // currently running UI
+ if (isUndefined(this.runningAlert)) {
+ this.runningAlert = this.createDom('a', { href: jasmine.HtmlReporter.sectionLink(), className: "runningAlert bar" });
+ dom.alert.appendChild(this.runningAlert);
+ }
+ this.runningAlert.innerHTML = "Running " + this.completeSpecCount + " of " + specPluralizedFor(this.totalSpecCount);
+
+ // skipped specs UI
+ if (isUndefined(this.skippedAlert)) {
+ this.skippedAlert = this.createDom('a', { href: jasmine.HtmlReporter.sectionLink(), className: "skippedAlert bar" });
+ }
+
+ this.skippedAlert.innerHTML = "Skipping " + this.skippedCount + " of " + specPluralizedFor(this.totalSpecCount) + " - run all";
+
+ if (this.skippedCount === 1 && isDefined(dom.alert)) {
+ dom.alert.appendChild(this.skippedAlert);
+ }
+
+ // passing specs UI
+ if (isUndefined(this.passedAlert)) {
+ this.passedAlert = this.createDom('span', { href: jasmine.HtmlReporter.sectionLink(), className: "passingAlert bar" });
+ }
+ this.passedAlert.innerHTML = "Passing " + specPluralizedFor(this.passedCount);
+
+ // failing specs UI
+ if (isUndefined(this.failedAlert)) {
+ this.failedAlert = this.createDom('span', {href: "?", className: "failingAlert bar"});
+ }
+ this.failedAlert.innerHTML = "Failing " + specPluralizedFor(this.failedCount);
+
+ if (this.failedCount === 1 && isDefined(dom.alert)) {
+ dom.alert.appendChild(this.failedAlert);
+ dom.alert.appendChild(this.resultsMenu);
+ }
+
+ // summary info
+ this.summaryMenuItem.innerHTML = "" + specPluralizedFor(this.runningSpecCount);
+ this.detailsMenuItem.innerHTML = "" + this.failedCount + " failing";
+ };
+
+ this.complete = function() {
+ dom.alert.removeChild(this.runningAlert);
+
+ this.skippedAlert.innerHTML = "Ran " + this.runningSpecCount + " of " + specPluralizedFor(this.totalSpecCount) + " - run all";
+
+ if (this.failedCount === 0) {
+ dom.alert.appendChild(this.createDom('span', {className: 'passingAlert bar'}, "Passing " + specPluralizedFor(this.passedCount)));
+ } else {
+ showDetails();
+ }
+
+ dom.banner.appendChild(this.createDom('span', {className: 'duration'}, "finished in " + ((new Date().getTime() - this.startedAt.getTime()) / 1000) + "s"));
+ };
+
+ return this;
+
+ function showDetails() {
+ if (dom.reporter.className.search(/showDetails/) === -1) {
+ dom.reporter.className += " showDetails";
+ }
+ }
+
+ function isUndefined(obj) {
+ return typeof obj === 'undefined';
+ }
+
+ function isDefined(obj) {
+ return !isUndefined(obj);
+ }
+
+ function specPluralizedFor(count) {
+ var str = count + " spec";
+ if (count > 1) {
+ str += "s"
+ }
+ return str;
+ }
+
+};
+
+jasmine.HtmlReporterHelpers.addHelpers(jasmine.HtmlReporter.ReporterView);
+
+
+jasmine.HtmlReporter.SpecView = function(spec, dom, views) {
+ this.spec = spec;
+ this.dom = dom;
+ this.views = views;
+
+ this.symbol = this.createDom('li', { className: 'pending' });
+ this.dom.symbolSummary.appendChild(this.symbol);
+
+ this.summary = this.createDom('div', { className: 'specSummary' },
+ this.createDom('a', {
+ className: 'description',
+ href: jasmine.HtmlReporter.sectionLink(this.spec.getFullName()),
+ title: this.spec.getFullName()
+ }, this.spec.description)
+ );
+
+ this.detail = this.createDom('div', { className: 'specDetail' },
+ this.createDom('a', {
+ className: 'description',
+ href: '?spec=' + encodeURIComponent(this.spec.getFullName()),
+ title: this.spec.getFullName()
+ }, this.spec.getFullName())
+ );
+};
+
+jasmine.HtmlReporter.SpecView.prototype.status = function() {
+ return this.getSpecStatus(this.spec);
+};
+
+jasmine.HtmlReporter.SpecView.prototype.refresh = function() {
+ this.symbol.className = this.status();
+
+ switch (this.status()) {
+ case 'skipped':
+ break;
+
+ case 'passed':
+ this.appendSummaryToSuiteDiv();
+ break;
+
+ case 'failed':
+ this.appendSummaryToSuiteDiv();
+ this.appendFailureDetail();
+ break;
+ }
+};
+
+jasmine.HtmlReporter.SpecView.prototype.appendSummaryToSuiteDiv = function() {
+ this.summary.className += ' ' + this.status();
+ this.appendToSummary(this.spec, this.summary);
+};
+
+jasmine.HtmlReporter.SpecView.prototype.appendFailureDetail = function() {
+ this.detail.className += ' ' + this.status();
+
+ var resultItems = this.spec.results().getItems();
+ var messagesDiv = this.createDom('div', { className: 'messages' });
+
+ for (var i = 0; i < resultItems.length; i++) {
+ var result = resultItems[i];
+
+ if (result.type == 'log') {
+ messagesDiv.appendChild(this.createDom('div', {className: 'resultMessage log'}, result.toString()));
+ } else if (result.type == 'expect' && result.passed && !result.passed()) {
+ messagesDiv.appendChild(this.createDom('div', {className: 'resultMessage fail'}, result.message));
+
+ if (result.trace.stack) {
+ messagesDiv.appendChild(this.createDom('div', {className: 'stackTrace'}, result.trace.stack));
+ }
+ }
+ }
+
+ if (messagesDiv.childNodes.length > 0) {
+ this.detail.appendChild(messagesDiv);
+ this.dom.details.appendChild(this.detail);
+ }
+};
+
+jasmine.HtmlReporterHelpers.addHelpers(jasmine.HtmlReporter.SpecView);jasmine.HtmlReporter.SuiteView = function(suite, dom, views) {
+ this.suite = suite;
+ this.dom = dom;
+ this.views = views;
+
+ this.element = this.createDom('div', { className: 'suite' },
+ this.createDom('a', { className: 'description', href: jasmine.HtmlReporter.sectionLink(this.suite.getFullName()) }, this.suite.description)
+ );
+
+ this.appendToSummary(this.suite, this.element);
+};
+
+jasmine.HtmlReporter.SuiteView.prototype.status = function() {
+ return this.getSpecStatus(this.suite);
+};
+
+jasmine.HtmlReporter.SuiteView.prototype.refresh = function() {
+ this.element.className += " " + this.status();
+};
+
+jasmine.HtmlReporterHelpers.addHelpers(jasmine.HtmlReporter.SuiteView);
+
+/* @deprecated Use jasmine.HtmlReporter instead
+ */
jasmine.TrivialReporter = function(doc) {
this.document = doc || document;
this.suiteDivs = {};
@@ -31,10 +522,10 @@ jasmine.TrivialReporter.prototype.createDom = function(type, attrs, childrenVarA
jasmine.TrivialReporter.prototype.reportRunnerStarting = function(runner) {
var showPassed, showSkipped;
- this.outerDiv = this.createDom('div', { className: 'jasmine_reporter' },
+ this.outerDiv = this.createDom('div', { id: 'TrivialReporter', className: 'jasmine_reporter' },
this.createDom('div', { className: 'banner' },
this.createDom('div', { className: 'logo' },
- this.createDom('a', { href: 'http://pivotal.github.com/jasmine/', target: "_blank" }, "Jasmine"),
+ this.createDom('span', { className: 'title' }, "Jasmine"),
this.createDom('span', { className: 'version' }, runner.env.versionString())),
this.createDom('div', { className: 'options' },
"Show ",
@@ -110,7 +601,7 @@ jasmine.TrivialReporter.prototype.reportRunnerResults = function(runner) {
jasmine.TrivialReporter.prototype.reportSuiteResults = function(suite) {
var results = suite.results();
var status = results.passed() ? 'passed' : 'failed';
- if (results.totalCount == 0) { // todo: change this to check results.skipped
+ if (results.totalCount === 0) { // todo: change this to check results.skipped
status = 'skipped';
}
this.suiteDivs[suite.id].className += " " + status;
@@ -183,6 +674,8 @@ jasmine.TrivialReporter.prototype.specFilter = function(spec) {
paramMap[decodeURIComponent(p[0])] = decodeURIComponent(p[1]);
}
- if (!paramMap["spec"]) return true;
- return spec.getFullName().indexOf(paramMap["spec"]) == 0;
+ if (!paramMap.spec) {
+ return true;
+ }
+ return spec.getFullName().indexOf(paramMap.spec) === 0;
};
diff --git a/test/lib/jasmine-jquery.js b/test/lib/jasmine-jquery.js
index 2fccd137..a0f28606 100755
--- a/test/lib/jasmine-jquery.js
+++ b/test/lib/jasmine-jquery.js
@@ -1,254 +1,705 @@
-var readFixtures = function() {
- return jasmine.getFixtures().proxyCallTo_('read', arguments);
-};
-
-var loadFixtures = function() {
- jasmine.getFixtures().proxyCallTo_('load', arguments);
-};
-
-var setFixtures = function(html) {
- jasmine.getFixtures().set(html);
-};
-
-var sandbox = function(attributes) {
- return jasmine.getFixtures().sandbox(attributes);
-};
-
-var spyOnEvent = function(selector, eventName) {
- jasmine.JQuery.events.spyOn(selector, eventName);
-}
-
-jasmine.getFixtures = function() {
- return jasmine.currentFixtures_ = jasmine.currentFixtures_ || new jasmine.Fixtures();
-};
-
-jasmine.Fixtures = function() {
- this.containerId = 'jasmine-fixtures';
- this.fixturesCache_ = {};
- this.fixturesPath = 'spec/javascripts/fixtures';
-};
-
-jasmine.Fixtures.prototype.set = function(html) {
- this.cleanUp();
- this.createContainer_(html);
-};
-
-jasmine.Fixtures.prototype.load = function() {
- this.cleanUp();
- this.createContainer_(this.read.apply(this, arguments));
-};
-
-jasmine.Fixtures.prototype.read = function() {
- var htmlChunks = [];
-
- var fixtureUrls = arguments;
- for(var urlCount = fixtureUrls.length, urlIndex = 0; urlIndex < urlCount; urlIndex++) {
- htmlChunks.push(this.getFixtureHtml_(fixtureUrls[urlIndex]));
- }
-
- return htmlChunks.join('');
-};
-
-jasmine.Fixtures.prototype.clearCache = function() {
- this.fixturesCache_ = {};
-};
-
-jasmine.Fixtures.prototype.cleanUp = function() {
- $('#' + this.containerId).remove();
-};
-
-jasmine.Fixtures.prototype.sandbox = function(attributes) {
- var attributesToSet = attributes || {};
- return $('
')
+ .attr('id', this.containerId)
+ .html(html)
-jasmine.JQuery.matchersClass = {};
+ $(document.body).append(container)
+ return container
+ }
+
+ jasmine.Fixtures.prototype.addToContainer_ = function (html){
+ var container = $(document.body).find('#'+this.containerId).append(html)
+ if(!container.length){
+ this.createContainer_(html)
+ }
+ }
+
+ jasmine.Fixtures.prototype.getFixtureHtml_ = function (url) {
+ if (typeof this.fixturesCache_[url] === 'undefined') {
+ this.loadFixtureIntoCache_(url)
+ }
+ return this.fixturesCache_[url]
+ }
+
+ jasmine.Fixtures.prototype.loadFixtureIntoCache_ = function (relativeUrl) {
+ var self = this
+ , url = this.makeFixtureUrl_(relativeUrl)
+ , request = $.ajax({
+ async: false, // must be synchronous to guarantee that no tests are run before fixture is loaded
+ cache: false,
+ url: url,
+ success: function (data, status, $xhr) {
+ self.fixturesCache_[relativeUrl] = $xhr.responseText
+ },
+ error: function (jqXHR, status, errorThrown) {
+ throw new Error('Fixture could not be loaded: ' + url + ' (status: ' + status + ', message: ' + errorThrown.message + ')')
+ }
+ })
+ }
+
+ jasmine.Fixtures.prototype.makeFixtureUrl_ = function (relativeUrl){
+ return this.fixturesPath.match('/$') ? this.fixturesPath + relativeUrl : this.fixturesPath + '/' + relativeUrl
+ }
+
+ jasmine.Fixtures.prototype.proxyCallTo_ = function (methodName, passedArguments) {
+ return this[methodName].apply(this, passedArguments)
+ }
+
+
+ jasmine.StyleFixtures = function () {
+ this.fixturesCache_ = {}
+ this.fixturesNodes_ = []
+ this.fixturesPath = 'spec/javascripts/fixtures'
+ }
+
+ jasmine.StyleFixtures.prototype.set = function (css) {
+ this.cleanUp()
+ this.createStyle_(css)
+ }
+
+ jasmine.StyleFixtures.prototype.appendSet = function (css) {
+ this.createStyle_(css)
+ }
+
+ jasmine.StyleFixtures.prototype.preload = function () {
+ this.read_.apply(this, arguments)
+ }
+
+ jasmine.StyleFixtures.prototype.load = function () {
+ this.cleanUp()
+ this.createStyle_(this.read_.apply(this, arguments))
+ }
+
+ jasmine.StyleFixtures.prototype.appendLoad = function () {
+ this.createStyle_(this.read_.apply(this, arguments))
+ }
+
+ jasmine.StyleFixtures.prototype.cleanUp = function () {
+ while(this.fixturesNodes_.length) {
+ this.fixturesNodes_.pop().remove()
+ }
+ }
+
+ jasmine.StyleFixtures.prototype.createStyle_ = function (html) {
+ var styleText = $('
').html(html).text()
+ , style = $('')
+
+ this.fixturesNodes_.push(style)
+ $('head').append(style)
+ }
+
+ jasmine.StyleFixtures.prototype.clearCache = jasmine.Fixtures.prototype.clearCache
+ jasmine.StyleFixtures.prototype.read_ = jasmine.Fixtures.prototype.read
+ jasmine.StyleFixtures.prototype.getFixtureHtml_ = jasmine.Fixtures.prototype.getFixtureHtml_
+ jasmine.StyleFixtures.prototype.loadFixtureIntoCache_ = jasmine.Fixtures.prototype.loadFixtureIntoCache_
+ jasmine.StyleFixtures.prototype.makeFixtureUrl_ = jasmine.Fixtures.prototype.makeFixtureUrl_
+ jasmine.StyleFixtures.prototype.proxyCallTo_ = jasmine.Fixtures.prototype.proxyCallTo_
+
+ jasmine.getJSONFixtures = function () {
+ return jasmine.currentJSONFixtures_ = jasmine.currentJSONFixtures_ || new jasmine.JSONFixtures()
+ }
+
+ jasmine.JSONFixtures = function () {
+ this.fixturesCache_ = {}
+ this.fixturesPath = 'spec/javascripts/fixtures/json'
+ }
+
+ jasmine.JSONFixtures.prototype.load = function () {
+ this.read.apply(this, arguments)
+ return this.fixturesCache_
+ }
+
+ jasmine.JSONFixtures.prototype.read = function () {
+ var fixtureUrls = arguments
+
+ for(var urlCount = fixtureUrls.length, urlIndex = 0; urlIndex < urlCount; urlIndex++) {
+ this.getFixtureData_(fixtureUrls[urlIndex])
+ }
+
+ return this.fixturesCache_
+ }
+
+ jasmine.JSONFixtures.prototype.clearCache = function () {
+ this.fixturesCache_ = {}
+ }
+
+ jasmine.JSONFixtures.prototype.getFixtureData_ = function (url) {
+ if (!this.fixturesCache_[url]) this.loadFixtureIntoCache_(url)
+ return this.fixturesCache_[url]
+ }
+
+ jasmine.JSONFixtures.prototype.loadFixtureIntoCache_ = function (relativeUrl) {
+ var self = this
+ , url = this.fixturesPath.match('/$') ? this.fixturesPath + relativeUrl : this.fixturesPath + '/' + relativeUrl
+
+ $.ajax({
+ async: false, // must be synchronous to guarantee that no tests are run before fixture is loaded
+ cache: false,
+ dataType: 'json',
+ url: url,
+ success: function (data) {
+ self.fixturesCache_[relativeUrl] = data
+ },
+ error: function (jqXHR, status, errorThrown) {
+ throw new Error('JSONFixture could not be loaded: ' + url + ' (status: ' + status + ', message: ' + errorThrown.message + ')')
+ }
+ })
+ }
+
+ jasmine.JSONFixtures.prototype.proxyCallTo_ = function (methodName, passedArguments) {
+ return this[methodName].apply(this, passedArguments)
+ }
+
+ jasmine.jQuery = function () {}
+
+ jasmine.jQuery.browserTagCaseIndependentHtml = function (html) {
+ return $('
').append(html).html()
+ }
+
+ jasmine.jQuery.elementToString = function (element) {
+ return $(element).map(function () { return this.outerHTML; }).toArray().join(', ')
+ }
+
+ jasmine.jQuery.matchersClass = {}
-(function(namespace) {
var data = {
- spiedEvents: {},
- handlers: []
- };
+ spiedEvents: {}
+ , handlers: []
+ }
+
+ jasmine.jQuery.events = {
+ spyOn: function (selector, eventName) {
+ var handler = function (e) {
+ data.spiedEvents[jasmine.spiedEventsKey(selector, eventName)] = jasmine.util.argsToArray(arguments)
+ }
+
+ $(selector).on(eventName, handler)
+ data.handlers.push(handler)
+
+ return {
+ selector: selector,
+ eventName: eventName,
+ handler: handler,
+ reset: function (){
+ delete data.spiedEvents[jasmine.spiedEventsKey(selector, eventName)]
+ }
+ }
+ },
+
+ args: function (selector, eventName) {
+ var actualArgs = data.spiedEvents[jasmine.spiedEventsKey(selector, eventName)]
+
+ if (!actualArgs) {
+ throw "There is no spy for " + eventName + " on " + selector.toString() + ". Make sure to create a spy using spyOnEvent."
+ }
+
+ return actualArgs
+ },
- namespace.events = {
- spyOn: function(selector, eventName) {
- var handler = function(e) {
- data.spiedEvents[[selector, eventName]] = e;
- };
- $(selector).bind(eventName, handler);
- data.handlers.push(handler);
+ wasTriggered: function (selector, eventName) {
+ return !!(data.spiedEvents[jasmine.spiedEventsKey(selector, eventName)])
},
- wasTriggered: function(selector, eventName) {
- return !!(data.spiedEvents[[selector, eventName]]);
+ wasTriggeredWith: function (selector, eventName, expectedArgs, env) {
+ var actualArgs = jasmine.jQuery.events.args(selector, eventName).slice(1)
+ if (Object.prototype.toString.call(expectedArgs) !== '[object Array]') {
+ actualArgs = actualArgs[0]
+ }
+ return env.equals_(expectedArgs, actualArgs)
+ },
+
+ wasPrevented: function (selector, eventName) {
+ var args = data.spiedEvents[jasmine.spiedEventsKey(selector, eventName)]
+ , e = args ? args[0] : undefined
+
+ return e && e.isDefaultPrevented()
},
- cleanUp: function() {
- data.spiedEvents = {};
- data.handlers = [];
+ wasStopped: function (selector, eventName) {
+ var args = data.spiedEvents[jasmine.spiedEventsKey(selector, eventName)]
+ , e = args ? args[0] : undefined
+ return e && e.isPropagationStopped()
+ },
+
+ cleanUp: function () {
+ data.spiedEvents = {}
+ data.handlers = []
}
}
-})(jasmine.JQuery);
-(function(){
var jQueryMatchers = {
- toHaveClass: function(className) {
- return this.actual.hasClass(className);
+ toHaveClass: function (className) {
+ return this.actual.hasClass(className)
+ },
+
+ toHaveCss: function (css){
+ for (var prop in css){
+ var value = css[prop]
+ // see issue #147 on gh
+ ;if (value === 'auto' && this.actual.get(0).style[prop] === 'auto') continue
+ if (this.actual.css(prop) !== value) return false
+ }
+ return true
},
- toBeVisible: function() {
- return this.actual.is(':visible');
+ toBeVisible: function () {
+ return this.actual.is(':visible')
},
- toBeHidden: function() {
- return this.actual.is(':hidden');
+ toBeHidden: function () {
+ return this.actual.is(':hidden')
},
- toBeSelected: function() {
- return this.actual.is(':selected');
+ toBeSelected: function () {
+ return this.actual.is(':selected')
},
- toBeChecked: function() {
- return this.actual.is(':checked');
+ toBeChecked: function () {
+ return this.actual.is(':checked')
},
- toBeEmpty: function() {
- return this.actual.is(':empty');
+ toBeEmpty: function () {
+ return this.actual.is(':empty')
},
- toExist: function() {
- return this.actual.size() > 0;
+ toBeInDOM: function () {
+ return $.contains(document.documentElement, this.actual[0])
},
- toHaveAttr: function(attributeName, expectedAttributeValue) {
- return hasProperty(this.actual.attr(attributeName), expectedAttributeValue);
+ toExist: function () {
+ return this.actual.length
},
- toHaveId: function(id) {
- return this.actual.attr('id') == id;
+ toHaveLength: function (length) {
+ return this.actual.length === length
},
- toHaveHtml: function(html) {
- return this.actual.html() == jasmine.JQuery.browserTagCaseIndependentHtml(html);
+ toHaveAttr: function (attributeName, expectedAttributeValue) {
+ return hasProperty(this.actual.attr(attributeName), expectedAttributeValue)
+ },
+
+ toHaveProp: function (propertyName, expectedPropertyValue) {
+ return hasProperty(this.actual.prop(propertyName), expectedPropertyValue)
+ },
+
+ toHaveId: function (id) {
+ return this.actual.attr('id') == id
+ },
+
+ toHaveHtml: function (html) {
+ return this.actual.html() == jasmine.jQuery.browserTagCaseIndependentHtml(html)
+ },
+
+ toContainHtml: function (html){
+ var actualHtml = this.actual.html()
+ , expectedHtml = jasmine.jQuery.browserTagCaseIndependentHtml(html)
+
+ return (actualHtml.indexOf(expectedHtml) >= 0)
+ },
+
+ toHaveText: function (text) {
+ var trimmedText = $.trim(this.actual.text())
+
+ if (text && $.isFunction(text.test)) {
+ return text.test(trimmedText)
+ } else {
+ return trimmedText == text
+ }
},
- toHaveText: function(text) {
- if (text && jQuery.isFunction(text.test)) {
- return text.test(this.actual.text());
+ toContainText: function (text) {
+ var trimmedText = $.trim(this.actual.text())
+
+ if (text && $.isFunction(text.test)) {
+ return text.test(trimmedText)
} else {
- return this.actual.text() == text;
+ return trimmedText.indexOf(text) != -1
}
},
- toHaveValue: function(value) {
- return this.actual.val() == value;
+ toHaveValue: function (value) {
+ return this.actual.val() === value
},
- toHaveData: function(key, expectedValue) {
- return hasProperty(this.actual.data(key), expectedValue);
+ toHaveData: function (key, expectedValue) {
+ return hasProperty(this.actual.data(key), expectedValue)
},
- toBe: function(selector) {
- return this.actual.is(selector);
+ toBe: function (selector) {
+ return this.actual.is(selector)
},
- toContain: function(selector) {
- return this.actual.find(selector).size() > 0;
+ toContain: function (selector) {
+ return this.actual.find(selector).length
},
- toBeDisabled: function(selector){
- return this.actual.attr("disabled") == true;
- }
- };
+ toBeMatchedBy: function (selector) {
+ return this.actual.filter(selector).length
+ },
- var hasProperty = function(actualValue, expectedValue) {
- if (expectedValue === undefined) {
- return actualValue !== undefined;
- }
- return actualValue == expectedValue;
- };
+ toBeDisabled: function (selector){
+ return this.actual.is(':disabled')
+ },
+
+ toBeFocused: function (selector) {
+ return this.actual[0] === this.actual[0].ownerDocument.activeElement
+ },
- var bindMatcher = function(methodName) {
- var builtInMatcher = jasmine.Matchers.prototype[methodName];
+ toHandle: function (event) {
+ var events = $._data(this.actual.get(0), "events")
- jasmine.JQuery.matchersClass[methodName] = function() {
- if (this.actual instanceof jQuery) {
- var result = jQueryMatchers[methodName].apply(this, arguments);
- this.actual = jasmine.JQuery.elementToString(this.actual);
- return result;
+ if(!events || !event || typeof event !== "string") {
+ return false
}
- if (builtInMatcher) {
- return builtInMatcher.apply(this, arguments);
+ var namespaces = event.split(".")
+ , eventType = namespaces.shift()
+ , sortedNamespaces = namespaces.slice(0).sort()
+ , namespaceRegExp = new RegExp("(^|\\.)" + sortedNamespaces.join("\\.(?:.*\\.)?") + "(\\.|$)")
+
+ if(events[eventType] && namespaces.length) {
+ for(var i = 0; i < events[eventType].length; i++) {
+ var namespace = events[eventType][i].namespace
+
+ if(namespaceRegExp.test(namespace)) {
+ return true
+ }
+ }
+ } else {
+ return events[eventType] && events[eventType].length > 0
}
+ },
- return false;
- };
- };
+ toHandleWith: function (eventName, eventHandler) {
+ var normalizedEventName = eventName.split('.')[0]
+ , stack = $._data(this.actual.get(0), "events")[normalizedEventName]
- for(var methodName in jQueryMatchers) {
- bindMatcher(methodName);
- }
-})();
-
-beforeEach(function() {
- this.addMatchers(jasmine.JQuery.matchersClass);
- this.addMatchers({
- toHaveBeenTriggeredOn: function(selector) {
- this.message = function() {
- return [
- "Expected event " + this.actual + " to have been triggered on" + selector,
- "Expected event " + this.actual + " not to have been triggered on" + selector
- ];
- };
- return jasmine.JQuery.events.wasTriggered(selector, this.actual);
+ for (var i = 0; i < stack.length; i++) {
+ if (stack[i].handler == eventHandler) return true
+ }
+
+ return false
+ }
+ }
+
+ var hasProperty = function (actualValue, expectedValue) {
+ if (expectedValue === undefined) return actualValue !== undefined
+
+ return actualValue === expectedValue
+ }
+
+ var bindMatcher = function (methodName) {
+ var builtInMatcher = jasmine.Matchers.prototype[methodName]
+
+ jasmine.jQuery.matchersClass[methodName] = function () {
+ if (this.actual
+ && (this.actual instanceof $
+ || jasmine.isDomNode(this.actual))) {
+ this.actual = $(this.actual)
+ var result = jQueryMatchers[methodName].apply(this, arguments)
+ , element
+
+ if (this.actual.get && (element = this.actual.get()[0]) && !$.isWindow(element) && element.tagName !== "HTML")
+ this.actual = jasmine.jQuery.elementToString(this.actual)
+
+ return result
+ }
+
+ if (builtInMatcher) {
+ return builtInMatcher.apply(this, arguments)
+ }
+
+ return false
}
+ }
+
+ for(var methodName in jQueryMatchers) {
+ bindMatcher(methodName)
+ }
+
+ beforeEach(function () {
+ this.addMatchers(jasmine.jQuery.matchersClass)
+ this.addMatchers({
+ toHaveBeenTriggeredOn: function (selector) {
+ this.message = function () {
+ return [
+ "Expected event " + this.actual + " to have been triggered on " + selector,
+ "Expected event " + this.actual + " not to have been triggered on " + selector
+ ]
+ }
+ return jasmine.jQuery.events.wasTriggered(selector, this.actual)
+ }
+ })
+
+ this.addMatchers({
+ toHaveBeenTriggered: function (){
+ var eventName = this.actual.eventName
+ , selector = this.actual.selector
+
+ this.message = function () {
+ return [
+ "Expected event " + eventName + " to have been triggered on " + selector,
+ "Expected event " + eventName + " not to have been triggered on " + selector
+ ]
+ }
+
+ return jasmine.jQuery.events.wasTriggered(selector, eventName)
+ }
+ })
+
+ this.addMatchers({
+ toHaveBeenTriggeredOnAndWith: function () {
+ var selector = arguments[0]
+ , expectedArgs = arguments[1]
+ , wasTriggered = jasmine.jQuery.events.wasTriggered(selector, this.actual)
+
+ this.message = function () {
+ if (wasTriggered) {
+ var actualArgs = jasmine.jQuery.events.args(selector, this.actual, expectedArgs)[1]
+ return [
+ "Expected event " + this.actual + " to have been triggered with " + jasmine.pp(expectedArgs) + " but it was triggered with " + jasmine.pp(actualArgs),
+ "Expected event " + this.actual + " not to have been triggered with " + jasmine.pp(expectedArgs) + " but it was triggered with " + jasmine.pp(actualArgs)
+ ]
+ } else {
+ return [
+ "Expected event " + this.actual + " to have been triggered on " + selector,
+ "Expected event " + this.actual + " not to have been triggered on " + selector
+ ]
+ }
+ }
+
+ return wasTriggered && jasmine.jQuery.events.wasTriggeredWith(selector, this.actual, expectedArgs, this.env)
+ }
+ })
+
+ this.addMatchers({
+ toHaveBeenPreventedOn: function (selector) {
+ this.message = function () {
+ return [
+ "Expected event " + this.actual + " to have been prevented on " + selector,
+ "Expected event " + this.actual + " not to have been prevented on " + selector
+ ]
+ }
+
+ return jasmine.jQuery.events.wasPrevented(selector, this.actual)
+ }
+ })
+
+ this.addMatchers({
+ toHaveBeenPrevented: function () {
+ var eventName = this.actual.eventName
+ , selector = this.actual.selector
+ this.message = function () {
+ return [
+ "Expected event " + eventName + " to have been prevented on " + selector,
+ "Expected event " + eventName + " not to have been prevented on " + selector
+ ]
+ }
+
+ return jasmine.jQuery.events.wasPrevented(selector, eventName)
+ }
+ })
+
+ this.addMatchers({
+ toHaveBeenStoppedOn: function (selector) {
+ this.message = function () {
+ return [
+ "Expected event " + this.actual + " to have been stopped on " + selector,
+ "Expected event " + this.actual + " not to have been stopped on " + selector
+ ]
+ }
+
+ return jasmine.jQuery.events.wasStopped(selector, this.actual)
+ }
+ })
+
+ this.addMatchers({
+ toHaveBeenStopped: function () {
+ var eventName = this.actual.eventName
+ , selector = this.actual.selector
+ this.message = function () {
+ return [
+ "Expected event " + eventName + " to have been stopped on " + selector,
+ "Expected event " + eventName + " not to have been stopped on " + selector
+ ]
+ }
+ return jasmine.jQuery.events.wasStopped(selector, eventName)
+ }
+ })
+
+ jasmine.getEnv().addEqualityTester(function (a, b) {
+ if(a instanceof $ && b instanceof $) {
+ if(a.size() != b.size()) {
+ return jasmine.undefined
+ }
+ else if(a.is(b)) {
+ return true
+ }
+ }
+
+ return jasmine.undefined
+ })
+ })
+
+ afterEach(function () {
+ jasmine.getFixtures().cleanUp()
+ jasmine.getStyleFixtures().cleanUp()
+ jasmine.jQuery.events.cleanUp()
})
-});
-afterEach(function() {
- jasmine.getFixtures().cleanUp();
- jasmine.JQuery.events.cleanUp();
-});
+ window.readFixtures = function () {
+ return jasmine.getFixtures().proxyCallTo_('read', arguments)
+ }
+
+ window.preloadFixtures = function () {
+ jasmine.getFixtures().proxyCallTo_('preload', arguments)
+ }
+
+ window.loadFixtures = function () {
+ jasmine.getFixtures().proxyCallTo_('load', arguments)
+ }
+
+ window.appendLoadFixtures = function () {
+ jasmine.getFixtures().proxyCallTo_('appendLoad', arguments)
+ }
+
+ window.setFixtures = function (html) {
+ return jasmine.getFixtures().proxyCallTo_('set', arguments)
+ }
+
+ window.appendSetFixtures = function () {
+ jasmine.getFixtures().proxyCallTo_('appendSet', arguments)
+ }
+
+ window.sandbox = function (attributes) {
+ return jasmine.getFixtures().sandbox(attributes)
+ }
+
+ window.spyOnEvent = function (selector, eventName) {
+ return jasmine.jQuery.events.spyOn(selector, eventName)
+ }
+
+ window.preloadStyleFixtures = function () {
+ jasmine.getStyleFixtures().proxyCallTo_('preload', arguments)
+ }
+
+ window.loadStyleFixtures = function () {
+ jasmine.getStyleFixtures().proxyCallTo_('load', arguments)
+ }
+
+ window.appendLoadStyleFixtures = function () {
+ jasmine.getStyleFixtures().proxyCallTo_('appendLoad', arguments)
+ }
+
+ window.setStyleFixtures = function (html) {
+ jasmine.getStyleFixtures().proxyCallTo_('set', arguments)
+ }
+
+ window.appendSetStyleFixtures = function (html) {
+ jasmine.getStyleFixtures().proxyCallTo_('appendSet', arguments)
+ }
+
+ window.loadJSONFixtures = function () {
+ return jasmine.getJSONFixtures().proxyCallTo_('load', arguments)
+ }
+
+ window.getJSONFixture = function (url) {
+ return jasmine.getJSONFixtures().proxyCallTo_('read', arguments)[url]
+ }
+}(window.jasmine, window.jQuery);
+
diff --git a/test/lib/jasmine.css b/test/lib/jasmine.css
index 6583fe7c..8c008dc7 100644
--- a/test/lib/jasmine.css
+++ b/test/lib/jasmine.css
@@ -1,166 +1,82 @@
-body {
- font-family: "Helvetica Neue Light", "Lucida Grande", "Calibri", "Arial", sans-serif;
-}
-
-
-.jasmine_reporter a:visited, .jasmine_reporter a {
- color: #303;
-}
-
-.jasmine_reporter a:hover, .jasmine_reporter a:active {
- color: blue;
-}
-
-.run_spec {
- float:right;
- padding-right: 5px;
- font-size: .8em;
- text-decoration: none;
-}
-
-.jasmine_reporter {
- margin: 0 5px;
-}
-
-.banner {
- color: #303;
- background-color: #fef;
- padding: 5px;
-}
-
-.logo {
- float: left;
- font-size: 1.1em;
- padding-left: 5px;
-}
-
-.logo .version {
- font-size: .6em;
- padding-left: 1em;
-}
-
-.runner.running {
- background-color: yellow;
-}
-
-
-.options {
- text-align: right;
- font-size: .8em;
-}
-
-
-
-
-.suite {
- border: 1px outset gray;
- margin: 5px 0;
- padding-left: 1em;
-}
-
-.suite .suite {
- margin: 5px;
-}
-
-.suite.passed {
- background-color: #dfd;
-}
-
-.suite.failed {
- background-color: #fdd;
-}
-
-.spec {
- margin: 5px;
- padding-left: 1em;
- clear: both;
-}
-
-.spec.failed, .spec.passed, .spec.skipped {
- padding-bottom: 5px;
- border: 1px solid gray;
-}
-
-.spec.failed {
- background-color: #fbb;
- border-color: red;
-}
-
-.spec.passed {
- background-color: #bfb;
- border-color: green;
-}
-
-.spec.skipped {
- background-color: #bbb;
-}
-
-.messages {
- border-left: 1px dashed gray;
- padding-left: 1em;
- padding-right: 1em;
-}
-
-.passed {
- background-color: #cfc;
- display: none;
-}
-
-.failed {
- background-color: #fbb;
-}
-
-.skipped {
- color: #777;
- background-color: #eee;
- display: none;
-}
-
-
-/*.resultMessage {*/
- /*white-space: pre;*/
-/*}*/
-
-.resultMessage span.result {
- display: block;
- line-height: 2em;
- color: black;
-}
-
-.resultMessage .mismatch {
- color: black;
-}
-
-.stackTrace {
- white-space: pre;
- font-size: .8em;
- margin-left: 10px;
- max-height: 5em;
- overflow: auto;
- border: 1px inset red;
- padding: 1em;
- background: #eef;
-}
-
-.finished-at {
- padding-left: 1em;
- font-size: .6em;
-}
-
-.show-passed .passed,
-.show-skipped .skipped {
- display: block;
-}
-
-
-#jasmine_content {
- position:fixed;
- right: 100%;
-}
-
-.runner {
- border: 1px solid gray;
- display: block;
- margin: 5px 0;
- padding: 2px 0 2px 10px;
-}
+body { background-color: #eeeeee; padding: 0; margin: 5px; overflow-y: scroll; }
+
+#HTMLReporter { font-size: 11px; font-family: Monaco, "Lucida Console", monospace; line-height: 14px; color: #333333; }
+#HTMLReporter a { text-decoration: none; }
+#HTMLReporter a:hover { text-decoration: underline; }
+#HTMLReporter p, #HTMLReporter h1, #HTMLReporter h2, #HTMLReporter h3, #HTMLReporter h4, #HTMLReporter h5, #HTMLReporter h6 { margin: 0; line-height: 14px; }
+#HTMLReporter .banner, #HTMLReporter .symbolSummary, #HTMLReporter .summary, #HTMLReporter .resultMessage, #HTMLReporter .specDetail .description, #HTMLReporter .alert .bar, #HTMLReporter .stackTrace { padding-left: 9px; padding-right: 9px; }
+#HTMLReporter #jasmine_content { position: fixed; right: 100%; }
+#HTMLReporter .version { color: #aaaaaa; }
+#HTMLReporter .banner { margin-top: 14px; }
+#HTMLReporter .duration { color: #aaaaaa; float: right; }
+#HTMLReporter .symbolSummary { overflow: hidden; *zoom: 1; margin: 14px 0; }
+#HTMLReporter .symbolSummary li { display: block; float: left; height: 7px; width: 14px; margin-bottom: 7px; font-size: 16px; }
+#HTMLReporter .symbolSummary li.passed { font-size: 14px; }
+#HTMLReporter .symbolSummary li.passed:before { color: #5e7d00; content: "\02022"; }
+#HTMLReporter .symbolSummary li.failed { line-height: 9px; }
+#HTMLReporter .symbolSummary li.failed:before { color: #b03911; content: "x"; font-weight: bold; margin-left: -1px; }
+#HTMLReporter .symbolSummary li.skipped { font-size: 14px; }
+#HTMLReporter .symbolSummary li.skipped:before { color: #bababa; content: "\02022"; }
+#HTMLReporter .symbolSummary li.pending { line-height: 11px; }
+#HTMLReporter .symbolSummary li.pending:before { color: #aaaaaa; content: "-"; }
+#HTMLReporter .exceptions { color: #fff; float: right; margin-top: 5px; margin-right: 5px; }
+#HTMLReporter .bar { line-height: 28px; font-size: 14px; display: block; color: #eee; }
+#HTMLReporter .runningAlert { background-color: #666666; }
+#HTMLReporter .skippedAlert { background-color: #aaaaaa; }
+#HTMLReporter .skippedAlert:first-child { background-color: #333333; }
+#HTMLReporter .skippedAlert:hover { text-decoration: none; color: white; text-decoration: underline; }
+#HTMLReporter .passingAlert { background-color: #a6b779; }
+#HTMLReporter .passingAlert:first-child { background-color: #5e7d00; }
+#HTMLReporter .failingAlert { background-color: #cf867e; }
+#HTMLReporter .failingAlert:first-child { background-color: #b03911; }
+#HTMLReporter .results { margin-top: 14px; }
+#HTMLReporter #details { display: none; }
+#HTMLReporter .resultsMenu, #HTMLReporter .resultsMenu a { background-color: #fff; color: #333333; }
+#HTMLReporter.showDetails .summaryMenuItem { font-weight: normal; text-decoration: inherit; }
+#HTMLReporter.showDetails .summaryMenuItem:hover { text-decoration: underline; }
+#HTMLReporter.showDetails .detailsMenuItem { font-weight: bold; text-decoration: underline; }
+#HTMLReporter.showDetails .summary { display: none; }
+#HTMLReporter.showDetails #details { display: block; }
+#HTMLReporter .summaryMenuItem { font-weight: bold; text-decoration: underline; }
+#HTMLReporter .summary { margin-top: 14px; }
+#HTMLReporter .summary .suite .suite, #HTMLReporter .summary .specSummary { margin-left: 14px; }
+#HTMLReporter .summary .specSummary.passed a { color: #5e7d00; }
+#HTMLReporter .summary .specSummary.failed a { color: #b03911; }
+#HTMLReporter .description + .suite { margin-top: 0; }
+#HTMLReporter .suite { margin-top: 14px; }
+#HTMLReporter .suite a { color: #333333; }
+#HTMLReporter #details .specDetail { margin-bottom: 28px; }
+#HTMLReporter #details .specDetail .description { display: block; color: white; background-color: #b03911; }
+#HTMLReporter .resultMessage { padding-top: 14px; color: #333333; }
+#HTMLReporter .resultMessage span.result { display: block; }
+#HTMLReporter .stackTrace { margin: 5px 0 0 0; max-height: 224px; overflow: auto; line-height: 18px; color: #666666; border: 1px solid #ddd; background: white; white-space: pre; }
+
+#TrivialReporter { padding: 8px 13px; position: absolute; top: 0; bottom: 0; left: 0; right: 0; overflow-y: scroll; background-color: white; font-family: "Helvetica Neue Light", "Lucida Grande", "Calibri", "Arial", sans-serif; /*.resultMessage {*/ /*white-space: pre;*/ /*}*/ }
+#TrivialReporter a:visited, #TrivialReporter a { color: #303; }
+#TrivialReporter a:hover, #TrivialReporter a:active { color: blue; }
+#TrivialReporter .run_spec { float: right; padding-right: 5px; font-size: .8em; text-decoration: none; }
+#TrivialReporter .banner { color: #303; background-color: #fef; padding: 5px; }
+#TrivialReporter .logo { float: left; font-size: 1.1em; padding-left: 5px; }
+#TrivialReporter .logo .version { font-size: .6em; padding-left: 1em; }
+#TrivialReporter .runner.running { background-color: yellow; }
+#TrivialReporter .options { text-align: right; font-size: .8em; }
+#TrivialReporter .suite { border: 1px outset gray; margin: 5px 0; padding-left: 1em; }
+#TrivialReporter .suite .suite { margin: 5px; }
+#TrivialReporter .suite.passed { background-color: #dfd; }
+#TrivialReporter .suite.failed { background-color: #fdd; }
+#TrivialReporter .spec { margin: 5px; padding-left: 1em; clear: both; }
+#TrivialReporter .spec.failed, #TrivialReporter .spec.passed, #TrivialReporter .spec.skipped { padding-bottom: 5px; border: 1px solid gray; }
+#TrivialReporter .spec.failed { background-color: #fbb; border-color: red; }
+#TrivialReporter .spec.passed { background-color: #bfb; border-color: green; }
+#TrivialReporter .spec.skipped { background-color: #bbb; }
+#TrivialReporter .messages { border-left: 1px dashed gray; padding-left: 1em; padding-right: 1em; }
+#TrivialReporter .passed { background-color: #cfc; display: none; }
+#TrivialReporter .failed { background-color: #fbb; }
+#TrivialReporter .skipped { color: #777; background-color: #eee; display: none; }
+#TrivialReporter .resultMessage span.result { display: block; line-height: 2em; color: black; }
+#TrivialReporter .resultMessage .mismatch { color: black; }
+#TrivialReporter .stackTrace { white-space: pre; font-size: .8em; margin-left: 10px; max-height: 5em; overflow: auto; border: 1px inset red; padding: 1em; background: #eef; }
+#TrivialReporter .finished-at { padding-left: 1em; font-size: .6em; }
+#TrivialReporter.show-passed .passed, #TrivialReporter.show-skipped .skipped { display: block; }
+#TrivialReporter #jasmine_content { position: fixed; right: 100%; }
+#TrivialReporter .runner { border: 1px solid gray; display: block; margin: 5px 0; padding: 2px 0 2px 10px; }
diff --git a/test/lib/jasmine.js b/test/lib/jasmine.js
index 63e415d8..6b3459b9 100644
--- a/test/lib/jasmine.js
+++ b/test/lib/jasmine.js
@@ -1,10 +1,12 @@
+var isCommonJS = typeof window == "undefined" && typeof exports == "object";
+
/**
* Top level namespace for Jasmine, a lightweight JavaScript BDD/spec/testing framework.
*
* @namespace
*/
var jasmine = {};
-
+if (isCommonJS) exports.jasmine = jasmine;
/**
* @private
*/
@@ -20,17 +22,35 @@ jasmine.unimplementedMethod_ = function() {
*/
jasmine.undefined = jasmine.___undefined___;
+/**
+ * Show diagnostic messages in the console if set to true
+ *
+ */
+jasmine.VERBOSE = false;
+
/**
* Default interval in milliseconds for event loop yields (e.g. to allow network activity or to refresh the screen with the HTML-based runner). Small values here may result in slow test running. Zero means no updates until all tests have completed.
*
*/
jasmine.DEFAULT_UPDATE_INTERVAL = 250;
+/**
+ * Maximum levels of nesting that will be included when an object is pretty-printed
+ */
+jasmine.MAX_PRETTY_PRINT_DEPTH = 40;
+
/**
* Default timeout interval in milliseconds for waitsFor() blocks.
*/
jasmine.DEFAULT_TIMEOUT_INTERVAL = 5000;
+/**
+ * By default exceptions thrown in the context of a test are caught by jasmine so that it can run the remaining tests in the suite.
+ * Set to false to let the exception bubble up in the browser.
+ *
+ */
+jasmine.CATCH_EXCEPTIONS = true;
+
jasmine.getGlobal = function() {
function getGlobal() {
return this;
@@ -72,7 +92,7 @@ jasmine.MessageResult = function(values) {
jasmine.MessageResult.prototype.toString = function() {
var text = "";
- for(var i = 0; i < this.values.length; i++) {
+ for (var i = 0; i < this.values.length; i++) {
if (i > 0) text += " ";
if (jasmine.isString_(this.values[i])) {
text += this.values[i];
@@ -89,9 +109,10 @@ jasmine.ExpectationResult = function(params) {
this.passed_ = params.passed;
this.expected = params.expected;
this.actual = params.actual;
-
this.message = this.passed_ ? 'Passed.' : params.message;
- this.trace = this.passed_ ? '' : new Error(this.message);
+
+ var trace = (params.trace || new Error(this.message));
+ this.trace = this.passed_ ? '' : trace;
};
jasmine.ExpectationResult.prototype.toString = function () {
@@ -106,7 +127,8 @@ jasmine.ExpectationResult.prototype.passed = function () {
* Getter for the Jasmine environment. Ensures one gets created
*/
jasmine.getEnv = function() {
- return jasmine.currentEnv_ = jasmine.currentEnv_ || new jasmine.Env();
+ var env = jasmine.currentEnv_ = jasmine.currentEnv_ || new jasmine.Env();
+ return env;
};
/**
@@ -116,7 +138,7 @@ jasmine.getEnv = function() {
* @returns {Boolean}
*/
jasmine.isArray_ = function(value) {
- return jasmine.isA_("Array", value);
+ return jasmine.isA_("Array", value);
};
/**
@@ -169,7 +191,7 @@ jasmine.pp = function(value) {
* @returns {Boolean}
*/
jasmine.isDomNode = function(obj) {
- return obj['nodeType'] > 0;
+ return obj.nodeType > 0;
};
/**
@@ -186,6 +208,21 @@ jasmine.any = function(clazz) {
return new jasmine.Matchers.Any(clazz);
};
+/**
+ * Returns a matchable subset of a JSON object. For use in expectations when you don't care about all of the
+ * attributes on the object.
+ *
+ * @example
+ * // don't care about any other attributes than foo.
+ * expect(mySpy).toHaveBeenCalledWith(jasmine.objectContaining({foo: "bar"});
+ *
+ * @param sample {Object} sample
+ * @returns matchable object for the sample
+ */
+jasmine.objectContaining = function (sample) {
+ return new jasmine.Matchers.ObjectContaining(sample);
+};
+
/**
* Jasmine Spies are test doubles that can act as stubs, spies, fakes or when used in an expecation, mocks.
*
@@ -405,7 +442,7 @@ jasmine.isSpy = function(putativeSpy) {
* @param {Array} methodNames array of names of methods to make spies
*/
jasmine.createSpyObj = function(baseName, methodNames) {
- if (!jasmine.isArray_(methodNames) || methodNames.length == 0) {
+ if (!jasmine.isArray_(methodNames) || methodNames.length === 0) {
throw new Error('createSpyObj requires a non-empty array of method names to create spies for');
}
var obj = {};
@@ -438,11 +475,12 @@ jasmine.log = function() {
* @see jasmine.createSpy
* @param obj
* @param methodName
- * @returns a Jasmine spy that can be chained with all spy methods
+ * @return {jasmine.Spy} a Jasmine spy that can be chained with all spy methods
*/
var spyOn = function(obj, methodName) {
return jasmine.getEnv().currentSpec.spyOn(obj, methodName);
};
+if (isCommonJS) exports.spyOn = spyOn;
/**
* Creates a Jasmine spec that will be added to the current suite.
@@ -460,6 +498,7 @@ var spyOn = function(obj, methodName) {
var it = function(desc, func) {
return jasmine.getEnv().it(desc, func);
};
+if (isCommonJS) exports.it = it;
/**
* Creates a
disabled Jasmine spec.
@@ -472,6 +511,7 @@ var it = function(desc, func) {
var xit = function(desc, func) {
return jasmine.getEnv().xit(desc, func);
};
+if (isCommonJS) exports.xit = xit;
/**
* Starts a chain for a Jasmine expectation.
@@ -480,10 +520,12 @@ var xit = function(desc, func) {
* jasmine.Matchers functions.
*
* @param {Object} actual Actual value to test against and expected value
+ * @return {jasmine.Matchers}
*/
var expect = function(actual) {
return jasmine.getEnv().currentSpec.expect(actual);
};
+if (isCommonJS) exports.expect = expect;
/**
* Defines part of a jasmine spec. Used in cominbination with waits or waitsFor in asynchrnous specs.
@@ -493,6 +535,7 @@ var expect = function(actual) {
var runs = function(func) {
jasmine.getEnv().currentSpec.runs(func);
};
+if (isCommonJS) exports.runs = runs;
/**
* Waits a fixed time period before moving to the next block.
@@ -503,6 +546,7 @@ var runs = function(func) {
var waits = function(timeout) {
jasmine.getEnv().currentSpec.waits(timeout);
};
+if (isCommonJS) exports.waits = waits;
/**
* Waits for the latchFunction to return true before proceeding to the next block.
@@ -514,6 +558,7 @@ var waits = function(timeout) {
var waitsFor = function(latchFunction, optional_timeoutMessage, optional_timeout) {
jasmine.getEnv().currentSpec.waitsFor.apply(jasmine.getEnv().currentSpec, arguments);
};
+if (isCommonJS) exports.waitsFor = waitsFor;
/**
* A function that is called before each spec in a suite.
@@ -525,6 +570,7 @@ var waitsFor = function(latchFunction, optional_timeoutMessage, optional_timeout
var beforeEach = function(beforeEachFunction) {
jasmine.getEnv().beforeEach(beforeEachFunction);
};
+if (isCommonJS) exports.beforeEach = beforeEach;
/**
* A function that is called after each spec in a suite.
@@ -536,6 +582,7 @@ var beforeEach = function(beforeEachFunction) {
var afterEach = function(afterEachFunction) {
jasmine.getEnv().afterEach(afterEachFunction);
};
+if (isCommonJS) exports.afterEach = afterEach;
/**
* Defines a suite of specifications.
@@ -555,6 +602,7 @@ var afterEach = function(afterEachFunction) {
var describe = function(description, specDefinitions) {
return jasmine.getEnv().describe(description, specDefinitions);
};
+if (isCommonJS) exports.describe = describe;
/**
* Disables a suite of specifications. Used to disable some suites in a file, or files, temporarily during development.
@@ -565,27 +613,35 @@ var describe = function(description, specDefinitions) {
var xdescribe = function(description, specDefinitions) {
return jasmine.getEnv().xdescribe(description, specDefinitions);
};
+if (isCommonJS) exports.xdescribe = xdescribe;
// Provide the XMLHttpRequest class for IE 5.x-6.x:
jasmine.XmlHttpRequest = (typeof XMLHttpRequest == "undefined") ? function() {
- try {
- return new ActiveXObject("Msxml2.XMLHTTP.6.0");
- } catch(e) {
- }
- try {
- return new ActiveXObject("Msxml2.XMLHTTP.3.0");
- } catch(e) {
- }
- try {
- return new ActiveXObject("Msxml2.XMLHTTP");
- } catch(e) {
- }
- try {
- return new ActiveXObject("Microsoft.XMLHTTP");
- } catch(e) {
+ function tryIt(f) {
+ try {
+ return f();
+ } catch(e) {
+ }
+ return null;
}
- throw new Error("This browser does not support XMLHttpRequest.");
+
+ var xhr = tryIt(function() {
+ return new ActiveXObject("Msxml2.XMLHTTP.6.0");
+ }) ||
+ tryIt(function() {
+ return new ActiveXObject("Msxml2.XMLHTTP.3.0");
+ }) ||
+ tryIt(function() {
+ return new ActiveXObject("Msxml2.XMLHTTP");
+ }) ||
+ tryIt(function() {
+ return new ActiveXObject("Microsoft.XMLHTTP");
+ });
+
+ if (!xhr) throw new Error("This browser does not support XMLHttpRequest.");
+
+ return xhr;
} : XMLHttpRequest;
/**
* @namespace
@@ -606,7 +662,7 @@ jasmine.util.inherit = function(childClass, parentClass) {
var subclass = function() {
};
subclass.prototype = parentClass.prototype;
- childClass.prototype = new subclass;
+ childClass.prototype = new subclass();
};
jasmine.util.formatException = function(e) {
@@ -707,12 +763,17 @@ jasmine.Env.prototype.version = function () {
* @returns string containing jasmine version build info, if set.
*/
jasmine.Env.prototype.versionString = function() {
- if (jasmine.version_) {
- var version = this.version();
- return version.major + "." + version.minor + "." + version.build + " revision " + version.revision;
- } else {
+ if (!jasmine.version_) {
return "version unknown";
}
+
+ var version = this.version();
+ var versionString = version.major + "." + version.minor + "." + version.build;
+ if (version.release_candidate) {
+ versionString += ".rc" + version.release_candidate;
+ }
+ versionString += " revision " + version.revision;
+ return versionString;
};
/**
@@ -760,14 +821,14 @@ jasmine.Env.prototype.describe = function(description, specDefinitions) {
declarationError = e;
}
- this.currentSuite = parentSuite;
-
if (declarationError) {
this.it("encountered a declaration exception", function() {
throw declarationError;
});
}
+ this.currentSuite = parentSuite;
+
return suite;
};
@@ -819,6 +880,25 @@ jasmine.Env.prototype.xit = function(desc, func) {
};
};
+jasmine.Env.prototype.compareRegExps_ = function(a, b, mismatchKeys, mismatchValues) {
+ if (a.source != b.source)
+ mismatchValues.push("expected pattern /" + b.source + "/ is not equal to the pattern /" + a.source + "/");
+
+ if (a.ignoreCase != b.ignoreCase)
+ mismatchValues.push("expected modifier i was" + (b.ignoreCase ? " " : " not ") + "set and does not equal the origin modifier");
+
+ if (a.global != b.global)
+ mismatchValues.push("expected modifier g was" + (b.global ? " " : " not ") + "set and does not equal the origin modifier");
+
+ if (a.multiline != b.multiline)
+ mismatchValues.push("expected modifier m was" + (b.multiline ? " " : " not ") + "set and does not equal the origin modifier");
+
+ if (a.sticky != b.sticky)
+ mismatchValues.push("expected modifier y was" + (b.sticky ? " " : " not ") + "set and does not equal the origin modifier");
+
+ return (mismatchValues.length === 0);
+};
+
jasmine.Env.prototype.compareObjects_ = function(a, b, mismatchKeys, mismatchValues) {
if (a.__Jasmine_been_here_before__ === b && b.__Jasmine_been_here_before__ === a) {
return true;
@@ -828,7 +908,7 @@ jasmine.Env.prototype.compareObjects_ = function(a, b, mismatchKeys, mismatchVal
b.__Jasmine_been_here_before__ = a;
var hasKey = function(obj, keyName) {
- return obj != null && obj[keyName] !== jasmine.undefined;
+ return obj !== null && obj[keyName] !== jasmine.undefined;
};
for (var property in b) {
@@ -854,7 +934,7 @@ jasmine.Env.prototype.compareObjects_ = function(a, b, mismatchKeys, mismatchVal
delete a.__Jasmine_been_here_before__;
delete b.__Jasmine_been_here_before__;
- return (mismatchKeys.length == 0 && mismatchValues.length == 0);
+ return (mismatchKeys.length === 0 && mismatchValues.length === 0);
};
jasmine.Env.prototype.equals_ = function(a, b, mismatchKeys, mismatchValues) {
@@ -881,11 +961,19 @@ jasmine.Env.prototype.equals_ = function(a, b, mismatchKeys, mismatchValues) {
return a.getTime() == b.getTime();
}
- if (a instanceof jasmine.Matchers.Any) {
+ if (a.jasmineMatches) {
+ return a.jasmineMatches(b);
+ }
+
+ if (b.jasmineMatches) {
+ return b.jasmineMatches(a);
+ }
+
+ if (a instanceof jasmine.Matchers.ObjectContaining) {
return a.matches(b);
}
- if (b instanceof jasmine.Matchers.Any) {
+ if (b instanceof jasmine.Matchers.ObjectContaining) {
return b.matches(a);
}
@@ -897,6 +985,10 @@ jasmine.Env.prototype.equals_ = function(a, b, mismatchKeys, mismatchValues) {
return (a == b);
}
+ if (a instanceof RegExp && b instanceof RegExp) {
+ return this.compareRegExps_(a, b, mismatchKeys, mismatchValues);
+ }
+
if (typeof a === "object" && typeof b === "object") {
return this.compareObjects_(a, b, mismatchKeys, mismatchValues);
}
@@ -963,11 +1055,16 @@ jasmine.Block = function(env, func, spec) {
this.spec = spec;
};
-jasmine.Block.prototype.execute = function(onComplete) {
- try {
+jasmine.Block.prototype.execute = function(onComplete) {
+ if (!jasmine.CATCH_EXCEPTIONS) {
this.func.apply(this.spec);
- } catch (e) {
- this.spec.fail(e);
+ }
+ else {
+ try {
+ this.func.apply(this.spec);
+ } catch (e) {
+ this.spec.fail(e);
+ }
}
onComplete();
};
@@ -1179,7 +1276,7 @@ jasmine.Matchers.prototype.toEqual = function(expected) {
/**
* toNotEqual: compares the actual to the expected using the ! of jasmine.Matchers.toEqual
* @param expected
- * @deprecated as of 1.0. Use not.toNotEqual() instead.
+ * @deprecated as of 1.0. Use not.toEqual() instead.
*/
jasmine.Matchers.prototype.toNotEqual = function(expected) {
return !this.env.equals_(this.actual, expected);
@@ -1225,6 +1322,17 @@ jasmine.Matchers.prototype.toBeNull = function() {
return (this.actual === null);
};
+/**
+ * Matcher that compares the actual to NaN.
+ */
+jasmine.Matchers.prototype.toBeNaN = function() {
+ this.message = function() {
+ return [ "Expected " + jasmine.pp(this.actual) + " to be NaN." ];
+ };
+
+ return (this.actual !== this.actual);
+};
+
/**
* Matcher that boolean not-nots the actual.
*/
@@ -1302,18 +1410,14 @@ jasmine.Matchers.prototype.toHaveBeenCalledWith = function() {
throw new Error('Expected a spy, but got ' + jasmine.pp(this.actual) + '.');
}
this.message = function() {
- if (this.actual.callCount == 0) {
- // todo: what should the failure message for .not.toHaveBeenCalledWith() be? is this right? test better. [xw]
- return [
- "Expected spy to have been called with " + jasmine.pp(expectedArgs) + " but it was never called.",
- "Expected spy not to have been called with " + jasmine.pp(expectedArgs) + " but it was."
- ];
+ var invertedMessage = "Expected spy " + this.actual.identity + " not to have been called with " + jasmine.pp(expectedArgs) + " but it was.";
+ var positiveMessage = "";
+ if (this.actual.callCount === 0) {
+ positiveMessage = "Expected spy " + this.actual.identity + " to have been called with " + jasmine.pp(expectedArgs) + " but it was never called.";
} else {
- return [
- "Expected spy to have been called with " + jasmine.pp(expectedArgs) + " but was called with " + jasmine.pp(this.actual.argsForCall),
- "Expected spy not to have been called with " + jasmine.pp(expectedArgs) + " but was called with " + jasmine.pp(this.actual.argsForCall)
- ];
+ positiveMessage = "Expected spy " + this.actual.identity + " to have been called with " + jasmine.pp(expectedArgs) + " but actual calls were " + jasmine.pp(this.actual.argsForCall).replace(/^\[ | \]$/g, '')
}
+ return [positiveMessage, invertedMessage];
};
return this.env.contains_(this.actual.argsForCall, expectedArgs);
@@ -1333,7 +1437,7 @@ jasmine.Matchers.prototype.wasNotCalledWith = function() {
return [
"Expected spy not to have been called with " + jasmine.pp(expectedArgs) + " but it was",
"Expected spy to have been called with " + jasmine.pp(expectedArgs) + " but it was"
- ]
+ ];
};
return !this.env.contains_(this.actual.argsForCall, expectedArgs);
@@ -1352,7 +1456,7 @@ jasmine.Matchers.prototype.toContain = function(expected) {
* Matcher that checks that the expected item is NOT an element in the actual Array.
*
* @param {Object} expected
- * @deprecated as of 1.0. Use not.toNotContain() instead.
+ * @deprecated as of 1.0. Use not.toContain() instead.
*/
jasmine.Matchers.prototype.toNotContain = function(expected) {
return !this.env.contains_(this.actual, expected);
@@ -1366,10 +1470,24 @@ jasmine.Matchers.prototype.toBeGreaterThan = function(expected) {
return this.actual > expected;
};
+/**
+ * Matcher that checks that the expected item is equal to the actual item
+ * up to a given level of decimal precision (default 2).
+ *
+ * @param {Number} expected
+ * @param {Number} precision, as number of decimal places
+ */
+jasmine.Matchers.prototype.toBeCloseTo = function(expected, precision) {
+ if (!(precision === 0)) {
+ precision = precision || 2;
+ }
+ return Math.abs(expected - this.actual) < (Math.pow(10, -precision) / 2);
+};
+
/**
* Matcher that checks that the expected exception was thrown by the actual.
*
- * @param {String} expected
+ * @param {String} [expected]
*/
jasmine.Matchers.prototype.toThrow = function(expected) {
var result = false;
@@ -1390,7 +1508,7 @@ jasmine.Matchers.prototype.toThrow = function(expected) {
this.message = function() {
if (exception && (expected === jasmine.undefined || !this.env.equals_(exception.message || exception, expected.message || expected))) {
- return ["Expected function " + not + "to throw", expected ? expected.message || expected : " an exception", ", but it threw", exception.message || exception].join(' ');
+ return ["Expected function " + not + "to throw", expected ? expected.message || expected : "an exception", ", but it threw", exception.message || exception].join(' ');
} else {
return "Expected function to throw an exception.";
}
@@ -1403,7 +1521,7 @@ jasmine.Matchers.Any = function(expectedClass) {
this.expectedClass = expectedClass;
};
-jasmine.Matchers.Any.prototype.matches = function(other) {
+jasmine.Matchers.Any.prototype.jasmineMatches = function(other) {
if (this.expectedClass == String) {
return typeof other == 'string' || other instanceof String;
}
@@ -1423,10 +1541,222 @@ jasmine.Matchers.Any.prototype.matches = function(other) {
return other instanceof this.expectedClass;
};
-jasmine.Matchers.Any.prototype.toString = function() {
+jasmine.Matchers.Any.prototype.jasmineToString = function() {
return '
';
};
+jasmine.Matchers.ObjectContaining = function (sample) {
+ this.sample = sample;
+};
+
+jasmine.Matchers.ObjectContaining.prototype.jasmineMatches = function(other, mismatchKeys, mismatchValues) {
+ mismatchKeys = mismatchKeys || [];
+ mismatchValues = mismatchValues || [];
+
+ var env = jasmine.getEnv();
+
+ var hasKey = function(obj, keyName) {
+ return obj != null && obj[keyName] !== jasmine.undefined;
+ };
+
+ for (var property in this.sample) {
+ if (!hasKey(other, property) && hasKey(this.sample, property)) {
+ mismatchKeys.push("expected has key '" + property + "', but missing from actual.");
+ }
+ else if (!env.equals_(this.sample[property], other[property], mismatchKeys, mismatchValues)) {
+ mismatchValues.push("'" + property + "' was '" + (other[property] ? jasmine.util.htmlEscape(other[property].toString()) : other[property]) + "' in expected, but was '" + (this.sample[property] ? jasmine.util.htmlEscape(this.sample[property].toString()) : this.sample[property]) + "' in actual.");
+ }
+ }
+
+ return (mismatchKeys.length === 0 && mismatchValues.length === 0);
+};
+
+jasmine.Matchers.ObjectContaining.prototype.jasmineToString = function () {
+ return "";
+};
+// Mock setTimeout, clearTimeout
+// Contributed by Pivotal Computer Systems, www.pivotalsf.com
+
+jasmine.FakeTimer = function() {
+ this.reset();
+
+ var self = this;
+ self.setTimeout = function(funcToCall, millis) {
+ self.timeoutsMade++;
+ self.scheduleFunction(self.timeoutsMade, funcToCall, millis, false);
+ return self.timeoutsMade;
+ };
+
+ self.setInterval = function(funcToCall, millis) {
+ self.timeoutsMade++;
+ self.scheduleFunction(self.timeoutsMade, funcToCall, millis, true);
+ return self.timeoutsMade;
+ };
+
+ self.clearTimeout = function(timeoutKey) {
+ self.scheduledFunctions[timeoutKey] = jasmine.undefined;
+ };
+
+ self.clearInterval = function(timeoutKey) {
+ self.scheduledFunctions[timeoutKey] = jasmine.undefined;
+ };
+
+};
+
+jasmine.FakeTimer.prototype.reset = function() {
+ this.timeoutsMade = 0;
+ this.scheduledFunctions = {};
+ this.nowMillis = 0;
+};
+
+jasmine.FakeTimer.prototype.tick = function(millis) {
+ var oldMillis = this.nowMillis;
+ var newMillis = oldMillis + millis;
+ this.runFunctionsWithinRange(oldMillis, newMillis);
+ this.nowMillis = newMillis;
+};
+
+jasmine.FakeTimer.prototype.runFunctionsWithinRange = function(oldMillis, nowMillis) {
+ var scheduledFunc;
+ var funcsToRun = [];
+ for (var timeoutKey in this.scheduledFunctions) {
+ scheduledFunc = this.scheduledFunctions[timeoutKey];
+ if (scheduledFunc != jasmine.undefined &&
+ scheduledFunc.runAtMillis >= oldMillis &&
+ scheduledFunc.runAtMillis <= nowMillis) {
+ funcsToRun.push(scheduledFunc);
+ this.scheduledFunctions[timeoutKey] = jasmine.undefined;
+ }
+ }
+
+ if (funcsToRun.length > 0) {
+ funcsToRun.sort(function(a, b) {
+ return a.runAtMillis - b.runAtMillis;
+ });
+ for (var i = 0; i < funcsToRun.length; ++i) {
+ try {
+ var funcToRun = funcsToRun[i];
+ this.nowMillis = funcToRun.runAtMillis;
+ funcToRun.funcToCall();
+ if (funcToRun.recurring) {
+ this.scheduleFunction(funcToRun.timeoutKey,
+ funcToRun.funcToCall,
+ funcToRun.millis,
+ true);
+ }
+ } catch(e) {
+ }
+ }
+ this.runFunctionsWithinRange(oldMillis, nowMillis);
+ }
+};
+
+jasmine.FakeTimer.prototype.scheduleFunction = function(timeoutKey, funcToCall, millis, recurring) {
+ this.scheduledFunctions[timeoutKey] = {
+ runAtMillis: this.nowMillis + millis,
+ funcToCall: funcToCall,
+ recurring: recurring,
+ timeoutKey: timeoutKey,
+ millis: millis
+ };
+};
+
+/**
+ * @namespace
+ */
+jasmine.Clock = {
+ defaultFakeTimer: new jasmine.FakeTimer(),
+
+ reset: function() {
+ jasmine.Clock.assertInstalled();
+ jasmine.Clock.defaultFakeTimer.reset();
+ },
+
+ tick: function(millis) {
+ jasmine.Clock.assertInstalled();
+ jasmine.Clock.defaultFakeTimer.tick(millis);
+ },
+
+ runFunctionsWithinRange: function(oldMillis, nowMillis) {
+ jasmine.Clock.defaultFakeTimer.runFunctionsWithinRange(oldMillis, nowMillis);
+ },
+
+ scheduleFunction: function(timeoutKey, funcToCall, millis, recurring) {
+ jasmine.Clock.defaultFakeTimer.scheduleFunction(timeoutKey, funcToCall, millis, recurring);
+ },
+
+ useMock: function() {
+ if (!jasmine.Clock.isInstalled()) {
+ var spec = jasmine.getEnv().currentSpec;
+ spec.after(jasmine.Clock.uninstallMock);
+
+ jasmine.Clock.installMock();
+ }
+ },
+
+ installMock: function() {
+ jasmine.Clock.installed = jasmine.Clock.defaultFakeTimer;
+ },
+
+ uninstallMock: function() {
+ jasmine.Clock.assertInstalled();
+ jasmine.Clock.installed = jasmine.Clock.real;
+ },
+
+ real: {
+ setTimeout: jasmine.getGlobal().setTimeout,
+ clearTimeout: jasmine.getGlobal().clearTimeout,
+ setInterval: jasmine.getGlobal().setInterval,
+ clearInterval: jasmine.getGlobal().clearInterval
+ },
+
+ assertInstalled: function() {
+ if (!jasmine.Clock.isInstalled()) {
+ throw new Error("Mock clock is not installed, use jasmine.Clock.useMock()");
+ }
+ },
+
+ isInstalled: function() {
+ return jasmine.Clock.installed == jasmine.Clock.defaultFakeTimer;
+ },
+
+ installed: null
+};
+jasmine.Clock.installed = jasmine.Clock.real;
+
+//else for IE support
+jasmine.getGlobal().setTimeout = function(funcToCall, millis) {
+ if (jasmine.Clock.installed.setTimeout.apply) {
+ return jasmine.Clock.installed.setTimeout.apply(this, arguments);
+ } else {
+ return jasmine.Clock.installed.setTimeout(funcToCall, millis);
+ }
+};
+
+jasmine.getGlobal().setInterval = function(funcToCall, millis) {
+ if (jasmine.Clock.installed.setInterval.apply) {
+ return jasmine.Clock.installed.setInterval.apply(this, arguments);
+ } else {
+ return jasmine.Clock.installed.setInterval(funcToCall, millis);
+ }
+};
+
+jasmine.getGlobal().clearTimeout = function(timeoutKey) {
+ if (jasmine.Clock.installed.clearTimeout.apply) {
+ return jasmine.Clock.installed.clearTimeout.apply(this, arguments);
+ } else {
+ return jasmine.Clock.installed.clearTimeout(timeoutKey);
+ }
+};
+
+jasmine.getGlobal().clearInterval = function(timeoutKey) {
+ if (jasmine.Clock.installed.clearTimeout.apply) {
+ return jasmine.Clock.installed.clearInterval.apply(this, arguments);
+ } else {
+ return jasmine.Clock.installed.clearInterval(timeoutKey);
+ }
+};
+
/**
* @constructor
*/
@@ -1555,10 +1885,6 @@ jasmine.PrettyPrinter = function() {
* @param value
*/
jasmine.PrettyPrinter.prototype.format = function(value) {
- if (this.ppNestLevel_ > 40) {
- throw new Error('jasmine.PrettyPrinter: format() nested too deeply!');
- }
-
this.ppNestLevel_++;
try {
if (value === jasmine.undefined) {
@@ -1567,8 +1893,8 @@ jasmine.PrettyPrinter.prototype.format = function(value) {
this.emitScalar('null');
} else if (value === jasmine.getGlobal()) {
this.emitScalar('');
- } else if (value instanceof jasmine.Matchers.Any) {
- this.emitScalar(value.toString());
+ } else if (value.jasmineToString) {
+ this.emitScalar(value.jasmineToString());
} else if (typeof value === 'string') {
this.emitString(value);
} else if (jasmine.isSpy(value)) {
@@ -1601,8 +1927,10 @@ jasmine.PrettyPrinter.prototype.format = function(value) {
jasmine.PrettyPrinter.prototype.iterateObject = function(obj, fn) {
for (var property in obj) {
+ if (!obj.hasOwnProperty(property)) continue;
if (property == '__Jasmine_been_here_before__') continue;
- fn(property, obj.__lookupGetter__ ? (obj.__lookupGetter__(property) != null) : false);
+ fn(property, obj.__lookupGetter__ ? (obj.__lookupGetter__(property) !== jasmine.undefined &&
+ obj.__lookupGetter__(property) !== null) : false);
}
};
@@ -1627,6 +1955,11 @@ jasmine.StringPrettyPrinter.prototype.emitString = function(value) {
};
jasmine.StringPrettyPrinter.prototype.emitArray = function(array) {
+ if (this.ppNestLevel_ > jasmine.MAX_PRETTY_PRINT_DEPTH) {
+ this.append("Array");
+ return;
+ }
+
this.append('[ ');
for (var i = 0; i < array.length; i++) {
if (i > 0) {
@@ -1638,6 +1971,11 @@ jasmine.StringPrettyPrinter.prototype.emitArray = function(array) {
};
jasmine.StringPrettyPrinter.prototype.emitObject = function(obj) {
+ if (this.ppNestLevel_ > jasmine.MAX_PRETTY_PRINT_DEPTH) {
+ this.append("Object");
+ return;
+ }
+
var self = this;
this.append('{ ');
var first = true;
@@ -1666,6 +2004,10 @@ jasmine.StringPrettyPrinter.prototype.append = function(value) {
};
jasmine.Queue = function(env) {
this.env = env;
+
+ // parallel to blocks. each true value in this array means the block will
+ // get executed even if we abort
+ this.ensured = [];
this.blocks = [];
this.running = false;
this.index = 0;
@@ -1673,15 +2015,30 @@ jasmine.Queue = function(env) {
this.abort = false;
};
-jasmine.Queue.prototype.addBefore = function(block) {
+jasmine.Queue.prototype.addBefore = function(block, ensure) {
+ if (ensure === jasmine.undefined) {
+ ensure = false;
+ }
+
this.blocks.unshift(block);
+ this.ensured.unshift(ensure);
};
-jasmine.Queue.prototype.add = function(block) {
+jasmine.Queue.prototype.add = function(block, ensure) {
+ if (ensure === jasmine.undefined) {
+ ensure = false;
+ }
+
this.blocks.push(block);
+ this.ensured.push(ensure);
};
-jasmine.Queue.prototype.insertNext = function(block) {
+jasmine.Queue.prototype.insertNext = function(block, ensure) {
+ if (ensure === jasmine.undefined) {
+ ensure = false;
+ }
+
+ this.ensured.splice((this.index + this.offset + 1), 0, ensure);
this.blocks.splice((this.index + this.offset + 1), 0, block);
this.offset++;
};
@@ -1705,7 +2062,7 @@ jasmine.Queue.prototype.next_ = function() {
while (goAgain) {
goAgain = false;
- if (self.index < self.blocks.length && !this.abort) {
+ if (self.index < self.blocks.length && !(this.abort && !this.ensured[self.index])) {
var calledSynchronously = true;
var completedSynchronously = false;
@@ -1962,7 +2319,8 @@ jasmine.Spec.prototype.waitsFor = function(latchFunction, optional_timeoutMessag
jasmine.Spec.prototype.fail = function (e) {
var expectationResult = new jasmine.ExpectationResult({
passed: false,
- message: e ? jasmine.util.formatException(e) : 'Exception'
+ message: e ? jasmine.util.formatException(e) : 'Exception',
+ trace: { stack: e.stack }
});
this.results_.addResult(expectationResult);
};
@@ -1995,7 +2353,7 @@ jasmine.Spec.prototype.finish = function(onComplete) {
jasmine.Spec.prototype.after = function(doAfter) {
if (this.queue.isRunning()) {
- this.queue.add(new jasmine.Block(this.env, doAfter, this));
+ this.queue.add(new jasmine.Block(this.env, doAfter, this), true);
} else {
this.afterCallbacks.unshift(doAfter);
}
@@ -2033,15 +2391,15 @@ jasmine.Spec.prototype.addBeforesAndAftersToQueue = function() {
this.queue.addBefore(new jasmine.Block(this.env, runner.before_[i], this));
}
for (i = 0; i < this.afterCallbacks.length; i++) {
- this.queue.add(new jasmine.Block(this.env, this.afterCallbacks[i], this));
+ this.queue.add(new jasmine.Block(this.env, this.afterCallbacks[i], this), true);
}
for (suite = this.suite; suite; suite = suite.parentSuite) {
for (i = 0; i < suite.after_.length; i++) {
- this.queue.add(new jasmine.Block(this.env, suite.after_[i], this));
+ this.queue.add(new jasmine.Block(this.env, suite.after_[i], this), true);
}
}
for (i = 0; i < runner.after_.length; i++) {
- this.queue.add(new jasmine.Block(this.env, runner.after_[i], this));
+ this.queue.add(new jasmine.Block(this.env, runner.after_[i], this), true);
}
};
@@ -2172,7 +2530,9 @@ jasmine.WaitsBlock = function(env, timeout, spec) {
jasmine.util.inherit(jasmine.WaitsBlock, jasmine.Block);
jasmine.WaitsBlock.prototype.execute = function (onComplete) {
- this.env.reporter.log('>> Jasmine waiting for ' + this.timeout + ' ms...');
+ if (jasmine.VERBOSE) {
+ this.env.reporter.log('>> Jasmine waiting for ' + this.timeout + ' ms...');
+ }
this.env.setTimeout(function () {
onComplete();
}, this.timeout);
@@ -2200,7 +2560,9 @@ jasmine.util.inherit(jasmine.WaitsForBlock, jasmine.Block);
jasmine.WaitsForBlock.TIMEOUT_INCREMENT = 10;
jasmine.WaitsForBlock.prototype.execute = function(onComplete) {
- this.env.reporter.log('>> Jasmine waiting for ' + (this.message || 'something to happen'));
+ if (jasmine.VERBOSE) {
+ this.env.reporter.log('>> Jasmine waiting for ' + (this.message || 'something to happen'));
+ }
var latchFunctionResult;
try {
latchFunctionResult = this.latchFunction.apply(this.spec);
@@ -2229,193 +2591,10 @@ jasmine.WaitsForBlock.prototype.execute = function(onComplete) {
}, jasmine.WaitsForBlock.TIMEOUT_INCREMENT);
}
};
-// Mock setTimeout, clearTimeout
-// Contributed by Pivotal Computer Systems, www.pivotalsf.com
-
-jasmine.FakeTimer = function() {
- this.reset();
-
- var self = this;
- self.setTimeout = function(funcToCall, millis) {
- self.timeoutsMade++;
- self.scheduleFunction(self.timeoutsMade, funcToCall, millis, false);
- return self.timeoutsMade;
- };
-
- self.setInterval = function(funcToCall, millis) {
- self.timeoutsMade++;
- self.scheduleFunction(self.timeoutsMade, funcToCall, millis, true);
- return self.timeoutsMade;
- };
-
- self.clearTimeout = function(timeoutKey) {
- self.scheduledFunctions[timeoutKey] = jasmine.undefined;
- };
-
- self.clearInterval = function(timeoutKey) {
- self.scheduledFunctions[timeoutKey] = jasmine.undefined;
- };
-
-};
-
-jasmine.FakeTimer.prototype.reset = function() {
- this.timeoutsMade = 0;
- this.scheduledFunctions = {};
- this.nowMillis = 0;
-};
-
-jasmine.FakeTimer.prototype.tick = function(millis) {
- var oldMillis = this.nowMillis;
- var newMillis = oldMillis + millis;
- this.runFunctionsWithinRange(oldMillis, newMillis);
- this.nowMillis = newMillis;
-};
-
-jasmine.FakeTimer.prototype.runFunctionsWithinRange = function(oldMillis, nowMillis) {
- var scheduledFunc;
- var funcsToRun = [];
- for (var timeoutKey in this.scheduledFunctions) {
- scheduledFunc = this.scheduledFunctions[timeoutKey];
- if (scheduledFunc != jasmine.undefined &&
- scheduledFunc.runAtMillis >= oldMillis &&
- scheduledFunc.runAtMillis <= nowMillis) {
- funcsToRun.push(scheduledFunc);
- this.scheduledFunctions[timeoutKey] = jasmine.undefined;
- }
- }
-
- if (funcsToRun.length > 0) {
- funcsToRun.sort(function(a, b) {
- return a.runAtMillis - b.runAtMillis;
- });
- for (var i = 0; i < funcsToRun.length; ++i) {
- try {
- var funcToRun = funcsToRun[i];
- this.nowMillis = funcToRun.runAtMillis;
- funcToRun.funcToCall();
- if (funcToRun.recurring) {
- this.scheduleFunction(funcToRun.timeoutKey,
- funcToRun.funcToCall,
- funcToRun.millis,
- true);
- }
- } catch(e) {
- }
- }
- this.runFunctionsWithinRange(oldMillis, nowMillis);
- }
-};
-
-jasmine.FakeTimer.prototype.scheduleFunction = function(timeoutKey, funcToCall, millis, recurring) {
- this.scheduledFunctions[timeoutKey] = {
- runAtMillis: this.nowMillis + millis,
- funcToCall: funcToCall,
- recurring: recurring,
- timeoutKey: timeoutKey,
- millis: millis
- };
-};
-
-/**
- * @namespace
- */
-jasmine.Clock = {
- defaultFakeTimer: new jasmine.FakeTimer(),
-
- reset: function() {
- jasmine.Clock.assertInstalled();
- jasmine.Clock.defaultFakeTimer.reset();
- },
-
- tick: function(millis) {
- jasmine.Clock.assertInstalled();
- jasmine.Clock.defaultFakeTimer.tick(millis);
- },
-
- runFunctionsWithinRange: function(oldMillis, nowMillis) {
- jasmine.Clock.defaultFakeTimer.runFunctionsWithinRange(oldMillis, nowMillis);
- },
-
- scheduleFunction: function(timeoutKey, funcToCall, millis, recurring) {
- jasmine.Clock.defaultFakeTimer.scheduleFunction(timeoutKey, funcToCall, millis, recurring);
- },
-
- useMock: function() {
- if (!jasmine.Clock.isInstalled()) {
- var spec = jasmine.getEnv().currentSpec;
- spec.after(jasmine.Clock.uninstallMock);
-
- jasmine.Clock.installMock();
- }
- },
-
- installMock: function() {
- jasmine.Clock.installed = jasmine.Clock.defaultFakeTimer;
- },
-
- uninstallMock: function() {
- jasmine.Clock.assertInstalled();
- jasmine.Clock.installed = jasmine.Clock.real;
- },
-
- real: {
- setTimeout: jasmine.getGlobal().setTimeout,
- clearTimeout: jasmine.getGlobal().clearTimeout,
- setInterval: jasmine.getGlobal().setInterval,
- clearInterval: jasmine.getGlobal().clearInterval
- },
-
- assertInstalled: function() {
- if (!jasmine.Clock.isInstalled()) {
- throw new Error("Mock clock is not installed, use jasmine.Clock.useMock()");
- }
- },
-
- isInstalled: function() {
- return jasmine.Clock.installed == jasmine.Clock.defaultFakeTimer;
- },
-
- installed: null
-};
-jasmine.Clock.installed = jasmine.Clock.real;
-
-//else for IE support
-jasmine.getGlobal().setTimeout = function(funcToCall, millis) {
- if (jasmine.Clock.installed.setTimeout.apply) {
- return jasmine.Clock.installed.setTimeout.apply(this, arguments);
- } else {
- return jasmine.Clock.installed.setTimeout(funcToCall, millis);
- }
-};
-
-jasmine.getGlobal().setInterval = function(funcToCall, millis) {
- if (jasmine.Clock.installed.setInterval.apply) {
- return jasmine.Clock.installed.setInterval.apply(this, arguments);
- } else {
- return jasmine.Clock.installed.setInterval(funcToCall, millis);
- }
-};
-
-jasmine.getGlobal().clearTimeout = function(timeoutKey) {
- if (jasmine.Clock.installed.clearTimeout.apply) {
- return jasmine.Clock.installed.clearTimeout.apply(this, arguments);
- } else {
- return jasmine.Clock.installed.clearTimeout(timeoutKey);
- }
-};
-
-jasmine.getGlobal().clearInterval = function(timeoutKey) {
- if (jasmine.Clock.installed.clearTimeout.apply) {
- return jasmine.Clock.installed.clearInterval.apply(this, arguments);
- } else {
- return jasmine.Clock.installed.clearInterval(timeoutKey);
- }
-};
-
jasmine.version_= {
"major": 1,
- "minor": 0,
- "build": 2,
- "revision": 1298837858
+ "minor": 3,
+ "build": 1,
+ "revision": 1354556913
};
diff --git a/test/lib/require.js b/test/lib/require.js
new file mode 100644
index 00000000..0e7b81bc
--- /dev/null
+++ b/test/lib/require.js
@@ -0,0 +1,1993 @@
+/** vim: et:ts=4:sw=4:sts=4
+ * @license RequireJS 2.1.2 Copyright (c) 2010-2012, The Dojo Foundation All Rights Reserved.
+ * Available via the MIT or new BSD license.
+ * see: http://github.com/jrburke/requirejs for details
+ */
+//Not using strict: uneven strict support in browsers, #392, and causes
+//problems with requirejs.exec()/transpiler plugins that may not be strict.
+/*jslint regexp: true, nomen: true, sloppy: true */
+/*global window, navigator, document, importScripts, jQuery, setTimeout, opera */
+
+var requirejs, require, define;
+(function (global) {
+ var req, s, head, baseElement, dataMain, src,
+ interactiveScript, currentlyAddingScript, mainScript, subPath,
+ version = '2.1.2',
+ commentRegExp = /(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg,
+ cjsRequireRegExp = /[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g,
+ jsSuffixRegExp = /\.js$/,
+ currDirRegExp = /^\.\//,
+ op = Object.prototype,
+ ostring = op.toString,
+ hasOwn = op.hasOwnProperty,
+ ap = Array.prototype,
+ aps = ap.slice,
+ apsp = ap.splice,
+ isBrowser = !!(typeof window !== 'undefined' && navigator && document),
+ isWebWorker = !isBrowser && typeof importScripts !== 'undefined',
+ //PS3 indicates loaded and complete, but need to wait for complete
+ //specifically. Sequence is 'loading', 'loaded', execution,
+ // then 'complete'. The UA check is unfortunate, but not sure how
+ //to feature test w/o causing perf issues.
+ readyRegExp = isBrowser && navigator.platform === 'PLAYSTATION 3' ?
+ /^complete$/ : /^(complete|loaded)$/,
+ defContextName = '_',
+ //Oh the tragedy, detecting opera. See the usage of isOpera for reason.
+ isOpera = typeof opera !== 'undefined' && opera.toString() === '[object Opera]',
+ contexts = {},
+ cfg = {},
+ globalDefQueue = [],
+ useInteractive = false;
+
+ function isFunction(it) {
+ return ostring.call(it) === '[object Function]';
+ }
+
+ function isArray(it) {
+ return ostring.call(it) === '[object Array]';
+ }
+
+ /**
+ * Helper function for iterating over an array. If the func returns
+ * a true value, it will break out of the loop.
+ */
+ function each(ary, func) {
+ if (ary) {
+ var i;
+ for (i = 0; i < ary.length; i += 1) {
+ if (ary[i] && func(ary[i], i, ary)) {
+ break;
+ }
+ }
+ }
+ }
+
+ /**
+ * Helper function for iterating over an array backwards. If the func
+ * returns a true value, it will break out of the loop.
+ */
+ function eachReverse(ary, func) {
+ if (ary) {
+ var i;
+ for (i = ary.length - 1; i > -1; i -= 1) {
+ if (ary[i] && func(ary[i], i, ary)) {
+ break;
+ }
+ }
+ }
+ }
+
+ function hasProp(obj, prop) {
+ return hasOwn.call(obj, prop);
+ }
+
+ function getOwn(obj, prop) {
+ return hasProp(obj, prop) && obj[prop];
+ }
+
+ /**
+ * Cycles over properties in an object and calls a function for each
+ * property value. If the function returns a truthy value, then the
+ * iteration is stopped.
+ */
+ function eachProp(obj, func) {
+ var prop;
+ for (prop in obj) {
+ if (hasProp(obj, prop)) {
+ if (func(obj[prop], prop)) {
+ break;
+ }
+ }
+ }
+ }
+
+ /**
+ * Simple function to mix in properties from source into target,
+ * but only if target does not already have a property of the same name.
+ */
+ function mixin(target, source, force, deepStringMixin) {
+ if (source) {
+ eachProp(source, function (value, prop) {
+ if (force || !hasProp(target, prop)) {
+ if (deepStringMixin && typeof value !== 'string') {
+ if (!target[prop]) {
+ target[prop] = {};
+ }
+ mixin(target[prop], value, force, deepStringMixin);
+ } else {
+ target[prop] = value;
+ }
+ }
+ });
+ }
+ return target;
+ }
+
+ //Similar to Function.prototype.bind, but the 'this' object is specified
+ //first, since it is easier to read/figure out what 'this' will be.
+ function bind(obj, fn) {
+ return function () {
+ return fn.apply(obj, arguments);
+ };
+ }
+
+ function scripts() {
+ return document.getElementsByTagName('script');
+ }
+
+ //Allow getting a global that expressed in
+ //dot notation, like 'a.b.c'.
+ function getGlobal(value) {
+ if (!value) {
+ return value;
+ }
+ var g = global;
+ each(value.split('.'), function (part) {
+ g = g[part];
+ });
+ return g;
+ }
+
+ /**
+ * Constructs an error with a pointer to an URL with more information.
+ * @param {String} id the error ID that maps to an ID on a web page.
+ * @param {String} message human readable error.
+ * @param {Error} [err] the original error, if there is one.
+ *
+ * @returns {Error}
+ */
+ function makeError(id, msg, err, requireModules) {
+ var e = new Error(msg + '\nhttp://requirejs.org/docs/errors.html#' + id);
+ e.requireType = id;
+ e.requireModules = requireModules;
+ if (err) {
+ e.originalError = err;
+ }
+ return e;
+ }
+
+ if (typeof define !== 'undefined') {
+ //If a define is already in play via another AMD loader,
+ //do not overwrite.
+ return;
+ }
+
+ if (typeof requirejs !== 'undefined') {
+ if (isFunction(requirejs)) {
+ //Do not overwrite and existing requirejs instance.
+ return;
+ }
+ cfg = requirejs;
+ requirejs = undefined;
+ }
+
+ //Allow for a require config object
+ if (typeof require !== 'undefined' && !isFunction(require)) {
+ //assume it is a config object.
+ cfg = require;
+ require = undefined;
+ }
+
+ function newContext(contextName) {
+ var inCheckLoaded, Module, context, handlers,
+ checkLoadedTimeoutId,
+ config = {
+ waitSeconds: 7,
+ baseUrl: './',
+ paths: {},
+ pkgs: {},
+ shim: {},
+ map: {},
+ config: {}
+ },
+ registry = {},
+ undefEvents = {},
+ defQueue = [],
+ defined = {},
+ urlFetched = {},
+ requireCounter = 1,
+ unnormalizedCounter = 1;
+
+ /**
+ * Trims the . and .. from an array of path segments.
+ * It will keep a leading path segment if a .. will become
+ * the first path segment, to help with module name lookups,
+ * which act like paths, but can be remapped. But the end result,
+ * all paths that use this function should look normalized.
+ * NOTE: this method MODIFIES the input array.
+ * @param {Array} ary the array of path segments.
+ */
+ function trimDots(ary) {
+ var i, part;
+ for (i = 0; ary[i]; i += 1) {
+ part = ary[i];
+ if (part === '.') {
+ ary.splice(i, 1);
+ i -= 1;
+ } else if (part === '..') {
+ if (i === 1 && (ary[2] === '..' || ary[0] === '..')) {
+ //End of the line. Keep at least one non-dot
+ //path segment at the front so it can be mapped
+ //correctly to disk. Otherwise, there is likely
+ //no path mapping for a path starting with '..'.
+ //This can still fail, but catches the most reasonable
+ //uses of ..
+ break;
+ } else if (i > 0) {
+ ary.splice(i - 1, 2);
+ i -= 2;
+ }
+ }
+ }
+ }
+
+ /**
+ * Given a relative module name, like ./something, normalize it to
+ * a real name that can be mapped to a path.
+ * @param {String} name the relative name
+ * @param {String} baseName a real name that the name arg is relative
+ * to.
+ * @param {Boolean} applyMap apply the map config to the value. Should
+ * only be done if this normalization is for a dependency ID.
+ * @returns {String} normalized name
+ */
+ function normalize(name, baseName, applyMap) {
+ var pkgName, pkgConfig, mapValue, nameParts, i, j, nameSegment,
+ foundMap, foundI, foundStarMap, starI,
+ baseParts = baseName && baseName.split('/'),
+ normalizedBaseParts = baseParts,
+ map = config.map,
+ starMap = map && map['*'];
+
+ //Adjust any relative paths.
+ if (name && name.charAt(0) === '.') {
+ //If have a base name, try to normalize against it,
+ //otherwise, assume it is a top-level require that will
+ //be relative to baseUrl in the end.
+ if (baseName) {
+ if (getOwn(config.pkgs, baseName)) {
+ //If the baseName is a package name, then just treat it as one
+ //name to concat the name with.
+ normalizedBaseParts = baseParts = [baseName];
+ } else {
+ //Convert baseName to array, and lop off the last part,
+ //so that . matches that 'directory' and not name of the baseName's
+ //module. For instance, baseName of 'one/two/three', maps to
+ //'one/two/three.js', but we want the directory, 'one/two' for
+ //this normalization.
+ normalizedBaseParts = baseParts.slice(0, baseParts.length - 1);
+ }
+
+ name = normalizedBaseParts.concat(name.split('/'));
+ trimDots(name);
+
+ //Some use of packages may use a . path to reference the
+ //'main' module name, so normalize for that.
+ pkgConfig = getOwn(config.pkgs, (pkgName = name[0]));
+ name = name.join('/');
+ if (pkgConfig && name === pkgName + '/' + pkgConfig.main) {
+ name = pkgName;
+ }
+ } else if (name.indexOf('./') === 0) {
+ // No baseName, so this is ID is resolved relative
+ // to baseUrl, pull off the leading dot.
+ name = name.substring(2);
+ }
+ }
+
+ //Apply map config if available.
+ if (applyMap && (baseParts || starMap) && map) {
+ nameParts = name.split('/');
+
+ for (i = nameParts.length; i > 0; i -= 1) {
+ nameSegment = nameParts.slice(0, i).join('/');
+
+ if (baseParts) {
+ //Find the longest baseName segment match in the config.
+ //So, do joins on the biggest to smallest lengths of baseParts.
+ for (j = baseParts.length; j > 0; j -= 1) {
+ mapValue = getOwn(map, baseParts.slice(0, j).join('/'));
+
+ //baseName segment has config, find if it has one for
+ //this name.
+ if (mapValue) {
+ mapValue = getOwn(mapValue, nameSegment);
+ if (mapValue) {
+ //Match, update name to the new value.
+ foundMap = mapValue;
+ foundI = i;
+ break;
+ }
+ }
+ }
+ }
+
+ if (foundMap) {
+ break;
+ }
+
+ //Check for a star map match, but just hold on to it,
+ //if there is a shorter segment match later in a matching
+ //config, then favor over this star map.
+ if (!foundStarMap && starMap && getOwn(starMap, nameSegment)) {
+ foundStarMap = getOwn(starMap, nameSegment);
+ starI = i;
+ }
+ }
+
+ if (!foundMap && foundStarMap) {
+ foundMap = foundStarMap;
+ foundI = starI;
+ }
+
+ if (foundMap) {
+ nameParts.splice(0, foundI, foundMap);
+ name = nameParts.join('/');
+ }
+ }
+
+ return name;
+ }
+
+ function removeScript(name) {
+ if (isBrowser) {
+ each(scripts(), function (scriptNode) {
+ if (scriptNode.getAttribute('data-requiremodule') === name &&
+ scriptNode.getAttribute('data-requirecontext') === context.contextName) {
+ scriptNode.parentNode.removeChild(scriptNode);
+ return true;
+ }
+ });
+ }
+ }
+
+ function hasPathFallback(id) {
+ var pathConfig = getOwn(config.paths, id);
+ if (pathConfig && isArray(pathConfig) && pathConfig.length > 1) {
+ removeScript(id);
+ //Pop off the first array value, since it failed, and
+ //retry
+ pathConfig.shift();
+ context.require.undef(id);
+ context.require([id]);
+ return true;
+ }
+ }
+
+ //Turns a plugin!resource to [plugin, resource]
+ //with the plugin being undefined if the name
+ //did not have a plugin prefix.
+ function splitPrefix(name) {
+ var prefix,
+ index = name ? name.indexOf('!') : -1;
+ if (index > -1) {
+ prefix = name.substring(0, index);
+ name = name.substring(index + 1, name.length);
+ }
+ return [prefix, name];
+ }
+
+ /**
+ * Creates a module mapping that includes plugin prefix, module
+ * name, and path. If parentModuleMap is provided it will
+ * also normalize the name via require.normalize()
+ *
+ * @param {String} name the module name
+ * @param {String} [parentModuleMap] parent module map
+ * for the module name, used to resolve relative names.
+ * @param {Boolean} isNormalized: is the ID already normalized.
+ * This is true if this call is done for a define() module ID.
+ * @param {Boolean} applyMap: apply the map config to the ID.
+ * Should only be true if this map is for a dependency.
+ *
+ * @returns {Object}
+ */
+ function makeModuleMap(name, parentModuleMap, isNormalized, applyMap) {
+ var url, pluginModule, suffix, nameParts,
+ prefix = null,
+ parentName = parentModuleMap ? parentModuleMap.name : null,
+ originalName = name,
+ isDefine = true,
+ normalizedName = '';
+
+ //If no name, then it means it is a require call, generate an
+ //internal name.
+ if (!name) {
+ isDefine = false;
+ name = '_@r' + (requireCounter += 1);
+ }
+
+ nameParts = splitPrefix(name);
+ prefix = nameParts[0];
+ name = nameParts[1];
+
+ if (prefix) {
+ prefix = normalize(prefix, parentName, applyMap);
+ pluginModule = getOwn(defined, prefix);
+ }
+
+ //Account for relative paths if there is a base name.
+ if (name) {
+ if (prefix) {
+ if (pluginModule && pluginModule.normalize) {
+ //Plugin is loaded, use its normalize method.
+ normalizedName = pluginModule.normalize(name, function (name) {
+ return normalize(name, parentName, applyMap);
+ });
+ } else {
+ normalizedName = normalize(name, parentName, applyMap);
+ }
+ } else {
+ //A regular module.
+ normalizedName = normalize(name, parentName, applyMap);
+
+ //Normalized name may be a plugin ID due to map config
+ //application in normalize. The map config values must
+ //already be normalized, so do not need to redo that part.
+ nameParts = splitPrefix(normalizedName);
+ prefix = nameParts[0];
+ normalizedName = nameParts[1];
+ isNormalized = true;
+
+ url = context.nameToUrl(normalizedName);
+ }
+ }
+
+ //If the id is a plugin id that cannot be determined if it needs
+ //normalization, stamp it with a unique ID so two matching relative
+ //ids that may conflict can be separate.
+ suffix = prefix && !pluginModule && !isNormalized ?
+ '_unnormalized' + (unnormalizedCounter += 1) :
+ '';
+
+ return {
+ prefix: prefix,
+ name: normalizedName,
+ parentMap: parentModuleMap,
+ unnormalized: !!suffix,
+ url: url,
+ originalName: originalName,
+ isDefine: isDefine,
+ id: (prefix ?
+ prefix + '!' + normalizedName :
+ normalizedName) + suffix
+ };
+ }
+
+ function getModule(depMap) {
+ var id = depMap.id,
+ mod = getOwn(registry, id);
+
+ if (!mod) {
+ mod = registry[id] = new context.Module(depMap);
+ }
+
+ return mod;
+ }
+
+ function on(depMap, name, fn) {
+ var id = depMap.id,
+ mod = getOwn(registry, id);
+
+ if (hasProp(defined, id) &&
+ (!mod || mod.defineEmitComplete)) {
+ if (name === 'defined') {
+ fn(defined[id]);
+ }
+ } else {
+ getModule(depMap).on(name, fn);
+ }
+ }
+
+ function onError(err, errback) {
+ var ids = err.requireModules,
+ notified = false;
+
+ if (errback) {
+ errback(err);
+ } else {
+ each(ids, function (id) {
+ var mod = getOwn(registry, id);
+ if (mod) {
+ //Set error on module, so it skips timeout checks.
+ mod.error = err;
+ if (mod.events.error) {
+ notified = true;
+ mod.emit('error', err);
+ }
+ }
+ });
+
+ if (!notified) {
+ req.onError(err);
+ }
+ }
+ }
+
+ /**
+ * Internal method to transfer globalQueue items to this context's
+ * defQueue.
+ */
+ function takeGlobalQueue() {
+ //Push all the globalDefQueue items into the context's defQueue
+ if (globalDefQueue.length) {
+ //Array splice in the values since the context code has a
+ //local var ref to defQueue, so cannot just reassign the one
+ //on context.
+ apsp.apply(defQueue,
+ [defQueue.length - 1, 0].concat(globalDefQueue));
+ globalDefQueue = [];
+ }
+ }
+
+ handlers = {
+ 'require': function (mod) {
+ if (mod.require) {
+ return mod.require;
+ } else {
+ return (mod.require = context.makeRequire(mod.map));
+ }
+ },
+ 'exports': function (mod) {
+ mod.usingExports = true;
+ if (mod.map.isDefine) {
+ if (mod.exports) {
+ return mod.exports;
+ } else {
+ return (mod.exports = defined[mod.map.id] = {});
+ }
+ }
+ },
+ 'module': function (mod) {
+ if (mod.module) {
+ return mod.module;
+ } else {
+ return (mod.module = {
+ id: mod.map.id,
+ uri: mod.map.url,
+ config: function () {
+ return (config.config && getOwn(config.config, mod.map.id)) || {};
+ },
+ exports: defined[mod.map.id]
+ });
+ }
+ }
+ };
+
+ function cleanRegistry(id) {
+ //Clean up machinery used for waiting modules.
+ delete registry[id];
+ }
+
+ function breakCycle(mod, traced, processed) {
+ var id = mod.map.id;
+
+ if (mod.error) {
+ mod.emit('error', mod.error);
+ } else {
+ traced[id] = true;
+ each(mod.depMaps, function (depMap, i) {
+ var depId = depMap.id,
+ dep = getOwn(registry, depId);
+
+ //Only force things that have not completed
+ //being defined, so still in the registry,
+ //and only if it has not been matched up
+ //in the module already.
+ if (dep && !mod.depMatched[i] && !processed[depId]) {
+ if (getOwn(traced, depId)) {
+ mod.defineDep(i, defined[depId]);
+ mod.check(); //pass false?
+ } else {
+ breakCycle(dep, traced, processed);
+ }
+ }
+ });
+ processed[id] = true;
+ }
+ }
+
+ function checkLoaded() {
+ var map, modId, err, usingPathFallback,
+ waitInterval = config.waitSeconds * 1000,
+ //It is possible to disable the wait interval by using waitSeconds of 0.
+ expired = waitInterval && (context.startTime + waitInterval) < new Date().getTime(),
+ noLoads = [],
+ reqCalls = [],
+ stillLoading = false,
+ needCycleCheck = true;
+
+ //Do not bother if this call was a result of a cycle break.
+ if (inCheckLoaded) {
+ return;
+ }
+
+ inCheckLoaded = true;
+
+ //Figure out the state of all the modules.
+ eachProp(registry, function (mod) {
+ map = mod.map;
+ modId = map.id;
+
+ //Skip things that are not enabled or in error state.
+ if (!mod.enabled) {
+ return;
+ }
+
+ if (!map.isDefine) {
+ reqCalls.push(mod);
+ }
+
+ if (!mod.error) {
+ //If the module should be executed, and it has not
+ //been inited and time is up, remember it.
+ if (!mod.inited && expired) {
+ if (hasPathFallback(modId)) {
+ usingPathFallback = true;
+ stillLoading = true;
+ } else {
+ noLoads.push(modId);
+ removeScript(modId);
+ }
+ } else if (!mod.inited && mod.fetched && map.isDefine) {
+ stillLoading = true;
+ if (!map.prefix) {
+ //No reason to keep looking for unfinished
+ //loading. If the only stillLoading is a
+ //plugin resource though, keep going,
+ //because it may be that a plugin resource
+ //is waiting on a non-plugin cycle.
+ return (needCycleCheck = false);
+ }
+ }
+ }
+ });
+
+ if (expired && noLoads.length) {
+ //If wait time expired, throw error of unloaded modules.
+ err = makeError('timeout', 'Load timeout for modules: ' + noLoads, null, noLoads);
+ err.contextName = context.contextName;
+ return onError(err);
+ }
+
+ //Not expired, check for a cycle.
+ if (needCycleCheck) {
+ each(reqCalls, function (mod) {
+ breakCycle(mod, {}, {});
+ });
+ }
+
+ //If still waiting on loads, and the waiting load is something
+ //other than a plugin resource, or there are still outstanding
+ //scripts, then just try back later.
+ if ((!expired || usingPathFallback) && stillLoading) {
+ //Something is still waiting to load. Wait for it, but only
+ //if a timeout is not already in effect.
+ if ((isBrowser || isWebWorker) && !checkLoadedTimeoutId) {
+ checkLoadedTimeoutId = setTimeout(function () {
+ checkLoadedTimeoutId = 0;
+ checkLoaded();
+ }, 50);
+ }
+ }
+
+ inCheckLoaded = false;
+ }
+
+ Module = function (map) {
+ this.events = getOwn(undefEvents, map.id) || {};
+ this.map = map;
+ this.shim = getOwn(config.shim, map.id);
+ this.depExports = [];
+ this.depMaps = [];
+ this.depMatched = [];
+ this.pluginMaps = {};
+ this.depCount = 0;
+
+ /* this.exports this.factory
+ this.depMaps = [],
+ this.enabled, this.fetched
+ */
+ };
+
+ Module.prototype = {
+ init: function (depMaps, factory, errback, options) {
+ options = options || {};
+
+ //Do not do more inits if already done. Can happen if there
+ //are multiple define calls for the same module. That is not
+ //a normal, common case, but it is also not unexpected.
+ if (this.inited) {
+ return;
+ }
+
+ this.factory = factory;
+
+ if (errback) {
+ //Register for errors on this module.
+ this.on('error', errback);
+ } else if (this.events.error) {
+ //If no errback already, but there are error listeners
+ //on this module, set up an errback to pass to the deps.
+ errback = bind(this, function (err) {
+ this.emit('error', err);
+ });
+ }
+
+ //Do a copy of the dependency array, so that
+ //source inputs are not modified. For example
+ //"shim" deps are passed in here directly, and
+ //doing a direct modification of the depMaps array
+ //would affect that config.
+ this.depMaps = depMaps && depMaps.slice(0);
+
+ this.errback = errback;
+
+ //Indicate this module has be initialized
+ this.inited = true;
+
+ this.ignore = options.ignore;
+
+ //Could have option to init this module in enabled mode,
+ //or could have been previously marked as enabled. However,
+ //the dependencies are not known until init is called. So
+ //if enabled previously, now trigger dependencies as enabled.
+ if (options.enabled || this.enabled) {
+ //Enable this module and dependencies.
+ //Will call this.check()
+ this.enable();
+ } else {
+ this.check();
+ }
+ },
+
+ defineDep: function (i, depExports) {
+ //Because of cycles, defined callback for a given
+ //export can be called more than once.
+ if (!this.depMatched[i]) {
+ this.depMatched[i] = true;
+ this.depCount -= 1;
+ this.depExports[i] = depExports;
+ }
+ },
+
+ fetch: function () {
+ if (this.fetched) {
+ return;
+ }
+ this.fetched = true;
+
+ context.startTime = (new Date()).getTime();
+
+ var map = this.map;
+
+ //If the manager is for a plugin managed resource,
+ //ask the plugin to load it now.
+ if (this.shim) {
+ context.makeRequire(this.map, {
+ enableBuildCallback: true
+ })(this.shim.deps || [], bind(this, function () {
+ return map.prefix ? this.callPlugin() : this.load();
+ }));
+ } else {
+ //Regular dependency.
+ return map.prefix ? this.callPlugin() : this.load();
+ }
+ },
+
+ load: function () {
+ var url = this.map.url;
+
+ //Regular dependency.
+ if (!urlFetched[url]) {
+ urlFetched[url] = true;
+ context.load(this.map.id, url);
+ }
+ },
+
+ /**
+ * Checks is the module is ready to define itself, and if so,
+ * define it.
+ */
+ check: function () {
+ if (!this.enabled || this.enabling) {
+ return;
+ }
+
+ var err, cjsModule,
+ id = this.map.id,
+ depExports = this.depExports,
+ exports = this.exports,
+ factory = this.factory;
+
+ if (!this.inited) {
+ this.fetch();
+ } else if (this.error) {
+ this.emit('error', this.error);
+ } else if (!this.defining) {
+ //The factory could trigger another require call
+ //that would result in checking this module to
+ //define itself again. If already in the process
+ //of doing that, skip this work.
+ this.defining = true;
+
+ if (this.depCount < 1 && !this.defined) {
+ if (isFunction(factory)) {
+ //If there is an error listener, favor passing
+ //to that instead of throwing an error.
+ if (this.events.error) {
+ try {
+ exports = context.execCb(id, factory, depExports, exports);
+ } catch (e) {
+ err = e;
+ }
+ } else {
+ exports = context.execCb(id, factory, depExports, exports);
+ }
+
+ if (this.map.isDefine) {
+ //If setting exports via 'module' is in play,
+ //favor that over return value and exports. After that,
+ //favor a non-undefined return value over exports use.
+ cjsModule = this.module;
+ if (cjsModule &&
+ cjsModule.exports !== undefined &&
+ //Make sure it is not already the exports value
+ cjsModule.exports !== this.exports) {
+ exports = cjsModule.exports;
+ } else if (exports === undefined && this.usingExports) {
+ //exports already set the defined value.
+ exports = this.exports;
+ }
+ }
+
+ if (err) {
+ err.requireMap = this.map;
+ err.requireModules = [this.map.id];
+ err.requireType = 'define';
+ return onError((this.error = err));
+ }
+
+ } else {
+ //Just a literal value
+ exports = factory;
+ }
+
+ this.exports = exports;
+
+ if (this.map.isDefine && !this.ignore) {
+ defined[id] = exports;
+
+ if (req.onResourceLoad) {
+ req.onResourceLoad(context, this.map, this.depMaps);
+ }
+ }
+
+ //Clean up
+ delete registry[id];
+
+ this.defined = true;
+ }
+
+ //Finished the define stage. Allow calling check again
+ //to allow define notifications below in the case of a
+ //cycle.
+ this.defining = false;
+
+ if (this.defined && !this.defineEmitted) {
+ this.defineEmitted = true;
+ this.emit('defined', this.exports);
+ this.defineEmitComplete = true;
+ }
+
+ }
+ },
+
+ callPlugin: function () {
+ var map = this.map,
+ id = map.id,
+ //Map already normalized the prefix.
+ pluginMap = makeModuleMap(map.prefix);
+
+ //Mark this as a dependency for this plugin, so it
+ //can be traced for cycles.
+ this.depMaps.push(pluginMap);
+
+ on(pluginMap, 'defined', bind(this, function (plugin) {
+ var load, normalizedMap, normalizedMod,
+ name = this.map.name,
+ parentName = this.map.parentMap ? this.map.parentMap.name : null,
+ localRequire = context.makeRequire(map.parentMap, {
+ enableBuildCallback: true,
+ skipMap: true
+ });
+
+ //If current map is not normalized, wait for that
+ //normalized name to load instead of continuing.
+ if (this.map.unnormalized) {
+ //Normalize the ID if the plugin allows it.
+ if (plugin.normalize) {
+ name = plugin.normalize(name, function (name) {
+ return normalize(name, parentName, true);
+ }) || '';
+ }
+
+ //prefix and name should already be normalized, no need
+ //for applying map config again either.
+ normalizedMap = makeModuleMap(map.prefix + '!' + name,
+ this.map.parentMap);
+ on(normalizedMap,
+ 'defined', bind(this, function (value) {
+ this.init([], function () { return value; }, null, {
+ enabled: true,
+ ignore: true
+ });
+ }));
+
+ normalizedMod = getOwn(registry, normalizedMap.id);
+ if (normalizedMod) {
+ //Mark this as a dependency for this plugin, so it
+ //can be traced for cycles.
+ this.depMaps.push(normalizedMap);
+
+ if (this.events.error) {
+ normalizedMod.on('error', bind(this, function (err) {
+ this.emit('error', err);
+ }));
+ }
+ normalizedMod.enable();
+ }
+
+ return;
+ }
+
+ load = bind(this, function (value) {
+ this.init([], function () { return value; }, null, {
+ enabled: true
+ });
+ });
+
+ load.error = bind(this, function (err) {
+ this.inited = true;
+ this.error = err;
+ err.requireModules = [id];
+
+ //Remove temp unnormalized modules for this module,
+ //since they will never be resolved otherwise now.
+ eachProp(registry, function (mod) {
+ if (mod.map.id.indexOf(id + '_unnormalized') === 0) {
+ cleanRegistry(mod.map.id);
+ }
+ });
+
+ onError(err);
+ });
+
+ //Allow plugins to load other code without having to know the
+ //context or how to 'complete' the load.
+ load.fromText = bind(this, function (text, textAlt) {
+ /*jslint evil: true */
+ var moduleName = map.name,
+ moduleMap = makeModuleMap(moduleName),
+ hasInteractive = useInteractive;
+
+ //As of 2.1.0, support just passing the text, to reinforce
+ //fromText only being called once per resource. Still
+ //support old style of passing moduleName but discard
+ //that moduleName in favor of the internal ref.
+ if (textAlt) {
+ text = textAlt;
+ }
+
+ //Turn off interactive script matching for IE for any define
+ //calls in the text, then turn it back on at the end.
+ if (hasInteractive) {
+ useInteractive = false;
+ }
+
+ //Prime the system by creating a module instance for
+ //it.
+ getModule(moduleMap);
+
+ //Transfer any config to this other module.
+ if (hasProp(config.config, id)) {
+ config.config[moduleName] = config.config[id];
+ }
+
+ try {
+ req.exec(text);
+ } catch (e) {
+ throw new Error('fromText eval for ' + moduleName +
+ ' failed: ' + e);
+ }
+
+ if (hasInteractive) {
+ useInteractive = true;
+ }
+
+ //Mark this as a dependency for the plugin
+ //resource
+ this.depMaps.push(moduleMap);
+
+ //Support anonymous modules.
+ context.completeLoad(moduleName);
+
+ //Bind the value of that module to the value for this
+ //resource ID.
+ localRequire([moduleName], load);
+ });
+
+ //Use parentName here since the plugin's name is not reliable,
+ //could be some weird string with no path that actually wants to
+ //reference the parentName's path.
+ plugin.load(map.name, localRequire, load, config);
+ }));
+
+ context.enable(pluginMap, this);
+ this.pluginMaps[pluginMap.id] = pluginMap;
+ },
+
+ enable: function () {
+ this.enabled = true;
+
+ //Set flag mentioning that the module is enabling,
+ //so that immediate calls to the defined callbacks
+ //for dependencies do not trigger inadvertent load
+ //with the depCount still being zero.
+ this.enabling = true;
+
+ //Enable each dependency
+ each(this.depMaps, bind(this, function (depMap, i) {
+ var id, mod, handler;
+
+ if (typeof depMap === 'string') {
+ //Dependency needs to be converted to a depMap
+ //and wired up to this module.
+ depMap = makeModuleMap(depMap,
+ (this.map.isDefine ? this.map : this.map.parentMap),
+ false,
+ !this.skipMap);
+ this.depMaps[i] = depMap;
+
+ handler = getOwn(handlers, depMap.id);
+
+ if (handler) {
+ this.depExports[i] = handler(this);
+ return;
+ }
+
+ this.depCount += 1;
+
+ on(depMap, 'defined', bind(this, function (depExports) {
+ this.defineDep(i, depExports);
+ this.check();
+ }));
+
+ if (this.errback) {
+ on(depMap, 'error', this.errback);
+ }
+ }
+
+ id = depMap.id;
+ mod = registry[id];
+
+ //Skip special modules like 'require', 'exports', 'module'
+ //Also, don't call enable if it is already enabled,
+ //important in circular dependency cases.
+ if (!hasProp(handlers, id) && mod && !mod.enabled) {
+ context.enable(depMap, this);
+ }
+ }));
+
+ //Enable each plugin that is used in
+ //a dependency
+ eachProp(this.pluginMaps, bind(this, function (pluginMap) {
+ var mod = getOwn(registry, pluginMap.id);
+ if (mod && !mod.enabled) {
+ context.enable(pluginMap, this);
+ }
+ }));
+
+ this.enabling = false;
+
+ this.check();
+ },
+
+ on: function (name, cb) {
+ var cbs = this.events[name];
+ if (!cbs) {
+ cbs = this.events[name] = [];
+ }
+ cbs.push(cb);
+ },
+
+ emit: function (name, evt) {
+ each(this.events[name], function (cb) {
+ cb(evt);
+ });
+ if (name === 'error') {
+ //Now that the error handler was triggered, remove
+ //the listeners, since this broken Module instance
+ //can stay around for a while in the registry.
+ delete this.events[name];
+ }
+ }
+ };
+
+ function callGetModule(args) {
+ //Skip modules already defined.
+ if (!hasProp(defined, args[0])) {
+ getModule(makeModuleMap(args[0], null, true)).init(args[1], args[2]);
+ }
+ }
+
+ function removeListener(node, func, name, ieName) {
+ //Favor detachEvent because of IE9
+ //issue, see attachEvent/addEventListener comment elsewhere
+ //in this file.
+ if (node.detachEvent && !isOpera) {
+ //Probably IE. If not it will throw an error, which will be
+ //useful to know.
+ if (ieName) {
+ node.detachEvent(ieName, func);
+ }
+ } else {
+ node.removeEventListener(name, func, false);
+ }
+ }
+
+ /**
+ * Given an event from a script node, get the requirejs info from it,
+ * and then removes the event listeners on the node.
+ * @param {Event} evt
+ * @returns {Object}
+ */
+ function getScriptData(evt) {
+ //Using currentTarget instead of target for Firefox 2.0's sake. Not
+ //all old browsers will be supported, but this one was easy enough
+ //to support and still makes sense.
+ var node = evt.currentTarget || evt.srcElement;
+
+ //Remove the listeners once here.
+ removeListener(node, context.onScriptLoad, 'load', 'onreadystatechange');
+ removeListener(node, context.onScriptError, 'error');
+
+ return {
+ node: node,
+ id: node && node.getAttribute('data-requiremodule')
+ };
+ }
+
+ function intakeDefines() {
+ var args;
+
+ //Any defined modules in the global queue, intake them now.
+ takeGlobalQueue();
+
+ //Make sure any remaining defQueue items get properly processed.
+ while (defQueue.length) {
+ args = defQueue.shift();
+ if (args[0] === null) {
+ return onError(makeError('mismatch', 'Mismatched anonymous define() module: ' + args[args.length - 1]));
+ } else {
+ //args are id, deps, factory. Should be normalized by the
+ //define() function.
+ callGetModule(args);
+ }
+ }
+ }
+
+ context = {
+ config: config,
+ contextName: contextName,
+ registry: registry,
+ defined: defined,
+ urlFetched: urlFetched,
+ defQueue: defQueue,
+ Module: Module,
+ makeModuleMap: makeModuleMap,
+ nextTick: req.nextTick,
+
+ /**
+ * Set a configuration for the context.
+ * @param {Object} cfg config object to integrate.
+ */
+ configure: function (cfg) {
+ //Make sure the baseUrl ends in a slash.
+ if (cfg.baseUrl) {
+ if (cfg.baseUrl.charAt(cfg.baseUrl.length - 1) !== '/') {
+ cfg.baseUrl += '/';
+ }
+ }
+
+ //Save off the paths and packages since they require special processing,
+ //they are additive.
+ var pkgs = config.pkgs,
+ shim = config.shim,
+ objs = {
+ paths: true,
+ config: true,
+ map: true
+ };
+
+ eachProp(cfg, function (value, prop) {
+ if (objs[prop]) {
+ if (prop === 'map') {
+ mixin(config[prop], value, true, true);
+ } else {
+ mixin(config[prop], value, true);
+ }
+ } else {
+ config[prop] = value;
+ }
+ });
+
+ //Merge shim
+ if (cfg.shim) {
+ eachProp(cfg.shim, function (value, id) {
+ //Normalize the structure
+ if (isArray(value)) {
+ value = {
+ deps: value
+ };
+ }
+ if ((value.exports || value.init) && !value.exportsFn) {
+ value.exportsFn = context.makeShimExports(value);
+ }
+ shim[id] = value;
+ });
+ config.shim = shim;
+ }
+
+ //Adjust packages if necessary.
+ if (cfg.packages) {
+ each(cfg.packages, function (pkgObj) {
+ var location;
+
+ pkgObj = typeof pkgObj === 'string' ? { name: pkgObj } : pkgObj;
+ location = pkgObj.location;
+
+ //Create a brand new object on pkgs, since currentPackages can
+ //be passed in again, and config.pkgs is the internal transformed
+ //state for all package configs.
+ pkgs[pkgObj.name] = {
+ name: pkgObj.name,
+ location: location || pkgObj.name,
+ //Remove leading dot in main, so main paths are normalized,
+ //and remove any trailing .js, since different package
+ //envs have different conventions: some use a module name,
+ //some use a file name.
+ main: (pkgObj.main || 'main')
+ .replace(currDirRegExp, '')
+ .replace(jsSuffixRegExp, '')
+ };
+ });
+
+ //Done with modifications, assing packages back to context config
+ config.pkgs = pkgs;
+ }
+
+ //If there are any "waiting to execute" modules in the registry,
+ //update the maps for them, since their info, like URLs to load,
+ //may have changed.
+ eachProp(registry, function (mod, id) {
+ //If module already has init called, since it is too
+ //late to modify them, and ignore unnormalized ones
+ //since they are transient.
+ if (!mod.inited && !mod.map.unnormalized) {
+ mod.map = makeModuleMap(id);
+ }
+ });
+
+ //If a deps array or a config callback is specified, then call
+ //require with those args. This is useful when require is defined as a
+ //config object before require.js is loaded.
+ if (cfg.deps || cfg.callback) {
+ context.require(cfg.deps || [], cfg.callback);
+ }
+ },
+
+ makeShimExports: function (value) {
+ function fn() {
+ var ret;
+ if (value.init) {
+ ret = value.init.apply(global, arguments);
+ }
+ return ret || (value.exports && getGlobal(value.exports));
+ }
+ return fn;
+ },
+
+ makeRequire: function (relMap, options) {
+ options = options || {};
+
+ function localRequire(deps, callback, errback) {
+ var id, map, requireMod;
+
+ if (options.enableBuildCallback && callback && isFunction(callback)) {
+ callback.__requireJsBuild = true;
+ }
+
+ if (typeof deps === 'string') {
+ if (isFunction(callback)) {
+ //Invalid call
+ return onError(makeError('requireargs', 'Invalid require call'), errback);
+ }
+
+ //If require|exports|module are requested, get the
+ //value for them from the special handlers. Caveat:
+ //this only works while module is being defined.
+ if (relMap && hasProp(handlers, deps)) {
+ return handlers[deps](registry[relMap.id]);
+ }
+
+ //Synchronous access to one module. If require.get is
+ //available (as in the Node adapter), prefer that.
+ if (req.get) {
+ return req.get(context, deps, relMap);
+ }
+
+ //Normalize module name, if it contains . or ..
+ map = makeModuleMap(deps, relMap, false, true);
+ id = map.id;
+
+ if (!hasProp(defined, id)) {
+ return onError(makeError('notloaded', 'Module name "' +
+ id +
+ '" has not been loaded yet for context: ' +
+ contextName +
+ (relMap ? '' : '. Use require([])')));
+ }
+ return defined[id];
+ }
+
+ //Grab defines waiting in the global queue.
+ intakeDefines();
+
+ //Mark all the dependencies as needing to be loaded.
+ context.nextTick(function () {
+ //Some defines could have been added since the
+ //require call, collect them.
+ intakeDefines();
+
+ requireMod = getModule(makeModuleMap(null, relMap));
+
+ //Store if map config should be applied to this require
+ //call for dependencies.
+ requireMod.skipMap = options.skipMap;
+
+ requireMod.init(deps, callback, errback, {
+ enabled: true
+ });
+
+ checkLoaded();
+ });
+
+ return localRequire;
+ }
+
+ mixin(localRequire, {
+ isBrowser: isBrowser,
+
+ /**
+ * Converts a module name + .extension into an URL path.
+ * *Requires* the use of a module name. It does not support using
+ * plain URLs like nameToUrl.
+ */
+ toUrl: function (moduleNamePlusExt) {
+ var index = moduleNamePlusExt.lastIndexOf('.'),
+ ext = null;
+
+ if (index !== -1) {
+ ext = moduleNamePlusExt.substring(index, moduleNamePlusExt.length);
+ moduleNamePlusExt = moduleNamePlusExt.substring(0, index);
+ }
+
+ return context.nameToUrl(normalize(moduleNamePlusExt,
+ relMap && relMap.id, true), ext);
+ },
+
+ defined: function (id) {
+ return hasProp(defined, makeModuleMap(id, relMap, false, true).id);
+ },
+
+ specified: function (id) {
+ id = makeModuleMap(id, relMap, false, true).id;
+ return hasProp(defined, id) || hasProp(registry, id);
+ }
+ });
+
+ //Only allow undef on top level require calls
+ if (!relMap) {
+ localRequire.undef = function (id) {
+ //Bind any waiting define() calls to this context,
+ //fix for #408
+ takeGlobalQueue();
+
+ var map = makeModuleMap(id, relMap, true),
+ mod = getOwn(registry, id);
+
+ delete defined[id];
+ delete urlFetched[map.url];
+ delete undefEvents[id];
+
+ if (mod) {
+ //Hold on to listeners in case the
+ //module will be attempted to be reloaded
+ //using a different config.
+ if (mod.events.defined) {
+ undefEvents[id] = mod.events;
+ }
+
+ cleanRegistry(id);
+ }
+ };
+ }
+
+ return localRequire;
+ },
+
+ /**
+ * Called to enable a module if it is still in the registry
+ * awaiting enablement. parent module is passed in for context,
+ * used by the optimizer.
+ */
+ enable: function (depMap, parent) {
+ var mod = getOwn(registry, depMap.id);
+ if (mod) {
+ getModule(depMap).enable();
+ }
+ },
+
+ /**
+ * Internal method used by environment adapters to complete a load event.
+ * A load event could be a script load or just a load pass from a synchronous
+ * load call.
+ * @param {String} moduleName the name of the module to potentially complete.
+ */
+ completeLoad: function (moduleName) {
+ var found, args, mod,
+ shim = getOwn(config.shim, moduleName) || {},
+ shExports = shim.exports;
+
+ takeGlobalQueue();
+
+ while (defQueue.length) {
+ args = defQueue.shift();
+ if (args[0] === null) {
+ args[0] = moduleName;
+ //If already found an anonymous module and bound it
+ //to this name, then this is some other anon module
+ //waiting for its completeLoad to fire.
+ if (found) {
+ break;
+ }
+ found = true;
+ } else if (args[0] === moduleName) {
+ //Found matching define call for this script!
+ found = true;
+ }
+
+ callGetModule(args);
+ }
+
+ //Do this after the cycle of callGetModule in case the result
+ //of those calls/init calls changes the registry.
+ mod = getOwn(registry, moduleName);
+
+ if (!found && !hasProp(defined, moduleName) && mod && !mod.inited) {
+ if (config.enforceDefine && (!shExports || !getGlobal(shExports))) {
+ if (hasPathFallback(moduleName)) {
+ return;
+ } else {
+ return onError(makeError('nodefine',
+ 'No define call for ' + moduleName,
+ null,
+ [moduleName]));
+ }
+ } else {
+ //A script that does not call define(), so just simulate
+ //the call for it.
+ callGetModule([moduleName, (shim.deps || []), shim.exportsFn]);
+ }
+ }
+
+ checkLoaded();
+ },
+
+ /**
+ * Converts a module name to a file path. Supports cases where
+ * moduleName may actually be just an URL.
+ * Note that it **does not** call normalize on the moduleName,
+ * it is assumed to have already been normalized. This is an
+ * internal API, not a public one. Use toUrl for the public API.
+ */
+ nameToUrl: function (moduleName, ext) {
+ var paths, pkgs, pkg, pkgPath, syms, i, parentModule, url,
+ parentPath;
+
+ //If a colon is in the URL, it indicates a protocol is used and it is just
+ //an URL to a file, or if it starts with a slash, contains a query arg (i.e. ?)
+ //or ends with .js, then assume the user meant to use an url and not a module id.
+ //The slash is important for protocol-less URLs as well as full paths.
+ if (req.jsExtRegExp.test(moduleName)) {
+ //Just a plain path, not module name lookup, so just return it.
+ //Add extension if it is included. This is a bit wonky, only non-.js things pass
+ //an extension, this method probably needs to be reworked.
+ url = moduleName + (ext || '');
+ } else {
+ //A module that needs to be converted to a path.
+ paths = config.paths;
+ pkgs = config.pkgs;
+
+ syms = moduleName.split('/');
+ //For each module name segment, see if there is a path
+ //registered for it. Start with most specific name
+ //and work up from it.
+ for (i = syms.length; i > 0; i -= 1) {
+ parentModule = syms.slice(0, i).join('/');
+ pkg = getOwn(pkgs, parentModule);
+ parentPath = getOwn(paths, parentModule);
+ if (parentPath) {
+ //If an array, it means there are a few choices,
+ //Choose the one that is desired
+ if (isArray(parentPath)) {
+ parentPath = parentPath[0];
+ }
+ syms.splice(0, i, parentPath);
+ break;
+ } else if (pkg) {
+ //If module name is just the package name, then looking
+ //for the main module.
+ if (moduleName === pkg.name) {
+ pkgPath = pkg.location + '/' + pkg.main;
+ } else {
+ pkgPath = pkg.location;
+ }
+ syms.splice(0, i, pkgPath);
+ break;
+ }
+ }
+
+ //Join the path parts together, then figure out if baseUrl is needed.
+ url = syms.join('/');
+ url += (ext || (/\?/.test(url) ? '' : '.js'));
+ url = (url.charAt(0) === '/' || url.match(/^[\w\+\.\-]+:/) ? '' : config.baseUrl) + url;
+ }
+
+ return config.urlArgs ? url +
+ ((url.indexOf('?') === -1 ? '?' : '&') +
+ config.urlArgs) : url;
+ },
+
+ //Delegates to req.load. Broken out as a separate function to
+ //allow overriding in the optimizer.
+ load: function (id, url) {
+ req.load(context, id, url);
+ },
+
+ /**
+ * Executes a module callack function. Broken out as a separate function
+ * solely to allow the build system to sequence the files in the built
+ * layer in the right sequence.
+ *
+ * @private
+ */
+ execCb: function (name, callback, args, exports) {
+ return callback.apply(exports, args);
+ },
+
+ /**
+ * callback for script loads, used to check status of loading.
+ *
+ * @param {Event} evt the event from the browser for the script
+ * that was loaded.
+ */
+ onScriptLoad: function (evt) {
+ //Using currentTarget instead of target for Firefox 2.0's sake. Not
+ //all old browsers will be supported, but this one was easy enough
+ //to support and still makes sense.
+ if (evt.type === 'load' ||
+ (readyRegExp.test((evt.currentTarget || evt.srcElement).readyState))) {
+ //Reset interactive script so a script node is not held onto for
+ //to long.
+ interactiveScript = null;
+
+ //Pull out the name of the module and the context.
+ var data = getScriptData(evt);
+ context.completeLoad(data.id);
+ }
+ },
+
+ /**
+ * Callback for script errors.
+ */
+ onScriptError: function (evt) {
+ var data = getScriptData(evt);
+ if (!hasPathFallback(data.id)) {
+ return onError(makeError('scripterror', 'Script error', evt, [data.id]));
+ }
+ }
+ };
+
+ context.require = context.makeRequire();
+ return context;
+ }
+
+ /**
+ * Main entry point.
+ *
+ * If the only argument to require is a string, then the module that
+ * is represented by that string is fetched for the appropriate context.
+ *
+ * If the first argument is an array, then it will be treated as an array
+ * of dependency string names to fetch. An optional function callback can
+ * be specified to execute when all of those dependencies are available.
+ *
+ * Make a local req variable to help Caja compliance (it assumes things
+ * on a require that are not standardized), and to give a short
+ * name for minification/local scope use.
+ */
+ req = requirejs = function (deps, callback, errback, optional) {
+
+ //Find the right context, use default
+ var context, config,
+ contextName = defContextName;
+
+ // Determine if have config object in the call.
+ if (!isArray(deps) && typeof deps !== 'string') {
+ // deps is a config object
+ config = deps;
+ if (isArray(callback)) {
+ // Adjust args if there are dependencies
+ deps = callback;
+ callback = errback;
+ errback = optional;
+ } else {
+ deps = [];
+ }
+ }
+
+ if (config && config.context) {
+ contextName = config.context;
+ }
+
+ context = getOwn(contexts, contextName);
+ if (!context) {
+ context = contexts[contextName] = req.s.newContext(contextName);
+ }
+
+ if (config) {
+ context.configure(config);
+ }
+
+ return context.require(deps, callback, errback);
+ };
+
+ /**
+ * Support require.config() to make it easier to cooperate with other
+ * AMD loaders on globally agreed names.
+ */
+ req.config = function (config) {
+ return req(config);
+ };
+
+ /**
+ * Execute something after the current tick
+ * of the event loop. Override for other envs
+ * that have a better solution than setTimeout.
+ * @param {Function} fn function to execute later.
+ */
+ req.nextTick = typeof setTimeout !== 'undefined' ? function (fn) {
+ setTimeout(fn, 4);
+ } : function (fn) { fn(); };
+
+ /**
+ * Export require as a global, but only if it does not already exist.
+ */
+ if (!require) {
+ require = req;
+ }
+
+ req.version = version;
+
+ //Used to filter out dependencies that are already paths.
+ req.jsExtRegExp = /^\/|:|\?|\.js$/;
+ req.isBrowser = isBrowser;
+ s = req.s = {
+ contexts: contexts,
+ newContext: newContext
+ };
+
+ //Create default context.
+ req({});
+
+ //Exports some context-sensitive methods on global require.
+ each([
+ 'toUrl',
+ 'undef',
+ 'defined',
+ 'specified'
+ ], function (prop) {
+ //Reference from contexts instead of early binding to default context,
+ //so that during builds, the latest instance of the default context
+ //with its config gets used.
+ req[prop] = function () {
+ var ctx = contexts[defContextName];
+ return ctx.require[prop].apply(ctx, arguments);
+ };
+ });
+
+ if (isBrowser) {
+ head = s.head = document.getElementsByTagName('head')[0];
+ //If BASE tag is in play, using appendChild is a problem for IE6.
+ //When that browser dies, this can be removed. Details in this jQuery bug:
+ //http://dev.jquery.com/ticket/2709
+ baseElement = document.getElementsByTagName('base')[0];
+ if (baseElement) {
+ head = s.head = baseElement.parentNode;
+ }
+ }
+
+ /**
+ * Any errors that require explicitly generates will be passed to this
+ * function. Intercept/override it if you want custom error handling.
+ * @param {Error} err the error object.
+ */
+ req.onError = function (err) {
+ throw err;
+ };
+
+ /**
+ * Does the request to load a module for the browser case.
+ * Make this a separate function to allow other environments
+ * to override it.
+ *
+ * @param {Object} context the require context to find state.
+ * @param {String} moduleName the name of the module.
+ * @param {Object} url the URL to the module.
+ */
+ req.load = function (context, moduleName, url) {
+ var config = (context && context.config) || {},
+ node;
+ if (isBrowser) {
+ //In the browser so use a script tag
+ node = config.xhtml ?
+ document.createElementNS('http://www.w3.org/1999/xhtml', 'html:script') :
+ document.createElement('script');
+ node.type = config.scriptType || 'text/javascript';
+ node.charset = 'utf-8';
+ node.async = true;
+
+ node.setAttribute('data-requirecontext', context.contextName);
+ node.setAttribute('data-requiremodule', moduleName);
+
+ //Set up load listener. Test attachEvent first because IE9 has
+ //a subtle issue in its addEventListener and script onload firings
+ //that do not match the behavior of all other browsers with
+ //addEventListener support, which fire the onload event for a
+ //script right after the script execution. See:
+ //https://connect.microsoft.com/IE/feedback/details/648057/script-onload-event-is-not-fired-immediately-after-script-execution
+ //UNFORTUNATELY Opera implements attachEvent but does not follow the script
+ //script execution mode.
+ if (node.attachEvent &&
+ //Check if node.attachEvent is artificially added by custom script or
+ //natively supported by browser
+ //read https://github.com/jrburke/requirejs/issues/187
+ //if we can NOT find [native code] then it must NOT natively supported.
+ //in IE8, node.attachEvent does not have toString()
+ //Note the test for "[native code" with no closing brace, see:
+ //https://github.com/jrburke/requirejs/issues/273
+ !(node.attachEvent.toString && node.attachEvent.toString().indexOf('[native code') < 0) &&
+ !isOpera) {
+ //Probably IE. IE (at least 6-8) do not fire
+ //script onload right after executing the script, so
+ //we cannot tie the anonymous define call to a name.
+ //However, IE reports the script as being in 'interactive'
+ //readyState at the time of the define call.
+ useInteractive = true;
+
+ node.attachEvent('onreadystatechange', context.onScriptLoad);
+ //It would be great to add an error handler here to catch
+ //404s in IE9+. However, onreadystatechange will fire before
+ //the error handler, so that does not help. If addEvenListener
+ //is used, then IE will fire error before load, but we cannot
+ //use that pathway given the connect.microsoft.com issue
+ //mentioned above about not doing the 'script execute,
+ //then fire the script load event listener before execute
+ //next script' that other browsers do.
+ //Best hope: IE10 fixes the issues,
+ //and then destroys all installs of IE 6-9.
+ //node.attachEvent('onerror', context.onScriptError);
+ } else {
+ node.addEventListener('load', context.onScriptLoad, false);
+ node.addEventListener('error', context.onScriptError, false);
+ }
+ node.src = url;
+
+ //For some cache cases in IE 6-8, the script executes before the end
+ //of the appendChild execution, so to tie an anonymous define
+ //call to the module name (which is stored on the node), hold on
+ //to a reference to this node, but clear after the DOM insertion.
+ currentlyAddingScript = node;
+ if (baseElement) {
+ head.insertBefore(node, baseElement);
+ } else {
+ head.appendChild(node);
+ }
+ currentlyAddingScript = null;
+
+ return node;
+ } else if (isWebWorker) {
+ //In a web worker, use importScripts. This is not a very
+ //efficient use of importScripts, importScripts will block until
+ //its script is downloaded and evaluated. However, if web workers
+ //are in play, the expectation that a build has been done so that
+ //only one script needs to be loaded anyway. This may need to be
+ //reevaluated if other use cases become common.
+ importScripts(url);
+
+ //Account for anonymous modules
+ context.completeLoad(moduleName);
+ }
+ };
+
+ function getInteractiveScript() {
+ if (interactiveScript && interactiveScript.readyState === 'interactive') {
+ return interactiveScript;
+ }
+
+ eachReverse(scripts(), function (script) {
+ if (script.readyState === 'interactive') {
+ return (interactiveScript = script);
+ }
+ });
+ return interactiveScript;
+ }
+
+ //Look for a data-main script attribute, which could also adjust the baseUrl.
+ if (isBrowser) {
+ //Figure out baseUrl. Get it from the script tag with require.js in it.
+ eachReverse(scripts(), function (script) {
+ //Set the 'head' where we can append children by
+ //using the script's parent.
+ if (!head) {
+ head = script.parentNode;
+ }
+
+ //Look for a data-main attribute to set main script for the page
+ //to load. If it is there, the path to data main becomes the
+ //baseUrl, if it is not already set.
+ dataMain = script.getAttribute('data-main');
+ if (dataMain) {
+ //Set final baseUrl if there is not already an explicit one.
+ if (!cfg.baseUrl) {
+ //Pull off the directory of data-main for use as the
+ //baseUrl.
+ src = dataMain.split('/');
+ mainScript = src.pop();
+ subPath = src.length ? src.join('/') + '/' : './';
+
+ cfg.baseUrl = subPath;
+ dataMain = mainScript;
+ }
+
+ //Strip off any trailing .js since dataMain is now
+ //like a module name.
+ dataMain = dataMain.replace(jsSuffixRegExp, '');
+
+ //Put the data-main script in the files to load.
+ cfg.deps = cfg.deps ? cfg.deps.concat(dataMain) : [dataMain];
+
+ return true;
+ }
+ });
+ }
+
+ /**
+ * The function that handles definitions of modules. Differs from
+ * require() in that a string for the module should be the first argument,
+ * and the function to execute after dependencies are loaded should
+ * return a value to define the module corresponding to the first argument's
+ * name.
+ */
+ define = function (name, deps, callback) {
+ var node, context;
+
+ //Allow for anonymous modules
+ if (typeof name !== 'string') {
+ //Adjust args appropriately
+ callback = deps;
+ deps = name;
+ name = null;
+ }
+
+ //This module may not have dependencies
+ if (!isArray(deps)) {
+ callback = deps;
+ deps = [];
+ }
+
+ //If no name, and callback is a function, then figure out if it a
+ //CommonJS thing with dependencies.
+ if (!deps.length && isFunction(callback)) {
+ //Remove comments from the callback string,
+ //look for require calls, and pull them into the dependencies,
+ //but only if there are function args.
+ if (callback.length) {
+ callback
+ .toString()
+ .replace(commentRegExp, '')
+ .replace(cjsRequireRegExp, function (match, dep) {
+ deps.push(dep);
+ });
+
+ //May be a CommonJS thing even without require calls, but still
+ //could use exports, and module. Avoid doing exports and module
+ //work though if it just needs require.
+ //REQUIRES the function to expect the CommonJS variables in the
+ //order listed below.
+ deps = (callback.length === 1 ? ['require'] : ['require', 'exports', 'module']).concat(deps);
+ }
+ }
+
+ //If in IE 6-8 and hit an anonymous define() call, do the interactive
+ //work.
+ if (useInteractive) {
+ node = currentlyAddingScript || getInteractiveScript();
+ if (node) {
+ if (!name) {
+ name = node.getAttribute('data-requiremodule');
+ }
+ context = contexts[node.getAttribute('data-requirecontext')];
+ }
+ }
+
+ //Always save off evaluating the def call until the script onload handler.
+ //This allows multiple modules to be in a file without prematurely
+ //tracing dependencies, and allows for anonymous module support,
+ //where the module name is not known until the script onload event
+ //occurs. If no context, use the global queue, and get it processed
+ //in the onscript load callback.
+ (context ? context.defQueue : globalDefQueue).push([name, deps, callback]);
+ };
+
+ define.amd = {
+ jQuery: true
+ };
+
+
+ /**
+ * Executes the text. Normally just uses eval, but can be modified
+ * to use a better, environment-specific call. Only used for transpiling
+ * loader plugins, not for plain JS modules.
+ * @param {String} text the text to execute/evaluate.
+ */
+ req.exec = function (text) {
+ /*jslint evil: true */
+ return eval(text);
+ };
+
+ //Set up with config info.
+ req(cfg);
+}(this));
diff --git a/test/lib/testloader.js b/test/lib/testloader.js
new file mode 100644
index 00000000..aa740aab
--- /dev/null
+++ b/test/lib/testloader.js
@@ -0,0 +1,47 @@
+function testLoader(){
+ var jasmineEnv = jasmine.getEnv();
+ jasmineEnv.updateInterval = 1000;
+
+ var htmlReporter = new jasmine.HtmlReporter();
+
+ jasmineEnv.addReporter(htmlReporter);
+
+ jasmineEnv.specFilter = function(spec) {
+ return htmlReporter.specFilter(spec);
+ };
+
+ var currentWindowOnload = window.onload;
+
+ window.onload = function() {
+ var count = 0;
+ var loadCoffee = function(files) {
+ for (var i = 0, len = files.length; i < len; i++) {
+ count++;
+ CoffeeScript.load(files[i], function() {
+ count--;
+ if (!count) {
+ jasmine.getFixtures().fixturesPath = 'fixtures';
+ execJasmine();
+ }
+ });
+ }
+ };
+
+ if (currentWindowOnload) {
+ currentWindowOnload();
+ }
+ loadCoffee([
+ 'waypoints.coffee',
+ 'infinite.coffee',
+ 'sticky.coffee'
+ ]);
+ };
+
+ function execJasmine() {
+ jasmineEnv.execute();
+ }
+
+ if (document.readyState === 'complete'){
+ window.onload();
+ }
+}
diff --git a/test/settings.js b/test/settings.js
new file mode 100644
index 00000000..0cdda718
--- /dev/null
+++ b/test/settings.js
@@ -0,0 +1,9 @@
+/* global jasmine, Waypoint */
+
+'use strict'
+
+jasmine.getFixtures().fixturesPath = 'test/fixtures'
+jasmine.getEnv().defaultTimeoutInterval = 1000
+Waypoint.requestAnimationFrame = function(callback) {
+ callback()
+}
diff --git a/test/spec.js b/test/spec.js
deleted file mode 100755
index 53dddee5..00000000
--- a/test/spec.js
+++ /dev/null
@@ -1,746 +0,0 @@
-//SETTINGS, VARS, UTILITY FUNCTIONS
-jasmine.getFixtures().fixturesPath = 'fixtures';
-$.waypoints.settings.scrollThrottle = 10;
-$.waypoints.settings.resizeThrottle = 20;
-var standardWait = 50,
-wputil = {
- getScrollElement: function() {
- var scrollElement = 'html, body';
- $('html, body').each(function () {
- var initScrollTop = $(this).attr('scrollTop');
- $(this).attr('scrollTop', initScrollTop + 1);
- if ($(this).attr('scrollTop') == initScrollTop + 1) {
- scrollElement = this.nodeName.toLowerCase();
- $(this).attr('scrollTop', initScrollTop);
- return false;
- }
- });
- return $(scrollElement);
- }
-};
-
-// Go tests, go
-describe('jQuery Waypoints', function() {
- var $se,
- $e,
- hit = false;
-
- beforeEach(function() {
- loadFixtures('standard.html');
- $se = wputil.getScrollElement();
- });
-
- describe('.waypoint()', function() {
- beforeEach(function() {
- $e = $('#same1').waypoint();
- spyOnEvent($e, 'waypoint.reached');
- $e.bind('waypoint.reached', function() {
- hit = true;
- });
- });
-
- it('should create a waypoint', function() {
- expect($.waypoints().length).toEqual(1);
- });
-
- it('should be bindable through waypoint.reached', function() {
- runs(function() {
- $se.scrollTop($e.offset().top + 100);
- });
-
- waits(standardWait);
-
- runs(function() {
- expect('waypoint.reached').toHaveBeenTriggeredOn($e);
- expect(hit).toEqual(true);
- });
- });
-
- it('should use the default offset', function() {
- runs(function() {
- $se.scrollTop($e.offset().top - 1);
- });
-
- waits(standardWait);
-
- runs(function() {
- expect('waypoint.reached').not.toHaveBeenTriggeredOn($e);
- expect(hit).toEqual(false);
- $se.scrollTop($e.offset().top);
- });
-
- waits(standardWait);
-
- runs(function() {
- expect('waypoint.reached').toHaveBeenTriggeredOn($e);
- });
- });
- });
-
- describe('.waypoint(callback)', function() {
- var currentDirection;
-
- beforeEach(function() {
- $e = $('#same1').waypoint(function(event, direction) {
- currentDirection = direction;
- hit = true;
- });
- spyOnEvent($e, 'waypoint.reached');
- });
-
- it('should create a waypoint', function() {
- expect($.waypoints().length).toEqual(1);
- });
-
- it('should trigger the callback', function() {
- runs(function() {
- $se.scrollTop($e.offset().top);
- });
-
- waits(standardWait);
-
- runs(function() {
- expect(hit).toEqual(true);
- });
- });
-
- it('should pass correct directions', function() {
- runs(function() {
- $se.scrollTop($e.offset().top);
- });
-
- waits(standardWait);
-
- runs(function() {
- expect(currentDirection).toEqual('down');
- $se.scrollTop($e.offset().top - 1);
- });
-
- waits(standardWait);
-
- runs(function() {
- expect(currentDirection).toEqual('up');
- });
- });
- });
-
- describe('.waypoint(options)', function() {
- beforeEach(function() {
- $e = $('#same1');
- spyOnEvent($e, 'waypoint.reached');
- });
-
- it('should create a waypoint', function() {
- $e.waypoint({
- offset: 1,
- triggerOnce: true
- });
- expect($.waypoints().length).toEqual(1);
- });
-
- it('should respect a px offset', function() {
- runs(function() {
- $e.waypoint({
- offset: 50
- });
- $se.scrollTop($e.offset().top - 51);
- });
-
- waits(standardWait);
-
- runs(function() {
- expect('waypoint.reached').not.toHaveBeenTriggeredOn($e);
- $se.scrollTop($e.offset().top - 50);
- });
-
- waits(standardWait);
-
- runs(function() {
- expect('waypoint.reached').toHaveBeenTriggeredOn($e);
- });
- });
-
- it('should respect a % offset', function() {
- runs(function() {
- $e.waypoint({
- offset: '37%'
- });
- $se.scrollTop($e.offset().top - $.waypoints('viewportHeight') * .37 - 1);
- });
-
- waits(standardWait);
-
- runs(function() {
- expect('waypoint.reached').not.toHaveBeenTriggeredOn($e);
- $se.scrollTop($e.offset().top - $.waypoints('viewportHeight') * .37);
- });
-
- waits(standardWait);
-
- runs(function() {
- expect('waypoint.reached').toHaveBeenTriggeredOn($e);
- });
- });
-
- it('should respect a function offset', function() {
- runs(function() {
- $e.waypoint({
- offset: function() {
- return $(this).height() * -1;
- }
- });
- $se.scrollTop($e.offset().top + $e.height() - 1);
- });
-
- waits(standardWait);
-
- runs(function() {
- expect('waypoint.reached').not.toHaveBeenTriggeredOn($e);
- $se.scrollTop($e.offset().top + $e.height());
- });
-
- waits(standardWait);
-
- runs(function() {
- expect('waypoint.reached').toHaveBeenTriggeredOn($e);
- });
- });
-
- it('should respect the bottom-in-view function alias', function() {
- var inview = $e.offset().top - $.waypoints('viewportHeight') + $e.outerHeight();
-
- runs(function() {
- $e.waypoint({
- offset: 'bottom-in-view'
- });
- $se.scrollTop(inview - 1);
- });
-
- waits(standardWait);
-
- runs(function() {
- expect('waypoint.reached').not.toHaveBeenTriggeredOn($e);
- $se.scrollTop(inview);
- });
-
- waits(standardWait);
-
- runs(function() {
- expect('waypoint.reached').toHaveBeenTriggeredOn($e);
- });
- });
-
- it('should destroy the waypoint if triggerOnce is true', function() {
- runs(function() {
- $e.waypoint({
- triggerOnce: true
- });
- $se.scrollTop($e.offset().top);
- });
-
- waits(standardWait);
-
- runs(function() {
- expect($.waypoints().length).toBeFalsy();
- });
- });
-
- it('should trigger if continuous is true and waypoint is not last', function() {
- var $f = $('#near1'),
- $g = $('#near2'),
- hitcount = 0;
-
- spyOnEvent($f, 'waypoint.reached');
-
- runs(function() {
- $e.add($f).add($g).waypoint(function() {
- hitcount++;
- });
- $se.scrollTop($g.offset().top);
- });
-
- waits(standardWait);
-
- runs(function() {
- expect(hitcount).toEqual(3);
- });
- });
-
- it('should not trigger if continuous is false and waypoint is not last', function() {
- var $f = $('#near1'),
- $g = $('#near2'),
- hitcount = 0;
-
- spyOnEvent($f, 'waypoint.reached');
-
- runs(function() {
- $e.add($f).add($g).waypoint(function() {
- hitcount++;
- });
- $f.waypoint({
- continuous: false
- });
- $se.scrollTop($g.offset().top);
- });
-
- waits(standardWait);
-
- runs(function() {
- expect(hitcount).toEqual(2);
- });
- });
-
- it('should trigger if continuous is false but the waypoint is last', function() {
- var $f = $('#near1'),
- $g = $('#near2'),
- hitcount = 0;
-
- spyOnEvent($f, 'waypoint.reached');
-
- runs(function() {
- $e.add($f).add($g).waypoint(function() {
- hitcount++;
- });
- $g.waypoint({
- continuous: false
- });
- $se.scrollTop($g.offset().top);
- });
-
- waits(standardWait);
-
- runs(function() {
- expect(hitcount).toEqual(3);
- });
- });
-
- it('should use the handler option if provided', function() {
- var hitcount = 0;
-
- runs(function() {
- $e.waypoint({
- handler: function(e, dir) {
- hitcount++;
- }
- });
- $se.scrollTop($e.offset().top);
- });
-
- waits(standardWait);
-
- runs(function() {
- expect(hitcount).toEqual(1);
- });
- });
- });
-
- describe('.waypoint(callback, options)', function() {
- beforeEach(function() {
- $e = $('#same1').waypoint(function() {
- hit = true;
- }, {
- offset:-1
- });
- spyOnEvent($e, 'waypoint.reached');
- });
-
- it('should create a waypoint', function() {
- expect($.waypoints().length).toEqual(1);
- });
-
- it('should respect options', function() {
- runs(function() {
- $se.scrollTop($e.offset().top);
- });
-
- waits(standardWait);
-
- runs(function() {
- expect('waypoint.reached').not.toHaveBeenTriggeredOn($e);
- $se.scrollTop($e.offset().top + 1);
- });
-
- waits(standardWait);
-
- runs(function() {
- expect('waypoint.reached').toHaveBeenTriggeredOn($e);
- });
- });
-
- it('should fire callback', function() {
- runs(function() {
- $se.scrollTop($e.offset().top + 1);
- });
-
- waits(standardWait);
-
- runs(function() {
- expect(hit).toEqual(true);
- });
- });
- });
-
- describe('.waypoint("remove")', function() {
- beforeEach(function() {
- $e = $('#same1').waypoint(function() {
- hit = true;
- });
- spyOnEvent($e, 'waypoint.reached');
- $e.waypoint('remove');
- });
-
- it('should remove waypoint from list of waypoints', function() {
- expect($.waypoints().length).toBeFalsy();
- });
-
- it('should no longer trigger waypoint.reached', function() {
- runs(function() {
- $se.scrollTop($e.offset().top);
- });
-
- waits(standardWait);
-
- runs(function() {
- expect('waypoint.reached').not.toHaveBeenTriggeredOn($e);
- });
- });
-
- it('should preserve callbacks if .waypoint recalled', function() {
- runs(function() {
- $e.waypoint();
- $se.scrollTop($e.offset().top);
- });
-
- waits(standardWait);
-
- runs(function() {
- expect(hit).toEqual(true);
- });
- });
- });
-
- describe('.waypoint("destroy")', function() {
- beforeEach(function() {
- $e = $('#same1').waypoint(function() {
- hit = true;
- });
- spyOnEvent($e, 'waypoint.reached');
- $e.waypoint('destroy');
- });
-
- it('should remove waypoint from list of waypoints', function() {
- expect($.waypoints().length).toBeFalsy();
- });
-
- it('should no longer trigger waypoint.reached', function() {
- runs(function() {
- $se.scrollTop($e.offset().top);
- });
-
- waits(standardWait);
-
- runs(function() {
- expect('waypoint.reached').not.toHaveBeenTriggeredOn($e);
- });
- });
-
- it('should not preserve callbacks if .waypoint recalled', function() {
- runs(function() {
- $e.waypoint();
- $se.scrollTop($e.offset().top);
- });
-
- waits(standardWait);
-
- runs(function() {
- expect(hit).toEqual(false);
- });
- });
- });
-
- describe('$.waypoints()', function() {
- it('should start as an empty jQuery object', function() {
- expect($.waypoints().length).toBeFalsy();
- expect($.waypoints()).toEqual($());
- });
-
- it('should return correct waypoint elements', function() {
- $e = $('#same1').waypoint();
- expect($.waypoints().get()).toEqual($e.get());
- });
-
- it('should work with multiple waypoints', function() {
- $e = $('.sameposition, #top').waypoint();
- expect($.waypoints().get()).toEqual($e.get());
- $e = $e.add($('#near1').waypoint());
- expect($.waypoints().get()).toEqual($e.get());
- });
- });
-
- describe('$.waypoints("refresh")', function() {
- var currentDirection;
-
- beforeEach(function() {
- $e = $('#same1').waypoint(function(event, direction) {
- currentDirection = direction;
- });
- spyOnEvent($e, 'waypoint.reached');
- });
-
- it('should trigger waypoint.reached when refresh crosses current scroll', function() {
- runs(function() {
- $se.scrollTop($e.offset().top - 1);
- });
-
- waits(standardWait);
-
- runs(function() {
- $e.css('top', ($e.offset().top - 50) + 'px');
- $.waypoints('refresh');
- expect(currentDirection).toEqual('down');
- $e.css('top', $e.offset().top + 50 + 'px');
- $.waypoints('refresh');
- expect(currentDirection).toEqual('up');
- });
- });
-
- it('should not trigger waypoint.reached when refresh crosses current scroll if prevented by option', function() {
- runs(function() {
- $se.scrollTop($e.offset().top - 1);
- $e.waypoint({ onlyOnScroll:true });
- });
-
- waits(standardWait);
-
- runs(function() {
- $e.css('top', ($e.offset().top - 50) + 'px');
- $.waypoints('refresh');
- expect('waypoint.reached').not.toHaveBeenTriggeredOn($e);
- $e.css('top', $e.offset().top + 50 + 'px');
- $.waypoints('refresh');
- expect('waypoint.reached').not.toHaveBeenTriggeredOn($e);
- });
- });
-
- it('should update the offset', function() {
- runs(function() {
- $se.scrollTop($e.offset().top - 51);
- $e.css('top', ($e.offset().top - 50) + 'px');
- $.waypoints('refresh');
- });
-
- waits(standardWait);
-
- runs(function() {
- expect('waypoint.reached').not.toHaveBeenTriggeredOn($e);
- $se.scrollTop($e.offset().top);
- });
-
- waits(standardWait);
-
- runs(function() {
- expect('waypoint.reached').toHaveBeenTriggeredOn($e);
- });
- });
- });
-
- describe('$.waypoints("viewportHeight")', function() {
- it('should return window innerheight if it exists', function() {
- if (window.innerHeight) {
- expect($.waypoints('viewportHeight')).toEqual(window.innerHeight);
- }
- else {
- expect($.waypoints('viewportHeight')).toEqual($(window).height());
- }
- });
- });
-
- describe('$.waypoints.settings', function() {
- var count = 0;
- var curID;
-
- beforeEach(function() {
- $('.sameposition, #near1, #near2').waypoint(function() {
- count++;
- curID = $(this).attr('id');
- });
- });
-
- it('should throttle the scroll check', function() {
- runs(function() {
- $se.scrollTop($('#same1').offset().top);
- expect(count).toEqual(0);
- });
-
- waits(standardWait);
-
- runs(function() {
- expect(count).toEqual(2);
- });
- });
-
- it('should throttle the resize event and call refresh', function() {
- runs(function() {
- $('#same1').css('top', "-1000px");
- $(window).resize();
- expect(count).toEqual(0);
- });
-
- waits(standardWait);
-
- runs(function() {
- expect(count).toEqual(1);
- });
- });
-
- afterEach(function() {
- count = 0;
- });
- });
-
- describe('non-window scroll context', function() {
- var $inner;
-
- beforeEach(function() {
- $inner = $('#bottom');
- });
-
- it('should trigger the waypoint within its context', function() {
- $e = $('#inner3').waypoint({
- context: '#bottom'
- });
-
- runs(function() {
- spyOnEvent($e, 'waypoint.reached');
- $inner.scrollTop(199);
- });
-
- waits(standardWait);
-
- runs(function() {
- expect('waypoint.reached').not.toHaveBeenTriggeredOn($e);
- $inner.scrollTop(200);
- });
-
- waits(standardWait);
-
- runs(function() {
- expect('waypoint.reached').toHaveBeenTriggeredOn($e);
- });
- });
-
- it('should respect % offsets within context', function() {
- $e = $('#inner3').waypoint({
- context: '#bottom',
- offset: '100%'
- });
-
- runs(function() {
- spyOnEvent($e, 'waypoint.reached');
- $inner.scrollTop(149);
- });
-
- waits(standardWait);
-
- runs(function() {
- expect('waypoint.reached').not.toHaveBeenTriggeredOn($e);
- $inner.scrollTop(150);
- });
-
- waits(standardWait);
-
- runs(function() {
- expect('waypoint.reached').toHaveBeenTriggeredOn($e);
- });
- });
-
- it('should respect % offsets within context', function() {
- $e = $('#inner3').waypoint({
- context: '#bottom',
- offset: function() {
- return $(this).height() / 2;
- }
- });
-
- runs(function() {
- spyOnEvent($e, 'waypoint.reached');
- $inner.scrollTop(149);
- });
-
- waits(standardWait);
-
- runs(function() {
- expect('waypoint.reached').not.toHaveBeenTriggeredOn($e);
- $inner.scrollTop(150);
- });
-
- waits(standardWait);
-
- runs(function() {
- expect('waypoint.reached').toHaveBeenTriggeredOn($e);
- });
- });
-
- it('should respect bottom-in-view alias', function() {
- $e = $('#inner3').waypoint({
- context: '#bottom',
- offset: 'bottom-in-view'
- });
-
- runs(function() {
- spyOnEvent($e, 'waypoint.reached');
- $inner.scrollTop(249);
- });
-
- waits(standardWait);
-
- runs(function() {
- expect('waypoint.reached').not.toHaveBeenTriggeredOn($e);
- $inner.scrollTop(250);
- });
-
- waits(standardWait);
-
- runs(function() {
- expect('waypoint.reached').toHaveBeenTriggeredOn($e);
- });
- });
-
- afterEach(function() {
- $inner.scrollTop(0);
- });
- });
-
- afterEach(function() {
- $.waypoints().waypoint('destroy');
- $se.scrollTop(0);
- hit = false;
- waits(standardWait);
- });
-
- describe('Waypoints added after load, Issue #28', function() {
- it('should trigger down on new but already reached waypoints', function() {
- runs(function() {
- $e = $('#pretop');
- spyOnEvent($e, 'waypoint.reached');
- });
-
- runs(function() {
- $e.waypoint(function(e, dir) {
- if (dir === 'down') {
- hit = true;
- }
- });
- });
-
- waits(standardWait);
-
- runs(function() {
- expect('waypoint.reached').toHaveBeenTriggeredOn($e);
- expect(hit).toBeTruthy();
- });
- });
-
-
- });
-});
diff --git a/test/sticky-spec.js b/test/sticky-spec.js
new file mode 100644
index 00000000..b6128a0b
--- /dev/null
+++ b/test/sticky-spec.js
@@ -0,0 +1,117 @@
+'use strict'
+/* global
+ * describe, it, beforeEach, afterEach, expect, spyOn, waits, runs,
+ * waitsFor, loadFixtures, Waypoint, jasmine
+ */
+
+describe('Waypoint Sticky Shortcut', function() {
+ var $ = window.jQuery
+ var $scroller = $(window)
+ var $sticky, waypoint, handlerSpy
+
+ beforeEach(function() {
+ loadFixtures('sticky.html')
+ $sticky = $('.sticky')
+ })
+
+ describe('with default options', function() {
+ beforeEach(function() {
+ handlerSpy = jasmine.createSpy('on handler')
+ waypoint = new Waypoint.Sticky({
+ element: $sticky[0],
+ handler: handlerSpy
+ })
+ })
+
+ afterEach(function() {
+ if (waypoint) {
+ waypoint.destroy()
+ }
+ $scroller.scrollTop(0)
+ })
+
+ describe('on init', function() {
+ afterEach(function() {
+ waypoint.destroy()
+ })
+
+ it('returns an instance of the Waypoint.Sticky class', function() {
+ expect(waypoint instanceof Waypoint.Sticky).toBeTruthy()
+ })
+
+ it('wraps the sticky element on init', function() {
+ expect($sticky.parent()).toHaveClass('sticky-wrapper')
+ })
+
+ describe('when sticky element is scrolled to', function() {
+ beforeEach(function() {
+ runs(function() {
+ $scroller.scrollTop($sticky.offset().top)
+ })
+ waitsFor(function() {
+ return $sticky.hasClass('stuck')
+ }, 'stuck class to apply')
+ })
+
+ it('adds/removes stuck class', function() {
+ runs(function() {
+ $scroller.scrollTop($scroller.scrollTop() - 1)
+ })
+ waitsFor(function() {
+ return !$sticky.hasClass('stuck')
+ })
+ })
+
+ it('gives the wrapper the same height as the sticky element', function() {
+ expect($sticky.parent().height()).toEqual($sticky.outerHeight())
+ })
+
+ it('executes handler option after stuck class applied', function() {
+ expect(handlerSpy).toHaveBeenCalled()
+ })
+ })
+ })
+
+ describe('#destroy', function() {
+ beforeEach(function() {
+ runs(function() {
+ $scroller.scrollTop($sticky.offset().top)
+ })
+ waitsFor(function() {
+ return handlerSpy.callCount
+ })
+ runs(function() {
+ waypoint.destroy()
+ })
+ })
+
+ it('unwraps the sticky element', function() {
+ expect($sticky.parent()).not.toHaveClass('sticky-wrapper')
+ })
+
+ it('removes the stuck class', function() {
+ expect($sticky).not.toHaveClass('stuck')
+ })
+ })
+ })
+
+ describe('with wrapper false', function() {
+ beforeEach(function() {
+ waypoint = new Waypoint.Sticky({
+ element: $sticky[0],
+ handler: handlerSpy,
+ wrapper: false
+ })
+ })
+
+ it('does not wrap the sticky element', function() {
+ expect($sticky.parent()).not.toHaveClass('sticky-wrapper')
+ })
+
+ it('does not unwrap on destroy', function() {
+ var parent = waypoint.wrapper
+ waypoint.destroy()
+ expect(parent).toBe(waypoint.wrapper)
+ })
+ })
+})
diff --git a/test/waypoint-spec.js b/test/waypoint-spec.js
new file mode 100644
index 00000000..8ffa6580
--- /dev/null
+++ b/test/waypoint-spec.js
@@ -0,0 +1,557 @@
+'use strict'
+/* global
+ * describe, it, beforeEach, afterEach, expect, spyOn, waits, runs,
+ * waitsFor, loadFixtures, Waypoint
+ */
+
+window.jQuery.each(Waypoint.adapters, function(i, adapter) {
+ describe(adapter.name + ' adapter: ', function() {
+ describe('Waypoint', function() {
+ var $ = window.jQuery
+ var standard = 50
+ var hit, $scroller, waypoint, $target, returnValue
+
+ function setHitTrue() {
+ hit = true
+ }
+
+ function hitToBeTrue() {
+ return hit
+ }
+
+ beforeEach(function() {
+ Waypoint.Adapter = adapter.Adapter
+ loadFixtures('standard.html')
+ $scroller = $(window)
+ hit = false
+ waypoint = null
+ })
+
+ afterEach(function() {
+ Waypoint.destroyAll()
+ $scroller.scrollTop(0).scrollLeft(0)
+ })
+
+ describe('new Waypoint()', function() {
+ it('errors out', function() {
+ expect(function() {
+ waypoint = new Waypoint()
+ }).toThrow()
+ })
+ })
+
+ describe('new Waypoint(options)', function() {
+ it('returns an instance of the Waypoint class', function() {
+ waypoint = new Waypoint({
+ element: document.getElementById('same1'),
+ handler: function() {}
+ })
+ expect(waypoint instanceof Waypoint).toBeTruthy()
+ })
+
+ it('requires the element option', function() {
+ expect(function() {
+ waypoint = new Waypoint({
+ handler: function() {}
+ })
+ }).toThrow()
+ })
+
+ it('requires the handler option', function() {
+ expect(function() {
+ waypoint = new Waypoint({
+ element: document.getElementById('same1')
+ })
+ }).toThrow()
+ })
+
+ it('triggers down on new already-reached waypoints', function() {
+ runs(function() {
+ $target = $('#same2')
+ $scroller.scrollTop($target.offset().top + 1)
+ waypoint = new Waypoint({
+ element: $target[0],
+ handler: function(direction) {
+ hit = direction === 'down'
+ }
+ })
+ })
+ waitsFor(hitToBeTrue, 'callback to trigger')
+ })
+ })
+
+ describe('handler option', function() {
+ var currentDirection
+
+ beforeEach(function() {
+ $target = $('#same1')
+ currentDirection = null
+ waypoint = new Waypoint({
+ element: $target[0],
+ handler: function(direction) {
+ currentDirection = direction
+ }
+ })
+ })
+
+ it('triggers with direction parameter', function() {
+ runs(function() {
+ $scroller.scrollTop($target.offset().top)
+ })
+ waitsFor(function() {
+ return currentDirection === 'down'
+ }, 'down to trigger')
+ runs(function() {
+ $scroller.scrollTop($target.offset().top - 1)
+ })
+ waitsFor(function() {
+ return currentDirection === 'up'
+ }, 'up to trigger')
+ })
+ })
+
+ describe('offset option', function() {
+ beforeEach(function() {
+ $target = $('#same1')
+ })
+
+ it('takes a px offset', function(){
+ runs(function() {
+ waypoint = new Waypoint({
+ element: $target[0],
+ handler: setHitTrue,
+ offset: 50
+ })
+ $scroller.scrollTop($target.offset().top - 51)
+ expect(hit).toBeFalsy()
+ $scroller.scrollTop($target.offset().top - 50)
+ })
+ waitsFor(hitToBeTrue, 'callback to trigger')
+ })
+
+ it('takes a % offset', function() {
+ var trigger = $target.offset().top - Waypoint.viewportHeight() * 0.37
+ runs(function() {
+ waypoint = new Waypoint({
+ element: $target[0],
+ handler: setHitTrue,
+ offset: '37%'
+ })
+ $scroller.scrollTop(trigger - 1)
+ expect(hit).toBeFalsy()
+ $scroller.scrollTop(trigger)
+ })
+ waitsFor(hitToBeTrue, 'callback to trigger')
+ })
+
+ it('takes a function offset', function() {
+ runs(function() {
+ waypoint = new Waypoint({
+ element: $target[0],
+ handler: setHitTrue,
+ offset: function() {
+ return -$(this.element).height()
+ }
+ })
+ $scroller.scrollTop($target.offset().top + $target.height() - 1)
+ expect(hit).toBeFalsy()
+ $scroller.scrollTop($target.offset().top + $target.height())
+ })
+ waitsFor(hitToBeTrue, 'callback to trigger')
+ })
+
+ it('takes a bottom-in-view function alias', function() {
+ var top = $target.offset().top
+ var height = $target.outerHeight()
+ var windowHeight = Waypoint.viewportHeight()
+ var inview = top + height - windowHeight
+ runs(function() {
+ waypoint = new Waypoint({
+ element: $target[0],
+ handler: setHitTrue,
+ offset: 'bottom-in-view'
+ })
+ $scroller.scrollTop(inview - 1)
+ expect(hit).toBeFalsy()
+ $scroller.scrollTop(inview)
+ })
+ waitsFor(hitToBeTrue, 'callback to trigger')
+ })
+ })
+
+ describe('context option', function() {
+ beforeEach(function() {
+ $scroller = $('#bottom')
+ $target = $('#inner3')
+ })
+
+ it('works with px offset', function() {
+ waypoint = new Waypoint({
+ element: $target[0],
+ handler: setHitTrue,
+ context: $scroller[0],
+ offset: 10
+ })
+ runs(function() {
+ $scroller.scrollTop(189)
+ expect(hit).toBeFalsy()
+ $scroller.scrollTop(190)
+ })
+ waitsFor(hitToBeTrue, 'callback to trigger')
+ })
+
+ it('works with % offset', function() {
+ waypoint = new Waypoint({
+ element: $target[0],
+ handler: setHitTrue,
+ context: $scroller[0],
+ offset: '100%'
+ })
+ runs(function() {
+ $scroller.scrollTop(149)
+ expect(hit).toBeFalsy()
+ $scroller.scrollTop(150)
+ })
+ waitsFor(hitToBeTrue, 'callback to trigger')
+ })
+
+ it('works with function offset', function() {
+ waypoint = new Waypoint({
+ element: $target[0],
+ handler: setHitTrue,
+ context: $scroller[0],
+ offset: function() {
+ return $(this.element).height() / 2
+ }
+ })
+ runs(function() {
+ $scroller.scrollTop(149)
+ expect(hit).toBeFalsy()
+ $scroller.scrollTop(150)
+ })
+ waitsFor(hitToBeTrue, 'callback to trigger')
+ })
+
+ it('works with bottom-in-view offset alias', function() {
+ waypoint = new Waypoint({
+ element: $target[0],
+ handler: setHitTrue,
+ context: $scroller[0],
+ offset: 'bottom-in-view'
+ })
+ runs(function() {
+ $scroller.scrollTop(249)
+ expect(hit).toBeFalsy()
+ $scroller.scrollTop(250)
+ })
+ waitsFor(hitToBeTrue, 'callback to trigger')
+ })
+ })
+
+ describe('horizontal option', function() {
+ var currentDirection
+
+ beforeEach(function() {
+ currentDirection = null
+ $target = $('#same1')
+ waypoint = new Waypoint({
+ element: $target[0],
+ horizontal: true,
+ handler: function(direction) {
+ currentDirection = direction
+ }
+ })
+ })
+
+ it('triggers right/left directions', function() {
+ runs(function() {
+ $scroller.scrollLeft($target.offset().left)
+ })
+ waitsFor(function() {
+ return currentDirection === 'right'
+ }, 'right direction to trigger')
+ runs(function() {
+ $scroller.scrollLeft($target.offset().left - 1)
+ })
+ waitsFor(function() {
+ return currentDirection === 'left'
+ })
+ })
+ })
+
+ describe('continuous option', function() {
+ var $later, laterWaypoint, hitCount, hitWaypoint
+
+ function incrementHitCount() {
+ hitCount += 1
+ hitWaypoint = this
+ }
+
+ beforeEach(function() {
+ $target = $('#same1')
+ $later = $('#near1')
+ hitCount = 0
+ waypoint = new Waypoint({
+ element: $target[0],
+ continuous: false,
+ handler: incrementHitCount
+ })
+ laterWaypoint = new Waypoint({
+ element: $later[0],
+ continuous: false,
+ handler: incrementHitCount
+ })
+ })
+
+ it('does not trigger the earlier waypoint', function() {
+ runs(function() {
+ $scroller.scrollTop($later.offset().top)
+ })
+ waitsFor(function() {
+ return hitCount
+ }, 'later callback to trigger')
+ runs(function() {
+ expect(hitCount).toEqual(1)
+ expect(hitWaypoint).toEqual(laterWaypoint)
+ })
+ })
+
+ it('prevents earlier trigger on refresh', function() {
+ runs(function() {
+ $target.css('top', '-1px')
+ $later.css('top', '-2px')
+ Waypoint.refreshAll()
+ })
+ waitsFor(function() {
+ return hitCount
+ }, 'later callback to trigger')
+ runs(function() {
+ expect(hitCount).toEqual(1)
+ expect(hitWaypoint).toEqual(waypoint)
+ })
+ })
+ })
+
+ describe('with window as the waypoint element', function() {
+ beforeEach(function() {
+ $target = $(window)
+ waypoint = new Waypoint({
+ element: $target[0],
+ offset: -$target.height(),
+ handler: setHitTrue
+ })
+ })
+
+ it('triggers waypoint', function() {
+ runs(function() {
+ $target.scrollTop($target.height() + 1)
+ })
+ waitsFor(hitToBeTrue, 'callback to trigger')
+ })
+ })
+
+ describe('#disable()', function() {
+ beforeEach(function() {
+ $target = $('#same1')
+ waypoint = new Waypoint({
+ element: $target[0],
+ handler: setHitTrue
+ })
+ returnValue = waypoint.disable()
+ })
+
+ it('returns the same waypoint object for chaining', function() {
+ expect(returnValue).toEqual(waypoint)
+ })
+
+ it('disables callback triggers', function() {
+ runs(function() {
+ $scroller.scrollTop($target.offset().top)
+ })
+ waits(standard)
+ runs(function() {
+ expect(hit).toBeFalsy()
+ })
+ })
+ })
+
+ describe('#enable()', function() {
+ beforeEach(function() {
+ $target = $('#same1')
+ waypoint = new Waypoint({
+ element: $target[0],
+ handler: setHitTrue
+ })
+ waypoint.disable()
+ returnValue = waypoint.enable()
+ })
+
+ it('returns the same waypoint instance for chaining', function() {
+ expect(returnValue).toEqual(waypoint)
+ })
+
+ it('enables callback triggers', function() {
+ runs(function() {
+ $scroller.scrollTop($target.offset().top)
+ })
+ waitsFor(hitToBeTrue, 'callback to trigger')
+ })
+ })
+
+ describe('#destroy()', function() {
+ beforeEach(function() {
+ $target = $('#same1')
+ waypoint = new Waypoint({
+ element: $target[0],
+ handler: setHitTrue
+ })
+ returnValue = waypoint.destroy()
+ })
+
+ it('returns undefined', function() {
+ expect(returnValue).toBeUndefined()
+ })
+
+ it('no longer triggers callbacks', function() {
+ runs(function() {
+ $scroller.scrollTop($target.offset().top)
+ })
+ waits(standard)
+ runs(function() {
+ expect(hit).toBeFalsy()
+ })
+ })
+ })
+
+ describe('#previous', function() {
+ beforeEach(function() {
+ $target = $('#same1')
+ waypoint = new Waypoint({
+ element: $target[0],
+ handler: setHitTrue
+ })
+ })
+
+ it('calls previous on the waypoint group', function() {
+ spyOn(waypoint.group, 'previous')
+ waypoint.previous()
+ expect(waypoint.group.previous).toHaveBeenCalledWith(waypoint)
+ })
+
+ it('returns the group call results', function() {
+ expect(waypoint.previous()).toBeNull()
+ })
+ })
+
+ describe('#next', function() {
+ beforeEach(function() {
+ $target = $('#same1')
+ waypoint = new Waypoint({
+ element: $target[0],
+ handler: setHitTrue
+ })
+ })
+
+ it('calls next on the waypoint group', function() {
+ spyOn(waypoint.group, 'next')
+ waypoint.next()
+ expect(waypoint.group.next).toHaveBeenCalledWith(waypoint)
+ })
+
+ it('returns the group call results', function() {
+ expect(waypoint.next()).toBeNull()
+ })
+ })
+
+ describe('Waypoint.viewportHeight()', function() {
+ it('returns window innerHeight if it exists', function() {
+ var height = Waypoint.viewportHeight()
+ if (window.innerHeight) {
+ expect(height).toEqual(window.innerHeight)
+ }
+ else {
+ expect(height).toEqual(document.documentElement.clientHeight)
+ }
+ })
+ })
+
+ describe('Waypoint.viewportWidth()', function() {
+ it('returns client width', function() {
+ var clientWidth = document.documentElement.clientWidth
+ expect(Waypoint.viewportWidth()).toEqual(clientWidth)
+ })
+ })
+
+ describe('Waypoint.refreshAll()', function() {
+ it('is an alias for Waypoint.Context.refreshAll', function() {
+ spyOn(Waypoint.Context, 'refreshAll')
+ Waypoint.refreshAll()
+ expect(Waypoint.Context.refreshAll).toHaveBeenCalled()
+ })
+ })
+
+ describe('Waypoint.destroyAll()', function() {
+ it('calls destroy on all waypoints', function() {
+ var secondWaypoint = new Waypoint({
+ element: $('#same1')[0],
+ handler: function() {}
+ })
+ waypoint = new Waypoint({
+ element: $('#same1')[0],
+ handler: function() {}
+ })
+ spyOn(secondWaypoint, 'destroy').andCallThrough()
+ spyOn(waypoint, 'destroy').andCallThrough()
+ Waypoint.destroyAll()
+ expect(secondWaypoint.destroy).toHaveBeenCalled()
+ expect(waypoint.destroy).toHaveBeenCalled()
+ })
+ })
+
+ describe('Waypoint.disableAll()', function() {
+ it('calls disable on all waypoints', function() {
+ var secondWaypoint = new Waypoint({
+ element: $('#same1')[0],
+ handler: function() {}
+ })
+ waypoint = new Waypoint({
+ element: $('#same1')[0],
+ handler: function() {}
+ })
+ spyOn(secondWaypoint, 'disable').andCallThrough()
+ spyOn(waypoint, 'disable').andCallThrough()
+ Waypoint.disableAll()
+ expect(secondWaypoint.disable).toHaveBeenCalled()
+ expect(waypoint.disable).toHaveBeenCalled()
+ })
+ })
+
+ describe('Waypoint.enableAll()', function() {
+ var secondWaypoint
+
+ beforeEach(function() {
+ secondWaypoint = new Waypoint({
+ element: $('#same1')[0],
+ handler: function() {}
+ })
+ waypoint = new Waypoint({
+ element: $('#same1')[0],
+ handler: function() {}
+ })
+ Waypoint.disableAll()
+ spyOn(Waypoint.Context, 'refreshAll').andCallThrough()
+ Waypoint.enableAll()
+ })
+
+ it('sets enabled on all waypoints', function() {
+ expect(secondWaypoint.enabled).toBeTruthy()
+ expect(waypoint.enabled).toBeTruthy()
+ })
+
+ it('refreshes all contexts', function() {
+ expect(Waypoint.Context.refreshAll).toHaveBeenCalled()
+ })
+ })
+ })
+ })
+})
diff --git a/testem.json b/testem.json
new file mode 100644
index 00000000..21f89a03
--- /dev/null
+++ b/testem.json
@@ -0,0 +1,24 @@
+{
+ "framework": "jasmine",
+ "launch_in_dev": [
+ "PhantomJS"
+ ],
+ "launch_in_ci": [
+ "PhantomJS"
+ ],
+ "src_files": [
+ "bower_components/jquery/dist/jquery.js",
+ "bower_components/jasmine-jquery/lib/jasmine-jquery.js",
+ "bower_components/zepto/zepto.js",
+
+ "src/waypoint.js",
+ "src/context.js",
+ "src/group.js",
+ "src/debug.js",
+ "src/adapters/*.js",
+ "src/shortcuts/*.js",
+
+ "test/settings.js",
+ "test/*-spec.js"
+ ]
+}
diff --git a/waypoints.js b/waypoints.js
deleted file mode 100644
index 85e71685..00000000
--- a/waypoints.js
+++ /dev/null
@@ -1,664 +0,0 @@
-/*!
-jQuery Waypoints - v1.1.4
-Copyright (c) 2011-2012 Caleb Troughton
-Dual licensed under the MIT license and GPL license.
-https://github.com/imakewebthings/jquery-waypoints/blob/master/MIT-license.txt
-https://github.com/imakewebthings/jquery-waypoints/blob/master/GPL-license.txt
-*/
-
-/*
-Waypoints is a small jQuery plugin that makes it easy to execute a function
-whenever you scroll to an element.
-
-GitHub Repository: https://github.com/imakewebthings/jquery-waypoints
-Documentation and Examples: http://imakewebthings.github.com/jquery-waypoints
-
-Changelog:
- v1.1.4
- - Add handler option to give alternate binding method. (Issue #34)
- v1.1.3
- - Fix cases where waypoints are added post-load and should be triggered
- immediately. (Issue #28)
- v1.1.2
- - Fixed error thrown by waypoints with triggerOnce option that were
- triggered via resize refresh.
- v1.1.1
- - Fixed bug in initialization where all offsets were being calculated
- as if set to 0 initially, causing unwarranted triggers during the
- subsequent refresh.
- - Added onlyOnScroll, an option for individual waypoints that disables
- triggers due to an offset refresh that crosses the current scroll
- point. (All credit to @knuton on this one.)
- v1.1
- - Moved the continuous option out of global settings and into the options
- object for individual waypoints.
- - Added the context option, which allows for using waypoints within any
- scrollable element, not just the window.
- v1.0.2
- - Moved scroll and resize handler bindings out of load. Should play nicer
- with async loaders like Head JS and LABjs.
- - Fixed a 1px off error when using certain % offsets.
- - Added unit tests.
- v1.0.1
- - Added $.waypoints('viewportHeight').
- - Fixed iOS bug (using the new viewportHeight method).
- - Added offset function alias: 'bottom-in-view'.
- v1.0
- - Initial release.
-
-Support:
- - jQuery versions 1.4.3+
- - IE6+, FF3+, Chrome 6+, Safari 4+, Opera 11
- - Other versions and browsers may work, these are just the ones I've looked at.
-*/
-
-(function($, wp, wps, window, undefined){
- '$:nomunge';
-
- var $w = $(window),
-
- // Keeping common strings as variables = better minification
- eventName = 'waypoint.reached',
-
- /*
- For the waypoint and direction passed in, trigger the waypoint.reached
- event and deal with the triggerOnce option.
- */
- triggerWaypoint = function(way, dir) {
- way.element.trigger(eventName, dir);
- if (way.options.triggerOnce) {
- way.element[wp]('destroy');
- }
- },
-
- /*
- Given a jQuery element and Context, returns the index of that element in the waypoints
- array. Returns the index, or -1 if the element is not a waypoint.
- */
- waypointIndex = function(el, context) {
- var i = context.waypoints.length - 1;
- while (i >= 0 && context.waypoints[i].element[0] !== el[0]) {
- i -= 1;
- }
- return i;
- },
-
- // Private list of all elements used as scrolling contexts for waypoints.
- contexts = [],
-
- /*
- Context Class - represents a scrolling context. Properties include:
- element: jQuery object containing a single HTML element.
- waypoints: Array of waypoints operating under this scroll context.
- oldScroll: Keeps the previous scroll position to determine scroll direction.
- didScroll: Flag used in scrolling the context's scroll event.
- didResize: Flag used in scrolling the context's resize event.
- doScroll: Function that checks for crossed waypoints. Called from throttler.
- */
- Context = function(context) {
- $.extend(this, {
- element: $(context),
- oldScroll: 0,
-
- /*
- List of all elements that have been registered as waypoints.
- Each object in the array contains:
- element: jQuery object containing a single HTML element.
- offset: The window scroll offset, in px, that triggers the waypoint event.
- options: Options object that was passed to the waypoint fn function.
- */
- 'waypoints': [],
-
- didScroll: false,
- didResize: false,
-
- doScroll: $.proxy(function() {
- var newScroll = this.element.scrollTop(),
-
- // Are we scrolling up or down? Used for direction argument in callback.
- isDown = newScroll > this.oldScroll,
- that = this,
-
- // Get a list of all waypoints that were crossed since last scroll move.
- pointsHit = $.grep(this.waypoints, function(el, i) {
- return isDown ?
- (el.offset > that.oldScroll && el.offset <= newScroll) :
- (el.offset <= that.oldScroll && el.offset > newScroll);
- }),
- len = pointsHit.length;
-
- // iOS adjustment
- if (!this.oldScroll || !newScroll) {
- $[wps]('refresh');
- }
-
- // Done with scroll comparisons, store new scroll before ejection
- this.oldScroll = newScroll;
-
- // No waypoints crossed? Eject.
- if (!len) return;
-
- // If several waypoints triggered, need to do so in reverse order going up
- if (!isDown) pointsHit.reverse();
-
- /*
- One scroll move may cross several waypoints. If the waypoint's continuous
- option is true it should fire even if it isn't the last waypoint. If false,
- it will only fire if it's the last one.
- */
- $.each(pointsHit, function(i, point) {
- if (point.options.continuous || i === len - 1) {
- triggerWaypoint(point, [isDown ? 'down' : 'up']);
- }
- });
- }, this)
- });
-
- // Setup scroll and resize handlers. Throttled at the settings-defined rate limits.
- $(context).scroll($.proxy(function() {
- if (!this.didScroll) {
- this.didScroll = true;
- window.setTimeout($.proxy(function() {
- this.doScroll();
- this.didScroll = false;
- }, this), $[wps].settings.scrollThrottle);
- }
- }, this)).resize($.proxy(function() {
- if (!this.didResize) {
- this.didResize = true;
- window.setTimeout($.proxy(function() {
- $[wps]('refresh');
- this.didResize = false;
- }, this), $[wps].settings.resizeThrottle);
- }
- }, this));
-
- $w.load($.proxy(function() {
- /*
- Fire a scroll check, should the page be loaded at a non-zero scroll value,
- as with a fragment id link or a page refresh.
- */
- this.doScroll();
- }, this));
- },
-
- /* Returns a Context object from the contexts array, given the raw HTML element
- for that context. */
- getContextByElement = function(element) {
- var found = null;
-
- $.each(contexts, function(i, c) {
- if (c.element[0] === element) {
- found = c;
- return false;
- }
- });
-
- return found;
- },
-
- // Methods exposed to the effin' object
- methods = {
- /*
- jQuery.fn.waypoint([handler], [options])
-
- handler
- function, optional
- A callback function called when the user scrolls past the element.
- The function signature is function(event, direction) where event is
- a standard jQuery Event Object and direction is a string, either 'down'
- or 'up' indicating which direction the user is scrolling.
-
- options
- object, optional
- A map of options to apply to this set of waypoints, including where on
- the browser window the waypoint is triggered. For a full list of
- options and their defaults, see $.fn.waypoint.defaults.
-
- This is how you register an element as a waypoint. When the user scrolls past
- that element it triggers waypoint.reached, a custom event. Since the
- parameters for creating a waypoint are optional, we have a few different
- possible signatures. Let’s look at each of them.
-
- someElements.waypoint();
-
- Calling .waypoint with no parameters will register the elements as waypoints
- using the default options. The elements will fire the waypoint.reached event,
- but calling it in this way does not bind any handler to the event. You can
- bind to the event yourself, as with any other event, like so:
-
- someElements.bind('waypoint.reached', function(event, direction) {
- // make it rain
- });
-
- You will usually want to create a waypoint and immediately bind a function to
- waypoint.reached, and can do so by passing a handler as the first argument to
- .waypoint:
-
- someElements.waypoint(function(event, direction) {
- if (direction === 'down') {
- // do this on the way down
- }
- else {
- // do this on the way back up through the waypoint
- }
- });
-
- This will still use the default options, which will trigger the waypoint when
- the top of the element hits the top of the window. We can pass .waypoint an
- options object to customize things:
-
- someElements.waypoint(function(event, direction) {
- // do something amazing
- }, {
- offset: '50%' // middle of the page
- });
-
- You can also pass just an options object.
-
- someElements.waypoint({
- offset: 100 // 100px from the top
- });
-
- This behaves like .waypoint(), in that it registers the elements as waypoints
- but binds no event handlers.
-
- Calling .waypoint on an existing waypoint will extend the previous options.
- If the call includes a handler, it will be bound to waypoint.reached without
- unbinding any other handlers.
- */
- init: function(f, options) {
- // Register each element as a waypoint, add to array.
- this.each(function() {
- var cElement = $.fn[wp].defaults.context,
- context,
- $this = $(this);
-
- // Default window context or a specific element?
- if (options && options.context) {
- cElement = options.context;
- }
-
- // Find the closest element that matches the context
- if (!$.isWindow(cElement)) {
- cElement = $this.closest(cElement)[0];
- }
- context = getContextByElement(cElement);
-
- // Not a context yet? Create and push.
- if (!context) {
- context = new Context(cElement);
- contexts.push(context);
- }
-
- // Extend default and preexisting options
- var ndx = waypointIndex($this, context),
- base = ndx < 0 ? $.fn[wp].defaults : context.waypoints[ndx].options,
- opts = $.extend({}, base, options);
-
- // Offset aliases
- opts.offset = opts.offset === "bottom-in-view" ?
- function() {
- var cHeight = $.isWindow(cElement) ? $[wps]('viewportHeight')
- : $(cElement).height();
- return cHeight - $(this).outerHeight();
- } : opts.offset;
-
- // Update, or create new waypoint
- if (ndx < 0) {
- context.waypoints.push({
- 'element': $this,
- 'offset': null,
- 'options': opts
- });
- }
- else {
- context.waypoints[ndx].options = opts;
- }
-
- // Bind the function if it was passed in.
- if (f) {
- $this.bind(eventName, f);
- }
- // Bind the function in the handler option if it exists.
- if (options && options.handler) {
- $this.bind(eventName, options.handler);
- }
- });
-
- // Need to re-sort+refresh the waypoints array after new elements are added.
- $[wps]('refresh');
-
- return this;
- },
-
-
- /*
- jQuery.fn.waypoint('remove')
-
- Passing the string 'remove' to .waypoint unregisters the elements as waypoints
- and wipes any custom options, but leaves the waypoint.reached events bound.
- Calling .waypoint again in the future would reregister the waypoint and the old
- handlers would continue to work.
- */
- remove: function() {
- return this.each(function(i, el) {
- var $el = $(el);
-
- $.each(contexts, function(i, c) {
- var ndx = waypointIndex($el, c);
-
- if (ndx >= 0) {
- c.waypoints.splice(ndx, 1);
- }
- });
- });
- },
-
- /*
- jQuery.fn.waypoint('destroy')
-
- Passing the string 'destroy' to .waypoint will unbind all waypoint.reached
- event handlers on those elements and unregisters them as waypoints.
- */
- destroy: function() {
- return this.unbind(eventName)[wp]('remove');
- }
- },
-
- /*
- Methods used by the jQuery object extension.
- */
- jQMethods = {
-
- /*
- jQuery.waypoints('refresh')
-
- This will force a recalculation of each waypoint’s trigger point based on
- its offset option and context. This is called automatically whenever the window
- (or other defined context) is resized, new waypoints are added, or a waypoint’s
- options are modified. If your project is changing the DOM or page layout without
- doing one of these things, you may want to manually call this refresh.
- */
- refresh: function() {
- $.each(contexts, function(i, c) {
- var isWin = $.isWindow(c.element[0]),
- contextOffset = isWin ? 0 : c.element.offset().top,
- contextHeight = isWin ? $[wps]('viewportHeight') : c.element.height(),
- contextScroll = isWin ? 0 : c.element.scrollTop();
-
- $.each(c.waypoints, function(j, o) {
- /* $.each isn't safe from element removal due to triggerOnce.
- Should rewrite the loop but this is way easier. */
- if (!o) return;
-
- // Adjustment is just the offset if it's a px value
- var adjustment = o.options.offset,
- oldOffset = o.offset;
-
- // Set adjustment to the return value if offset is a function.
- if (typeof o.options.offset === "function") {
- adjustment = o.options.offset.apply(o.element);
- }
- // Calculate the adjustment if offset is a percentage.
- else if (typeof o.options.offset === "string") {
- var amount = parseFloat(o.options.offset);
- adjustment = o.options.offset.indexOf("%") ?
- Math.ceil(contextHeight * (amount / 100)) : amount;
- }
-
- /*
- Set the element offset to the window scroll offset, less
- all our adjustments.
- */
- o.offset = o.element.offset().top - contextOffset
- + contextScroll - adjustment;
-
- /*
- An element offset change across the current scroll point triggers
- the event, just as if we scrolled past it unless prevented by an
- optional flag.
- */
- if (o.options.onlyOnScroll) return;
-
- if (oldOffset !== null && c.oldScroll > oldOffset && c.oldScroll <= o.offset) {
- triggerWaypoint(o, ['up']);
- }
- else if (oldOffset !== null && c.oldScroll < oldOffset && c.oldScroll >= o.offset) {
- triggerWaypoint(o, ['down']);
- }
- /* For new waypoints added after load, check that down should have
- already been triggered */
- else if (!oldOffset && contextScroll > o.offset) {
- triggerWaypoint(o, ['down']);
- }
- });
-
- // Keep waypoints sorted by offset value.
- c.waypoints.sort(function(a, b) {
- return a.offset - b.offset;
- });
- });
- },
-
-
- /*
- jQuery.waypoints('viewportHeight')
-
- This will return the height of the viewport, adjusting for inconsistencies
- that come with calling $(window).height() in iOS. Recommended for use
- within any offset functions.
- */
- viewportHeight: function() {
- return (window.innerHeight ? window.innerHeight : $w.height());
- },
-
-
- /*
- jQuery.waypoints()
-
- This will return a jQuery object with a collection of all registered waypoint
- elements.
-
- $('.post').waypoint();
- $('.ad-unit').waypoint(function(event, direction) {
- // Passed an ad unit
- });
- console.log($.waypoints());
-
- The example above would log a jQuery object containing all .post and .ad-unit
- elements.
- */
- aggregate: function() {
- var points = $();
- $.each(contexts, function(i, c) {
- $.each(c.waypoints, function(i, e) {
- points = points.add(e.element);
- });
- });
- return points;
- }
- };
-
-
- /*
- fn extension. Delegates to appropriate method.
- */
- $.fn[wp] = function(method) {
-
- if (methods[method]) {
- return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
- }
- else if (typeof method === "function" || !method) {
- return methods.init.apply(this, arguments);
- }
- else if (typeof method === "object") {
- return methods.init.apply(this, [null, method]);
- }
- else {
- $.error( 'Method ' + method + ' does not exist on jQuery ' + wp );
- }
- };
-
-
- /*
- The default options object that is extended when calling .waypoint. It has the
- following properties:
-
- context
- string | element | jQuery*
- default: window
- The context defines which scrollable element the waypoint belongs to and acts
- within. The default, window, means the waypoint offset is calculated with relation
- to the whole viewport. You can set this to another element to use the waypoints
- within that element. Accepts a selector string, *but if you use jQuery 1.6+ it
- also accepts a raw HTML element or jQuery object.
-
- continuous
- boolean
- default: true
- If true, and multiple waypoints are triggered in one scroll, this waypoint will
- trigger even if it is not the last waypoint reached. If false, it will only
- trigger if it is the last waypoint.
-
- handler
- function
- default: undefined
- An alternative way to bind functions to the waypoint, without using the function
- as the first argument to the waypoint function.
-
- offset
- number | string | function
- default: 0
- Determines how far the top of the element must be from the top of the browser
- window to trigger a waypoint. It can be a number, which is taken as a number
- of pixels, a string representing a percentage of the viewport height, or a
- function that will return a number of pixels.
-
- onlyOnScroll
- boolean
- default: false
- If true, this waypoint will not trigger if an offset change during a refresh
- causes it to pass the current scroll point.
-
- triggerOnce
- boolean
- default: false
- If true, the waypoint will be destroyed when triggered.
-
- An offset of 250 would trigger the waypoint when the top of the element is 250px
- from the top of the viewport. Negative values for any offset work as you might
- expect. A value of -100 would trigger the waypoint when the element is 100px above
- the top of the window.
-
- offset: '100%'
-
- A string percentage will determine the pixel offset based on the height of the
- window. When resizing the window, this offset will automatically be recalculated
- without needing to call $.waypoints('refresh').
-
- // The bottom of the element is in view
- offset: function() {
- return $.waypoints('viewportHeight') - $(this).outerHeight();
- }
-
- Offset can take a function, which must return a number of pixels from the top of
- the window. The this value will always refer to the raw HTML element of the
- waypoint. As with % values, functions are recalculated automatically when the
- window resizes. For more on recalculating offsets, see $.waypoints('refresh').
-
- An offset value of 'bottom-in-view' will act as an alias for the function in the
- example above, as this is a common usage.
-
- offset: 'bottom-in-view'
-
- You can see this alias in use on the Scroll Analytics example page.
-
- The triggerOnce flag, if true, will destroy the waypoint after the first trigger.
- This is just a shortcut for calling .waypoint('destroy') within the waypoint
- handler. This is useful in situations such as scroll analytics, where you only
- want to record an event once for each page visit.
-
- The context option lets you use Waypoints within an element other than the window.
- You can define the context with a selector string and the waypoint will act within
- the nearest ancestor that matches this selector.
-
- $('.something-scrollable .waypoint').waypoint({
- context: '.something-scrollable'
- });
-
- You can see this in action on the Dial Controls example.
-
- The handler option gives authors an alternative way to bind functions when
- creating a waypoint. In place of:
-
- $('.item').waypoint(function(event, direction) {
- // make things happen
- });
-
- You may instead write:
-
- $('.item').waypoint({
- handler: function(event, direction) {
- // make things happen
- }
- });
-
- */
- $.fn[wp].defaults = {
- continuous: true,
- offset: 0,
- triggerOnce: false,
- context: window
- };
-
-
-
-
-
- /*
- jQuery object extension. Delegates to appropriate methods above.
- */
- $[wps] = function(method) {
- if (jQMethods[method]) {
- return jQMethods[method].apply(this);
- }
- else {
- return jQMethods['aggregate']();
- }
- };
-
-
- /*
- $.waypoints.settings
-
- Settings object that determines some of the plugin’s behavior.
-
- resizeThrottle
- number
- default: 200
- For performance reasons, the refresh performed during resizes is
- throttled. This value is the rate-limit in milliseconds between resize
- refreshes. For more information on throttling, check out Ben Alman’s
- throttle / debounce plugin.
- http://benalman.com/projects/jquery-throttle-debounce-plugin/
-
- scrollThrottle
- number
- default: 100
- For performance reasons, checking for any crossed waypoints during a
- scroll event is throttled. This value is the rate-limit in milliseconds
- between scroll checks. For more information on throttling, check out Ben
- Alman’s throttle / debounce plugin.
- http://benalman.com/projects/jquery-throttle-debounce-plugin/
- */
- $[wps].settings = {
- resizeThrottle: 200,
- scrollThrottle: 100
- };
-
- $w.load(function() {
- // Calculate everything once on load.
- $[wps]('refresh');
- });
-})(jQuery, 'waypoint', 'waypoints', this);
diff --git a/waypoints.min.js b/waypoints.min.js
deleted file mode 100644
index 3b80564a..00000000
--- a/waypoints.min.js
+++ /dev/null
@@ -1,8 +0,0 @@
-/*
-jQuery Waypoints - v1.1.4
-Copyright (c) 2011-2012 Caleb Troughton
-Dual licensed under the MIT license and GPL license.
-https://github.com/imakewebthings/jquery-waypoints/blob/master/MIT-license.txt
-https://github.com/imakewebthings/jquery-waypoints/blob/master/GPL-license.txt
-*/
-(function($,k,m,i,d){var e=$(i),g="waypoint.reached",b=function(o,n){o.element.trigger(g,n);if(o.options.triggerOnce){o.element[k]("destroy")}},h=function(p,o){var n=o.waypoints.length-1;while(n>=0&&o.waypoints[n].element[0]!==p[0]){n-=1}return n},f=[],l=function(n){$.extend(this,{element:$(n),oldScroll:0,waypoints:[],didScroll:false,didResize:false,doScroll:$.proxy(function(){var q=this.element.scrollTop(),p=q>this.oldScroll,s=this,r=$.grep(this.waypoints,function(u,t){return p?(u.offset>s.oldScroll&&u.offset<=q):(u.offset<=s.oldScroll&&u.offset>q)}),o=r.length;if(!this.oldScroll||!q){$[m]("refresh")}this.oldScroll=q;if(!o){return}if(!p){r.reverse()}$.each(r,function(u,t){if(t.options.continuous||u===o-1){b(t,[p?"down":"up"])}})},this)});$(n).scroll($.proxy(function(){if(!this.didScroll){this.didScroll=true;i.setTimeout($.proxy(function(){this.doScroll();this.didScroll=false},this),$[m].settings.scrollThrottle)}},this)).resize($.proxy(function(){if(!this.didResize){this.didResize=true;i.setTimeout($.proxy(function(){$[m]("refresh");this.didResize=false},this),$[m].settings.resizeThrottle)}},this));e.load($.proxy(function(){this.doScroll()},this))},j=function(n){var o=null;$.each(f,function(p,q){if(q.element[0]===n){o=q;return false}});return o},c={init:function(o,n){this.each(function(){var u=$.fn[k].defaults.context,q,t=$(this);if(n&&n.context){u=n.context}if(!$.isWindow(u)){u=t.closest(u)[0]}q=j(u);if(!q){q=new l(u);f.push(q)}var p=h(t,q),s=p<0?$.fn[k].defaults:q.waypoints[p].options,r=$.extend({},s,n);r.offset=r.offset==="bottom-in-view"?function(){var v=$.isWindow(u)?$[m]("viewportHeight"):$(u).height();return v-$(this).outerHeight()}:r.offset;if(p<0){q.waypoints.push({element:t,offset:null,options:r})}else{q.waypoints[p].options=r}if(o){t.bind(g,o)}if(n&&n.handler){t.bind(g,n.handler)}});$[m]("refresh");return this},remove:function(){return this.each(function(o,p){var n=$(p);$.each(f,function(r,s){var q=h(n,s);if(q>=0){s.waypoints.splice(q,1)}})})},destroy:function(){return this.unbind(g)[k]("remove")}},a={refresh:function(){$.each(f,function(r,s){var q=$.isWindow(s.element[0]),n=q?0:s.element.offset().top,p=q?$[m]("viewportHeight"):s.element.height(),o=q?0:s.element.scrollTop();$.each(s.waypoints,function(u,x){if(!x){return}var t=x.options.offset,w=x.offset;if(typeof x.options.offset==="function"){t=x.options.offset.apply(x.element)}else{if(typeof x.options.offset==="string"){var v=parseFloat(x.options.offset);t=x.options.offset.indexOf("%")?Math.ceil(p*(v/100)):v}}x.offset=x.element.offset().top-n+o-t;if(x.options.onlyOnScroll){return}if(w!==null&&s.oldScroll>w&&s.oldScroll<=x.offset){b(x,["up"])}else{if(w!==null&&s.oldScroll=x.offset){b(x,["down"])}else{if(!w&&o>x.offset){b(x,["down"])}}}});s.waypoints.sort(function(u,t){return u.offset-t.offset})})},viewportHeight:function(){return(i.innerHeight?i.innerHeight:e.height())},aggregate:function(){var n=$();$.each(f,function(o,p){$.each(p.waypoints,function(q,r){n=n.add(r.element)})});return n}};$.fn[k]=function(n){if(c[n]){return c[n].apply(this,Array.prototype.slice.call(arguments,1))}else{if(typeof n==="function"||!n){return c.init.apply(this,arguments)}else{if(typeof n==="object"){return c.init.apply(this,[null,n])}else{$.error("Method "+n+" does not exist on jQuery "+k)}}}};$.fn[k].defaults={continuous:true,offset:0,triggerOnce:false,context:i};$[m]=function(n){if(a[n]){return a[n].apply(this)}else{return a.aggregate()}};$[m].settings={resizeThrottle:200,scrollThrottle:100};e.load(function(){$[m]("refresh")})})(jQuery,"waypoint","waypoints",this);
\ No newline at end of file