1 | import type { Draft } from 'immer'
|
2 | import createNextState, { isDraft, isDraftable } from 'immer'
|
3 | import type { AnyAction, Action, Reducer } from 'redux'
|
4 | import type { ActionReducerMapBuilder } from './mapBuilders'
|
5 | import { executeReducerBuilderCallback } from './mapBuilders'
|
6 | import type { NoInfer } from './tsHelpers'
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 | export type Actions<T extends keyof any = string> = Record<T, Action>
|
17 |
|
18 |
|
19 |
|
20 |
|
21 | export interface ActionMatcher<A extends AnyAction> {
|
22 | (action: AnyAction): action is A
|
23 | }
|
24 |
|
25 | export type ActionMatcherDescription<S, A extends AnyAction> = {
|
26 | matcher: ActionMatcher<A>
|
27 | reducer: CaseReducer<S, NoInfer<A>>
|
28 | }
|
29 |
|
30 | export type ReadonlyActionMatcherDescriptionCollection<S> = ReadonlyArray<
|
31 | ActionMatcherDescription<S, any>
|
32 | >
|
33 |
|
34 | export type ActionMatcherDescriptionCollection<S> = Array<
|
35 | ActionMatcherDescription<S, any>
|
36 | >
|
37 |
|
38 |
|
39 |
|
40 |
|
41 |
|
42 |
|
43 |
|
44 |
|
45 |
|
46 |
|
47 |
|
48 |
|
49 |
|
50 |
|
51 |
|
52 |
|
53 |
|
54 | export type CaseReducer<S = any, A extends Action = AnyAction> = (
|
55 | state: Draft<S>,
|
56 | action: A
|
57 | ) => S | void | Draft<S>
|
58 |
|
59 |
|
60 |
|
61 |
|
62 |
|
63 |
|
64 |
|
65 |
|
66 |
|
67 |
|
68 | export type CaseReducers<S, AS extends Actions> = {
|
69 | [T in keyof AS]: AS[T] extends Action ? CaseReducer<S, AS[T]> : void
|
70 | }
|
71 |
|
72 | export type NotFunction<T> = T extends Function ? never : T
|
73 |
|
74 | function isStateFunction<S>(x: unknown): x is () => S {
|
75 | return typeof x === 'function'
|
76 | }
|
77 |
|
78 | export type ReducerWithInitialState<S extends NotFunction<any>> = Reducer<S> & {
|
79 | getInitialState: () => S
|
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 | export function createReducer<S extends NotFunction<any>>(
|
147 | initialState: S | (() => S),
|
148 | builderCallback: (builder: ActionReducerMapBuilder<S>) => void
|
149 | ): ReducerWithInitialState<S>
|
150 |
|
151 | /**
|
152 | * A utility function that allows defining a reducer as a mapping from action
|
153 | * type to *case reducer* functions that handle these action types. The
|
154 | * reducer's initial state is passed as the first argument.
|
155 | *
|
156 | * The body of every case reducer is implicitly wrapped with a call to
|
157 | * `produce()` from the [immer](https:
|
158 | * This means that rather than returning a new state object, you can also
|
159 | * mutate the passed-in state object directly; these mutations will then be
|
160 | * automatically and efficiently translated into copies, giving you both
|
161 | * convenience and immutability.
|
162 | *
|
163 | * @overloadSummary
|
164 | * This overload accepts an object where the keys are string action types, and the values
|
165 | * are case reducer functions to handle those action types.
|
166 | *
|
167 | * @param initialState - `State | (() => State)`: The initial state that should be used when the reducer is called the first time. This may also be a "lazy initializer" function, which should return an initial state value when called. This will be used whenever the reducer is called with `undefined` as its state value, and is primarily useful for cases like reading initial state from `localStorage`.
|
168 | * @param actionsMap - An object mapping from action types to _case reducers_, each of which handles one specific action type.
|
169 | * @param actionMatchers - An array of matcher definitions in the form `{matcher, reducer}`.
|
170 | * All matching reducers will be executed in order, independently if a case reducer matched or not.
|
171 | * @param defaultCaseReducer - A "default case" reducer that is executed if no case reducer and no matcher
|
172 | * reducer was executed for this action.
|
173 | *
|
174 | * @example
|
175 | ```js
|
176 | const counterReducer = createReducer(0, {
|
177 | increment: (state, action) => state + action.payload,
|
178 | decrement: (state, action) => state - action.payload
|
179 | })
|
180 |
|
181 |
|
182 |
|
183 | const initialState = () => 0
|
184 | const counterReducer = createReducer(initialState, {
|
185 | increment: (state, action) => state + action.payload,
|
186 | decrement: (state, action) => state - action.payload
|
187 | })
|
188 | ```
|
189 |
|
190 | * Action creators that were generated using [`createAction`](./createAction) may be used directly as the keys here, using computed property syntax:
|
191 |
|
192 | ```js
|
193 | const increment = createAction('increment')
|
194 | const decrement = createAction('decrement')
|
195 |
|
196 | const counterReducer = createReducer(0, {
|
197 | [increment]: (state, action) => state + action.payload,
|
198 | [decrement.type]: (state, action) => state - action.payload
|
199 | })
|
200 | ```
|
201 | * @public
|
202 | */
|
203 | export function createReducer<
|
204 | S extends NotFunction<any>,
|
205 | CR extends CaseReducers<S, any> = CaseReducers<S, any>
|
206 | >(
|
207 | initialState: S | (() => S),
|
208 | actionsMap: CR,
|
209 | actionMatchers?: ActionMatcherDescriptionCollection<S>,
|
210 | defaultCaseReducer?: CaseReducer<S>
|
211 | ): ReducerWithInitialState<S>
|
212 |
|
213 | export function createReducer<S extends NotFunction<any>>(
|
214 | initialState: S | (() => S),
|
215 | mapOrBuilderCallback:
|
216 | | CaseReducers<S, any>
|
217 | | ((builder: ActionReducerMapBuilder<S>) => void),
|
218 | actionMatchers: ReadonlyActionMatcherDescriptionCollection<S> = [],
|
219 | defaultCaseReducer?: CaseReducer<S>
|
220 | ): ReducerWithInitialState<S> {
|
221 | let [actionsMap, finalActionMatchers, finalDefaultCaseReducer] =
|
222 | typeof mapOrBuilderCallback === 'function'
|
223 | ? executeReducerBuilderCallback(mapOrBuilderCallback)
|
224 | : [mapOrBuilderCallback, actionMatchers, defaultCaseReducer]
|
225 |
|
226 |
|
227 | let getInitialState: () => S
|
228 | if (isStateFunction(initialState)) {
|
229 | getInitialState = () => createNextState(initialState(), () => {})
|
230 | } else {
|
231 | const frozenInitialState = createNextState(initialState, () => {})
|
232 | getInitialState = () => frozenInitialState
|
233 | }
|
234 |
|
235 | function reducer(state = getInitialState(), action: any): S {
|
236 | let caseReducers = [
|
237 | actionsMap[action.type],
|
238 | ...finalActionMatchers
|
239 | .filter(({ matcher }) => matcher(action))
|
240 | .map(({ reducer }) => reducer),
|
241 | ]
|
242 | if (caseReducers.filter((cr) => !!cr).length === 0) {
|
243 | caseReducers = [finalDefaultCaseReducer]
|
244 | }
|
245 |
|
246 | return caseReducers.reduce((previousState, caseReducer): S => {
|
247 | if (caseReducer) {
|
248 | if (isDraft(previousState)) {
|
249 | // If it's already a draft, we must already be inside a `createNextState` call,
|
250 |
|
251 |
|
252 | const draft = previousState as Draft<S>
|
253 | const result = caseReducer(draft, action)
|
254 |
|
255 | if (typeof result === 'undefined') {
|
256 | return previousState
|
257 | }
|
258 |
|
259 | return result as S
|
260 | } else if (!isDraftable(previousState)) {
|
261 |
|
262 |
|
263 | const result = caseReducer(previousState as any, action)
|
264 |
|
265 | if (typeof result === 'undefined') {
|
266 | if (previousState === null) {
|
267 | return previousState
|
268 | }
|
269 | throw Error(
|
270 | 'A case reducer on a non-draftable value must not return undefined'
|
271 | )
|
272 | }
|
273 |
|
274 | return result as S
|
275 | } else {
|
276 |
|
277 |
|
278 |
|
279 | return createNextState(previousState, (draft: Draft<S>) => {
|
280 | return caseReducer(draft, action)
|
281 | })
|
282 | }
|
283 | }
|
284 |
|
285 | return previousState
|
286 | }, state)
|
287 | }
|
288 |
|
289 | reducer.getInitialState = getInitialState
|
290 |
|
291 | return reducer as ReducerWithInitialState<S>
|
292 | }
|