]> BookStack Code Mirror - bookstack/blob - resources/js/components/dropzone.js
Merge branch 'tinymce' into development
[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         this.successMessage = this.$opts.successMessage;
13         this.removeMessage = this.$opts.removeMessage;
14         this.uploadLimit = Number(this.$opts.uploadLimit);
15         this.uploadLimitMessage = this.$opts.uploadLimitMessage;
16         this.timeoutMessage = this.$opts.timeoutMessage;
17
18         const _this = this;
19         this.dz = new DropZoneLib(this.container, {
20             addRemoveLinks: true,
21             dictRemoveFile: this.removeMessage,
22             timeout: Number(window.uploadTimeout) || 60000,
23             maxFilesize: this.uploadLimit,
24             url: this.url,
25             withCredentials: true,
26             init() {
27                 this.dz = this;
28                 this.dz.on('sending', _this.onSending.bind(_this));
29                 this.dz.on('success', _this.onSuccess.bind(_this));
30                 this.dz.on('error', _this.onError.bind(_this));
31             }
32         });
33     }
34
35     onSending(file, xhr, data) {
36
37         const token = window.document.querySelector('meta[name=token]').getAttribute('content');
38         data.append('_token', token);
39
40         xhr.ontimeout = (e) => {
41             this.dz.emit('complete', file);
42             this.dz.emit('error', file, this.timeoutMessage);
43         }
44     }
45
46     onSuccess(file, data) {
47         this.$emit('success', {file, data});
48
49         if (this.successMessage) {
50             window.$events.emit('success', this.successMessage);
51         }
52
53         fadeOut(file.previewElement, 800, () => {
54             this.dz.removeFile(file);
55         });
56     }
57
58     onError(file, errorMessage, xhr) {
59         this.$emit('error', {file, errorMessage, xhr});
60
61         const setMessage = (message) => {
62             const messsageEl = file.previewElement.querySelector('[data-dz-errormessage]');
63             messsageEl.textContent = message;
64         }
65
66         if (xhr && xhr.status === 413) {
67             setMessage(this.uploadLimitMessage);
68         } else if (errorMessage.file) {
69             setMessage(errorMessage.file);
70         }
71     }
72
73     removeAll() {
74         this.dz.removeAllFiles(true);
75     }
76 }
77
78 export default Dropzone;