routes.ts 1.72 KB
import type { ComponentType } from 'react';

/** 路径参数:全部是字符串(来自地址栏),页面自己按需 Number()。 */
export type PageParams = Record<string, string>;

export interface RouteDef {
  /** 相对子应用首段的路径,全小写、参数用 :name,不含查询串。 */
  path: string;
  Page: ComponentType<{ params: PageParams }>;
}

export interface MatchedRoute {
  Page: RouteDef['Page'];
  params: PageParams;
}

/**
 * 按段匹配:段数不等的路径互不干扰(`user/:channelSource/:staffId` 三段、
 * `user/:channelSource/:merchantId/:phone` 四段),因此同一前缀下的长短路径可以共存。
 * 参数值做 decodeURIComponent,手机号与门店编号里不会有需要转义的字符,但保持成对。
 */
export function matchRoute(routes: RouteDef[], subPath: string): MatchedRoute | undefined {
  const segments = subPath
    .split('/')
    .filter(Boolean)
    .map((segment) => {
      try {
        return decodeURIComponent(segment);
      } catch {
        return segment;
      }
    });
  // 主壳菜单只配到 /points 时(没有子路径),落到本域第一个页面。
  if (!segments.length) {
    const first = routes[0];
    return first ? { Page: first.Page, params: {} } : undefined;
  }
  for (const route of routes) {
    const pattern = route.path.split('/').filter(Boolean);
    if (pattern.length !== segments.length) continue;
    const params: PageParams = {};
    const matched = pattern.every((segment, index) => {
      if (!segment.startsWith(':')) return segment === segments[index];
      params[segment.slice(1)] = segments[index];
      return true;
    });
    if (matched) return { Page: route.Page, params };
  }
  return undefined;
}