utils.ts 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import { Route } from 'vitepress'
  2. export const hashRE = /#.*$/
  3. export const extRE = /(index)?\.(md|html)$/
  4. export const endingSlashRE = /\/$/
  5. export const outboundRE = /^[a-z]+:/i
  6. export function isNullish(value: any): value is null | undefined {
  7. return value === null || value === undefined
  8. }
  9. export function isArray(value: any): value is any[] {
  10. return Array.isArray(value)
  11. }
  12. export function isExternal(path: string): boolean {
  13. return outboundRE.test(path)
  14. }
  15. export function isActive(route: Route, path?: string): boolean {
  16. if (path === undefined) {
  17. return false
  18. }
  19. const routePath = normalize(`/${route.data.relativePath}`)
  20. const pagePath = normalize(path)
  21. return routePath === pagePath
  22. }
  23. export function normalize(path: string): string {
  24. return decodeURI(path).replace(hashRE, '').replace(extRE, '')
  25. }
  26. export function joinUrl(base: string, path: string): string {
  27. const baseEndsWithSlash = base.endsWith('/')
  28. const pathStartsWithSlash = path.startsWith('/')
  29. if (baseEndsWithSlash && pathStartsWithSlash) {
  30. return base.slice(0, -1) + path
  31. }
  32. if (!baseEndsWithSlash && !pathStartsWithSlash) {
  33. return `${base}/${path}`
  34. }
  35. return base + path
  36. }
  37. /**
  38. * get the path without filename (the last segment). for example, if the given
  39. * path is `/guide/getting-started.html`, this method will return `/guide/`.
  40. * Always with a trailing slash.
  41. */
  42. export function getPathDirName(path: string): string {
  43. const segments = path.split('/')
  44. if (segments[segments.length - 1]) {
  45. segments.pop()
  46. }
  47. return ensureEndingSlash(segments.join('/'))
  48. }
  49. export function ensureSlash(path: string): string {
  50. return ensureEndingSlash(ensureStartingSlash(path))
  51. }
  52. export function ensureStartingSlash(path: string): string {
  53. return /^\//.test(path) ? path : `/${path}`
  54. }
  55. export function ensureEndingSlash(path: string): string {
  56. return /(\.html|\/)$/.test(path) ? path : `${path}/`
  57. }
  58. /**
  59. * Remove `.md` or `.html` extention from the given path. It also converts
  60. * `index` to slush.
  61. */
  62. export function removeExtention(path: string): string {
  63. return path.replace(/(index)?(\.(md|html))?$/, '') || '/'
  64. }