MicroApp.tsx 9.72 KB
import { useEffect, useReducer, useRef, useState } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import { Button, Empty } from 'antd';
import { bus } from 'wujie';
import { BrandLoader } from '@uj/biz';
import { busEvents } from '@uj/contracts';
import { entryOf } from './subapps';
import { forgetReady, isReady, markReady } from './subapp-handshake';
import { createSubAppProps } from './subapp-props';
import { logoutEverything } from './subapp-lifecycle';
import { destroyAppLocked, restartAppLocked, startAppLocked } from './wujie-lifecycle';

/**
 * 同一宿主元素 + 同一子应用只准启动一次(el -> 已启动的 shortName)。
 *
 * 真正的并发闸在 wujie-lifecycle.ts(按 shortName 串行)。这里这层只挡
 * 「同一 el 的 effect 重入」,避免 StrictMode 下重复 startApp。
 *
 * 键里必须带 shortName:`<Routes>` 在 /store/* 与 /system/* 之间切换时组件类型没变,
 * React 复用同一实例,hostRef 还是同一个 div;只按 el 记会让第二个子应用永远
 * 不发 startApp —— 表现为一片空白且零报错。
 */
const startedOn = new WeakMap<HTMLElement, string>();

type Phase = 'loading' | 'ready' | 'failed';

function errorText(err: unknown): string {
  if (err instanceof Error) return err.message;
  if (typeof err === 'string') return err;
  return '未知错误';
}

/**
 * 通用子应用挂载点。
 *
 * ⚠️ 直调 wujie core 而非 wujie-react 的原因(atlas 2026-10-23 实锤):
 * wujie-react@2.1.0 的 class 组件里 isUnmounted 被 componentWillUnmount 置 true 后
 * 永不重置,React 19 StrictMode 的 mount→unmount→mount 双跑会让它永久钉死,
 * 于是 execStartApp 直接 return —— 宿主 div 渲染出来但里面没有 <wujie-app>,
 * Console 无任何报错。core 直调后生命周期由本组件自管。
 *
 * page 的两条通道是「初值 + 增量」,不是两个真源:props.page 只在首次 startApp
 * 注入(alive 复用沙箱后主壳不会重算 props),首屏之后一切以 bus 为准。
 * 握手保证第一次 navigate 不丢:子应用订阅完 $emit(<shortName>:ready),
 * 本组件收到才补发当前 subPath 并撤掉加载占位。
 */
