editLink.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import { computed } from 'vue';
  2. import { useData } from 'vitepress';
  3. import { endingSlashRE, isExternal } from '../utils';
  4. const bitbucketRE = /bitbucket.org/;
  5. export function useEditLink() {
  6. const { page, theme, frontmatter } = useData();
  7. const url = computed(() => {
  8. const { repo, docsDir = '', docsBranch = 'master', docsRepo = repo, editLinks } = theme.value;
  9. const showEditLink = frontmatter.value.editLink != null
  10. ? frontmatter.value.editLink
  11. : editLinks;
  12. const { relativePath } = page.value;
  13. if (!showEditLink || !relativePath || !repo) {
  14. return null;
  15. }
  16. return createUrl(repo, docsRepo, docsDir, docsBranch, relativePath);
  17. });
  18. const text = computed(() => {
  19. return theme.value.editLinkText || 'Edit this page';
  20. });
  21. return {
  22. url,
  23. text
  24. };
  25. }
  26. function createUrl(repo, docsRepo, docsDir, docsBranch, path) {
  27. return bitbucketRE.test(repo)
  28. ? createBitbucketUrl(repo, docsRepo, docsDir, docsBranch, path)
  29. : createGitHubUrl(repo, docsRepo, docsDir, docsBranch, path);
  30. }
  31. function createGitHubUrl(repo, docsRepo, docsDir, docsBranch, path) {
  32. const base = isExternal(docsRepo)
  33. ? docsRepo
  34. : `https://github.com/${docsRepo}`;
  35. return (base.replace(endingSlashRE, '') +
  36. `/edit` +
  37. `/${docsBranch}/` +
  38. (docsDir ? docsDir.replace(endingSlashRE, '') + '/' : '') +
  39. path);
  40. }
  41. function createBitbucketUrl(repo, docsRepo, docsDir, docsBranch, path) {
  42. const base = isExternal(docsRepo) ? docsRepo : repo;
  43. return (base.replace(endingSlashRE, '') +
  44. `/src` +
  45. `/${docsBranch}/` +
  46. (docsDir ? docsDir.replace(endingSlashRE, '') + '/' : '') +
  47. path +
  48. `?mode=edit&spa=0&at=${docsBranch}&fileviewer=file-view-default`);
  49. }