Compare commits

...

10 Commits

Author SHA1 Message Date
12f46e6f8e 保存 2025-09-24 11:30:06 +08:00
16b4b27352 优化 2025-09-22 13:23:12 +08:00
e3ff2045ea 优化 2025-09-19 11:49:04 +08:00
fd4f9aa66b WindowFormElement 2025-09-19 10:35:46 +08:00
62b4ae7379 WindowFormImpl 2025-09-19 09:57:14 +08:00
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
122fba228a WindowFormElement 2025-09-16 14:32:57 +08:00
46 changed files with 2107 additions and 855 deletions

View File

@@ -1,18 +0,0 @@
<template>
<div id="root" ref="root-dom" class="w-100vw h-100vh"></div>
</template>
<script setup lang="ts">
import XSystem from '@/core/XSystem.ts'
import { onMounted, useTemplateRef } from 'vue'
const dom = useTemplateRef<HTMLDivElement>('root-dom')
onMounted(() => {
XSystem.instance.initialization(dom.value!);
})
</script>
<style scoped>
</style>

View File

@@ -0,0 +1,65 @@
import { onMounted, onBeforeUnmount, type Ref, watch } from "vue";
interface ClickFocusOptions {
once?: boolean; // 点击一次后解绑
}
/**
* Vue3 Hook点击自身聚焦 / 点击外部失焦
* @param targetRef 元素的 ref
* @param onFocus 点击自身回调
* @param onBlur 点击外部回调
* @param options 配置项 { once }
*/
export function useClickFocus(
targetRef: Ref<HTMLElement | null>,
onFocus?: () => void,
onBlur?: () => void,
options: ClickFocusOptions = {}
) {
let cleanupFn: (() => void) | null = null;
const bindEvents = (el: HTMLElement) => {
if (!el.hasAttribute("tabindex")) el.setAttribute("tabindex", "0");
const handleClick = (e: MouseEvent) => {
if (!el.isConnected) return cleanup();
if (el.contains(e.target as Node)) {
el.focus();
onFocus?.();
} else {
el.blur();
onBlur?.();
}
if (options.once) cleanup();
};
document.addEventListener("click", handleClick);
cleanupFn = () => {
document.removeEventListener("click", handleClick);
cleanupFn = null;
};
};
const cleanup = () => {
cleanupFn?.();
};
onMounted(() => {
const el = targetRef.value;
if (el) bindEvents(el);
});
onBeforeUnmount(() => {
cleanup();
});
// 支持动态 ref 变化
watch(targetRef, (newEl, oldEl) => {
if (oldEl) cleanup();
if (newEl) bindEvents(newEl);
});
}

View 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
}

View File

@@ -0,0 +1,10 @@
import {
create,
NButton,
NCard,
NConfigProvider,
} from 'naive-ui'
export const naiveUi = create({
components: [NButton, NCard, NConfigProvider]
})

View File

@@ -0,0 +1,21 @@
import { createDiscreteApi } from 'naive-ui'
import { configProviderProps } from './theme.ts'
const { message, notification, dialog, loadingBar, modal } = createDiscreteApi(
['message', 'dialog', 'notification', 'loadingBar', 'modal'],
{
configProviderProps: configProviderProps,
notificationProviderProps: {
placement: 'bottom-right',
max: 3
}
}
)
export const { messageApi, notificationApi, dialogApi, loadingBarApi, modalApi } = {
messageApi: message,
notificationApi: notification,
dialogApi: dialog,
loadingBarApi: loadingBar,
modalApi: modal
}

View File

@@ -0,0 +1,15 @@
import { type ConfigProviderProps, darkTheme, dateZhCN, type GlobalTheme, lightTheme, zhCN } from 'naive-ui'
const lTheme: GlobalTheme = {
...lightTheme,
common: {
...lightTheme.common,
primaryColor: '#0070f3'
}
}
export const configProviderProps: ConfigProviderProps = {
theme: lTheme,
dateLocale: dateZhCN,
locale: zhCN,
}

View File

@@ -0,0 +1,8 @@
/**
* 可销毁接口
* 销毁实例,清理副作用,让内存可以被回收
*/
export interface IDestroyable {
/** 销毁实例,清理副作用,让内存可以被回收 */
destroy(): void
}

View File

@@ -0,0 +1,29 @@
/**
* 版本信息
*/
export interface IVersion {
/**
* 公司名称
*/
company: string
/**
* 版本号
*/
major: number
/**
* 子版本号
*/
minor: number
/**
* 修订号
*/
build: number
/**
* 私有版本号
*/
private: number
}

View File

