utils.js 1.9 KB

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