communication.ts 4.43 KB
import { onUnmounted } from "vue";

/**
 * 全局状态接口定义(与基座保持一致)
 */
export interface GlobalState {
  config: {
    apiBaseUrl: string;
    timeout: number;
  };

  notifications: Notification[];

  theme: {
    mode: "dark" | "light";
    primaryColor: string;
  };

  user: null | {
    avatar: string;
    id: string;
    name: string;
    permissions: string[];
    role: string;
  };
}

/**
 * 通知消息接口
 */
export interface Notification {
  from?: string;
  id: string;
  message: string;
  timestamp: number;
  title: string;
  type: "error" | "info" | "success" | "warning";
}

/**
 * qiankun Props 类型定义
 */
export interface QiankunProps {
  [key: string]: any;
  container?: HTMLElement;
  onGlobalStateChange?: (
    callback: (state: GlobalState, prev: GlobalState) => void,
    fireImmediately?: boolean,
  ) => void;
  routerBase?: string;
  setGlobalState?: (state: Partial<GlobalState>) => void;
}

/**
 * 子应用通信管理器
 */
class SubAppCommunicationManager {
	private currentState: GlobalState | null = null; // 缓存当前状态
	private listeners: Array<(state: GlobalState, prev: GlobalState) => void> =
		[];
	private props: null | QiankunProps = null;
	private unsubscribe: (() => void) | null = null;

	/**
   * 销毁
   */
	destroy() {
		if (this.unsubscribe) {
			this.unsubscribe();
			this.unsubscribe = null;
		}
		this.listeners = [];
		this.props = null;
	}

	/**
   * 获取当前全局状态
   */
	getCurrentState(): GlobalState | null {
		return this.currentState;
	}

	/**
   * 初始化通信管理器
   * @param props qiankun 传递的 props
   */
	init(props: QiankunProps) {
		this.props = props;

		// 监听全局状态变化
		if (props.onGlobalStateChange) {
			const unsubscribeFn = props.onGlobalStateChange(
				(state: GlobalState, prev: GlobalState) => {
					// 缓存当前状态
					this.currentState = state;

					// 触发所有监听器
					this.listeners.forEach((listener) => {
						listener(state, prev);
					});
				},
				true, // 立即触发,获取当前状态 - 这确保了微应用一加载就能获取主应用的数据
			);
			// 只在返回值是函数时才赋值
			if (typeof unsubscribeFn === "function") {
				this.unsubscribe = unsubscribeFn;
			}
		}
	}

	/**
   * 监听全局状态变化
   * @param callback 回调函数
   * @returns 取消监听的函数
   */
	onStateChange(
		callback: (state: GlobalState, prev: GlobalState) => void,
	): () => void {
		this.listeners.push(callback);

		// 如果已经有缓存的状态,立即调用一次回调
		if (this.currentState) {
			callback(this.currentState, {} as GlobalState);
		}

		return () => {
			const index = this.listeners.indexOf(callback);
			if (index !== -1) {
				this.listeners.splice(index, 1);
			}
		};
	}

	/**
   * 向基座发送通知
   * @param notification 通知消息
   */
	sendNotification(notification: Omit<Notification, "id" | "timestamp">) {
		if (!this.props?.setGlobalState) {
			return;
		}

		// 获取当前通知列表(需要通过 props 或缓存获取)
		// 这里简化处理,直接通过 state 添加
		const newNotification: Notification = {
			...notification,
			id: Date.now().toString(),
			timestamp: Date.now(),
			from: notification.from || "Vue子应用",
		};

		// 通过修改全局状态来添加通知
		// 注意:这里需要基座的 communication manager 来处理通知添加逻辑
		// 所以我们实际上是触发一个状态变化,让基座来处理
		this.setGlobalState({
			notifications: [ newNotification ] as any, // 基座会合并到现有通知列表
		});
	}

	/**
   * 设置全局状态(向基座发送数据)
   * @param state 要更新的状态
   */
	setGlobalState(state: Partial<GlobalState>) {
		if (this.props?.setGlobalState) {
			this.props.setGlobalState(state);
		}
	}
}

// 导出单例
export const subAppCommunication = new SubAppCommunicationManager();

/**
 * Vue 组合式 API - 使用全局状态
 * @param callback 状态变化回调
 */
export function useGlobalState(
	callback: (state: GlobalState, prev: GlobalState) => void,
) {
	const unsubscribe = subAppCommunication.onStateChange(callback);

	// 在组件卸载时自动取消订阅
	onUnmounted(() => {
		unsubscribe();
	});

	return unsubscribe;
}

/**
 * 便捷方法:发送通知到基座
 */
export function notify(
	type: Notification["type"],
	title: string,
	message: string,
) {
	subAppCommunication.sendNotification({
		type,
		title,
		message,
	});
}