repo.ts 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import { computed } from 'vue'
  2. import { useSiteDataByRoute } from 'vitepress'
  3. import type { DefaultTheme } from '../config'
  4. export const platforms = ['GitHub', 'GitLab', 'Bitbucket'].map((platform) => {
  5. return [platform, new RegExp(platform, 'i')] as const
  6. })
  7. export function useRepo() {
  8. const site = useSiteDataByRoute()
  9. return computed(() => {
  10. const theme = site.value.themeConfig as DefaultTheme.Config
  11. const name = theme.docsRepo || theme.repo
  12. if (!name) {
  13. return null
  14. }
  15. const link = getRepoUrl(name)
  16. const text = getRepoText(link, theme.repoLabel)
  17. return { text, link }
  18. })
  19. }
  20. function getRepoUrl(repo: string): string {
  21. // if the full url is not provided, default to GitHub repo
  22. return /^https?:/.test(repo) ? repo : `https://github.com/${repo}`
  23. }
  24. function getRepoText(url: string, text?: string): string {
  25. if (text) {
  26. return text
  27. }
  28. // if no label is provided, deduce it from the repo url
  29. const hosts = url.match(/^https?:\/\/[^/]+/)
  30. if (!hosts) {
  31. return 'Source'
  32. }
  33. const platform = platforms.find(([_p, re]) => re.test(hosts[0]))
  34. if (platform && platform[0]) {
  35. return platform[0]
  36. }
  37. return 'Source'
  38. }