MicroApp.tsx 7.36 KB
import { useEffect, useReducer, useRef, useState } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import { Button, Empty, Spin } from 'antd';
import { bus, destroyApp, startApp } from 'wujie';
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';

/**
 * 同一宿主元素 + 同一子应用只准启动一次(el -> 已启动的 shortName)。
 *
 * HMR / 快速来回切路由会让两个 startApp(同名) 几乎同时进入,第二个 active()
 * 在第一个 iframe 注入 iframeWindow.__WUJIE 之前就跑 syncUrlToWindow,
 * 读到 undefined 直接 TypeError。用宿主 el 作键挡掉重入。
 *
 * 键里必须带 shortName:`<Routes>` 在 /store/* 与 /system/* 之间切换时组件类型没变,
 * React 复用同一实例,hostRef 还是同一个 div;只按 el 记会让第二个子应用永远
 * 不发 startApp —— 表现为一片空白且零报错。
 */
const startedOn = new WeakMap<HTMLElement, string>();

/**
 * 通用子应用挂载点。
 *
 * ⚠️ 直调 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 ready = isReady(shortName);
  const [failed, setFailed] = useState(false);
  const [attempt, setAttempt] = useState(0);

  const retry = () => {
    const el = hostRef.current;
    if (el) startedOn.delete(el);
    try {
      destroyApp(shortName);
    } catch {
      /* 销毁失败不影响重建 */
    }
    forgetReady(shortName);
    setFailed(false);
    setAttempt((n) => n + 1);
  };

  useEffect(() => {
    const el = hostRef.current;
    if (!el) return;
    if (!entry) {
      setFailed(true);
      return;
    }
    if (startedOn.get(el) === shortName) return;

    let cancelled = false;
    let retried = false;

    const launch = () => {
      if (cancelled) return;
      startedOn.set(el, shortName);
      setFailed(false);
      void startApp({
        name: shortName,
        url: entry,
        el,
        // 全仓唯一的一份请求能力经 props 注入;子应用不打包 axios / PEM / VITE_*。
        props: createSubAppProps({ shortName, page: subPath, navigate }),
        // 子应用实例由 wujie 缓存管理,路由切走不销毁、切回即激活。
        alive: true,
        // 主应用 URL 是唯一真源,不把子应用路由写进 query(否则菜单 selectedKey 要重写)。
        sync: false,
      }).catch((err) => {
        console.error(`[wujie] 子应用 ${shortName} 启动失败:`, err);
        startedOn.delete(el);
        forgetReady(shortName);
        announce();
        try {
          destroyApp(shortName);
        } catch {
          /* 销毁失败不影响后续自愈 */
        }
        // 清掉可能已毒化的同名 sandbox 后自动重试一次;仅一次,避免坏缓存无限循环。
        if (!retried && !cancelled) {
          retried = true;
          launch();
        } else if (!cancelled) {
          setFailed(true);
        }
      });
    };

    launch();

    // startApp 可能既不 resolve 也不 reject(iframe 静默失败),没有计时器用户会永远转圈。
    const timer = window.setTimeout(() => {
      if (!cancelled && !isReady(shortName)) setFailed(true);
    }, 15_000);

    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);
      setFailed(false);
      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">
          <Spin />
        </div>
      )}

      {(!entry || failed) && (
        <div className="uj-mfe-loading">
          <Empty description={entry ? '子应用加载失败' : '未找到子应用入口'} />
          <div style={{ marginTop: 12, fontSize: 13, color: '#56697d' }}>
            {entry
              ? '可能是子应用未启动或网络不可用。可以先重试;多次失败请刷新页面。'
              : `请为 ${shortName} 配置 package.json 的 uj.entry 或运行时 manifest。`}
          </div>
          <div style={{ display: 'flex', gap: 8, marginTop: 16 }}>
            {entry && (
              <Button type="primary" onClick={retry}>
                重试
              </Button>
            )}
            <Button onClick={() => window.location.reload()}>刷新页面</Button>
          </div>
        </div>
      )}
    </div>
  );
}