forked from phaserjs/phaser
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFile.js
More file actions
623 lines (543 loc) · 18.3 KB
/
Copy pathFile.js
File metadata and controls
623 lines (543 loc) · 18.3 KB
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
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
/**
* @author Richard Davey <rich@phaser.io>
* @copyright 2013-2026 Phaser Studio Inc.
* @license {@link https://opensource.org/licenses/MIT|MIT License}
*/
var Class = require('../utils/Class');
var CONST = require('./const');
var Events = require('./events');
var GetFastValue = require('../utils/object/GetFastValue');
var GetURL = require('./GetURL');
var MergeXHRSettings = require('./MergeXHRSettings');
var XHRLoader = require('./XHRLoader');
var XHRSettings = require('./XHRSettings');
/**
* @classdesc
* The base File class used by all File Types that the Loader can support. It manages the lifecycle
* of a single file from queue to download to processing to completion, handling XHR configuration,
* URL resolution, progress tracking, and error states. You should not create an instance of a File
* directly, but should extend it with your own class, setting a custom type and overriding the
* `onProcess` method to handle the loaded data. See `Phaser.Loader.FileTypes` for built-in file
* type examples.
*
* @class File
* @memberof Phaser.Loader
* @constructor
* @since 3.0.0
*
* @param {Phaser.Loader.LoaderPlugin} loader - The Loader that is going to load this File.
* @param {Phaser.Types.Loader.FileConfig} fileConfig - The file configuration object, as created by the file type.
*/
var File = new Class({
initialize:
function File (loader, fileConfig)
{
/**
* A reference to the Loader that is going to load this file.
*
* @name Phaser.Loader.File#loader
* @type {Phaser.Loader.LoaderPlugin}
* @since 3.0.0
*/
this.loader = loader;
/**
* A reference to the Cache, or Texture Manager, that is going to store this file if it loads.
*
* @name Phaser.Loader.File#cache
* @type {(Phaser.Cache.BaseCache|Phaser.Textures.TextureManager)}
* @since 3.7.0
*/
this.cache = GetFastValue(fileConfig, 'cache', false);
/**
* The file type string (image, json, etc) for sorting within the Loader.
*
* @name Phaser.Loader.File#type
* @type {string}
* @since 3.0.0
*/
this.type = GetFastValue(fileConfig, 'type', false);
if (!this.type)
{
throw new Error('Invalid File type: ' + this.type);
}
/**
* Unique cache key (unique within its file type)
*
* @name Phaser.Loader.File#key
* @type {string}
* @since 3.0.0
*/
this.key = GetFastValue(fileConfig, 'key', false);
var loadKey = this.key;
if (loader.prefix && loader.prefix !== '')
{
this.key = loader.prefix + loadKey;
}
if (!this.key)
{
throw new Error('Invalid File key: ' + this.key);
}
var url = GetFastValue(fileConfig, 'url');
if (url === undefined)
{
url = loader.path + loadKey + '.' + GetFastValue(fileConfig, 'extension', '');
}
else if (typeof url === 'string' && !url.match(/^(?:blob:|data:|capacitor:\/\/|http:\/\/|https:\/\/|\/\/)/))
{
url = loader.path + url;
}
/**
* The URL of the file, not including baseURL.
*
* Automatically has Loader.path prepended to it if a string.
*
* Can also be a JavaScript Object, such as the results of parsing JSON data.
*
* @name Phaser.Loader.File#url
* @type {object|string}
* @since 3.0.0
*/
this.url = url;
/**
* The final URL this file will load from, including baseURL and path.
* Set automatically when the Loader calls 'load' on this file.
*
* @name Phaser.Loader.File#src
* @type {string}
* @since 3.0.0
*/
this.src = '';
/**
* The merged XHRSettings for this file.
*
* @name Phaser.Loader.File#xhrSettings
* @type {Phaser.Types.Loader.XHRSettingsObject}
* @since 3.0.0
*/
this.xhrSettings = XHRSettings(GetFastValue(fileConfig, 'responseType', undefined));
if (GetFastValue(fileConfig, 'xhrSettings', false))
{
this.xhrSettings = MergeXHRSettings(this.xhrSettings, GetFastValue(fileConfig, 'xhrSettings', {}));
}
/**
* The XMLHttpRequest instance (as created by XHR Loader) that is loading this File.
*
* @name Phaser.Loader.File#xhrLoader
* @type {?XMLHttpRequest}
* @since 3.0.0
*/
this.xhrLoader = null;
/**
* The current state of the file. One of the FILE_CONST values.
*
* @name Phaser.Loader.File#state
* @type {number}
* @since 3.0.0
*/
this.state = (typeof(this.url) === 'function') ? CONST.FILE_POPULATED : CONST.FILE_PENDING;
/**
* The total size of this file.
* Set by onProgress and only if loading via XHR.
*
* @name Phaser.Loader.File#bytesTotal
* @type {number}
* @default 0
* @since 3.0.0
*/
this.bytesTotal = 0;
/**
* Updated as the file loads.
* Only set if loading via XHR.
*
* @name Phaser.Loader.File#bytesLoaded
* @type {number}
* @default -1
* @since 3.0.0
*/
this.bytesLoaded = -1;
/**
* A percentage value between 0 and 1 indicating how much of this file has loaded.
* Only set if loading via XHR.
*
* @name Phaser.Loader.File#percentComplete
* @type {number}
* @default -1
* @since 3.0.0
*/
this.percentComplete = -1;
/**
* For CORS based loading.
* If this is undefined then the File will check LoaderPlugin.crossOrigin and use that (if set)
*
* @name Phaser.Loader.File#crossOrigin
* @type {(string|undefined)}
* @since 3.0.0
*/
this.crossOrigin = undefined;
/**
* The processed file data, stored here after the file has loaded.
*
* @name Phaser.Loader.File#data
* @type {*}
* @since 3.0.0
*/
this.data = undefined;
/**
* A config object that can be used by file types to store transitional data.
*
* @name Phaser.Loader.File#config
* @type {*}
* @since 3.0.0
*/
this.config = GetFastValue(fileConfig, 'config', {});
/**
* If this is a multipart file, i.e. an atlas and its json together, then this is a reference
* to the parent MultiFile. Set and used internally by the Loader or specific file types.
*
* @name Phaser.Loader.File#multiFile
* @type {?Phaser.Loader.MultiFile}
* @since 3.7.0
*/
this.multiFile;
/**
* Does this file have an associated linked file? Such as an image and a normal map.
* Atlases and Bitmap Fonts use the multiFile, because those files need loading together but aren't
* actually bound by data, where-as a linkFile is.
*
* @name Phaser.Loader.File#linkFile
* @type {?Phaser.Loader.File}
* @since 3.7.0
*/
this.linkFile;
/**
* Does this File contain a data URI?
*
* @name Phaser.Loader.File#base64
* @type {boolean}
* @since 3.80.0
*/
this.base64 = (typeof url === 'string') && (url.indexOf('data:') === 0);
/**
* The counter for the number of times to retry loading this file before it fails.
*
* You can set this property value in the FileConfig object. If not present,
* this property is read from the `LoaderPlugin.maxRetries` property when
* this File instance is created.
*
* You can set this value via the Game Config, or you can adjust the `LoaderPlugin` property
* at any point after the Loader has started. However, it will not apply to files
* that have already been added to the Loader, only those added after this value
* is changed.
*
* @name Phaser.Loader.File#retryAttempts
* @type {number}
* @default 2
* @since 3.85.0
*/
this.retryAttempts = GetFastValue(fileConfig, 'maxRetries', loader.maxRetries);
},
/**
* Links this File with another, so they depend upon each other for loading and processing.
*
* @method Phaser.Loader.File#setLink
* @since 3.7.0
*
* @param {Phaser.Loader.File} fileB - The file to link to this one.
*/
setLink: function (fileB)
{
this.linkFile = fileB;
fileB.linkFile = this;
},
/**
* Clears the `onload`, `onerror`, and `onprogress` event handlers from the XHRLoader instance
* this file is using, preventing stale callbacks from firing after the load has completed or errored.
*
* @method Phaser.Loader.File#resetXHR
* @since 3.0.0
*/
resetXHR: function ()
{
if (this.xhrLoader)
{
this.xhrLoader.onload = undefined;
this.xhrLoader.onerror = undefined;
this.xhrLoader.onprogress = undefined;
}
},
/**
* Called by the Loader, starts the actual file downloading.
* During the load the methods onLoad, onError and onProgress are called, based on the XHR events.
* You shouldn't normally call this method directly, it's meant to be invoked by the Loader.
*
* @method Phaser.Loader.File#load
* @since 3.0.0
*/
load: function ()
{
if (this.state === CONST.FILE_POPULATED)
{
// Can happen for example in a JSONFile if they've provided a JSON object instead of a URL
this.loader.nextFile(this, true);
}
else
{
this.state = CONST.FILE_LOADING;
this.src = GetURL(this, this.loader.baseURL);
if (!this.src)
{
throw new Error('URL Error in File: ' + this.key + ' from: ' + this.url);
}
if (this.src.indexOf('data:') === 0)
{
this.base64 = true;
}
this.xhrLoader = XHRLoader(this, this.loader.xhr);
}
},
/**
* Called when the file finishes loading, is sent a DOM ProgressEvent.
*
* @method Phaser.Loader.File#onLoad
* @since 3.0.0
*
* @param {XMLHttpRequest} xhr - The XMLHttpRequest that caused this onload event.
* @param {ProgressEvent} event - The DOM ProgressEvent that resulted from this load.
*/
onLoad: function (xhr, event)
{
var isLocalFile = xhr.responseURL && this.loader.localSchemes.some(function (scheme)
{
return xhr.responseURL.indexOf(scheme) === 0;
});
var localFileOk = (isLocalFile && event.target.status === 0);
var success = !(event.target && event.target.status !== 200) || localFileOk;
// Handle HTTP status codes of 4xx and 5xx as errors, even if xhr.onerror was not called.
if (xhr.readyState === 4 && xhr.status >= 400 && xhr.status <= 599)
{
success = false;
}
this.state = CONST.FILE_LOADED;
this.resetXHR();
this.loader.nextFile(this, success);
},
/**
* Called by the XHRLoader if it was given a File with base64 data to load.
*
* @method Phaser.Loader.File#onBase64Load
* @since 3.80.0
*
* @param {XMLHttpRequest} xhr - The FakeXHR object containing the decoded base64 data.
*/
onBase64Load: function (xhr)
{
this.xhrLoader = xhr;
this.state = CONST.FILE_LOADED;
this.percentComplete = 1;
this.loader.emit(Events.FILE_PROGRESS, this, this.percentComplete);
this.loader.nextFile(this, true);
},
/**
* Called if the file errors while loading. Resets the XHR state, then either decrements
* `retryAttempts` and retries the load, or signals failure to the Loader via `nextFile`
* if no retry attempts remain.
*
* @method Phaser.Loader.File#onError
* @since 3.0.0
*
* @param {XMLHttpRequest} xhr - The XMLHttpRequest that caused this onerror event.
* @param {ProgressEvent} event - The DOM ProgressEvent that resulted from this error.
*/
onError: function ()
{
this.resetXHR();
if (this.retryAttempts > 0)
{
this.retryAttempts--;
this.load();
}
else
{
this.loader.nextFile(this, false);
}
},
/**
* Called during the file load progress. Is sent a DOM ProgressEvent.
*
* @method Phaser.Loader.File#onProgress
* @fires Phaser.Loader.Events#FILE_PROGRESS
* @since 3.0.0
*
* @param {ProgressEvent} event - The DOM ProgressEvent.
*/
onProgress: function (event)
{
if (event.lengthComputable)
{
this.bytesLoaded = event.loaded;
this.bytesTotal = event.total;
this.percentComplete = Math.min((this.bytesLoaded / this.bytesTotal), 1);
this.loader.emit(Events.FILE_PROGRESS, this, this.percentComplete);
}
},
/**
* Usually overridden by the FileTypes and is called by Loader.nextFile.
* This method controls what extra work this File does with its loaded data, for example a JSON file will parse itself during this stage.
*
* @method Phaser.Loader.File#onProcess
* @since 3.0.0
*/
onProcess: function ()
{
this.state = CONST.FILE_PROCESSING;
this.onProcessComplete();
},
/**
* Called when the File has completed processing.
* Checks on the state of its multifile, if set.
*
* @method Phaser.Loader.File#onProcessComplete
* @since 3.7.0
*/
onProcessComplete: function ()
{
this.state = CONST.FILE_COMPLETE;
if (this.multiFile)
{
this.multiFile.onFileComplete(this);
}
this.loader.fileProcessComplete(this);
},
/**
* Called when the File has completed processing but it generated an error.
* Checks on the state of its multifile, if set.
*
* @method Phaser.Loader.File#onProcessError
* @since 3.7.0
*/
onProcessError: function ()
{
// eslint-disable-next-line no-console
console.error('Failed to process file: %s "%s"', this.type, this.key);
this.state = CONST.FILE_ERRORED;
if (this.multiFile)
{
this.multiFile.onFileFailed(this);
}
this.loader.fileProcessComplete(this);
},
/**
* Checks if a key matching the one used by this file exists in the target Cache or not.
* This is called automatically by the LoaderPlugin to decide if the file can be safely
* loaded or will conflict.
*
* @method Phaser.Loader.File#hasCacheConflict
* @since 3.7.0
*
* @return {boolean} `true` if adding this file will cause a conflict, otherwise `false`.
*/
hasCacheConflict: function ()
{
return (this.cache && this.cache.exists(this.key));
},
/**
* Adds this file to its target cache upon successful loading and processing.
* This method is often overridden by specific file types.
*
* @method Phaser.Loader.File#addToCache
* @since 3.7.0
*/
addToCache: function ()
{
if (this.cache && this.data)
{
this.cache.add(this.key, this.data);
}
},
/**
* Called once the file has been added to its cache and is now ready for deletion from the Loader.
* It will emit a `filecomplete` event from the LoaderPlugin.
*
* @method Phaser.Loader.File#pendingDestroy
* @fires Phaser.Loader.Events#FILE_COMPLETE
* @fires Phaser.Loader.Events#FILE_KEY_COMPLETE
* @since 3.7.0
*/
pendingDestroy: function (data)
{
if (this.state === CONST.FILE_PENDING_DESTROY)
{
return;
}
if (data === undefined) { data = this.data; }
var key = this.key;
var type = this.type;
this.loader.emit(Events.FILE_COMPLETE, key, type, data);
this.loader.emit(Events.FILE_KEY_COMPLETE + type + '-' + key, key, type, data);
this.loader.flagForRemoval(this);
this.state = CONST.FILE_PENDING_DESTROY;
},
/**
* Destroy this File and any references it holds.
*
* @method Phaser.Loader.File#destroy
* @since 3.7.0
*/
destroy: function ()
{
this.loader = null;
this.cache = null;
this.xhrSettings = null;
this.multiFile = null;
this.linkFile = null;
this.data = null;
}
});
/**
* Static method for creating an object URL using the URL API and setting it as the image 'src' attribute.
* If the URL API is not supported (usually on old browsers) it falls back to creating a Base64 encoded URL using FileReader.
*
* @method Phaser.Loader.File.createObjectURL
* @static
* @since 3.7.0
*
* @param {HTMLImageElement} image - Image object which 'src' attribute should be set to object URL.
* @param {Blob} blob - A Blob object to create an object URL for.
* @param {string} defaultType - Default mime type used if blob type is not available.
*/
File.createObjectURL = function (image, blob, defaultType)
{
if (typeof URL === 'function')
{
image.src = URL.createObjectURL(blob);
}
else
{
var reader = new FileReader();
reader.onload = function ()
{
image.removeAttribute('crossOrigin');
image.src = 'data:' + (blob.type || defaultType) + ';base64,' + reader.result.split(',')[1];
};
reader.onerror = image.onerror;
reader.readAsDataURL(blob);
}
};
/**
* Static method for releasing an existing object URL which was previously created
* by calling {@link Phaser.Loader.File.createObjectURL} method.
*
* @method Phaser.Loader.File.revokeObjectURL
* @static
* @since 3.7.0
*
* @param {HTMLImageElement} image - Image object which 'src' attribute should be revoked.
*/
File.revokeObjectURL = function (image)
{
if (typeof URL === 'function')
{
URL.revokeObjectURL(image.src);
}
};
module.exports = File;