sideBar.ts 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import { DefaultTheme } from '../config'
  2. import { isArray, ensureStartingSlash, removeExtention } from '../utils'
  3. export function isSideBarConfig(
  4. sidebar: DefaultTheme.SideBarConfig | DefaultTheme.MultiSideBarConfig
  5. ): sidebar is DefaultTheme.SideBarConfig {
  6. return sidebar === false || sidebar === 'auto' || isArray(sidebar)
  7. }
  8. export function isSideBarGroup(
  9. item: DefaultTheme.SideBarItem
  10. ): item is DefaultTheme.SideBarGroup {
  11. return (item as DefaultTheme.SideBarGroup).children !== undefined
  12. }
  13. export function isSideBarEmpty(sidebar?: DefaultTheme.SideBarConfig): boolean {
  14. return isArray(sidebar) ? sidebar.length === 0 : !sidebar
  15. }
  16. /**
  17. * Get the `SideBarConfig` from sidebar option. This method will ensure to get
  18. * correct sidebar config from `MultiSideBarConfig` with various path
  19. * combinations such as matching `guide/` and `/guide/`. If no matching config
  20. * was found, it will return `auto` as a fallback.
  21. */
  22. export function getSideBarConfig(
  23. sidebar: DefaultTheme.SideBarConfig | DefaultTheme.MultiSideBarConfig,
  24. path: string
  25. ): DefaultTheme.SideBarConfig {
  26. if (isSideBarConfig(sidebar)) {
  27. return sidebar
  28. }
  29. path = ensureStartingSlash(path)
  30. for (const dir in sidebar) {
  31. // make sure the multi sidebar key starts with slash too
  32. if (path.startsWith(ensureStartingSlash(dir))) {
  33. return sidebar[dir]
  34. }
  35. }
  36. return 'auto'
  37. }
  38. /**
  39. * Get flat sidebar links from the sidebar items. This method is useful for
  40. * creating the "next and prev link" feature. It will ignore any items that
  41. * don't have `link` property and removes `.md` or `.html` extension if a
  42. * link contains it.
  43. */
  44. export function getFlatSideBarLinks(
  45. sidebar: DefaultTheme.SideBarItem[]
  46. ): DefaultTheme.SideBarLink[] {
  47. return sidebar.reduce<DefaultTheme.SideBarLink[]>((links, item) => {
  48. if (item.link) {
  49. links.push({ text: item.text, link: removeExtention(item.link) })
  50. }
  51. if (isSideBarGroup(item)) {
  52. links = [...links, ...getFlatSideBarLinks(item.children)]
  53. }
  54. return links
  55. }, [])
  56. }