From c4fb06f6a67a6a9acd26585c9cd9469ed1c26e7d Mon Sep 17 00:00:00 2001 From: Azure <983547216@qq.com> Date: Wed, 27 Aug 2025 11:16:56 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=9D=E5=AD=98=E4=B8=80=E4=B8=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/core/common/hooks/useObservableVue.ts | 87 ++++++ src/core/state/IObservable.ts | 57 ++++ src/core/state/Observable.ts | 158 ---------- src/core/state/impl/ObservableImpl.ts | 257 ++++++++++++++++ src/core/state/impl/ObservableWeakRefImpl.ts | 297 +++++++++++++++++++ src/core/state/useObservableReact.ts | 32 -- src/core/state/useObservableVue.ts | 38 --- 7 files changed, 698 insertions(+), 228 deletions(-) create mode 100644 src/core/common/hooks/useObservableVue.ts create mode 100644 src/core/state/IObservable.ts delete mode 100644 src/core/state/Observable.ts create mode 100644 src/core/state/impl/ObservableImpl.ts create mode 100644 src/core/state/impl/ObservableWeakRefImpl.ts delete mode 100644 src/core/state/useObservableReact.ts delete mode 100644 src/core/state/useObservableVue.ts diff --git a/src/core/common/hooks/useObservableVue.ts b/src/core/common/hooks/useObservableVue.ts new file mode 100644 index 0000000..9ca6458 --- /dev/null +++ b/src/core/common/hooks/useObservableVue.ts @@ -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({ + * 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(observable: IObservable): Reactive { + // 创建 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 +} diff --git a/src/core/state/IObservable.ts b/src/core/state/IObservable.ts new file mode 100644 index 0000000..c624da3 --- /dev/null +++ b/src/core/state/IObservable.ts @@ -0,0 +1,57 @@ +// 订阅函数类型 +export type TObservableListener = (state: T) => void + +// 字段订阅函数类型 +export type TObservableKeyListener = (values: Pick) => void + +// 工具类型:排除函数属性 +export type TNonFunctionProperties = { + [K in keyof T as T[K] extends Function ? never : K]: T[K] +} + +// ObservableImpl 数据类型 +export type TObservableState = T & { [key: string]: any } + +/** + * ObservableImpl 接口定义 + */ +export interface IObservable> { + /** ObservableImpl 状态对象,深层 Proxy */ + readonly state: TObservableState + + /** + * 订阅整个状态变化 + * @param fn 监听函数 + * @param options immediate 是否立即触发一次 + * @returns 取消订阅函数 + */ + subscribe(fn: TObservableListener, options?: { immediate?: boolean }): () => void + + /** + * 订阅指定字段变化 + * @param keys 单个或多个字段 + * @param fn 字段变化回调 + * @param options immediate 是否立即触发一次 + * @returns 取消订阅函数 + */ + subscribeKey( + keys: K | K[], + fn: TObservableKeyListener, + options?: { immediate?: boolean } + ): () => void + + /** + * 批量更新状态 + * @param values Partial + */ + patch(values: Partial): void + + /** 销毁 ObservableImpl 实例 */ + dispose(): void + + /** + * 语法糖:返回一个可解构赋值的 Proxy + * 用于直接赋值触发通知 + */ + toRefsProxy(): { [K in keyof T]: T[K] } +} diff --git a/src/core/state/Observable.ts b/src/core/state/Observable.ts deleted file mode 100644 index 6d053e6..0000000 --- a/src/core/state/Observable.ts +++ /dev/null @@ -1,158 +0,0 @@ -type Listener = (state: T) => void -type KeyListener = (changed: Pick) => void - -/** - * 从给定类型 T 中排除所有函数类型的属性,只保留非函数类型的属性 - * @template T - 需要处理的原始类型 - * @returns 一个新的类型,该类型只包含原始类型中非函数类型的属性 - */ -type NonFunctionProperties = { - [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({ - * 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 { - private listeners = new Set>>() - private keyListeners = new Map>>() - private registry = new FinalizationRegistry((ref: WeakRef) => { - this.listeners.delete(ref) - this.keyListeners.forEach(set => set.delete(ref)) - }) - - private pendingKeys = new Set() - private notifyScheduled = false - - constructor(initialState: NonFunctionProperties) { - 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() - - 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 = {} - subKeys.forEach(k => (result[k] = (this as any)[k])) - fn(result) - }) - } - - /** 全量订阅 */ - subscribe(fn: Listener) { - const ref = new WeakRef(fn) - this.listeners.add(ref) - this.registry.register(fn, ref) - return () => { - this.listeners.delete(ref) - this.registry.unregister(fn) - } - } - - /** 单字段或多字段订阅 */ - subscribeKey(keys: K | K[], fn: KeyListener) { - const keyArray = Array.isArray(keys) ? keys : [keys] - const refs: WeakRef[] = [] - - 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) - } - } -} diff --git a/src/core/state/impl/ObservableImpl.ts b/src/core/state/impl/ObservableImpl.ts new file mode 100644 index 0000000..d561496 --- /dev/null +++ b/src/core/state/impl/ObservableImpl.ts @@ -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({ + * 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> implements IObservable { + /** Observable 状态对象,深层 Proxy */ + public readonly state: TObservableState + + /** 全量订阅函数集合 */ + private listeners: Set> = new Set() + + /** 字段订阅函数集合 */ + private keyListeners: Map> = new Map() + + /** 待通知的字段集合 */ + private pendingKeys: Set = new Set() + + /** 是否已经安排通知 */ + private notifyScheduled = false + + /** 是否已销毁 */ + private disposed = false + + constructor(initialState: TNonFunctionProperties) { + // 创建深层响应式 Proxy + this.state = this.makeReactive(initialState) as TObservableState + } + + /** 创建深层 Proxy,拦截 get/set */ + private makeReactive(obj: TNonFunctionProperties): TObservableState { + const handler: ProxyHandler = { + 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 + } + + /** 包装数组方法,使 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() + 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 + subKeys.forEach(k => (result[k] = this.state[k])) + fn(result) + }) + } + + /** 订阅整个状态变化 */ + subscribe(fn: TObservableListener, options: { immediate?: boolean } = {}): () => void { + this.listeners.add(fn) + if (options.immediate) fn(this.state) + return () => { + this.listeners.delete(fn) + } + } + + /** 订阅指定字段变化 */ + subscribeKey( + keys: K | K[], + fn: TObservableKeyListener, + 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 + 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): 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 } + } + }) + } +} diff --git a/src/core/state/impl/ObservableWeakRefImpl.ts b/src/core/state/impl/ObservableWeakRefImpl.ts new file mode 100644 index 0000000..a3d3fc9 --- /dev/null +++ b/src/core/state/impl/ObservableWeakRefImpl.ts @@ -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({ + * 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> implements IObservable { + /** ObservableImpl 的状态对象,深层 Proxy */ + public readonly state: TObservableState + + /** 全量订阅列表 */ + private listeners: Set> | TObservableListener> = new Set() + + /** 字段订阅列表 */ + private keyListeners: Map | Function>> = new Map() + + /** FinalizationRegistry 用于自动清理 WeakRef */ + private registry?: FinalizationRegistry> + + /** 待通知的字段 */ + private pendingKeys: Set = new Set() + + /** 通知调度状态 */ + private notifyScheduled = false + + /** 已销毁标记 */ + private disposed = false + + constructor(initialState: TNonFunctionProperties) { + if (typeof WeakRef !== 'undefined' && typeof FinalizationRegistry !== 'undefined') { + this.registry = new FinalizationRegistry((ref: WeakRef) => { + this.listeners.delete(ref as unknown as TObservableListener) + this.keyListeners.forEach(set => set.delete(ref)) + }) + } + + // 创建深层响应式 Proxy + this.state = this.makeReactive(initialState) as TObservableState + } + + /** 创建响应式对象,深层递归 Proxy + 数组方法拦截 */ + private makeReactive(obj: TNonFunctionProperties): TObservableState { + const handler: ProxyHandler = { + 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 + } + + /** 包装数组方法,使 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) + } + + // 字段订阅 + const fnMap = new Map() + 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 + subKeys.forEach(k => (result[k] = this.state[k])) + fn(result) + }) + } + + /** 全量订阅 */ + subscribe(fn: TObservableListener, options: { immediate?: boolean } = {}): () => void { + const ref = this.makeRef(fn) + this.listeners.add(ref) + this.registry?.register(fn, ref as WeakRef) + if (options.immediate) fn(this.state) + return () => { + this.listeners.delete(ref) + this.registry?.unregister(fn) + } + } + + /** 字段订阅 */ + subscribeKey( + keys: K | K[], + fn: TObservableKeyListener, + options: { immediate?: boolean } = {} + ): () => void { + 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 = this.makeRef(fn) + this.keyListeners.get(key)!.add(ref) + this.registry?.register(fn as unknown as Function, ref as WeakRef) + refs.push(ref) + } + + if (options.immediate) { + const result = {} as Pick + 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): 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(fn: F): WeakRef | F { + return typeof WeakRef !== 'undefined' ? new WeakRef(fn) : fn + } + + /** WeakRef 解引用 */ + private deref(ref: WeakRef | F): F | undefined { + return typeof WeakRef !== 'undefined' && ref instanceof WeakRef ? ref.deref() : (ref as F) + } +} \ No newline at end of file diff --git a/src/core/state/useObservableReact.ts b/src/core/state/useObservableReact.ts deleted file mode 100644 index df73fd2..0000000 --- a/src/core/state/useObservableReact.ts +++ /dev/null @@ -1,32 +0,0 @@ -// import { useEffect, useState } from "react" -// import { Observable } from "./Observable" -// -// export function useObservable( -// observable: Observable, -// keys?: K | K[] -// ): Pick | T { -// const keyArray = keys ? (Array.isArray(keys) ? keys : [keys]) : null -// -// const [state, setState] = useState>(() => { -// if (keyArray) { -// const init: Partial = {} -// 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 -// } diff --git a/src/core/state/useObservableVue.ts b/src/core/state/useObservableVue.ts deleted file mode 100644 index fd17452..0000000 --- a/src/core/state/useObservableVue.ts +++ /dev/null @@ -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( - observable: Observable, - keys?: K[] | K -): Ref | 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 -}