]> BookStack Code Mirror - bookstack/blob - resources/js/components/image-manager.js
78abcf30d8b8c5465f360094f9a9d193be02dd5e
[bookstack] / resources / js / components / image-manager.js
1 import {
2     onChildEvent, onSelect, removeLoading, showLoading,
3 } from '../services/dom';
4 import {Component} from './component';
5
6 export class ImageManager extends Component {
7
8     setup() {
9         // Options
10         this.uploadedTo = this.$opts.uploadedTo;
11
12         // Element References
13         this.container = this.$el;
14         this.popupEl = this.$refs.popup;
15         this.searchForm = this.$refs.searchForm;
16         this.searchInput = this.$refs.searchInput;
17         this.cancelSearch = this.$refs.cancelSearch;
18         this.listContainer = this.$refs.listContainer;
19         this.filterTabs = this.$manyRefs.filterTabs;
20         this.selectButton = this.$refs.selectButton;
21         this.uploadButton = this.$refs.uploadButton;
22         this.uploadHint = this.$refs.uploadHint;
23         this.formContainer = this.$refs.formContainer;
24         this.formContainerPlaceholder = this.$refs.formContainerPlaceholder;
25         this.dropzoneContainer = this.$refs.dropzoneContainer;
26         this.loadMore = this.$refs.loadMore;
27
28         // Instance data
29         this.type = 'gallery';
30         this.lastSelected = {};
31         this.lastSelectedTime = 0;
32         this.callback = null;
33         this.resetState = () => {
34             this.hasData = false;
35             this.page = 1;
36             this.filter = 'all';
37         };
38         this.resetState();
39
40         this.setupListeners();
41     }
42
43     setupListeners() {
44         // Filter tab click
45         onSelect(this.filterTabs, e => {
46             this.resetAll();
47             this.filter = e.target.dataset.filter;
48             this.setActiveFilterTab(this.filter);
49             this.loadGallery();
50         });
51
52         // Search submit
53         this.searchForm.addEventListener('submit', event => {
54             this.resetListView();
55             this.loadGallery();
56             this.cancelSearch.toggleAttribute('hidden', !this.searchInput.value);
57             event.preventDefault();
58         });
59
60         // Cancel search button
61         onSelect(this.cancelSearch, () => {
62             this.resetListView();
63             this.resetSearchView();
64             this.loadGallery();
65         });
66
67         // Load more button click
68         onChildEvent(this.container, '.load-more button', 'click', this.runLoadMore.bind(this));
69
70         // Select image event
71         this.listContainer.addEventListener('event-emit-select-image', this.onImageSelectEvent.bind(this));
72
73         // Image load error handling
74         this.listContainer.addEventListener('error', event => {
75             event.target.src = window.baseUrl('loading_error.png');
76         }, true);
77
78         // Footer select button click
79         onSelect(this.selectButton, () => {
80             if (this.callback) {
81                 this.callback(this.lastSelected);
82             }
83             this.hide();
84         });
85
86         // Delete button click
87         onChildEvent(this.formContainer, '#image-manager-delete', 'click', () => {
88             if (this.lastSelected) {
89                 this.loadImageEditForm(this.lastSelected.id, true);
90             }
91         });
92
93         // Edit form submit
94         this.formContainer.addEventListener('ajax-form-success', () => {
95             this.refreshGallery();
96             this.resetEditForm();
97         });
98
99         // Image upload success
100         this.container.addEventListener('dropzone-upload-success', this.refreshGallery.bind(this));
101
102         // Auto load-more on scroll
103         const scrollZone = this.listContainer.parentElement;
104         let scrollEvents = [];
105         scrollZone.addEventListener('wheel', event => {
106             const scrollOffset = Math.ceil(scrollZone.scrollHeight - scrollZone.scrollTop);
107             const bottomedOut = scrollOffset === scrollZone.clientHeight;
108             if (!bottomedOut || event.deltaY < 1) {
109                 return;
110             }
111
112             const secondAgo = Date.now() - 1000;
113             scrollEvents.push(Date.now());
114             scrollEvents = scrollEvents.filter(d => d >= secondAgo);
115             if (scrollEvents.length > 5 && this.canLoadMore()) {
116                 this.runLoadMore();
117             }
118         });
119     }
120
121     show(callback, type = 'gallery') {
122         this.resetAll();
123
124         this.callback = callback;
125         this.type = type;
126         this.getPopup().show();
127
128         const hideUploads = type !== 'gallery';
129         this.dropzoneContainer.classList.toggle('hidden', hideUploads);
130         this.uploadButton.classList.toggle('hidden', hideUploads);
131         this.uploadHint.classList.toggle('hidden', hideUploads);
132
133         /** @var {Dropzone} * */
134         const dropzone = window.$components.firstOnElement(this.container, 'dropzone');
135         dropzone.toggleActive(!hideUploads);
136
137         if (!this.hasData) {
138             this.loadGallery();
139             this.hasData = true;
140         }
141     }
142
143     hide() {
144         this.getPopup().hide();
145     }
146
147     /**
148      * @returns {Popup}
149      */
150     getPopup() {
151         return window.$components.firstOnElement(this.popupEl, 'popup');
152     }
153
154     async loadGallery() {
155         const params = {
156             page: this.page,
157             search: this.searchInput.value || null,
158             uploaded_to: this.uploadedTo,
159             filter_type: this.filter === 'all' ? null : this.filter,
160         };
161
162         const {data: html} = await window.$http.get(`images/${this.type}`, params);
163         if (params.page === 1) {
164             this.listContainer.innerHTML = '';
165         }
166         this.addReturnedHtmlElementsToList(html);
167         removeLoading(this.listContainer);
168     }
169
170     addReturnedHtmlElementsToList(html) {
171         const el = document.createElement('div');
172         el.innerHTML = html;
173
174         const loadMore = el.querySelector('.load-more');
175         if (loadMore) {
176             loadMore.remove();
177             this.loadMore.innerHTML = loadMore.innerHTML;
178         }
179         this.loadMore.toggleAttribute('hidden', !loadMore);
180
181         window.$components.init(el);
182         for (const child of [...el.children]) {
183             this.listContainer.appendChild(child);
184         }
185     }
186
187     setActiveFilterTab(filterName) {
188         for (const tab of this.filterTabs) {
189             const selected = tab.dataset.filter === filterName;
190             tab.setAttribute('aria-selected', selected ? 'true' : 'false');
191         }
192     }
193
194     resetAll() {
195         this.resetState();
196         this.resetListView();
197         this.resetSearchView();
198         this.resetEditForm();
199         this.setActiveFilterTab('all');
200         this.selectButton.classList.add('hidden');
201     }
202
203     resetSearchView() {
204         this.searchInput.value = '';
205         this.cancelSearch.toggleAttribute('hidden', true);
206     }
207
208     resetEditForm() {
209         this.formContainer.innerHTML = '';
210         this.formContainerPlaceholder.removeAttribute('hidden');
211     }
212
213     resetListView() {
214         showLoading(this.listContainer);
215         this.page = 1;
216     }
217
218     refreshGallery() {
219         this.resetListView();
220         this.loadGallery();
221     }
222
223     onImageSelectEvent(event) {
224         const image = JSON.parse(event.detail.data);
225         const isDblClick = ((image && image.id === this.lastSelected.id)
226             && Date.now() - this.lastSelectedTime < 400);
227         const alreadySelected = event.target.classList.contains('selected');
228         [...this.listContainer.querySelectorAll('.selected')].forEach(el => {
229             el.classList.remove('selected');
230         });
231
232         if (!alreadySelected) {
233             event.target.classList.add('selected');
234             this.loadImageEditForm(image.id);
235         } else {
236             this.resetEditForm();
237         }
238         this.selectButton.classList.toggle('hidden', alreadySelected);
239
240         if (isDblClick && this.callback) {
241             this.callback(image);
242             this.hide();
243         }
244
245         this.lastSelected = image;
246         this.lastSelectedTime = Date.now();
247     }
248
249     async loadImageEditForm(imageId, requestDelete = false) {
250         if (!requestDelete) {
251             this.formContainer.innerHTML = '';
252         }
253
254         const params = requestDelete ? {delete: true} : {};
255         const {data: formHtml} = await window.$http.get(`/images/edit/${imageId}`, params);
256         this.formContainer.innerHTML = formHtml;
257         this.formContainerPlaceholder.setAttribute('hidden', '');
258         window.$components.init(this.formContainer);
259     }
260
261     runLoadMore() {
262         showLoading(this.loadMore);
263         this.page += 1;
264         this.loadGallery();
265     }
266
267     canLoadMore() {
268         return this.loadMore.querySelector('button') && !this.loadMore.hasAttribute('hidden');
269     }
270
271 }