UNPKG

react-concurrent-router

Version:

Performant routing embracing React concurrent UI patterns

71 lines (68 loc) 2.14 kB
import _extends from '@babel/runtime/helpers/esm/extends'; import { r as routesToMap, m as matchRoutes, p as prepareMatch, l as locationsMatch } from './utils-OBWL19XQ.js'; const createRouter = ({ assistPrefetch = false, awaitComponent = false, awaitPrefetch = false, history, routes }) => { const routesMap = routesToMap(routes); const entryMatch = matchRoutes(routesMap, history.location); let currentEntry = prepareMatch(entryMatch, assistPrefetch, awaitPrefetch); if (!locationsMatch(entryMatch.location, history.location, true)) { history.replace(entryMatch.location); } let nextId = 0; const subscribers = new Map(); history.listen(({ location, action }) => { if (locationsMatch(currentEntry.location, location, true)) return; const skipRender = location.state && location.state.skipRender && action !== 'POP'; const match = matchRoutes(routesMap, location); const nextEntry = skipRender ? _extends({}, currentEntry, { location: match.location, params: match.params, skipRender }) : prepareMatch(match, assistPrefetch, awaitPrefetch); if (!locationsMatch(match.location, location, true)) { return history.replace(match.location); } currentEntry = nextEntry; subscribers.forEach(callback => callback(nextEntry)); }); return { assistPrefetch, awaitComponent, history, isActive: (path, { exact } = {}) => locationsMatch(history.location, path, exact), get: () => currentEntry, preloadCode: (path, { ignoreRedirectRules } = {}) => { const { route } = matchRoutes(routesMap, path, ignoreRedirectRules); route.component.load(); }, warmRoute: (path, { ignoreRedirectRules } = {}) => { const match = matchRoutes(routesMap, path, ignoreRedirectRules); prepareMatch(match, assistPrefetch, awaitPrefetch); }, subscribe: callback => { const id = nextId++; const dispose = () => { subscribers.delete(id); }; subscribers.set(id, callback); return dispose; } }; }; export { createRouter as c };