navLink.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import { computed } from 'vue';
  2. import { useRoute, withBase } from 'vitepress';
  3. import { isExternal as isExternalCheck } from '../utils';
  4. export function useNavLink(item) {
  5. const route = useRoute();
  6. const isExternal = isExternalCheck(item.value.link);
  7. const props = computed(() => {
  8. const routePath = normalizePath(`/${route.data.relativePath}`);
  9. let active = false;
  10. if (item.value.activeMatch) {
  11. active = new RegExp(item.value.activeMatch).test(routePath);
  12. }
  13. else {
  14. const itemPath = normalizePath(item.value.link);
  15. active =
  16. itemPath === '/'
  17. ? itemPath === routePath
  18. : routePath.startsWith(itemPath);
  19. }
  20. return {
  21. class: {
  22. active,
  23. isExternal
  24. },
  25. href: isExternal ? item.value.link : withBase(item.value.link),
  26. target: item.value.target || (isExternal ? `_blank` : null),
  27. rel: item.value.rel || (isExternal ? `noopener noreferrer` : null),
  28. 'aria-label': item.value.ariaLabel
  29. };
  30. });
  31. return {
  32. props,
  33. isExternal
  34. };
  35. }
  36. function normalizePath(path) {
  37. return path
  38. .replace(/#.*$/, '')
  39. .replace(/\?.*$/, '')
  40. .replace(/\.(html|md)$/, '')
  41. .replace(/\/index$/, '/');
  42. }