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