保存一下
This commit is contained in:
87
src/core/common/hooks/useObservableVue.ts
Normal file
87
src/core/common/hooks/useObservableVue.ts
Normal file
@@ -0,0 +1,87 @@
|
||||
import { reactive, onBeforeUnmount, type Reactive } from 'vue'
|
||||
import type { IObservable } from '@/core/state/IObservable.ts'
|
||||
|
||||
/**
|
||||
* Vue Hook: useObservable
|
||||
* 支持深层解构赋值,直接修改触发 ObservableImpl 通知 + Vue 响应式更新
|
||||
* @example
|
||||
* interface AppState {
|
||||
* count: number
|
||||
* user: { name: string; age: number }
|
||||
* items: number[]
|
||||
* }
|
||||
*
|
||||
* // 创建 ObservableImpl
|
||||
* const obs = new ObservableImpl<AppState>({
|
||||
* count: 0,
|
||||
* user: { name: 'Alice', age: 20 },
|
||||
* items: []
|
||||
* })
|
||||
*
|
||||
* export default defineComponent({
|
||||
* setup() {
|
||||
* // 深层解构 Hook
|
||||
* const { count, user, items } = useObservable(obs)
|
||||
*
|
||||
* const increment = () => {
|
||||
* count += 1 // 触发 ObservableImpl 通知 + Vue 更新
|
||||
* }
|
||||
*
|
||||
* const changeAge = () => {
|
||||
* user.age = 30 // 深层对象也能触发通知
|
||||
* }
|
||||
*
|
||||
* const addItem = () => {
|
||||
* items.push(42) // 数组方法拦截,触发通知
|
||||
* }
|
||||
*
|
||||
* return { count, user, items, increment, changeAge, addItem }
|
||||
* }
|
||||
* })
|
||||
*/
|
||||
export function useObservable<T extends object>(observable: IObservable<T>): Reactive<T> {
|
||||
// 创建 Vue 响应式对象
|
||||
const state = reactive({} as T)
|
||||
|
||||
/**
|
||||
* 将 ObservableImpl Proxy 映射到 Vue 响应式对象
|
||||
* 递归支持深层对象
|
||||
*/
|
||||
function mapKeys(obj: any, proxy: any) {
|
||||
(Object.keys(proxy) as (keyof typeof proxy)[]).forEach(key => {
|
||||
const value = proxy[key]
|
||||
if (typeof value === 'object' && value !== null) {
|
||||
// 递归创建子对象 Proxy
|
||||
obj[key] = reactive({} as typeof value)
|
||||
mapKeys(obj[key], value)
|
||||
} else {
|
||||
// 基本类型通过 getter/setter 同步
|
||||
Object.defineProperty(obj, key, {
|
||||
enumerable: true,
|
||||
configurable: true,
|
||||
get() {
|
||||
return proxy[key]
|
||||
},
|
||||
set(val) {
|
||||
proxy[key] = val
|
||||
},
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// 获取 ObservableImpl 的 Proxy
|
||||
const refsProxy = observable.toRefsProxy()
|
||||
mapKeys(state, refsProxy)
|
||||
|
||||
// 订阅 ObservableImpl,保持响应式同步
|
||||
const unsubscribe = observable.subscribe(() => {
|
||||
// 空实现即可,getter/setter 已同步
|
||||
})
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
unsubscribe()
|
||||
})
|
||||
|
||||
return state
|
||||
}
|
||||
57
src/core/state/IObservable.ts
Normal file
57
src/core/state/IObservable.ts
Normal file
@@ -0,0 +1,57 @@
|
||||
// 订阅函数类型
|
||||
export type TObservableListener<T> = (state: T) => void
|
||||
|
||||
// 字段订阅函数类型
|
||||
export type TObservableKeyListener<T, K extends keyof T> = (values: Pick<T, K>) => void
|
||||
|
||||
// 工具类型:排除函数属性
|
||||
export type TNonFunctionProperties<T> = {
|
||||
[K in keyof T as T[K] extends Function ? never : K]: T[K]
|
||||
}
|
||||
|
||||
// ObservableImpl 数据类型
|
||||
export type TObservableState<T> = T & { [key: string]: any }
|
||||
|
||||
/**
|
||||
* ObservableImpl 接口定义
|
||||
*/
|
||||
export interface IObservable<T extends TNonFunctionProperties<T>> {
|
||||
/** ObservableImpl 状态对象,深层 Proxy */
|
||||
readonly state: TObservableState<T>
|
||||
|
||||
/**
|
||||
* 订阅整个状态变化
|
||||
* @param fn 监听函数
|
||||
* @param options immediate 是否立即触发一次
|
||||
* @returns 取消订阅函数
|
||||
*/
|
||||
subscribe(fn: TObservableListener<T>, options?: { immediate?: boolean }): () => void
|
||||
|
||||
/**
|
||||
* 订阅指定字段变化
|
||||
* @param keys 单个或多个字段
|
||||
* @param fn 字段变化回调
|
||||
* @param options immediate 是否立即触发一次
|
||||
* @returns 取消订阅函数
|
||||
*/
|
||||
subscribeKey<K extends keyof T>(
|
||||
keys: K | K[],
|
||||
fn: TObservableKeyListener<T, K>,
|
||||
options?: { immediate?: boolean }
|
||||
): () => void
|
||||
|
||||
/**
|
||||
* 批量更新状态
|
||||
* @param values Partial<T>
|
||||
*/
|
||||
patch(values: Partial<T>): void
|
||||
|
||||
/** 销毁 ObservableImpl 实例 */
|
||||
dispose(): void
|
||||
|
||||
/**
|
||||
* 语法糖:返回一个可解构赋值的 Proxy
|
||||
* 用于直接赋值触发通知
|
||||
*/
|
||||
toRefsProxy(): { [K in keyof T]: T[K] }
|
||||
}
|
||||
@@ -1,158 +0,0 @@
|
||||
type Listener<T> = (state: T) => void
|
||||
type KeyListener<T, K extends keyof T> = (changed: Pick<T, K>) => void
|
||||
|
||||
/**
|
||||
* 从给定类型 T 中排除所有函数类型的属性,只保留非函数类型的属性
|
||||
* @template T - 需要处理的原始类型
|
||||
* @returns 一个新的类型,该类型只包含原始类型中非函数类型的属性
|
||||
*/
|
||||
type NonFunctionProperties<T> = {
|
||||
[K in keyof T]: T[K] extends Function ? never : T[K]
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建一个可观察对象,用于管理状态和事件。
|
||||
* @template T - 需要处理的状态类型
|
||||
* @example
|
||||
* interface AppState {
|
||||
* count: number
|
||||
* isOpen: boolean
|
||||
* title: string
|
||||
* }
|
||||
*
|
||||
* const app = new Observable<AppState>({
|
||||
* count: 0,
|
||||
* isOpen: false,
|
||||
* title: "Demo"
|
||||
* })
|
||||
*
|
||||
* // 全量订阅
|
||||
* app.subscribe(state => console.log("全量:", state))
|
||||
*
|
||||
* // 单字段订阅
|
||||
* app.subscribeKey("count", changes => console.log("count 变化:", changes))
|
||||
*
|
||||
* // 多字段订阅
|
||||
* app.subscribeKey(["count", "isOpen"], changes =>
|
||||
* console.log("count/isOpen 回调:", changes)
|
||||
* )
|
||||
*
|
||||
* // 直接修改属性
|
||||
* app.count = 1
|
||||
* app.isOpen = true
|
||||
* app.title = "New Title"
|
||||
*
|
||||
* // 输出示例:
|
||||
* // 全量: { count: 1, isOpen: true, title: 'New Title' }
|
||||
* // count 变化: { count: 1 }
|
||||
* // count/isOpen 回调: { count: 1, isOpen: true }
|
||||
*/
|
||||
export class Observable<T extends object> {
|
||||
private listeners = new Set<WeakRef<Listener<T>>>()
|
||||
private keyListeners = new Map<keyof T, Set<WeakRef<Function>>>()
|
||||
private registry = new FinalizationRegistry((ref: WeakRef<any>) => {
|
||||
this.listeners.delete(ref)
|
||||
this.keyListeners.forEach(set => set.delete(ref))
|
||||
})
|
||||
|
||||
private pendingKeys = new Set<keyof T>()
|
||||
private notifyScheduled = false
|
||||
|
||||
constructor(initialState: NonFunctionProperties<T>) {
|
||||
Object.assign(this, initialState)
|
||||
|
||||
// Proxy 拦截属性修改
|
||||
return new Proxy(this, {
|
||||
set: (target, prop: string, value) => {
|
||||
const key = prop as keyof T
|
||||
(target as any)[key] = value
|
||||
|
||||
// 每次赋值都加入 pendingKeys
|
||||
this.pendingKeys.add(key)
|
||||
this.scheduleNotify()
|
||||
return true
|
||||
},
|
||||
get: (target, prop: string) => (target as any)[prop]
|
||||
})
|
||||
}
|
||||
|
||||
/** 安排微任务通知 */
|
||||
private scheduleNotify() {
|
||||
if (!this.notifyScheduled) {
|
||||
this.notifyScheduled = true
|
||||
Promise.resolve().then(() => this.flushNotify())
|
||||
}
|
||||
}
|
||||
|
||||
/** 执行通知:全量 + 单/多字段通知 */
|
||||
private flushNotify() {
|
||||
const keys = Array.from(this.pendingKeys)
|
||||
this.pendingKeys.clear()
|
||||
this.notifyScheduled = false
|
||||
|
||||
// 全量通知一次
|
||||
for (const ref of this.listeners) {
|
||||
const fn = ref.deref()
|
||||
if (fn) fn(this as unknown as T)
|
||||
else this.listeners.delete(ref)
|
||||
}
|
||||
|
||||
// 单/多字段通知(合并函数)
|
||||
const fnMap = new Map<Function, (keyof T)[]>()
|
||||
|
||||
for (const key of keys) {
|
||||
const set = this.keyListeners.get(key)
|
||||
if (!set) continue
|
||||
for (const ref of set) {
|
||||
const fn = ref.deref()
|
||||
if (!fn) {
|
||||
set.delete(ref)
|
||||
continue
|
||||
}
|
||||
if (!fnMap.has(fn)) fnMap.set(fn, [])
|
||||
const arr = fnMap.get(fn)!
|
||||
if (!arr.includes(key)) arr.push(key)
|
||||
}
|
||||
}
|
||||
|
||||
// 调用每个函数一次,并返回订阅字段的当前值
|
||||
fnMap.forEach((subKeys, fn) => {
|
||||
const result: Partial<T> = {}
|
||||
subKeys.forEach(k => (result[k] = (this as any)[k]))
|
||||
fn(result)
|
||||
})
|
||||
}
|
||||
|
||||
/** 全量订阅 */
|
||||
subscribe(fn: Listener<T>) {
|
||||
const ref = new WeakRef(fn)
|
||||
this.listeners.add(ref)
|
||||
this.registry.register(fn, ref)
|
||||
return () => {
|
||||
this.listeners.delete(ref)
|
||||
this.registry.unregister(fn)
|
||||
}
|
||||
}
|
||||
|
||||
/** 单字段或多字段订阅 */
|
||||
subscribeKey<K extends keyof T>(keys: K | K[], fn: KeyListener<T, K>) {
|
||||
const keyArray = Array.isArray(keys) ? keys : [keys]
|
||||
const refs: WeakRef<Function>[] = []
|
||||
|
||||
for (const key of keyArray) {
|
||||
if (!this.keyListeners.has(key)) this.keyListeners.set(key, new Set())
|
||||
const ref = new WeakRef(fn)
|
||||
this.keyListeners.get(key)!.add(ref)
|
||||
this.registry.register(fn, ref)
|
||||
refs.push(ref)
|
||||
}
|
||||
|
||||
return () => {
|
||||
for (let i = 0; i < keyArray.length; i++) {
|
||||
const set = this.keyListeners.get(keyArray[i])
|
||||
if (set) set.delete(refs[i])
|
||||
}
|
||||
this.registry.unregister(fn)
|
||||
}
|
||||
}
|
||||
}
|
||||
257
src/core/state/impl/ObservableImpl.ts
Normal file
257
src/core/state/impl/ObservableImpl.ts
Normal file
@@ -0,0 +1,257 @@
|
||||
import type {
|
||||
IObservable,
|
||||
TNonFunctionProperties,
|
||||
TObservableKeyListener,
|
||||
TObservableListener,
|
||||
TObservableState,
|
||||
} from '@/core/state/IObservable.ts'
|
||||
|
||||
/**
|
||||
* 创建一个可观察对象,用于管理状态和事件。
|
||||
* @template T - 需要处理的状态类型
|
||||
* @example
|
||||
* interface AppState {
|
||||
* count: number
|
||||
* user: {
|
||||
* name: string
|
||||
* age: number
|
||||
* }
|
||||
* items: number[]
|
||||
* }
|
||||
*
|
||||
* // 创建 ObservableImpl
|
||||
* const obs = new ObservableImpl<AppState>({
|
||||
* count: 0,
|
||||
* user: { name: 'Alice', age: 20 },
|
||||
* items: []
|
||||
* })
|
||||
*
|
||||
* // 1️⃣ 全量订阅
|
||||
* const unsubscribeAll = obs.subscribe(state => {
|
||||
* console.log('全量订阅', state)
|
||||
* }, { immediate: true })
|
||||
*
|
||||
* // 2️⃣ 单字段订阅
|
||||
* const unsubscribeCount = obs.subscribeKey('count', ({ count }) => {
|
||||
* console.log('count 字段变化:', count)
|
||||
* })
|
||||
*
|
||||
* // 3️⃣ 多字段订阅
|
||||
* const unsubscribeUser = obs.subscribeKey(['user', 'count'], ({ user, count }) => {
|
||||
* console.log('user 或 count 变化:', { user, count })
|
||||
* })
|
||||
*
|
||||
* // 4️⃣ 修改属性
|
||||
* obs.state.count = 1 // ✅ 会触发 count 和全量订阅
|
||||
* obs.state.user.age = 21 // ✅ 深层对象修改触发 user 订阅
|
||||
* obs.state.user.name = 'Bob'
|
||||
* // 语法糖:解构赋值直接赋值触发通知
|
||||
* const { count, user, items } = obs.toRefsProxy()
|
||||
* count = 1 // 触发 Proxy set
|
||||
* user.age = 18 // 深层对象 Proxy 支持
|
||||
* items.push(42) // 数组方法拦截触发通知
|
||||
*
|
||||
* // 5️⃣ 数组方法触发
|
||||
* obs.state.items.push(10) // ✅ push 会触发 items 的字段订阅
|
||||
* obs.state.items.splice(0, 1)
|
||||
*
|
||||
* // 6️⃣ 批量修改(同一事件循环只触发一次通知)
|
||||
* obs.patch({
|
||||
* count: 2,
|
||||
* user: { name: 'Charlie', age: 30 }
|
||||
* })
|
||||
*
|
||||
* // 7️⃣ 解构赋值访问对象属性仍然触发订阅
|
||||
* const { state } = obs
|
||||
* state.user.age = 31 // ✅ 会触发 user 订阅
|
||||
*
|
||||
* // 8️⃣ 取消订阅
|
||||
* unsubscribeAll()
|
||||
* unsubscribeCount()
|
||||
* unsubscribeUser()
|
||||
*
|
||||
* // 9️⃣ 销毁 ObservableImpl
|
||||
* obs.dispose()
|
||||
*/
|
||||
export class Observable<T extends TNonFunctionProperties<T>> implements IObservable<T> {
|
||||
/** Observable 状态对象,深层 Proxy */
|
||||
public readonly state: TObservableState<T>
|
||||
|
||||
/** 全量订阅函数集合 */
|
||||
private listeners: Set<TObservableListener<T>> = new Set()
|
||||
|
||||
/** 字段订阅函数集合 */
|
||||
private keyListeners: Map<keyof T, Set<Function>> = new Map()
|
||||
|
||||
/** 待通知的字段集合 */
|
||||
private pendingKeys: Set<keyof T> = new Set()
|
||||
|
||||
/** 是否已经安排通知 */
|
||||
private notifyScheduled = false
|
||||
|
||||
/** 是否已销毁 */
|
||||
private disposed = false
|
||||
|
||||
constructor(initialState: TNonFunctionProperties<T>) {
|
||||
// 创建深层响应式 Proxy
|
||||
this.state = this.makeReactive(initialState) as TObservableState<T>
|
||||
}
|
||||
|
||||
/** 创建深层 Proxy,拦截 get/set */
|
||||
private makeReactive(obj: TNonFunctionProperties<T>): TObservableState<T> {
|
||||
const handler: ProxyHandler<any> = {
|
||||
get: (target, prop: string | symbol, receiver) => {
|
||||
const key = prop as keyof T
|
||||
const value = Reflect.get(target, key, receiver)
|
||||
if (Array.isArray(value)) return this.wrapArray(value, key)
|
||||
if (typeof value === 'object' && value !== null) return this.makeReactive(value)
|
||||
return value
|
||||
},
|
||||
set: (target, prop: string | symbol, value, receiver) => {
|
||||
const key = prop as keyof T
|
||||
const oldValue = target[key]
|
||||
if (oldValue !== value) {
|
||||
target[key] = value
|
||||
this.pendingKeys.add(key)
|
||||
this.scheduleNotify()
|
||||
}
|
||||
return true
|
||||
}
|
||||
}
|
||||
return new Proxy(obj, handler) as TObservableState<T>
|
||||
}
|
||||
|
||||
/** 包装数组方法,使 push/pop 等触发通知 */
|
||||
private wrapArray(arr: any[], parentKey: keyof T): any {
|
||||
const self = this
|
||||
const arrayMethods = ['push', 'pop', 'shift', 'unshift', 'splice', 'sort', 'reverse'] as const
|
||||
arrayMethods.forEach(method => {
|
||||
const original = arr[method]
|
||||
Object.defineProperty(arr, method, {
|
||||
value: function (...args: any[]) {
|
||||
const result = original.apply(this, args)
|
||||
self.pendingKeys.add(parentKey)
|
||||
self.scheduleNotify()
|
||||
return result
|
||||
},
|
||||
writable: true,
|
||||
configurable: true,
|
||||
})
|
||||
})
|
||||
return arr
|
||||
}
|
||||
|
||||
/** 安排下一次通知 */
|
||||
private scheduleNotify(): void {
|
||||
if (!this.notifyScheduled && !this.disposed) {
|
||||
this.notifyScheduled = true
|
||||
Promise.resolve().then(() => this.flushNotify())
|
||||
}
|
||||
}
|
||||
|
||||
/** 执行通知 */
|
||||
private flushNotify(): void {
|
||||
if (this.disposed) return
|
||||
const keys = Array.from(this.pendingKeys)
|
||||
this.pendingKeys.clear()
|
||||
this.notifyScheduled = false
|
||||
|
||||
// 全量订阅
|
||||
for (const fn of this.listeners) {
|
||||
fn(this.state)
|
||||
}
|
||||
|
||||
// 字段订阅
|
||||
const fnMap = new Map<Function, (keyof T)[]>()
|
||||
for (const key of keys) {
|
||||
const set = this.keyListeners.get(key)
|
||||
if (!set) continue
|
||||
for (const fn of set) {
|
||||
if (!fnMap.has(fn)) fnMap.set(fn, [])
|
||||
fnMap.get(fn)!.push(key)
|
||||
}
|
||||
}
|
||||
|
||||
fnMap.forEach((subKeys, fn) => {
|
||||
const result = {} as Pick<T, typeof subKeys[number]>
|
||||
subKeys.forEach(k => (result[k] = this.state[k]))
|
||||
fn(result)
|
||||
})
|
||||
}
|
||||
|
||||
/** 订阅整个状态变化 */
|
||||
subscribe(fn: TObservableListener<T>, options: { immediate?: boolean } = {}): () => void {
|
||||
this.listeners.add(fn)
|
||||
if (options.immediate) fn(this.state)
|
||||
return () => {
|
||||
this.listeners.delete(fn)
|
||||
}
|
||||
}
|
||||
|
||||
/** 订阅指定字段变化 */
|
||||
subscribeKey<K extends keyof T>(
|
||||
keys: K | K[],
|
||||
fn: TObservableKeyListener<T, K>,
|
||||
options: { immediate?: boolean } = {}
|
||||
): () => void {
|
||||
const keyArray = Array.isArray(keys) ? keys : [keys]
|
||||
for (const key of keyArray) {
|
||||
if (!this.keyListeners.has(key)) this.keyListeners.set(key, new Set())
|
||||
this.keyListeners.get(key)!.add(fn)
|
||||
}
|
||||
|
||||
if (options.immediate) {
|
||||
const result = {} as Pick<T, K>
|
||||
keyArray.forEach(k => (result[k] = this.state[k]))
|
||||
fn(result)
|
||||
}
|
||||
|
||||
return () => {
|
||||
for (const key of keyArray) {
|
||||
this.keyListeners.get(key)?.delete(fn)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 批量更新状态 */
|
||||
patch(values: Partial<T>): void {
|
||||
for (const key in values) {
|
||||
if (Object.prototype.hasOwnProperty.call(values, key)) {
|
||||
const typedKey = key as keyof T
|
||||
this.state[typedKey] = values[typedKey]!
|
||||
this.pendingKeys.add(typedKey)
|
||||
}
|
||||
}
|
||||
this.scheduleNotify()
|
||||
}
|
||||
|
||||
/** 销毁 Observable 实例 */
|
||||
dispose(): void {
|
||||
this.disposed = true
|
||||
this.listeners.clear()
|
||||
this.keyListeners.clear()
|
||||
this.pendingKeys.clear()
|
||||
}
|
||||
|
||||
/** 语法糖:返回一个可解构赋值的 Proxy */
|
||||
toRefsProxy(): { [K in keyof T]: T[K] } {
|
||||
const self = this
|
||||
return new Proxy({} as T, {
|
||||
get(_, prop: string | symbol) {
|
||||
const key = prop as keyof T
|
||||
return self.state[key]
|
||||
},
|
||||
set(_, prop: string | symbol, value) {
|
||||
const key = prop as keyof T
|
||||
self.state[key] = value
|
||||
return true
|
||||
},
|
||||
ownKeys() {
|
||||
return Reflect.ownKeys(self.state)
|
||||
},
|
||||
getOwnPropertyDescriptor(_, prop: string | symbol) {
|
||||
return { enumerable: true, configurable: true }
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
297
src/core/state/impl/ObservableWeakRefImpl.ts
Normal file
297
src/core/state/impl/ObservableWeakRefImpl.ts
Normal file
@@ -0,0 +1,297 @@
|
||||
import type {
|
||||
IObservable,
|
||||
TNonFunctionProperties,
|
||||
TObservableKeyListener,
|
||||
TObservableListener,
|
||||
TObservableState,
|
||||
} from '@/core/state/IObservable.ts'
|
||||
|
||||
/**
|
||||
* 创建一个可观察对象,用于管理状态和事件。
|
||||
* WeakRef 和垃圾回收功能
|
||||
* @template T - 需要处理的状态类型
|
||||
* @example
|
||||
* interface AppState {
|
||||
* count: number
|
||||
* user: {
|
||||
* name: string
|
||||
* age: number
|
||||
* }
|
||||
* items: number[]
|
||||
* }
|
||||
*
|
||||
* // 创建 ObservableImpl
|
||||
* const obs = new ObservableImpl<AppState>({
|
||||
* count: 0,
|
||||
* user: { name: 'Alice', age: 20 },
|
||||
* items: []
|
||||
* })
|
||||
*
|
||||
* // 1️⃣ 全量订阅
|
||||
* const unsubscribeAll = obs.subscribe(state => {
|
||||
* console.log('全量订阅', state)
|
||||
* }, { immediate: true })
|
||||
*
|
||||
* // 2️⃣ 单字段订阅
|
||||
* const unsubscribeCount = obs.subscribeKey('count', ({ count }) => {
|
||||
* console.log('count 字段变化:', count)
|
||||
* })
|
||||
*
|
||||
* // 3️⃣ 多字段订阅
|
||||
* const unsubscribeUser = obs.subscribeKey(['user', 'count'], ({ user, count }) => {
|
||||
* console.log('user 或 count 变化:', { user, count })
|
||||
* })
|
||||
*
|
||||
* // 4️⃣ 修改属性
|
||||
* obs.state.count = 1 // ✅ 会触发 count 和全量订阅
|
||||
* obs.state.user.age = 21 // ✅ 深层对象修改触发 user 订阅
|
||||
* obs.state.user.name = 'Bob'
|
||||
* // 语法糖:解构赋值直接赋值触发通知
|
||||
* const { count, user, items } = obs.toRefsProxy()
|
||||
* count = 1 // 触发 Proxy set
|
||||
* user.age = 18 // 深层对象 Proxy 支持
|
||||
* items.push(42) // 数组方法拦截触发通知
|
||||
*
|
||||
* // 5️⃣ 数组方法触发
|
||||
* obs.state.items.push(10) // ✅ push 会触发 items 的字段订阅
|
||||
* obs.state.items.splice(0, 1)
|
||||
*
|
||||
* // 6️⃣ 批量修改(同一事件循环只触发一次通知)
|
||||
* obs.patch({
|
||||
* count: 2,
|
||||
* user: { name: 'Charlie', age: 30 }
|
||||
* })
|
||||
*
|
||||
* // 7️⃣ 解构赋值访问对象属性仍然触发订阅
|
||||
* const { state } = obs
|
||||
* state.user.age = 31 // ✅ 会触发 user 订阅
|
||||
*
|
||||
* // 8️⃣ 取消订阅
|
||||
* unsubscribeAll()
|
||||
* unsubscribeCount()
|
||||
* unsubscribeUser()
|
||||
*
|
||||
* // 9️⃣ 销毁 ObservableImpl
|
||||
* obs.dispose()
|
||||
*/
|
||||
export class ObservableImpl<T extends TNonFunctionProperties<T>> implements IObservable<T> {
|
||||
/** ObservableImpl 的状态对象,深层 Proxy */
|
||||
public readonly state: TObservableState<T>
|
||||
|
||||
/** 全量订阅列表 */
|
||||
private listeners: Set<WeakRef<TObservableListener<T>> | TObservableListener<T>> = new Set()
|
||||
|
||||
/** 字段订阅列表 */
|
||||
private keyListeners: Map<keyof T, Set<WeakRef<Function> | Function>> = new Map()
|
||||
|
||||
/** FinalizationRegistry 用于自动清理 WeakRef */
|
||||
private registry?: FinalizationRegistry<WeakRef<Function>>
|
||||
|
||||
/** 待通知的字段 */
|
||||
private pendingKeys: Set<keyof T> = new Set()
|
||||
|
||||
/** 通知调度状态 */
|
||||
private notifyScheduled = false
|
||||
|
||||
/** 已销毁标记 */
|
||||
private disposed = false
|
||||
|
||||
constructor(initialState: TNonFunctionProperties<T>) {
|
||||
if (typeof WeakRef !== 'undefined' && typeof FinalizationRegistry !== 'undefined') {
|
||||
this.registry = new FinalizationRegistry((ref: WeakRef<Function>) => {
|
||||
this.listeners.delete(ref as unknown as TObservableListener<T>)
|
||||
this.keyListeners.forEach(set => set.delete(ref))
|
||||
})
|
||||
}
|
||||
|
||||
// 创建深层响应式 Proxy
|
||||
this.state = this.makeReactive(initialState) as TObservableState<T>
|
||||
}
|
||||
|
||||
/** 创建响应式对象,深层递归 Proxy + 数组方法拦截 */
|
||||
private makeReactive(obj: TNonFunctionProperties<T>): TObservableState<T> {
|
||||
const handler: ProxyHandler<any> = {
|
||||
get: (target, prop: string | symbol, receiver) => {
|
||||
const key = prop as keyof T // 类型断言
|
||||
const value = Reflect.get(target, key, receiver)
|
||||
if (Array.isArray(value)) return this.wrapArray(value, key)
|
||||
if (typeof value === 'object' && value !== null) return this.makeReactive(value)
|
||||
return value
|
||||
},
|
||||
set: (target, prop: string | symbol, value, receiver) => {
|
||||
const key = prop as keyof T // 类型断言
|
||||
const oldValue = target[key]
|
||||
if (oldValue !== value) {
|
||||
target[key] = value
|
||||
this.pendingKeys.add(key)
|
||||
this.scheduleNotify()
|
||||
}
|
||||
return true
|
||||
},
|
||||
}
|
||||
return new Proxy(obj, handler) as TObservableState<T>
|
||||
}
|
||||
|
||||
/** 包装数组方法,使 push/pop/splice 等触发通知 */
|
||||
private wrapArray(arr: any[], parentKey: keyof T): any {
|
||||
const self = this
|
||||
const arrayMethods = ['push', 'pop', 'shift', 'unshift', 'splice', 'sort', 'reverse'] as const
|
||||
|
||||
arrayMethods.forEach(method => {
|
||||
const original = arr[method]
|
||||
Object.defineProperty(arr, method, {
|
||||
value: function (...args: any[]) {
|
||||
const result = original.apply(this, args)
|
||||
self.pendingKeys.add(parentKey)
|
||||
self.scheduleNotify()
|
||||
return result
|
||||
},
|
||||
writable: true,
|
||||
configurable: true,
|
||||
})
|
||||
})
|
||||
|
||||
return arr
|
||||
}
|
||||
|
||||
/** 调度异步通知 */
|
||||
private scheduleNotify(): void {
|
||||
if (!this.notifyScheduled && !this.disposed) {
|
||||
this.notifyScheduled = true
|
||||
Promise.resolve().then(() => this.flushNotify())
|
||||
}
|
||||
}
|
||||
|
||||
/** 执行通知逻辑 */
|
||||
private flushNotify(): void {
|
||||
if (this.disposed) return
|
||||
const keys = Array.from(this.pendingKeys)
|
||||
this.pendingKeys.clear()
|
||||
this.notifyScheduled = false
|
||||
|
||||
// 全量订阅
|
||||
for (const ref of this.listeners) {
|
||||
const fn = this.deref(ref)
|
||||
if (fn) fn(this.state)
|
||||
else this.listeners.delete(ref as TObservableListener<T>)
|
||||
}
|
||||
|
||||
// 字段订阅
|
||||
const fnMap = new Map<Function, (keyof T)[]>()
|
||||
for (const key of keys) {
|
||||
const set = this.keyListeners.get(key)
|
||||
if (!set) continue
|
||||
for (const ref of set) {
|
||||
const fn = this.deref(ref)
|
||||
if (!fn) {
|
||||
set.delete(ref)
|
||||
continue
|
||||
}
|
||||
if (!fnMap.has(fn)) fnMap.set(fn, [])
|
||||
fnMap.get(fn)!.push(key)
|
||||
}
|
||||
}
|
||||
|
||||
fnMap.forEach((subKeys, fn) => {
|
||||
const result = {} as Pick<T, typeof subKeys[number]>
|
||||
subKeys.forEach(k => (result[k] = this.state[k]))
|
||||
fn(result)
|
||||
})
|
||||
}
|
||||
|
||||
/** 全量订阅 */
|
||||
subscribe(fn: TObservableListener<T>, options: { immediate?: boolean } = {}): () => void {
|
||||
const ref = this.makeRef(fn)
|
||||
this.listeners.add(ref)
|
||||
this.registry?.register(fn, ref as WeakRef<Function>)
|
||||
if (options.immediate) fn(this.state)
|
||||
return () => {
|
||||
this.listeners.delete(ref)
|
||||
this.registry?.unregister(fn)
|
||||
}
|
||||
}
|
||||
|
||||
/** 字段订阅 */
|
||||
subscribeKey<K extends keyof T>(
|
||||
keys: K | K[],
|
||||
fn: TObservableKeyListener<T, K>,
|
||||
options: { immediate?: boolean } = {}
|
||||
): () => void {
|
||||
const keyArray = Array.isArray(keys) ? keys : [keys]
|
||||
const refs: (WeakRef<Function> | Function)[] = []
|
||||
|
||||
for (const key of keyArray) {
|
||||
if (!this.keyListeners.has(key)) this.keyListeners.set(key, new Set())
|
||||
const ref = this.makeRef(fn)
|
||||
this.keyListeners.get(key)!.add(ref)
|
||||
this.registry?.register(fn as unknown as Function, ref as WeakRef<Function>)
|
||||
refs.push(ref)
|
||||
}
|
||||
|
||||
if (options.immediate) {
|
||||
const result = {} as Pick<T, K>
|
||||
keyArray.forEach(k => (result[k] = this.state[k]))
|
||||
fn(result)
|
||||
}
|
||||
|
||||
return () => {
|
||||
for (let i = 0; i < keyArray.length; i++) {
|
||||
const set = this.keyListeners.get(keyArray[i])
|
||||
if (set) set.delete(refs[i])
|
||||
}
|
||||
this.registry?.unregister(fn as unknown as Function)
|
||||
}
|
||||
}
|
||||
|
||||
/** 批量更新 */
|
||||
patch(values: Partial<T>): void {
|
||||
for (const key in values) {
|
||||
if (Object.prototype.hasOwnProperty.call(values, key)) {
|
||||
const typedKey = key as keyof T
|
||||
this.state[typedKey] = values[typedKey]!
|
||||
this.pendingKeys.add(typedKey)
|
||||
}
|
||||
}
|
||||
this.scheduleNotify()
|
||||
}
|
||||
|
||||
/** 销毁 ObservableImpl */
|
||||
dispose(): void {
|
||||
this.disposed = true
|
||||
this.listeners.clear()
|
||||
this.keyListeners.clear()
|
||||
this.pendingKeys.clear()
|
||||
}
|
||||
|
||||
/** 语法糖:解构赋值直接赋值触发通知 */
|
||||
toRefsProxy(): { [K in keyof T]: T[K] } {
|
||||
const self = this
|
||||
return new Proxy({} as T, {
|
||||
get(_, prop: string | symbol) {
|
||||
const key = prop as keyof T
|
||||
return self.state[key]
|
||||
},
|
||||
set(_, prop: string | symbol, value) {
|
||||
const key = prop as keyof T
|
||||
self.state[key] = value
|
||||
return true
|
||||
},
|
||||
ownKeys() {
|
||||
return Reflect.ownKeys(self.state)
|
||||
},
|
||||
getOwnPropertyDescriptor(_, prop: string | symbol) {
|
||||
return { enumerable: true, configurable: true }
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/** WeakRef 创建 */
|
||||
private makeRef<F extends Function>(fn: F): WeakRef<F> | F {
|
||||
return typeof WeakRef !== 'undefined' ? new WeakRef(fn) : fn
|
||||
}
|
||||
|
||||
/** WeakRef 解引用 */
|
||||
private deref<F extends Function>(ref: WeakRef<F> | F): F | undefined {
|
||||
return typeof WeakRef !== 'undefined' && ref instanceof WeakRef ? ref.deref() : (ref as F)
|
||||
}
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
// import { useEffect, useState } from "react"
|
||||
// import { Observable } from "./Observable"
|
||||
//
|
||||
// export function useObservable<T extends object, K extends keyof T>(
|
||||
// observable: Observable<T>,
|
||||
// keys?: K | K[]
|
||||
// ): Pick<T, K> | T {
|
||||
// const keyArray = keys ? (Array.isArray(keys) ? keys : [keys]) : null
|
||||
//
|
||||
// const [state, setState] = useState<Partial<T>>(() => {
|
||||
// if (keyArray) {
|
||||
// const init: Partial<T> = {}
|
||||
// keyArray.forEach(k => (init[k] = (observable as any)[k]))
|
||||
// return init
|
||||
// }
|
||||
// return { ...(observable as any) }
|
||||
// })
|
||||
//
|
||||
// useEffect(() => {
|
||||
// const unsubscribe = keyArray
|
||||
// ? observable.subscribeKey(keyArray as K[], changed => {
|
||||
// setState(prev => ({ ...prev, ...changed }))
|
||||
// })
|
||||
// : observable.subscribe(s => setState({ ...s }))
|
||||
//
|
||||
// return () => {
|
||||
// unsubscribe()
|
||||
// }
|
||||
// }, [observable, ...(keyArray || [])])
|
||||
//
|
||||
// return state as any
|
||||
// }
|
||||
@@ -1,38 +0,0 @@
|
||||
import type { Observable } from '@/core/state/Observable.ts'
|
||||
import { onUnmounted, ref, type Ref } from 'vue'
|
||||
|
||||
/**
|
||||
* vue使用自定义的 observable
|
||||
* @param observable
|
||||
* @param keys
|
||||
* @returns
|
||||
* @example
|
||||
* const app = new Observable({ count: 0, isOpen: false, title: "Demo" })
|
||||
* // 多字段订阅
|
||||
* const state = useObservable(app, ["count", "isOpen"])
|
||||
* // state.value.count / state.value.isOpen 响应式
|
||||
*/
|
||||
export function useObservable<T extends object, K extends keyof T>(
|
||||
observable: Observable<T>,
|
||||
keys?: K[] | K
|
||||
): Ref<Pick<T, K> | T> {
|
||||
const state = ref({} as any) // 响应式
|
||||
|
||||
const keyArray = keys ? (Array.isArray(keys) ? keys : [keys]) : null
|
||||
|
||||
// 订阅回调
|
||||
const unsubscribe = keyArray
|
||||
? observable.subscribeKey(keyArray as K[], changed => {
|
||||
// 更新响应式 state
|
||||
Object.assign(state.value, changed)
|
||||
})
|
||||
: observable.subscribe(s => {
|
||||
state.value = { ...s }
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
unsubscribe()
|
||||
})
|
||||
|
||||
return state
|
||||
}
|
||||
Reference in New Issue
Block a user