communication.ts
6.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
// initGlobalState 定义全局状态,并返回通信方法,建议在主应用使用,微应用通过 props 获取通信方法。
import { initGlobalState, MicroAppStateActions } from 'qiankun';
/**
* 全局状态接口定义
*/
export interface GlobalState {
// 用户信息
user: null | {
avatar: string;
id: string;
name: string;
permissions: string[];
role: string;
};
// 主题配置
theme: {
mode: 'dark' | 'light';
primaryColor: string;
};
// 消息通知列表
notifications: Notification[];
// 系统配置
config: {
apiBaseUrl: string;
timeout: number;
};
// 当前激活的菜单信息
currentMenu: null | {
menuIcon?: string;
menuId: string;
menuMeta?: Record<string, any>;
menuPath: string;
menuTitle: string;
timestamp: number;
};
}
/**
* 通知消息接口
*/
export interface Notification {
id: string;
type: 'error' | 'info' | 'success' | 'warning';
title: string;
message: string;
timestamp: number;
from?: string; // 来自哪个子应用
}
/**
* 初始全局状态
*/
const initialState: GlobalState = {
user: {
id: '001',
name: '张三仨',
avatar: '👨💼',
role: 'admin',
permissions: ['read', 'write', 'delete', 'admin'],
},
theme: {
mode: 'light',
primaryColor: '#1890ff',
},
notifications: [],
config: {
apiBaseUrl: 'https://api.example.com',
timeout: 5000,
},
currentMenu: null,
};
/**
* 通信管理器类
* 负责管理基座和子应用之间的数据通信
*/
class CommunicationManager {
// qiankun 的状态管理实例
private actions: MicroAppStateActions | null = null;
// 当前全局状态的本地副本(qiankun 不提供 getGlobalState 方法,需要自己维护)
private currentState: GlobalState = initialState;
// 状态变化监听器列表
private listeners: Array<(state: GlobalState, prev: GlobalState) => void> =
[];
/**
* 添加通知消息
* @param notification 通知消息(不含id和timestamp)
*/
addNotification(notification: Omit<Notification, 'id' | 'timestamp'>) {
const newNotification: Notification = {
...notification,
id: Date.now().toString(),
timestamp: Date.now(),
};
this.setGlobalState({
notifications: [...this.currentState.notifications, newNotification],
});
}
/**
* 清空所有通知
*/
clearNotifications() {
this.setGlobalState({
notifications: [],
});
}
/**
* 获取当前全局状态
* 注意:qiankun 不提供 getGlobalState 方法,这里返回本地维护的状态副本
*/
getGlobalState(): GlobalState {
return this.currentState;
}
/**
* 初始化全局状态
*/
init() {
// 初始化 qiankun 的全局状态
this.actions = initGlobalState(initialState);
// 监听状态变化,同步更新本地副本
this.actions.onGlobalStateChange((state, prev) => {
console.log('[基座通信] 全局状态变化:', state, prev);
// 更新本地状态副本
this.currentState = state as GlobalState;
// 触发所有监听器
this.listeners.forEach((listener) => {
listener(state as GlobalState, prev as GlobalState);
});
});
console.log('[基座通信] 通信管理器初始化完成');
}
/**
* 监听全局状态变化
* @param callback 回调函数
* @returns 取消监听的函数
*/
onStateChange(
callback: (state: GlobalState, prev: GlobalState) => void,
): () => void {
this.listeners.push(callback);
// 返回取消监听的函数
return () => {
const index = this.listeners.indexOf(callback);
if (index !== -1) {
this.listeners.splice(index, 1);
}
};
}
/**
* 移除通知消息
* @param id 通知ID
*/
removeNotification(id: string) {
this.setGlobalState({
notifications: this.currentState.notifications.filter((n) => n.id !== id),
});
}
/**
* 设置全局状态(支持部分更新)
* @param state 要更新的状态
*/
setGlobalState(state: Partial<GlobalState>) {
if (this.actions) {
// 深度合并更新本地状态副本(立即更新,避免异步延迟)
this.currentState = this.deepMerge(this.currentState, state);
// 同步到 qiankun 全局状态(只传入变化的部分)
this.actions.setGlobalState(state);
console.log('[基座通信] 全局状态已更新:', state);
} else {
console.warn('[基座通信] 通信管理器未初始化');
}
}
/**
* 更新系统配置
* @param config 配置项
*/
updateConfig(config: Partial<GlobalState['config']>) {
this.setGlobalState({
config: {
...this.currentState.config,
...config,
} as GlobalState['config'],
});
}
/**
* 更新当前激活的菜单信息
* @param menu 菜单信息
*/
updateCurrentMenu(menu: {
menuIcon?: string;
menuId: string;
menuMeta?: Record<string, any>;
menuPath: string;
menuTitle: string;
}) {
this.setGlobalState({
currentMenu: {
...menu,
timestamp: Date.now(),
},
});
console.log('[基座通信] 当前菜单已更新:', menu);
}
/**
* 更新主题
* @param theme 主题配置
*/
updateTheme(theme: Partial<GlobalState['theme']>) {
this.setGlobalState({
theme: {
...this.currentState.theme,
...theme,
} as GlobalState['theme'],
});
}
/**
* 更新用户信息
* @param user 用户信息
*/
updateUser(user: GlobalState['user']) {
this.setGlobalState({ user });
}
/**
* 深度合并对象(简单实现)
*/
private deepMerge(target: any, source: any): any {
const result = { ...target };
for (const key in source) {
const sourceValue = source[key];
const targetValue = target[key];
if (
sourceValue &&
typeof sourceValue === 'object' &&
!Array.isArray(sourceValue)
) {
result[key] =
targetValue &&
typeof targetValue === 'object' &&
!Array.isArray(targetValue)
? this.deepMerge(targetValue, sourceValue)
: sourceValue;
} else {
result[key] = sourceValue;
}
}
return result;
}
}
// 导出单例
export const communicationManager = new CommunicationManager();
/**
* 便捷方法:向子应用广播消息
* @param type 消息类型
* @param title 标题
* @param message 消息内容
*/
export function broadcast(
type: Notification['type'],
title: string,
message: string,
) {
communicationManager.addNotification({
type,
title,
message,
from: '基座应用',
});
}