-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReactExt.ts
179 lines (159 loc) · 4.73 KB
/
ReactExt.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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
import * as React from "react";
import * as ReactDOM from "react-dom";
type Finalize = () => void;
/**
* Works like `useCallback` but returns a callback which debounces
* invocation by a specified amount of time.
*
* ```
* let [cb, flush, cancel] = useDebouncedCallback(ms, f, [...])
* ```
*
* The `flush` allows to flush execution of the recently scheduled
* invocation. This is useful in case you need force debounced execution.
*
* The `cancel()` cancels the most recently scheduled invocation.
*/
export function useDebouncedCallback<Args extends unknown[]>(
ms: number,
f: (...args: Args) => void,
deps: unknown[] = []
): readonly [
callback: (...args: Args) => void | Promise<void>,
flush: Finalize,
cancel: Finalize
] {
// Store current ms value in ref.
//
// Since we only care about this value changed when we schedule the next
// invocation we don't use state and only sync a commited `ms` value in
// useEffect.
let msref = React.useRef<number>(ms);
React.useEffect(() => {
msref.current = ms;
}, [ms]);
// Keep track of the currently scheduled invocation.
type State = {
timer: NodeJS.Timeout;
invocation: { f: Function; args: unknown[] };
};
let state = React.useRef<State | null>(null);
// Finalize currently scheduled invocation.
let finalize = React.useCallback((invoke: boolean = true) => {
if (state.current != null) {
let {
timer,
invocation: { f, args },
} = state.current;
clearTimeout(timer);
if (invoke) {
ReactDOM.unstable_batchedUpdates(() => {
f(...args);
});
}
state.current = null;
}
}, []);
let flush = React.useCallback(() => finalize(true), [finalize]);
let cancel = React.useCallback(() => finalize(false), [finalize]);
// If deps change or component is being unmounted we flush currently
// scheduled invocation, that makes sure the most recent invocation is not
// lost.
React.useEffect(() => flush, deps); // eslint-disable-line react-hooks/exhaustive-deps
let cbd = React.useCallback((...args: Array<unknown>) => {
// Cancel currently scheduled invocation if any.
if (state.current != null) {
clearTimeout(state.current.timer);
state.current = null;
}
// Schedule new invocation.
state.current = {
invocation: { f, args },
timer: setTimeout(flush, msref.current),
};
}, deps); // eslint-disable-line react-hooks/exhaustive-deps
return [cbd, flush, cancel] as const;
}
export type Codec<V> = {
encode: (v: V) => string;
decode: (s: string) => V;
};
export let NO_VALUE = {};
export let jsonCodec: Codec<any> = {
encode(v) {
return JSON.stringify({ v: v });
},
decode(s) {
let v;
try {
v = JSON.parse(s);
} catch (_err) {
return NO_VALUE;
}
if (v == null || !("v" in v)) return NO_VALUE;
return v.v;
},
};
/**
* Works like React.useState but persists state in a localStorage.
*
* Note that the state value stored in a state should be JSON-serializable.
*/
export function usePersistentState<V>(
id: string,
init: () => V,
codec: Codec<V> = jsonCodec
) {
let [v, setv] = React.useState<V>(() => {
let s: string | null = localStorage.getItem(id);
if (s == null) return init();
let v = codec.decode(s);
return v === NO_VALUE ? init() : v;
});
React.useEffect(() => {
let onChange = (ev: StorageEvent) => {
if (ev.key !== id) return;
if (ev.newValue == null) return setv(init());
let v = codec.decode(ev.newValue);
setv(v === NO_VALUE ? init() : v);
};
window.addEventListener("storage", onChange);
return () => window.removeEventListener("storage", onChange);
}, [id, setv]); // eslint-disable-line
// Persist committed state to localStorage
React.useEffect(() => {
localStorage.setItem(id, codec.encode(v));
}, [v, id, codec]);
return [v, setv] as const;
}
export function useMemoOnce<T>(f: () => T): T {
return React.useMemo(f, []); // eslint-disable-line
}
export function stopPropagation(
ev:
| React.MouseEvent
| React.KeyboardEvent
| React.FormEvent
| React.TouchEvent
) {
ev.stopPropagation();
}
export function useMatchMedia(
expr: string,
f: (matches: boolean) => any,
deps: unknown[]
): boolean {
let m = React.useMemo(() => window.matchMedia(expr), deps); // eslint-disable-line
React.useLayoutEffect(() => {
let listener = (ev: MediaQueryListEvent) => f(ev.matches);
m.addEventListener("change", listener);
return () => m.removeEventListener("change", listener);
}, deps); // eslint-disable-line
return m.matches;
}
export function usePrefersDarkMode(
f: (isDarkMode: boolean) => any,
deps: unknown[]
) {
return useMatchMedia("(prefers-color-scheme: dark)", f, deps);
}