compostrap 1.0.3 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,408 @@
1
+ /**
2
+ * SortableList: the items of a list moved by their handle, by the mouse, a finger or the keyboard.
3
+ *
4
+ * - `.sortable` is the list, its direct children `.sortable-item` the items, `.sortable-handle` (a button) in an
5
+ * item is what is grabbed; the rest of the item stays clickable and selectable.
6
+ * - `data-sortable-group` lets the items move between all lists of the same group (the sections of a menu); a list
7
+ * without a group keeps its items.
8
+ * - A `.sortable` inside an item is one level deeper (the links of a group of the menu). An item that holds such
9
+ * a list is not dropped into another one, so the nesting has at most two levels.
10
+ * - Keyboard: Space or Enter grabs the item, the arrows move it (also into the next or the previous list of the
11
+ * group), Space or Enter drops it, Escape puts it back. Every step is read by screen readers (`messages`).
12
+ *
13
+ * After a drop that changed the order the item dispatches `change.bs.sortable` (it bubbles) with `detail`
14
+ * `{ item, from, to, oldIndex, newIndex }`; SortableList.serialize(list) gives the order as the `data-id` of the
15
+ * items, with `children` for a nested list, e.g. to send it to the server.
16
+ *
17
+ * Everything is delegated from the document, so lists drawn later (an AJAX snippet) need no new init().
18
+ */
19
+ export class SortableList {
20
+ // the time the other items take to slide to their new place (ms), 0 without animation
21
+ static duration = 150;
22
+ // the distance from the top or the bottom of the window where the window scrolls while dragging (px)
23
+ static scrollEdge = 48;
24
+ static messages = {
25
+ grabbed: '{item} grabbed, position {position} of {count}. Arrows move it, Space drops it, Escape cancels.',
26
+ moved: '{item}, position {position} of {count}.',
27
+ dropped: '{item} dropped, position {position} of {count}.',
28
+ canceled: 'Move canceled, {item} is back at position {position} of {count}.',
29
+ };
30
+
31
+ static _initialized = false;
32
+ static _drag = null;
33
+ static _grab = null;
34
+ static _live = null;
35
+
36
+ static init() {
37
+ if (this._initialized) {
38
+ return;
39
+ }
40
+
41
+ this._initialized = true;
42
+ document.addEventListener('pointerdown', (event) => this._pointerDown(event));
43
+ document.addEventListener('keydown', (event) => this._keyDown(event));
44
+ document.addEventListener('focusout', (event) => this._focusOut(event));
45
+ }
46
+
47
+ /** The order of a list as the data-id of its items, with the order of a nested list in `children`. */
48
+ static serialize(list) {
49
+ return this._items(list).map((item) => {
50
+ const nested = item.querySelector(':scope > .sortable');
51
+ return nested ? { id: item.dataset.id, children: this.serialize(nested) } : { id: item.dataset.id };
52
+ });
53
+ }
54
+
55
+ // ---- pointer --------------------------------------------------------------------------------------------
56
+
57
+ static _pointerDown(event) {
58
+ const handle = event.target.closest?.('.sortable-handle');
59
+ const item = handle?.closest('.sortable-item');
60
+ const list = item?.parentElement;
61
+ if (!handle || !list?.matches('.sortable') || event.button !== 0 || this._drag) {
62
+ return;
63
+ }
64
+
65
+ event.preventDefault();
66
+ if (this._grab) {
67
+ this._drop(false);
68
+ }
69
+
70
+ const rect = item.getBoundingClientRect();
71
+ const ghost = item.cloneNode(true);
72
+ ghost.classList.add('sortable-ghost');
73
+ ghost.querySelectorAll('[id]').forEach((element) => element.removeAttribute('id'));
74
+ ghost.removeAttribute('id');
75
+ ghost.setAttribute('aria-hidden', 'true');
76
+ ghost.inert = true;
77
+ ghost.style.width = `${rect.width}px`;
78
+ ghost.style.height = `${rect.height}px`;
79
+ // the list-group-item of Bootstrap has its colors from its list, so the copy takes them along
80
+ ghost.style.setProperty('--bs-list-group-bg', getComputedStyle(list).getPropertyValue('--bs-list-group-bg'));
81
+ document.body.append(ghost);
82
+
83
+ this._drag = {
84
+ item,
85
+ ghost,
86
+ from: list,
87
+ oldIndex: this._items(list).indexOf(item),
88
+ offsetX: event.clientX - rect.left,
89
+ offsetY: event.clientY - rect.top,
90
+ x: event.clientX,
91
+ y: event.clientY,
92
+ frame: 0,
93
+ };
94
+
95
+ item.classList.add('sortable-placeholder');
96
+ document.documentElement.classList.add('sortable-active');
97
+ this._moveGhost();
98
+
99
+ this._onMove = (moveEvent) => {
100
+ this._drag.x = moveEvent.clientX;
101
+ this._drag.y = moveEvent.clientY;
102
+ this._moveGhost();
103
+ this._place();
104
+ };
105
+ this._onUp = () => this._endDrag(false);
106
+ this._onCancel = () => this._endDrag(true);
107
+ this._onEscape = (keyEvent) => {
108
+ if (keyEvent.key === 'Escape') {
109
+ keyEvent.preventDefault();
110
+ this._endDrag(true);
111
+ }
112
+ };
113
+ document.addEventListener('pointermove', this._onMove);
114
+ document.addEventListener('pointerup', this._onUp);
115
+ document.addEventListener('pointercancel', this._onCancel);
116
+ document.addEventListener('keydown', this._onEscape, true);
117
+ this._drag.frame = requestAnimationFrame(() => this._autoScroll());
118
+ }
119
+
120
+ static _moveGhost() {
121
+ const { ghost, x, y, offsetX, offsetY } = this._drag;
122
+ ghost.style.transform = `translate(${x - offsetX}px, ${y - offsetY}px)`;
123
+ }
124
+
125
+ /** Moves the placeholder to the place under the pointer. */
126
+ static _place() {
127
+ const { item, x, y } = this._drag;
128
+ const element = document.elementFromPoint(x, y);
129
+ if (!element || item.contains(element)) {
130
+ return;
131
+ }
132
+
133
+ // the nearest item under the pointer whose list takes the dragged item (a link of a group of another list
134
+ // stands for its group)
135
+ let target = element.closest('.sortable-item');
136
+ while (target && !this._accepts(target.parentElement, item)) {
137
+ target = target.parentElement.closest('.sortable-item');
138
+ }
139
+
140
+ if (target) {
141
+ const head = this._head(target);
142
+ if (y < head.top || y > head.bottom) {
143
+ return;
144
+ }
145
+
146
+ const middle = head.top + head.height / 2;
147
+ const sameList = target.parentElement === item.parentElement;
148
+ const after = sameList
149
+ ? Boolean(item.compareDocumentPosition(target) & Node.DOCUMENT_POSITION_FOLLOWING)
150
+ : y > middle;
151
+ // in its own list the item passes another one only when the pointer is over its far half, so the item
152
+ // does not swap back and forth while the others slide
153
+ if (sameList && (after ? y < middle : y > middle)) {
154
+ return;
155
+ }
156
+
157
+ this._moveTo(target.parentElement, after ? target.nextElementSibling : target);
158
+ return;
159
+ }
160
+
161
+ // an empty list, or the space under the last item of a list
162
+ const list = element.closest('.sortable');
163
+ if (list && this._accepts(list, item)) {
164
+ const items = this._items(list);
165
+ const last = items[items.length - 1];
166
+ if (!last || (last !== item && y > last.getBoundingClientRect().bottom)) {
167
+ this._moveTo(list, null);
168
+ }
169
+ }
170
+ }
171
+
172
+ /** The part of an item over its nested list: the item itself when it has none. */
173
+ static _head(item) {
174
+ const rect = item.getBoundingClientRect();
175
+ const nested = item.querySelector(':scope > .sortable');
176
+ if (!nested) {
177
+ return rect;
178
+ }
179
+
180
+ const bottom = nested.getBoundingClientRect().top;
181
+ return { top: rect.top, bottom, height: bottom - rect.top };
182
+ }
183
+
184
+ static _autoScroll() {
185
+ const drag = this._drag;
186
+ if (!drag) {
187
+ return;
188
+ }
189
+
190
+ const edge = this.scrollEdge;
191
+ const step = drag.y < edge ? -(edge - drag.y) / 3 : drag.y > innerHeight - edge ? (drag.y - innerHeight + edge) / 3 : 0;
192
+ if (step !== 0) {
193
+ window.scrollBy(0, step);
194
+ this._place();
195
+ }
196
+
197
+ drag.frame = requestAnimationFrame(() => this._autoScroll());
198
+ }
199
+
200
+ static _endDrag(cancel) {
201
+ const drag = this._drag;
202
+ if (!drag) {
203
+ return;
204
+ }
205
+
206
+ cancelAnimationFrame(drag.frame);
207
+ document.removeEventListener('pointermove', this._onMove);
208
+ document.removeEventListener('pointerup', this._onUp);
209
+ document.removeEventListener('pointercancel', this._onCancel);
210
+ document.removeEventListener('keydown', this._onEscape, true);
211
+ document.documentElement.classList.remove('sortable-active');
212
+ drag.ghost.remove();
213
+ drag.item.classList.remove('sortable-placeholder');
214
+ this._drag = null;
215
+
216
+ if (cancel) {
217
+ this._restore(drag);
218
+ } else {
219
+ this._changed(drag);
220
+ }
221
+ }
222
+
223
+ // ---- keyboard ---------------------------------------------------------------------------------------------
224
+
225
+ static _keyDown(event) {
226
+ const handle = event.target.closest?.('.sortable-handle');
227
+ const item = handle?.closest('.sortable-item');
228
+ if (!handle || !item?.parentElement?.matches('.sortable') || this._drag) {
229
+ return;
230
+ }
231
+
232
+ const grabbed = this._grab?.item === item;
233
+
234
+ if (event.key === ' ' || event.key === 'Enter') {
235
+ event.preventDefault();
236
+ if (grabbed) {
237
+ this._drop(true);
238
+ } else {
239
+ if (this._grab) {
240
+ this._drop(false);
241
+ }
242
+ this._grabItem(item, handle);
243
+ }
244
+ } else if (grabbed && (event.key === 'ArrowUp' || event.key === 'ArrowDown')) {
245
+ event.preventDefault();
246
+ this._step(event.key === 'ArrowUp' ? -1 : 1);
247
+ } else if (grabbed && event.key === 'Escape') {
248
+ event.preventDefault();
249
+ const grab = this._grab;
250
+ this._release();
251
+ this._restore(grab);
252
+ this._announce('canceled', grab.item);
253
+ grab.handle.focus();
254
+ }
255
+ }
256
+
257
+ static _grabItem(item, handle) {
258
+ this._grab = { item, handle, from: item.parentElement, oldIndex: this._items(item.parentElement).indexOf(item) };
259
+ item.classList.add('sortable-grabbed');
260
+ handle.setAttribute('aria-pressed', 'true');
261
+ this._announce('grabbed', item);
262
+ }
263
+
264
+ /** Moves the grabbed item one place up or down, at the end of its list into the next list of its group. */
265
+ static _step(direction) {
266
+ const { item, handle } = this._grab;
267
+ const list = item.parentElement;
268
+ const sibling = direction < 0 ? item.previousElementSibling : item.nextElementSibling;
269
+
270
+ if (sibling?.matches('.sortable-item')) {
271
+ this._moveTo(list, direction < 0 ? sibling : sibling.nextElementSibling);
272
+ } else {
273
+ const lists = this._lists(item);
274
+ const next = lists[lists.indexOf(list) + direction];
275
+ if (!next) {
276
+ return;
277
+ }
278
+ this._moveTo(next, direction < 0 ? null : this._items(next)[0] ?? null);
279
+ }
280
+
281
+ handle.focus();
282
+ item.scrollIntoView({ block: 'nearest' });
283
+ this._announce('moved', item);
284
+ }
285
+
286
+ static _drop(announce) {
287
+ const grab = this._grab;
288
+ this._release();
289
+ if (announce) {
290
+ this._announce('dropped', grab.item);
291
+ }
292
+ this._changed(grab);
293
+ }
294
+
295
+ static _release() {
296
+ this._grab.item.classList.remove('sortable-grabbed');
297
+ this._grab.handle.removeAttribute('aria-pressed');
298
+ this._grab = null;
299
+ }
300
+
301
+ /** Leaving the handle by Tab or a click elsewhere drops the grabbed item where it is. */
302
+ static _focusOut(event) {
303
+ if (this._grab && !this._moving && event.target === this._grab.handle) {
304
+ this._drop(true);
305
+ }
306
+ }
307
+
308
+ // ---- shared -----------------------------------------------------------------------------------------------
309
+
310
+ static _items(list) {
311
+ return [...list.children].filter((child) => child.matches('.sortable-item'));
312
+ }
313
+
314
+ /** Whether the list takes the item: its own list, or a list of its group, not inside the item itself. */
315
+ static _accepts(list, item) {
316
+ const from = item.parentElement;
317
+ if (!list?.matches('.sortable') || item.contains(list)) {
318
+ return false;
319
+ }
320
+ if (list === from) {
321
+ return true;
322
+ }
323
+
324
+ const group = from.dataset.sortableGroup;
325
+ if (!group || list.dataset.sortableGroup !== group) {
326
+ return false;
327
+ }
328
+
329
+ // at most two levels: a group of the menu is not dropped into another group
330
+ return !(list.closest('.sortable-item') && item.querySelector(':scope > .sortable'));
331
+ }
332
+
333
+ /** All lists the item may move to, in the order of the page. */
334
+ static _lists(item) {
335
+ const group = item.parentElement.dataset.sortableGroup;
336
+ if (!group) {
337
+ return [item.parentElement];
338
+ }
339
+
340
+ return [...document.querySelectorAll('.sortable')]
341
+ .filter((list) => list === item.parentElement || this._accepts(list, item));
342
+ }
343
+
344
+ /** Puts the item before `reference` in the list and slides the other items of the touched lists. */
345
+ static _moveTo(list, reference) {
346
+ const item = (this._drag ?? this._grab).item;
347
+ if (reference === item || (reference === null && list.lastElementChild === item)) {
348
+ return;
349
+ }
350
+
351
+ const animate = this.duration > 0 && !matchMedia('(prefers-reduced-motion: reduce)').matches;
352
+ const others = animate
353
+ ? [...new Set([...list.querySelectorAll('.sortable-item'), ...item.parentElement.querySelectorAll('.sortable-item')])]
354
+ .filter((other) => other !== item && !item.contains(other))
355
+ : [];
356
+ const before = new Map(others.map((other) => [other, other.getBoundingClientRect()]));
357
+
358
+ this._moving = true;
359
+ list.insertBefore(item, reference);
360
+ this._moving = false;
361
+
362
+ for (const [other, rect] of before) {
363
+ const now = other.getBoundingClientRect();
364
+ const dx = rect.left - now.left;
365
+ const dy = rect.top - now.top;
366
+ if (dx !== 0 || dy !== 0) {
367
+ other.animate(
368
+ [{ transform: `translate(${dx}px, ${dy}px)` }, { transform: 'none' }],
369
+ { duration: this.duration, easing: 'ease-out' },
370
+ );
371
+ }
372
+ }
373
+ }
374
+
375
+ static _restore({ item, from, oldIndex }) {
376
+ this._moving = true;
377
+ from.insertBefore(item, this._items(from).filter((other) => other !== item)[oldIndex] ?? null);
378
+ this._moving = false;
379
+ }
380
+
381
+ static _changed({ item, from, oldIndex }) {
382
+ const to = item.parentElement;
383
+ const newIndex = this._items(to).indexOf(item);
384
+ if (to === from && newIndex === oldIndex) {
385
+ return;
386
+ }
387
+
388
+ const event = new CustomEvent('change.bs.sortable', { bubbles: true, detail: { item, from, to, oldIndex, newIndex } });
389
+ item.dispatchEvent(event);
390
+ }
391
+
392
+ static _announce(message, item) {
393
+ if (!this._live) {
394
+ this._live = document.createElement('div');
395
+ this._live.className = 'sortable-live visually-hidden';
396
+ this._live.setAttribute('aria-live', 'assertive');
397
+ document.body.append(this._live);
398
+ }
399
+
400
+ const items = this._items(item.parentElement);
401
+ const handle = item.querySelector(':scope > .sortable-handle');
402
+ const name = item.dataset.sortableLabel || handle?.getAttribute('aria-label')?.replace(/^Move\s+/, '') || item.textContent.trim();
403
+ this._live.textContent = this.messages[message]
404
+ .replace('{item}', name)
405
+ .replace('{position}', String(items.indexOf(item) + 1))
406
+ .replace('{count}', String(items.length));
407
+ }
408
+ }
@@ -9,6 +9,7 @@
9
9
  @use 'settings/index' as settings;
10
10
  @use 'datagrid/index' as datagrid;
11
11
  @use 'selection/index' as selection;
12
+ @use 'sortable/index' as sortable;
12
13
  @use 'number-input/index' as number-input;
13
14
  @use 'otp-input/index' as otp-input;
14
15
  @use 'datepicker/index' as datepicker;
@@ -1,5 +1,5 @@
1
- //
2
- // datagrid module of compostrap
3
- //
4
-
5
- @use 'datagrid/index';
1
+ //
2
+ // datagrid module of compostrap
3
+ //
4
+
5
+ @use 'datagrid/index';