-
-
Notifications
You must be signed in to change notification settings - Fork 289
Expand file tree
/
Copy pathproxyMap.ts
More file actions
227 lines (218 loc) 路 6.25 KB
/
Copy pathproxyMap.ts
File metadata and controls
227 lines (218 loc) 路 6.25 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
import { proxy, unstable_getInternalStates } from '../../vanilla.ts'
const { proxyStateMap, snapCache } = unstable_getInternalStates()
const isProxy = (x: any) => proxyStateMap.has(x)
type InternalProxyObject<K, V> = Map<K, V> & {
data: Array<V>
index: number
epoch: number
toJSON: () => Map<K, V>
}
/**
* Determines if an object is a proxy Map created with proxyMap
*/
export const isProxyMap = (obj: object): boolean => {
return (
Symbol.toStringTag in obj &&
obj[Symbol.toStringTag] === 'Map' &&
proxyStateMap.has(obj)
)
}
/**
* Creates a reactive Map that integrates with Valtio's proxy system
*
* This utility creates a Map-like object that works with Valtio's reactivity system,
* allowing you to track changes to the Map in the same way as regular proxy objects.
* The API is the same as the standard JavaScript Map.
*
* @example
* import { proxyMap } from 'valtio/utils'
* const state = proxyMap([["key", "value"]])
*
* This can be used inside a proxy as well
*
* const state = proxy({
* count: 1,
* map: proxyMap()
* })
*
* When using an object as a key, you can wrap it with `ref` so it's not proxied
* this is useful if you want to preserve the key equality
*
* import { ref } from 'valtio'
*
* const key = ref({})
* state.set(key, "value")
* state.get(key) //value
*
* const key = {}
* state.set(key, "value")
* state.get(key) //undefined
*/
export function proxyMap<K, V>(entries?: Iterable<[K, V]> | undefined | null) {
const initialData: Array<V> = []
let initialIndex = 0
const indexMap = new Map<K, number>()
const snapMapCache = new WeakMap<object, Map<K, number>>()
const registerSnapMap = () => {
const cache = snapCache.get(vObject)
const latestSnap = cache?.[1]
if (latestSnap && !snapMapCache.has(latestSnap)) {
const clonedMap = new Map(indexMap)
snapMapCache.set(latestSnap, clonedMap)
}
}
const getMapForThis = (x: any) => snapMapCache.get(x) || indexMap
if (entries) {
if (typeof entries[Symbol.iterator] !== 'function') {
throw new TypeError(
'proxyMap:\n\tinitial state must be iterable\n\t\ttip: structure should be [[key, value]]',
)
}
for (const [key, value] of entries) {
indexMap.set(key, initialIndex)
initialData[initialIndex++] = value
}
}
const vObject: InternalProxyObject<K, V> = {
data: initialData,
index: initialIndex,
epoch: 0,
get size() {
if (!isProxy(this)) {
registerSnapMap()
}
const map = getMapForThis(this)
return map.size
},
get(key: K) {
const map = getMapForThis(this)
const index = map.get(key)
if (index === undefined) {
this.epoch // touch property for tracking
return undefined
}
return this.data[index]
},
has(key: K) {
const map = getMapForThis(this)
this.epoch // touch property for tracking
return map.has(key)
},
set(key: K, value: V) {
if (!isProxy(this)) {
throw new Error('Cannot perform mutations on a snapshot')
}
const index = indexMap.get(key)
if (index === undefined) {
indexMap.set(key, this.index)
this.data[this.index++] = value
} else {
this.data[index] = value
}
this.epoch++
return this
},
delete(key: K) {
if (!isProxy(this)) {
throw new Error('Cannot perform mutations on a snapshot')
}
const index = indexMap.get(key)
if (index === undefined) {
return false
}
delete this.data[index]
indexMap.delete(key)
this.epoch++
return true
},
clear() {
if (!isProxy(this)) {
throw new Error('Cannot perform mutations on a snapshot')
}
this.data.length = 0 // empty array
this.index = 0
this.epoch++
indexMap.clear()
},
forEach(cb: (value: V, key: K, map: Map<K, V>) => void) {
this.epoch // touch property for tracking
const map = getMapForThis(this)
map.forEach((index, key) => {
cb(this.data[index]!, key, this)
})
},
*entries(): MapIterator<[K, V]> {
this.epoch // touch property for tracking
const map = getMapForThis(this)
for (const [key, index] of map) {
yield [key, this.data[index]!]
}
},
*keys(): MapIterator<K> {
this.epoch // touch property for tracking
const map = getMapForThis(this)
for (const key of map.keys()) {
yield key
}
},
*values(): MapIterator<V> {
this.epoch // touch property for tracking
const map = getMapForThis(this)
for (const index of map.values()) {
yield this.data[index]!
}
},
[Symbol.iterator]() {
return this.entries()
},
get [Symbol.toStringTag]() {
return 'Map'
},
toJSON(): Map<K, V> {
return new Map(this.entries())
},
// [ONLY-TS-5.9.3] [ONLY-TS-5.8.3] [ONLY-TS-5.7.3] [ONLY-TS-5.6.3] @ts-ignore ignore
getOrInsert(key: K, defaultValue: V): V {
if (!isProxy(this)) {
throw new Error('Cannot perform mutations on a snapshot')
}
const index = indexMap.get(key)
if (index !== undefined) {
return this.data[index]!
}
indexMap.set(key, this.index)
this.data[this.index] = defaultValue
this.index++
this.epoch++
return defaultValue
},
// [ONLY-TS-5.9.3] [ONLY-TS-5.8.3] [ONLY-TS-5.7.3] [ONLY-TS-5.6.3] @ts-ignore ignore
getOrInsertComputed(key: K, callbackFn: (key: K) => V): V {
if (!isProxy(this)) {
throw new Error('Cannot perform mutations on a snapshot')
}
const index = indexMap.get(key)
if (index !== undefined) {
return this.data[index]!
}
const value = callbackFn(key)
indexMap.set(key, this.index)
this.data[this.index] = value
this.index++
this.epoch++
return value
},
}
const proxiedObject = proxy(vObject)
Object.defineProperties(proxiedObject, {
size: { enumerable: false },
index: { enumerable: false },
epoch: { enumerable: false },
data: { enumerable: false },
toJSON: { enumerable: false },
})
Object.seal(proxiedObject)
return proxiedObject as unknown as Map<K, V> & {
$$valtioSnapshot: Omit<Map<K, V>, 'set' | 'delete' | 'clear'>
}
}