-
-
Notifications
You must be signed in to change notification settings - Fork 97
/
assets.js
449 lines (407 loc) · 12.4 KB
/
assets.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
import { emit } from './events.js'
/**
* A promise based asset loader for loading images, audio, and data files. An `assetLoaded` event is emitted after each asset is fully loaded. The callback for the event is passed the asset and the url to the asset as parameters.
*
* ```js
* import { load, on } from 'kontra';
*
* let numAssets = 3;
* let assetsLoaded = 0;
* on('assetLoaded', (asset, url) => {
* assetsLoaded++;
*
* // inform user or update progress bar
* });
*
* load(
* 'assets/imgs/character.png',
* 'assets/data/tile_engine_basic.json',
* ['/audio/music.ogg', '/audio/music.mp3']
* ).then(function(assets) {
* // all assets have loaded
* }).catch(function(err) {
* // error loading an asset
* });
* ```
* @sectionName Assets
*/
let imageRegex = /(jpeg|jpg|gif|png)$/;
let audioRegex = /(wav|mp3|ogg|aac)$/;
let leadingSlash = /^\//;
let trailingSlash = /\/$/;
let dataMap = new WeakMap();
let imagePath = '';
let audioPath = '';
let dataPath = '';
/**
* Get the full URL from the base.
*
* @param {String} url - The URL to the asset.
* @param {String} base - Base URL.
*
* @returns {String}
*/
function getUrl(url, base) {
return new URL(url, base).href;
}
/**
* Join a base path and asset path.
*
* @param {String} base - The asset base path.
* @param {String} url - The URL to the asset.
*
* @returns {String}
*/
function joinPath(base, url) {
return [base.replace(trailingSlash, ''), base ? url.replace(leadingSlash, '') : url]
.filter(s => s)
.join('/')
}
/**
* Get the extension of an asset.
*
* @param {String} url - The URL to the asset.
*
* @returns {String}
*/
function getExtension(url) {
return url.split('.').pop();
}
/**
* Get the name of an asset.
*
* @param {String} url - The URL to the asset.
*
* @returns {String}
*/
function getName(url) {
let name = url.replace('.' + getExtension(url), '');
// remove leading slash if there is no folder in the path
// @see https://stackoverflow.com/a/50592629/2124254
return name.split('/').length == 2 ? name.replace(leadingSlash, '') : name;
}
/**
* Get browser audio playability.
* @see https://github.com/Modernizr/Modernizr/blob/master/feature-detects/audio.js
*
* @param {HTMLMediaElement} audio - Audio element.
*
* @returns {object}
*/
function getCanPlay(audio) {
return {
wav: '',
mp3: audio.canPlayType('audio/mpeg;'),
ogg: audio.canPlayType('audio/ogg; codecs="vorbis"'),
aac: audio.canPlayType('audio/aac;')
};
}
/**
* Object of all loaded image assets by both file name and path. If the base [image path](#setImagePath) was set before the image was loaded, the file name and path will not include the base image path.
*
* ```js
* import { load, setImagePath, imageAssets } from 'kontra';
*
* load('assets/imgs/character.png').then(function() {
* // Image asset can be accessed by both
* // name: imageAssets['assets/imgs/character']
* // path: imageAssets['assets/imgs/character.png']
* });
*
* setImagePath('assets/imgs');
* load('character_walk_sheet.png').then(function() {
* // Image asset can be accessed by both
* // name: imageAssets['character_walk_sheet']
* // path: imageAssets['character_walk_sheet.png']
* });
* ```
* @property {Object} imageAssets
*/
export let imageAssets = {};
/**
* Object of all loaded audio assets by both file name and path. If the base [audio path](#setAudioPath) was set before the audio was loaded, the file name and path will not include the base audio path.
*
* ```js
* import { load, setAudioPath, audioAssets } from 'kontra';
*
* load('/audio/music.ogg').then(function() {
* // Audio asset can be accessed by both
* // name: audioAssets['/audio/music']
* // path: audioAssets['/audio/music.ogg']
* });
*
* setAudioPath('/audio');
* load('sound.ogg').then(function() {
* // Audio asset can be accessed by both
* // name: audioAssets['sound']
* // path: audioAssets['sound.ogg']
* });
* ```
* @property {Object} audioAssets
*/
export let audioAssets = {};
/**
* Object of all loaded data assets by both file name and path. If the base [data path](#setDataPath) was set before the data was loaded, the file name and path will not include the base data path.
*
* ```js
* import { load, setDataPath, dataAssets } from 'kontra';
*
* load('assets/data/file.txt').then(function() {
* // Audio asset can be accessed by both
* // name: dataAssets['assets/data/file']
* // path: dataAssets['assets/data/file.txt']
* });
*
* setDataPath('assets/data');
* load('info.json').then(function() {
* // Audio asset can be accessed by both
* // name: dataAssets['info']
* // path: dataAssets['info.json']
* });
* ```
* @property {Object} dataAssets
*/
export let dataAssets = {};
/**
* Add a global kontra object so TileEngine can access information about the
* loaded assets when kontra is loaded in parts rather than as a whole (e.g.
* `import { load, TileEngine } from 'kontra';`)
*/
function addGlobal() {
if (!window.__k) {
window.__k = {
dm: dataMap,
u: getUrl,
d: dataAssets,
i: imageAssets
}
}
}
/**
* Sets the base path for all image assets. If a base path is set, all load calls for image assets will prepend the base path to the URL.
*
* ```js
* import { setImagePath, load } from 'kontra';
*
* setImagePath('/imgs');
* load('character.png'); // loads '/imgs/character.png'
* ```
* @function setImagePath
*
* @param {String} path - Base image path.
*/
export function setImagePath(path) {
imagePath = path;
}
/**
* Sets the base path for all audio assets. If a base path is set, all load calls for audio assets will prepend the base path to the URL.
*
* ```js
* import { setAudioPath, load } from 'kontra';
*
* setAudioPath('/audio');
* load('music.ogg'); // loads '/audio/music.ogg'
* ```
* @function setAudioPath
*
* @param {String} path - Base audio path.
*/
export function setAudioPath(path) {
audioPath = path;
}
/**
* Sets the base path for all data assets. If a base path is set, all load calls for data assets will prepend the base path to the URL.
*
* ```js
* import { setDataPath, load } from 'kontra';
*
* setDataPath('/data');
* load('file.json'); // loads '/data/file.json'
* ```
* @function setDataPath
*
* @param {String} path - Base data path.
*/
export function setDataPath(path) {
dataPath = path;
}
/**
* Load a single Image asset. Uses the base [image path](#setImagePath) to resolve the URL.
*
* Once loaded, the asset will be accessible on the the [imageAssets](#imageAssets) property.
*
* ```js
* import { loadImage } from 'kontra';
*
* loadImage('car.png').then(function(image) {
* console.log(image.src); //=> 'car.png'
* })
* ```
* @function loadImage
*
* @param {String} url - The URL to the Image file.
*
* @returns {Promise} A deferred promise. Promise resolves with the Image.
*/
export function loadImage(url) {
addGlobal();
return new Promise((resolve, reject) => {
let resolvedUrl, image, fullUrl;
resolvedUrl = joinPath(imagePath, url);
if (imageAssets[resolvedUrl]) return resolve(imageAssets[resolvedUrl]);
image = new Image();
image.onload = function loadImageOnLoad() {
fullUrl = getUrl(resolvedUrl, window.location.href);
imageAssets[ getName(url) ] = imageAssets[resolvedUrl] = imageAssets[fullUrl] = this;
emit('assetLoaded', this, url);
resolve(this);
};
image.onerror = function loadImageOnError() {
reject(/* @if DEBUG */ 'Unable to load image ' + /* @endif */ resolvedUrl);
};
image.src = resolvedUrl;
});
}
/**
* Load a single Audio asset. Supports loading multiple audio formats which the loader will use to load the first audio format supported by the browser in the order listed. Uses the base [audio path](#setAudioPath) to resolve the URL.
*
* Once loaded, the asset will be accessible on the the [audioAssets](#audioAssets) property. Since the loader determines which audio asset to load based on browser support, you should only reference the audio by its name and not by its file path since there's no guarantee which asset was loaded.
*
* ```js
* import { loadAudio, audioAssets } from 'kontra';
*
* loadAudio([
* '/audio/music.mp3',
* '/audio/music.ogg'
* ]).then(function(audio) {
*
* // access audio by its name only (not by its .mp3 or .ogg path)
* audioAssets['/audio/music'].play();
* })
* ```
* @function loadAudio
*
* @param {String} url - The URL to the Audio file.
*
* @returns {Promise} A deferred promise. Promise resolves with the Audio.
*/
export function loadAudio(url) {
return new Promise((resolve, reject) => {
let audioEl, canPlay, resolvedUrl, fullUrl;
audioEl = new Audio();
canPlay = getCanPlay(audioEl);
// determine the first audio format the browser can play
url = [].concat(url)
.reduce((playableSource, source) => playableSource
? playableSource
: canPlay[ getExtension(source) ]
? source
: null
, 0); // 0 is the shortest falsy value
if (!url) {
return reject(/* @if DEBUG */ 'cannot play any of the audio formats provided' + /* @endif */ url);
}
resolvedUrl = joinPath(audioPath, url);
if (audioAssets[resolvedUrl]) return resolve(audioAssets[resolvedUrl]);
audioEl.addEventListener('canplay', function loadAudioOnLoad() {
fullUrl = getUrl(resolvedUrl, window.location.href);
audioAssets[ getName(url) ] = audioAssets[resolvedUrl] = audioAssets[fullUrl] = this;
emit('assetLoaded', this, url);
resolve(this);
});
audioEl.onerror = function loadAudioOnError() {
reject(/* @if DEBUG */ 'Unable to load audio ' + /* @endif */ resolvedUrl);
};
audioEl.src = resolvedUrl;
audioEl.load();
});
}
/**
* Load a single Data asset. Uses the base [data path](#setDataPath) to resolve the URL.
*
* Once loaded, the asset will be accessible on the the [dataAssets](#dataAssets) property.
*
* ```js
* import { loadData } from 'kontra';
*
* loadData('assets/data/tile_engine_basic.json').then(function(data) {
* // data contains the parsed JSON data
* })
* ```
* @function loadData
*
* @param {String} url - The URL to the Data file.
*
* @returns {Promise} A deferred promise. Promise resolves with the contents of the file. If the file is a JSON file, the contents will be parsed as JSON.
*/
export function loadData(url) {
addGlobal();
let resolvedUrl, fullUrl;
resolvedUrl = joinPath(dataPath, url);
if (dataAssets[resolvedUrl]) return Promise.resolve(dataAssets[resolvedUrl]);
return fetch(resolvedUrl).then(response => {
if (!response.ok) throw response;
return response.clone().json().catch(() => response.text())
}).then(response => {
fullUrl = getUrl(resolvedUrl, window.location.href);
if (typeof response === 'object') {
dataMap.set(response, fullUrl);
}
dataAssets[ getName(url) ] = dataAssets[resolvedUrl] = dataAssets[fullUrl] = response;
emit('assetLoaded', response, url);
return response;
});
}
/**
* Load Image, Audio, or data files. Uses the [loadImage](#loadImage), [loadAudio](#loadAudio), and [loadData](#loadData) functions to load each asset type.
*
* ```js
* import { load } from 'kontra';
*
* load(
* 'assets/imgs/character.png',
* 'assets/data/tile_engine_basic.json',
* ['/audio/music.ogg', '/audio/music.mp3']
* ).then(function(assets) {
* // all assets have loaded
* }).catch(function(err) {
* // error loading an asset
* });
* ```
* @function load
*
* @param {String|String[]} urls - Comma separated list of asset urls to load.
*
* @returns {Promise} A deferred promise. Resolves with all the loaded assets.
*/
export function load(...urls) {
addGlobal();
return Promise.all(
urls.map(asset => {
// account for a string or an array for the url
let extension = getExtension( [].concat(asset)[0] );
return extension.match(imageRegex)
? loadImage(asset)
: extension.match(audioRegex)
? loadAudio(asset)
: loadData(asset);
})
);
}
// expose for testing
export function _reset() {
imageAssets = {};
audioAssets = {};
dataAssets = {};
imagePath = audioPath = dataPath = '';
window.__k = undefined;
if (getCanPlay._r) {
getCanPlay = getCanPlay._r;
}
}
// Override the getCanPlay function to provide a specific return type for tests
export function _setCanPlayFn(fn) {
let originalCanPlay = getCanPlay;
getCanPlay = fn;
getCanPlay._r = originalCanPlay;
}