-
-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathStore.ts
574 lines (482 loc) · 16.5 KB
/
Store.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
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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
// @ts-ignore
import { applyPatches, Draft, enablePatches, Patch, PatchListener, produce, produceWithPatches } from "immer";
import { useStoreState } from "./useStoreState";
import isEqual from "fast-deep-equal/es6";
import { useLocalStore } from "./useLocalStore";
import { globalClientState } from "./globalClientState";
enablePatches();
// const isEqual = require("fast-deep-equal/es6");
// import produce, { applyPatches, produceWithPatches } from "immer";
// const Immer = require("immer");
// const produce = Immer.produce;
// const produceWithPatches = Immer.produceWithPatches;
// const applyPatches = Immer.applyPatches;
export type TPullstateUpdateListener = () => void;
export interface IStoreInternalOptions<S extends object> {
ssr: boolean;
reactionCreators?: TReactionCreator<S>[];
}
/**
* @typeParam S The store's state
* @param draft The mutable store state to change during this update (uses immer, which makes use of Proxies)
* @param original A readonly version of the store's state, for referencing during this update
*/
export type TUpdateFunction<S> = (draft: Draft<S>, original: S) => void;
type TReactionFunction<S extends any, T> = (watched: T, draft: Draft<S>, original: S, previousWatched: T) => void;
/**
* @internal
*/
type TRunReactionFunction = (forceRun?: boolean) => string[];
type TRunSubscriptionFunction = () => void;
type TReactionCreator<S extends object> = (store: Store<S>) => TRunReactionFunction;
function makeSubscriptionFunction<S extends object, T>(
store: Store<S>,
watch: (state: S) => T,
listener: (watched: T, allState: S, previousWatched: T, uid?: string) => void
): TRunSubscriptionFunction {
let lastWatchState: T = watch(store.getRawState());
return () => {
const currentState = store.getRawState();
const nextWatchState = watch(currentState);
if (!isEqual(nextWatchState, lastWatchState)) {
listener(nextWatchState, currentState, lastWatchState);
lastWatchState = nextWatchState;
}
};
}
function makeReactionFunctionCreator<S extends object, T>(
watch: (state: S) => T,
reaction: TReactionFunction<S, T>
): TReactionCreator<S> {
return (store) => {
let lastWatchState: T = watch(store.getRawState());
return (forceRun: boolean = false) => {
const currentState = store.getRawState();
const nextWatchState = watch(currentState);
if (forceRun || !isEqual(nextWatchState, lastWatchState)) {
if (store._optListenerCount > 0) {
const [nextState, patches, inversePatches] = produceWithPatches(currentState as any, (s: S) =>
reaction(nextWatchState, s as Draft<S>, currentState, lastWatchState)
) as any;
store._updateStateWithoutReaction(nextState);
lastWatchState = nextWatchState;
if (patches.length > 0) {
store._patchListeners.forEach((listener) => listener(patches, inversePatches));
return Object.keys(getChangedPathsFromPatches(patches));
}
} else {
if (store._patchListeners.length > 0) {
const [nextState, patches, inversePatches] = produceWithPatches(currentState as any, (s: S) =>
reaction(nextWatchState, s as Draft<S>, currentState, lastWatchState)
) as any;
if (patches.length > 0) {
store._patchListeners.forEach((listener) => listener(patches, inversePatches));
}
store._updateStateWithoutReaction(nextState);
} else {
store._updateStateWithoutReaction(
produce(currentState as any, (s: S) =>
reaction(nextWatchState, s as Draft<S>, currentState, lastWatchState)
) as any
);
}
lastWatchState = nextWatchState;
}
}
return [];
};
};
}
interface ICreateReactionOptions {
runNow?: boolean;
runNowWithSideEffects?: boolean;
}
const optPathDivider = "~._.~";
export type TStoreActionUpdate<S extends object> = (
updater: TUpdateFunction<S> | TUpdateFunction<S>[],
patchesCallback?: (patches: Patch[], inversePatches: Patch[]) => void
) => void;
export type TStoreAction<S extends object> = (update: TStoreActionUpdate<S>) => void;
/**
* @typeParam S Your store's state interface
*/
export class Store<S extends object = object> {
private updateListeners: TPullstateUpdateListener[] = [];
private currentState: S;
private readonly initialState: S;
private readonly createInitialState: () => S;
private internalOrdId: number;
private batchState: S | undefined;
private ssr: boolean = false;
private reactions: TRunReactionFunction[] = [];
private clientSubscriptions: TRunSubscriptionFunction[] = [];
private reactionCreators: TReactionCreator<S>[] = [];
// Optimized listener / updates stuff
private optimizedUpdateListeners: {
[listenerOrd: string]: TPullstateUpdateListener;
} = {};
private optimizedUpdateListenerPaths: {
[listenerOrd: string]: string[];
} = {};
private optimizedListenerPropertyMap: {
[pathKey: string]: string[];
} = {};
/**
* @ignore
*/
public _optListenerCount = 0;
/**
* @ignore
*/
public _patchListeners: PatchListener[] = [];
constructor(initialState: S | (() => S)) {
if (initialState instanceof Function) {
const state: S = initialState();
this.currentState = state;
this.initialState = state;
this.createInitialState = initialState;
} else {
this.currentState = initialState;
this.initialState = initialState;
this.createInitialState = () => initialState;
}
this.internalOrdId = globalClientState.storeOrdinal++;
}
/**
* @internal
*/
_setInternalOptions({ ssr, reactionCreators = [] }: IStoreInternalOptions<S>) {
this.ssr = ssr;
this.reactionCreators = reactionCreators;
this.reactions = reactionCreators.map((rc) => rc(this));
}
/**
* @internal
*/
_getReactionCreators(): TReactionCreator<S>[] {
return this.reactionCreators;
}
/**
* @internal
*/
_instantiateReactions() {
this.reactions = this.reactionCreators.map((rc) => rc(this));
}
/**
* @internal
*/
_getInitialState(): S {
return this.createInitialState();
}
/**
* @internal
*/
_updateStateWithoutReaction(nextState: S) {
this.currentState = nextState;
}
/**
* @internal
*/
_updateState(nextState: S, updateKeyedPaths: string[] = []) {
this.currentState = nextState;
this.batchState = undefined;
for (const runReaction of this.reactions) {
updateKeyedPaths.push(...runReaction());
}
if (!this.ssr) {
for (const runSubscription of this.clientSubscriptions) {
runSubscription();
}
if (updateKeyedPaths.length > 0) {
// console.log(`Got update keyed paths: "${updateKeyedPaths.join(`", "`)}"`);
const updateOrds = new Set<string>();
for (const keyedPath of updateKeyedPaths) {
if (this.optimizedListenerPropertyMap[keyedPath]) {
for (const ord of this.optimizedListenerPropertyMap[keyedPath]) {
updateOrds.add(ord);
}
}
}
for (const ord of updateOrds.values()) {
// console.log(`Need to notify opt listener with ord: ${ord}`);
if (this.optimizedUpdateListeners[ord]) {
this.optimizedUpdateListeners[ord]();
}
}
}
this.updateListeners.forEach((listener) => listener());
}
}
/**
* @internal
* @param listener
*/
_addUpdateListener(listener: TPullstateUpdateListener) {
this.updateListeners.push(listener);
}
/**
* @internal
* @param listener
*/
_removeUpdateListener(listener: TPullstateUpdateListener) {
this.updateListeners = this.updateListeners.filter((f) => f !== listener);
}
/**
* @internal
* @param ordKey
*/
_removeUpdateListenerOpt(ordKey: string) {
const listenerPathsKeyed = this.optimizedUpdateListenerPaths[ordKey];
for (const keyedPath of listenerPathsKeyed) {
this.optimizedListenerPropertyMap[keyedPath] = this.optimizedListenerPropertyMap[keyedPath].filter(
(ord) => ord !== ordKey
);
}
delete this.optimizedUpdateListenerPaths[ordKey];
delete this.optimizedUpdateListeners[ordKey];
this._optListenerCount--;
}
listenToPatches(patchListener: PatchListener): () => void {
this._patchListeners.push(patchListener);
return () => {
this._patchListeners = this._patchListeners.filter((f) => f !== patchListener);
};
}
subscribe<T>(watch: (state: S) => T, listener: (watched: T, allState: S, previousWatched: T) => void): () => void {
if (!this.ssr) {
const func = makeSubscriptionFunction(this, watch, listener);
this.clientSubscriptions.push(func);
return () => {
this.clientSubscriptions = this.clientSubscriptions.filter((f) => f !== func);
};
}
return () => {
console.warn(
`Pullstate: Subscriptions made on the server side are not registered - so therefor this call to unsubscribe does nothing.`
);
};
}
createReaction<T>(
watch: (state: S) => T,
reaction: TReactionFunction<S, T>,
{ runNow = false, runNowWithSideEffects = false }: ICreateReactionOptions = {}
): () => void {
const creator = makeReactionFunctionCreator(watch, reaction);
this.reactionCreators.push(creator);
const func = creator(this);
this.reactions.push(func);
if (runNow || runNowWithSideEffects) {
func(true);
if (runNowWithSideEffects && !this.ssr) {
this._updateState(this.currentState);
}
}
return () => {
this.reactions = this.reactions.filter((f) => f !== func);
};
}
/**
* Returns the raw state object contained within this store at this moment
*
* ---
* ** WARNING **
*
* Most of the time, if you're using this in your App, there's probably a better way to do it
* ---
*/
getRawState(): S {
if (this.batchState !== undefined) {
return this.batchState;
} else {
return this.currentState;
}
}
useState(): S;
useState<SS = any>(getSubState: (state: S) => SS, deps?: ReadonlyArray<any>): SS;
useState<SS = any>(getSubState?: (state: S) => SS, deps?: ReadonlyArray<any>): SS {
return useStoreState(this, getSubState!, deps);
}
useLocalCopyInitial(deps?: ReadonlyArray<any>): Store<S> {
return useLocalStore(this.createInitialState, deps);
}
useLocalCopySnapshot(deps?: ReadonlyArray<any>): Store<S> {
return useLocalStore(this.currentState, deps);
}
/*action<A extends Array<any>>(
action: (...args: A) => TStoreAction<S>
): (...args: A) => TStoreAction<S> {
return action;
}*/
/*act(action: TStoreAction<S>): void {
action((u, p) => this.batch(u, p));
this.flushBatch(true);
}
batch(
updater: TUpdateFunction<S> | TUpdateFunction<S>[],
patchesCallback?: (patches: Patch[], inversePatches: Patch[]) => void,
): void {
if (this.batchState === undefined) {
this.batchState = this.currentState;
}
const func = typeof updater === "function";
const [nextState, patches, inversePatches] = runUpdates(this.batchState, updater, func);
if (patches.length > 0 && (this._patchListeners.length > 0 || patchesCallback)) {
if (patchesCallback) {
patchesCallback(patches, inversePatches);
}
this._patchListeners.forEach((listener) => listener(patches, inversePatches));
}
this.batchState = nextState;
}*/
flushBatch(ignoreError = false) {
if (this.batchState !== undefined) {
if (this.batchState !== this.currentState) {
this._updateState(this.batchState);
}
} else if (!ignoreError) {
console.error(`Pullstate: Trying to flush batch state which was never created or updated on`);
}
this.batchState = undefined;
}
update(
updater: TUpdateFunction<S> | TUpdateFunction<S>[],
patchesCallback?: (patches: Patch[], inversePatches: Patch[]) => void
) {
if (globalClientState.batching) {
if (this.batchState === undefined) {
this.batchState = this.currentState;
globalClientState.flushStores[this.internalOrdId] = this;
}
const func = typeof updater === "function";
const [nextState, patches, inversePatches] = runUpdates(this.batchState, updater, func);
if (patches.length > 0 && (this._patchListeners.length > 0 || patchesCallback)) {
if (patchesCallback) {
patchesCallback(patches, inversePatches);
}
this._patchListeners.forEach((listener) => listener(patches, inversePatches));
}
this.batchState = nextState;
} else {
this.batchState = undefined;
update(this, updater, patchesCallback);
}
}
/**
* Replace the store's state entirely with a new state value
*
* @param newState
*/
replace(newState: S) {
this._updateState(newState);
}
replaceFromCurrent(replacer: (state: S) => S) {
this._updateState(replacer(this.currentState));
}
applyPatches(patches: Patch[]) {
applyPatchesToStore(this, patches);
}
}
export function applyPatchesToStore<S extends object = object>(store: Store<S>, patches: Patch[]) {
const currentState: S = store.getRawState();
const nextState = applyPatches(currentState as any, patches);
if (nextState !== currentState) {
store._updateState(nextState, Object.keys(getChangedPathsFromPatches(patches)));
}
}
interface IChangedPaths {
[path: string]: 1;
}
/**
* @internal
*
* @param changePatches
* @param prev
*/
function getChangedPathsFromPatches(changePatches: Patch[], prev: IChangedPaths = {}): IChangedPaths {
// const updateKeyedPathsMap: IChangedPaths = {};
for (const patch of changePatches) {
let curKey;
for (const p of patch.path) {
if (curKey) {
curKey = `${curKey}${optPathDivider}${p}`;
} else {
curKey = p;
}
prev[curKey] = 1;
}
}
return prev;
// return Object.keys(updateKeyedPathsMap);
}
/**
* @internal
*
* @param currentState
* @param updater
* @param func
*/
function runUpdates<S extends any>(
currentState: S,
updater: TUpdateFunction<S> | TUpdateFunction<S>[],
func: boolean
): [S, Patch[], Patch[]] {
return func
? (produceWithPatches(currentState, (s: S) => (updater as TUpdateFunction<S>)(s as Draft<S>, currentState)) as any)
: ((updater as TUpdateFunction<S>[]).reduce(
([nextState, patches, inversePatches], currentValue) => {
const resp = produceWithPatches(nextState as any, (s: S) => currentValue(s as Draft<S>, nextState)) as any;
patches.push(...resp[1]);
inversePatches.push(...resp[2]);
return [resp[0], patches, inversePatches];
},
[currentState, [], []] as [S, Patch[], Patch[]]
) as [S, Patch[], Patch[]]);
}
/**
*
* @param store The store to run an update on
* @param updater The update function, or an array of update functions
* @param patchesCallback A callback to keep track of the patches made during this update.
*/
export function update<S extends object = object>(
store: Store<S>,
updater: TUpdateFunction<S> | TUpdateFunction<S>[],
patchesCallback?: (patches: Patch[], inversePatches: Patch[]) => void
) {
const currentState: S = store.getRawState();
const func = typeof updater === "function";
if (store._optListenerCount > 0) {
const [nextState, patches, inversePatches] = runUpdates(currentState, updater, func);
if (patches.length > 0) {
if (patchesCallback) {
patchesCallback(patches, inversePatches);
}
store._patchListeners.forEach((listener) => listener(patches, inversePatches));
store._updateState(nextState, Object.keys(getChangedPathsFromPatches(patches)));
}
} else {
let nextState: S;
if (store._patchListeners.length > 0 || patchesCallback) {
const [ns, patches, inversePatches] = runUpdates(currentState, updater, func);
if (patches.length > 0) {
if (patchesCallback) {
patchesCallback(patches, inversePatches);
}
store._patchListeners.forEach((listener) => listener(patches, inversePatches));
}
nextState = ns;
} else {
nextState = produce(currentState as any, (s: S) =>
func
? (updater as TUpdateFunction<S>)(s as Draft<S>, currentState)
: (updater as TUpdateFunction<S>[]).reduce((previousValue, currentUpdater) => {
return produce(previousValue as any, (s: S) => currentUpdater(s as Draft<S>, previousValue)) as any;
}, currentState)
) as any;
}
// .forEach(up => up(s, currentState))
if (nextState !== currentState) {
store._updateState(nextState);
}
}
}