1 import Sortable from 'sortablejs';
2 import {Component} from './component';
3 import {buildListActions, sortActionClickListener} from '../services/dual-lists.ts';
5 export class ShelfSort extends Component {
9 this.input = this.$refs.input;
10 this.shelfBookList = this.$refs.shelfBookList;
11 this.allBookList = this.$refs.allBookList;
12 this.bookSearchInput = this.$refs.bookSearch;
13 this.sortButtonContainer = this.$refs.sortButtonContainer;
18 this.setupListeners();
22 const scrollBoxes = this.elem.querySelectorAll('.scroll-box');
23 for (const scrollBox of scrollBoxes) {
24 new Sortable(scrollBox, {
26 ghostClass: 'primary-background-light',
29 onSort: this.onChange.bind(this),
35 const listActions = buildListActions(this.allBookList, this.shelfBookList);
36 const sortActionListener = sortActionClickListener(listActions, this.onChange.bind(this));
37 this.elem.addEventListener('click', sortActionListener);
39 this.bookSearchInput.addEventListener('input', () => {
40 this.filterBooksByName(this.bookSearchInput.value);
43 this.sortButtonContainer.addEventListener('click', event => {
44 const button = event.target.closest('button[data-sort]');
46 this.sortShelfBooks(button.dataset.sort);
52 * @param {String} filterVal
54 filterBooksByName(filterVal) {
55 // Set height on first search, if not already set, to prevent the distraction
56 // of the list height jumping around
57 if (!this.allBookList.style.height) {
58 this.allBookList.style.height = `${this.allBookList.getBoundingClientRect().height}px`;
61 const books = this.allBookList.children;
62 const lowerFilter = filterVal.trim().toLowerCase();
64 for (const bookEl of books) {
65 const show = !filterVal || bookEl.textContent.toLowerCase().includes(lowerFilter);
66 bookEl.style.display = show ? null : 'none';
71 const shelfBookElems = Array.from(this.shelfBookList.querySelectorAll('[data-id]'));
72 this.input.value = shelfBookElems.map(elem => elem.getAttribute('data-id')).join(',');
75 sortShelfBooks(sortProperty) {
76 const books = Array.from(this.shelfBookList.children);
77 const reverse = sortProperty === this.lastSort;
79 books.sort((bookA, bookB) => {
80 const aProp = bookA.dataset[sortProperty].toLowerCase();
81 const bProp = bookB.dataset[sortProperty].toLowerCase();
84 return bProp.localeCompare(aProp);
87 return aProp.localeCompare(bProp);
90 for (const book of books) {
91 this.shelfBookList.append(book);
94 this.lastSort = (this.lastSort === sortProperty) ? null : sortProperty;