')
+ .attr('id', this.containerId)
+ .html(html)
-jasmine.Fixtures.prototype.createContainer_ = function(html) {
- var container
- if(html instanceof jQuery) {
- container = jQuery('
')
- container.html(html)
- } else {
- container = '
' + html + '
'
+ $(document.body).append(container)
+ return container
}
- jQuery('body').append(container)
-}
-jasmine.Fixtures.prototype.addToContainer_ = function(html){
- var container = jQuery('body').find('#'+this.containerId).append(html)
- if(!container.length){
- this.createContainer_(html)
+ 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)
+ jasmine.Fixtures.prototype.getFixtureHtml_ = function (url) {
+ if (typeof this.fixturesCache_[url] === 'undefined') {
+ this.loadFixtureIntoCache_(url)
+ }
+ return this.fixturesCache_[url]
}
- return this.fixturesCache_[url]
-}
-jasmine.Fixtures.prototype.loadFixtureIntoCache_ = function(relativeUrl) {
- var url = this.makeFixtureUrl_(relativeUrl)
- var request = new XMLHttpRequest()
- request.open("GET", url + "?" + new Date().getTime(), false)
- request.send(null)
- this.fixturesCache_[relativeUrl] = request.responseText
-}
+ 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.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.Fixtures.prototype.proxyCallTo_ = function (methodName, passedArguments) {
+ return this[methodName].apply(this, passedArguments)
+ }
-jasmine.JQuery = function() {}
+ jasmine.StyleFixtures = function () {
+ this.fixturesCache_ = {}
+ this.fixturesNodes_ = []
+ this.fixturesPath = 'spec/javascripts/fixtures'
+ }
-jasmine.JQuery.browserTagCaseIndependentHtml = function(html) {
- return jQuery('
').append(html).html()
-}
+ jasmine.StyleFixtures.prototype.set = function (css) {
+ this.cleanUp()
+ this.createStyle_(css)
+ }
-jasmine.JQuery.elementToString = function(element) {
- var domEl = $(element).get(0)
- if (domEl == undefined || domEl.cloneNode)
- return jQuery('
').append($(element).clone()).html()
- else
- return element.toString()
-}
+ 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.JQuery.matchersClass = {};
+ 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: []
}
- namespace.events = {
- spyOn: function(selector, eventName) {
- var handler = function(e) {
- data.spiedEvents[jasmine.spiedEventsKey(selector, eventName)] = e
+ jasmine.jQuery.events = {
+ spyOn: function (selector, eventName) {
+ var handler = function (e) {
+ data.spiedEvents[jasmine.spiedEventsKey(selector, eventName)] = jasmine.util.argsToArray(arguments)
}
- jQuery(selector).bind(eventName, handler)
+
+ $(selector).on(eventName, handler)
data.handlers.push(handler)
+
return {
selector: selector,
eventName: eventName,
handler: handler,
- reset: function(){
- delete data.spiedEvents[jasmine.spiedEventsKey(selector, eventName)];
+ reset: function (){
+ delete data.spiedEvents[jasmine.spiedEventsKey(selector, eventName)]
}
}
},
- wasTriggered: function(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
+ },
+
+ wasTriggered: function (selector, eventName) {
return !!(data.spiedEvents[jasmine.spiedEventsKey(selector, eventName)])
},
- wasPrevented: function(selector, eventName) {
- return data.spiedEvents[jasmine.spiedEventsKey(selector, eventName)].isDefaultPrevented()
+ 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()
+ },
+
+ wasStopped: function (selector, eventName) {
+ var args = data.spiedEvents[jasmine.spiedEventsKey(selector, eventName)]
+ , e = args ? args[0] : undefined
+ return e && e.isPropagationStopped()
},
- cleanUp: function() {
+ cleanUp: function () {
data.spiedEvents = {}
data.handlers = []
}
}
-}(jasmine.JQuery)
-!function(){
var jQueryMatchers = {
- toHaveClass: function(className) {
+ toHaveClass: function (className) {
return this.actual.hasClass(className)
},
- toHaveCss: function(css){
+ toHaveCss: function (css){
for (var prop in css){
- if (this.actual.css(prop) !== css[prop]) return false
+ 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() {
+ toBeVisible: function () {
return this.actual.is(':visible')
},
- toBeHidden: function() {
+ toBeHidden: function () {
return this.actual.is(':hidden')
},
- toBeSelected: function() {
+ toBeSelected: function () {
return this.actual.is(':selected')
},
- toBeChecked: function() {
+ toBeChecked: function () {
return this.actual.is(':checked')
},
- toBeEmpty: function() {
+ toBeEmpty: function () {
return this.actual.is(':empty')
},
- toExist: function() {
- return $(document).find(this.actual).length
+ toBeInDOM: function () {
+ return $.contains(document.documentElement, this.actual[0])
+ },
+
+ toExist: function () {
+ return this.actual.length
},
- toHaveAttr: function(attributeName, expectedAttributeValue) {
+ toHaveLength: function (length) {
+ return this.actual.length === length
+ },
+
+ toHaveAttr: function (attributeName, expectedAttributeValue) {
return hasProperty(this.actual.attr(attributeName), expectedAttributeValue)
},
- toHaveProp: function(propertyName, expectedPropertyValue) {
+ toHaveProp: function (propertyName, expectedPropertyValue) {
return hasProperty(this.actual.prop(propertyName), expectedPropertyValue)
},
- toHaveId: function(id) {
+ toHaveId: function (id) {
return this.actual.attr('id') == id
},
- toHaveHtml: function(html) {
- return this.actual.html() == jasmine.JQuery.browserTagCaseIndependentHtml(html)
+ toHaveHtml: function (html) {
+ return this.actual.html() == jasmine.jQuery.browserTagCaseIndependentHtml(html)
},
- toContainHtml: function(html){
+ toContainHtml: function (html){
var actualHtml = this.actual.html()
- var expectedHtml = jasmine.JQuery.browserTagCaseIndependentHtml(html)
+ , expectedHtml = jasmine.jQuery.browserTagCaseIndependentHtml(html)
+
return (actualHtml.indexOf(expectedHtml) >= 0)
},
- toHaveText: function(text) {
+ toHaveText: function (text) {
var trimmedText = $.trim(this.actual.text())
- if (text && jQuery.isFunction(text.test)) {
+
+ if (text && $.isFunction(text.test)) {
return text.test(trimmedText)
} else {
return trimmedText == text
}
},
- toHaveValue: function(value) {
- return this.actual.val() == value
+ toContainText: function (text) {
+ var trimmedText = $.trim(this.actual.text())
+
+ if (text && $.isFunction(text.test)) {
+ return text.test(trimmedText)
+ } else {
+ return trimmedText.indexOf(text) != -1
+ }
+ },
+
+ toHaveValue: function (value) {
+ return this.actual.val() === value
},
- toHaveData: function(key, expectedValue) {
+ toHaveData: function (key, expectedValue) {
return hasProperty(this.actual.data(key), expectedValue)
},
- toBe: function(selector) {
+ toBe: function (selector) {
return this.actual.is(selector)
},
- toContain: function(selector) {
+ toContain: function (selector) {
return this.actual.find(selector).length
},
- toBeDisabled: function(selector){
- return this.actual.is(':disabled')
+ toBeMatchedBy: function (selector) {
+ return this.actual.filter(selector).length
},
- toBeFocused: function(selector) {
- return this.actual.is(':focus')
+ toBeDisabled: function (selector){
+ return this.actual.is(':disabled')
},
- toHandle: function(event) {
+ toBeFocused: function (selector) {
+ return this.actual[0] === this.actual[0].ownerDocument.activeElement
+ },
- var events = this.actual.data('events')
+ toHandle: function (event) {
+ var events = $._data(this.actual.get(0), "events")
if(!events || !event || typeof event !== "string") {
return false
}
var namespaces = event.split(".")
- var eventType = namespaces.shift()
- var sortedNamespaces = namespaces.slice(0).sort()
- var namespaceRegExp = new RegExp("(^|\\.)" + sortedNamespaces.join("\\.(?:.*\\.)?") + "(\\.|$)")
+ , 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
}
@@ -303,33 +465,38 @@ jasmine.JQuery.matchersClass = {};
}
},
- // tests the existence of a specific event binding + handler
- toHandleWith: function(eventName, eventHandler) {
- var stack = this.actual.data("events")[eventName]
+ toHandleWith: function (eventName, eventHandler) {
+ var normalizedEventName = eventName.split('.')[0]
+ , stack = $._data(this.actual.get(0), "events")[normalizedEventName]
+
for (var i = 0; i < stack.length; i++) {
if (stack[i].handler == eventHandler) return true
}
+
return false
}
}
- var hasProperty = function(actualValue, expectedValue) {
+ var hasProperty = function (actualValue, expectedValue) {
if (expectedValue === undefined) return actualValue !== undefined
- return actualValue == expectedValue
+
+ return actualValue === expectedValue
}
- var bindMatcher = function(methodName) {
+ var bindMatcher = function (methodName) {
var builtInMatcher = jasmine.Matchers.prototype[methodName]
- jasmine.JQuery.matchersClass[methodName] = function() {
+ jasmine.jQuery.matchersClass[methodName] = function () {
if (this.actual
- && (this.actual instanceof jQuery
+ && (this.actual instanceof $
|| jasmine.isDomNode(this.actual))) {
this.actual = $(this.actual)
var result = jQueryMatchers[methodName].apply(this, arguments)
- var element;
- if (this.actual.get && (element = this.actual.get()[0]) && !$.isWindow(element) && element.tagName !== "HTML")
- this.actual = jasmine.JQuery.elementToString(this.actual)
+ , element
+
+ if (this.actual.get && (element = this.actual.get()[0]) && !$.isWindow(element) && element.tagName !== "HTML")
+ this.actual = jasmine.jQuery.elementToString(this.actual)
+
return result
}
@@ -344,61 +511,195 @@ jasmine.JQuery.matchersClass = {};
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
- ]
+
+ 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)
}
- 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
- ]
+ })
+
+ 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)
}
- return jasmine.JQuery.events.wasTriggered(selector, eventName)
- }
- })
- 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
- ]
+ })
+
+ 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)
}
- 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
- ]
+ })
+
+ 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)
}
- return jasmine.JQuery.events.wasPrevented(selector, eventName)
- }
+ })
+
+ 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 826e5753..8c008dc7 100644
--- a/test/lib/jasmine.css
+++ b/test/lib/jasmine.css
@@ -19,6 +19,7 @@ body { background-color: #eeeeee; padding: 0; margin: 5px; overflow-y: scroll; }
#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; }
diff --git a/test/lib/jasmine.js b/test/lib/jasmine.js
index 03bf89a0..6b3459b9 100644
--- a/test/lib/jasmine.js
+++ b/test/lib/jasmine.js
@@ -1,4 +1,4 @@
-var isCommonJS = typeof window == "undefined";
+var isCommonJS = typeof window == "undefined" && typeof exports == "object";
/**
* Top level namespace for Jasmine, a lightweight JavaScript BDD/spec/testing framework.
@@ -34,11 +34,23 @@ jasmine.VERBOSE = false;
*/
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;
@@ -463,7 +475,7 @@ 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);
@@ -508,6 +520,7 @@ if (isCommonJS) exports.xit = xit;
* 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);
@@ -867,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;
@@ -953,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);
}
@@ -1019,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();
};
@@ -1281,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.
*/
@@ -1358,18 +1410,14 @@ jasmine.Matchers.prototype.toHaveBeenCalledWith = function() {
throw new Error('Expected a spy, but got ' + jasmine.pp(this.actual) + '.');
}
this.message = function() {
+ 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) {
- // todo: what should the failure message for .not.toHaveBeenCalledWith() be? is this right? test better. [xw]
- return [
- "Expected spy " + this.actual.identity + " to have been called with " + jasmine.pp(expectedArgs) + " but it was never called.",
- "Expected spy " + this.actual.identity + " not to have been called with " + jasmine.pp(expectedArgs) + " but it was."
- ];
+ positiveMessage = "Expected spy " + this.actual.identity + " to have been called with " + jasmine.pp(expectedArgs) + " but it was never called.";
} else {
- return [
- "Expected spy " + this.actual.identity + " to have been called with " + jasmine.pp(expectedArgs) + " but was called with " + jasmine.pp(this.actual.argsForCall),
- "Expected spy " + this.actual.identity + " 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);
@@ -1427,22 +1475,19 @@ jasmine.Matchers.prototype.toBeGreaterThan = function(expected) {
* up to a given level of decimal precision (default 2).
*
* @param {Number} expected
- * @param {Number} precision
+ * @param {Number} precision, as number of decimal places
*/
jasmine.Matchers.prototype.toBeCloseTo = function(expected, precision) {
if (!(precision === 0)) {
precision = precision || 2;
}
- var multiplier = Math.pow(10, precision);
- var actual = Math.round(this.actual * multiplier);
- expected = Math.round(expected * multiplier);
- return expected == actual;
+ 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;
@@ -1840,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) {
@@ -1886,6 +1927,7 @@ 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) !== jasmine.undefined &&
obj.__lookupGetter__(property) !== null) : false);
@@ -1913,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) {
@@ -1924,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;
@@ -1952,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;
@@ -1959,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++;
};
@@ -1991,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;
@@ -2282,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);
}
@@ -2320,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);
}
};
@@ -2523,7 +2594,7 @@ jasmine.WaitsForBlock.prototype.execute = function(onComplete) {
jasmine.version_= {
"major": 1,
- "minor": 2,
- "build": 0,
- "revision": 1337005947
+ "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/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/sticky.coffee b/test/sticky.coffee
deleted file mode 100644
index cea3d8ce..00000000
--- a/test/sticky.coffee
+++ /dev/null
@@ -1,39 +0,0 @@
-$.waypoints.settings.scrollThrottle = 10
-$.waypoints.settings.resizeThrottle = 20
-standardWait = 50
-
-describe 'Waypoints Sticky Elements Shortcut', ->
- $sticky = $return = null
- $win = $ window
-
- beforeEach ->
- loadFixtures 'sticky.html'
- $sticky = $ '.sticky'
- $return = $sticky.waypoint 'sticky'
-
- it 'returns the same jQuery object for chaining', ->
- expect($return.get()).toEqual $sticky.get()
-
- it 'wraps the sticky element', ->
- expect($sticky.parent()).toHaveClass 'sticky-wrapper'
-
- it 'gives the wrapper the same height as the sticky element', ->
- expect($sticky.parent().height()).toEqual $sticky.height()
-
- it 'adds stuck class when you reach the element', ->
- runs ->
- $win.scrollTop $sticky.offset().top
- waits standardWait
-
- runs ->
- expect($sticky).toHaveClass 'stuck'
- $win.scrollTop $win.scrollTop()-1
- waits standardWait
-
- runs ->
- expect($sticky).not.toHaveClass 'stuck'
-
- afterEach ->
- $.waypoints 'destroy'
- $win.scrollTop 0
-
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/test/waypoints.coffee b/test/waypoints.coffee
deleted file mode 100644
index 5753b034..00000000
--- a/test/waypoints.coffee
+++ /dev/null
@@ -1,708 +0,0 @@
-$.waypoints.settings.scrollThrottle = 10
-$.waypoints.settings.resizeThrottle = 20
-standardWait = 50
-
-# Go tests, go
-
-describe 'jQuery Waypoints', ->
- hit = $se = $e = null
-
- beforeEach ->
- loadFixtures 'standard.html'
- $se = $ window
- hit = false
-
- describe '#waypoint()', ->
- it 'errors out', ->
- fn = -> $('#same1').waypoint()
- expect(fn).toThrow $.Error
-
- describe '#waypoint(callback)', ->
- currentDirection = null
-
- beforeEach ->
- currentDirection = null
- $e = $('#same1').waypoint (direction) ->
- currentDirection = direction
- hit = true
-
- it 'creates a waypoint', ->
- expect($.waypoints().vertical.length).toEqual 1
-
- it 'triggers the callback', ->
- runs ->
- $se.scrollTop $e.offset().top
- waits standardWait
-
- runs ->
- expect(hit).toBeTruthy()
-
- it 'uses the default offset', ->
- runs ->
- $se.scrollTop($e.offset().top - 1)
- waits standardWait
-
- runs ->
- expect(hit).toBeFalsy()
- $se.scrollTop $e.offset().top
- waits standardWait
-
- runs ->
- expect(hit).toBeTruthy()
-
- it 'passes correct directions', ->
- runs ->
- $se.scrollTop $e.offset().top
- waits standardWait
-
- runs ->
- expect(currentDirection).toEqual 'down'
- $se.scrollTop($e.offset().top - 1)
- waits standardWait
-
- runs ->
- expect(currentDirection).toEqual 'up'
-
-
-
- describe '#waypoint(options)', ->
- beforeEach ->
- $e = $ '#same1'
-
- it 'creates a waypoint', ->
- $e.waypoint
- offset: 1
- triggerOnce: true
- expect($.waypoints().vertical.length).toEqual 1
-
- it 'respects a px offset', ->
- runs ->
- $e.waypoint
- offset: 50
- handler: -> hit = true
- $se.scrollTop($e.offset().top - 51)
- waits standardWait
-
- runs ->
- expect(hit).toBeFalsy()
- $se.scrollTop($e.offset().top - 50)
- waits standardWait
-
- runs ->
- expect(hit).toBeTruthy()
-
- it 'respects a % offset', ->
- pos = null
-
- runs ->
- $e.waypoint
- offset: '37%'
- handler: -> hit = true
- pos = $e.offset().top - $.waypoints('viewportHeight') * .37 - 1
- $se.scrollTop pos
- waits standardWait
-
- runs ->
- expect(hit).toBeFalsy()
- $se.scrollTop pos + 1
- waits standardWait
-
- runs ->
- expect(hit).toBeTruthy()
-
- it 'respects a function offset', ->
- runs ->
- $e.waypoint
- offset: ->
- $(this).height() * -1
- handler: -> hit = true
- $se.scrollTop($e.offset().top + $e.height() - 1)
- waits standardWait
-
- runs ->
- expect(hit).toBeFalsy()
- $se.scrollTop($e.offset().top + $e.height())
- waits standardWait
-
- runs ->
- expect(hit).toBeTruthy()
-
- it 'respects the bottom-in-view function alias', ->
- inview = $e.offset().top \
- - $.waypoints('viewportHeight') \
- + $e.outerHeight()
-
- runs ->
- $e.waypoint
- offset: 'bottom-in-view'
- handler: -> hit = true
- $se.scrollTop(inview - 1)
- waits standardWait
-
- runs ->
- expect(hit).toBeFalsy()
- $se.scrollTop inview
- waits standardWait
-
- runs ->
- expect(hit).toBeTruthy()
-
- it 'destroys the waypoint if triggerOnce is true', ->
- runs ->
- $e.waypoint
- triggerOnce: true
- $se.scrollTop $e.offset().top
- waits standardWait
-
- runs ->
- expect($.waypoints().length).toBeFalsy()
-
- it 'triggers if continuous is true and waypoint is not last', ->
- $f = $ '#near1'
- $g = $ '#near2'
- hitcount = 0
-
- runs ->
- $e.add($f).add($g).waypoint ->
- hitcount++
- $se.scrollTop $g.offset().top
- waits standardWait
-
- runs ->
- expect(hitcount).toEqual 3
-
- it 'does not trigger if continuous false, waypoint not last', ->
- $f = $ '#near1'
- $g = $ '#near2'
- hitcount = 0
-
- runs ->
- callback = ->
- hitcount++
- options =
- continuous: false
- $e.add($g).waypoint callback
- $f.waypoint callback, options
- $se.scrollTop $g.offset().top
- waits standardWait
-
- runs ->
- expect(hitcount).toEqual 2
-
- it 'triggers if continuous is false, waypoint is last', ->
- $f = $ '#near1'
- $g = $ '#near2'
- hitcount = 0
-
- runs ->
- callback = ->
- hitcount++
- options =
- continuous: false
- $e.add($f).waypoint callback
- $g.waypoint callback, options
- $se.scrollTop $g.offset().top
- waits standardWait
-
- runs ->
- expect(hitcount).toEqual 3
-
- it 'uses the handler option if provided', ->
- hitcount = 0
-
- runs ->
- $e.waypoint
- handler: (dir) ->
- hitcount++
- $se.scrollTop $e.offset().top
- waits standardWait
-
- runs ->
- expect(hitcount).toEqual 1
-
- describe '#waypoint(callback, options)', ->
- beforeEach ->
- callback = ->
- hit = true
- options =
- offset: -1
- $e = $('#same1').waypoint callback, options
-
- it 'creates a waypoint', ->
- expect($.waypoints().vertical.length).toEqual 1
-
- it 'respects options', ->
- runs ->
- $se.scrollTop $e.offset().top
- waits standardWait
-
- runs ->
- expect(hit).toBeFalsy()
- $se.scrollTop($e.offset().top + 1)
- waits standardWait
-
- runs ->
- expect(hit).toBeTruthy()
-
- it 'fires the callback', ->
- runs ->
- $se.scrollTop($e.offset().top + 1)
- waits standardWait
-
- runs ->
- expect(hit).toBeTruthy()
-
- describe '#waypoint("disable")', ->
- beforeEach ->
- $e = $('#same1').waypoint ->
- hit = true
- $e.waypoint 'disable'
-
- it 'disables callback triggers', ->
- runs ->
- $se.scrollTop $e.offset().top
- waits standardWait
-
- runs ->
- expect(hit).toBeFalsy()
-
- describe '.waypoint("enable")', ->
- beforeEach ->
- $e = $('#same1').waypoint ->
- hit = true
- $e.waypoint 'disable'
- $e.waypoint 'enable'
-
- it 'enables callback triggers', ->
- runs ->
- $se.scrollTop $e.offset().top
- waits standardWait
-
- runs ->
- expect(hit).toBeTruthy()
-
- describe '#waypoint("destroy")', ->
- beforeEach ->
- $e = $('#same1').waypoint ->
- hit = true
- $e.waypoint 'destroy'
-
- it 'removes waypoint from list of waypoints', ->
- expect($.waypoints().length).toBeFalsy()
-
- it 'no longer triggers callback', ->
- runs ->
- $se.scrollTop $e.offset().top
- waits standardWait
-
- runs ->
- expect(hit).toBeFalsy()
-
- it 'does not preserve callbacks if .waypoint recalled', ->
- runs ->
- $e.waypoint({})
- $se.scrollTop $e.offset().top
- waits standardWait
-
- runs ->
- expect(hit).toBeFalsy()
-
- describe '#waypoint("prev")', ->
- it 'returns jQuery object containing previous waypoint', ->
- $e = $ '#same1'
- $f = $ '#near1'
- $e.add($f).waypoint({})
- expect($f.waypoint('prev')[0]).toEqual $e[0]
-
- it 'can be used in a non-window context', ->
- $e = $ '#inner1'
- $f = $ '#inner2'
- $e.add($f).waypoint
- context: '#bottom'
- expect($f.waypoint('prev', 'vertical', '#bottom')[0]).toEqual $e[0]
-
- describe '#waypoint("next")', ->
- it 'returns jQuery object containing next waypoint', ->
- $e = $ '#same1'
- $f = $ '#near1'
- $e.add($f).waypoint({})
- expect($e.waypoint('next')[0]).toEqual $f[0]
-
- describe 'jQuery#waypoints()', ->
- it 'starts as an empty array for each axis', ->
- expect($.waypoints().vertical.length).toBeFalsy()
- expect($.waypoints().horizontal.length).toBeFalsy()
- expect($.isPlainObject $.waypoints()).toBeTruthy()
- expect($.isArray $.waypoints().horizontal).toBeTruthy()
- expect($.isArray $.waypoints().vertical).toBeTruthy()
-
- it 'returns waypoint elements', ->
- $e = $('#same1').waypoint({})
- expect($.waypoints().vertical[0]).toEqual $e[0]
-
- it 'does not blow up with multiple waypoint', ->
- $e = $('.sameposition, #top').waypoint({})
- $e = $e.add $('#near1').waypoint({})
- expect($.waypoints().vertical.length).toEqual 4
- expect($.waypoints().vertical[0]).toEqual $('#top')[0]
-
- it 'returns horizontal elements', ->
- $e = $('#same1').waypoint
- horizontal: true
- expect($.waypoints().horizontal[0]).toEqual $e[0]
-
- describe 'Directional filters', ->
- $f = null
-
- beforeEach ->
- $e = $ '#same1'
- $f = $ '#near1'
-
- describe 'above', ->
- it 'returns waypoints only above the current scroll position', ->
- runs ->
- $e.add($f).waypoint({})
- $se.scrollTop 1500
- waits standardWait
-
- runs ->
- expect($.waypoints('above')).toEqual [$e[0]]
-
- describe 'below', ->
- it 'returns waypoints only below the current scroll position', ->
- runs ->
- $e.add($f).waypoint({})
- $se.scrollTop 1500
- waits standardWait
-
- runs ->
- expect($.waypoints('below')).toEqual [$f[0]]
-
- describe 'left', ->
- it 'returns waypoints only left of the current scroll position', ->
- runs ->
- $e.add($f).waypoint
- horizontal: true
- $se.scrollLeft 1500
- waits standardWait
-
- runs ->
- expect($.waypoints('left')).toEqual [$e[0]]
-
- describe 'right', ->
- it 'returns waypoints only right of the current scroll position', ->
- runs ->
- $e.add($f).waypoint
- horizontal: true
- $se.scrollLeft 1500
- waits standardWait
-
- runs ->
- expect($.waypoints('right')).toEqual [$f[0]]
-
-
- describe 'jQuery#waypoints("refresh")', ->
- currentDirection = null
-
- beforeEach ->
- currentDirection = null
- $e = $('#same1').waypoint (direction) ->
- currentDirection = direction
-
- it 'triggers callback if refresh crosses scroll', ->
- runs ->
- $se.scrollTop($e.offset().top - 1)
- waits standardWait
-
- runs ->
- $e.css('top', ($e.offset().top - 50) + 'px')
- $.waypoints 'refresh'
- expect(currentDirection).toEqual 'down'
- expect(currentDirection).not.toEqual 'up'
- $e.css('top', $e.offset().top + 50 + 'px')
- $.waypoints 'refresh'
- expect(currentDirection).not.toEqual 'down'
- expect(currentDirection).toEqual 'up'
-
-
- it 'does not trigger callback if onlyOnScroll true', ->
- $f = null
-
- runs ->
- $f = $('#same2').waypoint
- onlyOnScroll: true
- handler: -> hit = true
- $se.scrollTop($f.offset().top - 1)
- waits standardWait
-
- runs ->
- $f.css('top', ($f.offset().top - 50) + 'px')
- $.waypoints 'refresh'
- expect(hit).toBeFalsy()
- $f.css('top', $f.offset().top + 50 + 'px')
- $.waypoints 'refresh'
- expect(hit).toBeFalsy()
-
- it 'updates the offset', ->
- runs ->
- $se.scrollTop($e.offset().top - 51)
- $e.css('top', ($e.offset().top - 50) + 'px')
- $.waypoints 'refresh'
- waits standardWait
-
- runs ->
- expect(currentDirection).toBeFalsy()
- $se.scrollTop $e.offset().top
- waits standardWait
-
- runs ->
- expect(currentDirection).toBeTruthy()
-
- describe 'jQuery#waypoints("viewportHeight")', ->
- it 'returns window innerheight if it exists', ->
- if window.innerHeight
- expect($.waypoints 'viewportHeight').toEqual window.innerHeight
- else
- expect($.waypoints 'viewportHeight').toEqual $(window).height()
-
- describe 'jQuery#waypoints("disable")', ->
- it 'disables all waypoints', ->
- count = 0
-
- runs ->
- $e = $('.sameposition').waypoint -> count++
- $.waypoints 'disable'
- $se.scrollTop($e.offset().top + 50)
- waits standardWait
-
- runs ->
- expect(count).toEqual 0
-
- describe 'jQuery#waypoints("enable")', ->
- it 'enables all waypoints', ->
- count = 0
-
- runs ->
- $e = $('.sameposition').waypoint -> count++
- $.waypoints 'disable'
- $.waypoints 'enable'
- $se.scrollTop($e.offset().top + 50)
- waits standardWait
-
- runs ->
- expect(count).toEqual 2
-
- describe 'jQuery#waypoints("destroy")', ->
- it 'destroys all waypoints', ->
- $e = $('.sameposition').waypoint({})
- $.waypoints 'destroy'
- expect($.waypoints().vertical.length).toEqual 0
-
- describe 'jQuery#waypoints("extendFn", methodName, function)', ->
- it 'adds method to the waypoint namespace', ->
- currentArg = null
- $.waypoints 'extendFn', 'myMethod', (arg) ->
- currentArg = arg
- $('#same1').waypoint 'myMethod', 'test'
- expect(currentArg).toEqual 'test'
-
- describe 'jQuery#waypoints.settings', ->
- count = curID = null
-
- beforeEach ->
- count = 0
- $('.sameposition, #near1, #near2').waypoint ->
- count++
- curID = $(this).attr 'id'
-
- it 'throttles the scroll check', ->
- runs ->
- $se.scrollTop $('#same1').offset().top
- expect(count).toEqual 0
- waits standardWait
-
- runs ->
- expect(count).toEqual 2
-
- it 'throttles the resize event and calls refresh', ->
- runs ->
- $('#same1').css 'top', "-1000px"
- $(window).resize()
- expect(count).toEqual 0
- waits standardWait
-
- runs ->
- expect(count).toEqual 1
-
- describe 'non-window scroll context', ->
- $inner = null
-
- beforeEach ->
- $inner = $ '#bottom'
-
- it 'triggers the waypoint within its context', ->
- $e = $('#inner3').waypoint
- context: '#bottom'
- handler: -> hit = true
-
- runs ->
- $inner.scrollTop 199
- waits standardWait
-
- runs ->
- expect(hit).toBeFalsy()
- $inner.scrollTop 200
- waits standardWait
-
- runs ->
- expect(hit).toBeTruthy()
-
- it 'respects % offsets within contexts', ->
- $e = $('#inner3').waypoint
- context: '#bottom'
- offset: '100%'
- handler: -> hit = true
-
- runs ->
- $inner.scrollTop 149
- waits standardWait
-
- runs ->
- expect(hit).toBeFalsy()
- $inner.scrollTop 150
- waits standardWait
-
- runs ->
- expect(hit).toBeTruthy()
-
- it 'respects function offsets within context', ->
- $e = $('#inner3').waypoint
- context: '#bottom'
- offset: ->
- $(this).height() / 2
- handler: -> hit = true
-
- runs ->
- $inner.scrollTop 149
- waits standardWait
-
- runs ->
- expect(hit).toBeFalsy()
- $inner.scrollTop 150
- waits standardWait
-
- runs ->
- expect(hit).toBeTruthy()
-
- it 'respects bottom-in-view alias', ->
- $e = $('#inner3').waypoint
- context: '#bottom'
- offset: 'bottom-in-view'
- handler: -> hit = true
-
- runs ->
- $inner.scrollTop 249
- waits standardWait
-
- runs ->
- expect(hit).toBeFalsy()
- $inner.scrollTop 250
- waits standardWait
-
- runs ->
- expect(hit).toBeTruthy()
-
- afterEach ->
- $inner.scrollTop 0
-
- describe 'Waypoints added after load, Issue #28, 62, 63', ->
- it 'triggers down on new but already reached waypoints', ->
- runs ->
- $e = $ '#same2'
- $se.scrollTop($e.offset().top + 1)
- waits standardWait
-
- runs ->
- $e.waypoint (direction) ->
- hit = direction is 'down'
-
- waitsFor (-> hit), '#same2 to trigger', 1000
-
- describe 'Multiple waypoints on the same element', ->
- hit2 = false
-
- beforeEach ->
- hit2 = false
- $e = $('#same1').waypoint
- handler: ->
- hit = true
- $e.waypoint
- handler: ->
- hit2 = true
- offset: -50
-
- it 'triggers all handlers', ->
- runs ->
- $se.scrollTop($e.offset().top + 50)
- waits standardWait
-
- runs ->
- expect(hit and hit2).toBeTruthy()
-
- it 'uses only one element in $.waypoints() array', ->
- expect($.waypoints().vertical.length).toEqual 1
-
- it 'disables all waypoints on the element when #disabled called', ->
- runs ->
- $e.waypoint 'disable'
- $se.scrollTop($e.offset().top + 50)
- waits standardWait
-
- runs ->
- expect(hit or hit2).toBeFalsy()
-
- describe 'Horizontal waypoints', ->
- currentDirection = null
-
- beforeEach ->
- currentDirection = null
- $e = $('#same1').waypoint
- horizontal: true
- handler: (direction) ->
- currentDirection = direction
-
- it 'triggers right/left direction', ->
- runs ->
- $se.scrollLeft $e.offset().left
- waits standardWait
-
- runs ->
- expect(currentDirection).toEqual 'right'
- $se.scrollLeft($e.offset().left - 1)
- waits standardWait
-
- runs ->
- expect(currentDirection).toEqual 'left'
-
- describe 'Waypoints attached to window object, pull request 86', ->
- $win = $ window;
-
- beforeEach ->
- $e = $win.waypoint
- offset:
- -$win.height()
- handler: -> hit = true
-
- it 'triggers waypoint reached', ->
- runs ->
- $win.scrollTop($win.height() + 1)
- waits standardWait
-
- runs ->
- expect(hit).toBeTruthy()
-
- afterEach ->
- $.waypoints 'destroy'
- $se.scrollTop(0).scrollLeft 0
- hit = false
- waits standardWait
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.coffee b/waypoints.coffee
deleted file mode 100644
index 2f62e760..00000000
--- a/waypoints.coffee
+++ /dev/null
@@ -1,682 +0,0 @@
-###
-jQuery Waypoints - v2.0.1
-Copyright (c) 2011-2013 Caleb Troughton
-Dual licensed under the MIT license and GPL license.
-https://github.com/imakewebthings/jquery-waypoints/blob/master/licenses.txt
-###
-$ = window.jQuery
-$w = $ window
-
-# Internal plugin-wide variables:
-
-# - allWaypoints: A hash containing two hashes, one for vertical waypoints and
-# one for horizontal waypoints. In each hash they value is a Waypoint
-# instance and the key is that waypoint's unique ID.
-
-# - contextCounter: A counter that is incremented with each instantiation
-# of the Context class, used in its unique ID.
-
-# - contexts: A hash of all contexts. The value of each entry is a Context
-# instance and the key is that context's unique ID.
-
-# - contextKey: The DOM element for each context keeps a reference to the
-# context's unique ID in the jQuery .data() object. This is the key for that
-# data entry.
-
-# - resizeEvent: The namespaced resize event used by contexts.
-
-# - scrollEvent: The namespaced scroll event used by contexts.
-
-# - waypointCounter: A counter that is incremented with each instantiation
-# of the Waypoint class, used in its unique ID.
-
-# - waypointKey: The DOM element for each waypoint keeps a reference to an
-# array of the unique IDs of all waypoints attached to that element. This
-# array is kept in the jQuery .data() object, and this is the key for
-# that entry.
-
-# - wp: A variable shortcut for the waypoint method name on the $.fn object.
-# Using this variable just helps with minification.
-
-# - wps: A variable shortcut for the waypoints method name on the $ object.
-# Using this variable just helps with minification.
-
-allWaypoints =
- horizontal: {}
- vertical: {}
-contextCounter = 1
-contexts = {}
-contextKey = 'waypoints-context-id'
-resizeEvent = 'resize.waypoints'
-scrollEvent = 'scroll.waypoints'
-waypointCounter = 1
-waypointKey = 'waypoints-waypoint-ids'
-wp = 'waypoint'
-wps = 'waypoints'
-
-# Context: Represents a single scrolling element in which waypoints live.
-# For most users there will only be one Context, the window, but users can
-# use other scrollable elements as a context using the "context" option
-# when creating waypoints.
-
-# Properties:
-
-# - $element: jQuery object containing the context element.
-
-# - element: The raw HTMLNode of the context element.
-
-# - didResize: A flag used in throttling the resize event.
-
-# - didScroll: A flag used in throttling the scroll event.
-
-# - id: A unique identifier for the context.
-
-# - oldScroll: A hash containing...
-# - x: The context's last known horizontal scroll value.
-# - y: The context's last known vertical scroll value.
-
-# - waypoints: A hash containing two hashes with all waypoints in the context.
-# Entries are in the same style as the allWaypoints hashes:
-# (key = waypoint.id, value = waypoint)
-# - horizontal: A hash of all horizontal waypoints.
-# - vertical: A hash of all vertical waypoints.
-
-class Context
- constructor: ($element) ->
- @$element = $element
- @element = $element[0]
- @didResize = no
- @didScroll = no
- @id = 'context' + contextCounter++
- @oldScroll =
- x: $element.scrollLeft()
- y: $element.scrollTop()
- @waypoints =
- horizontal: {}
- vertical: {}
-
- # We need to keep a reference to this Context instance on the DOM node
- # so we can look it up later based on the node.
- $element.data contextKey, @id
-
- # To do that look up, we need to have this instance in the global hash.
- contexts[@id] = this
-
- # Run scroll checks on scroll, but throttle it for performance reasons.
- $element.bind scrollEvent, =>
- unless @didScroll
- @didScroll = yes
- scrollHandler = =>
- @doScroll()
- @didScroll = no
- window.setTimeout scrollHandler, $[wps].settings.scrollThrottle
-
- # Run a refresh on resize, but throttle it for performance reasons.
- $element.bind resizeEvent, =>
- unless @didResize
- @didResize = yes
- resizeHandler = =>
- $[wps] 'refresh'
- @didResize = no
- window.setTimeout resizeHandler, $[wps].settings.resizeThrottle
-
- # doScroll()
-
- # Looks at the new scroll values for the context, compares them to the old
- # scroll values, and checks to see if any waypoints should be triggered
- # by that change.
- doScroll: ->
-
- # We use some hashes with common values for each axis so that we can
- # just iterate over it rather than write the whole thing twice for
- # each axis.
- axes =
- horizontal:
- newScroll: @$element.scrollLeft()
- oldScroll: @oldScroll.x
- forward: 'right'
- backward: 'left'
- vertical:
- newScroll: @$element.scrollTop()
- oldScroll: @oldScroll.y
- forward: 'down'
- backward: 'up'
-
- # This is a small "hack" for iOS, needed because scrolls in mobile
- # Safari that start or end with the URL bar showing will cause window
- # height changes without firing a resize event.
- if 'ontouchstart' in window \
- and (!axes.vertical.oldScroll or !axes.vertical.newScroll)
- $[wps] 'refresh'
-
- # For each axis, check to see if any waypoints have been crossed.
- # Also determine the direction it's being crossed and sort/reverse all
- # crossed waypoints accordingly. And, of course, trigger the waypoints.
- $.each axes, (aKey, axis) =>
- triggered = []
- isForward = axis.newScroll > axis.oldScroll
- direction = if isForward then axis.forward else axis.backward
- $.each @waypoints[aKey], (wKey, waypoint) ->
- if axis.oldScroll < waypoint.offset <= axis.newScroll
- triggered.push waypoint
- else if axis.newScroll < waypoint.offset <= axis.oldScroll
- triggered.push waypoint
- triggered.sort (a, b) -> a.offset - b.offset
- triggered.reverse() unless isForward
- $.each triggered, (i, waypoint) ->
- if waypoint.options.continuous or i is triggered.length - 1
- waypoint.trigger [direction]
-
- # Now that we're done with the check, the new scroll values become
- # the old scroll values for the next check.
- @oldScroll =
- x: axes.horizontal.newScroll
- y: axes.vertical.newScroll
-
- # refresh()
- # Runs through all of the waypoints in the context and recalculates
- # their offsets (the scroll value at which the waypoint is triggered.)
- # If a change in offset also happens to cross the context's current
- # scroll value, the waypoint will be triggered in the appropriate direction
- # unless prevented by the "onlyOnScroll" waypoint option.
- refresh: () ->
- isWin = $.isWindow @element
- cOffset = @$element.offset()
-
- # Make sure we have the most up-to-date scroll values for our context.
- @doScroll()
-
- # Each axis recalculation needs to know some things:
-
- # - contextOffset: The distance between the edge of the document and
- # the context element.
-
- # - contextScroll: The scroll value of the context. However, if the
- # context is the window this needs to be 0 because this value only
- # comes into play when used in adjustment calculations for non-window
- # context waypoints.
-
- # - contextDimension: Width or height of the context.
-
- # - oldScroll: The scroll value of the context. Unlike "contextScroll",
- # this is the same no matter the type of context, and is used when
- # determining whether a newly added waypoint should immediately fire
- # on its first offset calculation.
-
- # - forward: Direction string passed to forward waypoint triggers.
-
- # - backward: Direction string passed to backward waypoint triggers.
-
- # - offsetProp: Key of the .offset() object for this axis.
- axes =
- horizontal:
- contextOffset: if isWin then 0 else cOffset.left
- contextScroll: if isWin then 0 else @oldScroll.x
- contextDimension: @$element.width()
- oldScroll: @oldScroll.x
- forward: 'right'
- backward: 'left'
- offsetProp: 'left'
- vertical:
- contextOffset: if isWin then 0 else cOffset.top
- contextScroll: if isWin then 0 else @oldScroll.y
- contextDimension: if isWin then $[wps]('viewportHeight') else \
- @$element.height()
- oldScroll: @oldScroll.y
- forward: 'down'
- backward: 'up'
- offsetProp: 'top'
-
- # For each axis, run through the waypoints. Store the old offset.
- # Recalculate the new offset. Check the difference against the context's
- # current scroll value and trigger any crossed waypoints accordingly.
- $.each axes, (aKey, axis) =>
- $.each @waypoints[aKey], (i, waypoint) ->
- adjustment = waypoint.options.offset
- oldOffset = waypoint.offset
- elementOffset = if $.isWindow waypoint.element then 0 else \
- waypoint.$element.offset()[axis.offsetProp]
-
- # The "offset" waypoint option (which we call "adjustment" here) can
- # be a number, percentage string, keyword string (bottom-in-view),
- # or a function. So we deal with all of these types here.
- if $.isFunction adjustment
- adjustment = adjustment.apply waypoint.element
- else if typeof adjustment is 'string'
- adjustment = parseFloat adjustment
- if waypoint.options.offset.indexOf('%') > -1
- adjustment = Math.ceil(axis.contextDimension * adjustment / 100)
-
- # We've finally calculated all the crazy little adjustments that
- # can come from using non-window contexts and the "offset" option.
- # Store the damn thing.
- waypoint.offset = elementOffset \
- - axis.contextOffset \
- + axis.contextScroll \
- - adjustment
-
- # "onlyOnScroll" tells us to not even consider triggering waypoints
- # during refresh, so we can eject early.
- return if (waypoint.options.onlyOnScroll and oldOffset?) or \
- !waypoint.enabled
-
- # Case where the refresh causes a backward trigger.
- if oldOffset isnt null and \
- oldOffset < axis.oldScroll <= waypoint.offset
- waypoint.trigger [axis.backward]
-
- # Now the forward case.
- else if oldOffset isnt null and \
- oldOffset > axis.oldScroll >= waypoint.offset
- waypoint.trigger [axis.forward]
-
- # "oldOffset" values of null mean this is the first calculation of
- # the waypoint's offset. It's a special time in a waypoint's life.
- else if oldOffset is null and axis.oldScroll >= waypoint.offset
- waypoint.trigger [axis.forward]
-
- # checkEmpty()
-
- # Looks at the waypoints hashes. If they are empty, the context removes
- # itself from the global contexts hash.
- checkEmpty: ->
- if $.isEmptyObject(@waypoints.horizontal) and \
- $.isEmptyObject(@waypoints.vertical)
- @$element.unbind [resizeEvent, scrollEvent].join(' ')
- delete contexts[@id]
-
-# Waypoint: Represents a single callback function tied to an element. An
-# element can have multiple waypoints with multiple offsets.
-
-# Properties:
-
-# - $element: jQuery object containing the waypoint element.
-
-# - element: The raw HTMLNode of the waypoint element.
-
-# - axis: 'horizontal' || 'vertical' - The axis on which this waypoint lives.
-
-# - callback: The function that is fired when the waypoint is triggered.
-
-# - context: A reference to the context this waypoint belongs to.
-
-# - enabled: Boolean indicating whether this waypoint is enabled or not.
-# Disabled waypoints are still returned in functions that aggregate
-# waypoints, but do not fire their callbacks.
-
-# - id: A unique identifier for the waypoint.
-
-# - offset: The scroll offset at which the waypoint should trigger.
-
-# - options: A hash containing the various waypoint options.
-# See $.fn.waypoint.defaults for more information on those options.
-class Waypoint
- constructor: ($element, context, options) ->
- options = $.extend {}, $.fn[wp].defaults, options
- if options.offset is 'bottom-in-view'
- options.offset = ->
- contextHeight = $[wps] 'viewportHeight'
- unless $.isWindow context.element
- contextHeight = context.$element.height()
- contextHeight - $(this).outerHeight()
-
- @$element = $element
- @element = $element[0]
- @axis = if options.horizontal then 'horizontal' else 'vertical'
- @callback = options.handler
- @context = context
- @enabled = options.enabled
- @id = 'waypoints' + waypointCounter++
- @offset = null
- @options = options
-
- # Add our new waypoint to its context.
- context.waypoints[@axis][@id] = this
-
- # Add it to the global hash.
- allWaypoints[@axis][@id] = this
-
- # Add the waypoint's id to the element's waypoint id list.
- idList = $element.data(waypointKey) ? []
- idList.push @id
- $element.data waypointKey, idList
-
- # trigger(array)
-
- # Calls the waypoint's callback function, passing to it the arguments
- # supplied in the "args" array.
- trigger: (args) ->
- return unless @enabled
- if @callback?
- @callback.apply @element, args
- if @options.triggerOnce
- @destroy()
-
- # disable()
-
- # Temporarily disables a waypoint from firing its callback.
- disable: ->
- @enabled = false
-
- # enable()
-
- # Breathe life back into the waypoint.
- enable: ->
- @context.refresh()
- @enabled = true
-
- # destroy()
-
- # Kills the waypoint for good.
- destroy: ->
- delete allWaypoints[@axis][@id]
- delete @context.waypoints[@axis][@id]
- @context.checkEmpty()
-
- # Waypoint.getWaypointsByElement(HTMLNode)
-
- # Returns an array of all Waypoint instances attached to the "element"
- # HTMLNode. Returns an empty array if there are no attached waypoints.
- @getWaypointsByElement: (element) ->
- ids = $(element).data waypointKey
- return [] unless ids
- all = $.extend {}, allWaypoints.horizontal, allWaypoints.vertical
- $.map ids, (id) ->
- all[id]
-
-# These methods are available on the $.fn object by using the method
-# name as the first argument to .waypoint. Ex: $('div').waypoint('destroy')
-methods =
-
- # init(function, object)
-
- # Creates a new waypoint (and if needed, a new context) using the supplied
- # callback function and options.
-
- # The "f" function and the "options" object are both optional, but at least
- # one must be supplied. So acceptable signatures are:
-
- # - .waypoint(f)
- # - .waypoint(options)
- # - .waypoint(f, options)
-
- # This "init" method should never need to be called explicity by the user.
- # It is the default method that is delegated to when .waypoint is called
- # with one of the above signatures.
-
- # Ex: $('div').waypoint(function(direction) {
- # // Do things
- # }, { offset: '100%' });
- init: (f, options) ->
- options ?= {}
- options.handler ?= f
-
- @each ->
- $this = $ this
- contextElement = options.context ? $.fn[wp].defaults.context
- unless $.isWindow contextElement
- contextElement = $this.closest contextElement
- contextElement = $ contextElement
- context = contexts[contextElement.data contextKey]
- context = new Context contextElement unless context
- new Waypoint $this, context, options
- $[wps] 'refresh'
- this
-
- # Disable, enable, and destroy all just delegate to the instance methods
- # of the waypoints attached to the subject elements.
- disable: -> methods._invoke this, 'disable'
- enable: -> methods._invoke this, 'enable'
- destroy: -> methods._invoke this, 'destroy'
-
- # .waypoint('prev', string, string|HTMLNode|jQuery)
-
- # Returns a jQuery object containing previous waypoint elements. This
- # creates a new entry in the jQuery object stack just like jQuery's prev
- # function. "axis" indicates the axis on which to traverse
- # ('horizontal' | 'vertical') and "selector" indicates which context
- # element to use. The defaults are 'vertical' and window respectively.
- prev: (axis, selector) ->
- methods._traverse.call this, axis, selector, (stack, index, waypoints) ->
- stack.push waypoints[index-1] if index > 0
-
- # .waypoint('next', string, string|HTMLNode|jQuery)
-
- # Returns a jQuery object containing next waypoint elements. This
- # creates a new entry in the jQuery object stack just like jQuery's next
- # function. "axis" indicates the axis on which to traverse
- # ('horizontal' | 'vertical') and "selector" indicates which context
- # element to use. The defaults are 'vertical' and window respectively.
- next: (axis, selector) ->
- methods._traverse.call this, axis, selector, (stack, index, waypoints) ->
- stack.push waypoints[index+1] if index < waypoints.length-1
-
- # Internal: Aggregates waypoints on a given axis of a context, and applies
- # a "push" callback for each element in the subject jQuery object. This
- # callback builds the element array to push to the jQuery stack.
- _traverse: (axis = 'vertical', selector = window, push) ->
- waypoints = jQMethods.aggregate selector
- stack = []
- @each ->
- index = $.inArray this, waypoints[axis]
- push stack, index, waypoints[axis]
- @pushStack stack
-
- # Internal: Finds all waypoints on a given set of "$elements" and invokes
- # "method" on each instance.
- _invoke: ($elements, method) ->
- $elements.each ->
- waypoints = Waypoint.getWaypointsByElement this
- $.each waypoints, (i, waypoint) ->
- waypoint[method]()
- true
- this
-
-# $.fn.waypoint. Let's just hook this guy up to our methods hash and
-# add some trivial error reporting for bogus calls.
-$.fn[wp] = (method, args...) ->
- if methods[method]
- methods[method].apply this, args
- else if $.isFunction(method)
- methods.init.apply this, arguments
- else if $.isPlainObject(method)
- methods.init.apply this, [null, method]
- else if !method
- $.error "jQuery Waypoints needs a callback function or handler option."
- else
- $.error "The #{method} method does not exist in jQuery Waypoints."
-
-# The default options object for a waypoint.
-
-# - context: string|HTMLNode|jQuery - The scrollable element that the waypoint
-# acts within. The waypoint will look for the closest ancestor element
-# that matches this selector or node.
-
-# - continuous: Multiple waypoints may be triggered by a single scroll check.
-# If you would like a waypoint to only trigger if it is the last waypoint
-# in a scroll check, set this to false.
-
-# - enabled: Should this waypoint start enabled (true) or disabled (false)?
-
-# - handler: This option is not defined by default, but can be used as an
-# alternate way to pass the waypoint callback function, rather than as
-# the first argument to .waypoint.
-
-# Ex: $('div').waypoint({
-# handler: function(direction) { ... }
-# });
-
-# - horizontal: Set this to true if the waypoint is, well, horizontal.
-
-# - offset: number|string|function - Determines how far from the top (or left
-# if the waypoint is horizontal) of the context's viewport to trigger the
-# waypoint. The default of 0 means that the waypoint is triggered when the
-# top of the waypoint element hits the top of the window/context-element.
-# An offset of 50 would mean the waypoint triggers when the top of the
-# element is 50 pixels from the top of the window.
-
-# A % string is translated into a percentage of the width/height of
-# the context.
-
-# If a function is passed, that function should return a number. The "this"
-# keyword within this function will be set to the raw HTMLNode of the
-# waypoint element.
-
-# - triggerOnce: If true, the waypoint will destroy itself after first trigger.
-$.fn[wp].defaults =
- context: window
- continuous: true
- enabled: true
- horizontal: false
- offset: 0
- triggerOnce: false
-
-# These methods are available on the $ object by using the method name as
-# the first argument to .waypoint. Ex: $.waypoints('refresh')
-jQMethods =
-
- # $.waypoints('refresh')
-
- # Forces a refresh on all contexts, recalculating all waypoint offsets.
- # This is done automatically on waypoint addition and during resize events,
- # but if a user does something to change the DOM, CSS, or in some way change
- # the layout of a page and its elements, they might need to call this
- # method manually.
- refresh: ->
- $.each contexts, (i, context) -> context.refresh()
-
- # $.waypoints('viewportHeight')
-
- # A utility method that returns the window height, but takes into account
- # inconsistencies that come with just using jQuery's .height() on iOS.
- viewportHeight: ->
- window.innerHeight ? $w.height()
-
- # $.waypoints(['aggregate'], [contextSelector])
-
- # Returns an object containing two HTMLNode arrays, one for each axis:
-
- # {
- # horizontal: [ HTMLNode... ]
- # vertical: [ HTMLNode... ]
- # }
-
- # This is the default method used when calling $.waypoints(). If
- # "contextSelector" is not supplied, it returns all waypoints. If
- # "contextSelector" is supplied it only returns waypoints for that context.
-
- # The array of waypoint elements is returned sorted by calculated offset,
- # the order in which they would be triggered on the page.
- aggregate: (contextSelector) ->
- collection = allWaypoints
- if contextSelector
- collection = contexts[$(contextSelector).data contextKey]?.waypoints
- return [] unless collection
- waypoints =
- horizontal: []
- vertical: []
- $.each waypoints, (axis, arr) ->
- $.each collection[axis], (key, waypoint) ->
- arr.push waypoint
- arr.sort (a, b) -> a.offset - b.offset
- waypoints[axis] = $.map arr, (waypoint) -> waypoint.element
- waypoints[axis] = $.unique waypoints[axis]
- waypoints
-
- # $.waypoints('above', [string|HTMLNode|jQuery])
-
- # Returns all vertical waypoints that lie above the current scroll position
- # of the context specified by "contextSelector". If no "contextSelector"
- # is supplied, it defaults to the window.
- above: (contextSelector = window) ->
- jQMethods._filter contextSelector, 'vertical', (context, waypoint) ->
- waypoint.offset <= context.oldScroll.y
-
- # $.waypoints('below', [string|HTMLNode|jQuery])
-
- # Returns all vertical waypoints that lie below the current scroll position
- # of the context specified by "contextSelector". If no "contextSelector"
- # is supplied, it defaults to the window.
- below: (contextSelector = window) ->
- jQMethods._filter contextSelector, 'vertical', (context, waypoint) ->
- waypoint.offset > context.oldScroll.y
-
- # $.waypoints('left', [string|HTMLNode|jQuery])
-
- # Returns all horizontal waypoints left of the current scroll position
- # of the context specified by "contextSelector". If no "contextSelector"
- # is supplied, it defaults to the window.
- left: (contextSelector = window) ->
- jQMethods._filter contextSelector, 'horizontal', (context, waypoint) ->
- waypoint.offset <= context.oldScroll.x
-
- # $.waypoints('right', [string|HTMLNode|jQuery])
-
- # Returns all horizontal waypoints right of the current scroll position
- # of the context specified by "contextSelector". If no "contextSelector"
- # is supplied, it defaults to the window.
- right: (contextSelector = window) ->
- jQMethods._filter contextSelector, 'horizontal', (context, waypoint) ->
- waypoint.offset > context.oldScroll.x
-
- # $.waypoints('enable/disable/destroy')
-
- # These methods delegate to the enable/disable/destroy instance methods
- # for all waypoints.
- enable: -> jQMethods._invoke 'enable'
- disable: -> jQMethods._invoke 'disable'
- destroy: -> jQMethods._invoke 'destroy'
-
- # $.waypoints('extendFn', string, function)
-
- # Extends the $.fn.waypoint method object with a new method, "f". This
- # just lets other modules piggyback on the .waypoint namespace.
- extendFn: (methodName, f) ->
- methods[methodName] = f
-
- # Internal: Invokes "method" on all waypoints.
- _invoke: (method) ->
- waypoints = $.extend {}, allWaypoints.vertical, allWaypoints.horizontal
- $.each waypoints, (key, waypoint) ->
- waypoint[method]()
- true
-
- # Internal: Returns an array of all HTMLNodes for each waypoint that passes # the "test" function. Only waypoints within the "selector" context on the
- # "axis" axis are tested. As with .aggregate, the array is sorted by
- # calculated offset (trigger order).
- _filter: (selector, axis, test) ->
- context = contexts[$(selector).data contextKey]
- return [] unless context
- waypoints = []
- $.each context.waypoints[axis], (i, waypoint) ->
- waypoints.push waypoint if test context, waypoint
- waypoints.sort (a, b) -> a.offset - b.offset
- $.map waypoints, (waypoint) -> waypoint.element
-
-# Hook up jQMethods to the $.waypoints namespace.
-$[wps] = (method, args...) ->
- if jQMethods[method]
- jQMethods[method].apply null, args
- else
- jQMethods.aggregate.call null, method
-
-# Plugin-wide settings:
-
-# - resizeThrottle: 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: 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: 100
- scrollThrottle: 30
-
-# Ensure a refresh on page load. Newly loaded images often shift layout.
-$w.load -> $[wps] 'refresh'
\ No newline at end of file
diff --git a/waypoints.js b/waypoints.js
deleted file mode 100644
index aa6b8730..00000000
--- a/waypoints.js
+++ /dev/null
@@ -1,510 +0,0 @@
-// Generated by CoffeeScript 1.4.0
-
-/*
-jQuery Waypoints - v2.0.1
-Copyright (c) 2011-2013 Caleb Troughton
-Dual licensed under the MIT license and GPL license.
-https://github.com/imakewebthings/jquery-waypoints/blob/master/licenses.txt
-*/
-
-
-(function() {
- var $, $w, Context, Waypoint, allWaypoints, contextCounter, contextKey, contexts, jQMethods, methods, resizeEvent, scrollEvent, waypointCounter, waypointKey, wp, wps,
- __indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; },
- __slice = [].slice;
-
- $ = window.jQuery;
-
- $w = $(window);
-
- allWaypoints = {
- horizontal: {},
- vertical: {}
- };
-
- contextCounter = 1;
-
- contexts = {};
-
- contextKey = 'waypoints-context-id';
-
- resizeEvent = 'resize.waypoints';
-
- scrollEvent = 'scroll.waypoints';
-
- waypointCounter = 1;
-
- waypointKey = 'waypoints-waypoint-ids';
-
- wp = 'waypoint';
-
- wps = 'waypoints';
-
- Context = (function() {
-
- function Context($element) {
- var _this = this;
- this.$element = $element;
- this.element = $element[0];
- this.didResize = false;
- this.didScroll = false;
- this.id = 'context' + contextCounter++;
- this.oldScroll = {
- x: $element.scrollLeft(),
- y: $element.scrollTop()
- };
- this.waypoints = {
- horizontal: {},
- vertical: {}
- };
- $element.data(contextKey, this.id);
- contexts[this.id] = this;
- $element.bind(scrollEvent, function() {
- var scrollHandler;
- if (!_this.didScroll) {
- _this.didScroll = true;
- scrollHandler = function() {
- _this.doScroll();
- return _this.didScroll = false;
- };
- return window.setTimeout(scrollHandler, $[wps].settings.scrollThrottle);
- }
- });
- $element.bind(resizeEvent, function() {
- var resizeHandler;
- if (!_this.didResize) {
- _this.didResize = true;
- resizeHandler = function() {
- $[wps]('refresh');
- return _this.didResize = false;
- };
- return window.setTimeout(resizeHandler, $[wps].settings.resizeThrottle);
- }
- });
- }
-
- Context.prototype.doScroll = function() {
- var axes,
- _this = this;
- axes = {
- horizontal: {
- newScroll: this.$element.scrollLeft(),
- oldScroll: this.oldScroll.x,
- forward: 'right',
- backward: 'left'
- },
- vertical: {
- newScroll: this.$element.scrollTop(),
- oldScroll: this.oldScroll.y,
- forward: 'down',
- backward: 'up'
- }
- };
- if (__indexOf.call(window, 'ontouchstart') >= 0 && (!axes.vertical.oldScroll || !axes.vertical.newScroll)) {
- $[wps]('refresh');
- }
- $.each(axes, function(aKey, axis) {
- var direction, isForward, triggered;
- triggered = [];
- isForward = axis.newScroll > axis.oldScroll;
- direction = isForward ? axis.forward : axis.backward;
- $.each(_this.waypoints[aKey], function(wKey, waypoint) {
- var _ref, _ref1;
- if ((axis.oldScroll < (_ref = waypoint.offset) && _ref <= axis.newScroll)) {
- return triggered.push(waypoint);
- } else if ((axis.newScroll < (_ref1 = waypoint.offset) && _ref1 <= axis.oldScroll)) {
- return triggered.push(waypoint);
- }
- });
- triggered.sort(function(a, b) {
- return a.offset - b.offset;
- });
- if (!isForward) {
- triggered.reverse();
- }
- return $.each(triggered, function(i, waypoint) {
- if (waypoint.options.continuous || i === triggered.length - 1) {
- return waypoint.trigger([direction]);
- }
- });
- });
- return this.oldScroll = {
- x: axes.horizontal.newScroll,
- y: axes.vertical.newScroll
- };
- };
-
- Context.prototype.refresh = function() {
- var axes, cOffset, isWin,
- _this = this;
- isWin = $.isWindow(this.element);
- cOffset = this.$element.offset();
- this.doScroll();
- axes = {
- horizontal: {
- contextOffset: isWin ? 0 : cOffset.left,
- contextScroll: isWin ? 0 : this.oldScroll.x,
- contextDimension: this.$element.width(),
- oldScroll: this.oldScroll.x,
- forward: 'right',
- backward: 'left',
- offsetProp: 'left'
- },
- vertical: {
- contextOffset: isWin ? 0 : cOffset.top,
- contextScroll: isWin ? 0 : this.oldScroll.y,
- contextDimension: isWin ? $[wps]('viewportHeight') : this.$element.height(),
- oldScroll: this.oldScroll.y,
- forward: 'down',
- backward: 'up',
- offsetProp: 'top'
- }
- };
- return $.each(axes, function(aKey, axis) {
- return $.each(_this.waypoints[aKey], function(i, waypoint) {
- var adjustment, elementOffset, oldOffset, _ref, _ref1;
- adjustment = waypoint.options.offset;
- oldOffset = waypoint.offset;
- elementOffset = $.isWindow(waypoint.element) ? 0 : waypoint.$element.offset()[axis.offsetProp];
- if ($.isFunction(adjustment)) {
- adjustment = adjustment.apply(waypoint.element);
- } else if (typeof adjustment === 'string') {
- adjustment = parseFloat(adjustment);
- if (waypoint.options.offset.indexOf('%') > -1) {
- adjustment = Math.ceil(axis.contextDimension * adjustment / 100);
- }
- }
- waypoint.offset = elementOffset - axis.contextOffset + axis.contextScroll - adjustment;
- if ((waypoint.options.onlyOnScroll && (oldOffset != null)) || !waypoint.enabled) {
- return;
- }
- if (oldOffset !== null && (oldOffset < (_ref = axis.oldScroll) && _ref <= waypoint.offset)) {
- return waypoint.trigger([axis.backward]);
- } else if (oldOffset !== null && (oldOffset > (_ref1 = axis.oldScroll) && _ref1 >= waypoint.offset)) {
- return waypoint.trigger([axis.forward]);
- } else if (oldOffset === null && axis.oldScroll >= waypoint.offset) {
- return waypoint.trigger([axis.forward]);
- }
- });
- });
- };
-
- Context.prototype.checkEmpty = function() {
- if ($.isEmptyObject(this.waypoints.horizontal) && $.isEmptyObject(this.waypoints.vertical)) {
- this.$element.unbind([resizeEvent, scrollEvent].join(' '));
- return delete contexts[this.id];
- }
- };
-
- return Context;
-
- })();
-
- Waypoint = (function() {
-
- function Waypoint($element, context, options) {
- var idList, _ref;
- options = $.extend({}, $.fn[wp].defaults, options);
- if (options.offset === 'bottom-in-view') {
- options.offset = function() {
- var contextHeight;
- contextHeight = $[wps]('viewportHeight');
- if (!$.isWindow(context.element)) {
- contextHeight = context.$element.height();
- }
- return contextHeight - $(this).outerHeight();
- };
- }
- this.$element = $element;
- this.element = $element[0];
- this.axis = options.horizontal ? 'horizontal' : 'vertical';
- this.callback = options.handler;
- this.context = context;
- this.enabled = options.enabled;
- this.id = 'waypoints' + waypointCounter++;
- this.offset = null;
- this.options = options;
- context.waypoints[this.axis][this.id] = this;
- allWaypoints[this.axis][this.id] = this;
- idList = (_ref = $element.data(waypointKey)) != null ? _ref : [];
- idList.push(this.id);
- $element.data(waypointKey, idList);
- }
-
- Waypoint.prototype.trigger = function(args) {
- if (!this.enabled) {
- return;
- }
- if (this.callback != null) {
- this.callback.apply(this.element, args);
- }
- if (this.options.triggerOnce) {
- return this.destroy();
- }
- };
-
- Waypoint.prototype.disable = function() {
- return this.enabled = false;
- };
-
- Waypoint.prototype.enable = function() {
- this.context.refresh();
- return this.enabled = true;
- };
-
- Waypoint.prototype.destroy = function() {
- delete allWaypoints[this.axis][this.id];
- delete this.context.waypoints[this.axis][this.id];
- return this.context.checkEmpty();
- };
-
- Waypoint.getWaypointsByElement = function(element) {
- var all, ids;
- ids = $(element).data(waypointKey);
- if (!ids) {
- return [];
- }
- all = $.extend({}, allWaypoints.horizontal, allWaypoints.vertical);
- return $.map(ids, function(id) {
- return all[id];
- });
- };
-
- return Waypoint;
-
- })();
-
- methods = {
- init: function(f, options) {
- var _ref;
- if (options == null) {
- options = {};
- }
- if ((_ref = options.handler) == null) {
- options.handler = f;
- }
- this.each(function() {
- var $this, context, contextElement, _ref1;
- $this = $(this);
- contextElement = (_ref1 = options.context) != null ? _ref1 : $.fn[wp].defaults.context;
- if (!$.isWindow(contextElement)) {
- contextElement = $this.closest(contextElement);
- }
- contextElement = $(contextElement);
- context = contexts[contextElement.data(contextKey)];
- if (!context) {
- context = new Context(contextElement);
- }
- return new Waypoint($this, context, options);
- });
- $[wps]('refresh');
- return this;
- },
- disable: function() {
- return methods._invoke(this, 'disable');
- },
- enable: function() {
- return methods._invoke(this, 'enable');
- },
- destroy: function() {
- return methods._invoke(this, 'destroy');
- },
- prev: function(axis, selector) {
- return methods._traverse.call(this, axis, selector, function(stack, index, waypoints) {
- if (index > 0) {
- return stack.push(waypoints[index - 1]);
- }
- });
- },
- next: function(axis, selector) {
- return methods._traverse.call(this, axis, selector, function(stack, index, waypoints) {
- if (index < waypoints.length - 1) {
- return stack.push(waypoints[index + 1]);
- }
- });
- },
- _traverse: function(axis, selector, push) {
- var stack, waypoints;
- if (axis == null) {
- axis = 'vertical';
- }
- if (selector == null) {
- selector = window;
- }
- waypoints = jQMethods.aggregate(selector);
- stack = [];
- this.each(function() {
- var index;
- index = $.inArray(this, waypoints[axis]);
- return push(stack, index, waypoints[axis]);
- });
- return this.pushStack(stack);
- },
- _invoke: function($elements, method) {
- $elements.each(function() {
- var waypoints;
- waypoints = Waypoint.getWaypointsByElement(this);
- return $.each(waypoints, function(i, waypoint) {
- waypoint[method]();
- return true;
- });
- });
- return this;
- }
- };
-
- $.fn[wp] = function() {
- var args, method;
- method = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
- if (methods[method]) {
- return methods[method].apply(this, args);
- } else if ($.isFunction(method)) {
- return methods.init.apply(this, arguments);
- } else if ($.isPlainObject(method)) {
- return methods.init.apply(this, [null, method]);
- } else if (!method) {
- return $.error("jQuery Waypoints needs a callback function or handler option.");
- } else {
- return $.error("The " + method + " method does not exist in jQuery Waypoints.");
- }
- };
-
- $.fn[wp].defaults = {
- context: window,
- continuous: true,
- enabled: true,
- horizontal: false,
- offset: 0,
- triggerOnce: false
- };
-
- jQMethods = {
- refresh: function() {
- return $.each(contexts, function(i, context) {
- return context.refresh();
- });
- },
- viewportHeight: function() {
- var _ref;
- return (_ref = window.innerHeight) != null ? _ref : $w.height();
- },
- aggregate: function(contextSelector) {
- var collection, waypoints, _ref;
- collection = allWaypoints;
- if (contextSelector) {
- collection = (_ref = contexts[$(contextSelector).data(contextKey)]) != null ? _ref.waypoints : void 0;
- }
- if (!collection) {
- return [];
- }
- waypoints = {
- horizontal: [],
- vertical: []
- };
- $.each(waypoints, function(axis, arr) {
- $.each(collection[axis], function(key, waypoint) {
- return arr.push(waypoint);
- });
- arr.sort(function(a, b) {
- return a.offset - b.offset;
- });
- waypoints[axis] = $.map(arr, function(waypoint) {
- return waypoint.element;
- });
- return waypoints[axis] = $.unique(waypoints[axis]);
- });
- return waypoints;
- },
- above: function(contextSelector) {
- if (contextSelector == null) {
- contextSelector = window;
- }
- return jQMethods._filter(contextSelector, 'vertical', function(context, waypoint) {
- return waypoint.offset <= context.oldScroll.y;
- });
- },
- below: function(contextSelector) {
- if (contextSelector == null) {
- contextSelector = window;
- }
- return jQMethods._filter(contextSelector, 'vertical', function(context, waypoint) {
- return waypoint.offset > context.oldScroll.y;
- });
- },
- left: function(contextSelector) {
- if (contextSelector == null) {
- contextSelector = window;
- }
- return jQMethods._filter(contextSelector, 'horizontal', function(context, waypoint) {
- return waypoint.offset <= context.oldScroll.x;
- });
- },
- right: function(contextSelector) {
- if (contextSelector == null) {
- contextSelector = window;
- }
- return jQMethods._filter(contextSelector, 'horizontal', function(context, waypoint) {
- return waypoint.offset > context.oldScroll.x;
- });
- },
- enable: function() {
- return jQMethods._invoke('enable');
- },
- disable: function() {
- return jQMethods._invoke('disable');
- },
- destroy: function() {
- return jQMethods._invoke('destroy');
- },
- extendFn: function(methodName, f) {
- return methods[methodName] = f;
- },
- _invoke: function(method) {
- var waypoints;
- waypoints = $.extend({}, allWaypoints.vertical, allWaypoints.horizontal);
- return $.each(waypoints, function(key, waypoint) {
- waypoint[method]();
- return true;
- });
- },
- _filter: function(selector, axis, test) {
- var context, waypoints;
- context = contexts[$(selector).data(contextKey)];
- if (!context) {
- return [];
- }
- waypoints = [];
- $.each(context.waypoints[axis], function(i, waypoint) {
- if (test(context, waypoint)) {
- return waypoints.push(waypoint);
- }
- });
- waypoints.sort(function(a, b) {
- return a.offset - b.offset;
- });
- return $.map(waypoints, function(waypoint) {
- return waypoint.element;
- });
- }
- };
-
- $[wps] = function() {
- var args, method;
- method = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
- if (jQMethods[method]) {
- return jQMethods[method].apply(null, args);
- } else {
- return jQMethods.aggregate.call(null, method);
- }
- };
-
- $[wps].settings = {
- resizeThrottle: 100,
- scrollThrottle: 30
- };
-
- $w.load(function() {
- return $[wps]('refresh');
- });
-
-}).call(this);
diff --git a/waypoints.min.js b/waypoints.min.js
deleted file mode 100644
index 4fae8c51..00000000
--- a/waypoints.min.js
+++ /dev/null
@@ -1,8 +0,0 @@
-// Generated by CoffeeScript 1.4.0
-/*
-jQuery Waypoints - v2.0.1
-Copyright (c) 2011-2013 Caleb Troughton
-Dual licensed under the MIT license and GPL license.
-https://github.com/imakewebthings/jquery-waypoints/blob/master/licenses.txt
-*/
-(function(){var t,e,n,r,i,o,l,s,f,u,a,c,h,d,p,w,y=[].indexOf||function(t){for(var e=0,n=this.length;e
=0&&(!e.vertical.oldScroll||!e.vertical.newScroll)){t[w]("refresh")}t.each(e,function(e,r){var i,o,l;l=[];o=r.newScroll>r.oldScroll;i=o?r.forward:r.backward;t.each(n.waypoints[e],function(t,e){var n,i;if(r.oldScroll<(n=e.offset)&&n<=r.newScroll){return l.push(e)}else if(r.newScroll<(i=e.offset)&&i<=r.oldScroll){return l.push(e)}});l.sort(function(t,e){return t.offset-e.offset});if(!o){l.reverse()}return t.each(l,function(t,e){if(e.options.continuous||t===l.length-1){return e.trigger([i])}})});return this.oldScroll={x:e.horizontal.newScroll,y:e.vertical.newScroll}};e.prototype.refresh=function(){var e,n,r,i=this;r=t.isWindow(this.element);n=this.$element.offset();this.doScroll();e={horizontal:{contextOffset:r?0:n.left,contextScroll:r?0:this.oldScroll.x,contextDimension:this.$element.width(),oldScroll:this.oldScroll.x,forward:"right",backward:"left",offsetProp:"left"},vertical:{contextOffset:r?0:n.top,contextScroll:r?0:this.oldScroll.y,contextDimension:r?t[w]("viewportHeight"):this.$element.height(),oldScroll:this.oldScroll.y,forward:"down",backward:"up",offsetProp:"top"}};return t.each(e,function(e,n){return t.each(i.waypoints[e],function(e,r){var i,o,l,s,f;i=r.options.offset;l=r.offset;o=t.isWindow(r.element)?0:r.$element.offset()[n.offsetProp];if(t.isFunction(i)){i=i.apply(r.element)}else if(typeof i==="string"){i=parseFloat(i);if(r.options.offset.indexOf("%")>-1){i=Math.ceil(n.contextDimension*i/100)}}r.offset=o-n.contextOffset+n.contextScroll-i;if(r.options.onlyOnScroll&&l!=null||!r.enabled){return}if(l!==null&&l<(s=n.oldScroll)&&s<=r.offset){return r.trigger([n.backward])}else if(l!==null&&l>(f=n.oldScroll)&&f>=r.offset){return r.trigger([n.forward])}else if(l===null&&n.oldScroll>=r.offset){return r.trigger([n.forward])}})})};e.prototype.checkEmpty=function(){if(t.isEmptyObject(this.waypoints.horizontal)&&t.isEmptyObject(this.waypoints.vertical)){this.$element.unbind([a,c].join(" "));return delete s[this.id]}};return e}();r=function(){function e(e,n,r){var o,l;r=t.extend({},t.fn[p].defaults,r);if(r.offset==="bottom-in-view"){r.offset=function(){var e;e=t[w]("viewportHeight");if(!t.isWindow(n.element)){e=n.$element.height()}return e-t(this).outerHeight()}}this.$element=e;this.element=e[0];this.axis=r.horizontal?"horizontal":"vertical";this.callback=r.handler;this.context=n;this.enabled=r.enabled;this.id="waypoints"+h++;this.offset=null;this.options=r;n.waypoints[this.axis][this.id]=this;i[this.axis][this.id]=this;o=(l=e.data(d))!=null?l:[];o.push(this.id);e.data(d,o)}e.prototype.trigger=function(t){if(!this.enabled){return}if(this.callback!=null){this.callback.apply(this.element,t)}if(this.options.triggerOnce){return this.destroy()}};e.prototype.disable=function(){return this.enabled=false};e.prototype.enable=function(){this.context.refresh();return this.enabled=true};e.prototype.destroy=function(){delete i[this.axis][this.id];delete this.context.waypoints[this.axis][this.id];return this.context.checkEmpty()};e.getWaypointsByElement=function(e){var n,r;r=t(e).data(d);if(!r){return[]}n=t.extend({},i.horizontal,i.vertical);return t.map(r,function(t){return n[t]})};return e}();u={init:function(e,i){var o;if(i==null){i={}}if((o=i.handler)==null){i.handler=e}this.each(function(){var e,o,f,u;e=t(this);f=(u=i.context)!=null?u:t.fn[p].defaults.context;if(!t.isWindow(f)){f=e.closest(f)}f=t(f);o=s[f.data(l)];if(!o){o=new n(f)}return new r(e,o,i)});t[w]("refresh");return this},disable:function(){return u._invoke(this,"disable")},enable:function(){return u._invoke(this,"enable")},destroy:function(){return u._invoke(this,"destroy")},prev:function(t,e){return u._traverse.call(this,t,e,function(t,e,n){if(e>0){return t.push(n[e-1])}})},next:function(t,e){return u._traverse.call(this,t,e,function(t,e,n){if(e<=t.oldScroll.y})},below:function(t){if(t==null){t=window}return f._filter(t,"vertical",function(t,e){return e.offset>t.oldScroll.y})},left:function(t){if(t==null){t=window}return f._filter(t,"horizontal",function(t,e){return e.offset<=t.oldScroll.x})},right:function(t){if(t==null){t=window}return f._filter(t,"horizontal",function(t,e){return e.offset>t.oldScroll.x})},enable:function(){return f._invoke("enable")},disable:function(){return f._invoke("disable")},destroy:function(){return f._invoke("destroy")},extendFn:function(t,e){return u[t]=e},_invoke:function(e){var n;n=t.extend({},i.vertical,i.horizontal);return t.each(n,function(t,n){n[e]();return true})},_filter:function(e,n,r){var i,o;i=s[t(e).data(l)];if(!i){return[]}o=[];t.each(i.waypoints[n],function(t,e){if(r(i,e)){return o.push(e)}});o.sort(function(t,e){return t.offset-e.offset});return t.map(o,function(t){return t.element})}};t[w]=function(){var t,e;e=arguments[0],t=2<=arguments.length?v.call(arguments,1):[];if(f[e]){return f[e].apply(null,t)}else{return f.aggregate.call(null,e)}};t[w].settings={resizeThrottle:100,scrollThrottle:30};e.load(function(){return t[w]("refresh")})}).call(this);
\ No newline at end of file