UNPKG

@shopify/react-async

Version:

Tools for creating powerful, asynchronously-loaded React components.

69 lines (68 loc) 2.94 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var React = tslib_1.__importStar(require("react")); var types_1 = require("../types"); exports.EFFECT_ID = Symbol('react-async'); var AsyncAssetManager = /** @class */ (function () { function AsyncAssetManager() { var _this = this; this.effect = { id: exports.EFFECT_ID, betweenEachPass: function () { _this.assets.clear(); }, }; this.assets = new Map(); } AsyncAssetManager.prototype.used = function (timing) { if (timing === void 0) { timing = types_1.AssetTiming.Immediate; } var e_1, _a; var timingArray = Array.isArray(timing) ? timing : [timing]; var assets = []; try { for (var _b = tslib_1.__values(this.assets), _c = _b.next(); !_c.done; _c = _b.next()) { var _d = tslib_1.__read(_c.value, 2), asset = _d[0], _e = _d[1], scripts = _e.scripts, styles = _e.styles; var scriptsMatch = timingArray.includes(scripts); var stylesMatch = timingArray.includes(styles); if (stylesMatch || scriptsMatch) { assets.push({ id: asset, scripts: scriptsMatch, styles: stylesMatch }); } } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (_c && !_c.done && (_a = _b.return)) _a.call(_b); } finally { if (e_1) throw e_1.error; } } return assets; }; AsyncAssetManager.prototype.markAsUsed = function (id, timing) { if (timing === void 0) { timing = types_1.AssetTiming.Immediate; } var current = this.assets.get(id); var scripts = typeof timing === 'object' ? timing.scripts : timing; var styles = typeof timing === 'object' ? timing.styles : timing; if (current == null) { this.assets.set(id, { scripts: scripts || types_1.AssetTiming.Immediate, styles: styles || types_1.AssetTiming.Immediate, }); } else { this.assets.set(id, { // the AssetTiming enum has values where the smallest value is // the lowest importance load, and the highest value is for assets // needed immediately. So, when a new asset comes in that has // already been recorded, we can take the maximum value to // keep only the highest priority timing for the asset. scripts: Math.max(scripts || current.scripts, current.styles), styles: Math.max(styles || current.styles, current.styles), }); } }; return AsyncAssetManager; }()); exports.AsyncAssetManager = AsyncAssetManager; exports.AsyncAssetContext = React.createContext(null);