2019-06-06 12:49:51 +02:00
|
|
|
import Sortable from "sortablejs";
|
2018-08-27 15:18:09 +02:00
|
|
|
|
|
|
|
class ShelfSort {
|
|
|
|
|
|
|
|
constructor(elem) {
|
|
|
|
this.elem = elem;
|
|
|
|
this.input = document.getElementById('books-input');
|
2019-06-06 12:49:51 +02:00
|
|
|
this.shelfBooksList = elem.querySelector('[shelf-sort-assigned-books]');
|
|
|
|
|
|
|
|
this.initSortable();
|
2018-09-16 17:59:01 +02:00
|
|
|
this.setupListeners();
|
2018-08-27 15:18:09 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
initSortable() {
|
2019-06-06 12:49:51 +02:00
|
|
|
const scrollBoxes = this.elem.querySelectorAll('.scroll-box');
|
|
|
|
for (let scrollBox of scrollBoxes) {
|
|
|
|
new Sortable(scrollBox, {
|
|
|
|
group: 'shelf-books',
|
|
|
|
ghostClass: 'primary-background-light',
|
|
|
|
animation: 150,
|
|
|
|
onSort: this.onChange.bind(this),
|
|
|
|
});
|
|
|
|
}
|
2018-08-27 15:18:09 +02:00
|
|
|
}
|
|
|
|
|
2018-09-16 17:59:01 +02:00
|
|
|
setupListeners() {
|
|
|
|
this.elem.addEventListener('click', event => {
|
|
|
|
const sortItem = event.target.closest('.scroll-box-item:not(.instruction)');
|
|
|
|
if (sortItem) {
|
|
|
|
event.preventDefault();
|
|
|
|
this.sortItemClick(sortItem);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Called when a sort item is clicked.
|
|
|
|
* @param {Element} sortItem
|
|
|
|
*/
|
|
|
|
sortItemClick(sortItem) {
|
|
|
|
const lists = this.elem.querySelectorAll('.scroll-box');
|
|
|
|
const newList = Array.from(lists).filter(list => sortItem.parentElement !== list);
|
|
|
|
if (newList.length > 0) {
|
|
|
|
newList[0].appendChild(sortItem);
|
|
|
|
}
|
|
|
|
this.onChange();
|
|
|
|
}
|
|
|
|
|
|
|
|
onChange() {
|
2019-06-06 12:49:51 +02:00
|
|
|
const shelfBookElems = Array.from(this.shelfBooksList.querySelectorAll('[data-id]'));
|
|
|
|
this.input.value = shelfBookElems.map(elem => elem.getAttribute('data-id')).join(',');
|
2018-08-27 15:18:09 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
|
2018-11-09 22:17:35 +01:00
|
|
|
export default ShelfSort;
|