App.tsx 2.55 KB
import { useEffect, useMemo, useState } from 'react';
import { busEvents } from '@uj/contracts';
import { SubAppProvider, readInitialPage, shortName, subappBus } from '@uj/platform-sdk';
import { UEmpty, UPageTransition } from '@uj/ui';
import MerchantPage from './pages/Merchant';
import CreateMerchantPage from './pages/Merchant/Create';
import MerchantEditPage from './pages/Merchant/Edit';
import MerchantDetailPage from './pages/Merchant/Detail';
import EmployeePage from './pages/Employee';
import RolePage from './pages/Role';
import type { PageParams, RouteDef } from './routes';
import { matchRoute } from './routes';

/**
 * 三条主路由逐字对应菜单 SQL 的 route 末段:merchant / employee / role。
 * merchant/create、merchant/create/:parentId(子商户)、merchant/edit/:id、merchant/detail/:id
 * 是二级页(老 add/addSubMerchant/edit/detail.html 表单太长,抽屉放不下),不进菜单。
 */
const ROUTES: RouteDef[] = [
  { path: 'merchant', Page: MerchantPage },
  { path: 'merchant/create', Page: CreateMerchantPage },
  { path: 'merchant/create/:parentId', Page: CreateMerchantPage },
  { path: 'merchant/sub/:parentId', Page: CreateMerchantPage },
  { path: 'merchant/edit/:id', Page: MerchantEditPage },
  { path: 'merchant/detail/:id', Page: MerchantDetailPage },
  { path: 'employee', Page: EmployeePage },
  { path: 'employee/create/:merchantId', Page: EmployeePage },
  { path: 'role', Page: RolePage },
];

function renderPage(subPath: string) {
  const matched = matchRoute(ROUTES, subPath);
  if (!matched) {
    return <UEmpty description={`没有匹配「${subPath}」的页面,请从菜单进入`} />;
  }
  const { Page, params } = matched;
  return <Page params={params as PageParams} />;
}

function MerchantApp() {
  const [subPath, setSubPath] = useState<string>(readInitialPage);

  useEffect(() => {
    const bus = subappBus();
    if (!bus) return;
    const events = busEvents(shortName());
    const onNavigate = (...args: unknown[]) => setSubPath(String(args[0] ?? ''));
    const onLogout = () => setSubPath('');
    bus.$on(events.navigate, onNavigate);
    bus.$on(events.logout, onLogout);
    bus.$emit(events.ready);
    return () => {
      bus.$off(events.navigate, onNavigate);
      bus.$off(events.logout, onLogout);
    };
  }, []);

  const page = useMemo(() => renderPage(subPath), [subPath]);
  return <UPageTransition pageKey={subPath}>{page}</UPageTransition>;
}

export function App() {
  return (
    <SubAppProvider>
      <div className="uj-scope uj-merchant-app">{MerchantApp()}</div>
    </SubAppProvider>
  );
}