@@ -1,27 +1,14 @@
import ProcessImpl from './process/impl/ProcessImpl.ts'
import { isUndefined } from 'lodash'
import { BasicSystemProcess } from '@/core/system/BasicSystemProcess.ts' import { BasicSystemProcess } from '@/core/system/BasicSystemProcess.ts'
import { DesktopProcess } from '@/core/desktop/DesktopProcess.ts' import { DesktopProcess } from '@/core/desktop/DesktopProcess.ts'
import type { IProcess } from '@/core/process/IProcess.ts'
import type { IProcessInfo } from '@/core/process/IProcessInfo.ts'
import { ObservableWeakRefImpl } from '@/core/state/impl/ObservableWeakRefImpl.ts'
import type { IObservable } from '@/core/state/IObservable.ts'
import { NotificationService } from '@/core/service/services/NotificationService.ts' import { NotificationService } from '@/core/service/services/NotificationService.ts'
import { SettingsService } from '@/core/service/services/SettingsService.ts' import { SettingsService } from '@/core/service/services/SettingsService.ts'
import { WindowFormService } from '@/core/service/services/WindowFormService.ts' import { WindowFormService } from '@/core/service/services/WindowFormService.ts'
import { UserService } from '@/core/service/services/UserService.ts' import { UserService } from '@/core/service/services/UserService.ts'
import { processManager } from '@/core/process/ProcessManager.ts' import { processManager } from '@/core/process/ProcessManager.ts'
interface IGlobalState {
isLogin: boolean
}
export default class XSystem { export default class XSystem {
private static _instance: XSystem = new XSystem() private static _instance: XSystem = new XSystem()
private _globalState: IObservable<IGlobalState> = new ObservableWeakRefImpl<IGlobalState>({
isLogin: false
})
private _desktopRootDom: HTMLElement; private _desktopRootDom: HTMLElement;
constructor() { constructor() {
@@ -35,44 +22,13 @@ export default class XSystem {
public static get instance() { public static get instance() {
return this._instance return this._instance
} }
public get globalState() {
return this._globalState
}
public get desktopRootDom() { public get desktopRootDom() {
return this._desktopRootDom return this._desktopRootDom
} }
public initialization(dom: HTMLDivElement) { public async initialization(dom: HTMLDivElement) {
this._desktopRootDom = dom this._desktopRootDom = dom
this.run('basic-system', BasicSystemProcess).then(() => { await processManager.runProcess('basic-system', BasicSystemProcess)
this.run('desktop', DesktopProcess).then((proc) => { await processManager.runProcess('desktop', DesktopProcess, dom)
proc.mount(dom)
// console.log(dom.querySelector('.desktop-root'))
})
})
}
// 运行进程
public async run<T extends IProcess = IProcess>(
proc: string | IProcessInfo,
constructor?: new (info: IProcessInfo) => T,
): Promise<T> {
let info = typeof proc === 'string' ? processManager.findProcessInfoByName(proc)! : proc
if (isUndefined(info)) {
throw new Error(`未找到进程信息:${proc}`)
}
// 是单例应用
if (info.singleton) {
let process = processManager.findProcessByName(info.name)
if (process) {
return process as T
}
}
// 创建进程
let process = isUndefined(constructor) ? new ProcessImpl(info) : new constructor(info)
return process as T
} }
} }

View File

@@ -0,0 +1,8 @@
/**
* 可销毁接口
* 销毁实例,清理副作用,让内存可以被回收
*/
export interface IDestroyable {
/** 销毁实例,清理副作用,让内存可以被回收 */
destroy(): void
}

View File

@@ -5,92 +5,78 @@ import DesktopComponent from '@/core/desktop/ui/DesktopComponent.vue'
import { naiveUi } from '@/core/common/naive-ui/components.ts' import { naiveUi } from '@/core/common/naive-ui/components.ts'
import { debounce } from 'lodash' import { debounce } from 'lodash'
import type { IProcessInfo } from '@/core/process/IProcessInfo.ts' import type { IProcessInfo } from '@/core/process/IProcessInfo.ts'
import { eventManager } from '@/core/events/EventManager.ts'
import { processManager } from '@/core/process/ProcessManager.ts' import { processManager } from '@/core/process/ProcessManager.ts'
import './ui/DesktopElement.ts'
import { ObservableImpl } from '@/core/state/impl/ObservableImpl.ts'
interface IDesktopDataState {
/** 显示器宽度 */
monitorWidth: number;
/** 显示器高度 */
monitorHeight: number;
}
export class DesktopProcess extends ProcessImpl { export class DesktopProcess extends ProcessImpl {
private _desktopRootDom: HTMLElement; /** 桌面根dom类似显示器 */
private _isMounted: boolean = false; private readonly _monitorDom: HTMLElement
private _width: number = 0; private _isMounted: boolean = false
private _height: number = 0; private _data = new ObservableImpl<IDesktopDataState>({
private _pendingResize: boolean = false; monitorWidth: 0,
monitorHeight: 0,
})
public get desktopRootDom() { public get monitorDom() {
return this._desktopRootDom; return this._monitorDom
} }
public get isMounted() { public get isMounted() {
return this._isMounted; return this._isMounted
} }
public get basicSystemProcess() { public get basicSystemProcess() {
return processManager.findProcessByName<BasicSystemProcess>('basic-system') return processManager.findProcessByName<BasicSystemProcess>('basic-system')
} }
public get width() { get data() {
return this._width; return this._data
}
public set width(value: number) {
if (this._height === value) return;
if (!this._isMounted) return;
this._width = value;
this._desktopRootDom.style.width = value >= 0 ? `${value}px` : '100%';
this.scheduleResizeEvent()
}
public get height() {
return this._height;
}
public set height(value: number) {
if (this._height === value) return;
if (!this._isMounted) return;
this._height = value;
this._desktopRootDom.style.height = value >= 0 ? `${value}px` : '100%';
this.scheduleResizeEvent()
} }
private scheduleResizeEvent() { constructor(info: IProcessInfo, dom: HTMLDivElement) {
if (this._pendingResize) return;
this._pendingResize = true;
Promise.resolve().then(() => {
if (this._pendingResize) {
this._pendingResize = false;
console.log('onDesktopRootDomResize')
eventManager.notifyEvent('onDesktopRootDomResize', this._width, this._height);
}
});
}
constructor(info: IProcessInfo) {
super(info) super(info)
console.log('DesktopProcess') console.log('DesktopProcess')
}
public mount(dom: HTMLDivElement) {
console.log('DesktopProcess: start mount')
if (this._isMounted) return
this._width = window.innerWidth
this._height = window.innerHeight
window.addEventListener(
'resize',
debounce(() => {
this.width = window.innerWidth
this.height = window.innerHeight
}, 300)
)
dom.style.zIndex = '0';
dom.style.width = `${this._width}px`
dom.style.height = `${this._height}px`
dom.style.position = 'relative' dom.style.position = 'relative'
dom.style.overflow = 'hidden' dom.style.overflow = 'hidden'
this._desktopRootDom = dom dom.style.width = `${window.innerWidth}px`
dom.style.height = `${window.innerHeight}px`
this._monitorDom = dom
this._data.state.monitorWidth = window.innerWidth
this._data.state.monitorHeight = window.innerHeight
window.addEventListener('resize', this.onResize)
this.createDesktopUI()
}
private onResize = debounce(() => {
this._monitorDom.style.width = `${window.innerWidth}px`
this._monitorDom.style.height = `${window.innerHeight}px`
this._data.state.monitorWidth = window.innerWidth
this._data.state.monitorHeight = window.innerHeight
}, 300)
private createDesktopUI() {
if (this._isMounted) return
const app = createApp(DesktopComponent, { process: this }) const app = createApp(DesktopComponent, { process: this })
app.use(naiveUi) app.use(naiveUi)
app.mount(dom) app.mount(this._monitorDom)
this._isMounted = true this._isMounted = true
} }
private initDesktop(dom: HTMLDivElement) {
const d = document.createElement('desktop-element')
dom.appendChild(d)
}
override destroy() {
super.destroy()
window.removeEventListener('resize', this.onResize)
}
} }

View File

@@ -5,16 +5,20 @@
> >
<div class="desktop-root" @contextmenu="onContextMenu"> <div class="desktop-root" @contextmenu="onContextMenu">
<div class="desktop-bg"> <div class="desktop-bg">
<div class="desktop-icons-container" <div class="desktop-icons-container" :style="gridStyle">
:style="gridStyle"> <AppIcon
<AppIcon v-for="(appIcon, i) in appIconsRef" :key="i" v-for="(appIcon, i) in appIconsRef"
:iconInfo="appIcon" :gridTemplate="gridTemplate" :key="i"
:iconInfo="appIcon"
:gridTemplate="gridTemplate"
@dblclick="runApp(appIcon)" @dblclick="runApp(appIcon)"
/> />
</div> </div>
</div> </div>
<div class="task-bar"> <div class="task-bar">
<div id="taskbar" class="w-[80px] h-full flex justify-center items-center bg-blue">测试</div> <div id="taskbar" class="w-[80px] h-full flex justify-center items-center bg-blue">
测试
</div>
</div> </div>
</div> </div>
</n-config-provider> </n-config-provider>
@@ -22,35 +26,46 @@
<script setup lang="ts"> <script setup lang="ts">
import type { DesktopProcess } from '@/core/desktop/DesktopProcess.ts' import type { DesktopProcess } from '@/core/desktop/DesktopProcess.ts'
import XSystem from '@/core/XSystem.ts'
import { notificationApi } from '@/core/common/naive-ui/discrete-api.ts' import { notificationApi } from '@/core/common/naive-ui/discrete-api.ts'
import { configProviderProps } from '@/core/common/naive-ui/theme.ts' import { configProviderProps } from '@/core/common/naive-ui/theme.ts'
import { useDesktopInit } from '@/core/desktop/ui/hooks/useDesktopInit.ts' import { useDesktopInit } from '@/core/desktop/ui/hooks/useDesktopInit.ts'
import AppIcon from '@/core/desktop/ui/components/AppIcon.vue' import AppIcon from '@/core/desktop/ui/components/AppIcon.vue'
import type { IDesktopAppIcon } from '@/core/desktop/types/IDesktopAppIcon.ts' import type { IDesktopAppIcon } from '@/core/desktop/types/IDesktopAppIcon.ts'
import { eventManager } from '@/core/events/EventManager.ts' import { eventManager } from '@/core/events/EventManager.ts'
import { processManager } from '@/core/process/ProcessManager.ts'
const props = defineProps<{ process: DesktopProcess }>() const props = defineProps<{ process: DesktopProcess }>()
const { appIconsRef, gridStyle, gridTemplate } = useDesktopInit('.desktop-icons-container') props.process.data.subscribeKey(['monitorWidth', 'monitorHeight'], ({monitorWidth, monitorHeight}) => {
console.log('onDesktopRootDomResize', monitorWidth, monitorHeight)
eventManager.addEventListener('onDesktopRootDomResize',
(width, height) => {
console.log(width, height)
notificationApi.create({ notificationApi.create({
title: '桌面通知', title: '桌面通知',
content: `桌面尺寸变化${width}x${height}}`, content: `桌面尺寸变化${monitorWidth}x${monitorHeight}}`,
duration: 2000, duration: 2000,
}) })
}, })
)
// props.process.data.subscribe((data) => {
// console.log('desktopData', data.monitorWidth)
// })
const { appIconsRef, gridStyle, gridTemplate } = useDesktopInit('.desktop-icons-container')
// eventManager.addEventListener('onDesktopRootDomResize', (width, height) => {
// console.log(width, height)
// notificationApi.create({
// title: '桌面通知',
// content: `桌面尺寸变化${width}x${height}}`,
// duration: 2000,
// })
// })
const onContextMenu = (e: MouseEvent) => { const onContextMenu = (e: MouseEvent) => {
e.preventDefault() e.preventDefault()
} }
const runApp = (appIcon: IDesktopAppIcon) => { const runApp = (appIcon: IDesktopAppIcon) => {
XSystem.instance.run(appIcon.name) processManager.runProcess(appIcon.name)
} }
</script> </script>
@@ -61,7 +76,7 @@ $taskBarHeight: 40px;
.desktop-bg { .desktop-bg {
@apply w-full h-full flex-1 p-2 pos-relative; @apply w-full h-full flex-1 p-2 pos-relative;
background-image: url("imgs/desktop-bg-2.jpeg"); background-image: url('imgs/desktop-bg-2.jpeg');
background-repeat: no-repeat; background-repeat: no-repeat;
background-size: cover; background-size: cover;
height: calc(100% - #{$taskBarHeight}); height: calc(100% - #{$taskBarHeight});

View File

@@ -0,0 +1,35 @@
import { css, html, LitElement, unsafeCSS } from 'lit'
import { customElement } from 'lit/decorators.js'
import desktopStyle from './css/desktop.scss?inline'
@customElement('desktop-element')
export class DesktopElement extends LitElement {
static override styles = css`
${unsafeCSS(desktopStyle)}
`
private onContextMenu = (e: MouseEvent) => {
e.preventDefault()
e.stopPropagation()
console.log('contextmenu')
}
override render() {
return html`
<div class="desktop-root" @contextmenu=${this.onContextMenu}>
<div class="desktop-container">
<div class="desktop-icons-container"
:style="gridStyle">
<AppIcon v-for="(appIcon, i) in appIconsRef" :key="i"
:iconInfo="appIcon" :gridTemplate="gridTemplate"
@dblclick="runApp(appIcon)"
/>
</div>
</div>
<div class="task-bar">
<div id="taskbar" class="w-[80px] h-full flex justify-center items-center bg-blue">测试</div>
</div>
</div>
`
}
}

View File

@@ -0,0 +1,17 @@
import { css, html, LitElement } from 'lit'
export class DesktopAppIconElement extends LitElement {
static override styles = css`
:host {
width: 100%;
height: 100%;
@apply flex flex-col items-center justify-center bg-gray-200;
}
`
override render() {
return html`<div class="desktop-app-icon">
<slot></slot>
</div>`
}
}

View File

@@ -0,0 +1,31 @@
*,
*::before,
*::after {
box-sizing: border-box; /* 使用更直观的盒模型 */
margin: 0;
padding: 0;
}
$taskBarHeight: 40px;
.desktop-root {
@apply w-full h-full flex flex-col;
.desktop-container {
@apply w-full h-full flex-1 p-2 pos-relative;
background-image: url("../imgs/desktop-bg-2.jpeg");
background-repeat: no-repeat;
background-size: cover;
height: calc(100% - #{$taskBarHeight});
}
.desktop-icons-container {
@apply w-full h-full flex-1 grid grid-auto-flow-col pos-relative;
}
.task-bar {
@apply w-full bg-gray-200 flex justify-center items-center;
height: $taskBarHeight;
flex-shrink: 0;
}
}

View File

@@ -1,3 +1,5 @@
import type { IDestroyable } from '@/core/common/types/IDestroyable.ts'
/** /**
* 事件定义 * 事件定义
* @interface IEventMap 事件定义 键是事件名称,值是事件处理函数 * @interface IEventMap 事件定义 键是事件名称,值是事件处理函数
@@ -9,7 +11,7 @@ export interface IEventMap {
/** /**
* 事件管理器接口定义 * 事件管理器接口定义
*/ */
export interface IEventBuilder<Events extends IEventMap> { export interface IEventBuilder<Events extends IEventMap> extends IDestroyable {
/** /**
* 添加事件监听 * 添加事件监听
* @param eventName 事件名称 * @param eventName 事件名称

View File

@@ -0,0 +1,61 @@
import { EventBuilderImpl } from '@/core/events/impl/EventBuilderImpl.ts'
import type { IEventMap } from '@/core/events/IEventBuilder.ts'
import type { TWindowFormState } from '@/core/window/types/WindowFormTypes.ts'
/**
* 窗口的事件
*/
export interface WindowFormEvent extends IEventMap {
/**
* 窗口最小化
* @param id 窗口id
*/
windowFormMinimize: (id: string) => void;
/**
* 窗口最大化
* @param id 窗口id
*/
windowFormMaximize: (id: string) => void;
/**
* 窗口还原
* @param id 窗口id
*/
windowFormRestore: (id: string) => void;
/**
* 窗口关闭
* @param id 窗口id
*/
windowFormClose: (id: string) => void;
/**
* 窗口聚焦
* @param id 窗口id
*/
windowFormFocus: (id: string) => void;
/**
* 窗口数据更新
* @param data 窗口数据
*/
windowFormDataUpdate: (data: IWindowFormDataUpdateParams) => void;
/**
* 窗口创建完成
*/
windowFormCreated: () => void;
}
interface IWindowFormDataUpdateParams {
/** 窗口id */
id: string;
/** 窗口状态 */
state: TWindowFormState,
/** 窗口宽度 */
width: number,
/** 窗口高度 */
height: number,
/** 窗口x坐标(左上角) */
x: number,
/** 窗口y坐标(左上角) */
y: number
}
/** 窗口事件管理器 */
export const wfem = new EventBuilderImpl<WindowFormEvent>()

View File

@@ -5,9 +5,7 @@ interface HandlerWrapper<T extends (...args: any[]) => any> {
once: boolean once: boolean
} }
export class EventBuilderImpl<Events extends IEventMap> export class EventBuilderImpl<Events extends IEventMap> implements IEventBuilder<Events> {
implements IEventBuilder<Events>
{
private _eventHandlers = new Map<keyof Events, Set<HandlerWrapper<Events[keyof Events]>>>() private _eventHandlers = new Map<keyof Events, Set<HandlerWrapper<Events[keyof Events]>>>()
/** /**
@@ -24,9 +22,9 @@ export class EventBuilderImpl<Events extends IEventMap>
eventName: E, eventName: E,
handler: F, handler: F,
options?: { options?: {
immediate?: boolean; immediate?: boolean
immediateArgs?: Parameters<F>; immediateArgs?: Parameters<F>
once?: boolean; once?: boolean
}, },
) { ) {
if (!handler) return if (!handler) return
@@ -91,4 +89,8 @@ export class EventBuilderImpl<Events extends IEventMap>
} }
} }
} }
destroy() {
this._eventHandlers.clear()
}
} }

View File

@@ -1,12 +1,13 @@
import type { IProcessInfo } from '@/core/process/IProcessInfo.ts' import type { IProcessInfo } from '@/core/process/IProcessInfo.ts'
import type { IWindowForm } from '@/core/window/IWindowForm.ts' import type { IWindowForm } from '@/core/window/IWindowForm.ts'
import type { IEventBuilder } from '@/core/events/IEventBuilder.ts' import type { IEventBuilder } from '@/core/events/IEventBuilder.ts'
import type { IProcessEvent } from '@/core/process/types/ProcessEvent.ts' import type { IProcessEvent } from '@/core/process/types/ProcessEventTypes.ts'
import type { IDestroyable } from '@/core/common/types/IDestroyable.ts'
/** /**
* 进程接口 * 进程接口
*/ */
export interface IProcess { export interface IProcess extends IDestroyable {
/** 进程id */ /** 进程id */
get id(): string; get id(): string;
/** 进程信息 */ /** 进程信息 */
@@ -19,4 +20,9 @@ export interface IProcess {
* @param startName 窗体启动名 * @param startName 窗体启动名
*/ */
openWindowForm(startName: string): void; openWindowForm(startName: string): void;
/**
* 关闭窗体
* @param id 窗体id
*/
closeWindowForm(id: string): void;
} }

View File

@@ -6,7 +6,7 @@ import type { IWindowForm } from '@/core/window/IWindowForm.ts'
import { processManager } from '@/core/process/ProcessManager.ts' import { processManager } from '@/core/process/ProcessManager.ts'
import { EventBuilderImpl } from '@/core/events/impl/EventBuilderImpl.ts' import { EventBuilderImpl } from '@/core/events/impl/EventBuilderImpl.ts'
import type { IEventBuilder } from '@/core/events/IEventBuilder.ts' import type { IEventBuilder } from '@/core/events/IEventBuilder.ts'
import type { IProcessEvent } from '@/core/process/types/ProcessEvent.ts' import type { IProcessEvent } from '@/core/process/types/ProcessEventTypes.ts'
/** /**
* 进程 * 进程
@@ -47,7 +47,7 @@ export default class ProcessImpl implements IProcess {
} }
private initEvent() { private initEvent() {
this.event.addEventListener('onProcessWindowFormExit', (id: string) => { this.event.addEventListener('processWindowFormExit', (id: string) => {
this.windowForms.delete(id) this.windowForms.delete(id)
if(this.windowForms.size === 0) { if(this.windowForms.size === 0) {
processManager.removeProcess(this) processManager.removeProcess(this)
@@ -58,7 +58,26 @@ export default class ProcessImpl implements IProcess {
public openWindowForm(startName: string) { public openWindowForm(startName: string) {
const info = this._processInfo.windowFormConfigs.find(item => item.name === startName); const info = this._processInfo.windowFormConfigs.find(item => item.name === startName);
if (!info) throw new Error(`未找到窗体:${startName}`); if (!info) throw new Error(`未找到窗体:${startName}`);
const window = new WindowFormImpl(this, info); const wf = new WindowFormImpl(this, info);
this._windowForms.set(window.id, window); this._windowForms.set(wf.id, wf);
}
public closeWindowForm(id: string) {
try {
const wf = this._windowForms.get(id);
if (!wf) throw new Error(`未找到窗体:${id}`);
wf.destroy();
this.windowForms.delete(id)
if(this.windowForms.size === 0) {
this.destroy()
processManager.removeProcess(this)
}
} catch (e) {
console.log('关闭窗体失败', e)
}
}
public destroy() {
this._event.destroy()
} }
} }

View File

@@ -1,4 +1,4 @@
import type ProcessImpl from './ProcessImpl.ts' import ProcessImpl from './ProcessImpl.ts'
import { ProcessInfoImpl } from '@/core/process/impl/ProcessInfoImpl.ts' import { ProcessInfoImpl } from '@/core/process/impl/ProcessInfoImpl.ts'
import { BasicSystemProcessInfo } from '@/core/system/BasicSystemProcessInfo.ts' import { BasicSystemProcessInfo } from '@/core/system/BasicSystemProcessInfo.ts'
import { DesktopProcessInfo } from '@/core/desktop/DesktopProcessInfo.ts' import { DesktopProcessInfo } from '@/core/desktop/DesktopProcessInfo.ts'
@@ -6,6 +6,8 @@ import type { IAppProcessInfoParams } from '@/core/process/types/IAppProcessInfo
import type { IProcessManager } from '@/core/process/IProcessManager.ts' import type { IProcessManager } from '@/core/process/IProcessManager.ts'
import type { IProcess } from '@/core/process/IProcess.ts' import type { IProcess } from '@/core/process/IProcess.ts'
import type { IProcessInfo } from '@/core/process/IProcessInfo.ts' import type { IProcessInfo } from '@/core/process/IProcessInfo.ts'
import { processManager } from '@/core/process/ProcessManager.ts'
import { isUndefined } from 'lodash'
/** /**
* 进程管理 * 进程管理
@@ -35,6 +37,30 @@ export default class ProcessManagerImpl implements IProcessManager {
this._processInfos.push(...internalProcessInfos) this._processInfos.push(...internalProcessInfos)
} }
public async runProcess<T extends IProcess = IProcess, A extends any[] = any[]>(
proc: string | IProcessInfo,
constructor?: new (info: IProcessInfo, ...args: A) => T,
...args: A
): Promise<T> {
let info = typeof proc === 'string' ? this.findProcessInfoByName(proc) : proc
if (isUndefined(info)) {
throw new Error(`未找到进程信息:${proc}`)
}
// 是单例应用
if (info.singleton) {
let process = this.findProcessByName(info.name)
if (process) {
return process as T
}
}
// 创建进程
let process = isUndefined(constructor) ? new ProcessImpl(info) : new constructor(info, ...args)
return process as T
}
// 添加进程 // 添加进程
public registerProcess(process: ProcessImpl) { public registerProcess(process: ProcessImpl) {
this._processPool.set(process.id, process); this._processPool.set(process.id, process);

View File

@@ -20,5 +20,5 @@ export interface IProcessEvent extends IEventMap {
* 退 * 退
* @param id id * @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 { 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 { interface IWindow {
id: string; id: string;
@@ -13,67 +17,47 @@ interface IWindow {
} }
export class WindowFormService extends AService { export class WindowFormService extends AService {
private windows: Map<string, IWindow> = new Map(); private windows: Map<string, IWindowForm> = new Map();
private zCounter = 1;
constructor() { constructor() {
super("WindowForm"); super("WindowFormService");
console.log('WindowFormService - 服务注册') console.log('WindowFormService - 服务注册')
} }
createWindow(title: string, config?: Partial<IWindow>): IWindow { public createWindow(proc: IProcess, info: IWindowFormConfig): IWindowForm {
const id = `win-${Date.now()}-${Math.random()}`; const window = new WindowFormImpl(proc, info);
const win: IWindow = { this.windows.set(window.id, window);
id, return window;
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;
} }
closeWindow(id: string) { public closeWindow(id: string) {
if (this.windows.has(id)) { if (this.windows.has(id)) {
this.windows.delete(id); this.windows.delete(id);
this.sm.broadcast("WindowFrom:closed", id); this.sm.broadcast("WindowFrom:closed", id);
} }
} }
focusWindow(id: string) { public focusWindow(id: string) {
const win = this.windows.get(id); const win = this.windows.get(id);
if (win) { if (win) {
win.zIndex = this.zCounter++;
this.sm.broadcast("WindowFrom:focused", win); this.sm.broadcast("WindowFrom:focused", win);
} }
} }
minimizeWindow(id: string) { public minimizeWindow(id: string) {
const win = this.windows.get(id); const win = this.windows.get(id);
if (win) { if (win) {
win.minimized = true;
this.sm.broadcast("WindowFrom:minimized", win); this.sm.broadcast("WindowFrom:minimized", win);
} }
} }
maximizeWindow(id: string) { public maximizeWindow(id: string) {
const win = this.windows.get(id); const win = this.windows.get(id);
if (win) { if (win) {
win.maximized = !win.maximized;
this.sm.broadcast("WindowFrom:maximized", win); 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) { onMessage(event: string, data?: any) {
console.log(`[WindowService] 收到事件:`, event, data); console.log(`[WindowService] 收到事件:`, event, data);
} }

View File

@@ -10,68 +10,69 @@ import type {
* 创建一个可观察对象,用于管理状态和事件。 * 创建一个可观察对象,用于管理状态和事件。
* @template T - 需要处理的状态类型 * @template T - 需要处理的状态类型
* @example * @example
* interface Todos {
* id: number
* text: string
* done: boolean
* }
*
* interface AppState { * interface AppState {
* count: number * count: number
* todos: Todos[]
* user: { * user: {
* name: string * name: string
* age: number * age: number
* } * }
* items: number[] * inc(): void
* } * }
* *
* // 创建 ObservableImpl
* const obs = new ObservableImpl<AppState>({ * const obs = new ObservableImpl<AppState>({
* count: 0, * count: 0,
* user: { name: 'Alice', age: 20 }, * todos: [],
* items: [] * user: { name: "Alice", age: 20 },
* inc() {
* this.count++ // ✅ this 指向 obs.state
* },
* }) * })
* *
* // 1⃣ 全量订阅 * // ================== 使用示例 ==================
* const unsubscribeAll = obs.subscribe(state => {
* console.log('全量订阅', state)
* }, { immediate: true })
* *
* // 2⃣ 单字段订阅 * // 1. 订阅整个 state
* const unsubscribeCount = obs.subscribeKey('count', ({ count }) => { * obs.subscribe(state => {
* console.log('count 字段变化:', count) * console.log("[全量订阅] state 更新:", state)
* }) * })
* *
* // 3⃣ 多字段订阅 * // 2. 订阅单个字段
* const unsubscribeUser = obs.subscribeKey(['user', 'count'], ({ user, count }) => { * obs.subscribeKey("count", ({ count }) => {
* console.log('user 或 count 变化:', { user, count }) * console.log("[字段订阅] count 更新:", count)
* }) * })
* *
* // 4⃣ 修改属性 * // 3. 订阅多个字段
* obs.state.count = 1 // ✅ 会触发 count 和全量订阅 * obs.subscribeKey(["name", "age"] as (keyof AppState["user"])[], (user) => {
* obs.state.user.age = 21 // ✅ 深层对象修改触发 user 订阅 * console.log("[多字段订阅] user 更新:", 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⃣ 解构赋值访问对象属性仍然触发订阅 * // 4. 批量更新
* const { state } = obs * obs.patch({ count: 10, user: { name: "Bob", age: 30 } })
* state.user.age = 31 // ✅ 会触发 user 订阅
* *
* // 8⃣ 取消订阅 * // 5. 方法里操作 state
* unsubscribeAll() * obs.state.inc() // this.count++ → 相当于 obs.state.count++
* unsubscribeCount()
* unsubscribeUser()
* *
* // 9⃣ 销毁 ObservableImpl * // 6. 数组操作
* obs.dispose() * 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> { export class ObservableImpl<T extends TNonFunctionProperties<T>> implements IObservable<T> {
/** Observable 状态对象,深层 Proxy */ /** Observable 状态对象,深层 Proxy */
@@ -80,8 +81,13 @@ export class ObservableImpl<T extends TNonFunctionProperties<T>> implements IObs
/** 全量订阅函数集合 */ /** 全量订阅函数集合 */
private listeners: Set<TObservableListener<T>> = new Set() private listeners: Set<TObservableListener<T>> = new Set()
/** 字段订阅函数集合 */ /**
private keyListeners: Map<keyof T, Set<Function>> = new Map() * 字段订阅函数集合
* 新结构:
* Map<TObservableKeyListener, Array<keyof T>>
* 记录每个回调订阅的字段数组,保证多字段订阅 always 返回所有订阅字段值
*/
private keyListeners: Map<TObservableKeyListener<T, keyof T>, Array<keyof T>> = new Map()
/** 待通知的字段集合 */ /** 待通知的字段集合 */
private pendingKeys: Set<keyof T> = new Set() private pendingKeys: Set<keyof T> = new Set()
@@ -92,166 +98,208 @@ export class ObservableImpl<T extends TNonFunctionProperties<T>> implements IObs
/** 是否已销毁 */ /** 是否已销毁 */
private disposed = false private disposed = false
/** 缓存 Proxy避免重复包装 */
private proxyCache: WeakMap<object, TObservableState<unknown>> = new WeakMap()
constructor(initialState: TNonFunctionProperties<T>) { constructor(initialState: TNonFunctionProperties<T>) {
// 创建深层响应式 Proxy // 创建深层响应式 Proxy
this.state = this.makeReactive(initialState) as TObservableState<T> this.state = this.makeReactive(initialState) as TObservableState<T>
} }
/** 创建深层 Proxy拦截 get/set */ /** 创建深层 Proxy拦截 get/set/delete并自动缓存 */
private makeReactive(obj: TNonFunctionProperties<T>): TObservableState<T> { private makeReactive<O extends object>(obj: O): TObservableState<O> {
const handler: ProxyHandler<any> = { // 非对象直接返回(包括 null 已被排除)
get: (target, prop: string | symbol, receiver) => { if (typeof obj !== "object" || obj === null) {
const key = prop as keyof T return obj as unknown as TObservableState<O>
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 缓存则直接返回
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 return value
}, },
set: (target, prop: string | symbol, value, receiver) => {
const key = prop as keyof T set: (target, prop, value, receiver) => {
const oldValue = target[key] // 读取旧值(使用 Record 以便类型安全访问属性)
if (oldValue !== value) { const oldValue = (target as Record<PropertyKey, unknown>)[prop as PropertyKey] as unknown
target[key] = value const result = Reflect.set(target, prop, value as unknown, receiver)
this.pendingKeys.add(key) // 仅在值改变时触发通知(基于引用/原始值比较)
if (!this.disposed && oldValue !== (value as unknown)) {
this.pendingKeys.add(prop as keyof T)
this.scheduleNotify() 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 return result
}, },
writable: true,
configurable: true, deleteProperty: (target, prop) => {
}) if (prop in target) {
}) // 使用 Reflect.deleteProperty 以保持一致性
return arr 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 { private scheduleNotify(): void {
if (!this.notifyScheduled && !this.disposed) { if (!this.notifyScheduled && !this.disposed && this.pendingKeys.size > 0) {
this.notifyScheduled = true this.notifyScheduled = true
Promise.resolve().then(() => this.flushNotify()) Promise.resolve().then(() => this.flushNotify())
} }
} }
/** 执行通知 */ /** 执行通知(聚合字段订阅并保证错误隔离) */
private flushNotify(): void { private flushNotify(): void {
if (this.disposed) return if (this.disposed) return
const keys = Array.from(this.pendingKeys)
this.pendingKeys.clear() this.pendingKeys.clear()
this.notifyScheduled = false this.notifyScheduled = false
// 全量订阅 // 全量订阅 —— 每个订阅单独 try/catch避免一个错误阻塞其它订阅
for (const fn of this.listeners) { for (const fn of this.listeners) {
fn(this.state) try {
} fn(this.state as unknown as T)
} catch (err) {
// 字段订阅 console.error("Observable listener error:", err)
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])) this.keyListeners.forEach((subKeys, fn) => {
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) {
console.error("Observable keyListener error:", err)
}
}) })
} }
/** 订阅整个状态变化 */ /** 订阅整个状态变化 */
subscribe(fn: TObservableListener<T>, options: { immediate?: boolean } = {}): () => void { public subscribe(fn: TObservableListener<T>, options: { immediate?: boolean } = {}): () => void {
this.listeners.add(fn) this.listeners.add(fn)
if (options.immediate) fn(this.state) if (options.immediate) {
try {
fn(this.state as unknown as T)
} catch (err) {
console.error("Observable subscribe immediate error:", err)
}
}
return () => { return () => {
this.listeners.delete(fn) this.listeners.delete(fn)
} }
} }
/** 订阅指定字段变化 */ /** 订阅指定字段变化(多字段订阅 always 返回所有字段值) */
subscribeKey<K extends keyof T>( public subscribeKey<K extends keyof T>(
keys: K | K[], keys: K | K[],
fn: TObservableKeyListener<T, K>, fn: TObservableKeyListener<T, K>,
options: { immediate?: boolean } = {} options: { immediate?: boolean } = {}
): () => void { ): () => void {
const keyArray = Array.isArray(keys) ? keys : [keys] 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)
}
// ================== 存储回调和它订阅的字段数组 ==================
this.keyListeners.set(fn as TObservableKeyListener<T, keyof T>, keyArray as (keyof T)[])
// ================== 立即调用 ==================
if (options.immediate) { if (options.immediate) {
const result = {} as Pick<T, K> 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) fn(result)
} catch (err) {
console.error("Observable subscribeKey immediate error:", err)
}
} }
// ================== 返回取消订阅函数 ==================
return () => { return () => {
for (const key of keyArray) { this.keyListeners.delete(fn as TObservableKeyListener<T, keyof T>)
this.keyListeners.get(key)?.delete(fn)
}
} }
} }
/** 批量更新状态 */ /** 批量更新状态(避免重复 schedule */
patch(values: Partial<T>): void { public patch(values: Partial<T>): void {
let changed = false
for (const key in values) { for (const key in values) {
if (Object.prototype.hasOwnProperty.call(values, key)) { if (Object.prototype.hasOwnProperty.call(values, key)) {
const typedKey = key as keyof T const typedKey = key as keyof T
this.state[typedKey] = values[typedKey]! const oldValue = (this.state as Record<keyof T, unknown>)[typedKey]
this.pendingKeys.add(typedKey) const newValue = values[typedKey] as unknown
if (oldValue !== newValue) {
(this.state as Record<keyof T, unknown>)[typedKey] = newValue
changed = true
} }
} }
this.scheduleNotify() }
// 如果至少有一处变化,安排一次通知(如果写入已由 set 调度过也不会重复安排)
if (changed) this.scheduleNotify()
} }
/** 销毁 Observable 实例 */ /** 销毁 Observable 实例 */
dispose(): void { public dispose(): void {
this.disposed = true this.disposed = true
this.listeners.clear() this.listeners.clear()
this.keyListeners.clear() this.keyListeners.clear()
this.pendingKeys.clear() this.pendingKeys.clear()
this.proxyCache = new WeakMap()
Object.freeze(this.state)
} }
/** 语法糖:返回一个可解构赋值的 Proxy */ /** 语法糖:返回一个可解构赋值的 Proxy */
toRefsProxy(): { [K in keyof T]: T[K] } { public toRefsProxy(): { [K in keyof T]: T[K] } {
const self = this const self = this
return new Proxy({} as T, { return new Proxy({} as { [K in keyof T]: T[K] }, {
get(_, prop: string | symbol) { get(_, prop: string | symbol) {
const key = prop as keyof T 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) { set(_, prop: string | symbol, value) {
const key = prop as keyof T const key = prop as keyof T
self.state[key] = value ;(self.state as Record<keyof T, unknown>)[key] = value as unknown
return true return true
}, },
ownKeys() { ownKeys() {
return Reflect.ownKeys(self.state) return Reflect.ownKeys(self.state)
}, },
getOwnPropertyDescriptor(_, prop: string | symbol) { getOwnPropertyDescriptor(_, _prop: string | symbol) {
return { enumerable: true, configurable: true } return { enumerable: true, configurable: true }
} }
}) })
} }
} }

View File

@@ -0,0 +1,14 @@
import { ObservableImpl } from '@/core/state/impl/ObservableImpl.ts'
interface IGlobalStoreParams {
/** 桌面根dom ID类似显示器 */
monitorDomId: string;
monitorWidth: number;
monitorHeight: number;
}
export const globalStore = new ObservableImpl<IGlobalStoreParams>({
monitorDomId: '#app',
monitorWidth: 0,
monitorHeight: 0
})

View File

@@ -734,6 +734,7 @@ export class DraggableResizableWindow {
* 销毁实例 * 销毁实例
*/ */
public destroy() { public destroy() {
try {
if (this.handle) this.handle.removeEventListener('mousedown', this.onMouseDownDrag); if (this.handle) this.handle.removeEventListener('mousedown', this.onMouseDownDrag);
this.target.removeEventListener('mousedown', this.onMouseDownResize); this.target.removeEventListener('mousedown', this.onMouseDownResize);
document.removeEventListener('mousemove', this.onMouseMoveDragRAF); document.removeEventListener('mousemove', this.onMouseMoveDragRAF);
@@ -746,5 +747,6 @@ export class DraggableResizableWindow {
this.resizeObserver?.disconnect(); this.resizeObserver?.disconnect();
this.mutationObserver.disconnect(); this.mutationObserver.disconnect();
cancelAnimationFrame(this.animationFrame ?? 0); cancelAnimationFrame(this.animationFrame ?? 0);
} catch (e) {}
} }
} }

View File

@@ -1,7 +1,8 @@
import type { IProcess } from '@/core/process/IProcess.ts' import type { IProcess } from '@/core/process/IProcess.ts'
import type { TWindowFormState } from '@/core/window/types/WindowFormTypes.ts' import type { TWindowFormState } from '@/core/window/types/WindowFormTypes.ts'
import type { IDestroyable } from '@/core/common/types/IDestroyable.ts'
export interface IWindowForm { export interface IWindowForm extends IDestroyable {
/** 窗体id */ /** 窗体id */
get id(): string; get id(): string;
/** 窗体所属的进程 */ /** 窗体所属的进程 */
@@ -10,6 +11,4 @@ export interface IWindowForm {
get windowFormEle(): HTMLElement; get windowFormEle(): HTMLElement;
/** 窗体状态 */ /** 窗体状态 */
get windowFormState(): TWindowFormState; get windowFormState(): TWindowFormState;
/** 关闭窗体 */
closeWindowForm(): void;
} }

View File

@@ -1,63 +0,0 @@
$titleBarHeight: 40px;
/* 窗体容器 */
.window {
width: 100%;
height: 100%;
border: 1px solid #666;
box-shadow: 0 0 10px rgba(0,0,0,0.5);
background-color: #ffffff;
overflow: hidden;
border-radius: 5px;
}
/* 标题栏 */
.title-bar {
display: flex;
justify-content: space-between;
align-items: center;
user-select: none;
width: 100%;
height: $titleBarHeight;
.title {
display: block;
padding: 0 5px;
flex-grow: 1;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
font-size: 18px;
line-height: $titleBarHeight;
}
.window-controls {
display: flex;
gap: 2px;
flex-shrink: 0;
.btn {
width: 40px;
height: 40px;
padding: 0;
cursor: pointer;
font-size: 24px;
color: black;
display: flex;
align-items: center;
justify-content: center;
transition: background-color 0.3s ease;
&:hover {
@apply bg-gray-200;
}
}
}
}
/* 窗体内容 */
.window-content {
width: 100%;
height: calc(100% - #{$titleBarHeight});
background-color: #e0e0e0;
}

View File

@@ -3,128 +3,112 @@ import XSystem from '../../XSystem.ts'
import type { IProcess } from '@/core/process/IProcess.ts' import type { IProcess } from '@/core/process/IProcess.ts'
import type { IWindowForm } from '@/core/window/IWindowForm.ts' import type { IWindowForm } from '@/core/window/IWindowForm.ts'
import type { IWindowFormConfig } from '@/core/window/types/IWindowFormConfig.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 { DraggableResizableWindow } from '@/core/utils/DraggableResizableWindow.ts'
import '../css/window-form.scss'
import { serviceManager } from '@/core/service/kernel/ServiceManager.ts'
import '../ui/WindowFormElement.ts' import '../ui/WindowFormElement.ts'
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;
/** 窗体标题 */
title: string;
/** 窗体位置x (左上角) */
x: number;
/** 窗体位置y (左上角) */
y: number;
/** 窗体宽度 */
width: number;
/** 窗体高度 */
height: number;
/** 窗体状态 'default' | 'minimized' | 'maximized' */
state: TWindowFormState;
/** 窗体是否已关闭 */
closed: boolean;
}
export default class WindowFormImpl implements IWindowForm { export default class WindowFormImpl implements IWindowForm {
private readonly _id: string = uuidV4(); private readonly _id: string = uuidV4()
private readonly _procId: string; private readonly _proc: IProcess
private dom: HTMLElement; private readonly _data: IObservable<IWindowFormDataState>
private drw: DraggableResizableWindow; private dom: HTMLElement
private pos: WindowFormPos = { x: 0, y: 0 }; private drw: DraggableResizableWindow
private width: number;
private height: number;
public get id() { public get id() {
return this._id; return this._id
} }
public get proc() { public get proc() {
return processManager.findProcessById(this._procId) return this._proc
} }
private get desktopRootDom() { private get desktopRootDom() {
return XSystem.instance.desktopRootDom; return XSystem.instance.desktopRootDom
}
private get sm() {
return serviceManager.getService('WindowForm')
} }
public get windowFormEle() { public get windowFormEle() {
return this.dom; return this.dom
} }
public get windowFormState() { public get windowFormState() {
return this.drw.windowFormState return this.drw.windowFormState
} }
constructor(proc: IProcess, config: IWindowFormConfig) { constructor(proc: IProcess, config: IWindowFormConfig) {
this._procId = proc.id; this._proc = proc
console.log('WindowForm') console.log('WindowForm')
this.pos = {
x: config.left ?? 0,
y: config.top ?? 0
}
this.width = config.width ?? 200;
this.height = config.height ?? 100;
this.createWindowFrom(); this._data = new ObservableImpl<IWindowFormDataState>({
id: this.id,
procId: proc.id,
name: proc.processInfo.name,
title: config.title ?? '未命名',
x: config.left ?? 0,
y: config.top ?? 0,
width: config.width ?? 200,
height: config.height ?? 100,
state: 'default',
closed: false,
})
this.initEvent()
this.createWindowFrom()
}
private initEvent() {
this._data.subscribeKey('closed', (state) => {
console.log('closed', state)
this.closeWindowForm()
this._proc.closeWindowForm(this.id)
})
} }
private createWindowFrom() { private createWindowFrom() {
this.dom = this.createWindowFormEle();
this.dom.style.position = 'absolute';
this.dom.style.width = `${this.width}px`;
this.dom.style.height = `${this.height}px`;
this.dom.style.zIndex = '10';
const header = this.dom.querySelector('.title-bar') as HTMLElement;
const content = this.dom.querySelector('.window-content') as HTMLElement;
this.drw = new DraggableResizableWindow({
target: this.dom,
handle: header,
snapAnimation: true,
snapThreshold: 20,
boundaryElement: document.body,
taskbarElementId: '#taskbar',
onWindowStateChange: (state) => {
if (state === 'maximized') {
this.dom.style.borderRadius = '0px';
} else {
this.dom.style.borderRadius = '5px';
}
},
})
// this.desktopRootDom.appendChild(this.dom);
const wf = document.createElement('window-form-element') const wf = document.createElement('window-form-element')
wf.wid = this.id
wf.wfData = this._data
wf.title = this._data.state.title
wf.dragContainer = document.body wf.dragContainer = document.body
wf.snapDistance = 20 wf.snapDistance = 20
wf.addEventListener('windowForm:dragStart', (e) => { wf.taskbarElementId = '#taskbar'
console.log('dragstart', e) this.dom = wf
this.desktopRootDom.appendChild(this.dom)
Promise.resolve().then(() => {
wfem.notifyEvent('windowFormCreated')
wfem.notifyEvent('windowFormFocus', this.id)
}) })
this.desktopRootDom.appendChild(wf)
} }
public closeWindowForm() { private closeWindowForm() {
this.drw.destroy(); this.desktopRootDom.removeChild(this.dom)
this.desktopRootDom.removeChild(this.dom); this._data.dispose()
this.proc?.event.notifyEvent('onProcessWindowFormExit', this.id)
} }
private createWindowFormEle() { public minimize() {}
const template = document.createElement('template'); public maximize() {}
template.innerHTML = ` public restore() {}
<div class="window">
<div class="title-bar">
<div class="title">我的窗口</div>
<div class="window-controls">
<div class="minimize btn" title="最小化"">-</div>
<div class="maximize btn" title="最大化">□</div>
<div class="close btn" title="关闭">×</div>
</div>
</div>
<div class="window-content"></div>
</div>
`
const fragment = template.content.cloneNode(true) as DocumentFragment;
const windowElement = fragment.firstElementChild as HTMLElement
windowElement.querySelector('.btn.minimize') public destroy() {}
?.addEventListener('click', () => this.drw.minimize());
windowElement.querySelector('.btn.maximize')
?.addEventListener('click', () => {
if (this.drw.windowFormState === 'maximized') {
this.drw.restore()
} else {
this.drw.maximize()
}
});
windowElement.querySelector('.btn.close')
?.addEventListener('click', () => this.closeWindowForm());
return windowElement
}
} }

File diff suppressed because it is too large Load Diff

View File

@@ -1,3 +1,11 @@
*,
*::before,
*::after {
box-sizing: border-box; /* 使用更直观的盒模型 */
margin: 0;
padding: 0;
}
:host { :host {
position: absolute; position: absolute;
top: 0; top: 0;
@@ -9,6 +17,21 @@
--shadow: 0 10px 30px rgba(0,0,0,0.25); --shadow: 0 10px 30px rgba(0,0,0,0.25);
font-family: system-ui, "Segoe UI", Roboto, "Helvetica Neue", Arial; font-family: system-ui, "Segoe UI", Roboto, "Helvetica Neue", Arial;
} }
:host([focused]) {
z-index: 11;
.window {
border-color: #8338ec;
}
}
:host([windowFormState='maximized']) {
.window {
border-radius: 0;
box-shadow: none;
}
}
.window { .window {
position: absolute; position: absolute;
box-shadow: var(--shadow, 0 10px 30px rgba(0,0,0,0.25)); box-shadow: var(--shadow, 0 10px 30px rgba(0,0,0,0.25));
@@ -20,17 +43,22 @@
flex-direction: column; flex-direction: column;
width: 100%; width: 100%;
height: 100%; height: 100%;
&.focus {
border-color: #3a86ff;
}
} }
.titlebar { .titlebar {
height: var(--titlebar-height, 32px); height: var(--titlebar-height);
display: flex; display: flex;
align-items: center; align-items: center;
padding: 0 8px; padding: 0 8px;
gap: 8px; gap: 8px;
background: linear-gradient(#f2f2f2, #e9e9e9); background: linear-gradient(#f2f2f2, #e9e9e9);
border-bottom: 1px solid rgba(0,0,0,0.06); border-bottom: 1px solid rgba(0,0,0,0.06);
}
.title { .title {
font-size: 13px; font-size: 13px;
font-weight: 600; font-weight: 600;
flex: 1; flex: 1;
@@ -38,9 +66,12 @@
overflow: hidden; overflow: hidden;
text-overflow: ellipsis; text-overflow: ellipsis;
color: #111; color: #111;
} }
.controls { display: flex; gap: 6px; }
button.ctrl { .controls {
display: flex; gap: 6px;
button.ctrl {
width: 34px; width: 34px;
height: 24px; height: 24px;
border: none; border: none;
@@ -49,8 +80,14 @@ button.ctrl {
cursor: pointer; cursor: pointer;
font-weight: 600; font-weight: 600;
font-size: 12px; font-size: 12px;
&:hover {
background: rgba(0,0,0,0.06);
}
}
}
} }
button.ctrl:hover { background: rgba(0,0,0,0.06); }
.content { flex: 1; overflow: auto; padding: 12px; background: transparent; } .content { flex: 1; overflow: auto; padding: 12px; background: transparent; }
.resizer { position: absolute; z-index: 20; } .resizer { position: absolute; z-index: 20; }
@@ -62,16 +99,3 @@ button.ctrl:hover { background: rgba(0,0,0,0.06); }
.resizer.tl { width: 12px; height: 12px; left: -6px; top: -6px; cursor: nwse-resize; } .resizer.tl { width: 12px; height: 12px; left: -6px; top: -6px; cursor: nwse-resize; }
.resizer.br { width: 12px; height: 12px; right: -6px; bottom: -6px; cursor: nwse-resize; } .resizer.br { width: 12px; height: 12px; right: -6px; bottom: -6px; cursor: nwse-resize; }
.resizer.bl { width: 12px; height: 12px; left: -6px; bottom: -6px; cursor: nesw-resize; } .resizer.bl { width: 12px; height: 12px; left: -6px; bottom: -6px; cursor: nesw-resize; }
.minimized {
height: var(--titlebar-height, 32px);
width: 200px;
display: inline-flex;
align-items: center;
gap: 8px;
padding: 0 8px;
border-radius: 4px;
background: linear-gradient(#f6f6f6,#efefef);
border: 1px solid rgba(0,0,0,0.06);
cursor: pointer;
}

View File

@@ -0,0 +1,16 @@
import { EventBuilderImpl } from '@/events/impl/EventBuilderImpl.ts'
import type { IEventMap } from '@/events/IEventBuilder.ts'
import type { IDesktopAppIcon } from '@/ui/types/IDesktopAppIcon.ts'
/**
* 桌面相关的事件
*/
export interface IDesktopEvent extends IEventMap {
/**
* 桌面应用位置改变
*/
desktopAppPosChange: (info: IDesktopAppIcon) => void;
}
/** 窗口事件管理器 */
export const desktopEM = new EventBuilderImpl<IDesktopEvent>()

View File

@@ -0,0 +1,35 @@
import { EventBuilderImpl } from '@/core/events/impl/EventBuilderImpl.ts'
import type { IEventMap } from '@/core/events/IEventBuilder.ts'
import type { IDesktopAppIcon } from '@/core/desktop/types/IDesktopAppIcon.ts'
export const eventManager = new EventBuilderImpl<IAllEvent>()
/**
* 系统进程的事件
* @description
* <p>onAuthChange - 认证状态改变</p>
* <p>onThemeChange - 主题改变</p>
*/
export interface IBasicSystemEvent extends IEventMap {
/** 认证状态改变 */
onAuthChange: () => {},
/** 主题改变 */
onThemeChange: (theme: string) => void
}
/**
* 桌面进程的事件
* @description
* <p>onDesktopRootDomResize - 桌面根dom尺寸改变</p>
* <p>onDesktopProcessInitialize - 桌面进程初始化完成</p>
*/
export interface IDesktopEvent extends IEventMap {
/** 桌面根dom尺寸改变 */
onDesktopRootDomResize: (width: number, height: number) => void
/** 桌面进程初始化完成 */
onDesktopProcessInitialize: () => void
/** 桌面应用图标位置改变 */
onDesktopAppIconPos: (iconInfo: IDesktopAppIcon) => void
}
export interface IAllEvent extends IDesktopEvent, IBasicSystemEvent {}

View File

@@ -0,0 +1,47 @@
import type { IDestroyable } from '@/core/common/types/IDestroyable.ts'
/**
* 事件定义
* @interface IEventMap 事件定义 键是事件名称,值是事件处理函数
*/
export interface IEventMap {
[key: string]: (...args: any[]) => void
}
/**
* 事件管理器接口定义
*/
export interface IEventBuilder<Events extends IEventMap> extends IDestroyable {
/**
* 添加事件监听
* @param eventName 事件名称
* @param handler 事件处理函数
* @param options 配置项 { immediate: 立即执行一次 immediateArgs: 立即执行的参数 once: 只监听一次 }
* @returns void
*/
addEventListener<E extends keyof Events, F extends Events[E]>(
eventName: E,
handler: F,
options?: {
immediate?: boolean
immediateArgs?: Parameters<F>
once?: boolean
},
): void
/**
* 移除事件监听
* @param eventName 事件名称
* @param handler 事件处理函数
* @returns void
*/
removeEventListener<E extends keyof Events, F extends Events[E]>(eventName: E, handler: F): void
/**
* 触发事件
* @param eventName 事件名称
* @param args 参数
* @returns void
*/
notifyEvent<E extends keyof Events, F extends Events[E]>(eventName: E, ...args: Parameters<F>): void
}

View File

@@ -0,0 +1,61 @@
import { EventBuilderImpl } from '@/events/impl/EventBuilderImpl.ts'
import type { IEventMap } from '@/events/IEventBuilder.ts'
import type { TWindowFormState } from '@/ui/types/WindowFormTypes.ts'
/**
* 窗口的事件
*/
export interface IWindowFormEvent extends IEventMap {
/**
* 窗口最小化
* @param id 窗口id
*/
windowFormMinimize: (id: string) => void;
/**
* 窗口最大化
* @param id 窗口id
*/
windowFormMaximize: (id: string) => void;
/**
* 窗口还原
* @param id 窗口id
*/
windowFormRestore: (id: string) => void;
/**
* 窗口关闭
* @param id 窗口id
*/
windowFormClose: (id: string) => void;
/**
* 窗口聚焦
* @param id 窗口id
*/
windowFormFocus: (id: string) => void;
/**
* 窗口数据更新
* @param data 窗口数据
*/
windowFormDataUpdate: (data: IWindowFormDataUpdateParams) => void;
/**
* 窗口创建完成
*/
windowFormCreated: () => void;
}
interface IWindowFormDataUpdateParams {
/** 窗口id */
id: string;
/** 窗口状态 */
state: TWindowFormState,
/** 窗口宽度 */
width: number,
/** 窗口高度 */
height: number,
/** 窗口x坐标(左上角) */
x: number,
/** 窗口y坐标(左上角) */
y: number
}
/** 窗口事件管理器 */
export const wfem = new EventBuilderImpl<IWindowFormEvent>()

View File

@@ -0,0 +1,96 @@
import type { IEventBuilder, IEventMap } from '@/core/events/IEventBuilder.ts'
interface HandlerWrapper<T extends (...args: any[]) => any> {
fn: T
once: boolean
}
export class EventBuilderImpl<Events extends IEventMap> implements IEventBuilder<Events> {
private _eventHandlers = new Map<keyof Events, Set<HandlerWrapper<Events[keyof Events]>>>()
/**
* 添加事件监听器
* @param eventName 事件名称
* @param handler 监听器
* @param options { immediate: 立即执行一次 immediateArgs: 立即执行的参数 once: 只监听一次 }
* @example
* eventBus.addEventListener('noArgs', () => {})
* eventBus.addEventListener('greet', name => {}, { immediate: true, immediateArgs: ['abc'] })
* eventBus.addEventListener('onResize', (w, h) => {}, { immediate: true, immediateArgs: [1, 2] })
*/
addEventListener<E extends keyof Events, F extends Events[E]>(
eventName: E,
handler: F,
options?: {
immediate?: boolean
immediateArgs?: Parameters<F>
once?: boolean
},
) {
if (!handler) return
if (!this._eventHandlers.has(eventName)) {
this._eventHandlers.set(eventName, new Set<HandlerWrapper<F>>())
}
const set = this._eventHandlers.get(eventName)!
if (![...set].some((wrapper) => wrapper.fn === handler)) {
set.add({ fn: handler, once: options?.once ?? false })
}
if (options?.immediate) {
try {
handler(...(options.immediateArgs ?? []))
} catch (e) {
console.error(e)
}
}
}
/**
* 移除事件监听器
* @param eventName 事件名称
* @param handler 监听器
* @example
* eventBus.removeEventListener('noArgs', () => {})
*/
removeEventListener<E extends keyof Events, F extends Events[E]>(eventName: E, handler: F) {
const set = this._eventHandlers.get(eventName)
if (!set) return
for (const wrapper of set) {
if (wrapper.fn === handler) {
set.delete(wrapper)
}
}
}
/**
* 通知事件
* @param eventName 事件名称
* @param args 参数
* @example
* eventBus.notifyEvent('noArgs')
* eventBus.notifyEvent('greet', 'Alice')
* eventBus.notifyEvent('onResize', 1, 2)
*/
notifyEvent<E extends keyof Events, F extends Events[E]>(eventName: E, ...args: Parameters<F>) {
if (!this._eventHandlers.has(eventName)) return
const set = this._eventHandlers.get(eventName)!
for (const wrapper of set) {
try {
wrapper.fn(...args)
} catch (e) {
console.error(e)
}
if (wrapper.once) {
set.delete(wrapper)
}
}
}
destroy() {
this._eventHandlers.clear()
}
}

View File

@@ -1,16 +1,15 @@
import { createApp } from 'vue' import { createApp } from 'vue'
import { createPinia } from 'pinia' import { createPinia } from 'pinia'
import { naiveUi } from '@/common/naive-ui/components.ts'
import 'virtual:uno.css' import 'virtual:uno.css'
import './css/basic.css' import './css/basic.css'
// import App from './App.vue' import App from './ui/App.vue'
// const app = createApp(App) const app = createApp(App)
//
// app.use(createPinia())
//
// app.mount('#app')
import XSystem from '@/core/XSystem.ts' app.use(createPinia())
XSystem.instance.initialization(document.querySelector('#app')!); app.use(naiveUi)
app.mount('#app')

53
src/ui/App.vue Normal file
View File

@@ -0,0 +1,53 @@
<template>
<n-config-provider
:config-provider-props="configProviderProps"
class="pos-relative w-screen h-vh"
>
<div class="desktop-root" @contextmenu="onContextMenu">
<div class="desktop-bg">
<DesktopContainer/>
</div>
<div class="task-bar">
<div id="taskbar" class="w-[80px] h-full flex justify-center items-center bg-blue">
测试
</div>
</div>
</div>
</n-config-provider>
</template>
<script setup lang="ts">
import { configProviderProps } from '@/core/common/naive-ui/theme.ts'
import DesktopContainer from '@/ui/desktop-container/DesktopContainer.vue'
const onContextMenu = (e: MouseEvent) => {
e.preventDefault()
e.stopPropagation()
console.log(e)
}
</script>
<style lang="scss" scoped>
$taskBarHeight: 40px;
.desktop-root {
@apply w-full h-full flex flex-col;
.desktop-bg {
@apply w-full h-full flex-1 p-2 pos-relative;
background-image: url('imgs/desktop-bg-2.jpeg');
background-repeat: no-repeat;
background-size: cover;
height: calc(100% - #{$taskBarHeight});
}
.desktop-icons-container {
@apply w-full h-full flex-1 grid grid-auto-flow-col pos-relative;
}
.task-bar {
@apply w-full bg-gray-200 flex justify-center items-center;
height: $taskBarHeight;
flex-shrink: 0;
}
}
</style>

View File

@@ -0,0 +1,52 @@
<template>
<div
class="icon-container"
:style="`grid-column: ${iconInfo.x}/${iconInfo.x + 1};grid-row: ${iconInfo.y}/${iconInfo.y + 1};`"
draggable="true"
@dragstart="onDragStart"
@dragend="onDragEnd"
>
{{ iconInfo.name }}
</div>
</template>
<script setup lang="ts">
import type { IDesktopAppIcon } from '@/ui/types/IDesktopAppIcon.ts'
import type { IGridTemplateParams } from '@/ui/types/IGridTemplateParams.ts'
const { iconInfo, gridTemplate } = defineProps<{ iconInfo: IDesktopAppIcon, gridTemplate: IGridTemplateParams }>()
const onDragStart = (e: DragEvent) => {}
const onDragEnd = (e: DragEvent) => {
const el = e.target as HTMLElement | null
if (!el) return
// 鼠标所在位置已存在图标元素
const pointTarget = document.elementFromPoint(e.clientX, e.clientY)
if (!pointTarget) return
if (pointTarget.classList.contains('icon-container')) return
if (!pointTarget.classList.contains('desktop-icons-container')) return
// 获取容器边界
const rect = el.parentElement!.getBoundingClientRect()
// 鼠标相对容器左上角坐标
const mouseX = e.clientX - rect.left
const mouseY = e.clientY - rect.top
// 计算鼠标所在单元格坐标向上取整从1开始
const gridX = Math.ceil(mouseX / gridTemplate.cellRealWidth)
const gridY = Math.ceil(mouseY / gridTemplate.cellRealHeight)
iconInfo.x = gridX
iconInfo.y = gridY
}
</script>
<style scoped lang="scss">
.icon-container {
width: 100%;
height: 100%;
@apply flex flex-col items-center justify-center bg-gray-200;
}
</style>

View File

@@ -0,0 +1,23 @@
<template>
<div class="desktop-icons-container" :style="gridStyle">
<AppIcon
v-for="(appIcon, i) in appIconsRef"
:key="i"
:iconInfo="appIcon"
:gridTemplate="gridTemplate"
@dblclick="runApp(appIcon)"
/>
</div>
</template>
<script setup lang="ts">
import AppIcon from '@/ui/desktop-container/AppIcon.vue'
import type { IDesktopAppIcon } from '@/ui/types/IDesktopAppIcon.ts'
import { useDesktopContainerInit } from '@/ui/desktop-container/useDesktopContainerInit.ts'
const { appIconsRef, gridStyle, gridTemplate } = useDesktopContainerInit('.desktop-icons-container')
const runApp = (appIcon: IDesktopAppIcon) => {}
</script>
<style scoped></style>

View File

@@ -0,0 +1,164 @@
import type { IDesktopAppIcon } from '@/ui/types/IDesktopAppIcon.ts'
import {
computed,
onMounted,
onUnmounted,
reactive,
ref,
toRaw,
toValue,
watch,
} from 'vue'
import type { IGridTemplateParams } from '@/ui/types/IGridTemplateParams.ts'
import type { IProcessInfo } from '@/core/process/IProcessInfo.ts'
export function useDesktopContainerInit(containerStr: string) {
let container:HTMLElement
// 初始值
const gridTemplate = reactive<IGridTemplateParams>({
cellExpectWidth: 90,
cellExpectHeight: 110,
cellRealWidth: 90,
cellRealHeight: 110,
gapX: 4,
gapY: 4,
colCount: 1,
rowCount: 1
})
const gridStyle = computed(() => ({
gridTemplateColumns: `repeat(${gridTemplate.colCount}, minmax(${gridTemplate.cellExpectWidth}px, 1fr))`,
gridTemplateRows: `repeat(${gridTemplate.rowCount}, minmax(${gridTemplate.cellExpectHeight}px, 1fr))`,
gap: `${gridTemplate.gapX}px ${gridTemplate.gapY}px`
}))
const ro = new ResizeObserver(entries => {
const containerRect = container.getBoundingClientRect()
gridTemplate.colCount = Math.floor((containerRect.width + gridTemplate.gapX) / (gridTemplate.cellExpectWidth + gridTemplate.gapX));
gridTemplate.rowCount = Math.floor((containerRect.height + gridTemplate.gapY) / (gridTemplate.cellExpectHeight + gridTemplate.gapY));
const w = containerRect.width - (gridTemplate.gapX * (gridTemplate.colCount - 1))
const h = containerRect.height - (gridTemplate.gapY * (gridTemplate.rowCount - 1))
gridTemplate.cellRealWidth = Number((w / gridTemplate.colCount).toFixed(2))
gridTemplate.cellRealHeight = Number((h / gridTemplate.rowCount).toFixed(2))
})
onMounted(() => {
container = document.querySelector(containerStr)!
ro.observe(container)
})
onUnmounted(() => {
ro.unobserve(container)
ro.disconnect()
})
// 有桌面图标的app
// const appInfos = processManager.processInfos.filter(processInfo => !processInfo.isJustProcess)
const appInfos: IProcessInfo[] = []
const oldAppIcons: IDesktopAppIcon[] = JSON.parse(localStorage.getItem('desktopAppIconInfo') || '[]')
const appIcons: IDesktopAppIcon[] = appInfos.map((processInfo, index) => {
const oldAppIcon = oldAppIcons.find(oldAppIcon => oldAppIcon.name === processInfo.name)
// 左上角坐标原点,从上到下从左到右 索引从1开始
const x = index % gridTemplate.rowCount + 1
const y = Math.floor(index / gridTemplate.rowCount) + 1
return {
name: processInfo.name,
icon: processInfo.icon,
path: processInfo.startName,
x: oldAppIcon ? oldAppIcon.x : x,
y: oldAppIcon ? oldAppIcon.y : y
}
})
const appIconsRef = ref(appIcons)
const exceedApp = ref<IDesktopAppIcon[]>([])
watch(() => [gridTemplate.colCount, gridTemplate.rowCount], ([nCols, nRows], [oCols, oRows]) => {
// if (oCols == 1 && oRows == 1) return
if (oCols === nCols && oRows === nRows) return
const { appIcons, hideAppIcons } = rearrangeIcons(toRaw(appIconsRef.value), nCols, nRows)
appIconsRef.value = appIcons
exceedApp.value = hideAppIcons
})
watch(() => appIconsRef.value, (appIcons) => {
localStorage.setItem('desktopAppIconInfo', JSON.stringify(appIcons))
})
return {
gridTemplate,
appIconsRef,
gridStyle
}
}
/**
* 重新安排图标位置
* @param appIconInfos 图标信息
* @param maxCol 列数
* @param maxRow 行数
*/
function rearrangeIcons(
appIconInfos: IDesktopAppIcon[],
maxCol: number,
maxRow: number
): IRearrangeInfo {
const occupied = new Set<string>();
function key(x: number, y: number) {
return `${x},${y}`;
}
const appIcons: IDesktopAppIcon[] = []
const hideAppIcons: IDesktopAppIcon[] = []
const temp: IDesktopAppIcon[] = []
for (const appIcon of appIconInfos) {
const { x, y } = appIcon;
if (x <= maxCol && y <= maxRow) {
if (!occupied.has(key(x, y))) {
occupied.add(key(x, y))
appIcons.push({ ...appIcon, x, y })
}
} else {
temp.push(appIcon)
}
}
const max = maxCol * maxRow
for (const appIcon of temp) {
if (appIcons.length < max) {
// 最后格子也被占 → 从 (1,1) 开始找空位
let placed = false;
for (let c = 1; c <= maxCol; c++) {
for (let r = 1; r <= maxRow; r++) {
if (!occupied.has(key(c, r))) {
occupied.add(key(c, r));
appIcons.push({ ...appIcon, x: c, y: r });
placed = true;
break;
}
}
if (placed) break;
}
} else {
// 放不下了
hideAppIcons.push(appIcon)
}
}
return {
appIcons,
hideAppIcons
};
}
interface IRearrangeInfo {
/** 正常的桌面图标信息 */
appIcons: IDesktopAppIcon[];
/** 隐藏的桌面图标信息(超出屏幕显示的) */
hideAppIcons: IDesktopAppIcon[];
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 48 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 58 KiB

View File

@@ -0,0 +1,15 @@
/**
* 桌面应用图标信息
*/
export interface IDesktopAppIcon {
/** 图标name */
name: string;
/** 图标 */
icon: string;
/** 图标路径 */
path: string;
/** 图标在grid布局中的列 */
x: number;
/** 图标在grid布局中的行 */
y: number;
}

View File

@@ -0,0 +1,21 @@
/**
* 桌面网格模板参数
*/
export interface IGridTemplateParams {
/** 单元格预设宽度 */
readonly cellExpectWidth: number
/** 单元格预设高度 */
readonly cellExpectHeight: number
/** 单元格实际宽度 */
cellRealWidth: number
/** 单元格实际高度 */
cellRealHeight: number
/** 列间距 */
gapX: number
/** 行间距 */
gapY: number
/** 总列数 */
colCount: number
/** 总行数 */
rowCount: number
}

View File

@@ -0,0 +1,10 @@
/**
* 窗体位置坐标 - 左上角
*/
export interface WindowFormPos {
x: number;
y: number;
}
/** 窗口状态 */
export type TWindowFormState = 'default' | 'minimized' | 'maximized';