-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdom-context-hooks.ts
145 lines (130 loc) · 3.62 KB
/
dom-context-hooks.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
import {
createContext as rawCreate,
ContextProvider,
ContextListener,
ListenerOptions,
} from "dom-context";
import {
useEffect,
useMemo,
useReducer,
useRef,
useState,
} from "@saasquatch/universal-hooks";
import debugFactory from "debug";
const debug = debugFactory("useDomContext");
/**
* Create a new context.
*
* Unlike React context, this object is just a helper and NOT a unique key. The `name` used here MUST be unique.
*
* @param name a unique global event name used for the `dom-context` listeners
* @param initial the initial value used by providers
*/
export function createContext<T>(name: string, initial?: T) {
const raw = rawCreate(name, initial);
const useContext = (host: HTMLElement, options?: PollingOpts) =>
useDomContext<T>(host, name, options);
const useContextState = (host: HTMLElement, initialState?: T) =>
useDomContextState<T>(host, name, initialState || initial);
const stencil = {
...raw,
useContext,
useContextState,
};
return stencil;
}
type PollingOpts<T = unknown> = Omit<
ListenerOptions<T>,
"contextName" | "element" | "onChange"
>;
/**
* Uses the parent context, if it exists. Similar to React's `useContext`
*
* Since this uses `dom-context` as the library, functional components can't provide context
*
* @param contextName
*/
export function useDomContext<T = unknown>(
host: HTMLElement,
contextName: string,
options: PollingOpts = {}
): T | undefined {
const initialContextValue = useRef(undefined);
const [state, setState] = useState(undefined);
const { listener } = useMemo(() => {
const onChange = (next: T) => {
if (initialContextValue) initialContextValue.current = next;
setState(next);
};
let l;
try {
l = new ContextListener({
contextName,
element: host,
onChange,
...options,
});
l.start();
} catch (error) {
debug("Listener failed to start", error);
}
debug("Listener initialized", l);
return {
listener: l,
};
}, [contextName, initialContextValue]);
useEffect(() => {
debug("Listener starting (or restarting)", listener);
listener.start();
return () => {
debug("Listener stopping (or restopping)", listener);
listener.stop();
};
}, [listener, host.isConnected]);
return state || initialContextValue?.current;
}
type NewState<T> = T | ((previousState?: T) => T);
type StateUpdater<T> = (value: NewState<T>) => void;
/**
* Similar to `useState` except the state is shared with children `dom-context` listeners
*/
export function useDomContextState<T>(
host: HTMLElement,
contextName: string,
initialState?: T
): readonly [T, StateUpdater<T>, ContextProvider<T>] {
const provider = useMemo(() => {
const p = new ContextProvider({
contextName: contextName,
element: host,
initialState: initialState,
});
p.start();
debug("Provider initialized", p);
return p;
}, [contextName, host]);
useEffect(() => {
debug("Provider starting (or restarting)", provider);
provider.start();
return () => {
debug("Provider stopping (or re-stopping)", provider);
provider.stop();
};
}, [provider, host.isConnected]);
const [value, dispatch] = useReducer<T, NewState<T>>(
(_, next: NewState<T>) => {
let newValue: T;
debug("New context value", next);
if (typeof next === "function") {
newValue = (next as (n: T) => T)(provider.context);
} else {
newValue = next;
}
provider.context = newValue;
return provider.context;
},
provider.context
);
return [value, dispatch, provider];
}