AccountLayout.utils.ts 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. import type { SidebarSection } from './AccountLayout.types'
  2. import type { SubMenuSection } from '@/components/ui/ProductMenu/ProductMenu.types'
  3. /**
  4. * Converts AccountLayout SidebarSection[] to SubMenuSection[] for SubMenu/ProductMenu.
  5. * Defensive: handles missing or malformed sections/links.
  6. */
  7. export function toSubMenuSections(sections: SidebarSection[]): SubMenuSection[] {
  8. if (!Array.isArray(sections)) return []
  9. return sections
  10. .filter((s): s is SidebarSection => s != null && typeof s === 'object')
  11. .map((s) => ({
  12. key: s.key ?? '',
  13. heading: s.heading,
  14. links: (s.links ?? [])
  15. .filter((l) => l != null && typeof l === 'object' && l.key && l.label != null)
  16. .map((l) => ({
  17. key: l.key,
  18. label: l.label,
  19. href: l.href,
  20. })),
  21. }))
  22. .filter((s) => s.key || s.heading)
  23. }
  24. /**
  25. * Returns the key of the first active link across all sections.
  26. * Used to highlight the current page in SubMenu.
  27. */
  28. export function getActiveKey(sections: SidebarSection[]): string | undefined {
  29. if (!Array.isArray(sections)) return undefined
  30. for (const section of sections) {
  31. if (!section?.links || !Array.isArray(section.links)) continue
  32. const active = section.links.find((l) => l?.isActive === true)
  33. if (active?.key) return active.key
  34. }
  35. return undefined
  36. }