UNPKG

@shopify/react-async

Version:

Tools for creating powerful, asynchronously-loaded React components

69 lines (62 loc) 2.27 kB
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var React = require('react'); var types = require('../types.js'); function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } var React__default = /*#__PURE__*/_interopDefaultLegacy(React); const EFFECT_ID = Symbol('react-async'); class AsyncAssetManager { constructor() { this.effect = { id: EFFECT_ID, betweenEachPass: () => { this.assets.clear(); } }; this.assets = new Map(); } used(timing = types.AssetTiming.Immediate) { const timingArray = Array.isArray(timing) ? timing : [timing]; const assets = []; for (const [asset, { scripts, styles }] of this.assets) { const scriptsMatch = timingArray.includes(scripts); const stylesMatch = timingArray.includes(styles); if (stylesMatch || scriptsMatch) { assets.push({ id: asset, scripts: scriptsMatch, styles: stylesMatch }); } } return assets; } markAsUsed(id, timing = types.AssetTiming.Immediate) { const current = this.assets.get(id); const scripts = typeof timing === 'object' ? timing.scripts : timing; const styles = typeof timing === 'object' ? timing.styles : timing; if (current == null) { this.assets.set(id, { scripts: scripts || types.AssetTiming.Immediate, styles: styles || types.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) }); } } } const AsyncAssetContext = /*#__PURE__*/React__default["default"].createContext(null); exports.AsyncAssetContext = AsyncAssetContext; exports.AsyncAssetManager = AsyncAssetManager; exports.EFFECT_ID = EFFECT_ID;