export function MicroApp({ shortName, route }: { shortName: string; route: string }) {
  const location = useLocation();
  const navigate = useNavigate();
  const subPath = location.pathname.replace(new RegExp(`^/${route}/?`), '') || '';
  const hostRef = useRef<HTMLDivElement>(null);
  const entry = entryOf(shortName);
  // 就绪真源是 subapp-handshake 那张表;本地 state 只当「表变了,再渲染一次」的信号。
  // 不写成布尔 useState:两个子应用切换时复用同一组件实例,本地布尔会带着上一个的值过来。
  const [, announce] = useReducer((n: number) => n + 1, 0);
  const [phase, setPhase] = useState<Phase>('loading');
  const [message, setMessage] = useState('');
  const [attempt, setAttempt] = useState(0);
  const failed = phase === 'failed';
  // 就绪真源仍是握手表:alive 切回来时表已就绪,不能因为本地 phase 重置就又盖一层 loading。
  const ready = isReady(shortName) && !failed;

  const retry = () => {
    const el = hostRef.current;
    if (el) startedOn.delete(el);
    // 先排销毁再让 effect 排启动:两者同一把锁,顺序确定,不会撞上 __WUJIE.sync。
    void destroyAppLocked(shortName).catch(() => {});
    forgetReady(shortName);
    setMessage('');
    setPhase('loading');
    setAttempt((n) => n + 1);
  };

  useEffect(() => {
    const el = hostRef.current;
    if (!el) return;

    let cancelled = false;
    let retried = false;
    let timeoutRetried = false;
    let timer = 0;

    /** 失败即终态,只有 retry / 新一次挂载能清掉;避免后来到的 reject 把错误态抹回 loading。 */
    const fail = (err: unknown) => {
      if (cancelled) return;
      window.clearTimeout(timer);
      startedOn.delete(el);
      forgetReady(shortName);
      setMessage(errorText(err));
      setPhase('failed');
      announce();
      void destroyAppLocked(shortName).catch(() => {});
    };

    const armTimeout = () => {
      window.clearTimeout(timer);
      timer = window.setTimeout(() => {
        // alive 复用时握手表还留着上次会话的 ready,不必等新一次上报。
        if (cancelled || isReady(shortName)) return;
        // 首次超时多因 dev 冷启动:Vite 临时预构建依赖触发 iframe reload,
        // 恰好打断 <short>:ready 握手。重启一次让子应用重新上报,比直接甩错误页准确。
        // 只自动重试一次,避免服务真挂掉时无限重启。
        if (!timeoutRetried) {
          timeoutRetried = true;
          launch(true);
          return;
        }
        fail(
          new Error(
            '启动超时(2 次 × 20 秒),子应用未上报就绪。请检查子应用服务与浏览器控制台。',
          ),
        );
      }, 20_000);
    };

    if (!entry) {
      fail(new Error('未找到子应用入口。请检查 manifest.json 或 VITE_<SHORT>_SUBAPP_URL 配置。'));
      return () => {
        cancelled = true;
        window.clearTimeout(timer);
      };
    }

    const options = {
      name: shortName,
      url: entry,
      el,
      // 全仓唯一的一份请求能力经 props 注入;子应用不打包 axios / PEM / VITE_*。
      props: createSubAppProps({ shortName, page: subPath, navigate }),
      // 子应用实例由 wujie 缓存管理,路由切走不销毁、切回即激活。
      alive: true,
      // 主应用 URL 是唯一真源,不把子应用路由写进 query(否则菜单 selectedKey 要重写)。
      sync: false,
    };

    const launch = (fresh: boolean) => {
      if (cancelled) return;
      startedOn.set(el, shortName);
      setMessage('');
      setPhase('loading');
      armTimeout();
      const task = fresh ? restartAppLocked(options) : startAppLocked(options);
      void task.catch((err: unknown) => {
        if (cancelled) return;
        console.error(`[wujie] 子应用 ${shortName} 启动失败:`, err);
        startedOn.delete(el);
        forgetReady(shortName);
        announce();
        // 清掉可能已毒化的同名 sandbox 后自动重试一次;重试整体进闸,
        // 不再出现 destroy 未落地就 startApp 的 __WUJIE.sync 竞态。
        if (!retried) {
          retried = true;
          launch(true);
        } else {
          fail(err);
        }
      });
    };

    // 已启动过(alive 切回来)就不重复 startApp;未启动才发。
    // 跳过启动也要挂超时:StrictMode 首个 effect 被取消时会清掉自己的计时器,
    // 否则第二个实例会无限停在 loading。
    if (startedOn.get(el) !== shortName) launch(false);
    else armTimeout();

    return () => {
      cancelled = true;
      window.clearTimeout(timer);
      // 刻意不销毁实例:alive 保活语义即「state 不丢」。真正要销毁的场景是登出。
    };
    // subPath 刻意不进依赖:页面切换走下面的 bus 事件,重建 iframe 会让整个子应用重载。
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [shortName, entry, attempt]);

  useEffect(() => {
    const events = busEvents(shortName);
    // 主应用侧必须用 wujie 模块级导出的 bus:window.$wujie 只存在于子应用 iframe。
    const onReady = () => {
      markReady(shortName);
      setMessage('');
      setPhase('ready');
      announce();
      bus.$emit(events.navigate, subPath);
    };
    const onNavigateHost = (...args: unknown[]) => navigate(String(args[0] ?? '/'));
    const onLogoutHost = () => void logoutEverything(navigate);

    bus.$on(events.ready, onReady);
    bus.$on(events.navigateHost, onNavigateHost);
    bus.$on(events.logoutHost, onLogoutHost);

    // 已握过手(alive 切回来)就直接发,不必空等第二次 ready。
    // 还没握手时什么都不发:那次 emit 必丢,交给 onReady。
    if (isReady(shortName)) bus.$emit(events.navigate, subPath);

    return () => {
      bus.$off(events.ready, onReady);
      bus.$off(events.navigateHost, onNavigateHost);
      bus.$off(events.logoutHost, onLogoutHost);
    };
  }, [shortName, subPath, navigate]);

  return (
    <div style={{ position: 'relative', width: '100%', height: '100%' }}>
      {/* 宿主必须常驻:startApp 认的就是这个 el,卸载重建等于把子应用整个重载一遍。
          占位做成绝对定位盖在上面,而不是替换它。 */}
      <div ref={hostRef} style={{ width: '100%', height: '100%' }} />

      {!ready && !failed && entry && (
        <div className="uj-mfe-loading" role="status" aria-live="polite">
          <div className="uj-mfe-loading__spinner">
            <BrandLoader />
            <span className="uj-mfe-loading__label">正在接入…</span>
          </div>
        </div>
      )}

      {failed && (
        <div className="uj-mfe-loading uj-mfe-loading--error" role="alert">
          <Empty description={entry ? '子应用启动失败' : '未找到子应用入口'} />
          <div className="uj-mfe-loading__error-message">{message}</div>
          <div className="uj-mfe-loading__hint">
            {entry
              ? '可先重试;若反复失败,请刷新页面并查看浏览器控制台的子应用报错。'
              : `请为 ${shortName} 配置 manifest.json 或 package.json 的 uj.entry。`}
          </div>
          <div className="uj-mfe-loading__actions">
            {entry && (
              <Button type="primary" onClick={retry}>
                重试
              </Button>
            )}
            <Button onClick={() => window.location.reload()}>刷新页面</Button>
          </div>
        </div>
      )}
    </div>
  );
}