]> BookStack Code Mirror - bookstack/blob - resources/js/components/dropzone.js
Started migration of attachment manager from vue
[bookstack] / resources / js / components / dropzone.js
1 import DropZoneLib from "dropzone";
2 import {fadeOut} from "../services/animations";
3
4 /**
5  * Dropzone
6  * @extends {Component}
7  */
8 class Dropzone {
9     setup() {
10         this.container = this.$el;
11         this.url = this.$opts.url;
12
13         const _this = this;
14         this.dz = new DropZoneLib(this.container, {
15             addRemoveLinks: true,
16             dictRemoveFile: window.trans('components.image_upload_remove'),
17             timeout: Number(window.uploadTimeout) || 60000,
18             maxFilesize: Number(window.uploadLimit) || 256,
19             url: this.url,
20             withCredentials: true,
21             init() {
22                 this.dz = this;
23                 this.dz.on('sending', _this.onSending.bind(_this));
24                 this.dz.on('success', _this.onSuccess.bind(_this));
25                 this.dz.on('error', _this.onError.bind(_this));
26             }
27         });
28     }
29
30     onSending(file, xhr, data) {
31
32         const token = window.document.querySelector('meta[name=token]').getAttribute('content');
33         data.append('_token', token);
34
35         xhr.ontimeout = function (e) {
36             this.dz.emit('complete', file);
37             this.dz.emit('error', file, window.trans('errors.file_upload_timeout'));
38         }
39     }
40
41     onSuccess(file, data) {
42         this.container.dispatchEvent(new Event('dropzone'))
43         this.$emit('success', {file, data});
44         fadeOut(file.previewElement, 800, () => {
45             this.dz.removeFile(file);
46         });
47     }
48
49     onError(file, errorMessage, xhr) {
50         this.$emit('error', {file, errorMessage, xhr});
51
52         const setMessage = (message) => {
53             const messsageEl = file.previewElement.querySelector('[data-dz-errormessage]');
54             messsageEl.textContent = message;
55         }
56
57         if (xhr && xhr.status === 413) {
58             setMessage(window.trans('errors.server_upload_limit'))
59         } else if (errorMessage.file) {
60             setMessage(errorMessage.file);
61         }
62     }
63
64     removeAll() {
65         this.dz.removeAllFiles(true);
66     }
67 }
68
69 export default Dropzone;