-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchild.ts
More file actions
87 lines (78 loc) · 1.86 KB
/
Copy pathchild.ts
File metadata and controls
87 lines (78 loc) · 1.86 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
import {
type WritableSignal,
type ReadableSignal,
type Accessor,
type NewValue,
computed,
morph,
isWritable,
unsafeMarkWritable,
nextValue,
untracked
} from 'agera'
import type { AnyObject } from './types.js'
import { $get } from './utils.js'
/**
* Create a writable child signal from a parent signal.
* @param $parent - Parent signal.
* @param key - Static or signal key to get from the parent.
* @param setValue - Function to set the value in the parent.
* @returns A writable child signal.
*/
export function child<
P extends AnyObject,
K extends keyof P,
V extends P[K]
>(
$parent: WritableSignal<P>,
key: K | Accessor<K>,
setValue: (parentValue: P, key: K, value: V) => P
): WritableSignal<V>
/**
* Create a readable child signal from a parent signal.
* @param $parent - Parent signal.
* @param key - Static or signal key to get from the parent.
* @param setValue - Function to set the value in the parent.
* @returns A readable child signal.
*/
export function child<
P extends AnyObject,
K extends keyof P,
V extends P[K]
>(
$parent: Accessor<P>,
key: K | Accessor<K>,
setValue?: (parentValue: P, key: K, value: V) => P
): ReadableSignal<V>
/* @__NO_SIDE_EFFECTS__ */
export function child<
P extends AnyObject,
K extends keyof P,
V extends P[K]
>(
$parent: WritableSignal<P> | Accessor<P>,
key: K | Accessor<K>,
setValue?: (parentValue: P, key: K, value: V) => P
) {
const getter = computed(() => {
const parent = $parent()
return parent?.[$get(key)]
})
if (!isWritable($parent)) {
return getter
}
const setter = (value: NewValue<V>) => untracked(() => {
const parent = $parent()
const k = $get(key)
$parent(setValue!(
parent,
k,
nextValue(parent[k], value)
))
})
unsafeMarkWritable(getter)
return morph(getter, {
get: getter,
set: setter
})
}