editLink.ts 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. import { computed } from 'vue'
  2. import { useSiteDataByRoute, usePageData } from 'vitepress'
  3. import { endingSlashRE, isNullish, isExternal } from '../utils'
  4. const bitbucketRE = /bitbucket.org/
  5. export function useEditLink() {
  6. const site = useSiteDataByRoute()
  7. const page = usePageData()
  8. const url = computed(() => {
  9. const showEditLink = isNullish(page.value.frontmatter.editLink)
  10. ? site.value.themeConfig.editLinks
  11. : page.value.frontmatter.editLink
  12. const {
  13. repo,
  14. docsDir = '',
  15. docsBranch = 'master',
  16. docsRepo = repo
  17. } = site.value.themeConfig
  18. const { relativePath } = page.value
  19. if (!showEditLink || !relativePath || !repo) {
  20. return null
  21. }
  22. return createUrl(repo, docsRepo, docsDir, docsBranch, relativePath)
  23. })
  24. const text = computed(() => {
  25. return site.value.themeConfig.editLinkText || 'Edit this page'
  26. })
  27. return {
  28. url,
  29. text
  30. }
  31. }
  32. function createUrl(
  33. repo: string,
  34. docsRepo: string,
  35. docsDir: string,
  36. docsBranch: string,
  37. path: string
  38. ): string {
  39. return bitbucketRE.test(repo)
  40. ? createBitbucketUrl(repo, docsRepo, docsDir, docsBranch, path)
  41. : createGitHubUrl(repo, docsRepo, docsDir, docsBranch, path)
  42. }
  43. function createGitHubUrl(
  44. repo: string,
  45. docsRepo: string,
  46. docsDir: string,
  47. docsBranch: string,
  48. path: string
  49. ): string {
  50. const base = isExternal(docsRepo)
  51. ? docsRepo
  52. : `https://github.com/${docsRepo}`
  53. return (
  54. base.replace(endingSlashRE, '') +
  55. `/edit` +
  56. `/${docsBranch}/` +
  57. (docsDir ? docsDir.replace(endingSlashRE, '') + '/' : '') +
  58. path
  59. )
  60. }
  61. function createBitbucketUrl(
  62. repo: string,
  63. docsRepo: string,
  64. docsDir: string,
  65. docsBranch: string,
  66. path: string
  67. ): string {
  68. const base = isExternal(docsRepo) ? docsRepo : repo
  69. return (
  70. base.replace(endingSlashRE, '') +
  71. `/src` +
  72. `/${docsBranch}/` +
  73. (docsDir ? docsDir.replace(endingSlashRE, '') + '/' : '') +
  74. path +
  75. `?mode=edit&spa=0&at=${docsBranch}&fileviewer=file-view-default`
  76. )
  77. }