import { Controller } from '@hotwired/stimulus' import { useFetch } from '../mixins/use_fetch' import Dropzone from 'dropzone' Dropzone.autoDiscover = false /* stimulusFetch: 'lazy' */ export default class extends Controller { static targets = ['dropzone', 'errors', 'previewTemplate'] static values = { endpointUpload: String, endpointDelete: String, maxFiles: Number, maxFilesize: Number, acceptedFiles: String, chunking: Boolean, params: Object, language: Object, } connect () { useFetch(this) const dropzone = new Dropzone(this.dropzoneTarget, { url: this.endpointUploadValue, withCredentials: true, maxFiles: this.maxFilesValue, maxFilesize: this.maxFilesizeValue, acceptedFiles: this.acceptedFilesValue, chunking: true, chunkSize: 10000000, parallelUploads: 3, retryChunks: true, disablePreviews: false, previewTemplate: this.previewTemplateTarget.innerHTML, createImageThumbnails: true, autoProcessQueue: true, addRemoveLinks: false, dictFileTooBig: this.languageValue.fileTooBig, dictInvalidFileType: this.languageValue.invalidFileType, dictMaxFilesExceeded: this.languageValue.maxFilesExceeded, }) dropzone.on('addedfile', file => { this.errorsTarget.classList.add('hidden') }) dropzone.on('removedfile', (file) => { fetch(`${this.endpointDeleteValue}?uuid=${file.upload.uuid}`, { method: 'delete', credentials: 'include' }) }) dropzone.on('sending', (file, xhr, formData) => { if (this.hasParamsValue) { let keys = Object.keys(this.paramsValue) keys.forEach(key => { formData.append(key, this.paramsValue[key]) }) } formData.append('uuid', file.upload.uuid) formData.append('originalFilename', file.name) window.dispatchEvent(new CustomEvent('dropzone:uploading')) }) dropzone.on('queuecomplete', () => { window.dispatchEvent(new CustomEvent('dropzone:complete')) }) dropzone.on('error', (file, errorMessage) => { this.errorsTarget.innerText = errorMessage this.errorsTarget.classList.remove('hidden') dropzone.removeFile(file) }) } }