gitea源码

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. import {svg} from '../svg.ts';
  2. import {html} from '../utils/html.ts';
  3. import {clippie} from 'clippie';
  4. import {showTemporaryTooltip} from '../modules/tippy.ts';
  5. import {GET, POST} from '../modules/fetch.ts';
  6. import {showErrorToast} from '../modules/toast.ts';
  7. import {createElementFromHTML, createElementFromAttrs} from '../utils/dom.ts';
  8. import {isImageFile, isVideoFile} from '../utils.ts';
  9. import type {DropzoneFile, DropzoneOptions} from 'dropzone/index.js';
  10. const {csrfToken, i18n} = window.config;
  11. type CustomDropzoneFile = DropzoneFile & {uuid: string};
  12. // dropzone has its owner event dispatcher (emitter)
  13. export const DropzoneCustomEventReloadFiles = 'dropzone-custom-reload-files';
  14. export const DropzoneCustomEventRemovedFile = 'dropzone-custom-removed-file';
  15. export const DropzoneCustomEventUploadDone = 'dropzone-custom-upload-done';
  16. async function createDropzone(el: HTMLElement, opts: DropzoneOptions) {
  17. const [{default: Dropzone}] = await Promise.all([
  18. import(/* webpackChunkName: "dropzone" */'dropzone'),
  19. import(/* webpackChunkName: "dropzone" */'dropzone/dist/dropzone.css'),
  20. ]);
  21. return new Dropzone(el, opts);
  22. }
  23. export function generateMarkdownLinkForAttachment(file: Partial<CustomDropzoneFile>, {width, dppx}: {width?: number, dppx?: number} = {}) {
  24. let fileMarkdown = `[${file.name}](/attachments/${file.uuid})`;
  25. if (isImageFile(file)) {
  26. fileMarkdown = `!${fileMarkdown}`;
  27. if (width > 0 && dppx > 1) {
  28. // Scale down images from HiDPI monitors. This uses the <img> tag because it's the only
  29. // method to change image size in Markdown that is supported by all implementations.
  30. // Make the image link relative to the repo path, then the final URL is "/sub-path/owner/repo/attachments/{uuid}"
  31. fileMarkdown = html`<img width="${Math.round(width / dppx)}" alt="${file.name}" src="attachments/${file.uuid}">`;
  32. } else {
  33. // Markdown always renders the image with a relative path, so the final URL is "/sub-path/owner/repo/attachments/{uuid}"
  34. // TODO: it should also use relative path for consistency, because absolute is ambiguous for "/sub-path/attachments" or "/attachments"
  35. fileMarkdown = `![${file.name}](/attachments/${file.uuid})`;
  36. }
  37. } else if (isVideoFile(file)) {
  38. fileMarkdown = html`<video src="attachments/${file.uuid}" title="${file.name}" controls></video>`;
  39. }
  40. return fileMarkdown;
  41. }
  42. function addCopyLink(file: Partial<CustomDropzoneFile>) {
  43. // Create a "Copy Link" element, to conveniently copy the image or file link as Markdown to the clipboard
  44. // The "<a>" element has a hardcoded cursor: pointer because the default is overridden by .dropzone
  45. const copyLinkEl = createElementFromHTML(`
  46. <div class="tw-text-center">
  47. <a href="#" class="tw-cursor-pointer">${svg('octicon-copy', 14)} Copy link</a>
  48. </div>`);
  49. copyLinkEl.addEventListener('click', async (e) => {
  50. e.preventDefault();
  51. const success = await clippie(generateMarkdownLinkForAttachment(file));
  52. showTemporaryTooltip(e.target as Element, success ? i18n.copy_success : i18n.copy_error);
  53. });
  54. file.previewTemplate.append(copyLinkEl);
  55. }
  56. type FileUuidDict = Record<string, {submitted: boolean}>;
  57. /**
  58. * @param {HTMLElement} dropzoneEl
  59. */
  60. export async function initDropzone(dropzoneEl: HTMLElement) {
  61. const listAttachmentsUrl = dropzoneEl.closest('[data-attachment-url]')?.getAttribute('data-attachment-url');
  62. const removeAttachmentUrl = dropzoneEl.getAttribute('data-remove-url');
  63. const attachmentBaseLinkUrl = dropzoneEl.getAttribute('data-link-url');
  64. let disableRemovedfileEvent = false; // when resetting the dropzone (removeAllFiles), disable the "removedfile" event
  65. let fileUuidDict: FileUuidDict = {}; // to record: if a comment has been saved, then the uploaded files won't be deleted from server when clicking the Remove in the dropzone
  66. const opts: Record<string, any> = {
  67. url: dropzoneEl.getAttribute('data-upload-url'),
  68. headers: {'X-Csrf-Token': csrfToken},
  69. acceptedFiles: ['*/*', ''].includes(dropzoneEl.getAttribute('data-accepts')) ? null : dropzoneEl.getAttribute('data-accepts'),
  70. addRemoveLinks: true,
  71. dictDefaultMessage: dropzoneEl.getAttribute('data-default-message'),
  72. dictInvalidFileType: dropzoneEl.getAttribute('data-invalid-input-type'),
  73. dictFileTooBig: dropzoneEl.getAttribute('data-file-too-big'),
  74. dictRemoveFile: dropzoneEl.getAttribute('data-remove-file'),
  75. timeout: 0,
  76. thumbnailMethod: 'contain',
  77. thumbnailWidth: 480,
  78. thumbnailHeight: 480,
  79. };
  80. if (dropzoneEl.hasAttribute('data-max-file')) opts.maxFiles = Number(dropzoneEl.getAttribute('data-max-file'));
  81. if (dropzoneEl.hasAttribute('data-max-size')) opts.maxFilesize = Number(dropzoneEl.getAttribute('data-max-size'));
  82. // there is a bug in dropzone: if a non-image file is uploaded, then it tries to request the file from server by something like:
  83. // "http://localhost:3000/owner/repo/issues/[object%20Event]"
  84. // the reason is that the preview "callback(dataURL)" is assign to "img.onerror" then "thumbnail" uses the error object as the dataURL and generates '<img src="[object Event]">'
  85. const dzInst = await createDropzone(dropzoneEl, opts);
  86. dzInst.on('success', (file: CustomDropzoneFile, resp: any) => {
  87. file.uuid = resp.uuid;
  88. fileUuidDict[file.uuid] = {submitted: false};
  89. const input = createElementFromAttrs('input', {name: 'files', type: 'hidden', id: `dropzone-file-${resp.uuid}`, value: resp.uuid});
  90. dropzoneEl.querySelector('.files').append(input);
  91. addCopyLink(file);
  92. dzInst.emit(DropzoneCustomEventUploadDone, {file});
  93. });
  94. dzInst.on('removedfile', async (file: CustomDropzoneFile) => {
  95. if (disableRemovedfileEvent) return;
  96. dzInst.emit(DropzoneCustomEventRemovedFile, {fileUuid: file.uuid});
  97. document.querySelector(`#dropzone-file-${file.uuid}`)?.remove();
  98. // when the uploaded file number reaches the limit, there is no uuid in the dict, and it doesn't need to be removed from server
  99. if (removeAttachmentUrl && fileUuidDict[file.uuid] && !fileUuidDict[file.uuid].submitted) {
  100. await POST(removeAttachmentUrl, {data: new URLSearchParams({file: file.uuid})});
  101. }
  102. });
  103. dzInst.on('submit', () => {
  104. for (const fileUuid of Object.keys(fileUuidDict)) {
  105. fileUuidDict[fileUuid].submitted = true;
  106. }
  107. });
  108. dzInst.on(DropzoneCustomEventReloadFiles, async () => {
  109. try {
  110. const resp = await GET(listAttachmentsUrl);
  111. const respData = await resp.json();
  112. // do not trigger the "removedfile" event, otherwise the attachments would be deleted from server
  113. disableRemovedfileEvent = true;
  114. dzInst.removeAllFiles(true);
  115. disableRemovedfileEvent = false;
  116. dropzoneEl.querySelector('.files').innerHTML = '';
  117. for (const el of dropzoneEl.querySelectorAll('.dz-preview')) el.remove();
  118. fileUuidDict = {};
  119. for (const attachment of respData) {
  120. const file = {name: attachment.name, uuid: attachment.uuid, size: attachment.size};
  121. dzInst.emit('addedfile', file);
  122. dzInst.emit('complete', file);
  123. if (isImageFile(file.name)) {
  124. const imgSrc = `${attachmentBaseLinkUrl}/${file.uuid}`;
  125. dzInst.emit('thumbnail', file, imgSrc);
  126. }
  127. addCopyLink(file); // it is from server response, so no "type"
  128. fileUuidDict[file.uuid] = {submitted: true};
  129. const input = createElementFromAttrs('input', {name: 'files', type: 'hidden', id: `dropzone-file-${file.uuid}`, value: file.uuid});
  130. dropzoneEl.querySelector('.files').append(input);
  131. }
  132. if (!dropzoneEl.querySelector('.dz-preview')) {
  133. dropzoneEl.classList.remove('dz-started');
  134. }
  135. } catch (error) {
  136. // TODO: if listing the existing attachments failed, it should stop from operating the content or attachments,
  137. // otherwise the attachments might be lost.
  138. showErrorToast(`Failed to load attachments: ${error}`);
  139. console.error(error);
  140. }
  141. });
  142. dzInst.on('error', (file, message) => {
  143. showErrorToast(`Dropzone upload error: ${message}`);
  144. dzInst.removeFile(file);
  145. });
  146. if (listAttachmentsUrl) dzInst.emit(DropzoneCustomEventReloadFiles);
  147. return dzInst;
  148. }