Merge branch 'master' into production

This commit is contained in:
Matt Lott 2014-12-09 17:33:26 -08:00
commit 8d7c8dc52a
35 changed files with 999 additions and 453 deletions

Binary file not shown.

After

Width:  |  Height:  |  Size: 329 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 552 KiB

View file

@ -1,328 +0,0 @@
/*
Jasmine-Ajax : a set of helpers for testing AJAX requests under the Jasmine
BDD framework for JavaScript.
http://github.com/pivotal/jasmine-ajax
Jasmine Home page: http://pivotal.github.com/jasmine
Copyright (c) 2008-2013 Pivotal Labs
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
(function() {
function extend(destination, source, propertiesToSkip) {
propertiesToSkip = propertiesToSkip || [];
for (var property in source) {
if (!arrayContains(propertiesToSkip, property)) {
destination[property] = source[property];
}
}
return destination;
}
function arrayContains(arr, item) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] === item) {
return true;
}
}
return false;
}
function MockAjax(global) {
var requestTracker = new RequestTracker(),
stubTracker = new StubTracker(),
realAjaxFunction = global.XMLHttpRequest,
mockAjaxFunction = fakeRequest(requestTracker, stubTracker);
this.install = function() {
global.XMLHttpRequest = mockAjaxFunction;
};
this.uninstall = function() {
global.XMLHttpRequest = realAjaxFunction;
this.stubs.reset();
this.requests.reset();
};
this.stubRequest = function(url, data) {
var stub = new RequestStub(url, data);
stubTracker.addStub(stub);
return stub;
};
this.withMock = function(closure) {
this.install();
try {
closure();
} finally {
this.uninstall();
}
};
this.requests = requestTracker;
this.stubs = stubTracker;
}
function StubTracker() {
var stubs = [];
this.addStub = function(stub) {
stubs.push(stub);
};
this.reset = function() {
stubs = [];
};
this.findStub = function(url, data) {
for (var i = stubs.length - 1; i >= 0; i--) {
var stub = stubs[i];
if (stub.matches(url, data)) {
return stub;
}
}
};
}
function fakeRequest(requestTracker, stubTracker) {
function FakeXMLHttpRequest() {
requestTracker.track(this);
this.requestHeaders = {};
}
var iePropertiesThatCannotBeCopied = ['responseBody', 'responseText', 'responseXML', 'status', 'statusText', 'responseTimeout'];
extend(FakeXMLHttpRequest.prototype, new window.XMLHttpRequest(), iePropertiesThatCannotBeCopied);
extend(FakeXMLHttpRequest.prototype, {
open: function() {
this.method = arguments[0];
this.url = arguments[1];
this.username = arguments[3];
this.password = arguments[4];
this.readyState = 1;
this.onreadystatechange();
},
setRequestHeader: function(header, value) {
this.requestHeaders[header] = value;
},
abort: function() {
this.readyState = 0;
this.status = 0;
this.statusText = "abort";
this.onreadystatechange();
},
readyState: 0,
onload: function() {
},
onreadystatechange: function(isTimeout) {
},
status: null,
send: function(data) {
this.params = data;
this.readyState = 2;
this.onreadystatechange();
var stub = stubTracker.findStub(this.url, data);
if (stub) {
this.response(stub);
}
},
data: function() {
var data = {};
if (typeof this.params !== 'string') { return data; }
var params = this.params.split('&');
for (var i = 0; i < params.length; ++i) {
var kv = params[i].replace(/\+/g, ' ').split('=');
var key = decodeURIComponent(kv[0]);
data[key] = data[key] || [];
data[key].push(decodeURIComponent(kv[1]));
}
return data;
},
getResponseHeader: function(name) {
return this.responseHeaders[name];
},
getAllResponseHeaders: function() {
var responseHeaders = [];
for (var i in this.responseHeaders) {
if (this.responseHeaders.hasOwnProperty(i)) {
responseHeaders.push(i + ': ' + this.responseHeaders[i]);
}
}
return responseHeaders.join('\r\n');
},
responseText: null,
response: function(response) {
this.status = response.status;
this.statusText = response.statusText || "";
this.responseText = response.responseText || "";
this.readyState = 4;
this.responseHeaders = response.responseHeaders ||
{"Content-type": response.contentType || "application/json" };
this.onload();
this.onreadystatechange();
},
responseTimeout: function() {
this.readyState = 4;
jasmine.clock().tick(30000);
this.onreadystatechange('timeout');
}
});
return FakeXMLHttpRequest;
}
function RequestTracker() {
var requests = [];
this.track = function(request) {
requests.push(request);
};
this.first = function() {
return requests[0];
};
this.count = function() {
return requests.length;
};
this.reset = function() {
requests = [];
};
this.mostRecent = function() {
return requests[requests.length - 1];
};
this.at = function(index) {
return requests[index];
};
this.all = function() {
return requests.slice(0);
};
this.filter = function(url_to_match) {
if (requests.length == 0) return [];
var matching_requests = [];
for (var i = 0; i < requests.length; i++) {
if (url_to_match instanceof RegExp &&
url_to_match.test(requests[i].url)) {
matching_requests.push(requests[i]);
} else if (url_to_match instanceof Function &&
url_to_match(requests[i])) {
matching_requests.push(requests[i]);
} else {
if (requests[i].url == url_to_match) {
matching_requests.push(requests[i]);
}
}
}
return matching_requests;
};
this.sendResponses = function(responseMap) {
var urls = Object.keys(responseMap);
var success = true;
for(var i in urls) {
var url = urls[i];
var responseBody = responseMap[url];
var responded = false;
var requests = jasmine.Ajax.requests.all().slice();
for(var j in requests) {
var request = requests[j];
if(request.url.startsWith(url)) {
request.response({status: 200, responseText: JSON.stringify(responseBody)});
responded = true;
break;
}
}
if(!responded) {
var allRequests = jasmine.Ajax.requests.all();
urls = [];
for(var k in allRequests) urls.push(allRequests[k].url);
console.error('could not find response for', url, 'in', urls, allRequests);
success = false;
continue;
}
}
return success;
}
}
function RequestStub(url, stubData) {
var split = url.split('?');
this.url = split[0];
var normalizeQuery = function(query) {
return query ? query.split('&').sort().join('&') : undefined;
};
this.query = normalizeQuery(split[1]);
this.data = normalizeQuery(stubData);
this.andReturn = function(options) {
this.status = options.status || 200;
this.contentType = options.contentType;
this.responseText = options.responseText;
};
this.matches = function(fullUrl, data) {
var urlSplit = fullUrl.split('?'),
url = urlSplit[0],
query = urlSplit[1];
return this.url === url && this.query === normalizeQuery(query) && (!this.data || this.data === normalizeQuery(data));
};
}
if (typeof window === "undefined" && typeof exports === "object") {
exports.MockAjax = MockAjax;
jasmine.Ajax = new MockAjax(exports);
} else {
window.MockAjax = MockAjax;
jasmine.Ajax = new MockAjax(window);
}
}());

View file

@ -20,6 +20,7 @@ module.exports = ModuleLoader = class ModuleLoader extends CocoClass
wrapped = _.wrap window.require, (func, name, loaderPath) ->
# vendor libraries aren't actually wrapped with common.js, so short circuit those requires
return {} if _.string.startsWith(name, 'vendor/')
return {} if name is 'tests'
name = 'core/auth' if name is 'lib/auth' # proxy for iPad until it's been updated to use the new, refactored location. TODO: remove this
return func(name, loaderPath)
_.extend wrapped, window.require # for functions like 'list'

View file

@ -207,6 +207,11 @@ module.exports = LevelOptions =
hidesCodeToolbar: true
requiredGear: {feet: 'leather-boots', 'right-hand': 'crude-builders-hammer'}
restrictedGear: {feet: 'simple-boots', 'right-hand': 'simple-sword'}
'patrol-buster':
hidesRealTimePlayback: true
hidesCodeToolbar: true
requiredGear: {feet: 'leather-boots', 'right-hand': 'simple-sword', 'programming-book': 'programmaticon-ii', eyes: 'crude-glasses'}
restrictedGear: {feet: 'simple-boots', 'right-hand': 'crude-builders-hammer', 'programming-book': 'programmaticon-i'}
'endangered-burl':
hidesRealTimePlayback: true
hidesCodeToolbar: true

View file

@ -560,8 +560,8 @@ module.exports = Lank = class Lank extends CocoClass
updateMarks: ->
return unless @options.camera
@addMark 'repair', null, 'repair' if @thang?.errorsOut
@marks.repair?.toggle @thang?.errorsOut
@addMark 'repair', null, 'repair' if @thang?.erroredOut
@marks.repair?.toggle @thang?.erroredOut
if @selected
@marks[range['name']].toggle true for range in @ranges

View file

@ -128,6 +128,7 @@ module.exports = class User extends CocoModel
getGemPromptGroup: ->
# A/B Testing whether extra prompt when low gems leads to more gem purchases
# TODO: Rename gem purchase event in BuyGemsModal to 'Started gem purchase' after this test is over
return @gemPromptGroup if @gemPromptGroup
group = me.get('testGroupNumber') % 8
@gemPromptGroup = switch group

View file

@ -1,11 +1,14 @@
CocoView = require 'views/core/CocoView'
RootView = require 'views/core/RootView'
template = require 'templates/test'
requireUtils = require 'lib/requireUtils'
require 'vendor/jasmine-bundle'
require 'tests'
TEST_REQUIRE_PREFIX = 'test/app/'
TEST_URL_PREFIX = '/test/'
module.exports = TestView = class TestView extends CocoView
module.exports = TestView = class TestView extends RootView
id: 'test-view'
template: template
reloadOnClose: true
@ -16,24 +19,8 @@ module.exports = TestView = class TestView extends CocoView
constructor: (options, @subPath='') ->
super(options)
@subPath = @subPath[1..] if @subPath[0] is '/'
@loadTestingLibs()
loadTestingLibs: ->
@queue = new createjs.LoadQueue() unless @queue
@queue.on('complete', @scriptsLoaded, @)
@queue.on('fileload', @onFileLoad, @)
for f in ['jasmine', 'jasmine-html', 'boot', 'mock-ajax', 'test-app']
if f not in @loadedFileIDs
@queue.loadFile({
id: f
src: "/javascripts/#{f}.js"
type: createjs.LoadQueue.JAVASCRIPT
})
onFileLoad: (e) ->
@loadedFileIDs.push e.item.id if e.item.id
scriptsLoaded: ->
afterInsert: ->
@initSpecFiles()
@render()
TestView.runTests(@specFiles)

View file

@ -36,10 +36,6 @@ DEFAULT_COMPONENTS =
Mark: []
Item: [LC('Item')]
class ItemThangTypeSearchCollection extends CocoCollection
url: '/db/thang.type?view=items&project=original,name,version,slug,kind,components'
model: ThangType
module.exports = class ThangComponentsEditView extends CocoView
id: 'thang-components-edit-view'
template: template

View file

@ -45,7 +45,7 @@ module.exports = class SimulateTabView extends CocoView
onSimulateButtonClick: (e) ->
application.tracker?.trackEvent 'Simulate Button Click', {}
@startSimulating
@startSimulating()
startSimulating: ->
@simulationPageRefreshTimeout = _.delay @refreshAndContinueSimulating, 20 * 60 * 1000

View file

@ -644,9 +644,21 @@ forest = [
original: '5446cb40ce01c23e05ecf027'
description: 'Stay alive and navigate through the forest.'
nextLevels:
continue: 'endangered-burl'
continue: 'patrol-buster'
x: 24
y: 35
adventurer: true
}
{
name: 'Patrol Buster'
type: 'hero'
id: 'patrol-buster'
original: '5487330d84f7b4dac246d440'
description: 'Defeat ogre patrols with new, selective targeting skills.'
nextLevels:
continue: 'thornbush-farm'
x: 34
y: 25
}
{
name: 'Endangered Burl'

View file

@ -35,7 +35,8 @@ module.exports = class ControlBarView extends CocoView
@levelID = @level.get('slug')
@spectateGame = options.spectateGame ? false
super options
if @isMultiplayerLevel = @level.get('type') in ['hero-ladder']
if @level.get('type') in ['hero-ladder'] and me.isAdmin()
@isMultiplayerLevel = true
@multiplayerStatusManager = new MultiplayerStatusManager @levelID, @onMultiplayerStateChanged
setBus: (@bus) ->

View file

@ -80,6 +80,7 @@ module.exports = class ProblemAlertView extends CocoView
_.delay pauseJiggle, 1000
onHideProblemAlert: ->
return unless @$el.is(':visible')
@onRemoveClicked()
onRemoveClicked: ->

View file

@ -215,13 +215,13 @@ module.exports = class InventoryModal extends ModalView
onItemSlotClick: (e) ->
return if @remainingRequiredEquipment?.length # Don't let them select a slot if we need them to first equip some require gear.
@playSound 'menu-button-click'
#@playSound 'menu-button-click'
@selectItemSlot($(e.target).closest('.item-slot'))
onUnequippedItemClick: (e) ->
return if @justDoubleClicked
itemEl = $(e.target).closest('.item')
@playSound 'menu-button-click'
#@playSound 'menu-button-click'
@selectUnequippedItem(itemEl)
onUnequippedItemDoubleClick: (e) ->

View file

@ -27,7 +27,7 @@ module.exports = class MultiplayerView extends CocoView
@levelID = @level?.get 'slug'
@session = options.session
@listenTo @session, 'change:multiplayer', @updateLinkSection
@watchRealTimeSessions() if @level?.get('type') in ['hero-ladder']
@watchRealTimeSessions() if @level?.get('type') in ['hero-ladder'] and me.isAdmin()
destroy: ->
@realTimeSessions?.off 'add', @onRealTimeSessionAdded
@ -47,7 +47,7 @@ module.exports = class MultiplayerView extends CocoView
c.readyToRank = @session?.readyToRank()
# Real-time multiplayer stuff
if @level?.get('type') in ['hero-ladder']
if @level?.get('type') in ['hero-ladder'] and me.isAdmin()
c.levelID = @session.get('levelID')
c.realTimeSessions = @realTimeSessions
c.currentRealTimeSession = @currentRealTimeSession if @currentRealTimeSession

View file

@ -57,6 +57,7 @@ module.exports = class BuyGemsModal extends ModalView
Backbone.Mediator.publish 'buy-gems-modal:purchase-initiated', { productID: productID }
else
# TODO: rename this event to 'Started gem purchase' after gemPrompt A/B test is over
application.tracker?.trackEvent 'Started purchase', { productID: productID }
stripeHandler.open({
description: $.t(product.i18n)
@ -78,6 +79,9 @@ module.exports = class BuyGemsModal extends ModalView
@render()
jqxhr = $.post('/db/payment', data)
jqxhr.done(=>
application.tracker?.trackEvent 'Finished gem purchase',
productID: @productBeingPurchased.id
revenue: @productBeingPurchased.amount / 100
document.location.reload()
)
jqxhr.fail(=>

View file

@ -72,6 +72,8 @@ module.exports = class SubscribeModal extends ModalView
amount: 599
}
@purchasedAmount = options.amount
stripeHandler.open(options)
onStripeReceivedToken: (e) ->
@ -88,7 +90,7 @@ module.exports = class SubscribeModal extends ModalView
me.patch({headers: {'X-Change-Plan': 'true'}})
onSubscriptionSuccess: ->
application.tracker?.trackEvent 'Finished subscription purchase', {}
application.tracker?.trackEvent 'Finished subscription purchase', revenue: @purchasedAmount / 100
application.tracker?.trackPageView "subscription/finish-purchase", ['Google Analytics']
Backbone.Mediator.publish 'subscribe-modal:subscribed', {}
@playSound 'victory'

View file

@ -76,7 +76,7 @@ exports.config =
#- vendor.js, all the vendor libraries
'javascripts/vendor.js': [
regJoin('^vendor/scripts/(?!(Box2d|coffeescript|difflib|diffview))')
regJoin('^vendor/scripts/(?!(Box2d|coffeescript|difflib|diffview|jasmine))')
regJoin('^bower_components/(?!(aether|d3|treema))')
'bower_components/treema/treema-utils.js'
]
@ -102,15 +102,23 @@ exports.config =
'javascripts/app/vendor/difflib.js': 'vendor/scripts/difflib.js'
'javascripts/app/vendor/diffview.js': 'vendor/scripts/diffview.js'
'javascripts/app/vendor/treema.js': 'bower_components/treema/treema.js'
'javascripts/app/vendor/jasmine-bundle.js': regJoin('^vendor/scripts/jasmine')
#- test, demo libraries
'javascripts/test-app.js': regJoin('^test/app/')
'javascripts/app/tests.js': regJoin('^test/app/')
'javascripts/demo-app.js': regJoin('^test/demo/')
#- More output files are generated at the below
order:
before: [
# jasmine-bundle.js ordering
'vendor/scripts/jasmine.js'
'vendor/scripts/jasmine-html.js'
'vendor/scripts/jasmine-boot.js'
'vendor/scripts/jasmine-mock-ajax.js'
# vendor.js ordering
'bower_components/jquery/dist/jquery.js'
'bower_components/lodash/dist/lodash.js'
'bower_components/backbone/backbone.js'

View file

@ -21,10 +21,6 @@ AchievablePlugin = (schema, options) ->
# Check if an achievement has been earned
schema.post 'save', (doc) ->
# sometimes post appears to be called twice. Handle this...
# TODO: Refactor this system to make it request-specific,
# perhaps by having POST/PUT requests store the copy on the request object themselves.
return if doc.isInit('_id') and not (doc.id of before)
isNew = not doc.isInit('_id') or not (doc.id of before)
originalDocObj = before[doc.id] unless isNew

View file

@ -1,4 +1,4 @@
deltas = require 'lib/deltas'
deltas = require 'core/deltas'
describe 'deltas lib', ->

View file

@ -1,4 +1,4 @@
FacebookHandler = require 'lib/FacebookHandler'
FacebookHandler = require 'core/social-handlers/FacebookHandler'
mockAuthEvent =
response:

View file

@ -1,5 +1,5 @@
describe 'Utility library', ->
util = require 'lib/utils'
util = require 'core/utils'
describe 'i18n', ->
beforeEach ->

View file

@ -119,7 +119,7 @@ describe 'LevelLoader', ->
# first load Tharin by the 'normal' session load
responses = '/db/level/id': levelWithOgreWithMace
jasmine.Ajax.requests.sendResponses(responses)
responses = '/db/level_session/id': sessionWithTharinWithHelmet
responses = '/db/level.session/id': sessionWithTharinWithHelmet
jasmine.Ajax.requests.sendResponses(responses)
# then try to load Tharin some more

View file

@ -1,5 +1,5 @@
CocoModel = require 'models/CocoModel'
utils = require 'lib/utils'
utils = require 'core/utils'
class BlandClass extends CocoModel
@className: 'Bland'
@ -93,7 +93,7 @@ describe 'CocoModel', ->
b.patch()
request = jasmine.Ajax.requests.mostRecent()
attrs = JSON.stringify(b.attributes) # server responds with all
request.response({status: 200, responseText: attrs})
request.respondWith({status: 200, responseText: attrs})
b.set('number', 3)
b.patch()
@ -125,7 +125,7 @@ describe 'CocoModel', ->
b = new BlandClass({})
res = b.save()
request = jasmine.Ajax.requests.mostRecent()
request.response(status: 200, responseText: '{}')
request.respondWith(status: 200, responseText: '{}')
collection = []
model =
@ -140,7 +140,7 @@ describe 'CocoModel', ->
ready true
else return ready false
request.response {status: 200, responseText: JSON.stringify collection}
request.respondWith {status: 200, responseText: JSON.stringify collection}
utils.keepDoingUntil (ready) ->
request = jasmine.Ajax.requests.mostRecent()
@ -149,7 +149,7 @@ describe 'CocoModel', ->
ready true
else return ready false
request.response {status:200, responseText: JSON.stringify me}
request.respondWith {status:200, responseText: JSON.stringify me}
describe 'updateI18NCoverage', ->
class FlexibleClass extends CocoModel

View file

@ -46,7 +46,7 @@ describe 'SuperModel', ->
s.once 'loaded-all', -> triggered = true
s.loadModel(m, 'user')
request = jasmine.Ajax.requests.mostRecent()
request.response({status: 200, responseText: '{}'})
request.respondWith({status: 200, responseText: '{}'})
_.defer ->
expect(triggered).toBe(true)
done()

View file

@ -1,9 +1,9 @@
AuthModal = require 'views/modal/AuthModal'
RecoverModal = require 'views/modal/RecoverModal'
AuthModal = require 'views/core/AuthModal'
RecoverModal = require 'views/core/RecoverModal'
describe 'AuthModal', ->
it 'opens the recover modal when you click the recover link', ->
m = new AuthModal()
m = new AuthModal({mode: 'login'})
m.render()
spyOn(m, 'openModalView')
m.$el.find('#link-to-recover').click()

View file

@ -34,7 +34,6 @@ describe 'ThangComponentsEditView', ->
supermodel = new SuperModel()
supermodel.registerModel(componentC)
view = new ThangComponentEditView({ components: [], supermodel: supermodel })
jasmine.Ajax.requests.sendResponses { '/db/thang.type': [] }
_.defer ->
view.render()
view.componentsTreema.set('/', [ { original: 'C', majorVersion: 0 }])

View file

@ -7,7 +7,7 @@ describe 'LevelEditView', ->
it 'opens just one modal when you click it', ->
view = new LevelEditView({}, 'something')
request = jasmine.Ajax.requests.first()
request.response {status: 200, responseText: JSON.stringify(emptyLevel)}
request.respondWith {status: 200, responseText: JSON.stringify(emptyLevel)}
view.render()
spyOn(view, 'openModalView')
view.$el.find('#revert-button').click()

View file

@ -1,4 +1,4 @@
LadderTabView = require 'views/play/ladder/LadderTabView'
LadderTabView = require 'views/ladder/LadderTabView'
Level = require 'models/Level'
fixtures = require 'test/app/fixtures/levels'
@ -14,5 +14,5 @@ describe 'LeaderboardData', ->
request = jasmine.Ajax.requests.mostRecent()
triggered = false
leaderboard.once 'sync', -> triggered = true
request.response({status: 200, responseText: '{}'})
request.respondWith({status: 200, responseText: '{}'})
expect(triggered).toBe(true)

View file

@ -69,7 +69,7 @@ describe 'POST /db/user', ->
expect(user.get('password')).toBeUndefined()
expect(user?.get('passwordHash')).not.toBeUndefined()
if user?.get('passwordHash')?
expect(user.get('passwordHash')[..5]).toBe('948c7e')
expect(user.get('passwordHash')[..5]).toBe('31dc3d')
expect(user.get('permissions').length).toBe(0)
done()

176
vendor/scripts/jasmine-boot.js vendored Executable file
View file

@ -0,0 +1,176 @@
/**
Starting with version 2.0, this file "boots" Jasmine, performing all of the necessary initialization before executing the loaded environment and all of a project's specs. This file should be loaded after `jasmine.js`, but before any project source files or spec files are loaded. Thus this file can also be used to customize Jasmine for a project.
If a project is using Jasmine via the standalone distribution, this file can be customized directly. If a project is using Jasmine via the [Ruby gem][jasmine-gem], this file can be copied into the support directory via `jasmine copy_boot_js`. Other environments (e.g., Python) will have different mechanisms.
The location of `boot.js` can be specified and/or overridden in `jasmine.yml`.
[jasmine-gem]: http://github.com/pivotal/jasmine-gem
*/
(function() {
/**
* ## Require &amp; Instantiate
*
* Require Jasmine's core files. Specifically, this requires and attaches all of Jasmine's code to the `jasmine` reference.
*/
window.jasmine = jasmineRequire.core(jasmineRequire);
/**
* Since this is being run in a browser and the results should populate to an HTML page, require the HTML-specific Jasmine code, injecting the same reference.
*/
jasmineRequire.html(jasmine);
/**
* Create the Jasmine environment. This is used to run all specs in a project.
*/
var env = jasmine.getEnv();
/**
* ## The Global Interface
*
* Build up the functions that will be exposed as the Jasmine public interface. A project can customize, rename or alias any of these functions as desired, provided the implementation remains unchanged.
*/
var jasmineInterface = {
describe: function(description, specDefinitions) {
return env.describe(description, specDefinitions);
},
xdescribe: function(description, specDefinitions) {
return env.xdescribe(description, specDefinitions);
},
it: function(desc, func) {
return env.it(desc, func);
},
xit: function(desc, func) {
return env.xit(desc, func);
},
beforeEach: function(beforeEachFunction) {
return env.beforeEach(beforeEachFunction);
},
afterEach: function(afterEachFunction) {
return env.afterEach(afterEachFunction);
},
expect: function(actual) {
return env.expect(actual);
},
pending: function() {
return env.pending();
},
spyOn: function(obj, methodName) {
return env.spyOn(obj, methodName);
},
jsApiReporter: new jasmine.JsApiReporter({
timer: new jasmine.Timer()
})
};
/**
* Add all of the Jasmine global/public interface to the proper global, so a project can use the public interface directly. For example, calling `describe` in specs instead of `jasmine.getEnv().describe`.
*/
if (typeof window == "undefined" && typeof exports == "object") {
extend(exports, jasmineInterface);
} else {
extend(window, jasmineInterface);
}
/**
* Expose the interface for adding custom equality testers.
*/
jasmine.addCustomEqualityTester = function(tester) {
env.addCustomEqualityTester(tester);
};
/**
* Expose the interface for adding custom expectation matchers
*/
jasmine.addMatchers = function(matchers) {
return env.addMatchers(matchers);
};
/**
* Expose the mock interface for the JavaScript timeout functions
*/
jasmine.clock = function() {
return env.clock;
};
/**
* ## Runner Parameters
*
* More browser specific code - wrap the query string in an object and to allow for getting/setting parameters from the runner user interface.
*/
var queryString = new jasmine.QueryString({
getWindowLocation: function() { return window.location; }
});
var catchingExceptions = false; // Setting to false always for CodeCombat, because Jasmine-HTML's reporter doesn't do source maps, and Chrome console does.
env.catchExceptions(typeof catchingExceptions === "undefined" ? true : catchingExceptions);
/**
* ## Reporters
* The `HtmlReporter` builds all of the HTML UI for the runner page. This reporter paints the dots, stars, and x's for specs, as well as all spec names and all failures (if any).
*/
var htmlReporter = new jasmine.HtmlReporter({
env: env,
onRaiseExceptionsClick: function() { queryString.setParam("catch", !env.catchingExceptions()); },
getContainer: function() { return $('#testing-area')[0]; },
createElement: function() { return document.createElement.apply(document, arguments); },
createTextNode: function() { return document.createTextNode.apply(document, arguments); },
timer: new jasmine.Timer()
});
/**
* The `jsApiReporter` also receives spec results, and is used by any environment that needs to extract the results from JavaScript.
*/
env.addReporter(jasmineInterface.jsApiReporter);
env.addReporter(htmlReporter);
/**
* Filter which specs will be run by matching the start of the full name against the `spec` query param.
*/
var specFilter = new jasmine.HtmlSpecFilter({
filterString: function() { return queryString.getParam("spec"); }
});
env.specFilter = function(spec) {
return specFilter.matches(spec.getFullName());
};
/**
* Setting up timing functions to be able to be overridden. Certain browsers (Safari, IE 8, phantomjs) require this hack.
*/
window.setTimeout = window.setTimeout;
window.setInterval = window.setInterval;
window.clearTimeout = window.clearTimeout;
window.clearInterval = window.clearInterval;
/**
* ## Execution
*
* Replace the browser window's `onload`, ensure it's called, and then run all of the loaded specs. This includes initializing the `HtmlReporter` instance and then executing the loaded Jasmine environment. All of this will happen after all of the specs are loaded.
*/
window.runJasmine = function() {
htmlReporter.initialize();
env.execute();
};
/**
* Helper function for readability above.
*/
function extend(destination, source) {
for (var property in source) destination[property] = source[property];
return destination;
}
}());

