communication.ts 6.64 KB
// 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: '基座应用',
  });
}