gitea源码

repo-common.ts 5.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. import {queryElems, type DOMEvent} from '../utils/dom.ts';
  2. import {POST} from '../modules/fetch.ts';
  3. import {showErrorToast} from '../modules/toast.ts';
  4. import {sleep} from '../utils.ts';
  5. import RepoActivityTopAuthors from '../components/RepoActivityTopAuthors.vue';
  6. import {createApp} from 'vue';
  7. import {toOriginUrl} from '../utils/url.ts';
  8. import {createTippy} from '../modules/tippy.ts';
  9. async function onDownloadArchive(e: DOMEvent<MouseEvent>) {
  10. e.preventDefault();
  11. // there are many places using the "archive-link", eg: the dropdown on the repo code page, the release list
  12. const el = e.target.closest<HTMLAnchorElement>('a.archive-link[href]');
  13. const targetLoading = el.closest('.ui.dropdown') ?? el;
  14. targetLoading.classList.add('is-loading', 'loading-icon-2px');
  15. try {
  16. for (let tryCount = 0; ;tryCount++) {
  17. const response = await POST(el.href);
  18. if (!response.ok) throw new Error(`Invalid server response: ${response.status}`);
  19. const data = await response.json();
  20. if (data.complete) break;
  21. await sleep(Math.min((tryCount + 1) * 750, 2000));
  22. }
  23. window.location.href = el.href; // the archive is ready, start real downloading
  24. } catch (e) {
  25. console.error(e);
  26. showErrorToast(`Failed to download the archive: ${e}`, {duration: 2500});
  27. } finally {
  28. targetLoading.classList.remove('is-loading', 'loading-icon-2px');
  29. }
  30. }
  31. export function initRepoArchiveLinks() {
  32. queryElems(document, 'a.archive-link[href]', (el) => el.addEventListener('click', onDownloadArchive));
  33. }
  34. export function initRepoActivityTopAuthorsChart() {
  35. const el = document.querySelector('#repo-activity-top-authors-chart');
  36. if (el) {
  37. createApp(RepoActivityTopAuthors).mount(el);
  38. }
  39. }
  40. export function substituteRepoOpenWithUrl(tmpl: string, url: string): string {
  41. const pos = tmpl.indexOf('{url}');
  42. if (pos === -1) return tmpl;
  43. const posQuestionMark = tmpl.indexOf('?');
  44. const needEncode = posQuestionMark >= 0 && posQuestionMark < pos;
  45. return tmpl.replace('{url}', needEncode ? encodeURIComponent(url) : url);
  46. }
  47. function initCloneSchemeUrlSelection(parent: Element) {
  48. const elCloneUrlInput = parent.querySelector<HTMLInputElement>('.repo-clone-url');
  49. const tabHttps = parent.querySelector('.repo-clone-https');
  50. const tabSsh = parent.querySelector('.repo-clone-ssh');
  51. const tabTea = parent.querySelector('.repo-clone-tea');
  52. const updateClonePanelUi = function() {
  53. let scheme = localStorage.getItem('repo-clone-protocol');
  54. if (!['https', 'ssh', 'tea'].includes(scheme)) {
  55. scheme = 'https';
  56. }
  57. // Fallbacks if the scheme preference is not available in the tabs, for example: empty repo page, there are only HTTPS and SSH
  58. if (scheme === 'tea' && !tabTea) {
  59. scheme = 'https';
  60. }
  61. if (scheme === 'https' && !tabHttps) {
  62. scheme = 'ssh';
  63. } else if (scheme === 'ssh' && !tabSsh) {
  64. scheme = 'https';
  65. }
  66. const isHttps = scheme === 'https';
  67. const isSsh = scheme === 'ssh';
  68. const isTea = scheme === 'tea';
  69. if (tabHttps) {
  70. tabHttps.textContent = window.origin.split(':')[0].toUpperCase(); // show "HTTP" or "HTTPS"
  71. tabHttps.classList.toggle('active', isHttps);
  72. }
  73. if (tabSsh) {
  74. tabSsh.classList.toggle('active', isSsh);
  75. }
  76. if (tabTea) {
  77. tabTea.classList.toggle('active', isTea);
  78. }
  79. let tab: Element;
  80. if (isHttps) {
  81. tab = tabHttps;
  82. } else if (isSsh) {
  83. tab = tabSsh;
  84. } else if (isTea) {
  85. tab = tabTea;
  86. }
  87. if (!tab) return;
  88. const link = toOriginUrl(tab.getAttribute('data-link'));
  89. for (const el of document.querySelectorAll('.js-clone-url')) {
  90. if (el.nodeName === 'INPUT') {
  91. (el as HTMLInputElement).value = link;
  92. } else {
  93. el.textContent = link;
  94. }
  95. }
  96. for (const el of parent.querySelectorAll<HTMLAnchorElement>('.js-clone-url-editor')) {
  97. el.href = substituteRepoOpenWithUrl(el.getAttribute('data-href-template'), link);
  98. }
  99. };
  100. updateClonePanelUi();
  101. // tabSsh or tabHttps might not both exist, eg: guest view, or one is disabled by the server
  102. tabHttps?.addEventListener('click', () => {
  103. localStorage.setItem('repo-clone-protocol', 'https');
  104. updateClonePanelUi();
  105. });
  106. tabSsh?.addEventListener('click', () => {
  107. localStorage.setItem('repo-clone-protocol', 'ssh');
  108. updateClonePanelUi();
  109. });
  110. tabTea?.addEventListener('click', () => {
  111. localStorage.setItem('repo-clone-protocol', 'tea');
  112. updateClonePanelUi();
  113. });
  114. elCloneUrlInput.addEventListener('focus', () => {
  115. elCloneUrlInput.select();
  116. });
  117. }
  118. function initClonePanelButton(btn: HTMLButtonElement) {
  119. const elPanel = btn.nextElementSibling;
  120. // "init" must be before the "createTippy" otherwise the "tippy-target" will be removed from the document
  121. initCloneSchemeUrlSelection(elPanel);
  122. createTippy(btn, {
  123. content: elPanel,
  124. trigger: 'click',
  125. placement: 'bottom-end',
  126. interactive: true,
  127. hideOnClick: true,
  128. arrow: false,
  129. });
  130. }
  131. export function initRepoCloneButtons() {
  132. queryElems(document, '.js-btn-clone-panel', initClonePanelButton);
  133. queryElems(document, '.clone-buttons-combo', initCloneSchemeUrlSelection);
  134. }
  135. export async function updateIssuesMeta(url: string, action: string, issue_ids: string, id: string) {
  136. try {
  137. const response = await POST(url, {data: new URLSearchParams({action, issue_ids, id})});
  138. if (!response.ok) {
  139. throw new Error('Failed to update issues meta');
  140. }
  141. } catch (error) {
  142. console.error(error);
  143. }
  144. }
  145. export function sanitizeRepoName(name: string): string {
  146. name = name.trim().replace(/[^-.\w]/g, '-');
  147. for (let lastName = ''; lastName !== name;) {
  148. lastName = name;
  149. name = name.replace(/\.+$/g, '');
  150. name = name.replace(/\.{2,}/g, '.');
  151. for (const ext of ['.git', '.wiki', '.rss', '.atom']) {
  152. if (name.endsWith(ext)) {
  153. name = name.substring(0, name.length - ext.length);
  154. }
  155. }
  156. }
  157. if (['.', '..', '-'].includes(name)) name = '';
  158. return name;
  159. }