-
-
Notifications
You must be signed in to change notification settings - Fork 221
/
fork.ts
64 lines (59 loc) · 1.86 KB
/
fork.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
import {is} from '../is'
import {assert} from '../throw'
import type {Domain, ValuesMap, HandlersMap, Scope, Store} from '../unit.h'
import {normalizeValues} from './util'
import {createScope} from './createScope'
import {forEach} from '../collection'
import {getMeta} from '../getter'
type ForkConfig = {
values?: ValuesMap
handlers?: HandlersMap
scope?: Scope
}
export function fork(
domainOrConfig?: Domain | ForkConfig,
optionalConfig?: ForkConfig,
) {
let config: ForkConfig | void = domainOrConfig as any
let domain: Domain
if (is.domain(domainOrConfig)) {
domain = domainOrConfig
config = optionalConfig
}
const scope = createScope(domain!)
if (config) {
const oldScope = config.scope
if (oldScope) {
const activeEffects = oldScope.activeEffects
oldScope.activeEffects = []
scope.activeEffects = activeEffects
forEach(activeEffects, scopeRef => (scopeRef.ref = scope))
}
if (config.values) {
const {sidMap, unitMap, hasSidDoubles} = normalizeValues(config.values, unit =>
assert(is.store(unit), 'Values map can contain only stores as keys'),
)
Object.assign(scope.values.sidMap, sidMap)
forEach(unitMap, (value, unit) => {
scope.values.idMap[(unit as Store<any>).stateRef.id] = value
const serialize = getMeta(unit, 'serialize')
const sid = getMeta(unit, 'sid')
if (serialize === 'ignore') {
scope.sidSerializeSettings.set(sid, {ignore: true})
}
})
scope.fromSerialize =
!Array.isArray(config.values) && !(config.values instanceof Map)
scope.hasSidDoubles = hasSidDoubles
}
if (config.handlers) {
scope.handlers = normalizeValues(config.handlers, unit =>
assert(
is.effect(unit),
`Handlers map can contain only effects as keys`,
),
)
}
}
return scope
}