Compare commits

..

4 Commits

Author SHA1 Message Date
68bdabf928 修改 2025-09-17 12:22:28 +08:00
e3cbba0607 优化ObservableImpl 2025-09-17 10:11:11 +08:00
3a6f5cdbba 优化ObservableImpl 2025-09-17 10:10:25 +08:00
6eee4933e1 优化ObservableImpl 2025-09-17 09:58:27 +08:00
8 changed files with 274 additions and 169 deletions

View File

@@ -19,4 +19,9 @@ export interface IProcess {
* @param startName 窗体启动名
*/
openWindowForm(startName: string): void;
/**
* 关闭窗体
* @param id 窗体id
*/
closeWindowForm(id: string): void;
}

View File

@@ -47,7 +47,7 @@ export default class ProcessImpl implements IProcess {
}
private initEvent() {
this.event.addEventListener('onProcessWindowFormExit', (id: string) => {
this.event.addEventListener('processWindowFormExit', (id: string) => {
this.windowForms.delete(id)
if(this.windowForms.size === 0) {
processManager.removeProcess(this)
@@ -58,7 +58,20 @@ export default class ProcessImpl implements IProcess {
public openWindowForm(startName: string) {
const info = this._processInfo.windowFormConfigs.find(item => item.name === startName);
if (!info) throw new Error(`未找到窗体:${startName}`);
const window = new WindowFormImpl(this, info);
this._windowForms.set(window.id, window);
const wf = new WindowFormImpl(this, info);
this._windowForms.set(wf.id, wf);
}
public closeWindowForm(id: string) {
try {
const wf = this._windowForms.get(id);
if (!wf) throw new Error(`未找到窗体:${id}`);
this.windowForms.delete(id)
if(this.windowForms.size === 0) {
processManager.removeProcess(this)
}
} catch (e) {
console.log('关闭窗体失败', e)
}
}
}

View File

@@ -20,5 +20,5 @@ export interface IProcessEvent extends IEventMap {
* 进程的窗体退出
* @param id 窗体id
*/
onProcessWindowFormExit: (id: string) => void
processWindowFormExit: (id: string) => void
}

View File

@@ -1,4 +1,8 @@
import { AService } from '@/core/service/kernel/AService.ts'
import type { IWindowForm } from '@/core/window/IWindowForm.ts'
import WindowFormImpl from '@/core/window/impl/WindowFormImpl.ts'
import type { IProcess } from '@/core/process/IProcess.ts'
import type { IWindowFormConfig } from '@/core/window/types/IWindowFormConfig.ts'
interface IWindow {
id: string;
@@ -13,67 +17,47 @@ interface IWindow {
}
export class WindowFormService extends AService {
private windows: Map<string, IWindow> = new Map();
private zCounter = 1;
private windows: Map<string, IWindowForm> = new Map();
constructor() {
super("WindowForm");
super("WindowFormService");
console.log('WindowFormService - 服务注册')
}
createWindow(title: string, config?: Partial<IWindow>): IWindow {
const id = `win-${Date.now()}-${Math.random()}`;
const win: IWindow = {
id,
title,
x: config?.x ?? 100,
y: config?.y ?? 100,
width: config?.width ?? 400,
height: config?.height ?? 300,
zIndex: this.zCounter++,
minimized: false,
maximized: false
};
this.windows.set(id, win);
this.sm.broadcast("WindowFrom:created", win);
return win;
public createWindow(proc: IProcess, info: IWindowFormConfig): IWindowForm {
const window = new WindowFormImpl(proc, info);
this.windows.set(window.id, window);
return window;
}
closeWindow(id: string) {
public closeWindow(id: string) {
if (this.windows.has(id)) {
this.windows.delete(id);
this.sm.broadcast("WindowFrom:closed", id);
}
}
focusWindow(id: string) {
public focusWindow(id: string) {
const win = this.windows.get(id);
if (win) {
win.zIndex = this.zCounter++;
this.sm.broadcast("WindowFrom:focused", win);
}
}
minimizeWindow(id: string) {
public minimizeWindow(id: string) {
const win = this.windows.get(id);
if (win) {
win.minimized = true;
this.sm.broadcast("WindowFrom:minimized", win);
}
}
maximizeWindow(id: string) {
public maximizeWindow(id: string) {
const win = this.windows.get(id);
if (win) {
win.maximized = !win.maximized;
this.sm.broadcast("WindowFrom:maximized", win);
}
}
getWindows(): IWindow[] {
return Array.from(this.windows.values()).sort((a, b) => a.zIndex - b.zIndex);
}
onMessage(event: string, data?: any) {
console.log(`[WindowService] 收到事件:`, event, data);
}

View File

@@ -10,68 +10,69 @@ import type {
* 创建一个可观察对象,用于管理状态和事件。
* @template T - 需要处理的状态类型
* @example
* interface Todos {
* id: number
* text: string
* done: boolean
* }
*
* interface AppState {
* count: number
* todos: Todos[]
* user: {
* name: string
* age: number
* }
* items: number[]
* inc(): void
* }
*
* // 创建 ObservableImpl
* const obs = new ObservableImpl<AppState>({
* count: 0,
* user: { name: 'Alice', age: 20 },
* items: []
* todos: [],
* user: { name: "Alice", age: 20 },
* inc() {
* this.count++ // ✅ this 指向 obs.state
* },
* })
*
* // 1⃣ 全量订阅
* const unsubscribeAll = obs.subscribe(state => {
* console.log('全量订阅', state)
* }, { immediate: true })
* // ================== 使用示例 ==================
*
* // 2⃣ 单字段订阅
* const unsubscribeCount = obs.subscribeKey('count', ({ count }) => {
* console.log('count 字段变化:', count)
* // 1. 订阅整个 state
* obs.subscribe(state => {
* console.log("[全量订阅] state 更新:", state)
* })
*
* // 3⃣ 多字段订阅
* const unsubscribeUser = obs.subscribeKey(['user', 'count'], ({ user, count }) => {
* console.log('user 或 count 变化:', { user, count })
* // 2. 订阅单个字段
* obs.subscribeKey("count", ({ count }) => {
* console.log("[字段订阅] count 更新:", 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 }
* // 3. 订阅多个字段
* obs.subscribeKey(["name", "age"] as (keyof AppState["user"])[], (user) => {
* console.log("[多字段订阅] user 更新:", user)
* })
*
* // 7⃣ 解构赋值访问对象属性仍然触发订阅
* const { state } = obs
* state.user.age = 31 // ✅ 会触发 user 订阅
* // 4. 批量更新
* obs.patch({ count: 10, user: { name: "Bob", age: 30 } })
*
* // 8⃣ 取消订阅
* unsubscribeAll()
* unsubscribeCount()
* unsubscribeUser()
* // 5. 方法里操作 state
* obs.state.inc() // this.count++ → 相当于 obs.state.count++
*
* // 9⃣ 销毁 ObservableImpl
* obs.dispose()
* // 6. 数组操作
* obs.subscribeKey("todos", ({ todos }) => {
* console.log("[数组订阅] todos 更新:", todos.map(t => t.text))
* })
*
* obs.state.todos.push({ id: 1, text: "Buy milk", done: false })
* obs.state.todos.push({ id: 2, text: "Read book", done: false })
* obs.state.todos[0].done = true
*
* // 7. 嵌套对象
* obs.subscribeKey("user", ({ user }) => {
* console.log("[嵌套订阅] user 更新:", user)
* })
*
* obs.state.user.age++
*/
export class ObservableImpl<T extends TNonFunctionProperties<T>> implements IObservable<T> {
/** Observable 状态对象,深层 Proxy */
@@ -81,7 +82,7 @@ export class ObservableImpl<T extends TNonFunctionProperties<T>> implements IObs
private listeners: Set<TObservableListener<T>> = new Set()
/** 字段订阅函数集合 */
private keyListeners: Map<keyof T, Set<Function>> = new Map()
private keyListeners: Map<keyof T, Set<TObservableKeyListener<T, keyof T>>> = new Map()
/** 待通知的字段集合 */
private pendingKeys: Set<keyof T> = new Set()
@@ -92,56 +93,73 @@ export class ObservableImpl<T extends TNonFunctionProperties<T>> implements IObs
/** 是否已销毁 */
private disposed = false
/** 缓存 Proxy避免重复包装 */
private proxyCache: WeakMap<object, TObservableState<unknown>> = new WeakMap()
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)
/** 创建深层 Proxy拦截 get/set/delete并自动缓存 */
private makeReactive<O extends object>(obj: O): TObservableState<O> {
// 非对象直接返回(包括 null 已被排除)
if (typeof obj !== "object" || obj === null) {
return obj as unknown as TObservableState<O>
}
// 如果已有 Proxy 缓存则直接返回
const cached = this.proxyCache.get(obj as object)
if (cached !== undefined) {
return cached as TObservableState<O>
}
const handler: ProxyHandler<O> = {
get: (target, prop, receiver) => {
const value = Reflect.get(target, prop, receiver) as unknown
// 不包装函数
if (typeof value === "function") {
return value
}
// 对对象/数组继续进行响应式包装(递归)
if (typeof value === "object" && value !== null) {
return this.makeReactive(value as object)
}
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)
set: (target, prop, value, receiver) => {
// 读取旧值(使用 Record 以便类型安全访问属性)
const oldValue = (target as Record<PropertyKey, unknown>)[prop as PropertyKey] as unknown
const result = Reflect.set(target, prop, value as unknown, receiver)
// 仅在值改变时触发通知(基于引用/原始值比较)
if (!this.disposed && oldValue !== (value as unknown)) {
this.pendingKeys.add(prop as keyof T)
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
deleteProperty: (target, prop) => {
if (prop in target) {
// 使用 Reflect.deleteProperty 以保持一致性
const deleted = Reflect.deleteProperty(target, prop)
if (deleted && !this.disposed) {
this.pendingKeys.add(prop as keyof T)
this.scheduleNotify()
}
return deleted
}
return false
}
}
/** 安排下一次通知 */
const proxy = new Proxy(obj, handler) as TObservableState<O>
this.proxyCache.set(obj as object, proxy as TObservableState<unknown>)
return proxy
}
/** 安排下一次通知(微任务合并) */
private scheduleNotify(): void {
if (!this.notifyScheduled && !this.disposed) {
this.notifyScheduled = true
@@ -149,40 +167,70 @@ export class ObservableImpl<T extends TNonFunctionProperties<T>> implements IObs
}
}
/** 执行通知 */
/** 执行通知(聚合字段订阅并保证错误隔离) */
private flushNotify(): void {
if (this.disposed) return
const keys = Array.from(this.pendingKeys)
this.pendingKeys.clear()
this.notifyScheduled = false
// 全量订阅
// 全量订阅 —— 每个订阅单独 try/catch避免一个错误阻塞其它订阅
for (const fn of this.listeners) {
fn(this.state)
try {
fn(this.state as unknown as T)
} catch (err) {
// 可以根据需要把错误上报或自定义处理
// 这里简单打印以便调试
// eslint-disable-next-line no-console
console.error("Observable listener error:", err)
}
}
// 字段订阅
const fnMap = new Map<Function, (keyof T)[]>()
// 字段订阅:把同一个回调的多个 key 聚合到一次调用里
const fnMap: Map<TObservableKeyListener<T, keyof T>, Array<keyof T>> = 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)
const existing = fnMap.get(fn)
if (existing === undefined) {
fnMap.set(fn, [key])
} else {
existing.push(key)
}
}
}
// 调用每个字段订阅回调
fnMap.forEach((subKeys, fn) => {
const result = {} as Pick<T, typeof subKeys[number]>
subKeys.forEach(k => (result[k] = this.state[k]))
fn(result)
try {
// 构造 Pick<T, K> 风格的结果对象:结果类型为 Pick<T, (typeof subKeys)[number]>
const result = {} as Pick<T, (typeof subKeys)[number]>
subKeys.forEach(k => {
// 这里断言原因state 的索引访问返回 unknown但我们把它赋回到受限的 Pick 上
result[k] = (this.state as Record<keyof T, unknown>)[k] as T[(typeof k) & keyof T]
})
// 调用时类型上兼容 TObservableKeyListener<T, K>,因为我们传的是对应 key 的 Pick
fn(result as Pick<T, (typeof subKeys)[number]>)
} catch (err) {
// eslint-disable-next-line no-console
console.error("Observable keyListener error:", err)
}
})
}
/** 订阅整个状态变化 */
public subscribe(fn: TObservableListener<T>, options: { immediate?: boolean } = {}): () => void {
this.listeners.add(fn)
if (options.immediate) fn(this.state)
if (options.immediate) {
try {
fn(this.state as unknown as T)
} catch (err) {
// eslint-disable-next-line no-console
console.error("Observable subscribe immediate error:", err)
}
}
return () => {
this.listeners.delete(fn)
}
@@ -197,32 +245,48 @@ export class ObservableImpl<T extends TNonFunctionProperties<T>> implements IObs
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)
// 存储为 Set<TObservableKeyListener<T, keyof T>>
this.keyListeners.get(key)!.add(fn as TObservableKeyListener<T, keyof T>)
}
if (options.immediate) {
const result = {} as Pick<T, K>
keyArray.forEach(k => (result[k] = this.state[k]))
keyArray.forEach(k => {
result[k] = (this.state as Record<keyof T, unknown>)[k] as T[K]
})
try {
fn(result)
} catch (err) {
// eslint-disable-next-line no-console
console.error("Observable subscribeKey immediate error:", err)
}
}
return () => {
for (const key of keyArray) {
this.keyListeners.get(key)?.delete(fn)
this.keyListeners.get(key)?.delete(fn as TObservableKeyListener<T, keyof T>)
}
}
}
/** 批量更新状态 */
/** 批量更新状态(避免重复 schedule */
public patch(values: Partial<T>): void {
let changed = false
// 用 for..in 保持和对象字面量兼容(跳过原型链)
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)
const oldValue = (this.state as Record<keyof T, unknown>)[typedKey]
const newValue = values[typedKey] as unknown
if (oldValue !== newValue) {
// 直接写入 state会被 Proxy 的 set 捕获并安排通知
;(this.state as Record<keyof T, unknown>)[typedKey] = newValue
changed = true
}
}
this.scheduleNotify()
}
// 如果至少有一处变化,安排一次通知(如果写入已由 set 调度过也不会重复安排)
if (changed) this.scheduleNotify()
}
/** 销毁 Observable 实例 */
@@ -231,27 +295,30 @@ export class ObservableImpl<T extends TNonFunctionProperties<T>> implements IObs
this.listeners.clear()
this.keyListeners.clear()
this.pendingKeys.clear()
this.proxyCache = new WeakMap()
Object.freeze(this.state)
}
/** 语法糖:返回一个可解构赋值的 Proxy */
public toRefsProxy(): { [K in keyof T]: T[K] } {
const self = this
return new Proxy({} as T, {
return new Proxy({} as { [K in keyof T]: T[K] }, {
get(_, prop: string | symbol) {
const key = prop as keyof T
return self.state[key]
return (self.state as Record<keyof T, unknown>)[key] as T[typeof key]
},
set(_, prop: string | symbol, value) {
const key = prop as keyof T
self.state[key] = value
;(self.state as Record<keyof T, unknown>)[key] = value as unknown
return true
},
ownKeys() {
return Reflect.ownKeys(self.state)
},
getOwnPropertyDescriptor(_, prop: string | symbol) {
getOwnPropertyDescriptor(_, _prop: string | symbol) {
return { enumerable: true, configurable: true }
}
})
}
}

View File

@@ -10,6 +10,4 @@ export interface IWindowForm {
get windowFormEle(): HTMLElement;
/** 窗体状态 */
get windowFormState(): TWindowFormState;
/** 关闭窗体 */
closeWindowForm(): void;
}

View File

@@ -3,7 +3,7 @@ import XSystem from '../../XSystem.ts'
import type { IProcess } from '@/core/process/IProcess.ts'
import type { IWindowForm } from '@/core/window/IWindowForm.ts'
import type { IWindowFormConfig } from '@/core/window/types/IWindowFormConfig.ts'
import type { WindowFormPos } from '@/core/window/types/WindowFormTypes.ts'
import type { TWindowFormState, WindowFormPos } from '@/core/window/types/WindowFormTypes.ts'
import { processManager } from '@/core/process/ProcessManager.ts'
import { DraggableResizableWindow } from '@/core/utils/DraggableResizableWindow.ts'
import '../css/window-form.scss'
@@ -13,31 +13,43 @@ import { wfem } from '@/core/events/WindowFormEventManager.ts'
import type { IObservable } from '@/core/state/IObservable.ts'
import { ObservableImpl } from '@/core/state/impl/ObservableImpl.ts'
export interface IWindowFormDataState {
/** 窗体id */
id: string;
/** 窗体进程id */
procId: string;
/** 进程名称唯一 */
name: string;
/** 窗体位置x (左上角) */
x: number;
/** 窗体位置y (左上角) */
y: number;
/** 窗体宽度 */
width: number;
/** 窗体高度 */
height: number;
/** 窗体状态 'default' | 'minimized' | 'maximized' */
state: TWindowFormState;
/** 窗体是否已关闭 */
closed: boolean;
}
export default class WindowFormImpl implements IWindowForm {
private readonly _id: string = uuidV4()
private readonly _procId: string
private readonly _proc: IProcess;
private dom: HTMLElement
private drw: DraggableResizableWindow
private pos: WindowFormPos = { x: 0, y: 0 }
private width: number
private height: number
private _state: IObservable<{ x: number, y: number }> = new ObservableImpl({
x: 0,
y: 0,
})
private _data: IObservable<IWindowFormDataState>;
public get id() {
return this._id
}
public get proc() {
return processManager.findProcessById(this._procId)
return this._proc
}
private get desktopRootDom() {
return XSystem.instance.desktopRootDom
}
private get sm() {
return serviceManager.getService('WindowForm')
}
public get windowFormEle() {
return this.dom
}
@@ -46,27 +58,35 @@ export default class WindowFormImpl implements IWindowForm {
}
constructor(proc: IProcess, config: IWindowFormConfig) {
this._procId = proc.id
this._proc = proc
console.log('WindowForm')
this.pos = {
this._data = new ObservableImpl<IWindowFormDataState>({
id: this.id,
procId: proc.id,
name: proc.processInfo.name,
x: config.left ?? 0,
y: config.top ?? 0,
}
this.width = config.width ?? 200
this.height = config.height ?? 100
width: config.width ?? 200,
height: config.height ?? 100,
state: 'default',
closed: false
})
this.createWindowFrom()
this.initEvent()
this.createWindowFrom()
}
private initEvent() {
wfem.addEventListener('windowFormClose', this.windowFormCloseFun)
}
private windowFormCloseFun = (id: string) => {
if (id === this.id) {
this._data.subscribeKey('closed', (state) => {
console.log('closed', state)
this.closeWindowForm()
}
this._proc.closeWindowForm(this.id)
})
// this._data.subscribeKey(['x', 'y'], (state) => {
// console.log('x,y', state)
// })
}
private createWindowFrom() {
@@ -96,8 +116,8 @@ export default class WindowFormImpl implements IWindowForm {
// this.desktopRootDom.appendChild(this.dom);
const wf = document.createElement('window-form-element')
wf.pos = this._state
wf.wid = this.id
wf.wfData = this._data
wf.dragContainer = document.body
wf.snapDistance = 20
wf.taskbarElementId = '#taskbar'
@@ -111,21 +131,24 @@ export default class WindowFormImpl implements IWindowForm {
console.log('windowForm:stateChange:restore', e)
})
wf.addManagedEventListener('windowForm:close', () => {
this.closeWindowForm()
// this.closeWindowForm()
})
this.dom = wf
this.desktopRootDom.appendChild(this.dom)
wfem.notifyEvent('windowFormFocus', this.id)
}
public closeWindowForm() {
private closeWindowForm() {
// this.drw.destroy();
this.desktopRootDom.removeChild(this.dom)
this.proc?.event.notifyEvent('onProcessWindowFormExit', this.id)
wfem.removeEventListener('windowFormClose', this.windowFormCloseFun)
this._data.dispose()
// wfem.notifyEvent('windowFormClose', this.id)
}
public minimize() {}
public maximize() {}
public restore() {}
private createWindowFormEle() {
const template = document.createElement('template')
template.innerHTML = `

View File

@@ -4,6 +4,7 @@ import wfStyle from './wf.scss?inline'
import type { TWindowFormState } from '@/core/window/types/WindowFormTypes.ts'
import { wfem } from '@/core/events/WindowFormEventManager.ts'
import type { IObservable } from '@/core/state/IObservable.ts'
import type { IWindowFormDataState } from '@/core/window/impl/WindowFormImpl.ts'
/** 拖拽移动开始的回调 */
type TDragStartCallback = (x: number, y: number) => void;
@@ -84,7 +85,7 @@ export class WindowFormElement extends LitElement {
@property({ type: Number }) maxHeight?: number
@property({ type: Number }) minHeight?: number
@property({ type: String }) taskbarElementId?: string
@property({ type: Object }) pos: IObservable<{ x: number, y: number }>;
@property({ type: Object }) wfData: IObservable<IWindowFormDataState>;
private _listeners: Array<{ type: string; handler: EventListener }> = []
@@ -107,6 +108,19 @@ export class WindowFormElement extends LitElement {
private animationFrame?: number
private resizing = false
// private get x() {
// return this.wfData.state.x
// }
// private set x(value: number) {
// this.wfData.patch({ x: value })
// }
// private get y() {
// return this.wfData.state.y
// }
// private set y(value: number) {
// this.wfData.patch({ y: value })
// }
// private windowFormState: TWindowFormState = 'default';
/** 元素信息 */
private targetBounds: IElementRect
@@ -687,6 +701,7 @@ export class WindowFormElement extends LitElement {
composed: true,
}),
)
this.wfData.state.closed = true
}
/**