]> BookStack Code Mirror - bookstack/blob - resources/js/components/image-manager.js
Comments: Addressed a range of edge cases and ux issues for references
[bookstack] / resources / js / components / image-manager.js
1 import {
2     onChildEvent, onSelect, removeLoading, showLoading,
3 } from '../services/dom.ts';
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         // Rebuild thumbs click
94         onChildEvent(this.formContainer, '#image-manager-rebuild-thumbs', 'click', async (_, button) => {
95             button.disabled = true;
96             if (this.lastSelected) {
97                 await this.rebuildThumbnails(this.lastSelected.id);
98             }
99             button.disabled = false;
100         });
101
102         // Edit form submit
103         this.formContainer.addEventListener('ajax-form-success', () => {
104             this.refreshGallery();
105             this.resetEditForm();
106         });
107
108         // Image upload success
109         this.container.addEventListener('dropzone-upload-success', this.refreshGallery.bind(this));
110
111         // Auto load-more on scroll
112         const scrollZone = this.listContainer.parentElement;
113         let scrollEvents = [];
114         scrollZone.addEventListener('wheel', event => {
115             const scrollOffset = Math.ceil(scrollZone.scrollHeight - scrollZone.scrollTop);
116             const bottomedOut = scrollOffset === scrollZone.clientHeight;
117             if (!bottomedOut || event.deltaY < 1) {
118                 return;
119             }
120
121             const secondAgo = Date.now() - 1000;
122             scrollEvents.push(Date.now());
123             scrollEvents = scrollEvents.filter(d => d >= secondAgo);
124             if (scrollEvents.length > 5 && this.canLoadMore()) {
125                 this.runLoadMore();
126             }
127         });
128     }
129
130     show(callback, type = 'gallery') {
131         this.resetAll();
132
133         this.callback = callback;
134         this.type = type;
135         this.getPopup().show();
136
137         const hideUploads = type !== 'gallery';
138         this.dropzoneContainer.classList.toggle('hidden', hideUploads);
139         this.uploadButton.classList.toggle('hidden', hideUploads);
140         this.uploadHint.classList.toggle('hidden', hideUploads);
141
142         /** @var {Dropzone} * */
143         const dropzone = window.$components.firstOnElement(this.container, 'dropzone');
144         dropzone.toggleActive(!hideUploads);
145
146         if (!this.hasData) {
147             this.loadGallery();
148             this.hasData = true;
149         }
150     }
151
152     hide() {
153         this.getPopup().hide();
154     }
155
156     /**
157      * @returns {Popup}
158      */
159     getPopup() {
160         return window.$components.firstOnElement(this.popupEl, 'popup');
161     }
162
163     async loadGallery() {
164         const params = {
165             page: this.page,
166             search: this.searchInput.value || null,
167             uploaded_to: this.uploadedTo,
168             filter_type: this.filter === 'all' ? null : this.filter,
169         };
170
171         const {data: html} = await window.$http.get(`images/${this.type}`, params);
172         if (params.page === 1) {
173             this.listContainer.innerHTML = '';
174         }
175         this.addReturnedHtmlElementsToList(html);
176         removeLoading(this.listContainer);
177     }
178
179     addReturnedHtmlElementsToList(html) {
180         const el = document.createElement('div');
181         el.innerHTML = html;
182
183         const loadMore = el.querySelector('.load-more');
184         if (loadMore) {
185             loadMore.remove();
186             this.loadMore.innerHTML = loadMore.innerHTML;
187         }
188         this.loadMore.toggleAttribute('hidden', !loadMore);
189
190         window.$components.init(el);
191         for (const child of [...el.children]) {
192             this.listContainer.appendChild(child);
193         }
194     }
195
196     setActiveFilterTab(filterName) {
197         for (const tab of this.filterTabs) {
198             const selected = tab.dataset.filter === filterName;
199             tab.setAttribute('aria-selected', selected ? 'true' : 'false');
200         }
201     }
202
203     resetAll() {
204         this.resetState();
205         this.resetListView();
206         this.resetSearchView();
207         this.resetEditForm();
208         this.setActiveFilterTab('all');
209         this.selectButton.classList.add('hidden');
210     }
211
212     resetSearchView() {
213         this.searchInput.value = '';
214         this.cancelSearch.toggleAttribute('hidden', true);
215     }
216
217     resetEditForm() {
218         this.formContainer.innerHTML = '';
219         this.formContainerPlaceholder.removeAttribute('hidden');
220     }
221
222     resetListView() {
223         showLoading(this.listContainer);
224         this.page = 1;
225     }
226
227     refreshGallery() {
228         this.resetListView();
229         this.loadGallery();
230     }
231
232     async onImageSelectEvent(event) {
233         let image = JSON.parse(event.detail.data);
234         const isDblClick = ((image && image.id === this.lastSelected.id)
235             && Date.now() - this.lastSelectedTime < 400);
236         const alreadySelected = event.target.classList.contains('selected');
237         [...this.listContainer.querySelectorAll('.selected')].forEach(el => {
238             el.classList.remove('selected');
239         });
240
241         if (!alreadySelected && !isDblClick) {
242             event.target.classList.add('selected');
243             image = await this.loadImageEditForm(image.id);
244         } else if (!isDblClick) {
245             this.resetEditForm();
246         } else if (isDblClick) {
247             image = this.lastSelected;
248         }
249
250         this.selectButton.classList.toggle('hidden', alreadySelected);
251
252         if (isDblClick && this.callback) {
253             this.callback(image);
254             this.hide();
255         }
256
257         this.lastSelected = image;
258         this.lastSelectedTime = Date.now();
259     }
260
261     async loadImageEditForm(imageId, requestDelete = false) {
262         if (!requestDelete) {
263             this.formContainer.innerHTML = '';
264         }
265
266         const params = requestDelete ? {delete: true} : {};
267         const {data: formHtml} = await window.$http.get(`/images/edit/${imageId}`, params);
268         this.formContainer.innerHTML = formHtml;
269         this.formContainerPlaceholder.setAttribute('hidden', '');
270         window.$components.init(this.formContainer);
271
272         const imageDataEl = this.formContainer.querySelector('#image-manager-form-image-data');
273         return JSON.parse(imageDataEl.text);
274     }
275
276     runLoadMore() {
277         showLoading(this.loadMore);
278         this.page += 1;
279         this.loadGallery();
280     }
281
282     canLoadMore() {
283         return this.loadMore.querySelector('button') && !this.loadMore.hasAttribute('hidden');
284     }
285
286     async rebuildThumbnails(imageId) {
287         try {
288             const response = await window.$http.put(`/images/${imageId}/rebuild-thumbnails`);
289             window.$events.success(response.data);
290             this.refreshGallery();
291         } catch (err) {
292             window.$events.showResponseError(err);
293         }
294     }
295
296 }