]> BookStack Code Mirror - bookstack/blob - resources/js/components/shelf-sort.js
Merge branch 'master' of git://github.com/almandin/BookStack into almandin-master
[bookstack] / resources / js / components / shelf-sort.js
1 import Sortable from "sortablejs";
2
3 class ShelfSort {
4
5     constructor(elem) {
6         this.elem = elem;
7         this.input = document.getElementById('books-input');
8         this.shelfBooksList = elem.querySelector('[shelf-sort-assigned-books]');
9
10         this.initSortable();
11         this.setupListeners();
12     }
13
14     initSortable() {
15         const scrollBoxes = this.elem.querySelectorAll('.scroll-box');
16         for (let scrollBox of scrollBoxes) {
17             new Sortable(scrollBox, {
18                 group: 'shelf-books',
19                 ghostClass: 'primary-background-light',
20                 animation: 150,
21                 onSort: this.onChange.bind(this),
22             });
23         }
24     }
25
26     setupListeners() {
27         this.elem.addEventListener('click', event => {
28             const sortItem = event.target.closest('.scroll-box-item:not(.instruction)');
29             if (sortItem) {
30                 event.preventDefault();
31                 this.sortItemClick(sortItem);
32             }
33         });
34     }
35
36     /**
37      * Called when a sort item is clicked.
38      * @param {Element} sortItem
39      */
40     sortItemClick(sortItem) {
41         const lists = this.elem.querySelectorAll('.scroll-box');
42         const newList = Array.from(lists).filter(list => sortItem.parentElement !== list);
43         if (newList.length > 0) {
44             newList[0].appendChild(sortItem);
45         }
46         this.onChange();
47     }
48
49     onChange() {
50         const shelfBookElems = Array.from(this.shelfBooksList.querySelectorAll('[data-id]'));
51         this.input.value = shelfBookElems.map(elem => elem.getAttribute('data-id')).join(',');
52     }
53
54 }
55
56 export default ShelfSort;