communication.ts 5.63 KB
import { onUnmounted } from 'vue';

/**
 * 全局状态接口定义(与基座保持一致)
 */
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;
}

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

/**
 * 子应用通信管理器
 */
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;
    console.log('[子应用通信] 通信管理器已销毁');
  }

  /**
   * 获取当前全局状态
   */
  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) => {
          console.log('[子应用通信] 全局状态变化:', state, prev);

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

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

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

    // 额外的保险措施:延迟一点再触发一次所有监听器,确保数据已经传递
    setTimeout(() => {
      if (this.props?.onGlobalStateChange) {
        console.log('[子应用通信] 二次确认全局状态同步');
      }
    }, 100);
  }

  /**
   * 监听全局状态变化
   * @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'>) {
    if (!this.props?.setGlobalState) {
      console.warn('[子应用通信] 无法发送通知,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);
      console.log('[子应用通信] 全局状态已更新:', state);
    } else {
      console.warn('[子应用通信] setGlobalState 方法不可用');
    }
  }
}

// 导出单例
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,
  });
}