]> BookStack Code Mirror - bookstack/blob - resources/js/components/image-manager.js
Merge pull request #5731 from BookStackApp/lexical_jul25
[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     /**
131      * @param {({ thumbs: { display: string; }; url: string; name: string; }) => void} callback
132      * @param {String} type
133      */
134     show(callback, type = 'gallery') {
135         this.resetAll();
136
137         this.callback = callback;
138         this.type = type;
139         this.getPopup().show();
140
141         const hideUploads = type !== 'gallery';
142         this.dropzoneContainer.classList.toggle('hidden', hideUploads);
143         this.uploadButton.classList.toggle('hidden', hideUploads);
144         this.uploadHint.classList.toggle('hidden', hideUploads);
145
146         /** @var {Dropzone} * */
147         const dropzone = window.$components.firstOnElement(this.container, 'dropzone');
148         dropzone.toggleActive(!hideUploads);
149
150         if (!this.hasData) {
151             this.loadGallery();
152             this.hasData = true;
153         }
154     }
155
156     hide() {
157         this.getPopup().hide();
158     }
159
160     /**
161      * @returns {Popup}
162      */
163     getPopup() {
164         return window.$components.firstOnElement(this.popupEl, 'popup');
165     }
166
167     async loadGallery() {
168         const params = {
169             page: this.page,
170             search: this.searchInput.value || null,
171             uploaded_to: this.uploadedTo,
172             filter_type: this.filter === 'all' ? null : this.filter,
173         };
174
175         const {data: html} = await window.$http.get(`images/${this.type}`, params);
176         if (params.page === 1) {
177             this.listContainer.innerHTML = '';
178         }
179         this.addReturnedHtmlElementsToList(html);
180         removeLoading(this.listContainer);
181     }
182
183     addReturnedHtmlElementsToList(html) {
184         const el = document.createElement('div');
185         el.innerHTML = html;
186
187         const loadMore = el.querySelector('.load-more');
188         if (loadMore) {
189             loadMore.remove();
190             this.loadMore.innerHTML = loadMore.innerHTML;
191         }
192         this.loadMore.toggleAttribute('hidden', !loadMore);
193
194         window.$components.init(el);
195         for (const child of [...el.children]) {
196             this.listContainer.appendChild(child);
197         }
198     }
199
200     setActiveFilterTab(filterName) {
201         for (const tab of this.filterTabs) {
202             const selected = tab.dataset.filter === filterName;
203             tab.setAttribute('aria-selected', selected ? 'true' : 'false');
204         }
205     }
206
207     resetAll() {
208         this.resetState();
209         this.resetListView();
210         this.resetSearchView();
211         this.resetEditForm();
212         this.setActiveFilterTab('all');
213         this.selectButton.classList.add('hidden');
214     }
215
216     resetSearchView() {
217         this.searchInput.value = '';
218         this.cancelSearch.toggleAttribute('hidden', true);
219     }
220
221     resetEditForm() {
222         this.formContainer.innerHTML = '';
223         this.formContainerPlaceholder.removeAttribute('hidden');
224     }
225
226     resetListView() {
227         showLoading(this.listContainer);
228         this.page = 1;
229     }
230
231     refreshGallery() {
232         this.resetListView();
233         this.loadGallery();
234     }
235
236     async onImageSelectEvent(event) {
237         let image = JSON.parse(event.detail.data);
238         const isDblClick = ((image && image.id === this.lastSelected.id)
239             && Date.now() - this.lastSelectedTime < 400);
240         const alreadySelected = event.target.classList.contains('selected');
241         [...this.listContainer.querySelectorAll('.selected')].forEach(el => {
242             el.classList.remove('selected');
243         });
244
245         if (!alreadySelected && !isDblClick) {
246             event.target.classList.add('selected');
247             image = await this.loadImageEditForm(image.id);
248         } else if (!isDblClick) {
249             this.resetEditForm();
250         } else if (isDblClick) {
251             image = this.lastSelected;
252         }
253
254         this.selectButton.classList.toggle('hidden', alreadySelected);
255
256         if (isDblClick && this.callback) {
257             this.callback(image);
258             this.hide();
259         }
260
261         this.lastSelected = image;
262         this.lastSelectedTime = Date.now();
263     }
264
265     async loadImageEditForm(imageId, requestDelete = false) {
266         if (!requestDelete) {
267             this.formContainer.innerHTML = '';
268         }
269
270         const params = requestDelete ? {delete: true} : {};
271         const {data: formHtml} = await window.$http.get(`/images/edit/${imageId}`, params);
272         this.formContainer.innerHTML = formHtml;
273         this.formContainerPlaceholder.setAttribute('hidden', '');
274         window.$components.init(this.formContainer);
275
276         const imageDataEl = this.formContainer.querySelector('#image-manager-form-image-data');
277         return JSON.parse(imageDataEl.text);
278     }
279
280     runLoadMore() {
281         showLoading(this.loadMore);
282         this.page += 1;
283         this.loadGallery();
284     }
285
286     canLoadMore() {
287         return this.loadMore.querySelector('button') && !this.loadMore.hasAttribute('hidden');
288     }
289
290     async rebuildThumbnails(imageId) {
291         try {
292             const response = await window.$http.put(`/images/${imageId}/rebuild-thumbnails`);
293             window.$events.success(response.data);
294             this.refreshGallery();
295         } catch (err) {
296             window.$events.showResponseError(err);
297         }
298     }
299
300 }