SiderMenuUtils.ts 992 Bytes
Newer Older
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
1 2
import pathToRegexp from 'path-to-regexp';
import { urlToList } from '../_utils/pathTools';
何乐's avatar
何乐 committed
3
import { MenuDataItem, BaseMenuProps } from './BaseMenu';
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
4 5 6 7 8 9

/**
 * Recursively flatten the data
 * [{path:string},{path:string}] => {path,path2}
 * @param  menus
 */
何乐's avatar
何乐 committed
10 11
export const getFlatMenuKeys = (menuData: MenuDataItem[] = []) => {
  let keys: string[] = [];
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
12 13 14 15 16 17 18 19 20
  menuData.forEach(item => {
    keys.push(item.path);
    if (item.children) {
      keys = keys.concat(getFlatMenuKeys(item.children));
    }
  });
  return keys;
};

何乐's avatar
何乐 committed
21 22
export const getMenuMatches = (flatMenuKeys: string[] = [], path: string) =>
  flatMenuKeys.filter(item => item && pathToRegexp(item).test(path));
23

ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
24 25 26
/**
 * θŽ·εΎ—θœε•ε­θŠ‚η‚Ή
 */
何乐's avatar
何乐 committed
27 28 29
export const getDefaultCollapsedSubMenus = (props: BaseMenuProps) => {
  const { location, flatMenuKeys } = props;
  return urlToList(location!.pathname)
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
30
    .map(item => getMenuMatches(flatMenuKeys, item)[0])
Yu's avatar
Yu committed
31 32
    .filter(item => item)
    .reduce((acc, curr) => [...acc, curr], ['/']);
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
33
};