menu.ts 1.76 KB
import type { MenuNode } from '@/types/auth'

export function flattenMenuPaths(menus: MenuNode[]): string[] {
  const paths: string[] = []
  const walk = (items: MenuNode[]) => {
    for (const item of items) {
      if (item.path) paths.push(item.path)
      if (item.children?.length) walk(item.children)
    }
  }
  walk(menus)
  return paths
}

export function flattenMenus(menus: MenuNode[]): MenuNode[] {
  const result: MenuNode[] = []
  const walk = (items: MenuNode[]) => {
    for (const item of items) {
      result.push(item)
      if (item.children?.length) walk(item.children)
    }
  }
  walk(menus)
  return result
}

export function findMenuByPath(menus: MenuNode[], path: string): MenuNode | null {
  for (const item of menus) {
    if (item.path === path) return item
    if (item.children?.length) {
      const found = findMenuByPath(item.children, path)
      if (found) return found
    }
  }
  return null
}

export function findMenuTrailByPath(menus: MenuNode[], path: string): MenuNode[] {
  for (const item of menus) {
    if (item.path === path) return [item]
    if (item.children?.length) {
      const childTrail = findMenuTrailByPath(item.children, path)
      if (childTrail.length) return [item, ...childTrail]
    }
  }
  return []
}

export function findFirstMenuPath(menus: MenuNode[]): string {
  for (const item of menus) {
    if (item.path) return item.path
    if (item.children?.length) {
      const childPath = findFirstMenuPath(item.children)
      if (childPath) return childPath
    }
  }
  return '/dashboard'
}

export function filterPinnedMenuEntries(
  menus: MenuNode[],
  pinned: Array<{ path: string; title: string; desc: string }>
) {
  const available = new Set(flattenMenuPaths(menus))
  return pinned.filter(item => available.has(item.path))
}