-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathEcosystem.ts
More file actions
1119 lines (951 loc) · 32.8 KB
/
Ecosystem.ts
File metadata and controls
1119 lines (951 loc) · 32.8 KB
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
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { createStore, detailedTypeof, is, isPlainObject } from '@zedux/core'
import { internalStore } from '../store/index'
import {
AnyAtomGenerics,
AnyAtomInstance,
AnyAtomTemplate,
AtomGenerics,
AtomGetters,
AtomGettersBase,
NodeOf,
ParamsOf,
AtomSelectorConfig,
AtomSelectorOrConfig,
StateOf,
Cleanup,
DehydrationFilter,
EcosystemConfig,
GraphEdgeConfig,
GraphViewRecursive,
MaybeCleanup,
NodeFilter,
ParamlessTemplate,
PartialAtomInstance,
Selectable,
SelectorGenerics,
EventMap,
None,
InjectSignalConfig,
MapEvents,
} from '../types/index'
import {
External,
compare,
makeReasonsReadable,
Eventless,
EventlessStatic,
} from '../utils/general'
import { pluginActions } from '../utils/plugin-actions'
import { IdGenerator } from './IdGenerator'
import { Scheduler } from './Scheduler'
import { Mod, ZeduxPlugin } from './ZeduxPlugin'
import { AtomTemplate } from './templates/AtomTemplate'
import { GraphNode } from './GraphNode'
import { bufferEdge, getEvaluationContext } from '../utils/evaluationContext'
import {
getSelectorKey,
getSelectorName,
SelectorInstance,
swapSelectorRefs,
} from './SelectorInstance'
import { AtomTemplateBase } from './templates/AtomTemplateBase'
import { AtomInstance } from './instances/AtomInstance'
import { Signal } from './Signal'
const defaultMods = Object.keys(pluginActions).reduce((map, mod) => {
map[mod as Mod] = 0
return map
}, {} as Record<Mod, number>)
const mapOverrides = (overrides: AnyAtomTemplate[]) =>
overrides.reduce((map, atom) => {
map[atom.key] = atom
return map
}, {} as Record<string, AnyAtomTemplate>)
export class Ecosystem<Context extends Record<string, any> | undefined = any>
implements AtomGettersBase
{
public atomDefaults?: EcosystemConfig['atomDefaults']
public complexParams?: boolean
public context: Context
public destroyOnUnmount?: boolean
public flags?: string[]
public hydration?: Record<string, any>
public id: string
public live: AtomGetters
public modBus = createStore() // use an empty store as a message bus
public onReady: EcosystemConfig<Context>['onReady']
public overrides: Record<string, AnyAtomTemplate> = {}
public ssr?: boolean
public _idGenerator = new IdGenerator()
/**
* `b`aseKeys - map selectors (or selector config objects) to a base
* selectorKey that can be used to predictably create selectorKey+params ids
* to look up the cached selector instance in `this.n`odes.
*/
public b = new WeakMap<AtomSelectorOrConfig, string>()
/**
* `n`odes - a flat map of every cached graph node (atom instance or selector)
* keyed by id.
*/
public n = new Map<string, GraphNode>()
public _mods: Record<Mod, number> = { ...defaultMods }
public _refCount = 0
public _scheduler: Scheduler = new Scheduler(this)
/**
* Only for use by internal addon packages - lets us attach anything we want
* to the ecosystem. For example, the React package uses this to store React
* Context objects
*/
public _storage: Record<string, any> = {}
private cleanup?: MaybeCleanup
private isInitialized = false
private plugins: { plugin: ZeduxPlugin; cleanup: Cleanup }[] = []
constructor(config: EcosystemConfig<Context>) {
if (DEV) {
if (config.flags && !Array.isArray(config.flags)) {
throw new TypeError(
"Zedux: The Ecosystem's `flags` property must be an array of strings"
)
}
if (config.overrides && !Array.isArray(config.overrides)) {
throw new TypeError(
"Zedux: The Ecosystem's `overrides` property must be an array of atom template objects"
)
}
}
Object.assign(this, config)
this.id ||= this._idGenerator.generateId('es')
if (config.overrides) {
this.setOverrides(config.overrides)
}
this.context = (this as any).context
this.isInitialized = true
this.cleanup = config.onReady?.(this)
const get: AtomGetters['get'] = <G extends AtomGenerics>(
atom: AtomTemplateBase<G>,
params?: G['Params']
) => this.getNode(atom, params as G['Params']).get()
const getInstance: AtomGetters['getInstance'] = <G extends AtomGenerics>(
atom: AtomTemplateBase<G>,
params?: G['Params'],
edgeConfig?: GraphEdgeConfig
) => getNode(atom, params, edgeConfig)
const getNode: AtomGetters['getNode'] = <G extends AtomGenerics>(
template: AtomTemplateBase<G> | GraphNode<G> | AtomSelectorOrConfig<G>,
params?: G['Params'],
edgeConfig?: GraphEdgeConfig
) => {
const instance = this.getNode(template, params as G['Params'])
// If getNode is called in a reactive context, track the required atom
// instances so we can add graph edges for them. When called outside a
// reactive context, getNode() is just an alias for ecosystem.getNode()
getEvaluationContext().n &&
bufferEdge(
instance,
edgeConfig?.op || 'getNode',
edgeConfig?.f ?? EventlessStatic
)
return instance
}
const select: AtomGetters['select'] = <S extends Selectable>(
selectable: S,
...args: ParamsOf<S>
): StateOf<S> => {
const node = getEvaluationContext().n
// when called outside a reactive context, select() is just an alias for
// ecosystem.select()
if (!node) return this.select(selectable, ...args)
const instance = this.getNode(selectable, args)
bufferEdge(instance, 'select', Eventless)
return instance.v
}
this.live = {
ecosystem: this,
get,
getInstance,
getNode,
select,
}
}
/**
* Merge the passed atom overrides into the ecosystem's current list of
* overrides. Force-destroys all atom instances currently in the ecosystem
* that should now be overridden.
*
* This can't be used to remove overrides. Use `.setOverrides()` or
* `.removeOverrides()` for that.
*/
public addOverrides(overrides: AnyAtomTemplate[]) {
this.overrides = {
...this.overrides,
...mapOverrides(overrides),
}
overrides.forEach(override => {
const nodes = this.findAll(override)
Object.values(nodes).forEach(node => node.destroy(true))
})
}
/**
* Batch all state updates that happen synchronously during the passed
* callback's execution. Flush all updates when the passed callback completes.
*
* Has no effect if the scheduler is already running - updates are always
* batched when the scheduler is running.
*/
public batch<T = any>(callback: () => T) {
const scheduler = this._scheduler
const pre = scheduler.pre()
const result = callback()
scheduler.post(pre)
return result
}
/**
* Retrieve an object mapping atom instance ids to their current values.
*
* Calls the `dehydrate` atom config option (on atoms that have one) to
* transform state to a serializable form. Pass `transform: false` to prevent
* this.
*
* Atoms can be excluded from dehydration by passing `exclude` and/or
* `excludeFlags` options:
*
* ```ts
* myEcosystem.dehydrate({
* exclude: [myAtom, 'my-fuzzy-search-string'],
* excludeFlags: ['no-ssr']
* })
* ```
*
* An atom passed to `exclude` will exclude all instances of that atom. A
* string passed to `exclude` will exclude all instances whose id contains the
* string (case-insensitive)
*
* You can dehydrate only a subset of all atoms by passing `include` and/or
* `includeFlags` options:
*
* ```ts
* myEcosystem.dehydrate({
* include: [myAtom, 'my-fuzzy-search-string'],
* includeFlags: ['ssr']
* })
* ```
*
* An atom passed to `include` will include all instances of that atom. A
* string passed to `include` will include all instances whose id contains the
* string (case-insensitive)
*
* Excludes takes precedence over includes.
*
* By default, dehydration will call any configured `dehydrate` atom config
* options to transform atom instance state. Pass `{ transform: false }` to
* prevent this.
*/
public dehydrate(options: DehydrationFilter = {}) {
return [...this.n.values()].reduce((obj, node) => {
const dehydration = node.d(options)
if (typeof dehydration !== 'undefined') obj[node.id] = dehydration
return obj
}, {} as Record<string, any>)
}
/**
* Destroy this ecosystem - destroy all this ecosystem's atom instances,
* remove and clean up all plugins, and remove this ecosystem from the
* internal store.
*
* Destruction will bail out by default if this ecosystem is still being
* provided via an '<EcosystemProvider>'. Pass `true` as the first parameter
* to force destruction anyway.
*/
public destroy(force?: boolean) {
if (!force && this._refCount > 0) return
this.wipe()
// Check if this ecosystem has been destroyed already
const ecosystem = internalStore.getState()[this.id]
if (!ecosystem) return
this.plugins.forEach(({ cleanup }) => cleanup())
this.plugins = []
internalStore.setState(state => {
const newState = { ...state }
delete newState[this.id]
return newState
})
}
/**
* Get an atom instance. Don't create the atom instance if it doesn't exist.
* Don't register any graph dependencies.
*
* Tries to find an exact match, but falls back to doing a fuzzy search if no
* exact match is found. Pass atom params (or an empty array if no params or
* when passing a search string) for the second argument to disable fuzzy
* search.
*/
public find<
G extends Pick<AtomGenerics, 'Node' | 'Params' | 'State' | 'Template'>
>(
template: G extends AtomGenerics
? AtomTemplateBase<G>
: AtomSelectorOrConfig<G>,
params: G['Params']
): G['Node'] | undefined
public find<
G extends Pick<AtomGenerics, 'Node' | 'State' | 'Template'> & { Params: [] }
>(
template: G extends AtomGenerics
? AtomTemplateBase<G>
: AtomSelectorOrConfig<G>
): G['Node'] | undefined
public find<
G extends Pick<AtomGenerics, 'Node' | 'Params' | 'State' | 'Template'>
>(
template: ParamlessTemplate<
G extends AtomGenerics ? AtomTemplateBase<G> : AtomSelectorOrConfig<G>
>
): G['Node'] | undefined
public find(searchStr: string, params?: []): GraphNode | undefined
public find<G extends AtomGenerics>(
template: AtomTemplateBase<G> | AtomSelectorOrConfig<G> | string,
params?: G['Params']
) {
const isString = typeof template === 'string'
const isTemplate = is(template, AtomTemplateBase)
if (!isString) {
const id = isTemplate
? (template as AnyAtomTemplate).getInstanceId(this, params)
: getSelectorKey(this, template as AtomSelectorOrConfig)
// try to find an existing instance
const instance = this.n.get(id)
if (instance) return instance
}
// if params are passed, don't fuzzy search
if (params) {
return this.n.get(
isString
? template
: `${
isTemplate
? (template as AnyAtomTemplate).key
: getSelectorKey(this, template as AtomSelectorOrConfig)
}-${this._idGenerator.hashParams(params, this.complexParams)}`
)
}
const matches = this.findAll(template)
return (
(isString && matches[template]) ||
(Object.values(matches)[0] as G['Node'] | undefined)
)
}
/**
* Get an object of all atom instances in this ecosystem keyed by their id.
*
* Pass an atom template to only find instances of that atom. Pass an atom key
* string to only return instances whose id weakly matches the passed key.
*/
public findAll(options?: NodeFilter) {
const hash: Record<string, GraphNode> = {}
// TODO: normalize filter options here, before passing to `node.f`ilter
;[...this.n.values()]
.filter(node => node.f(options))
.sort((a, b) => a.id.localeCompare(b.id))
.forEach(node => {
hash[node.id] = node
})
return hash
}
public get<A extends AnyAtomTemplate>(
template: A,
params: ParamsOf<A>
): StateOf<A>
public get<A extends AnyAtomTemplate<{ Params: [] }>>(template: A): StateOf<A>
public get<A extends AnyAtomTemplate>(
template: ParamlessTemplate<A>
): StateOf<A>
// public get<G extends AtomGenerics>(template: AnyAtomTemplate<G>): G['State']
public get<N extends GraphNode>(node: N): StateOf<N>
/**
* Returns an atom instance's value. Creates the atom instance if it doesn't
* exist yet. Doesn't register any graph dependencies.
*/
public get<A extends AnyAtomTemplate>(
atom: A | AnyAtomInstance,
params?: ParamsOf<A>
) {
if ((atom as GraphNode).izn) {
return (atom as GraphNode).v
}
const instance = this.getInstance(
atom as A,
params as ParamsOf<A>
) as AnyAtomInstance
return instance.v
}
public getInstance<A extends AnyAtomTemplate>(
template: A,
params: ParamsOf<A>,
edgeConfig?: GraphEdgeConfig // only here for AtomGetters type compatibility
): NodeOf<A>
public getInstance<A extends AnyAtomTemplate<{ Params: [] }>>(
template: A
): NodeOf<A>
public getInstance<A extends AnyAtomTemplate>(
template: ParamlessTemplate<A>
): NodeOf<A>
public getInstance<I extends AnyAtomInstance>(
instance: I,
params?: [],
edgeConfig?: GraphEdgeConfig // only here for AtomGetters type compatibility
): I
/**
* Returns an atom instance. Creates the atom instance if it doesn't exist
* yet. Doesn't register any graph dependencies.
*
* @deprecated in favor of `getNode`
*/
public getInstance<A extends AnyAtomTemplate>(
atom: A | AnyAtomInstance,
params?: ParamsOf<A>
) {
return this.getNode(atom, params)
}
// TODO: Dedupe these overloads
// atoms
public getNode<G extends AtomGenerics = AnyAtomGenerics>(
templateOrNode: AtomTemplateBase<G> | GraphNode<G>,
params: G['Params'],
edgeConfig?: GraphEdgeConfig // only here for AtomGetters type compatibility
): G['Node']
public getNode<G extends AtomGenerics = AnyAtomGenerics<{ Params: [] }>>(
templateOrNode: AtomTemplateBase<G> | GraphNode<G>
): G['Node']
public getNode<G extends AtomGenerics = AnyAtomGenerics>(
templateOrInstance: ParamlessTemplate<AtomTemplateBase<G> | GraphNode<G>>
): G['Node']
public getNode<I extends AnyAtomInstance>(instance: I, params?: []): I
// selectors
public getNode<S extends Selectable>(
selectable: S,
params: ParamsOf<S>,
edgeConfig?: GraphEdgeConfig // only here for AtomGetters type compatibility
): S extends AtomSelectorOrConfig
? SelectorInstance<{
Params: ParamsOf<S>
State: StateOf<S>
Template: S
}>
: S
public getNode<S extends Selectable<any, []>>(
selectable: S
): S extends AtomSelectorOrConfig
? SelectorInstance<{
Params: ParamsOf<S>
State: StateOf<S>
Template: S
}>
: S
public getNode<S extends Selectable>(
selectable: ParamlessTemplate<S>
): S extends AtomSelectorOrConfig
? SelectorInstance<{
Params: ParamsOf<S>
State: StateOf<S>
Template: S
}>
: S
public getNode<N extends GraphNode>(
node: N,
params?: [],
edgeConfig?: GraphEdgeConfig // only here for AtomGetters type compatibility
): N
// catch-all
public getNode<G extends AtomGenerics>(
template: AtomTemplateBase<G> | GraphNode<G> | AtomSelectorOrConfig<G>,
params?: G['Params'],
edgeConfig?: GraphEdgeConfig // only here for AtomGetters type compatibility
): G['Node']
/**
* Returns a graph node. The type is determined by the passed value.
*
* - An atom template returns an atom instance
* - A signal template returns a signal instance
* - A selector returns a selector instance
* - A custom template returns its configured instance
*
* If the template requires params, the second `params` argument is required.
* It will be used to create the node if it doesn't exist yet or to find the
* exact id of a cached node.
*
* Doesn't register any graph dependencies.
*/
public getNode<G extends AtomGenerics>(
template: AtomTemplateBase<G> | GraphNode<G> | AtomSelectorOrConfig<G>,
params?: G['Params']
) {
if ((template as GraphNode).izn) {
// if the passed atom instance is Destroyed, get(/create) the
// non-Destroyed instance
return (template as GraphNode).l === 'Destroyed' &&
(template as GraphNode).t
? this.getNode((template as GraphNode).t, (template as GraphNode).p)
: template
}
if (DEV) {
if (typeof params !== 'undefined' && !Array.isArray(params)) {
throw new TypeError(
`Zedux: Expected atom params to be an array. Received ${detailedTypeof(
params
)}`
)
}
}
if (is(template, AtomTemplateBase)) {
const id = (template as AtomTemplate).getInstanceId(this, params)
// try to find an existing instance
const instance = this.n.get(id) as AtomInstance
if (instance) {
if (this._mods.instanceReused) {
this.modBus.dispatch(
pluginActions.instanceReused({
instance: instance as AtomInstance,
template: template as AtomTemplate,
})
)
}
return instance
}
// create a new instance
const newInstance = this.resolveAtom(
template as AtomTemplate
)._createInstance(this, id, (params || []) as G['Params'])
this.n.set(id, newInstance)
newInstance.i()
return newInstance
}
if (
typeof template === 'function' ||
(template && (template as AtomSelectorConfig).selector)
) {
const selectorOrConfig = template as AtomSelectorOrConfig<G>
const id = this.hash(selectorOrConfig, params)
let instance = this.n.get(id) as SelectorInstance<G>
if (instance) return instance
// create the instance; it doesn't exist yet
instance = new SelectorInstance(this, id, selectorOrConfig, params || [])
this.n.set(id, instance)
return instance
}
if (DEV) {
throw new TypeError(
`Zedux: Expected a template or node. Received ${detailedTypeof(
template
)}`
)
}
}
/**
* Get the fully qualified id for the given selector+params combo.
*
* TODO: convert this to handle hashing for all types, replacing
* `_idGenerator.hashParams`.
*/
public hash(selectorOrConfig: AtomSelectorOrConfig, args?: any[]) {
const paramsHash = args?.length
? this._idGenerator.hashParams(args, this.complexParams)
: ''
const baseKey = getSelectorKey(this, selectorOrConfig)
return paramsHash ? `${baseKey}-${paramsHash}` : baseKey
}
/**
* Hydrate the state of atoms in this ecosystem with an object mapping atom
* instance ids to their hydrated state. This object will usually be the
* result of a call to `ecosystem.dehydrate()`.
*
* This is the key to SSR. The ecosystem's initial state can be dehydrated on
* the server, sent to the client in serialized form, deserialized, and passed
* to `ecosystem.hydrate()`. Every atom instance that evaluates after this
* hydration can use the `hydrate` injectStore config option to retrieve its
* hydrated state.
*
* Pass `retroactive: false` to prevent this call from updating the state of
* all atom instances that have already been initialized with this new
* hydration. Hydration is retroactive by default.
*
* ```ts
* ecosystem.hydrate(dehydratedState, { retroactive: false })
* ```
*/
public hydrate(
dehydratedState: Record<string, any>,
config?: { retroactive?: boolean }
) {
if (DEV) {
if (!isPlainObject(dehydratedState)) {
throw new TypeError(
'Zedux: ecosystem.hydrate() - first parameter must be a plain object'
)
}
}
this.hydration = { ...this.hydration, ...dehydratedState }
if (config?.retroactive === false) return
Object.entries(dehydratedState).forEach(([id, val]) => {
const node = this.n.get(id)
if (!node) return
node.h(val)
// we know hydration is defined at this point
delete (this.hydration as Record<string, any>)[id]
})
}
/**
* Add a ZeduxPlugin to this ecosystem. This ecosystem will subscribe to the
* plugin's modStore, whose state can be changed to reactively update the mods
* of this ecosystem.
*
* This method will also call the passed plugin's `.registerEcosystem` method,
* allowing the plugin to subscribe to this ecosystem's modBus
*
* The plugin will remain part of this ecosystem until it is unregistered or
* this ecosystem is destroyed. `.wipe()` and `.reset()` don't remove plugins.
* However, a plugin _can_ set the `ecosystemWiped` mod and react to those
* events.
*/
public registerPlugin(plugin: ZeduxPlugin) {
if (this.plugins.some(descriptor => descriptor.plugin === plugin)) return
const subscription = plugin.modStore.subscribe((newState, oldState) => {
this.recalculateMods(newState, oldState)
})
const cleanupRegistration = plugin.registerEcosystem(this)
const cleanup = () => {
subscription.unsubscribe()
if (cleanupRegistration) cleanupRegistration()
}
this.plugins.push({ cleanup, plugin })
this.recalculateMods(plugin.modStore.getState())
}
/**
* Remove all passed atoms from this ecosystem's list of atom overrides. Does
* nothing for passed atoms that aren't currently in the overrides list.
*
* Force destroys all instances of all removed atoms. This forced destruction
* will cause dependents of those instances to recreate their dependency atom
* instance without using an override.
*/
public removeOverrides(overrides: (AnyAtomTemplate | string)[]) {
this.overrides = mapOverrides(
Object.values(this.overrides).filter(template =>
overrides.every(override => {
const key = typeof override === 'string' ? override : override.key
return key !== template.key
})
)
)
overrides.forEach(override => {
const instances = this.findAll(override)
Object.values(instances).forEach(instance => instance.destroy(true))
})
}
/**
* Destroys all atom instances in this ecosystem, runs the cleanup function
* returned from `onReady` (if any), and calls `onReady` again to reinitialize
* the ecosystem.
*
* Note that this doesn't remove overrides or plugins but _does_ remove
* hydrations. This is because you can remove overrides/plugins yourself if
* needed, but there isn't currently a way to remove hydrations.
*/
public reset(newContext?: Context) {
this.wipe()
const prevContext = this.context
if (typeof newContext !== 'undefined') this.context = newContext
this.cleanup = this.onReady?.(this, prevContext)
}
/**
* Runs an AtomSelector statically - without registering any dependencies or
* updating any caches. If we've already cached this exact selector + args
* combo, returns the cached value without running the selector again
*
* TODO: Deprecate this, replace with `ecosystem.get()` and `ecosystem.run()`
*/
public select<S extends Selectable>(
selectable: S,
...args: ParamsOf<S>
): StateOf<S> {
if (is(selectable, SelectorInstance)) {
return (selectable as SelectorInstance).v
}
const atomSelector = selectable as AtomSelectorOrConfig
const hash = this.hash(atomSelector, args)
const instance = this.n.get(hash)
if (instance) return (instance as SelectorInstance).v
const resolvedSelector =
typeof atomSelector === 'function' ? atomSelector : atomSelector.selector
return resolvedSelector(
{
ecosystem: this,
get: this.get.bind(this),
getInstance: this.getInstance.bind(this),
getNode: this.getNode.bind(this),
select: this.select.bind(this),
},
...args
)
}
/**
* Completely replace this ecosystem's current list of atom overrides with a
* new list.
*
* Force destroys all instances of all previously- and newly-overridden atoms.
* This forced destruction will cause dependents of those instances to
* recreate their dependency atom instance.
*/
public setOverrides(newOverrides: AnyAtomTemplate[]) {
const oldOverrides = this.overrides
this.overrides = mapOverrides(newOverrides)
if (!this.isInitialized) return
newOverrides.forEach(atom => {
const instances = this.findAll(atom)
Object.values(instances).forEach(instance => {
instance.destroy(true)
})
})
Object.values(oldOverrides).forEach(atom => {
const instances = this.findAll(atom)
Object.values(instances).forEach(instance => {
instance.destroy(true)
})
})
}
public signal<State, MappedEvents extends EventMap = None>(
state: State,
config?: Pick<InjectSignalConfig<MappedEvents>, 'events'>
) {
const id = this._idGenerator.generateId('@signal')
const signal = new Signal<{
Events: MapEvents<MappedEvents>
State: State
}>(this, id, state, config?.events)
this.n.set(id, signal)
return signal
}
/**
* `u`pdateSelectorRef - swaps out the `t`emplate of a selector instance if
* needed. Bails out if args have changed or the selector template ref hasn't
* changed.
*
* This is used for "inline" selectors e.g. passed to `useAtomSelector`
*/
public u<G extends SelectorGenerics>(
instance: SelectorInstance<G>,
template: G['Template'],
params: G['Params'],
ref: { m?: boolean }
) {
const paramsUnchanged = (
(template as AtomSelectorConfig).argsComparator || compare
)(params, instance.p || ([] as unknown as G['Params']))
const resolvedArgs = paramsUnchanged ? instance.p : params
// if the refs/args don't match, instance has refCount: 1, there is no
// cache yet for the new ref, and the new ref has the same name, assume it's
// an inline selector and can be swapped
const isSwappingRefs =
instance.t !== template &&
paramsUnchanged &&
instance.o.size === 1 &&
!this.b.has(template) &&
getSelectorName(instance.t) === getSelectorName(template)
if (isSwappingRefs) {
// switch `m`ounted to false temporarily to prevent circular rerenders
ref.m = false
swapSelectorRefs(this, instance, template, resolvedArgs)
ref.m = true
}
return isSwappingRefs
? instance
: this.getNode(template, resolvedArgs as ParamsOf<G['Template']>)
}
/**
* Unregister a plugin registered in this ecosystem via `.registerPlugin()`
*/
public unregisterPlugin(plugin: ZeduxPlugin) {
const index = this.plugins.findIndex(
descriptor => descriptor.plugin === plugin
)
if (index === -1) return
this.plugins[index].cleanup()
this.plugins.splice(index, 1)
this.recalculateMods(undefined, plugin.modStore.getState())
}
public viewGraph(view: 'bottom-up'): GraphViewRecursive
public viewGraph(view?: 'flat'): Record<
string,
{
dependencies: { key: string; operation: string }[]
dependents: { key: string; operation: string }[]
weight: number
}
>
public viewGraph(view: 'top-down'): GraphViewRecursive
/**
* Get the current graph of this ecosystem. There are 3 views:
*
* Flat (default). Returns an object with all graph nodes on the top layer,
* each node pointing to its dependencies and dependents. No nesting.
*
* Bottom-Up. Returns an object containing all the leaf nodes of the graph
* (nodes that have no internal dependents), each node containing an object of
* its parent nodes, recursively.
*
* Top-Down. Returns an object containing all the root nodes of the graph
* (nodes that have no dependencies), each node containing an object of its
* child nodes, recursively.
*/
public viewGraph(view?: string) {
if (view !== 'top-down' && view !== 'bottom-up') {
const hash: Record<
string,
{
dependencies: { key: string; operation: string }[]
dependents: { key: string; operation: string }[]
weight: number
}
> = {}
for (const [id, node] of this.n) {
hash[id] = {
dependencies: [...node.s].map(([source, edge]) => ({
key: source.id,
operation: edge.operation,
})),
dependents: [...node.o].map(([observer, edge]) => ({
key: observer.id,
operation: edge.operation,
})),
weight: node.W,
}
}
return hash
}
const hash: GraphViewRecursive = {}
for (const [key, node] of this.n) {
const isTopLevel =
view === 'bottom-up'
? [...node.o.values()].every(dependent => dependent.flags & External)
: !node.s.size
if (isTopLevel) {
hash[key] = {}
}
}
const recurse = (node?: GraphNode) => {
if (!node) return
const map = view === 'bottom-up' ? node.s : node.o
const children: GraphViewRecursive = {}
for (const key of map.keys()) {
const child = recurse(typeof key === 'string' ? this.n.get(key) : key)
if (child) children[typeof key === 'string' ? key : key.id] = child
}
return children
}
Object.keys(hash).forEach(key => {
const node = this.n.get(key)
const children = recurse(node)
if (children) hash[key] = children
})
return hash
}
/**
* Returns the list of reasons detailing why the current atom instance or
* selector is evaluating.