UNPKG

@stencil/router

Version:
74 lines (70 loc) 2.44 kB
import { h } from './stencilrouter-1307249c.js'; const createProviderConsumer = (defaultState, consumerRender) => { let listeners = new Map(); let currentState = defaultState; const updateListener = (fields, instance) => { if (Array.isArray(fields)) { [...fields].forEach(fieldName => { instance[fieldName] = currentState[fieldName]; }); } else { instance[fields] = Object.assign({}, currentState); } }; const subscribe = (instance, propList) => { if (!listeners.has(instance)) { listeners.set(instance, propList); updateListener(propList, instance); } return () => { if (listeners.has(instance)) { listeners.delete(instance); } }; }; const Provider = ({ state }, children) => { currentState = state; listeners.forEach(updateListener); return children; }; const Consumer = (props, children) => { // The casting on subscribe is to allow for crossover through the stencil compiler // In the future we should allow for generics in components. return consumerRender(subscribe, children[0]); }; const injectProps = (Cstr, fieldList) => { const CstrPrototype = Cstr.prototype; const cstrConnectedCallback = CstrPrototype.connectedCallback; const cstrDisconnectedCallback = CstrPrototype.disconnectedCallback; CstrPrototype.connectedCallback = function () { subscribe(this, fieldList); if (cstrConnectedCallback) { return cstrConnectedCallback.call(this); } }; CstrPrototype.disconnectedCallback = function () { listeners.delete(this); if (cstrDisconnectedCallback) { cstrDisconnectedCallback.call(this); } }; }; return { Provider, Consumer, injectProps }; }; const ActiveRouter = createProviderConsumer({ historyType: 'browser', location: { pathname: '', query: {}, key: '' }, titleSuffix: '', root: '/', routeViewsUpdated: () => { } }, (subscribe, child) => (h("context-consumer", { subscribe: subscribe, renderer: child }))); export { ActiveRouter as A };