609
vendor/scripts/jasmine-mock-ajax.js vendored Normal file
View file

@ -0,0 +1,609 @@
/*
Jasmine-Ajax : a set of helpers for testing AJAX requests under the Jasmine
BDD framework for JavaScript.
http://github.com/pivotal/jasmine-ajax
Jasmine Home page: http://pivotal.github.com/jasmine
Copyright (c) 2008-2013 Pivotal Labs
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
getJasmineRequireObj().ajax = function(jRequire) {
var $ajax = {};
$ajax.RequestStub = jRequire.AjaxRequestStub();
$ajax.RequestTracker = jRequire.AjaxRequestTracker();
$ajax.StubTracker = jRequire.AjaxStubTracker();
$ajax.ParamParser = jRequire.AjaxParamParser();
$ajax.fakeRequest = jRequire.AjaxFakeRequest();
$ajax.MockAjax = jRequire.MockAjax($ajax);
return $ajax.MockAjax;
};
getJasmineRequireObj().AjaxFakeRequest = function() {
function extend(destination, source, propertiesToSkip) {
propertiesToSkip = propertiesToSkip || [];
for (var property in source) {
if (!arrayContains(propertiesToSkip, property)) {
destination[property] = source[property];
}
}
return destination;
}
function arrayContains(arr, item) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] === item) {
return true;
}
}
return false;
}
function wrapProgressEvent(xhr, eventName) {
return function() {
if (xhr[eventName]) {
xhr[eventName]();
}
};
}
function initializeEvents(xhr) {
return {
'loadstart': wrapProgressEvent(xhr, 'onloadstart'),
'load': wrapProgressEvent(xhr, 'onload'),
'loadend': wrapProgressEvent(xhr, 'onloadend'),
'progress': wrapProgressEvent(xhr, 'onprogress'),
'error': wrapProgressEvent(xhr, 'onerror'),
'abort': wrapProgressEvent(xhr, 'onabort'),
'timeout': wrapProgressEvent(xhr, 'ontimeout')
};
}
function unconvertibleResponseTypeMessage(type) {
var msg = [
"Can't build XHR.response for XHR.responseType of '",
type,
"'.",
"XHR.response must be explicitly stubbed"
];
return msg.join(' ');
}
function fakeRequest(global, requestTracker, stubTracker, paramParser) {
function FakeXMLHttpRequest() {
requestTracker.track(this);
this.events = initializeEvents(this);
this.requestHeaders = {};
this.overriddenMimeType = null;
}
function findHeader(name, headers) {
name = name.toLowerCase();
for (var header in headers) {
if (header.toLowerCase() === name) {
return headers[header];
}
}
}
function normalizeHeaders(rawHeaders, contentType) {
var headers = [];
if (rawHeaders) {
if (rawHeaders instanceof Array) {
headers = rawHeaders;
} else {
for (var headerName in rawHeaders) {
if (rawHeaders.hasOwnProperty(headerName)) {
headers.push({ name: headerName, value: rawHeaders[headerName] });
}
}
}
} else {
headers.push({ name: "Content-Type", value: contentType || "application/json" });
}
return headers;
}
function parseXml(xmlText, contentType) {
if (global.DOMParser) {
return (new global.DOMParser()).parseFromString(xmlText, 'text/xml');
} else {
var xml = new global.ActiveXObject("Microsoft.XMLDOM");
xml.async = "false";
xml.loadXML(xmlText);
return xml;
}
}
var xmlParsables = ['text/xml', 'application/xml'];
function getResponseXml(responseText, contentType) {
if (arrayContains(xmlParsables, contentType.toLowerCase())) {
return parseXml(responseText, contentType);
} else if (contentType.match(/\+xml$/)) {
return parseXml(responseText, 'text/xml');
}
return null;
}
var iePropertiesThatCannotBeCopied = ['responseBody', 'responseText', 'responseXML', 'status', 'statusText', 'responseTimeout'];
extend(FakeXMLHttpRequest.prototype, new global.XMLHttpRequest(), iePropertiesThatCannotBeCopied);
extend(FakeXMLHttpRequest.prototype, {
open: function() {
this.method = arguments[0];
this.url = arguments[1];
this.username = arguments[3];
this.password = arguments[4];
this.readyState = 1;
this.onreadystatechange();
},
setRequestHeader: function(header, value) {
if(this.requestHeaders.hasOwnProperty(header)) {
this.requestHeaders[header] = [this.requestHeaders[header], value].join(', ');
} else {
this.requestHeaders[header] = value;
}
},
overrideMimeType: function(mime) {
this.overriddenMimeType = mime;
},
abort: function() {
this.readyState = 0;
this.status = 0;
this.statusText = "abort";
this.onreadystatechange();
this.events.progress();
this.events.abort();
this.events.loadend();
},
readyState: 0,
onloadstart: null,
onprogress: null,
onabort: null,
onerror: null,
onload: null,
ontimeout: null,
onloadend: null,
onreadystatechange: function(isTimeout) {
},
addEventListener: function(event, callback) {
var existingCallback = this.events[event],
self = this;
this.events[event] = function() {
callback.apply(self);
existingCallback();
};
},
status: null,
send: function(data) {
this.params = data;
this.readyState = 2;
this.events.loadstart();
this.onreadystatechange();
var stub = stubTracker.findStub(this.url, data, this.method);
if (stub) {
this.respondWith(stub);
}
},
contentType: function() {
return findHeader('content-type', this.requestHeaders);
},
data: function() {
if (!this.params) {
return {};
}
return paramParser.findParser(this).parse(this.params);
},
getResponseHeader: function(name) {
name = name.toLowerCase();
var resultHeader;
for(var i = 0; i < this.responseHeaders.length; i++) {
var header = this.responseHeaders[i];
if (name === header.name.toLowerCase()) {
if (resultHeader) {
resultHeader = [resultHeader, header.value].join(', ');
} else {
resultHeader = header.value;
}
}
}
return resultHeader;
},
getAllResponseHeaders: function() {
var responseHeaders = [];
for (var i = 0; i < this.responseHeaders.length; i++) {
responseHeaders.push(this.responseHeaders[i].name + ': ' +
this.responseHeaders[i].value);
}
return responseHeaders.join('\r\n');
},
responseText: null,
response: null,
responseType: '',
responseValue: function() {
switch(this.responseType) {
case null:
case "":
case "text":
return this.readyState >= 3 ? this.responseText : "";
case "json":
return JSON.parse(this.responseText);
case "arraybuffer":
throw unconvertibleResponseTypeMessage('arraybuffer');
case "blob":
throw unconvertibleResponseTypeMessage('blob');
case "document":
return this.responseXML;
}
},
respondWith: function(response) {
if (this.readyState === 4) {
throw new Error("FakeXMLHttpRequest already completed");
}
this.status = response.status;
this.statusText = response.statusText || "";
this.responseText = response.responseText || "";
this.responseType = response.responseType || "";
this.readyState = 4;
this.responseHeaders = normalizeHeaders(response.responseHeaders, response.contentType);
this.responseXML = getResponseXml(response.responseText, this.getResponseHeader('content-type') || '');
if (this.responseXML) {
this.responseType = 'document';
}
if ('response' in response) {
this.response = response.response;
} else {
this.response = this.responseValue();
}
this.onreadystatechange();
this.events.progress();
this.events.load();
this.events.loadend();
},
responseTimeout: function() {
if (this.readyState === 4) {
throw new Error("FakeXMLHttpRequest already completed");
}
this.readyState = 4;
jasmine.clock().tick(30000);
this.onreadystatechange('timeout');
this.events.progress();
this.events.timeout();
this.events.loadend();
},
responseError: function() {
if (this.readyState === 4) {
throw new Error("FakeXMLHttpRequest already completed");
}
this.readyState = 4;
this.onreadystatechange();
this.events.progress();
this.events.error();
this.events.loadend();
}
});
return FakeXMLHttpRequest;
}
return fakeRequest;
};
getJasmineRequireObj().MockAjax = function($ajax) {
function MockAjax(global) {
var requestTracker = new $ajax.RequestTracker(),
stubTracker = new $ajax.StubTracker(),
paramParser = new $ajax.ParamParser(),
realAjaxFunction = global.XMLHttpRequest,
mockAjaxFunction = $ajax.fakeRequest(global, requestTracker, stubTracker, paramParser);
this.install = function() {
global.XMLHttpRequest = mockAjaxFunction;
};
this.uninstall = function() {
global.XMLHttpRequest = realAjaxFunction;
this.stubs.reset();
this.requests.reset();
paramParser.reset();
};
this.stubRequest = function(url, data, method) {
var stub = new $ajax.RequestStub(url, data, method);
stubTracker.addStub(stub);
return stub;
};
this.withMock = function(closure) {
this.install();
try {
closure();
} finally {
this.uninstall();
}
};
this.addCustomParamParser = function(parser) {
paramParser.add(parser);
};
this.requests = requestTracker;
this.stubs = stubTracker;
}
return MockAjax;
};
getJasmineRequireObj().AjaxParamParser = function() {
function ParamParser() {
var defaults = [
{
test: function(xhr) {
return (/^application\/json/).test(xhr.contentType());
},
parse: function jsonParser(paramString) {
return JSON.parse(paramString);
}
},
{
test: function(xhr) {
return true;
},
parse: function naiveParser(paramString) {
var data = {};
var params = paramString.split('&');
for (var i = 0; i < params.length; ++i) {
var kv = params[i].replace(/\+/g, ' ').split('=');
var key = decodeURIComponent(kv[0]);
data[key] = data[key] || [];
data[key].push(decodeURIComponent(kv[1]));
}
return data;
}
}
];
var paramParsers = [];
this.add = function(parser) {
paramParsers.unshift(parser);
};
this.findParser = function(xhr) {
for(var i in paramParsers) {
var parser = paramParsers[i];
if (parser.test(xhr)) {
return parser;
}
}
};
this.reset = function() {
paramParsers = [];
for(var i in defaults) {
paramParsers.push(defaults[i]);
}
};
this.reset();
}
return ParamParser;
};
getJasmineRequireObj().AjaxRequestStub = function() {
function RequestStub(url, stubData, method) {
var normalizeQuery = function(query) {
return query ? query.split('&').sort().join('&') : undefined;
};
if (url instanceof RegExp) {
this.url = url;
this.query = undefined;
} else {
var split = url.split('?');
this.url = split[0];
this.query = split.length > 1 ? normalizeQuery(split[1]) : undefined;
}
this.data = normalizeQuery(stubData);
this.method = method;
this.andReturn = function(options) {
this.status = options.status || 200;
this.contentType = options.contentType;
this.response = options.response;
this.responseText = options.responseText;
};
this.matches = function(fullUrl, data, method) {
var matches = false;
fullUrl = fullUrl.toString();
if (this.url instanceof RegExp) {
matches = this.url.test(fullUrl);
} else {
var urlSplit = fullUrl.split('?'),
url = urlSplit[0],
query = urlSplit[1];
matches = this.url === url && this.query === normalizeQuery(query);
}
return matches && (!this.data || this.data === normalizeQuery(data)) && (!this.method || this.method === method);
};
}
return RequestStub;
};
getJasmineRequireObj().AjaxRequestTracker = function() {
function RequestTracker() {
var requests = [];
this.track = function(request) {
requests.push(request);
};
this.first = function() {
return requests[0];
};
this.count = function() {
return requests.length;
};
this.reset = function() {
requests = [];
};
this.mostRecent = function() {
return requests[requests.length - 1];
};
this.at = function(index) {
return requests[index];
};
this.all = function() {
return requests.slice(0);
};
this.sendResponses = function(responseMap) {
var urls = Object.keys(responseMap);
var success = true;
for(var i in urls) {
var url = urls[i];
var responseBody = responseMap[url];
var responded = false;
var requests = jasmine.Ajax.requests.all().slice();
for(var j in requests) {
var request = requests[j];
if(request.url.startsWith(url)) {
request.respondWith({status: 200, responseText: JSON.stringify(responseBody)});
responded = true;
break;
}
}
if(!responded) {
var allRequests = jasmine.Ajax.requests.all();
urls = [];
for(var k in allRequests) urls.push(allRequests[k].url);
console.error('could not find response for', url, 'in', urls, allRequests);
success = false;
continue;
}
}
return success;
}
this.filter = function(url_to_match) {
var matching_requests = [];
for (var i = 0; i < requests.length; i++) {
if (url_to_match instanceof RegExp &&
url_to_match.test(requests[i].url)) {
matching_requests.push(requests[i]);
} else if (url_to_match instanceof Function &&
url_to_match(requests[i])) {
matching_requests.push(requests[i]);
} else {
if (requests[i].url === url_to_match) {
matching_requests.push(requests[i]);
}
}
}
return matching_requests;
};
}
return RequestTracker;
};
getJasmineRequireObj().AjaxStubTracker = function() {
function StubTracker() {
var stubs = [];
this.addStub = function(stub) {
stubs.push(stub);
};
this.reset = function() {
stubs = [];
};
this.findStub = function(url, data, method) {
for (var i = stubs.length - 1; i >= 0; i--) {
var stub = stubs[i];
if (stub.matches(url, data, method)) {
return stub;
}
}
};
}
return StubTracker;
};
(function() {
var jRequire = getJasmineRequireObj(),
MockAjax = jRequire.ajax(jRequire);
if (typeof window === "undefined" && typeof exports === "object") {
exports.MockAjax = MockAjax;
jasmine.Ajax = new MockAjax(exports);
} else {
window.MockAjax = MockAjax;
jasmine.Ajax = new MockAjax(window);
}
}());

View file

@ -927,7 +927,7 @@ this.createjs = this.createjs || {};
* @type {Number}
* @default 0
*/
this.progress = (total == 0) ? 0 : loaded / total;
this.progress = (total == 0) ? 0 : this.loaded / this.total;
};
var p = createjs.extend(ProgressEvent, createjs.Event);
@ -1287,6 +1287,44 @@ this.createjs = this.createjs || {};
}
};
/**
* Utility function to check if item is a valid HTMLImageElement
*
* @param item {object}
* @returns {boolean}
*/
s.isImageTag = function(item) {
return item instanceof HTMLImageElement;
};
/**
* Utility function to check if item is a valid HTMLAudioElement
*
* @param item
* @returns {boolean}
*/
s.isAudioTag = function(item) {
if (window.HTMLAudioElement) {
return item instanceof HTMLAudioElement;
} else {
return false;
}
};
/**
* Utility function to check if item is a valid HTMLVideoElement
*
* @param item
* @returns {boolean}
*/
s.isVideoTag = function(item) {
if (window.HTMLVideoElement) {
return item instanceof HTMLVideoElement;
} else {
false;
}
};
/**
* Determine if a specific type is a text based asset, and should be loaded as UTF-8.
* @method isText
@ -1322,6 +1360,7 @@ this.createjs = this.createjs || {};
if (extension == null) {
return createjs.AbstractLoader.TEXT;
}
switch (extension.toLowerCase()) {
case "jpeg":
case "jpg":
@ -1455,17 +1494,19 @@ this.createjs = this.createjs || {};
/**
* Defines a POST request, use for a method value when loading data.
*
* @property POST
* @type {string}
* @defaultValue post
*/
s.POST = 'POST';
s.POST = "POST";
/**
* Defines a GET request, use for a method value when loading data.
*
* @property GET
* @type {string}
* @defaultValue get
*/
s.GET = 'GET';
s.GET = "GET";
/**
* The preload type for generic binary types. Note that images are loaded as binary files when using XHR.
@ -1473,6 +1514,7 @@ this.createjs = this.createjs || {};
* @type {String}
* @default binary
* @static
* @since 0.6.0
*/
s.BINARY = "binary";
@ -1483,6 +1525,7 @@ this.createjs = this.createjs || {};
* @type {String}
* @default css
* @static
* @since 0.6.0
*/
s.CSS = "css";
@ -1492,6 +1535,7 @@ this.createjs = this.createjs || {};
* @type {String}
* @default image
* @static
* @since 0.6.0
*/
s.IMAGE = "image";
@ -1506,6 +1550,7 @@ this.createjs = this.createjs || {};
* @type {String}
* @default javascript
* @static
* @since 0.6.0
*/
s.JAVASCRIPT = "javascript";
@ -1518,6 +1563,7 @@ this.createjs = this.createjs || {};
* @type {String}
* @default json
* @static
* @since 0.6.0
*/
s.JSON = "json";
@ -1530,6 +1576,7 @@ this.createjs = this.createjs || {};
* @type {String}
* @default jsonp
* @static
* @since 0.6.0
*/
s.JSONP = "jsonp";
@ -1543,7 +1590,7 @@ this.createjs = this.createjs || {};
* @type {String}
* @default manifest
* @static
* @since 0.4.1
* @since 0.6.0
*/
s.MANIFEST = "manifest";
@ -1554,6 +1601,7 @@ this.createjs = this.createjs || {};
* @type {String}
* @default sound
* @static
* @since 0.6.0
*/
s.SOUND = "sound";
@ -1564,15 +1612,27 @@ this.createjs = this.createjs || {};
* @type {String}
* @default video
* @static
* @since 0.6.0
*/
s.VIDEO = "video";
/**
* The preload type for SpriteSheet files. SpriteSheet files are JSON files that contain string image paths.
* @property SPRITESHEET
* @type {String}
* @default spritesheet
* @static
* @since 0.6.0
*/
s.SPRITESHEET = "spritesheet";
/**
* The preload type for SVG files.
* @property SVG
* @type {String}
* @default svg
* @static
* @since 0.6.0
*/
s.SVG = "svg";
@ -1583,6 +1643,7 @@ this.createjs = this.createjs || {};
* @type {String}
* @default text
* @static
* @since 0.6.0
*/
s.TEXT = "text";
@ -1592,6 +1653,7 @@ this.createjs = this.createjs || {};
* @type {String}
* @default xml
* @static
* @since 0.6.0
*/
s.XML = "xml";
@ -1757,7 +1819,7 @@ this.createjs = this.createjs || {};
/**
* Remove all references to this loader.
*
* @method destroy
*/
p.destroy = function() {
if (this._request) {
@ -1771,6 +1833,8 @@ this.createjs = this.createjs || {};
this._rawResult = null;
this._result = null;
this._loadItems = null;
this.removeAllEventListeners();
};
@ -1808,15 +1872,13 @@ this.createjs = this.createjs || {};
var event = null;
if (typeof(value) == "number") {
this.progress = value;
event = new createjs.ProgressEvent();
event.loaded = this.progress;
event.total = 1;
event = new createjs.ProgressEvent(this.progress);
} else {
event = value;
this.progress = value.loaded / value.total;
event.progress = this.progress;
if (isNaN(this.progress) || this.progress == Infinity) { this.progress = 0; }
}
event.progress = this.progress;
this.hasEventListener("progress") && this.dispatchEvent(event);
};
@ -1828,6 +1890,8 @@ this.createjs = this.createjs || {};
p._sendComplete = function () {
if (this._isCanceled()) { return; }
this.loaded = true;
var event = new createjs.Event("complete");
event.rawResult = this._rawResult;
@ -1848,7 +1912,7 @@ this.createjs = this.createjs || {};
p._sendError = function (event) {
if (this._isCanceled() || !this.hasEventListener("error")) { return; }
if (event == null) {
event = new createjs.Event("error");
event = new createjs.ErrorEvent(); // TODO: Populate error
}
this.dispatchEvent(event);
};
@ -2023,6 +2087,10 @@ this.createjs = this.createjs || {};
};
p.cancel = function() {
};
createjs.AbstractRequest = createjs.promote(AbstractRequest, "EventDispatcher");
}());
@ -2071,9 +2139,7 @@ this.createjs = this.createjs || {};
};
p.destroy = function() {
this._tag.onreadystatechange = null;
this._tag.onload = null;
this._clean();
this._tag = null;
this.AbstractRequest_destory();
@ -2097,14 +2163,24 @@ this.createjs = this.createjs || {};
};
p._handleTagComplete = function () {
this._tag.onload = null;
this._tag.onreadystatechange = null;
this._rawResult = this._tag;
this._result = this.resultFormatter && this.resultFormatter(this) || this._rawResult;
this._clean();
this.dispatchEvent("complete");
};
/**
* Remove event listeners, but don't destory the request object
*
* @private
*/
p._clean = function() {
this._tag.onload = null;
this._tag.onreadystatechange = null;
};
/**
* Handle a stalled audio event. The main place we seem to get these is with HTMLAudio in Chrome when we try and
* playback audio that is already in a load, but not complete.
@ -2159,14 +2235,6 @@ this.createjs = this.createjs || {};
this.TagRequest_load();
};
p.destroy = function() {
this._tag.addEventListener && this._tag.removeEventListener("canplaythrough", this._loadedHandler);
this._tag.onstalled = null;
this._tag.onprogress = null;
this.TagRequest_destory();
};
/**
* Handle the readyStateChange event from a tag. We sometimes need this in place of the onload event (mainly SCRIPT
* and LINK tags), but other cases may exist.
@ -2209,13 +2277,17 @@ this.createjs = this.createjs || {};
this.dispatchEvent(newEvent);
};
p._handleTagComplete = function () {
/**
*
* @private
*/
p._clean = function () {
this._tag.removeEventListener && this._tag.removeEventListener("canplaythrough", this._loadedHandler);
this._tag.onstalled = null;
this._tag.onprogress = null;
this.TagRequest__handleTagComplete();
};
this.TagRequest__clean();
};
createjs.MediaTagRequest = createjs.promote(MediaTagRequest, "TagRequest");
@ -2309,7 +2381,7 @@ this.createjs = this.createjs || {};
}
};
var p = createjs.extend(XHRRequest, createjs.AbstractLoader);
var p = createjs.extend(XHRRequest, createjs.AbstractRequest);
// static properties
/**
@ -2355,7 +2427,7 @@ this.createjs = this.createjs || {};
return this._response;
};
// Overrides abstract method in AbstractLoader
// Overrides abstract method in AbstractRequest
p.cancel = function () {
this.canceled = true;
this._clean();
@ -2393,9 +2465,7 @@ this.createjs = this.createjs || {};
this._request.send(createjs.RequestUtils.formatQueryString(this._item.values));
}
} catch (error) {
var event = new createjs.Event("error");
event.error = error;
this._sendError(event);
this.dispatchEvent(new createjs.ErrorEvent("XHR_SEND", null, error));
}
};
@ -2464,7 +2534,7 @@ this.createjs = this.createjs || {};
*/
p._handleLoadStart = function (event) {
clearTimeout(this._loadTimeout);
this._sendLoadStart();
this.dispatchEvent("loadstart");
};
/**
@ -2475,9 +2545,7 @@ this.createjs = this.createjs || {};
*/
p._handleAbort = function (event) {
this._clean();
var newEvent = new createjs.Event("error");
newEvent.text = "XHR_ABORTED";
this._sendError(newEvent);
this.dispatchEvent(new createjs.ErrorEvent("XHR_ABORTED", null, event));
};
/**
@ -2488,10 +2556,9 @@ this.createjs = this.createjs || {};
*/
p._handleError = function (event) {
this._clean();
var newEvent = new createjs.Event("error");
newEvent.error = event;
this._sendError(newEvent);
this.dispatchEvent(new createjs.ErrorEvent(null, null, event));
};
/**
@ -2520,15 +2587,16 @@ this.createjs = this.createjs || {};
}
this.loaded = true;
if (!this._checkError()) {
this._handleError();
var error = this._checkError();
if (error) {
this._handleError(error);
return;
}
this._response = this._getResponse();
this._clean();
this._sendComplete();
this.dispatchEvent(new createjs.Event("complete"));
};
/**
@ -2540,11 +2608,8 @@ this.createjs = this.createjs || {};
*/
p._handleTimeout = function (event) {
this._clean();
var newEvent = new createjs.Event("error");
newEvent.text = "PRELOAD_TIMEOUT";
newEvent.error = event;
this._sendError(event);
this.dispatchEvent(new createjs.ErrorEvent("PRELOAD_TIMEOUT", null, event));
};
// Protected
@ -2552,7 +2617,7 @@ this.createjs = this.createjs || {};
* Determine if there is an error in the current load. This checks the status of the request for problem codes. Note
* that this does not check for an actual response. Currently, it only checks for 404 or 0 error code.
* @method _checkError
* @return {Boolean} If the request status returns an error code.
* @return {int} If the request status returns an error code.
* @private
*/
p._checkError = function () {
@ -2562,9 +2627,9 @@ this.createjs = this.createjs || {};
switch (status) {
case 404: // Not Found
case 0: // Not Loaded
return false;
return new Error(status);
}
return true;
return null;
};
/**
@ -2731,6 +2796,11 @@ this.createjs = this.createjs || {};
this.AbstractMediaLoader_constructor(loadItem, preferXHR, createjs.AbstractLoader.SOUND);
this._tagType = "audio";
if (createjs.RequestUtils.isAudioTag(loadItem) || createjs.RequestUtils.isAudioTag(loadItem.src)) {
this._preferXHR = false;
this._tag =createjs.RequestUtils.isAudioTag(loadItem)?loadItem:loadItem.src;
}
};
var p = createjs.extend(SoundLoader, createjs.AbstractMediaLoader);
@ -5158,13 +5228,15 @@ this.createjs = this.createjs || {};
* @since 0.6.0
*/
p.setLoop = function (value) {
// remove looping
if (this._loop != 0 && value == 0) {
this._removeLooping(value);
}
// add looping
if (this._loop == 0 && value != 0) {
this._addLooping(value);
if(this._playbackResource != null) {
// remove looping
if (this._loop != 0 && value == 0) {
this._removeLooping(value);
}
// add looping
if (this._loop == 0 && value != 0) {
this._addLooping(value);
}
}
this._loop = value;
};
@ -5658,7 +5730,7 @@ this.createjs = this.createjs || {};
*/
p._handlePreloadComplete = function (event) {
var src = event.target.getItem().src;
this._audioSources[src] = event.target.getResult(false);
this._audioSources[src] = event.result;
for (var i = 0, l = this._soundInstances[src].length; i < l; i++) {
var item = this._soundInstances[src][i];
item.setPlaybackResource(this._audioSources[src]);
@ -5708,12 +5780,10 @@ this.createjs = this.createjs || {};
* @protected
*/
function Loader(src) {
var loaditem = createjs.LoadItem.create(src);
this.XHRRequest_constructor(loaditem, true, createjs.AbstractLoader.SOUND);
this.AbstractLoader_constructor(src, true, createjs.AbstractLoader.SOUND);
this._request.responseType = "arraybuffer";
};
var p = createjs.extend(Loader, createjs.XHRRequest);
var p = createjs.extend(Loader, createjs.AbstractLoader);
/**
* web audio context required for decoding audio
@ -5731,9 +5801,14 @@ this.createjs = this.createjs || {};
// private methods
p._handleLoad = function (event) {
p._createRequest = function() {
this._request = new createjs.XHRRequest(this._item, false);
this._request.setResponseType("arraybuffer");
};
p._sendComplete = function (event) {
// OJR we leave this wrapped in Loader because we need to reference src and the handler only receives a single argument, the decodedAudio
Loader.context.decodeAudioData(this._request.response,
Loader.context.decodeAudioData(this._rawResult,
createjs.proxy(this._handleAudioDecoded, this),
createjs.proxy(this._handleError, this));
};
@ -5746,11 +5821,11 @@ this.createjs = this.createjs || {};
* @protected
*/
p._handleAudioDecoded = function (decodedAudio) {
this._response = decodedAudio;
this.XHRRequest__handleLoad();
this._result = decodedAudio;
this.AbstractLoader__sendComplete();
};
createjs.WebAudioLoader = createjs.promote(Loader, "XHRRequest");
createjs.WebAudioLoader = createjs.promote(Loader, "AbstractLoader");
}());
//##############################################################################
@ -5911,6 +5986,7 @@ this.createjs = this.createjs || {};
};
p._addLooping = function() {
if (this.playState != createjs.Sound.PLAY_SUCCEEDED) { return; }
this._sourceNodeNext = this._createAndPlayAudioNode(this._playbackStartTime, 0);
};