1 import Sortable, {MultiDrag} from 'sortablejs';
2 import {Component} from './component';
3 import {htmlToDom} from '../services/dom';
6 const sortOperations = {
8 const aName = a.getAttribute('data-name').trim().toLowerCase();
9 const bName = b.getAttribute('data-name').trim().toLowerCase();
10 return aName.localeCompare(bName);
13 const aTime = Number(a.getAttribute('data-created'));
14 const bTime = Number(b.getAttribute('data-created'));
18 const aTime = Number(a.getAttribute('data-updated'));
19 const bTime = Number(b.getAttribute('data-updated'));
23 const aType = a.getAttribute('data-type');
24 const bType = b.getAttribute('data-type');
25 if (aType === bType) {
28 return (aType === 'chapter' ? -1 : 1);
31 const aType = a.getAttribute('data-type');
32 const bType = b.getAttribute('data-type');
33 if (aType === bType) {
36 return (aType === 'chapter' ? 1 : -1);
41 * The available move actions.
42 * The active function indicates if the action is possible for the given item.
43 * The run function performs the move.
44 * @type {{up: {active(Element, ?Element, Element): boolean, run(Element, ?Element, Element)}}}
48 active(elem, parent) {
49 return !(elem.previousElementSibling === null && !parent);
52 const newSibling = elem.previousElementSibling || parent;
53 newSibling.insertAdjacentElement('beforebegin', elem);
57 active(elem, parent) {
58 return !(elem.nextElementSibling === null && !parent);
61 const newSibling = elem.nextElementSibling || parent;
62 newSibling.insertAdjacentElement('afterend', elem);
66 active(elem, parent, book) {
67 return book.nextElementSibling !== null;
69 run(elem, parent, book) {
70 const newList = book.nextElementSibling.querySelector('ul');
71 newList.prepend(elem);
75 active(elem, parent, book) {
76 return book.previousElementSibling !== null;
78 run(elem, parent, book) {
79 const newList = book.previousElementSibling.querySelector('ul');
80 newList.appendChild(elem);
84 active(elem, parent) {
85 return elem.dataset.type === 'page' && this.getNextChapter(elem, parent);
88 const nextChapter = this.getNextChapter(elem, parent);
89 nextChapter.querySelector('ul').prepend(elem);
91 getNextChapter(elem, parent) {
92 const topLevel = (parent || elem);
93 const topItems = Array.from(topLevel.parentElement.children);
94 const index = topItems.indexOf(topLevel);
95 return topItems.slice(index + 1).find(item => item.dataset.type === 'chapter');
99 active(elem, parent) {
100 return elem.dataset.type === 'page' && this.getPrevChapter(elem, parent);
103 const prevChapter = this.getPrevChapter(elem, parent);
104 prevChapter.querySelector('ul').append(elem);
106 getPrevChapter(elem, parent) {
107 const topLevel = (parent || elem);
108 const topItems = Array.from(topLevel.parentElement.children);
109 const index = topItems.indexOf(topLevel);
110 return topItems.slice(0, index).reverse().find(item => item.dataset.type === 'chapter');
114 active(elem, parent) {
115 return parent || (parent === null && elem.nextElementSibling);
117 run(elem, parent, book) {
118 book.querySelector('ul').append(elem);
122 active(elem, parent) {
123 return parent || (parent === null && elem.previousElementSibling);
125 run(elem, parent, book) {
126 book.querySelector('ul').prepend(elem);
130 active(elem, parent) {
134 parent.insertAdjacentElement('beforebegin', elem);
138 active(elem, parent) {
142 parent.insertAdjacentElement('afterend', elem);
147 export class BookSort extends Component {
150 this.container = this.$el;
151 this.sortContainer = this.$refs.sortContainer;
152 this.input = this.$refs.input;
154 Sortable.mount(new MultiDrag());
156 const initialSortBox = this.container.querySelector('.sort-box');
157 this.setupBookSortable(initialSortBox);
158 this.setupSortPresets();
159 this.setupMoveActions();
161 window.$events.listen('entity-select-change', this.bookSelect.bind(this));
165 * Set up the handlers for the item-level move buttons.
168 // Handle move button click
169 this.container.addEventListener('click', event => {
170 if (event.target.matches('[data-move]')) {
171 const action = event.target.getAttribute('data-move');
172 const sortItem = event.target.closest('[data-id]');
173 this.runSortAction(sortItem, action);
177 this.updateMoveActionStateForAll();
181 * Set up the handlers for the preset sort type buttons.
186 const reversibleTypes = ['name', 'created', 'updated'];
188 this.sortContainer.addEventListener('click', event => {
189 const sortButton = event.target.closest('.sort-box-options [data-sort]');
190 if (!sortButton) return;
192 event.preventDefault();
193 const sortLists = sortButton.closest('.sort-box').querySelectorAll('ul');
194 const sort = sortButton.getAttribute('data-sort');
196 reverse = (lastSort === sort) ? !reverse : false;
197 let sortFunction = sortOperations[sort];
198 if (reverse && reversibleTypes.includes(sort)) {
199 sortFunction = function reverseSortOperation(a, b) {
200 return 0 - sortOperations[sort](a, b);
204 for (const list of sortLists) {
205 const directItems = Array.from(list.children).filter(child => child.matches('li'));
206 directItems.sort(sortFunction).forEach(sortedItem => {
207 list.appendChild(sortedItem);
212 this.updateMapInput();
217 * Handle book selection from the entity selector.
218 * @param {Object} entityInfo
220 bookSelect(entityInfo) {
221 const alreadyAdded = this.container.querySelector(`[data-type="book"][data-id="${entityInfo.id}"]`) !== null;
222 if (alreadyAdded) return;
224 const entitySortItemUrl = `${entityInfo.link}/sort-item`;
225 window.$http.get(entitySortItemUrl).then(resp => {
226 const newBookContainer = htmlToDom(resp.data);
227 this.sortContainer.append(newBookContainer);
228 this.setupBookSortable(newBookContainer);
229 this.updateMoveActionStateForAll();
231 const summary = newBookContainer.querySelector('summary');
237 * Set up the given book container element to have sortable items.
238 * @param {Element} bookContainer
240 setupBookSortable(bookContainer) {
241 const sortElems = Array.from(bookContainer.querySelectorAll('.sort-list, .sortable-page-sublist'));
243 const bookGroupConfig = {
245 pull: ['book', 'chapter'],
246 put: ['book', 'chapter'],
249 const chapterGroupConfig = {
251 pull: ['book', 'chapter'],
252 put(toList, fromList, draggedElem) {
253 return draggedElem.getAttribute('data-type') === 'page';
257 for (const sortElem of sortElems) {
258 Sortable.create(sortElem, {
259 group: sortElem.classList.contains('sort-list') ? bookGroupConfig : chapterGroupConfig,
261 fallbackOnBody: true,
264 this.ensureNoNestedChapters();
265 this.updateMapInput();
266 this.updateMoveActionStateForAll();
268 dragClass: 'bg-white',
269 ghostClass: 'primary-background-light',
271 multiDragKey: 'Control',
272 selectedClass: 'sortable-selected',
278 * Handle nested chapters by moving them to the parent book.
279 * Needed since sorting with multi-sort only checks group rules based on the active item,
280 * not all in group, therefore need to manually check after a sort.
281 * Must be done before updating the map input.
283 ensureNoNestedChapters() {
284 const nestedChapters = this.container.querySelectorAll('[data-type="chapter"] [data-type="chapter"]');
285 for (const chapter of nestedChapters) {
286 const parentChapter = chapter.parentElement.closest('[data-type="chapter"]');
287 parentChapter.insertAdjacentElement('afterend', chapter);
292 * Update the input with our sort data.
295 const pageMap = this.buildEntityMap();
296 this.input.value = JSON.stringify(pageMap);
300 * Build up a mapping of entities with their ordering and nesting.
304 const entityMap = [];
305 const lists = this.container.querySelectorAll('.sort-list');
307 for (const list of lists) {
308 const bookId = list.closest('[data-type="book"]').getAttribute('data-id');
309 const directChildren = Array.from(list.children)
310 .filter(elem => elem.matches('[data-type="page"], [data-type="chapter"]'));
311 for (let i = 0; i < directChildren.length; i++) {
312 this.addBookChildToMap(directChildren[i], i, bookId, entityMap);
320 * Parse a sort item and add it to a data-map array.
321 * Parses sub0items if existing also.
322 * @param {Element} childElem
323 * @param {Number} index
324 * @param {Number} bookId
325 * @param {Array} entityMap
327 addBookChildToMap(childElem, index, bookId, entityMap) {
328 const type = childElem.getAttribute('data-type');
329 const parentChapter = false;
330 const childId = childElem.getAttribute('data-id');
340 const subPages = childElem.querySelectorAll('[data-type="page"]');
341 for (let i = 0; i < subPages.length; i++) {
343 id: subPages[i].getAttribute('data-id'),
345 parentChapter: childId,
353 * Run the given sort action up the provided sort item.
354 * @param {Element} item
355 * @param {String} action
357 runSortAction(item, action) {
358 const parentItem = item.parentElement.closest('li[data-id]');
359 const parentBook = item.parentElement.closest('[data-type="book"]');
360 moveActions[action].run(item, parentItem, parentBook);
361 this.updateMapInput();
362 this.updateMoveActionStateForAll();
363 item.scrollIntoView({behavior: 'smooth', block: 'nearest'});
368 * Update the state of the available move actions on this item.
369 * @param {Element} item
371 updateMoveActionState(item) {
372 const parentItem = item.parentElement.closest('li[data-id]');
373 const parentBook = item.parentElement.closest('[data-type="book"]');
374 for (const [action, functions] of Object.entries(moveActions)) {
375 const moveButton = item.querySelector(`[data-move="${action}"]`);
376 moveButton.disabled = !functions.active(item, parentItem, parentBook);
380 updateMoveActionStateForAll() {
381 const items = this.container.querySelectorAll('[data-type="chapter"],[data-type="page"]');
382 for (const item of items) {
383 this.updateMoveActionState(item);