Improve attachment upload methods (#30513)

* Use dropzone to handle file uploading for all cases, including pasting
and dragging
* Merge duplicate code, use consistent behavior for link generating

Close #20130

---------

Co-authored-by: silverwind <me@silverwind.io>
Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
This commit is contained in:
Tyrone Yeh 2024-06-27 17:31:49 +08:00 committed by GitHub
parent 00fc29aee1
commit 9bc5552c11
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
10 changed files with 169 additions and 97 deletions

View file

@ -5,9 +5,15 @@ import {showTemporaryTooltip} from '../modules/tippy.js';
import {GET, POST} from '../modules/fetch.js';
import {showErrorToast} from '../modules/toast.js';
import {createElementFromHTML, createElementFromAttrs} from '../utils/dom.js';
import {isImageFile, isVideoFile} from '../utils.js';
const {csrfToken, i18n} = window.config;
// dropzone has its owner event dispatcher (emitter)
export const DropzoneCustomEventReloadFiles = 'dropzone-custom-reload-files';
export const DropzoneCustomEventRemovedFile = 'dropzone-custom-removed-file';
export const DropzoneCustomEventUploadDone = 'dropzone-custom-upload-done';
async function createDropzone(el, opts) {
const [{Dropzone}] = await Promise.all([
import(/* webpackChunkName: "dropzone" */'dropzone'),
@ -16,6 +22,26 @@ async function createDropzone(el, opts) {
return new Dropzone(el, opts);
}
export function generateMarkdownLinkForAttachment(file, {width, dppx} = {}) {
let fileMarkdown = `[${file.name}](/attachments/${file.uuid})`;
if (isImageFile(file)) {
fileMarkdown = `!${fileMarkdown}`;
if (width > 0 && dppx > 1) {
// Scale down images from HiDPI monitors. This uses the <img> tag because it's the only
// method to change image size in Markdown that is supported by all implementations.
// Make the image link relative to the repo path, then the final URL is "/sub-path/owner/repo/attachments/{uuid}"
fileMarkdown = `<img width="${Math.round(width / dppx)}" alt="${htmlEscape(file.name)}" src="attachments/${htmlEscape(file.uuid)}">`;
} else {
// Markdown always renders the image with a relative path, so the final URL is "/sub-path/owner/repo/attachments/{uuid}"
// TODO: it should also use relative path for consistency, because absolute is ambiguous for "/sub-path/attachments" or "/attachments"
fileMarkdown = `![${file.name}](/attachments/${file.uuid})`;
}
} else if (isVideoFile(file)) {
fileMarkdown = `<video src="attachments/${htmlEscape(file.uuid)}" title="${htmlEscape(file.name)}" controls></video>`;
}
return fileMarkdown;
}
function addCopyLink(file) {
// Create a "Copy Link" element, to conveniently copy the image or file link as Markdown to the clipboard
// The "<a>" element has a hardcoded cursor: pointer because the default is overridden by .dropzone
@ -25,13 +51,7 @@ function addCopyLink(file) {
</div>`);
copyLinkEl.addEventListener('click', async (e) => {
e.preventDefault();
let fileMarkdown = `[${file.name}](/attachments/${file.uuid})`;
if (file.type?.startsWith('image/')) {
fileMarkdown = `!${fileMarkdown}`;
} else if (file.type?.startsWith('video/')) {
fileMarkdown = `<video src="/attachments/${htmlEscape(file.uuid)}" title="${htmlEscape(file.name)}" controls></video>`;
}
const success = await clippie(fileMarkdown);
const success = await clippie(generateMarkdownLinkForAttachment(file));
showTemporaryTooltip(e.target, success ? i18n.copy_success : i18n.copy_error);
});
file.previewTemplate.append(copyLinkEl);
@ -68,16 +88,19 @@ export async function initDropzone(dropzoneEl) {
// "http://localhost:3000/owner/repo/issues/[object%20Event]"
// 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]">'
const dzInst = await createDropzone(dropzoneEl, opts);
dzInst.on('success', (file, data) => {
file.uuid = data.uuid;
dzInst.on('success', (file, resp) => {
file.uuid = resp.uuid;
fileUuidDict[file.uuid] = {submitted: false};
const input = createElementFromAttrs('input', {name: 'files', type: 'hidden', id: `dropzone-file-${data.uuid}`, value: data.uuid});
const input = createElementFromAttrs('input', {name: 'files', type: 'hidden', id: `dropzone-file-${resp.uuid}`, value: resp.uuid});
dropzoneEl.querySelector('.files').append(input);
addCopyLink(file);
dzInst.emit(DropzoneCustomEventUploadDone, {file});
});
dzInst.on('removedfile', async (file) => {
if (disableRemovedfileEvent) return;
dzInst.emit(DropzoneCustomEventRemovedFile, {fileUuid: file.uuid});
document.querySelector(`#dropzone-file-${file.uuid}`)?.remove();
// 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
if (removeAttachmentUrl && fileUuidDict[file.uuid] && !fileUuidDict[file.uuid].submitted) {
@ -91,7 +114,7 @@ export async function initDropzone(dropzoneEl) {
}
});
dzInst.on('reload', async () => {
dzInst.on(DropzoneCustomEventReloadFiles, async () => {
try {
const resp = await GET(listAttachmentsUrl);
const respData = await resp.json();
@ -104,13 +127,14 @@ export async function initDropzone(dropzoneEl) {
for (const el of dropzoneEl.querySelectorAll('.dz-preview')) el.remove();
fileUuidDict = {};
for (const attachment of respData) {
const imgSrc = `${attachmentBaseLinkUrl}/${attachment.uuid}`;
dzInst.emit('addedfile', attachment);
dzInst.emit('thumbnail', attachment, imgSrc);
dzInst.emit('complete', attachment);
addCopyLink(attachment);
fileUuidDict[attachment.uuid] = {submitted: true};
const input = createElementFromAttrs('input', {name: 'files', type: 'hidden', id: `dropzone-file-${attachment.uuid}`, value: attachment.uuid});
const file = {name: attachment.name, uuid: attachment.uuid, size: attachment.size};
const imgSrc = `${attachmentBaseLinkUrl}/${file.uuid}`;
dzInst.emit('addedfile', file);
dzInst.emit('thumbnail', file, imgSrc);
dzInst.emit('complete', file);
addCopyLink(file); // it is from server response, so no "type"
fileUuidDict[file.uuid] = {submitted: true};
const input = createElementFromAttrs('input', {name: 'files', type: 'hidden', id: `dropzone-file-${file.uuid}`, value: file.uuid});
dropzoneEl.querySelector('.files').append(input);
}
if (!dropzoneEl.querySelector('.dz-preview')) {
@ -129,6 +153,6 @@ export async function initDropzone(dropzoneEl) {
dzInst.removeFile(file);
});
if (listAttachmentsUrl) dzInst.emit('reload');
if (listAttachmentsUrl) dzInst.emit(DropzoneCustomEventReloadFiles);
return dzInst;
}