Source: dependencies/resource-loader/lib/Resource.js

dependencies/resource-loader/lib/Resource.js

  1. //引入小程序补丁
  2. import { windowAlias,
  3. atob,
  4. devicePixelRatio,
  5. documentAlias,
  6. Element,
  7. Event,
  8. EventTarget,
  9. HTMLCanvasElement,
  10. HTMLElement,
  11. HTMLMediaElement,
  12. HTMLVideoElement,
  13. Image,
  14. navigator,
  15. Node,
  16. requestAnimationFrame,
  17. cancelAnimationFrame,
  18. screen,
  19. XMLHttpRequestAlias,
  20. XMLHttpRequest
  21. } from '@ali/pixi-miniprogram-adapter';
  22. 'use strict';
  23. exports.__esModule = true;
  24. exports.Resource = undefined;
  25. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  26. var _parseUri = require('parse-uri');
  27. var _parseUri2 = _interopRequireDefault(_parseUri);
  28. var _miniSignals = require('mini-signals');
  29. var _miniSignals2 = _interopRequireDefault(_miniSignals);
  30. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  31. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  32. // tests if CORS is supported in XHR, if not we need to use XDR
  33. var useXdr = !!(windowAlias.XDomainRequest && !('withCredentials' in new XMLHttpRequest()));
  34. var tempAnchor = null;
  35. // some status constants
  36. var STATUS_NONE = 0;
  37. var STATUS_OK = 200;
  38. var STATUS_EMPTY = 204;
  39. var STATUS_IE_BUG_EMPTY = 1223;
  40. var STATUS_TYPE_OK = 2;
  41. // noop
  42. function _noop() {} /* empty */
  43. /**
  44. * Manages the state and loading of a resource and all child resources.
  45. *
  46. * @class
  47. */
  48. var Resource = exports.Resource = function () {
  49. /**
  50. * Sets the load type to be used for a specific extension.
  51. *
  52. * @static
  53. * @param {string} extname - The extension to set the type for, e.g. "png" or "fnt"
  54. * @param {Resource.LOAD_TYPE} loadType - The load type to set it to.
  55. */
  56. Resource.setExtensionLoadType = function setExtensionLoadType(extname, loadType) {
  57. setExtMap(Resource._loadTypeMap, extname, loadType);
  58. };
  59. /**
  60. * Sets the load type to be used for a specific extension.
  61. *
  62. * @static
  63. * @param {string} extname - The extension to set the type for, e.g. "png" or "fnt"
  64. * @param {Resource.XHR_RESPONSE_TYPE} xhrType - The xhr type to set it to.
  65. */
  66. Resource.setExtensionXhrType = function setExtensionXhrType(extname, xhrType) {
  67. setExtMap(Resource._xhrTypeMap, extname, xhrType);
  68. };
  69. /**
  70. * @param {string} name - The name of the resource to load.
  71. * @param {string|string[]} url - The url for this resource, for audio/video loads you can pass
  72. * an array of sources.
  73. * @param {object} [options] - The options for the load.
  74. * @param {string|boolean} [options.crossOrigin] - Is this request cross-origin? Default is to
  75. * determine automatically.
  76. * @param {number} [options.timeout=0] - A timeout in milliseconds for the load. If the load takes
  77. * longer than this time it is cancelled and the load is considered a failure. If this value is
  78. * set to `0` then there is no explicit timeout.
  79. * @param {Resource.LOAD_TYPE} [options.loadType=Resource.LOAD_TYPE.XHR] - How should this resource
  80. * be loaded?
  81. * @param {Resource.XHR_RESPONSE_TYPE} [options.xhrType=Resource.XHR_RESPONSE_TYPE.DEFAULT] - How
  82. * should the data being loaded be interpreted when using XHR?
  83. * @param {Resource.IMetadata} [options.metadata] - Extra configuration for middleware and the Resource object.
  84. */
  85. function Resource(name, url, options) {
  86. _classCallCheck(this, Resource);
  87. if (typeof name !== 'string' || typeof url !== 'string') {
  88. throw new Error('Both name and url are required for constructing a resource.');
  89. }
  90. options = options || {};
  91. /**
  92. * The state flags of this resource.
  93. *
  94. * @private
  95. * @member {number}
  96. */
  97. this._flags = 0;
  98. // set data url flag, needs to be set early for some _determineX checks to work.
  99. this._setFlag(Resource.STATUS_FLAGS.DATA_URL, url.indexOf('data:') === 0);
  100. /**
  101. * The name of this resource.
  102. *
  103. * @readonly
  104. * @member {string}
  105. */
  106. this.name = name;
  107. /**
  108. * The url used to load this resource.
  109. *
  110. * @readonly
  111. * @member {string}
  112. */
  113. this.url = url;
  114. /**
  115. * The extension used to load this resource.
  116. *
  117. * @readonly
  118. * @member {string}
  119. */
  120. this.extension = this._getExtension();
  121. /**
  122. * The data that was loaded by the resource.
  123. *
  124. * @member {any}
  125. */
  126. this.data = null;
  127. /**
  128. * Is this request cross-origin? If unset, determined automatically.
  129. *
  130. * @member {string}
  131. */
  132. this.crossOrigin = options.crossOrigin === true ? 'anonymous' : options.crossOrigin;
  133. /**
  134. * A timeout in milliseconds for the load. If the load takes longer than this time
  135. * it is cancelled and the load is considered a failure. If this value is set to `0`
  136. * then there is no explicit timeout.
  137. *
  138. * @member {number}
  139. */
  140. this.timeout = options.timeout || 0;
  141. /**
  142. * The method of loading to use for this resource.
  143. *
  144. * @member {Resource.LOAD_TYPE}
  145. */
  146. this.loadType = options.loadType || this._determineLoadType();
  147. /**
  148. * The type used to load the resource via XHR. If unset, determined automatically.
  149. *
  150. * @member {string}
  151. */
  152. this.xhrType = options.xhrType;
  153. /**
  154. * Extra info for middleware, and controlling specifics about how the resource loads.
  155. *
  156. * Note that if you pass in a `loadElement`, the Resource class takes ownership of it.
  157. * Meaning it will modify it as it sees fit.
  158. *
  159. * @member {Resource.IMetadata}
  160. */
  161. this.metadata = options.metadata || {};
  162. /**
  163. * The error that occurred while loading (if any).
  164. *
  165. * @readonly
  166. * @member {Error}
  167. */
  168. this.error = null;
  169. /**
  170. * The XHR object that was used to load this resource. This is only set
  171. * when `loadType` is `Resource.LOAD_TYPE.XHR`.
  172. *
  173. * @readonly
  174. * @member {XMLHttpRequest}
  175. */
  176. this.xhr = null;
  177. /**
  178. * The child resources this resource owns.
  179. *
  180. * @readonly
  181. * @member {Resource[]}
  182. */
  183. this.children = [];
  184. /**
  185. * The resource type.
  186. *
  187. * @readonly
  188. * @member {Resource.TYPE}
  189. */
  190. this.type = Resource.TYPE.UNKNOWN;
  191. /**
  192. * The progress chunk owned by this resource.
  193. *
  194. * @readonly
  195. * @member {number}
  196. */
  197. this.progressChunk = 0;
  198. /**
  199. * The `dequeue` method that will be used a storage place for the async queue dequeue method
  200. * used privately by the loader.
  201. *
  202. * @private
  203. * @member {function}
  204. */
  205. this._dequeue = _noop;
  206. /**
  207. * Used a storage place for the on load binding used privately by the loader.
  208. *
  209. * @private
  210. * @member {function}
  211. */
  212. this._onLoadBinding = null;
  213. /**
  214. * The timer for element loads to check if they timeout.
  215. *
  216. * @private
  217. * @member {number}
  218. */
  219. this._elementTimer = 0;
  220. /**
  221. * The `complete` function bound to this resource's context.
  222. *
  223. * @private
  224. * @member {function}
  225. */
  226. this._boundComplete = this.complete.bind(this);
  227. /**
  228. * The `_onError` function bound to this resource's context.
  229. *
  230. * @private
  231. * @member {function}
  232. */
  233. this._boundOnError = this._onError.bind(this);
  234. /**
  235. * The `_onProgress` function bound to this resource's context.
  236. *
  237. * @private
  238. * @member {function}
  239. */
  240. this._boundOnProgress = this._onProgress.bind(this);
  241. /**
  242. * The `_onTimeout` function bound to this resource's context.
  243. *
  244. * @private
  245. * @member {function}
  246. */
  247. this._boundOnTimeout = this._onTimeout.bind(this);
  248. // xhr callbacks
  249. this._boundXhrOnError = this._xhrOnError.bind(this);
  250. this._boundXhrOnTimeout = this._xhrOnTimeout.bind(this);
  251. this._boundXhrOnAbort = this._xhrOnAbort.bind(this);
  252. this._boundXhrOnLoad = this._xhrOnLoad.bind(this);
  253. /**
  254. * Dispatched when the resource beings to load.
  255. *
  256. * The callback looks like {@link Resource.OnStartSignal}.
  257. *
  258. * @member {Signal<Resource.OnStartSignal>}
  259. */
  260. this.onStart = new _miniSignals2.default();
  261. /**
  262. * Dispatched each time progress of this resource load updates.
  263. * Not all resources types and loader systems can support this event
  264. * so sometimes it may not be available. If the resource
  265. * is being loaded on a modern browser, using XHR, and the remote server
  266. * properly sets Content-Length headers, then this will be available.
  267. *
  268. * The callback looks like {@link Resource.OnProgressSignal}.
  269. *
  270. * @member {Signal<Resource.OnProgressSignal>}
  271. */
  272. this.onProgress = new _miniSignals2.default();
  273. /**
  274. * Dispatched once this resource has loaded, if there was an error it will
  275. * be in the `error` property.
  276. *
  277. * The callback looks like {@link Resource.OnCompleteSignal}.
  278. *
  279. * @member {Signal<Resource.OnCompleteSignal>}
  280. */
  281. this.onComplete = new _miniSignals2.default();
  282. /**
  283. * Dispatched after this resource has had all the *after* middleware run on it.
  284. *
  285. * The callback looks like {@link Resource.OnCompleteSignal}.
  286. *
  287. * @member {Signal<Resource.OnCompleteSignal>}
  288. */
  289. this.onAfterMiddleware = new _miniSignals2.default();
  290. }
  291. /**
  292. * When the resource starts to load.
  293. *
  294. * @memberof Resource
  295. * @callback OnStartSignal
  296. * @param {Resource} resource - The resource that the event happened on.
  297. */
  298. /**
  299. * When the resource reports loading progress.
  300. *
  301. * @memberof Resource
  302. * @callback OnProgressSignal
  303. * @param {Resource} resource - The resource that the event happened on.
  304. * @param {number} percentage - The progress of the load in the range [0, 1].
  305. */
  306. /**
  307. * When the resource finishes loading.
  308. *
  309. * @memberof Resource
  310. * @callback OnCompleteSignal
  311. * @param {Resource} resource - The resource that the event happened on.
  312. */
  313. /**
  314. * @memberof Resource
  315. * @typedef {object} IMetadata
  316. * @property {HTMLImageElement|HTMLAudioElement|HTMLVideoElement} [loadElement=null] - The
  317. * element to use for loading, instead of creating one.
  318. * @property {boolean} [skipSource=false] - Skips adding source(s) to the load element. This
  319. * is useful if you want to pass in a `loadElement` that you already added load sources to.
  320. * @property {string|string[]} [mimeType] - The mime type to use for the source element
  321. * of a video/audio elment. If the urls are an array, you can pass this as an array as well
  322. * where each index is the mime type to use for the corresponding url index.
  323. */
  324. /**
  325. * Stores whether or not this url is a data url.
  326. *
  327. * @readonly
  328. * @member {boolean}
  329. */
  330. /**
  331. * Marks the resource as complete.
  332. *
  333. */
  334. Resource.prototype.complete = function complete() {
  335. this._clearEvents();
  336. this._finish();
  337. };
  338. /**
  339. * Aborts the loading of this resource, with an optional message.
  340. *
  341. * @param {string} message - The message to use for the error
  342. */
  343. Resource.prototype.abort = function abort(message) {
  344. // abort can be called multiple times, ignore subsequent calls.
  345. if (this.error) {
  346. return;
  347. }
  348. // store error
  349. this.error = new Error(message);
  350. // clear events before calling aborts
  351. this._clearEvents();
  352. // abort the actual loading
  353. if (this.xhr) {
  354. this.xhr.abort();
  355. } else if (this.xdr) {
  356. this.xdr.abort();
  357. } else if (this.data) {
  358. // single source
  359. if (this.data.src) {
  360. this.data.src = Resource.EMPTY_GIF;
  361. }
  362. // multi-source
  363. else {
  364. while (this.data.firstChild) {
  365. this.data.removeChild(this.data.firstChild);
  366. }
  367. }
  368. }
  369. // done now.
  370. this._finish();
  371. };
  372. /**
  373. * Kicks off loading of this resource. This method is asynchronous.
  374. *
  375. * @param {Resource.OnCompleteSignal} [cb] - Optional callback to call once the resource is loaded.
  376. */
  377. Resource.prototype.load = function load(cb) {
  378. var _this = this;
  379. if (this.isLoading) {
  380. return;
  381. }
  382. if (this.isComplete) {
  383. if (cb) {
  384. setTimeout(function () {
  385. return cb(_this);
  386. }, 1);
  387. }
  388. return;
  389. } else if (cb) {
  390. this.onComplete.once(cb);
  391. }
  392. this._setFlag(Resource.STATUS_FLAGS.LOADING, true);
  393. this.onStart.dispatch(this);
  394. // if unset, determine the value
  395. if (this.crossOrigin === false || typeof this.crossOrigin !== 'string') {
  396. this.crossOrigin = this._determineCrossOrigin(this.url);
  397. }
  398. switch (this.loadType) {
  399. case Resource.LOAD_TYPE.IMAGE:
  400. this.type = Resource.TYPE.IMAGE;
  401. this._loadElement('image');
  402. break;
  403. case Resource.LOAD_TYPE.AUDIO:
  404. this.type = Resource.TYPE.AUDIO;
  405. this._loadSourceElement('audio');
  406. break;
  407. case Resource.LOAD_TYPE.VIDEO:
  408. this.type = Resource.TYPE.VIDEO;
  409. this._loadSourceElement('video');
  410. break;
  411. case Resource.LOAD_TYPE.XHR:
  412. /* falls through */
  413. default:
  414. if (useXdr && this.crossOrigin) {
  415. this._loadXdr();
  416. } else {
  417. this._loadXhr();
  418. }
  419. break;
  420. }
  421. };
  422. /**
  423. * Checks if the flag is set.
  424. *
  425. * @private
  426. * @param {number} flag - The flag to check.
  427. * @return {boolean} True if the flag is set.
  428. */
  429. Resource.prototype._hasFlag = function _hasFlag(flag) {
  430. return (this._flags & flag) !== 0;
  431. };
  432. /**
  433. * (Un)Sets the flag.
  434. *
  435. * @private
  436. * @param {number} flag - The flag to (un)set.
  437. * @param {boolean} value - Whether to set or (un)set the flag.
  438. */
  439. Resource.prototype._setFlag = function _setFlag(flag, value) {
  440. this._flags = value ? this._flags | flag : this._flags & ~flag;
  441. };
  442. /**
  443. * Clears all the events from the underlying loading source.
  444. *
  445. * @private
  446. */
  447. Resource.prototype._clearEvents = function _clearEvents() {
  448. clearTimeout(this._elementTimer);
  449. if (this.data && this.data.removeEventListener) {
  450. this.data.removeEventListener('error', this._boundOnError, false);
  451. this.data.removeEventListener('load', this._boundComplete, false);
  452. this.data.removeEventListener('progress', this._boundOnProgress, false);
  453. this.data.removeEventListener('canplaythrough', this._boundComplete, false);
  454. }
  455. if (this.xhr) {
  456. if (this.xhr.removeEventListener) {
  457. this.xhr.removeEventListener('error', this._boundXhrOnError, false);
  458. this.xhr.removeEventListener('timeout', this._boundXhrOnTimeout, false);
  459. this.xhr.removeEventListener('abort', this._boundXhrOnAbort, false);
  460. this.xhr.removeEventListener('progress', this._boundOnProgress, false);
  461. this.xhr.removeEventListener('load', this._boundXhrOnLoad, false);
  462. } else {
  463. this.xhr.onerror = null;
  464. this.xhr.ontimeout = null;
  465. this.xhr.onprogress = null;
  466. this.xhr.onload = null;
  467. }
  468. }
  469. };
  470. /**
  471. * Finalizes the load.
  472. *
  473. * @private
  474. */
  475. Resource.prototype._finish = function _finish() {
  476. if (this.isComplete) {
  477. throw new Error('Complete called again for an already completed resource.');
  478. }
  479. this._setFlag(Resource.STATUS_FLAGS.COMPLETE, true);
  480. this._setFlag(Resource.STATUS_FLAGS.LOADING, false);
  481. this.onComplete.dispatch(this);
  482. };
  483. /**
  484. * Loads this resources using an element that has a single source,
  485. * like an HTMLImageElement.
  486. *
  487. * @private
  488. * @param {string} type - The type of element to use.
  489. */
  490. Resource.prototype._loadElement = function _loadElement(type) {
  491. // TODO miniprogram 在小程序宿主下,如果读取路径问本地文件,则通过my.FileSystemManager.readFile实现
  492. const url = this.url;
  493. let isLocalFile = false;
  494. if( typeof url === 'string'){
  495. let reg = /(http|https):\/\/([\w.]+\/?)\S*/ig;
  496. isLocalFile = !url.match(reg);
  497. }
  498. if (this.metadata.loadElement) {
  499. this.data = this.metadata.loadElement;
  500. } else if (type === 'image' && typeof windowAlias.Image !== 'undefined') {
  501. // if(isLocalFile){
  502. // // TODO miniprogram 在小程序宿主下,如果读取路径问本地文
  503. // // this.data = my.FileSystemManager.readFile({
  504. // // filePath:url,
  505. // // success:(res)=>{
  506. // // //res.data string/ArrayBuffer 文件内容
  507. // // // dataType String 如果未传入dataType,则默认以arrayBuffer读取数据
  508. // // this._boundComplete.call(this,res);
  509. // // },
  510. // // fail:this._boundOnError
  511. // // });
  512. // console.warn('当前版本暂不支持读取本地文件');
  513. // // TODO 后期去掉 为了避免报错 暂时用Image代替
  514. // this.data = new Image();
  515. // }else{
  516. // this.data = new Image();
  517. // }
  518. this.data = new Image();
  519. } else {
  520. this.data = documentAlias.createElement(type);
  521. }
  522. if (this.crossOrigin) {
  523. this.data.crossOrigin = this.crossOrigin;
  524. }
  525. // miniprogram 上Image只有onLoad和 onerror,且 onload和onerro需要放在src设置之前。
  526. this.data.onload = this._boundComplete;
  527. this.data.onerror = this._boundOnError;
  528. if (!this.metadata.skipSource) {
  529. this.data.src = this.url;
  530. }
  531. // this.data.addEventListener('error', this._boundOnError, false);
  532. // this.data.addEventListener('load', this._boundComplete, false);
  533. // this.data.addEventListener('progress', this._boundOnProgress, false);
  534. if (this.timeout) {
  535. this._elementTimer = setTimeout(this._boundOnTimeout, this.timeout);
  536. }
  537. };
  538. /**
  539. * Loads this resources using an element that has multiple sources,
  540. * like an HTMLAudioElement or HTMLVideoElement.
  541. *
  542. * @private
  543. * @param {string} type - The type of element to use.
  544. */
  545. Resource.prototype._loadSourceElement = function _loadSourceElement(type) {
  546. if (this.metadata.loadElement) {
  547. this.data = this.metadata.loadElement;
  548. } else if (type === 'audio' && typeof windowAlias.Audio !== 'undefined') {
  549. this.data = new Audio();
  550. } else {
  551. this.data = documentAlias.createElement(type);
  552. }
  553. if (this.data === null) {
  554. this.abort('Unsupported element: ' + type);
  555. return;
  556. }
  557. if (this.crossOrigin) {
  558. this.data.crossOrigin = this.crossOrigin;
  559. }
  560. if (!this.metadata.skipSource) {
  561. // support for CocoonJS Canvas+ runtime, lacks documentAlias.createElement('source')
  562. if (navigator.isCocoonJS) {
  563. this.data.src = Array.isArray(this.url) ? this.url[0] : this.url;
  564. } else if (Array.isArray(this.url)) {
  565. var mimeTypes = this.metadata.mimeType;
  566. for (var i = 0; i < this.url.length; ++i) {
  567. this.data.appendChild(this._createSource(type, this.url[i], Array.isArray(mimeTypes) ? mimeTypes[i] : mimeTypes));
  568. }
  569. } else {
  570. var _mimeTypes = this.metadata.mimeType;
  571. this.data.appendChild(this._createSource(type, this.url, Array.isArray(_mimeTypes) ? _mimeTypes[0] : _mimeTypes));
  572. }
  573. }
  574. this.data.addEventListener('error', this._boundOnError, false);
  575. this.data.addEventListener('load', this._boundComplete, false);
  576. this.data.addEventListener('progress', this._boundOnProgress, false);
  577. this.data.addEventListener('canplaythrough', this._boundComplete, false);
  578. this.data.load();
  579. if (this.timeout) {
  580. this._elementTimer = setTimeout(this._boundOnTimeout, this.timeout);
  581. }
  582. };
  583. /**
  584. * Loads this resources using an XMLHttpRequest.
  585. *
  586. * @private
  587. */
  588. Resource.prototype._loadXhr = function _loadXhr() {
  589. // if unset, determine the value
  590. if (typeof this.xhrType !== 'string') {
  591. this.xhrType = this._determineXhrType();
  592. }
  593. // miniprogram 使用 XMLHttpRequestAlias 代理 XMLHttpRequest
  594. var xhr = this.xhr = new XMLHttpRequestAlias();
  595. // set the request type and url
  596. xhr.open('GET', this.url, true);
  597. xhr.timeout = this.timeout;
  598. // load json as text and parse it ourselves. We do this because some browsers
  599. // *cough* safari *cough* can't deal with it.
  600. if (this.xhrType === Resource.XHR_RESPONSE_TYPE.JSON || this.xhrType === Resource.XHR_RESPONSE_TYPE.DOCUMENT) {
  601. xhr.responseType = Resource.XHR_RESPONSE_TYPE.TEXT;
  602. } else {
  603. xhr.responseType = this.xhrType;
  604. }
  605. xhr.addEventListener('error', this._boundXhrOnError, false);
  606. xhr.addEventListener('timeout', this._boundXhrOnTimeout, false);
  607. xhr.addEventListener('abort', this._boundXhrOnAbort, false);
  608. xhr.addEventListener('progress', this._boundOnProgress, false);
  609. xhr.addEventListener('load', this._boundXhrOnLoad, false);
  610. xhr.send();
  611. };
  612. /**
  613. * Loads this resources using an XDomainRequest. This is here because we need to support IE9 (gross).
  614. *
  615. * @private
  616. */
  617. Resource.prototype._loadXdr = function _loadXdr() {
  618. // if unset, determine the value
  619. if (typeof this.xhrType !== 'string') {
  620. this.xhrType = this._determineXhrType();
  621. }
  622. var xdr = this.xhr = new XDomainRequest(); // eslint-disable-line no-undef
  623. // XDomainRequest has a few quirks. Occasionally it will abort requests
  624. // A way to avoid this is to make sure ALL callbacks are set even if not used
  625. // More info here: http://stackoverflow.com/questions/15786966/xdomainrequest-aborts-post-on-ie-9
  626. xdr.timeout = this.timeout || 5000; // XDR needs a timeout value or it breaks in IE9
  627. xdr.onerror = this._boundXhrOnError;
  628. xdr.ontimeout = this._boundXhrOnTimeout;
  629. xdr.onprogress = this._boundOnProgress;
  630. xdr.onload = this._boundXhrOnLoad;
  631. xdr.open('GET', this.url, true);
  632. // Note: The xdr.send() call is wrapped in a timeout to prevent an
  633. // issue with the interface where some requests are lost if multiple
  634. // XDomainRequests are being sent at the same time.
  635. // Some info here: https://github.com/photonstorm/phaser/issues/1248
  636. setTimeout(function () {
  637. return xdr.send();
  638. }, 1);
  639. };
  640. /**
  641. * Creates a source used in loading via an element.
  642. *
  643. * @private
  644. * @param {string} type - The element type (video or audio).
  645. * @param {string} url - The source URL to load from.
  646. * @param {string} [mime] - The mime type of the video
  647. * @return {HTMLSourceElement} The source element.
  648. */
  649. Resource.prototype._createSource = function _createSource(type, url, mime) {
  650. if (!mime) {
  651. mime = type + '/' + this._getExtension(url);
  652. }
  653. var source = documentAlias.createElement('source');
  654. source.src = url;
  655. source.type = mime;
  656. return source;
  657. };
  658. /**
  659. * Called if a load errors out.
  660. *
  661. * @param {Event} event - The error event from the element that emits it.
  662. * @private
  663. */
  664. Resource.prototype._onError = function _onError(event) {
  665. this.abort('Failed to load element using: ' + event.target.nodeName);
  666. };
  667. /**
  668. * Called if a load progress event fires for an element or xhr/xdr.
  669. *
  670. * @private
  671. * @param {XMLHttpRequestProgressEvent|Event} event - Progress event.
  672. */
  673. Resource.prototype._onProgress = function _onProgress(event) {
  674. if (event && event.lengthComputable) {
  675. this.onProgress.dispatch(this, event.loaded / event.total);
  676. }
  677. };
  678. /**
  679. * Called if a timeout event fires for an element.
  680. *
  681. * @private
  682. */
  683. Resource.prototype._onTimeout = function _onTimeout() {
  684. this.abort('Load timed out.');
  685. };
  686. /**
  687. * Called if an error event fires for xhr/xdr.
  688. *
  689. * @private
  690. */
  691. Resource.prototype._xhrOnError = function _xhrOnError() {
  692. var xhr = this.xhr;
  693. this.abort(reqType(xhr) + ' Request failed. Status: ' + xhr.status + ', text: "' + xhr.statusText + '"');
  694. };
  695. /**
  696. * Called if an error event fires for xhr/xdr.
  697. *
  698. * @private
  699. */
  700. Resource.prototype._xhrOnTimeout = function _xhrOnTimeout() {
  701. var xhr = this.xhr;
  702. this.abort(reqType(xhr) + ' Request timed out.');
  703. };
  704. /**
  705. * Called if an abort event fires for xhr/xdr.
  706. *
  707. * @private
  708. */
  709. Resource.prototype._xhrOnAbort = function _xhrOnAbort() {
  710. var xhr = this.xhr;
  711. this.abort(reqType(xhr) + ' Request was aborted by the user.');
  712. };
  713. /**
  714. * Called when data successfully loads from an xhr/xdr request.
  715. *
  716. * @private
  717. * @param {XMLHttpRequestLoadEvent|Event} event - Load event
  718. */
  719. Resource.prototype._xhrOnLoad = function _xhrOnLoad() {
  720. var xhr = this.xhr;
  721. var text = '';
  722. var status = typeof xhr.status === 'undefined' ? STATUS_OK : xhr.status; // XDR has no `.status`, assume 200.
  723. // responseText is accessible only if responseType is '' or 'text' and on older browsers
  724. if (xhr.responseType === '' || xhr.responseType === 'text' || typeof xhr.responseType === 'undefined') {
  725. text = xhr.responseText;
  726. }
  727. // status can be 0 when using the `file://` protocol so we also check if a response is set.
  728. // If it has a response, we assume 200; otherwise a 0 status code with no contents is an aborted request.
  729. if (status === STATUS_NONE && (text.length > 0 || xhr.responseType === Resource.XHR_RESPONSE_TYPE.BUFFER)) {
  730. status = STATUS_OK;
  731. }
  732. // handle IE9 bug: http://stackoverflow.com/questions/10046972/msie-returns-status-code-of-1223-for-ajax-request
  733. else if (status === STATUS_IE_BUG_EMPTY) {
  734. status = STATUS_EMPTY;
  735. }
  736. var statusType = status / 100 | 0;
  737. if (statusType === STATUS_TYPE_OK) {
  738. // if text, just return it
  739. if (this.xhrType === Resource.XHR_RESPONSE_TYPE.TEXT) {
  740. this.data = text;
  741. this.type = Resource.TYPE.TEXT;
  742. }
  743. // if json, parse into json object
  744. else if (this.xhrType === Resource.XHR_RESPONSE_TYPE.JSON) {
  745. try {
  746. this.data = JSON.parse(text);
  747. this.type = Resource.TYPE.JSON;
  748. } catch (e) {
  749. this.abort('Error trying to parse loaded json: ' + e);
  750. return;
  751. }
  752. }
  753. // if xml, parse into an xml document or div element
  754. else if (this.xhrType === Resource.XHR_RESPONSE_TYPE.DOCUMENT) {
  755. try {
  756. if (windowAlias.DOMParser) {
  757. var domparser = new DOMParser();
  758. this.data = domparser.parseFromString(text, 'text/xml');
  759. } else {
  760. var div = documentAlias.createElement('div');
  761. div.innerHTML = text;
  762. this.data = div;
  763. }
  764. this.type = Resource.TYPE.XML;
  765. } catch (e) {
  766. this.abort('Error trying to parse loaded xml: ' + e);
  767. return;
  768. }
  769. }
  770. // other types just return the response
  771. else {
  772. this.data = xhr.response || text;
  773. }
  774. } else {
  775. this.abort('[' + xhr.status + '] ' + xhr.statusText + ': ' + xhr.responseURL);
  776. return;
  777. }
  778. this.complete();
  779. };
  780. /**
  781. * Sets the `crossOrigin` property for this resource based on if the url
  782. * for this resource is cross-origin. If crossOrigin was manually set, this
  783. * function does nothing.
  784. *
  785. * @private
  786. * @param {string} url - The url to test.
  787. * @param {object} [loc=windowAlias.location] - The location object to test against.
  788. * @return {string} The crossOrigin value to use (or empty string for none).
  789. */
  790. Resource.prototype._determineCrossOrigin = function _determineCrossOrigin(url, loc) {
  791. // data: and javascript: urls are considered same-origin
  792. if (url.indexOf('data:') === 0) {
  793. return '';
  794. }
  795. // A sandboxed iframe without the 'allow-same-origin' attribute will have a special
  796. // origin designed not to match windowAlias.location.origin, and will always require
  797. // crossOrigin requests regardless of whether the location matches.
  798. if (windowAlias.origin !== windowAlias.location.origin) {
  799. return 'anonymous';
  800. }
  801. // default is windowAlias.location
  802. loc = loc || windowAlias.location;
  803. if (!tempAnchor) {
  804. tempAnchor = documentAlias.createElement('a');
  805. }
  806. // let the browser determine the full href for the url of this resource and then
  807. // parse with the node url lib, we can't use the properties of the anchor element
  808. // because they don't work in IE9 :(
  809. tempAnchor.href = url;
  810. url = (0, _parseUri2.default)(tempAnchor.href, { strictMode: true });
  811. var samePort = !url.port && loc.port === '' || url.port === loc.port;
  812. var protocol = url.protocol ? url.protocol + ':' : '';
  813. // if cross origin
  814. if (url.host !== loc.hostname || !samePort || protocol !== loc.protocol) {
  815. return 'anonymous';
  816. }
  817. return '';
  818. };
  819. /**
  820. * Determines the responseType of an XHR request based on the extension of the
  821. * resource being loaded.
  822. *
  823. * @private
  824. * @return {Resource.XHR_RESPONSE_TYPE} The responseType to use.
  825. */
  826. Resource.prototype._determineXhrType = function _determineXhrType() {
  827. return Resource._xhrTypeMap[this.extension] || Resource.XHR_RESPONSE_TYPE.TEXT;
  828. };
  829. /**
  830. * Determines the loadType of a resource based on the extension of the
  831. * resource being loaded.
  832. *
  833. * @private
  834. * @return {Resource.LOAD_TYPE} The loadType to use.
  835. */
  836. Resource.prototype._determineLoadType = function _determineLoadType() {
  837. return Resource._loadTypeMap[this.extension] || Resource.LOAD_TYPE.XHR;
  838. };
  839. /**
  840. * Extracts the extension (sans '.') of the file being loaded by the resource.
  841. *
  842. * @private
  843. * @return {string} The extension.
  844. */
  845. Resource.prototype._getExtension = function _getExtension() {
  846. var url = this.url;
  847. var ext = '';
  848. if (this.isDataUrl) {
  849. var slashIndex = url.indexOf('/');
  850. ext = url.substring(slashIndex + 1, url.indexOf(';', slashIndex));
  851. } else {
  852. var queryStart = url.indexOf('?');
  853. var hashStart = url.indexOf('#');
  854. var index = Math.min(queryStart > -1 ? queryStart : url.length, hashStart > -1 ? hashStart : url.length);
  855. url = url.substring(0, index);
  856. ext = url.substring(url.lastIndexOf('.') + 1);
  857. }
  858. return ext.toLowerCase();
  859. };
  860. /**
  861. * Determines the mime type of an XHR request based on the responseType of
  862. * resource being loaded.
  863. *
  864. * @private
  865. * @param {Resource.XHR_RESPONSE_TYPE} type - The type to get a mime type for.
  866. * @return {string} The mime type to use.
  867. */
  868. Resource.prototype._getMimeFromXhrType = function _getMimeFromXhrType(type) {
  869. switch (type) {
  870. case Resource.XHR_RESPONSE_TYPE.BUFFER:
  871. return 'application/octet-binary';
  872. case Resource.XHR_RESPONSE_TYPE.BLOB:
  873. return 'application/blob';
  874. case Resource.XHR_RESPONSE_TYPE.DOCUMENT:
  875. return 'application/xml';
  876. case Resource.XHR_RESPONSE_TYPE.JSON:
  877. return 'application/json';
  878. case Resource.XHR_RESPONSE_TYPE.DEFAULT:
  879. case Resource.XHR_RESPONSE_TYPE.TEXT:
  880. /* falls through */
  881. default:
  882. return 'text/plain';
  883. }
  884. };
  885. _createClass(Resource, [{
  886. key: 'isDataUrl',
  887. get: function get() {
  888. return this._hasFlag(Resource.STATUS_FLAGS.DATA_URL);
  889. }
  890. /**
  891. * Describes if this resource has finished loading. Is true when the resource has completely
  892. * loaded.
  893. *
  894. * @readonly
  895. * @member {boolean}
  896. */
  897. }, {
  898. key: 'isComplete',
  899. get: function get() {
  900. return this._hasFlag(Resource.STATUS_FLAGS.COMPLETE);
  901. }
  902. /**
  903. * Describes if this resource is currently loading. Is true when the resource starts loading,
  904. * and is false again when complete.
  905. *
  906. * @readonly
  907. * @member {boolean}
  908. */
  909. }, {
  910. key: 'isLoading',
  911. get: function get() {
  912. return this._hasFlag(Resource.STATUS_FLAGS.LOADING);
  913. }
  914. }]);
  915. return Resource;
  916. }();
  917. /**
  918. * The types of resources a resource could represent.
  919. *
  920. * @static
  921. * @readonly
  922. * @enum {number}
  923. */
  924. Resource.STATUS_FLAGS = {
  925. NONE: 0,
  926. DATA_URL: 1 << 0,
  927. COMPLETE: 1 << 1,
  928. LOADING: 1 << 2
  929. };
  930. /**
  931. * The types of resources a resource could represent.
  932. *
  933. * @static
  934. * @readonly
  935. * @enum {number}
  936. */
  937. Resource.TYPE = {
  938. UNKNOWN: 0,
  939. JSON: 1,
  940. XML: 2,
  941. IMAGE: 3,
  942. AUDIO: 4,
  943. VIDEO: 5,
  944. TEXT: 6
  945. };
  946. /**
  947. * The types of loading a resource can use.
  948. *
  949. * @static
  950. * @readonly
  951. * @enum {number}
  952. */
  953. Resource.LOAD_TYPE = {
  954. /** Uses XMLHttpRequest to load the resource. */
  955. XHR: 1,
  956. /** Uses an `Image` object to load the resource. */
  957. IMAGE: 2,
  958. /** Uses an `Audio` object to load the resource. */
  959. AUDIO: 3,
  960. /** Uses a `Video` object to load the resource. */
  961. VIDEO: 4
  962. };
  963. /**
  964. * The XHR ready states, used internally.
  965. *
  966. * @static
  967. * @readonly
  968. * @enum {string}
  969. */
  970. Resource.XHR_RESPONSE_TYPE = {
  971. /** string */
  972. DEFAULT: 'text',
  973. /** ArrayBuffer */
  974. BUFFER: 'arraybuffer',
  975. /** Blob */
  976. BLOB: 'blob',
  977. /** Document */
  978. DOCUMENT: 'document',
  979. /** Object */
  980. JSON: 'json',
  981. /** String */
  982. TEXT: 'text'
  983. };
  984. Resource._loadTypeMap = {
  985. // images
  986. gif: Resource.LOAD_TYPE.IMAGE,
  987. png: Resource.LOAD_TYPE.IMAGE,
  988. bmp: Resource.LOAD_TYPE.IMAGE,
  989. jpg: Resource.LOAD_TYPE.IMAGE,
  990. jpeg: Resource.LOAD_TYPE.IMAGE,
  991. tif: Resource.LOAD_TYPE.IMAGE,
  992. tiff: Resource.LOAD_TYPE.IMAGE,
  993. webp: Resource.LOAD_TYPE.IMAGE,
  994. tga: Resource.LOAD_TYPE.IMAGE,
  995. svg: Resource.LOAD_TYPE.IMAGE,
  996. 'svg+xml': Resource.LOAD_TYPE.IMAGE, // for SVG data urls
  997. // audio
  998. mp3: Resource.LOAD_TYPE.AUDIO,
  999. ogg: Resource.LOAD_TYPE.AUDIO,
  1000. wav: Resource.LOAD_TYPE.AUDIO,
  1001. // videos
  1002. mp4: Resource.LOAD_TYPE.VIDEO,
  1003. webm: Resource.LOAD_TYPE.VIDEO
  1004. };
  1005. Resource._xhrTypeMap = {
  1006. // xml
  1007. xhtml: Resource.XHR_RESPONSE_TYPE.DOCUMENT,
  1008. html: Resource.XHR_RESPONSE_TYPE.DOCUMENT,
  1009. htm: Resource.XHR_RESPONSE_TYPE.DOCUMENT,
  1010. xml: Resource.XHR_RESPONSE_TYPE.DOCUMENT,
  1011. tmx: Resource.XHR_RESPONSE_TYPE.DOCUMENT,
  1012. svg: Resource.XHR_RESPONSE_TYPE.DOCUMENT,
  1013. // This was added to handle Tiled Tileset XML, but .tsx is also a TypeScript React Component.
  1014. // Since it is way less likely for people to be loading TypeScript files instead of Tiled files,
  1015. // this should probably be fine.
  1016. tsx: Resource.XHR_RESPONSE_TYPE.DOCUMENT,
  1017. // images
  1018. gif: Resource.XHR_RESPONSE_TYPE.BLOB,
  1019. png: Resource.XHR_RESPONSE_TYPE.BLOB,
  1020. bmp: Resource.XHR_RESPONSE_TYPE.BLOB,
  1021. jpg: Resource.XHR_RESPONSE_TYPE.BLOB,
  1022. jpeg: Resource.XHR_RESPONSE_TYPE.BLOB,
  1023. tif: Resource.XHR_RESPONSE_TYPE.BLOB,
  1024. tiff: Resource.XHR_RESPONSE_TYPE.BLOB,
  1025. webp: Resource.XHR_RESPONSE_TYPE.BLOB,
  1026. tga: Resource.XHR_RESPONSE_TYPE.BLOB,
  1027. // json
  1028. json: Resource.XHR_RESPONSE_TYPE.JSON,
  1029. // text
  1030. text: Resource.XHR_RESPONSE_TYPE.TEXT,
  1031. txt: Resource.XHR_RESPONSE_TYPE.TEXT,
  1032. // fonts
  1033. ttf: Resource.XHR_RESPONSE_TYPE.BUFFER,
  1034. otf: Resource.XHR_RESPONSE_TYPE.BUFFER
  1035. };
  1036. // We can't set the `src` attribute to empty string, so on abort we set it to this 1px transparent gif
  1037. Resource.EMPTY_GIF = 'data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==';
  1038. /**
  1039. * Quick helper to set a value on one of the extension maps. Ensures there is no
  1040. * dot at the start of the extension.
  1041. *
  1042. * @ignore
  1043. * @param {object} map - The map to set on.
  1044. * @param {string} extname - The extension (or key) to set.
  1045. * @param {number} val - The value to set.
  1046. */
  1047. function setExtMap(map, extname, val) {
  1048. if (extname && extname.indexOf('.') === 0) {
  1049. extname = extname.substring(1);
  1050. }
  1051. if (!extname) {
  1052. return;
  1053. }
  1054. map[extname] = val;
  1055. }
  1056. /**
  1057. * Quick helper to get string xhr type.
  1058. *
  1059. * @ignore
  1060. * @param {XMLHttpRequest|XDomainRequest} xhr - The request to check.
  1061. * @return {string} The type.
  1062. */
  1063. function reqType(xhr) {
  1064. return xhr.toString().replace('object ', '');
  1065. }
  1066. // Backwards compat
  1067. if (typeof module !== 'undefined') {
  1068. module.exports.default = Resource; // eslint-disable-line no-undef
  1069. }
  1070. //# sourceMappingURL=Resource.js.map