]> BookStack Code Mirror - bookstack/blob - resources/js/services/dual-lists.ts
Deps: Updated composer/npm packages, fixed test namespace
[bookstack] / resources / js / services / dual-lists.ts
1 /**
2  * Service for helping manage common dual-list scenarios.
3  * (Shelf book manager, sort set manager).
4  */
5
6 type ListActionsSet = Record<string, ((item: HTMLElement) => void)>;
7
8 export function buildListActions(
9     availableList: HTMLElement,
10     configuredList: HTMLElement,
11 ): ListActionsSet {
12     return {
13         move_up(item) {
14             const list = item.parentNode as HTMLElement;
15             const index = Array.from(list.children).indexOf(item);
16             const newIndex = Math.max(index - 1, 0);
17             list.insertBefore(item, list.children[newIndex] || null);
18         },
19         move_down(item) {
20             const list = item.parentNode as HTMLElement;
21             const index = Array.from(list.children).indexOf(item);
22             const newIndex = Math.min(index + 2, list.children.length);
23             list.insertBefore(item, list.children[newIndex] || null);
24         },
25         remove(item) {
26             availableList.appendChild(item);
27         },
28         add(item) {
29             configuredList.appendChild(item);
30         },
31     };
32 }
33
34 export function sortActionClickListener(actions: ListActionsSet, onChange: () => void) {
35     return (event: MouseEvent) => {
36         const sortItemAction = (event.target as Element).closest('.scroll-box-item button[data-action]') as HTMLElement|null;
37         if (sortItemAction) {
38             const sortItem = sortItemAction.closest('.scroll-box-item') as HTMLElement;
39             const action = sortItemAction.dataset.action;
40             if (!action) {
41                 throw new Error('No action defined for clicked button');
42             }
43
44             const actionFunction = actions[action];
45             actionFunction(sortItem);
46
47             onChange();
48         }
49     };
50 }
51
Morty Proxy This is a proxified and sanitized view of the page, visit original site.