-
-
Notifications
You must be signed in to change notification settings - Fork 238
/
proxyWithComputed.ts
81 lines (79 loc) 路 2.39 KB
/
proxyWithComputed.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
import { proxy, snapshot } from '../vanilla'
import type { INTERNAL_AsRef } from '../vanilla'
// Unfortunately, this doesn't work with tsc.
// Hope to find a solution to make this work.
//
// class SnapshotWrapper<T extends object> {
// fn(p: T) {
// return snapshot(p)
// }
// }
// type Snapshot<T extends object> = ReturnType<SnapshotWrapper<T>['fn']>
//
// Using copy-paste types for now:
type AnyFunction = (...args: any[]) => any
type Snapshot<T> = T extends AnyFunction
? T
: T extends INTERNAL_AsRef
? T
: T extends Promise<infer V>
? Snapshot<V>
: {
readonly [K in keyof T]: Snapshot<T[K]>
}
/**
* proxyWithComputed
*
* This is to create a proxy with initial object and additional object,
* which specifies getters for computed values with dependency tracking.
* It also accepts optional setters for computed values.
*
* [Notes]
* This comes with a cost and overlaps with useSnapshot.
* Do not try to optimize too early. It can worsen the performance.
* Measurement and comparison will be very important.
*
* @example
* import { proxyWithComputed } from 'valtio/utils'
* const state = proxyWithComputed({
* count: 1,
* }, {
* doubled: snap => snap.count * 2, // getter only
* tripled: {
* get: snap => snap.count * 3,
* set: (state, newValue) => { state.count = newValue / 3 }
* }, // with optional setter
* })
*/
export function proxyWithComputed<T extends object, U extends object>(
initialObject: T,
computedFns: {
[K in keyof U]:
| ((snap: Snapshot<T>) => U[K])
| {
get: (snap: Snapshot<T>) => U[K]
set?: (state: T, newValue: U[K]) => void
}
}
) {
;(Object.keys(computedFns) as (keyof U)[]).forEach((key) => {
if (Object.getOwnPropertyDescriptor(initialObject, key)) {
throw new Error('object property already defined')
}
const computedFn = computedFns[key]
const { get, set } = (
typeof computedFn === 'function' ? { get: computedFn } : computedFn
) as {
get: (snap: Snapshot<T>) => U[typeof key]
set?: (state: T, newValue: U[typeof key]) => void
}
const desc: PropertyDescriptor = {}
desc.get = () => get(snapshot(proxyObject))
if (set) {
desc.set = (newValue) => set(proxyObject, newValue)
}
Object.defineProperty(initialObject, key, desc)
})
const proxyObject = proxy(initialObject) as T & U
return proxyObject
}