1 | import $$observable from 'symbol-observable'
|
2 |
|
3 | import ActionTypes from './utils/actionTypes'
|
4 | import isPlainObject from './utils/isPlainObject'
|
5 |
|
6 | /**
|
7 | * Creates a Redux store that holds the state tree.
|
8 | * The only way to change the data in the store is to call `dispatch()` on it.
|
9 | *
|
10 | * There should only be a single store in your app. To specify how different
|
11 | * parts of the state tree respond to actions, you may combine several reducers
|
12 | * into a single reducer function by using `combineReducers`.
|
13 | *
|
14 | * @param {Function} reducer A function that returns the next state tree, given
|
15 | * the current state tree and the action to handle.
|
16 | *
|
17 | * @param {any} [preloadedState] The initial state. You may optionally specify it
|
18 | * to hydrate the state from the server in universal apps, or to restore a
|
19 | * previously serialized user session.
|
20 | * If you use `combineReducers` to produce the root reducer function, this must be
|
21 | * an object with the same shape as `combineReducers` keys.
|
22 | *
|
23 | * @param {Function} [enhancer] The store enhancer. You may optionally specify it
|
24 | * to enhance the store with third-party capabilities such as middleware,
|
25 | * time travel, persistence, etc. The only store enhancer that ships with Redux
|
26 | * is `applyMiddleware()`.
|
27 | *
|
28 | * @returns {Store} A Redux store that lets you read the state, dispatch actions
|
29 | * and subscribe to changes.
|
30 | */
|
31 | export default function createStore(reducer, preloadedState, enhancer) {
|
32 | if (
|
33 | (typeof preloadedState === 'function' && typeof enhancer === 'function') ||
|
34 | (typeof enhancer === 'function' && typeof arguments[3] === 'function')
|
35 | ) {
|
36 | throw new Error(
|
37 | 'It looks like you are passing several store enhancers to ' +
|
38 | 'createStore(). This is not supported. Instead, compose them ' +
|
39 | 'together to a single function'
|
40 | )
|
41 | }
|
42 |
|
43 | if (typeof preloadedState === 'function' && typeof enhancer === 'undefined') {
|
44 | enhancer = preloadedState
|
45 | preloadedState = undefined
|
46 | }
|
47 |
|
48 | if (typeof enhancer !== 'undefined') {
|
49 | if (typeof enhancer !== 'function') {
|
50 | throw new Error('Expected the enhancer to be a function.')
|
51 | }
|
52 |
|
53 | return enhancer(createStore)(reducer, preloadedState)
|
54 | }
|
55 |
|
56 | if (typeof reducer !== 'function') {
|
57 | throw new Error('Expected the reducer to be a function.')
|
58 | }
|
59 |
|
60 | let currentReducer = reducer
|
61 | let currentState = preloadedState
|
62 | let currentListeners = []
|
63 | let nextListeners = currentListeners
|
64 | let isDispatching = false
|
65 |
|
66 | function ensureCanMutateNextListeners() {
|
67 | if (nextListeners === currentListeners) {
|
68 | nextListeners = currentListeners.slice()
|
69 | }
|
70 | }
|
71 |
|
72 | /**
|
73 | * Reads the state tree managed by the store.
|
74 | *
|
75 | * @returns {any} The current state tree of your application.
|
76 | */
|
77 | function getState() {
|
78 | if (isDispatching) {
|
79 | throw new Error(
|
80 | 'You may not call store.getState() while the reducer is executing. ' +
|
81 | 'The reducer has already received the state as an argument. ' +
|
82 | 'Pass it down from the top reducer instead of reading it from the store.'
|
83 | )
|
84 | }
|
85 |
|
86 | return currentState
|
87 | }
|
88 |
|
89 | /**
|
90 | * Adds a change listener. It will be called any time an action is dispatched,
|
91 | * and some part of the state tree may potentially have changed. You may then
|
92 | * call `getState()` to read the current state tree inside the callback.
|
93 | *
|
94 | * You may call `dispatch()` from a change listener, with the following
|
95 | * caveats:
|
96 | *
|
97 | * 1. The subscriptions are snapshotted just before every `dispatch()` call.
|
98 | * If you subscribe or unsubscribe while the listeners are being invoked, this
|
99 | * will not have any effect on the `dispatch()` that is currently in progress.
|
100 | * However, the next `dispatch()` call, whether nested or not, will use a more
|
101 | * recent snapshot of the subscription list.
|
102 | *
|
103 | * 2. The listener should not expect to see all state changes, as the state
|
104 | * might have been updated multiple times during a nested `dispatch()` before
|
105 | * the listener is called. It is, however, guaranteed that all subscribers
|
106 | * registered before the `dispatch()` started will be called with the latest
|
107 | * state by the time it exits.
|
108 | *
|
109 | * @param {Function} listener A callback to be invoked on every dispatch.
|
110 | * @returns {Function} A function to remove this change listener.
|
111 | */
|
112 | function subscribe(listener) {
|
113 | if (typeof listener !== 'function') {
|
114 | throw new Error('Expected the listener to be a function.')
|
115 | }
|
116 |
|
117 | if (isDispatching) {
|
118 | throw new Error(
|
119 | 'You may not call store.subscribe() while the reducer is executing. ' +
|
120 | 'If you would like to be notified after the store has been updated, subscribe from a ' +
|
121 | 'component and invoke store.getState() in the callback to access the latest state. ' +
|
122 | 'See https://redux.js.org/api-reference/store#subscribe(listener) for more details.'
|
123 | )
|
124 | }
|
125 |
|
126 | let isSubscribed = true
|
127 |
|
128 | ensureCanMutateNextListeners()
|
129 | nextListeners.push(listener)
|
130 |
|
131 | return function unsubscribe() {
|
132 | if (!isSubscribed) {
|
133 | return
|
134 | }
|
135 |
|
136 | if (isDispatching) {
|
137 | throw new Error(
|
138 | 'You may not unsubscribe from a store listener while the reducer is executing. ' +
|
139 | 'See https://redux.js.org/api-reference/store#subscribe(listener) for more details.'
|
140 | )
|
141 | }
|
142 |
|
143 | isSubscribed = false
|
144 |
|
145 | ensureCanMutateNextListeners()
|
146 | const index = nextListeners.indexOf(listener)
|
147 | nextListeners.splice(index, 1)
|
148 | }
|
149 | }
|
150 |
|
151 | /**
|
152 | * Dispatches an action. It is the only way to trigger a state change.
|
153 | *
|
154 | * The `reducer` function, used to create the store, will be called with the
|
155 | * current state tree and the given `action`. Its return value will
|
156 | * be considered the **next** state of the tree, and the change listeners
|
157 | * will be notified.
|
158 | *
|
159 | * The base implementation only supports plain object actions. If you want to
|
160 | * dispatch a Promise, an Observable, a thunk, or something else, you need to
|
161 | * wrap your store creating function into the corresponding middleware. For
|
162 | * example, see the documentation for the `redux-thunk` package. Even the
|
163 | * middleware will eventually dispatch plain object actions using this method.
|
164 | *
|
165 | * @param {Object} action A plain object representing “what changed”. It is
|
166 | * a good idea to keep actions serializable so you can record and replay user
|
167 | * sessions, or use the time travelling `redux-devtools`. An action must have
|
168 | * a `type` property which may not be `undefined`. It is a good idea to use
|
169 | * string constants for action types.
|
170 | *
|
171 | * @returns {Object} For convenience, the same action object you dispatched.
|
172 | *
|
173 | * Note that, if you use a custom middleware, it may wrap `dispatch()` to
|
174 | * return something else (for example, a Promise you can await).
|
175 | */
|
176 | function dispatch(action) {
|
177 | if (!isPlainObject(action)) {
|
178 | throw new Error(
|
179 | 'Actions must be plain objects. ' +
|
180 | 'Use custom middleware for async actions.'
|
181 | )
|
182 | }
|
183 |
|
184 | if (typeof action.type === 'undefined') {
|
185 | throw new Error(
|
186 | 'Actions may not have an undefined "type" property. ' +
|
187 | 'Have you misspelled a constant?'
|
188 | )
|
189 | }
|
190 |
|
191 | if (isDispatching) {
|
192 | throw new Error('Reducers may not dispatch actions.')
|
193 | }
|
194 |
|
195 | try {
|
196 | isDispatching = true
|
197 | currentState = currentReducer(currentState, action)
|
198 | } finally {
|
199 | isDispatching = false
|
200 | }
|
201 |
|
202 | const listeners = (currentListeners = nextListeners)
|
203 | for (let i = 0; i < listeners.length; i++) {
|
204 | const listener = listeners[i]
|
205 | listener()
|
206 | }
|
207 |
|
208 | return action
|
209 | }
|
210 |
|
211 | /**
|
212 | * Replaces the reducer currently used by the store to calculate the state.
|
213 | *
|
214 | * You might need this if your app implements code splitting and you want to
|
215 | * load some of the reducers dynamically. You might also need this if you
|
216 | * implement a hot reloading mechanism for Redux.
|
217 | *
|
218 | * @param {Function} nextReducer The reducer for the store to use instead.
|
219 | * @returns {void}
|
220 | */
|
221 | function replaceReducer(nextReducer) {
|
222 | if (typeof nextReducer !== 'function') {
|
223 | throw new Error('Expected the nextReducer to be a function.')
|
224 | }
|
225 |
|
226 | currentReducer = nextReducer
|
227 | dispatch({ type: ActionTypes.REPLACE })
|
228 | }
|
229 |
|
230 | /**
|
231 | * Interoperability point for observable/reactive libraries.
|
232 | * @returns {observable} A minimal observable of state changes.
|
233 | * For more information, see the observable proposal:
|
234 | * https://github.com/tc39/proposal-observable
|
235 | */
|
236 | function observable() {
|
237 | const outerSubscribe = subscribe
|
238 | return {
|
239 | /**
|
240 | * The minimal observable subscription method.
|
241 | * @param {Object} observer Any object that can be used as an observer.
|
242 | * The observer object should have a `next` method.
|
243 | * @returns {subscription} An object with an `unsubscribe` method that can
|
244 | * be used to unsubscribe the observable from the store, and prevent further
|
245 | * emission of values from the observable.
|
246 | */
|
247 | subscribe(observer) {
|
248 | if (typeof observer !== 'object' || observer === null) {
|
249 | throw new TypeError('Expected the observer to be an object.')
|
250 | }
|
251 |
|
252 | function observeState() {
|
253 | if (observer.next) {
|
254 | observer.next(getState())
|
255 | }
|
256 | }
|
257 |
|
258 | observeState()
|
259 | const unsubscribe = outerSubscribe(observeState)
|
260 | return { unsubscribe }
|
261 | },
|
262 |
|
263 | [$$observable]() {
|
264 | return this
|
265 | }
|
266 | }
|
267 | }
|
268 |
|
269 | // When a store is created, an "INIT" action is dispatched so that every
|
270 | // reducer returns their initial state. This effectively populates
|
271 | // the initial state tree.
|
272 | dispatch({ type: ActionTypes.INIT })
|
273 |
|
274 | return {
|
275 | dispatch,
|
276 | subscribe,
|
277 | getState,
|
278 | replaceReducer,
|
279 | [$$observable]: observable
|
280 | }
|
281 | }
|