ProxyStoreSingleton.ts
// ProxyStoreSingleton.ts - 代理模式单例导出
import { ProxyStore, ProxyStoreSubscriber } from './ProxyStore'
// 单例实例
const store = new ProxyStore<Record<string, any>>()
// legacy wrapper map: subscribeSharedData 会包装 callback,这里保存映射用于正确取消订阅
const legacyWrapperMap = new Map<
string,
WeakMap<Function, ProxyStoreSubscriber>
>()
// ========== Vue3 风格:最小可用的响应式内核(依赖收集/触发) ==========
type Dep = Set<ReactiveEffect>
type ReactiveEffect = {
active: boolean
deps: Dep[]
run: () => any
stop: () => void
}
let activeEffect: ReactiveEffect | null = null
const effectStack: ReactiveEffect[] = []
const targetMap = new WeakMap<object, Map<PropertyKey, Dep>>()
function cleanupEffect(effect: ReactiveEffect): void {
for (const dep of effect.deps) {
dep.delete(effect)
}
effect.deps.length = 0
}
function track(target: object, key: PropertyKey): void {
if (!activeEffect || !activeEffect.active) return
let depsMap = targetMap.get(target)
if (!depsMap) {
depsMap = new Map<PropertyKey, Dep>()
targetMap.set(target, depsMap)
}
let dep = depsMap.get(key)
if (!dep) {
dep = new Set<ReactiveEffect>()
depsMap.set(key, dep)
}
if (!dep.has(activeEffect)) {
dep.add(activeEffect)
activeEffect.deps.push(dep)
}
}
function trigger(target: object, key: PropertyKey): void {
const depsMap = targetMap.get(target)
const dep = depsMap?.get(key)
if (!dep || dep.size === 0) return
// clone 避免迭代过程中集合被修改
const effects = Array.from(dep)
for (const eff of effects) {
if (eff.active) eff.run()
}
}
function effect(fn: () => any): () => any {
const reactiveEffect: ReactiveEffect = {
active: true,
deps: [],
run: () => {
if (!reactiveEffect.active) return fn()
cleanupEffect(reactiveEffect)
try {
activeEffect = reactiveEffect
effectStack.push(reactiveEffect)
return fn()
} finally {
effectStack.pop()
activeEffect = effectStack[effectStack.length - 1] ?? null
}
},
stop: () => {
if (!reactiveEffect.active) return
reactiveEffect.active = false
cleanupEffect(reactiveEffect)
}
}
reactiveEffect.run()
return () => reactiveEffect.stop()
}
/**
* Vue3 风格:reactive
*
* 说明:这是一个“够用版”的 reactive,只做浅层 key 的依赖追踪。
*/
export function reactive<T extends object>(raw: T): T {
return new Proxy(raw, {
get(target, key, receiver) {
track(target, key)
return Reflect.get(target, key, receiver)
},
set(target, key, value, receiver) {
const oldValue = (target as any)[key]
const result = Reflect.set(target, key, value, receiver)
if (oldValue !== value) {
trigger(target, key)
}
return result
},
deleteProperty(target, key) {
const hadKey = Object.prototype.hasOwnProperty.call(target, key)
const result = Reflect.deleteProperty(target, key)
if (hadKey) {
trigger(target, key)
}
return result
}
})
}
/**
* Vue3 风格:ref(简化版)
*/
export function ref<T>(value: T): { value: T } {
return reactive({ value })
}
/**
* Vue3 风格:computed(简化版)
*
* 返回一个只读 ref:通过 watchEffect 保持 value 最新。
*/
export function computed<T>(getter: () => T): { readonly value: T } {
const r = ref<T>(getter())
watchEffect(() => {
r.value = getter()
})
return r as { readonly value: T }
}
type WatchOptions = {
immediate?: boolean
}
/**
* Vue3 风格:watch(简化版)
*
* 支持:watch(() => state.xxx, (next, prev) => {})
*/
export function watch<T>(
source: () => T,
cb: (value: T, oldValue: T | undefined) => void,
options: WatchOptions = {}
): () => void {
let oldValue: T | undefined = undefined
let inited = false
const stop = effect(() => {
const newValue = source()
if (!inited) {
inited = true
if (options.immediate) {
cb(newValue, oldValue)
}
oldValue = newValue
return
}
if (newValue !== oldValue) {
const prev = oldValue
oldValue = newValue
cb(newValue, prev)
}
})
return stop
}
/**
* Vue3 风格:watchEffect(简化版)
*/
export function watchEffect(fn: () => void): () => void {
return effect(fn)
}
// ========== 类型导出 ==========
export type { ProxyStoreSubscriber }
export type SharedDataSubscriber<T = any> = (data: T) => void
// ========== 最推荐的调用方式(Vue3 reactive state) ==========
/**
* 单例响应式状态(Vue3 风格)
*
* 用法:
* watch(() => state.count, (v) => console.log(v));
* state.count++;
*/
export const state = reactive(store.proxy)
export const subscribe = (
key: string,
subscriber: ProxyStoreSubscriber
): (() => void) => {
return store.subscribe(key, subscriber)
}
export const unsubscribe = (
key: string,
subscriber: ProxyStoreSubscriber
): void => {
store.unsubscribe(key, subscriber)
}
export const getSnapshot = (): Record<string, any> => {
return store.getSnapshot()
}
export const batchUpdate = (updates: Record<string, any>): void => {
store.batch(updates)
}
export const resetStore = (newState: Record<string, any> = {}): void => {
store.reset(newState)
}
// ========== 共享数据(代理模式) ==========
/**
* 发布共享数据(直接赋值即可)
*/
export const publishSharedData = <T>(key: string, data: T): void => {
;(state as any)[key] = data
}
/**
* 获取共享数据
*/
export const getSharedData = <T>(key: string): T | undefined => {
return (state as any)[key] as T | undefined
}
/**
* 清除共享数据
*/
export const clearSharedData = (key: string): void => {
delete (state as any)[key]
}
/**
* 订阅共享数据变化
*/
export const subscribeSharedData = <T>(
key: string,
callback: SharedDataSubscriber<T>
): void => {
if (!legacyWrapperMap.has(key)) {
legacyWrapperMap.set(key, new WeakMap())
}
const perKeyMap = legacyWrapperMap.get(key)!
const wrapper: ProxyStoreSubscriber = (value) => callback(value)
perKeyMap.set(callback as unknown as Function, wrapper)
subscribe(key, wrapper)
}
/**
* 取消订阅共享数据变化
*/
export const unsubscribeSharedData = <T>(
key: string,
callback: SharedDataSubscriber<T>
): void => {
const perKeyMap = legacyWrapperMap.get(key)
const wrapper = perKeyMap?.get(callback as unknown as Function)
if (wrapper) {
unsubscribe(key, wrapper)
perKeyMap?.delete(callback as unknown as Function)
return
}
// fallback(尽力而为)
store.unsubscribe(key, callback as unknown as ProxyStoreSubscriber)
}
// ========== 代理模式扩展 API ==========
/**
* 获取代理对象(可直接操作)
*/
export const getProxy = (): Record<string, any> => {
return state
}
/**
* 订阅所有变化
*/
export const subscribeAll = (callback: ProxyStoreSubscriber): (() => void) => {
return store.subscribeAll(callback)
}
// 导出实例(供高级用法)
export { ProxyStore, store }
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
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
