|
1 |
| -import $ from 'jquery'; |
2 | 1 | import {svg} from '../svg.js';
|
3 | 2 | import {htmlEscape} from 'escape-goat';
|
4 | 3 | import {clippie} from 'clippie';
|
5 | 4 | import {showTemporaryTooltip} from '../modules/tippy.js';
|
6 |
| -import {POST} from '../modules/fetch.js'; |
| 5 | +import {GET, POST} from '../modules/fetch.js'; |
7 | 6 | import {showErrorToast} from '../modules/toast.js';
|
| 7 | +import {createElementFromHTML, createElementFromObject} from '../utils/dom.js'; |
8 | 8 |
|
9 | 9 | const {csrfToken, i18n} = window.config;
|
10 | 10 |
|
11 |
| -export async function createDropzone(el, opts) { |
| 11 | +async function createDropzone(el, opts) { |
12 | 12 | const [{Dropzone}] = await Promise.all([
|
13 | 13 | import(/* webpackChunkName: "dropzone" */'dropzone'),
|
14 | 14 | import(/* webpackChunkName: "dropzone" */'dropzone/dist/dropzone.css'),
|
15 | 15 | ]);
|
16 | 16 | return new Dropzone(el, opts);
|
17 | 17 | }
|
18 | 18 |
|
19 |
| -export function initGlobalDropzone() { |
20 |
| - for (const el of document.querySelectorAll('.dropzone')) { |
21 |
| - initDropzone(el); |
22 |
| - } |
| 19 | +function addCopyLink(file) { |
| 20 | + // Create a "Copy Link" element, to conveniently copy the image or file link as Markdown to the clipboard |
| 21 | + // The "<a>" element has a hardcoded cursor: pointer because the default is overridden by .dropzone |
| 22 | + const copyLinkEl = createElementFromHTML(` |
| 23 | +<div class="tw-text-center"> |
| 24 | + <a href="#" class="tw-cursor-pointer">${svg('octicon-copy', 14)} Copy link</a> |
| 25 | +</div>`); |
| 26 | + copyLinkEl.addEventListener('click', async (e) => { |
| 27 | + e.preventDefault(); |
| 28 | + let fileMarkdown = `[${file.name}](/attachments/${file.uuid})`; |
| 29 | + if (file.type?.startsWith('image/')) { |
| 30 | + fileMarkdown = `!${fileMarkdown}`; |
| 31 | + } else if (file.type?.startsWith('video/')) { |
| 32 | + fileMarkdown = `<video src="/attachments/${htmlEscape(file.uuid)}" title="${htmlEscape(file.name)}" controls></video>`; |
| 33 | + } |
| 34 | + const success = await clippie(fileMarkdown); |
| 35 | + showTemporaryTooltip(e.target, success ? i18n.copy_success : i18n.copy_error); |
| 36 | + }); |
| 37 | + file.previewTemplate.append(copyLinkEl); |
23 | 38 | }
|
24 | 39 |
|
25 |
| -export function initDropzone(el) { |
26 |
| - const $dropzone = $(el); |
27 |
| - const _promise = createDropzone(el, { |
28 |
| - url: $dropzone.data('upload-url'), |
| 40 | +/** |
| 41 | + * @param {HTMLElement} dropzoneEl |
| 42 | + */ |
| 43 | +export async function initDropzone(dropzoneEl) { |
| 44 | + if (!dropzoneEl) return null; |
| 45 | + |
| 46 | + const listAttachmentsUrl = dropzoneEl.closest('[data-attachment-url]')?.getAttribute('data-attachment-url'); |
| 47 | + const removeAttachmentUrl = dropzoneEl.getAttribute('data-remove-url'); |
| 48 | + const attachmentBaseLinkUrl = dropzoneEl.getAttribute('data-link-url'); |
| 49 | + |
| 50 | + let disableRemovedfileEvent = false; // when resetting the dropzone (removeAllFiles), disable the "removedfile" event |
| 51 | + let 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 |
| 52 | + const dzInst = await createDropzone(dropzoneEl, { |
| 53 | + url: dropzoneEl.getAttribute('data-upload-url'), |
29 | 54 | headers: {'X-Csrf-Token': csrfToken},
|
30 |
| - maxFiles: $dropzone.data('max-file'), |
31 |
| - maxFilesize: $dropzone.data('max-size'), |
32 |
| - acceptedFiles: (['*/*', ''].includes($dropzone.data('accepts'))) ? null : $dropzone.data('accepts'), |
| 55 | + maxFiles: dropzoneEl.getAttribute('data-max-file'), |
| 56 | + maxFilesize: dropzoneEl.getAttribute('data-max-size'), |
| 57 | + acceptedFiles: ['*/*', ''].includes(dropzoneEl.getAttribute('data-accepts')) ? null : dropzoneEl.getAttribute('data-accepts'), |
33 | 58 | addRemoveLinks: true,
|
34 |
| - dictDefaultMessage: $dropzone.data('default-message'), |
35 |
| - dictInvalidFileType: $dropzone.data('invalid-input-type'), |
36 |
| - dictFileTooBig: $dropzone.data('file-too-big'), |
37 |
| - dictRemoveFile: $dropzone.data('remove-file'), |
| 59 | + dictDefaultMessage: dropzoneEl.getAttribute('data-default-message'), |
| 60 | + dictInvalidFileType: dropzoneEl.getAttribute('data-invalid-input-type'), |
| 61 | + dictFileTooBig: dropzoneEl.getAttribute('data-file-too-big'), |
| 62 | + dictRemoveFile: dropzoneEl.getAttribute('data-remove-file'), |
38 | 63 | timeout: 0,
|
39 | 64 | thumbnailMethod: 'contain',
|
40 | 65 | thumbnailWidth: 480,
|
41 | 66 | thumbnailHeight: 480,
|
42 |
| - init() { |
43 |
| - this.on('success', (file, data) => { |
44 |
| - file.uuid = data.uuid; |
45 |
| - const $input = $(`<input id="${data.uuid}" name="files" type="hidden">`).val(data.uuid); |
46 |
| - $dropzone.find('.files').append($input); |
47 |
| - // Create a "Copy Link" element, to conveniently copy the image |
48 |
| - // or file link as Markdown to the clipboard |
49 |
| - const copyLinkElement = document.createElement('div'); |
50 |
| - copyLinkElement.className = 'tw-text-center'; |
51 |
| - // The a element has a hardcoded cursor: pointer because the default is overridden by .dropzone |
52 |
| - copyLinkElement.innerHTML = `<a href="#" style="cursor: pointer;">${svg('octicon-copy', 14, 'copy link')} Copy link</a>`; |
53 |
| - copyLinkElement.addEventListener('click', async (e) => { |
54 |
| - e.preventDefault(); |
55 |
| - let fileMarkdown = `[${file.name}](/attachments/${file.uuid})`; |
56 |
| - if (file.type.startsWith('image/')) { |
57 |
| - fileMarkdown = `!${fileMarkdown}`; |
58 |
| - } else if (file.type.startsWith('video/')) { |
59 |
| - fileMarkdown = `<video src="/attachments/${file.uuid}" title="${htmlEscape(file.name)}" controls></video>`; |
60 |
| - } |
61 |
| - const success = await clippie(fileMarkdown); |
62 |
| - showTemporaryTooltip(e.target, success ? i18n.copy_success : i18n.copy_error); |
63 |
| - }); |
64 |
| - file.previewTemplate.append(copyLinkElement); |
65 |
| - }); |
66 |
| - this.on('removedfile', (file) => { |
67 |
| - $(`#${file.uuid}`).remove(); |
68 |
| - if ($dropzone.data('remove-url')) { |
69 |
| - POST($dropzone.data('remove-url'), { |
70 |
| - data: new URLSearchParams({file: file.uuid}), |
71 |
| - }); |
72 |
| - } |
73 |
| - }); |
74 |
| - this.on('error', function (file, message) { |
75 |
| - showErrorToast(message); |
76 |
| - this.removeFile(file); |
77 |
| - }); |
78 |
| - }, |
79 | 67 | });
|
| 68 | + |
| 69 | + dzInst.on('success', (file, data) => { |
| 70 | + file.uuid = data.uuid; |
| 71 | + fileUuidDict[file.uuid] = {submitted: false}; |
| 72 | + const input = createElementFromObject('input', {name: 'files', type: 'hidden', id: `dropzone-file-${data.uuid}`, value: data.uuid}); |
| 73 | + dropzoneEl.querySelector('.files').append(input); |
| 74 | + addCopyLink(file); |
| 75 | + }); |
| 76 | + |
| 77 | + dzInst.on('removedfile', async (file) => { |
| 78 | + if (disableRemovedfileEvent) return; |
| 79 | + document.querySelector(`#dropzone-file-${file.uuid}`)?.remove(); |
| 80 | + if (removeAttachmentUrl && !fileUuidDict[file.uuid].submitted) { |
| 81 | + await POST(removeAttachmentUrl, {data: new URLSearchParams({file: file.uuid})}); |
| 82 | + } |
| 83 | + }); |
| 84 | + |
| 85 | + dzInst.on('submit', () => { |
| 86 | + for (const fileUuid of Object.keys(fileUuidDict)) { |
| 87 | + fileUuidDict[fileUuid].submitted = true; |
| 88 | + } |
| 89 | + }); |
| 90 | + |
| 91 | + dzInst.on('reload', async () => { |
| 92 | + try { |
| 93 | + const resp = await GET(listAttachmentsUrl); |
| 94 | + const respData = await resp.json(); |
| 95 | + // do not trigger the "removedfile" event, otherwise the attachments would be deleted from server |
| 96 | + disableRemovedfileEvent = true; |
| 97 | + dzInst.removeAllFiles(true); |
| 98 | + disableRemovedfileEvent = false; |
| 99 | + |
| 100 | + dropzoneEl.querySelector('.files').innerHTML = ''; |
| 101 | + for (const el of dropzoneEl.querySelectorAll('.dz-preview')) el.remove(); |
| 102 | + fileUuidDict = {}; |
| 103 | + for (const attachment of respData) { |
| 104 | + const imgSrc = `${attachmentBaseLinkUrl}/${attachment.uuid}`; |
| 105 | + dzInst.emit('addedfile', attachment); |
| 106 | + dzInst.emit('thumbnail', attachment, imgSrc); |
| 107 | + dzInst.emit('complete', attachment); |
| 108 | + addCopyLink(attachment); |
| 109 | + fileUuidDict[attachment.uuid] = {submitted: true}; |
| 110 | + const input = createElementFromObject('input', {name: 'files', type: 'hidden', id: `dropzone-file-${attachment.uuid}`, value: attachment.uuid}); |
| 111 | + dropzoneEl.querySelector('.files').append(input); |
| 112 | + } |
| 113 | + if (!dropzoneEl.querySelector('.dz-preview')) { |
| 114 | + dropzoneEl.classList.remove('dz-started'); |
| 115 | + } |
| 116 | + } catch (error) { |
| 117 | + // TODO: if listing the existing attachments failed, it should stop from operating the content or attachments, |
| 118 | + // otherwise the attachments might be lost. |
| 119 | + console.error(error); |
| 120 | + } |
| 121 | + }); |
| 122 | + |
| 123 | + dzInst.on('error', function (file, message) { |
| 124 | + showErrorToast(message); |
| 125 | + this.removeFile(file); |
| 126 | + }); |
| 127 | + |
| 128 | + if (listAttachmentsUrl) dzInst.emit('reload'); |
| 129 | + return dzInst; |
80 | 130 | }
|
0 commit comments