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