]> BookStack Code Mirror - bookstack/blob - resources/js/components/shelf-sort.js
Added shortcut input controls to make custom shortcuts work
[bookstack] / resources / js / components / shelf-sort.js
1 import Sortable from "sortablejs";
2
3 class ShelfSort {
4
5     setup() {
6         this.elem = this.$el;
7         this.input = this.$refs.input;
8         this.shelfBookList = this.$refs.shelfBookList;
9         this.allBookList = this.$refs.allBookList;
10         this.bookSearchInput = this.$refs.bookSearch;
11
12         this.initSortable();
13         this.setupListeners();
14     }
15
16     initSortable() {
17         const scrollBoxes = this.elem.querySelectorAll('.scroll-box');
18         for (let scrollBox of scrollBoxes) {
19             new Sortable(scrollBox, {
20                 group: 'shelf-books',
21                 ghostClass: 'primary-background-light',
22                 handle: '.handle',
23                 animation: 150,
24                 onSort: this.onChange.bind(this),
25             });
26         }
27     }
28
29     setupListeners() {
30         this.elem.addEventListener('click', event => {
31             const sortItem = event.target.closest('.scroll-box-item');
32             if (sortItem) {
33                 event.preventDefault();
34                 this.sortItemClick(sortItem);
35             }
36         });
37
38         this.bookSearchInput.addEventListener('input', event => {
39             this.filterBooksByName(this.bookSearchInput.value);
40         });
41     }
42
43     /**
44      * @param {String} filterVal
45      */
46     filterBooksByName(filterVal) {
47
48         // Set height on first search, if not already set, to prevent the distraction
49         // of the list height jumping around
50         if (!this.allBookList.style.height) {
51             this.allBookList.style.height = this.allBookList.getBoundingClientRect().height + 'px';
52         }
53
54         const books = this.allBookList.children;
55         const lowerFilter = filterVal.trim().toLowerCase();
56
57         for (const bookEl of books) {
58             const show = !filterVal || bookEl.textContent.toLowerCase().includes(lowerFilter);
59             bookEl.style.display = show ? null : 'none';
60         }
61     }
62
63     /**
64      * Called when a sort item is clicked.
65      * @param {Element} sortItem
66      */
67     sortItemClick(sortItem) {
68         const lists = this.elem.querySelectorAll('.scroll-box');
69         const newList = Array.from(lists).filter(list => sortItem.parentElement !== list);
70         if (newList.length > 0) {
71             newList[0].appendChild(sortItem);
72         }
73         this.onChange();
74     }
75
76     onChange() {
77         const shelfBookElems = Array.from(this.shelfBookList.querySelectorAll('[data-id]'));
78         this.input.value = shelfBookElems.map(elem => elem.getAttribute('data-id')).join(',');
79     }
80
81 }
82
83 export default ShelfSort;