]> BookStack Code Mirror - bookstack/blob - resources/js/components/image-picker.js
7455fa622379a798ae102dd65dc7c72aed28417e
[bookstack] / resources / js / components / image-picker.js
1
2 class ImagePicker {
3
4     constructor(elem) {
5         this.elem = elem;
6         this.imageElem = elem.querySelector('img');
7         this.imageInput = elem.querySelector('input[type=file]');
8         this.resetInput = elem.querySelector('input[data-reset-input]');
9         this.removeInput = elem.querySelector('input[data-remove-input]');
10
11         this.defaultImage = elem.getAttribute('data-default-image');
12
13         const resetButton = elem.querySelector('button[data-action="reset-image"]');
14         resetButton.addEventListener('click', this.reset.bind(this));
15
16         const removeButton = elem.querySelector('button[data-action="remove-image"]');
17         if (removeButton) {
18             removeButton.addEventListener('click', this.removeImage.bind(this));
19         }
20
21         this.imageInput.addEventListener('change', this.fileInputChange.bind(this));
22     }
23
24     fileInputChange() {
25         this.resetInput.setAttribute('disabled', 'disabled');
26         if (this.removeInput) {
27             this.removeInput.setAttribute('disabled', 'disabled');
28         }
29
30         for (let file of this.imageInput.files) {
31             this.imageElem.src = window.URL.createObjectURL(file);
32         }
33         this.imageElem.classList.remove('none');
34     }
35
36     reset() {
37         this.imageInput.value = '';
38         this.imageElem.src = this.defaultImage;
39         this.resetInput.removeAttribute('disabled');
40         if (this.removeInput) {
41             this.removeInput.setAttribute('disabled', 'disabled');
42         }
43         this.imageElem.classList.remove('none');
44     }
45
46     removeImage() {
47         this.imageInput.value = '';
48         this.imageElem.classList.add('none');
49         this.removeInput.removeAttribute('disabled');
50         this.resetInput.setAttribute('disabled', 'disabled');
51     }
52
53 }
54
55 export default ImagePicker;