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