utils.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import { useSiteData } 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 withBase(path) {
  7. return (useSiteData().value.base + path).replace(/\/+/g, '/');
  8. }
  9. export function isExternal(path) {
  10. return outboundRE.test(path);
  11. }
  12. export function isActive(route, path) {
  13. if (path === undefined) {
  14. return false;
  15. }
  16. const routePath = normalize(route.path);
  17. const pagePath = normalize(path);
  18. return routePath === pagePath;
  19. }
  20. export function normalize(path) {
  21. return decodeURI(path).replace(hashRE, '').replace(extRE, '');
  22. }
  23. export function joinUrl(base, path) {
  24. const baseEndsWithSlash = base.endsWith('/');
  25. const pathStartsWithSlash = path.startsWith('/');
  26. if (baseEndsWithSlash && pathStartsWithSlash) {
  27. return base.slice(0, -1) + path;
  28. }
  29. if (!baseEndsWithSlash && !pathStartsWithSlash) {
  30. return `${base}/${path}`;
  31. }
  32. return base + path;
  33. }
  34. /**
  35. * get the path without filename (the last segment). for example, if the given
  36. * path is `/guide/getting-started.html`, this method will return `/guide/`.
  37. * Always with a trailing slash.
  38. */
  39. export function getPathDirName(path) {
  40. const segments = path.split('/');
  41. if (segments[segments.length - 1]) {
  42. segments.pop();
  43. }
  44. return ensureEndingSlash(segments.join('/'));
  45. }
  46. export function ensureEndingSlash(path) {
  47. return /(\.html|\/)$/.test(path) ? path : `${path}/`;
  48. }