UNPKG

react-concurrent-router

Version:

Performant routing embracing React concurrent UI patterns

73 lines (69 loc) 2.17 kB
'use strict'; var _extends = require('@babel/runtime/helpers/extends'); var utils = require('./utils-BDbVHWV6.js'); const createRouter = ({ assistPrefetch = false, awaitComponent = false, awaitPrefetch = false, history, routes }) => { const routesMap = utils.routesToMap(routes); const entryMatch = utils.matchRoutes(routesMap, history.location); let currentEntry = utils.prepareMatch(entryMatch, assistPrefetch, awaitPrefetch); if (!utils.locationsMatch(entryMatch.location, history.location, true)) { history.replace(entryMatch.location); } let nextId = 0; const subscribers = new Map(); history.listen(({ location, action }) => { if (utils.locationsMatch(currentEntry.location, location, true)) return; const skipRender = location.state && location.state.skipRender && action !== 'POP'; const match = utils.matchRoutes(routesMap, location); const nextEntry = skipRender ? _extends({}, currentEntry, { location: match.location, params: match.params, skipRender }) : utils.prepareMatch(match, assistPrefetch, awaitPrefetch); if (!utils.locationsMatch(match.location, location, true)) { return history.replace(match.location); } currentEntry = nextEntry; subscribers.forEach(callback => callback(nextEntry)); }); return { assistPrefetch, awaitComponent, history, isActive: (path, { exact } = {}) => utils.locationsMatch(history.location, path, exact), get: () => currentEntry, preloadCode: (path, { ignoreRedirectRules } = {}) => { const { route } = utils.matchRoutes(routesMap, path, ignoreRedirectRules); route.component.load(); }, warmRoute: (path, { ignoreRedirectRules } = {}) => { const match = utils.matchRoutes(routesMap, path, ignoreRedirectRules); utils.prepareMatch(match, assistPrefetch, awaitPrefetch); }, subscribe: callback => { const id = nextId++; const dispose = () => { subscribers.delete(id); }; subscribers.set(id, callback); return dispose; } }; }; exports.createRouter = createRouter;