]> BookStack Code Mirror - bookstack/blob - resources/js/components/dropzone.js
ESLINT: Added GH action and details to dev docs
[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
7     setup() {
8         this.container = this.$el;
9         this.url = this.$opts.url;
10         this.successMessage = this.$opts.successMessage;
11         this.removeMessage = this.$opts.removeMessage;
12         this.uploadLimit = Number(this.$opts.uploadLimit);
13         this.uploadLimitMessage = this.$opts.uploadLimitMessage;
14         this.timeoutMessage = this.$opts.timeoutMessage;
15
16         const component = this;
17         this.dz = new DropZoneLib(this.container, {
18             addRemoveLinks: true,
19             dictRemoveFile: this.removeMessage,
20             timeout: Number(window.uploadTimeout) || 60000,
21             maxFilesize: this.uploadLimit,
22             url: this.url,
23             withCredentials: true,
24             init() {
25                 this.dz = this;
26                 this.dz.on('sending', component.onSending.bind(component));
27                 this.dz.on('success', component.onSuccess.bind(component));
28                 this.dz.on('error', component.onError.bind(component));
29             },
30         });
31     }
32
33     onSending(file, xhr, data) {
34         const token = window.document.querySelector('meta[name=token]').getAttribute('content');
35         data.append('_token', token);
36
37         xhr.ontimeout = () => {
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
74 }