subAppAdapter.ts 5.45 KB
import type { Request } from "glsk-toolkit";

import type { GlobalState, Notification } from "./communication";

import { communicationManager } from "./communication";

/**
 * qiankun Props 类型定义(子应用使用)
 */
export interface QiankunProps {
  container?: HTMLElement;
  routerBase?: string;
  onGlobalStateChange?: (
    callback: (state: GlobalState, prev: GlobalState) => void,
    fireImmediately?: boolean,
  ) => void;
  setGlobalState?: (state: Partial<GlobalState>) => void;
  /**
   * 获取 GSC Request 实例的函数
   * 子应用可以通过此函数获取基座已初始化的 Request 实例
   * @returns Promise<Request> Request 实例
   */
  getGscRequest?: () => Promise<Request>;
  [key: string]: any;
}

/**
 * 子应用通信管理器接口
 * 这个接口定义了子应用需要的所有通信方法
 */
export interface SubAppCommunicationManager {
  /**
   * 初始化通信管理器
   * @param props qiankun 传递的 props
   */
  init(props: QiankunProps): void;

  /**
   * 获取当前全局状态
   */
  getCurrentState(): GlobalState | null;

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

  /**
   * 设置全局状态(向基座发送数据)
   * @param state 要更新的状态
   */
  setGlobalState(state: Partial<GlobalState>): void;

  /**
   * 向基座发送通知
   * @param notification 通知消息
   */
  sendNotification(notification: Omit<Notification, "id" | "timestamp">): void;

  /**
   * 销毁通信管理器
   */
  destroy(): void;
}

/**
 * 子应用通信适配器
 * 将基座的 CommunicationManager 适配成子应用需要的接口
 */
class SubAppCommunicationAdapter implements 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;
		this.currentState = null;
		console.log("[子应用通信适配器] 通信管理器已销毁");
	}

	/**
   * 获取当前全局状态
   */
	getCurrentState(): GlobalState | null {
		// 优先返回缓存的状态
		if (this.currentState) {
			return this.currentState;
		}
		// 如果没有缓存,从基座获取
		return communicationManager.getGlobalState();
	}

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

		// 获取基座的当前状态
		this.currentState = communicationManager.getGlobalState();

		// 监听全局状态变化
		if (props.onGlobalStateChange) {
			props.onGlobalStateChange(
				(state: GlobalState, prev: GlobalState) => {
					console.log("[子应用通信适配器] 全局状态变化:", state, prev);

					// 缓存当前状态
					this.currentState = state;

					// 触发所有监听器
					this.listeners.forEach((listener) => {
						listener(state, prev);
					});
				},
				true, // 立即触发,获取当前状态
			);
		}

		// 同时监听基座通信管理器的状态变化(作为补充)
		const baseUnsubscribe = communicationManager.onStateChange(
			(state, prev) => {
				// 如果 qiankun 的状态变化没有触发,这里作为备用
				if (this.currentState !== state) {
					this.currentState = state;
					this.listeners.forEach((listener) => {
						listener(state, prev);
					});
				}
			},
		);

		// 保存取消订阅函数(qiankun 的 onGlobalStateChange 不返回取消函数,只取消基座的监听)
		this.unsubscribe = () => {
			baseUnsubscribe();
		};

		console.log("[子应用通信适配器] 通信管理器初始化完成");
	}

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

		// 如果已经有缓存的状态,立即调用一次回调
		if (this.currentState) {
			console.log("[子应用通信适配器] 立即触发回调,使用缓存的全局状态");
			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">) {
		// 通过基座的通信管理器添加通知
		communicationManager.addNotification({
			...notification,
			from: notification.from || "Vue子应用",
		});
	}

	/**
   * 设置全局状态(向基座发送数据)
   * @param state 要更新的状态
   */
	setGlobalState(state: Partial<GlobalState>) {
		// 通过基座的通信管理器设置状态
		communicationManager.setGlobalState(state);

		// 同时通过 qiankun 的 props 设置(如果可用)
		if (this.props?.setGlobalState) {
			this.props.setGlobalState(state);
		}

		console.log("[子应用通信适配器] 全局状态已更新:", state);
	}
}

/**
 * 创建子应用通信管理器实例
 * @returns 子应用通信管理器实例
 */
export function createSubAppAdapter(): SubAppCommunicationManager {
	return new SubAppCommunicationAdapter();
}