UNPKG

2.44 kBJavaScriptView Raw
1import { h } from './stencilrouter-1307249c.js';
2
3const createProviderConsumer = (defaultState, consumerRender) => {
4 let listeners = new Map();
5 let currentState = defaultState;
6 const updateListener = (fields, instance) => {
7 if (Array.isArray(fields)) {
8 [...fields].forEach(fieldName => {
9 instance[fieldName] = currentState[fieldName];
10 });
11 }
12 else {
13 instance[fields] = Object.assign({}, currentState);
14 }
15 };
16 const subscribe = (instance, propList) => {
17 if (!listeners.has(instance)) {
18 listeners.set(instance, propList);
19 updateListener(propList, instance);
20 }
21 return () => {
22 if (listeners.has(instance)) {
23 listeners.delete(instance);
24 }
25 };
26 };
27 const Provider = ({ state }, children) => {
28 currentState = state;
29 listeners.forEach(updateListener);
30 return children;
31 };
32 const Consumer = (props, children) => {
33 // The casting on subscribe is to allow for crossover through the stencil compiler
34 // In the future we should allow for generics in components.
35 return consumerRender(subscribe, children[0]);
36 };
37 const injectProps = (Cstr, fieldList) => {
38 const CstrPrototype = Cstr.prototype;
39 const cstrConnectedCallback = CstrPrototype.connectedCallback;
40 const cstrDisconnectedCallback = CstrPrototype.disconnectedCallback;
41 CstrPrototype.connectedCallback = function () {
42 subscribe(this, fieldList);
43 if (cstrConnectedCallback) {
44 return cstrConnectedCallback.call(this);
45 }
46 };
47 CstrPrototype.disconnectedCallback = function () {
48 listeners.delete(this);
49 if (cstrDisconnectedCallback) {
50 cstrDisconnectedCallback.call(this);
51 }
52 };
53 };
54 return {
55 Provider,
56 Consumer,
57 injectProps
58 };
59};
60
61const ActiveRouter = createProviderConsumer({
62 historyType: 'browser',
63 location: {
64 pathname: '',
65 query: {},
66 key: ''
67 },
68 titleSuffix: '',
69 root: '/',
70 routeViewsUpdated: () => { }
71}, (subscribe, child) => (h("context-consumer", { subscribe: subscribe, renderer: child })));
72
73export { ActiveRouter as A };