This repository was archived by the owner on Sep 14, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathreact-atom-internal.tsx
205 lines (188 loc) · 7.63 KB
/
react-atom-internal.tsx
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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
/**
* `react-atom` is a _lightweight_ abstraction around React's proposed Hooks API
* that provides the ability to ___share and update state across function
* components___. It offers a very simple and straightforward approach to managing
* state, whether local component state, or shared application state.
*/
import {
addChangeHandler,
Atom,
DeepImmutable,
deref,
getValidator,
removeChangeHandler,
set,
setValidator,
swap
} from "@libre/atom";
import React, { SetStateAction, useLayoutEffect, useMemo, useState } from "react";
import * as ErrorMsgs from "./error-messages";
import { HookDependencies, PublicExports, ReactUseStateHook, UseAtomOptions } from "./internal-types";
import { isShallowEqual, memoLast } from "./utils";
// ------------------------------------------------------------------------------------------ //
// ---------------------------------- INTERNAL STATE ---------------------------------------- //
// ------------------------------------------------------------------------------------------ //
let initializationCount = 0;
let hookIdTicker = 0;
// ------------------------------------------------------------------------------------------ //
// -------------------------------------- PUBLIC API ---------------------------------------- //
// ------------------------------------------------------------------------------------------ //
/**
* **NOTE: This is a back door for users of `react` prior to hooks**
*
* Initializes `react-atom` with the provided [[HookDependencies]] and
* returns the full public API of `react-atom`.
*
* By default, react-atom imports the [[HookDependencies]] from the
* version of `react` you've installed, but `initialize` provides you
* the option to use a different implementation of hooks. For example,
* if you're using a version of `react` prior to the release of hooks,
* you might like to use a poly/ponyfill like [react-with-hooks](https://github.com/yesmeck/react-with-hooks).
*
* If you use `initialize`, you need to be careful to avoid importing
* `useAtom` and co. from `react-atom` and make sure to only use the
* instances returned by `initialize` throughout your application.
*
* @example
* ```jsx
*
* import {useLayoutEffect, useMemo, useState} from 'alt-hooks'
* import { initialize } from '@dbeining/react-atom';
*
* export const {Atom, deref, set, swap, useAtom} = initialize({
* useLayoutEffect,
* useMemo,
* useState,
* });
* ```
*/
export function initialize(hooks: HookDependencies): PublicExports {
const { useLayoutEffect, useMemo, useState } = hooks;
initializationCount = initializationCount + 1;
/* instanbul ignore next */
function useAtom<S, R>(atom: Atom<S>, options?: UseAtomOptions<S, R>): DeepImmutable<R> {
if (!(atom instanceof Atom)) {
const arg = JSON.stringify(atom, null, " ");
throw TypeError(`${ErrorMsgs.calledUseAtomWithNonAtom}\n${arg}`);
}
const { select } = options || { select: null };
const atomValue = deref(atom) as S;
let selector: NonNullable<typeof select> = select ? select : (a: S) => (a as unknown) as R;
let hook: ReactUseStateHook<S | R>;
try {
selector = useMemo(() => memoLast(selector), [select]);
[, hook] = (useState({}) as unknown) as [{}, ReactUseStateHook<S | R>];
} catch (err) {
throw new TypeError(ErrorMsgs.calledUseAtomOutsideFunctionComponent);
}
useLayoutEffect(
() => {
const idKey = hook["@@react-atom/hook_id"] ? hook["@@react-atom/hook_id"] : `hook#${++hookIdTicker}`;
hook["@@react-atom/hook_id"] = idKey;
addChangeHandler(atom, hook["@@react-atom/hook_id"], ({ previous, current }) => {
if (!isShallowEqual(selector(previous), selector(current))) {
hook({} as SetStateAction<S | R>);
}
});
return function unhook() {
removeChangeHandler(atom, hook["@@react-atom/hook_id"] as string);
};
},
[hook, select]
);
return selector(atomValue) as DeepImmutable<R>;
}
return {
Atom,
addChangeHandler,
deref,
getValidator,
removeChangeHandler,
set,
setValidator,
swap,
useAtom
};
}
// ======================================= USEATOM ==============================================
//
// tslint:disable:max-line-length
/**
* #### **Important:** _`useAtom` is a React Hook and must follow the [Rules of Hooks](https://github.com/reactjs/reactjs.org/blob/f203cd5d86c4c611a31a4f72c5a91e2db0858ce3/content/docs/hooks-rules.md)_
*
* Reads the current state of an [[Atom]] and subscribes the currently
* rendering function component to the [[Atom]]'s state such that, when the
* [[Atom]]'s state changes, the component will automatically re-render to
* read the new state. The subscription is removed when the component unmounts.
*
* @param S the type of the internal state of the [[Atom]]
* @returns the internal state of the [[Atom]]
*
* @example
* ```jsx
*
*import {Atom, useAtom} from '@dbeining/react-atom'
*
*const stateAtom = Atom.of({ count: 0 })
*
*function MyComponent() {
* const {count} = useAtom(stateAtom)
* return <p>The count is {count}</p>
*}
* ```
*/
export function useAtom<S>(atom: Atom<S>): DeepImmutable<S>;
/**
* #### **Important:** _`useAtom` is a React Hook and must follow the [Rules of Hooks](https://github.com/reactjs/reactjs.org/blob/f203cd5d86c4c611a31a4f72c5a91e2db0858ce3/content/docs/hooks-rules.md)_
*
* [[useAtom]] enhanced with `options`.
*
* Reads the current state of an [[Atom]] and subscribes the currently
* rendering function component to the [[Atom]]'s state such that, when the
* [[Atom]]'s state changes, the component will automatically re-render to
* read the new state. The subscription is removed when the component unmounts.
*
* @tip if `options.select` is an expensive computation, it should be memoized
*
* @param S the type of the internal state of the [[Atom]]
* @param R the type of the return value of [[useAtom]] computed via `options.select`
* @param options.select a pure function applied to the Atom's state to compute the value you want [[useAtom]] to return. If provided, **the component will only re-render when the value returned from `options.select` has changed**, as determined by a strict equality check for primitive/scalar values, or, for objects, a shallow strict equality comparison of own properties.
* @returns the value returned from applying `options.select` to `S`
* @example
*```jsx
*
*import { Atom, useAtom } from '@dbeining/react-atom'
*import { Orders } from 'elsewhere'
*
*const stateAtom = Atom.of({ orders: [...Orders] })
*
*function MyComponent() {
* const orderCount = useAtom(stateAtom, {
* select: (s) => s.orders.length
* })
*
* return <p>There are {orderCount} orders</p>
*}
*```
*/
export function useAtom<S, R>(atom: Atom<S>, options: UseAtomOptions<S, R>): DeepImmutable<R>;
export function useAtom<S, R>(atom: Atom<S>, options?: UseAtomOptions<S, R>) {
if (initializationCount > 1) throw Error(ErrorMsgs.multipleInstantiations);
const { select } = options || { select: null };
return select ? internalUseAtom(atom, { select }) : internalUseAtom(atom);
}
// =========================== CONNECTATOM ====================================
export function connectAtom<A, S>(atom: Atom<A>, mapStateToProps: (state: A) => S) {
return function<P>(Component: React.ComponentType<S & P>) {
const wrapper: React.FC<P> = (props: P) => {
const state = useAtom(atom);
const stateProps = mapStateToProps(state);
return <Component {...stateProps} {...props} />;
};
return wrapper;
};
}
/**
* default instance of useAtom
*/
const internalUseAtom = initialize({ useLayoutEffect, useMemo, useState }).useAtom;