UNPKG

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