tyrell-components 1.0.0-RC19 → 1.0.0-RC20

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,1838 @@
1
+ import { ensureStyles } from '../utils/styles.js';
2
+ import { upgradeProperties } from '../utils/upgrade-properties.js';
3
+ import { sortableStyles, sortableLightStyles, sortableCursorStyles } from '../styles/sortable.js';
4
+ const DEFAULT_STRINGS = {
5
+ pickedUp: 'Picked up {item}. Position {position} of {total} in {list}. Arrow keys move, Space drops, Escape cancels.',
6
+ moved: '{item}: position {position} of {total} in {list}.',
7
+ blocked: '{list} does not accept {item}.',
8
+ dropped: '{item} moved to position {position} of {total} in {list}.',
9
+ rejected: 'Move not saved. {item} is back at position {position} in {list}.',
10
+ reconciled: '{item} is now at position {position} of {total} in {list}.',
11
+ removed: '{item} was removed.',
12
+ unknown: 'The move of {item} may not have been saved.',
13
+ cancelled: 'Move cancelled. {item} is back at position {position} in {list}.',
14
+ pending: 'Saving, please wait.',
15
+ };
16
+ const TOUCH_DELAY = 250;
17
+ const TOUCH_TOLERANCE = 8;
18
+ const MOUSE_DISTANCE = 5;
19
+ const HANDLE_TOUCH_DISTANCE = 3;
20
+ const FLING_GUARD = 100;
21
+ const HOLD_TIMEOUT = 5000;
22
+ const BUSY_CAP = 30000;
23
+ const IDLE_GRACE = 250;
24
+ const HTMX_SETTLE_CAP = 3000;
25
+ const AUTOSCROLL_SPEED = 20;
26
+ const AUTOSCROLL_ARM = 16;
27
+ const INTERACTIVE = 'button, a[href], input, select, textarea, label, summary, [contenteditable]:not([contenteditable="false"]), [data-no-drag]';
28
+ const instances = new Set();
29
+ let session = null;
30
+ let keyHandledAt = 0;
31
+ let droppedBy = null;
32
+ let lastScrollAt = 0;
33
+ document.addEventListener('scroll', () => { lastScrollAt = performance.now(); }, { capture: true, passive: true });
34
+ const styledRoots = new WeakSet();
35
+ const lightSheet = (() => {
36
+ let sheet = null;
37
+ return () => {
38
+ if (!sheet) {
39
+ sheet = new CSSStyleSheet();
40
+ sheet.replaceSync(sortableLightStyles);
41
+ }
42
+ return sheet;
43
+ };
44
+ })();
45
+ const handleRules = new Set(['[data-handle]']);
46
+ function adoptLightStyles(host) {
47
+ const root = host.getRootNode();
48
+ if (!('adoptedStyleSheets' in root))
49
+ return;
50
+ if (!styledRoots.has(root)) {
51
+ styledRoots.add(root);
52
+ root.adoptedStyleSheets = [...root.adoptedStyleSheets, lightSheet()];
53
+ }
54
+ const sel = host.handleSelector;
55
+ if (handleRules.has(sel))
56
+ return;
57
+ handleRules.add(sel);
58
+ try {
59
+ lightSheet().insertRule(`ty-sortable ${sel} { touch-action: none; cursor: grab; -webkit-touch-callout: none; -webkit-user-select: none; user-select: none; }`);
60
+ }
61
+ catch {
62
+ }
63
+ }
64
+ function reducedMotion() {
65
+ return matchMedia('(prefers-reduced-motion: reduce)').matches;
66
+ }
67
+ function duration(el) {
68
+ if (reducedMotion())
69
+ return 0;
70
+ const v = getComputedStyle(el).getPropertyValue('--ty-sortable-duration').trim();
71
+ const n = parseFloat(v);
72
+ return Number.isFinite(n) ? (v.endsWith('ms') ? n : n * 1000) : 200;
73
+ }
74
+ function cssVar(el, name, fallback) {
75
+ return getComputedStyle(el).getPropertyValue(name).trim() || fallback;
76
+ }
77
+ function setState(el, name, on) {
78
+ const states = el._states;
79
+ if (!states)
80
+ return;
81
+ try {
82
+ if (on)
83
+ states.add(name);
84
+ else
85
+ states.delete(name);
86
+ }
87
+ catch {
88
+ }
89
+ }
90
+ function flatParent(n) {
91
+ return n.assignedSlot ?? n.parentElement ?? (n.getRootNode().host ?? null);
92
+ }
93
+ function openDialogOf(el) {
94
+ for (let n = el; n; n = flatParent(n)) {
95
+ if (n instanceof HTMLDialogElement && n.open)
96
+ return n;
97
+ }
98
+ return null;
99
+ }
100
+ function deepElementFromPoint(x, y) {
101
+ let el = document.elementFromPoint(x, y);
102
+ const seen = new Set();
103
+ while (el?.shadowRoot && !seen.has(el)) {
104
+ seen.add(el);
105
+ const inner = el.shadowRoot.elementFromPoint(x, y);
106
+ if (!inner || seen.has(inner) || !el.shadowRoot.contains(inner))
107
+ break;
108
+ el = inner;
109
+ }
110
+ return el;
111
+ }
112
+ function members(group, self) {
113
+ if (!group)
114
+ return [self];
115
+ return [...instances].filter((i) => i.isConnected && i.group === group);
116
+ }
117
+ function resolveContainer(c, id, group) {
118
+ if (c.isConnected)
119
+ return c;
120
+ if (!id)
121
+ return null;
122
+ return [...instances].find((i) => i.isConnected && i.id === id && i.group === group) ?? null;
123
+ }
124
+ function handleOf(c, item) {
125
+ try {
126
+ return item.querySelector(c.handleSelector);
127
+ }
128
+ catch {
129
+ return null;
130
+ }
131
+ }
132
+ function textOf(node, skip) {
133
+ if (node.nodeType === Node.TEXT_NODE)
134
+ return node.textContent ?? '';
135
+ if (!(node instanceof Element))
136
+ return '';
137
+ if (node === skip || node.matches('[aria-hidden="true"], button, input, select, textarea, style, script, template'))
138
+ return '';
139
+ return Array.from(node.childNodes).map((n) => textOf(n, skip)).join(' ');
140
+ }
141
+ function itemLabel(c, item) {
142
+ const handle = handleOf(c, item);
143
+ const handleName = handle?.getAttribute('aria-label')?.replace(/^move\s+/i, '');
144
+ const label = item.getAttribute('aria-label') || item.getAttribute('data-label') || handleName || textOf(item, handle);
145
+ const text = label.replace(/\s+/g, ' ').trim();
146
+ return text.length > 60 ? `${text.slice(0, 57)}…` : text || 'item';
147
+ }
148
+ function listLabel(c) {
149
+ return c.getAttribute('label') || c.getAttribute('aria-label') || c.id || 'list';
150
+ }
151
+ function sameTokens(a, b) {
152
+ return a.length === b.length && a.every((t, i) => t === b[i]);
153
+ }
154
+ function scrolls(v) {
155
+ return v === 'auto' || v === 'scroll' || v === 'overlay';
156
+ }
157
+ function scrollersOf(start) {
158
+ const out = [];
159
+ for (let el = start; el; el = flatParent(el)) {
160
+ if (el instanceof HTMLDialogElement && el.open)
161
+ return out;
162
+ if (el === document.documentElement || el === document.body)
163
+ break;
164
+ const cs = getComputedStyle(el);
165
+ if ((scrolls(cs.overflowY) && el.scrollHeight > el.clientHeight) || (scrolls(cs.overflowX) && el.scrollWidth > el.clientWidth)) {
166
+ out.push(el);
167
+ }
168
+ }
169
+ const page = document.scrollingElement;
170
+ if (page)
171
+ out.push(page);
172
+ return out;
173
+ }
174
+ function viewportRect() {
175
+ return { top: 0, left: 0, bottom: innerHeight, right: innerWidth, width: innerWidth, height: innerHeight };
176
+ }
177
+ function visibleRect(c) {
178
+ const r = c.getBoundingClientRect();
179
+ let top = r.top, left = r.left, bottom = r.bottom, right = r.right;
180
+ const page = document.scrollingElement;
181
+ for (const s of scrollersOf(c)) {
182
+ const sr = s === page ? viewportRect() : s.getBoundingClientRect();
183
+ top = Math.max(top, sr.top);
184
+ left = Math.max(left, sr.left);
185
+ bottom = Math.min(bottom, sr.bottom);
186
+ right = Math.min(right, sr.right);
187
+ }
188
+ return bottom > top && right > left ? { top, left, bottom, right } : null;
189
+ }
190
+ function autoScroll(scrollers, x, y) {
191
+ const page = document.scrollingElement;
192
+ let moved = false;
193
+ for (const axis of ['y', 'x']) {
194
+ for (const el of scrollers) {
195
+ const r = el === page ? viewportRect() : el.getBoundingClientRect();
196
+ if (el !== page && (x < r.left || x > r.right || y < r.top || y > r.bottom))
197
+ continue;
198
+ const size = axis === 'y' ? r.height : r.width;
199
+ const zone = Math.min(Math.max(40, Math.min(size * 0.15, 100)), size * 0.25);
200
+ const p = axis === 'y' ? y : x;
201
+ const lo = axis === 'y' ? r.top : r.left;
202
+ const hi = axis === 'y' ? r.bottom : r.right;
203
+ const pos = axis === 'y' ? el.scrollTop : el.scrollLeft;
204
+ const max = axis === 'y' ? el.scrollHeight - el.clientHeight : el.scrollWidth - el.clientWidth;
205
+ let delta = 0;
206
+ if (p < lo + zone && pos > 0)
207
+ delta = -AUTOSCROLL_SPEED * ((lo + zone - p) / zone) ** 2;
208
+ else if (p > hi - zone && pos < max - 1)
209
+ delta = AUTOSCROLL_SPEED * ((p - (hi - zone)) / zone) ** 2;
210
+ if (!delta)
211
+ continue;
212
+ if (reducedMotion())
213
+ delta = Math.sign(delta) * AUTOSCROLL_SPEED / 2;
214
+ if (axis === 'y')
215
+ el.scrollTop += delta;
216
+ else
217
+ el.scrollLeft += delta;
218
+ moved = true;
219
+ break;
220
+ }
221
+ }
222
+ return moved;
223
+ }
224
+ let suppressUntil = 0;
225
+ addEventListener('click', (e) => {
226
+ if (performance.now() < suppressUntil) {
227
+ suppressUntil = 0;
228
+ e.preventDefault();
229
+ e.stopImmediatePropagation();
230
+ }
231
+ }, true);
232
+ addEventListener('pointerdown', () => { suppressUntil = 0; }, true);
233
+ function suppressNextRelease(pointerId) {
234
+ const done = () => {
235
+ removeEventListener('pointerup', onUp, true);
236
+ removeEventListener('pointerdown', done, true);
237
+ clearTimeout(timer);
238
+ };
239
+ const onUp = (e) => {
240
+ if (e.pointerId !== pointerId)
241
+ return;
242
+ suppressUntil = performance.now() + 300;
243
+ done();
244
+ };
245
+ const timer = window.setTimeout(done, 5000);
246
+ addEventListener('pointerup', onUp, true);
247
+ addEventListener('pointerdown', done, true);
248
+ }
249
+ export class TySortable extends HTMLElement {
250
+ static get observedAttributes() {
251
+ return ['handle', 'disabled'];
252
+ }
253
+ constructor() {
254
+ super();
255
+ this._states = null;
256
+ this._press = null;
257
+ this._canDrop = null;
258
+ this._labels = {};
259
+ this._childObserver = null;
260
+ this._onPressMove = (e) => {
261
+ const press = this._press;
262
+ if (!press || e.pointerId !== press.pointerId)
263
+ return;
264
+ const d = Math.hypot(e.clientX - press.startX, e.clientY - press.startY);
265
+ if (press.pointerType === 'mouse') {
266
+ if (d >= MOUSE_DISTANCE)
267
+ this._activate(press, e.clientX, e.clientY);
268
+ }
269
+ else if (press.onHandle) {
270
+ if (d >= HANDLE_TOUCH_DISTANCE)
271
+ this._activate(press, e.clientX, e.clientY);
272
+ }
273
+ else if (d > TOUCH_TOLERANCE) {
274
+ this._endPress();
275
+ }
276
+ };
277
+ this._onPressEnd = (e) => {
278
+ if (this._press && e.pointerId === this._press.pointerId)
279
+ this._endPress();
280
+ };
281
+ try {
282
+ this._states = this.attachInternals().states;
283
+ }
284
+ catch {
285
+ this._states = null;
286
+ }
287
+ const root = this.attachShadow({ mode: 'open' });
288
+ ensureStyles(root, { css: sortableStyles, id: 'ty-sortable' });
289
+ root.innerHTML = '<slot></slot><div class="live" part="live" aria-live="assertive" aria-atomic="true"></div>';
290
+ this._live = root.querySelector('.live');
291
+ this.addEventListener('pointerdown', (e) => this._onPointerDown(e));
292
+ this.addEventListener('keydown', (e) => this._onKeyDown(e));
293
+ this.addEventListener('keyup', (e) => this._onKeyUp(e));
294
+ this.addEventListener('click', (e) => this._onClick(e));
295
+ this.addEventListener('focusout', (e) => this._onFocusOut(e));
296
+ this.addEventListener('dragstart', (e) => {
297
+ if (this._itemFrom(e))
298
+ e.preventDefault();
299
+ });
300
+ this.addEventListener('touchmove', blockTouchScroll, { passive: false });
301
+ this.addEventListener('touchstart', (e) => {
302
+ const t = e.target;
303
+ t.addEventListener('touchmove', blockTouchScroll, { passive: false });
304
+ const done = () => {
305
+ t.removeEventListener('touchmove', blockTouchScroll);
306
+ t.removeEventListener('touchend', done);
307
+ t.removeEventListener('touchcancel', done);
308
+ };
309
+ t.addEventListener('touchend', done);
310
+ t.addEventListener('touchcancel', done);
311
+ }, { passive: true });
312
+ }
313
+ get group() {
314
+ return this.getAttribute('group');
315
+ }
316
+ set group(v) {
317
+ if (v == null)
318
+ this.removeAttribute('group');
319
+ else
320
+ this.setAttribute('group', v);
321
+ }
322
+ get axis() {
323
+ return this.getAttribute('axis') === 'horizontal' ? 'horizontal' : 'vertical';
324
+ }
325
+ set axis(v) {
326
+ this.setAttribute('axis', v);
327
+ }
328
+ get disabled() {
329
+ return this.hasAttribute('disabled');
330
+ }
331
+ set disabled(v) {
332
+ this.toggleAttribute('disabled', !!v && String(v) !== 'false');
333
+ }
334
+ get dropLine() {
335
+ return this.hasAttribute('drop-line');
336
+ }
337
+ set dropLine(v) {
338
+ this.toggleAttribute('drop-line', !!v && String(v) !== 'false');
339
+ }
340
+ get flash() {
341
+ return this.hasAttribute('flash');
342
+ }
343
+ set flash(v) {
344
+ this.toggleAttribute('flash', !!v && String(v) !== 'false');
345
+ }
346
+ get handleSelector() {
347
+ return this.getAttribute('handle') || '[data-handle]';
348
+ }
349
+ get accepts() {
350
+ return this.getAttribute('accepts');
351
+ }
352
+ set accepts(v) {
353
+ if (v == null)
354
+ this.removeAttribute('accepts');
355
+ else
356
+ this.setAttribute('accepts', v);
357
+ }
358
+ get holdTimeout() {
359
+ const n = parseInt(this.getAttribute('hold-timeout') ?? '', 10);
360
+ return Number.isFinite(n) && n >= 0 ? n : HOLD_TIMEOUT;
361
+ }
362
+ get canDrop() {
363
+ return this._canDrop;
364
+ }
365
+ set canDrop(fn) {
366
+ this._canDrop = typeof fn === 'function' ? fn : null;
367
+ }
368
+ get labels() {
369
+ return this._labels;
370
+ }
371
+ set labels(v) {
372
+ this._labels = v && typeof v === 'object' ? v : {};
373
+ }
374
+ get items() {
375
+ return Array.from(this.children).filter((c) => c instanceof HTMLElement && !(c instanceof HTMLTemplateElement) && !c.hasAttribute('data-sortable-ignore'));
376
+ }
377
+ keyOf(item) {
378
+ const attr = this.getAttribute('key-attr');
379
+ return (attr && item.getAttribute(attr)) || item.getAttribute('data-key') || item.id || null;
380
+ }
381
+ connectedCallback() {
382
+ upgradeProperties(this);
383
+ instances.add(this);
384
+ adoptLightStyles(this);
385
+ this._syncStructure();
386
+ this._childObserver = new MutationObserver(() => this._onChildren());
387
+ this._childObserver.observe(this, { childList: true });
388
+ const s = session;
389
+ if (s?.phase === 'holding' && this.group === s.group && (s.group || this.id === s.sourceId || this.id === s.targetId)) {
390
+ observeForHold(s, this);
391
+ queueMicrotask(() => evaluateHold('mutation'));
392
+ }
393
+ }
394
+ disconnectedCallback() {
395
+ instances.delete(this);
396
+ this._childObserver?.disconnect();
397
+ this._childObserver = null;
398
+ this._endPress();
399
+ if (session?.mode === 'keyboard' && session.phase === 'dragging')
400
+ queueMicrotask(checkKeyboard);
401
+ }
402
+ connectedMoveCallback() { }
403
+ attributeChangedCallback(name, oldValue, newValue) {
404
+ if (oldValue === newValue || !this.isConnected)
405
+ return;
406
+ if (name === 'handle') {
407
+ adoptLightStyles(this);
408
+ this._syncStructure();
409
+ }
410
+ else if (name === 'disabled' && newValue !== null && session?.phase === 'dragging' && session.source === this) {
411
+ cancelDrag('disabled');
412
+ }
413
+ }
414
+ _onChildren() {
415
+ this._syncStructure();
416
+ if (session?.mode === 'keyboard' && session.phase === 'dragging')
417
+ checkKeyboard();
418
+ }
419
+ _syncStructure() {
420
+ const items = this.items;
421
+ setState(this, 'empty', items.length === 0);
422
+ setState(this, 'handles', items.some((i) => handleOf(this, i)));
423
+ }
424
+ move(itemOrKey, opts = {}) {
425
+ if (session)
426
+ return Promise.reject(new Error('ty-sortable: a move is still pending'));
427
+ const item = typeof itemOrKey === 'string' ? this.items.find((i) => this.keyOf(i) === itemOrKey) : itemOrKey;
428
+ if (!item || item.parentElement !== this)
429
+ return Promise.reject(new Error('ty-sortable: no such item'));
430
+ const target = typeof opts.to === 'string'
431
+ ? members(this.group, this).find((m) => m.id === opts.to)
432
+ : opts.to ?? this;
433
+ if (!target || (target !== this && (!this.group || target.group !== this.group))) {
434
+ return Promise.reject(new Error('ty-sortable: no such list in this group'));
435
+ }
436
+ const s = newSession('api', this, item);
437
+ const others = target.items.filter((i) => i !== item);
438
+ let slot = others.length;
439
+ if (opts.before != null)
440
+ slot = others.findIndex((i) => target.keyOf(i) === opts.before);
441
+ else if (opts.after != null) {
442
+ const i = others.findIndex((o) => target.keyOf(o) === opts.after);
443
+ slot = i < 0 ? -1 : i + 1;
444
+ }
445
+ else if (opts.index != null)
446
+ slot = Math.max(0, Math.min(opts.index, others.length));
447
+ if (slot < 0)
448
+ return Promise.reject(new Error('ty-sortable: no such neighbour'));
449
+ setTargetOf(s, target);
450
+ s.slot = clampLocked(target, item, slot);
451
+ s.legal = legality(s, target, s.slot);
452
+ if (s.legal !== 'ok')
453
+ return Promise.reject(new Error('ty-sortable: drop not allowed'));
454
+ session = s;
455
+ return new Promise((resolve) => {
456
+ s.resolve = resolve;
457
+ if (!commit())
458
+ resolve('accepted');
459
+ });
460
+ }
461
+ settle(outcome) {
462
+ if (session?.phase !== 'holding')
463
+ return;
464
+ if (outcome)
465
+ release(outcome);
466
+ else
467
+ evaluateHold('settle');
468
+ }
469
+ _announce(name, vars = {}) {
470
+ const tpl = this._labels[name] ?? DEFAULT_STRINGS[name];
471
+ const text = tpl.replace(/\{(\w+)\}/g, (_, k) => String(vars[k] ?? ''));
472
+ this._live.textContent = '';
473
+ requestAnimationFrame(() => { this._live.textContent = text; });
474
+ }
475
+ _itemFrom(e) {
476
+ for (const n of e.composedPath()) {
477
+ if (n === this)
478
+ return null;
479
+ if (n instanceof HTMLElement && n.parentElement === this)
480
+ return this.items.includes(n) ? n : null;
481
+ }
482
+ return null;
483
+ }
484
+ _gripFrom(e) {
485
+ if (this.disabled)
486
+ return null;
487
+ const item = this._itemFrom(e);
488
+ if (!item || item.hasAttribute('data-locked'))
489
+ return null;
490
+ const origin = e.composedPath()[0];
491
+ if (!(origin instanceof Element))
492
+ return null;
493
+ const hasHandle = !!handleOf(this, item);
494
+ let handle = null;
495
+ try {
496
+ handle = origin.closest(this.handleSelector);
497
+ }
498
+ catch {
499
+ handle = null;
500
+ }
501
+ if (handle && !item.contains(handle))
502
+ handle = null;
503
+ if (hasHandle)
504
+ return handle ? { item, onHandle: true, handle } : null;
505
+ const control = origin.closest(INTERACTIVE);
506
+ if (control && item.contains(control) && control !== item)
507
+ return null;
508
+ return { item, onHandle: false, handle: null };
509
+ }
510
+ _onPointerDown(e) {
511
+ if (session || !e.isPrimary || (e.pointerType === 'mouse' && e.button !== 0) || this._press)
512
+ return;
513
+ const grip = this._gripFrom(e);
514
+ if (!grip)
515
+ return;
516
+ const touchLike = e.pointerType !== 'mouse';
517
+ if (touchLike && !grip.onHandle && performance.now() - lastScrollAt < FLING_GUARD)
518
+ return;
519
+ const press = {
520
+ pointerId: e.pointerId,
521
+ pointerType: e.pointerType,
522
+ item: grip.item,
523
+ onHandle: grip.onHandle,
524
+ startX: e.clientX,
525
+ startY: e.clientY,
526
+ timer: 0,
527
+ };
528
+ this._press = press;
529
+ if (!touchLike && grip.onHandle)
530
+ e.preventDefault();
531
+ if (touchLike && !grip.onHandle) {
532
+ press.timer = window.setTimeout(() => {
533
+ if (this._press === press)
534
+ this._activate(press, press.startX, press.startY);
535
+ }, TOUCH_DELAY);
536
+ }
537
+ addEventListener('pointermove', this._onPressMove, true);
538
+ addEventListener('pointerup', this._onPressEnd, true);
539
+ addEventListener('pointercancel', this._onPressEnd, true);
540
+ if (touchLike)
541
+ addEventListener('contextmenu', preventDefault, true);
542
+ }
543
+ _endPress() {
544
+ const press = this._press;
545
+ if (!press)
546
+ return;
547
+ clearTimeout(press.timer);
548
+ this._press = null;
549
+ removeEventListener('pointermove', this._onPressMove, true);
550
+ removeEventListener('pointerup', this._onPressEnd, true);
551
+ removeEventListener('pointercancel', this._onPressEnd, true);
552
+ if (session?.mode !== 'pointer')
553
+ removeEventListener('contextmenu', preventDefault, true);
554
+ }
555
+ _activate(press, x, y) {
556
+ const item = press.item;
557
+ const touchLike = press.pointerType !== 'mouse';
558
+ this._endPress();
559
+ if (session || !item.isConnected || item.parentElement !== this)
560
+ return;
561
+ const s = newSession('pointer', this, item);
562
+ const rect = item.getBoundingClientRect();
563
+ s.pointerId = press.pointerId;
564
+ s.x = x;
565
+ s.y = y;
566
+ s.startX = x;
567
+ s.startY = y;
568
+ s.offsetX = press.startX - rect.left;
569
+ s.offsetY = press.startY - rect.top;
570
+ session = s;
571
+ const active = document.activeElement;
572
+ if (active && item.contains(active) && active.matches('input, textarea, select, [contenteditable]'))
573
+ active.blur();
574
+ getSelection()?.removeAllRanges();
575
+ createLayer(s, rect);
576
+ markSource(s, 'dim');
577
+ setState(this, 'dragging', true);
578
+ addEventListener('pointermove', onDragMove, true);
579
+ addEventListener('pointerup', onDragEnd, true);
580
+ addEventListener('pointercancel', onDragCancel, true);
581
+ addEventListener('pointerdown', onSecondPointer, true);
582
+ addEventListener('selectstart', preventDefault, true);
583
+ addEventListener('keydown', onDragKey, true);
584
+ addEventListener('blur', onWindowBlur);
585
+ document.addEventListener('visibilitychange', onWindowBlur);
586
+ screen.orientation?.addEventListener('change', onWindowBlur);
587
+ if (touchLike)
588
+ addEventListener('contextmenu', preventDefault, true);
589
+ s.cleanup.push(() => {
590
+ removeEventListener('pointermove', onDragMove, true);
591
+ removeEventListener('pointerup', onDragEnd, true);
592
+ removeEventListener('pointercancel', onDragCancel, true);
593
+ removeEventListener('pointerdown', onSecondPointer, true);
594
+ removeEventListener('selectstart', preventDefault, true);
595
+ removeEventListener('keydown', onDragKey, true);
596
+ removeEventListener('blur', onWindowBlur);
597
+ document.removeEventListener('visibilitychange', onWindowBlur);
598
+ screen.orientation?.removeEventListener('change', onWindowBlur);
599
+ removeEventListener('contextmenu', preventDefault, true);
600
+ });
601
+ dispatchStart(s);
602
+ s.raf = requestAnimationFrame(frame);
603
+ }
604
+ _onKeyDown(e) {
605
+ if (session?.mode === 'keyboard' && session.phase === 'dragging')
606
+ return;
607
+ if (e.key !== ' ' && e.key !== 'Enter')
608
+ return;
609
+ if (e.repeat || e === droppedBy)
610
+ return;
611
+ const grip = this._gripFrom(e);
612
+ if (!grip)
613
+ return;
614
+ const origin = e.composedPath()[0];
615
+ if (!grip.onHandle && origin !== grip.item)
616
+ return;
617
+ e.preventDefault();
618
+ keyHandledAt = performance.now();
619
+ const s = session;
620
+ if (s) {
621
+ if (s.phase === 'holding')
622
+ this._announce('pending');
623
+ return;
624
+ }
625
+ startKeyboard(this, grip.item);
626
+ }
627
+ _onKeyUp(e) {
628
+ if (e.key === ' ' && performance.now() - keyHandledAt < 1000)
629
+ e.preventDefault();
630
+ }
631
+ _onClick(e) {
632
+ if (e.detail !== 0 || performance.now() - keyHandledAt < 1000)
633
+ return;
634
+ const grip = this._gripFrom(e);
635
+ if (!grip?.onHandle)
636
+ return;
637
+ e.preventDefault();
638
+ const s = session;
639
+ if (s?.mode === 'keyboard' && s.phase === 'dragging' && s.item === grip.item) {
640
+ dropKeyboard(s);
641
+ }
642
+ else if (!s) {
643
+ grip.handle?.focus({ preventScroll: true });
644
+ startKeyboard(this, grip.item);
645
+ }
646
+ else if (s.phase === 'holding') {
647
+ this._announce('pending');
648
+ }
649
+ }
650
+ _onFocusOut(e) {
651
+ const s = session;
652
+ if (!s || s.mode !== 'keyboard' || s.phase !== 'dragging' || s.source !== this)
653
+ return;
654
+ const to = e.relatedTarget;
655
+ if (to && s.item.contains(to))
656
+ return;
657
+ if (to) {
658
+ cancelDrag('blur');
659
+ return;
660
+ }
661
+ queueMicrotask(() => {
662
+ if (session !== s || s.phase !== 'dragging')
663
+ return;
664
+ if (s.item.isConnected && s.source.isConnected)
665
+ cancelDrag('blur');
666
+ else
667
+ checkKeyboard();
668
+ });
669
+ }
670
+ }
671
+ function newSession(mode, source, item) {
672
+ return {
673
+ mode,
674
+ phase: 'dragging',
675
+ source,
676
+ sourceId: source.id || null,
677
+ item,
678
+ key: source.keyOf(item),
679
+ group: source.group,
680
+ fromIndex: source.items.indexOf(item),
681
+ target: null,
682
+ targetId: null,
683
+ slot: -1,
684
+ legal: 'ok',
685
+ pointerId: -1,
686
+ x: 0,
687
+ y: 0,
688
+ offsetX: 0,
689
+ offsetY: 0,
690
+ startX: 0,
691
+ startY: 0,
692
+ armed: false,
693
+ raf: 0,
694
+ layer: null,
695
+ ghost: null,
696
+ indicator: null,
697
+ shifts: new Map(),
698
+ cursorMarker: null,
699
+ value: null,
700
+ snapshot: null,
701
+ observed: new WeakSet(),
702
+ observers: [],
703
+ busy: false,
704
+ htmx: false,
705
+ holdStart: 0,
706
+ painted: new Map(),
707
+ timer: 0,
708
+ focus: null,
709
+ resolve: null,
710
+ cleanup: [],
711
+ };
712
+ }
713
+ function setTargetOf(s, c) {
714
+ s.target = c;
715
+ s.targetId = c?.id || null;
716
+ }
717
+ function preventDefault(e) {
718
+ e.preventDefault();
719
+ }
720
+ function blockTouchScroll(e) {
721
+ if (session?.mode === 'pointer' && session.phase === 'dragging' && e.cancelable)
722
+ e.preventDefault();
723
+ }
724
+ function onWindowBlur() {
725
+ if (session?.phase === 'dragging')
726
+ cancelDrag('pointercancel');
727
+ }
728
+ function onSecondPointer(e) {
729
+ if (session?.mode === 'pointer' && session.phase === 'dragging' && e.pointerId !== session.pointerId)
730
+ cancelDrag('pointercancel');
731
+ }
732
+ function dragValue(s) {
733
+ return { key: s.key, group: s.group, source: s.mode, from: fromPos(s) };
734
+ }
735
+ function dispatchStart(s) {
736
+ s.source.dispatchEvent(new CustomEvent('ty-sortable-start', {
737
+ detail: { value: dragValue(s), item: s.item },
738
+ }));
739
+ }
740
+ function fromPos(s) {
741
+ const items = s.source.items;
742
+ const i = items.indexOf(s.item);
743
+ const index = i >= 0 ? i : s.fromIndex;
744
+ return {
745
+ list: s.sourceId,
746
+ index,
747
+ prev: items[index - 1] ? s.source.keyOf(items[index - 1]) : null,
748
+ next: items[index + 1] ? s.source.keyOf(items[index + 1]) : null,
749
+ };
750
+ }
751
+ function othersIn(c, item) {
752
+ return c.items.filter((i) => i !== item);
753
+ }
754
+ function clampLocked(c, item, slot) {
755
+ const others = othersIn(c, item);
756
+ let lead = 0;
757
+ while (lead < others.length && others[lead].hasAttribute('data-locked'))
758
+ lead++;
759
+ let trail = others.length;
760
+ while (trail > lead && others[trail - 1].hasAttribute('data-locked'))
761
+ trail--;
762
+ return Math.max(lead, Math.min(slot, trail));
763
+ }
764
+ function legality(s, c, slot) {
765
+ if (c !== s.source) {
766
+ if (c.disabled)
767
+ return 'blocked';
768
+ const accepts = c.accepts;
769
+ if (accepts) {
770
+ try {
771
+ if (!s.item.matches(accepts))
772
+ return 'blocked';
773
+ }
774
+ catch {
775
+ return 'blocked';
776
+ }
777
+ }
778
+ }
779
+ const fn = c.canDrop;
780
+ if (fn && !fn({ item: s.item, key: s.key, from: s.source, to: c, index: slot }))
781
+ return 'blocked';
782
+ return 'ok';
783
+ }
784
+ function revalidate(s) {
785
+ const source = resolveContainer(s.source, s.sourceId, s.group);
786
+ if (!source)
787
+ return false;
788
+ s.source = source;
789
+ let moved = false;
790
+ if (!s.item.isConnected || s.item.parentElement !== source) {
791
+ const again = s.key ? source.items.find((i) => source.keyOf(i) === s.key) : null;
792
+ if (!again)
793
+ return false;
794
+ s.item = again;
795
+ moved = true;
796
+ }
797
+ if (s.target && !s.target.isConnected) {
798
+ setTargetOf(s, resolveContainer(s.target, s.targetId, s.group));
799
+ moved = true;
800
+ }
801
+ for (const [el, sh] of s.shifts) {
802
+ if (el.isConnected)
803
+ continue;
804
+ sh.anim.cancel();
805
+ s.shifts.delete(el);
806
+ moved = true;
807
+ }
808
+ if (s.layer && !s.layer.isConnected) {
809
+ s.layer = null;
810
+ createLayer(s, s.ghost ? s.ghost.getBoundingClientRect() : s.item.getBoundingClientRect());
811
+ }
812
+ if (moved && s.phase === 'dragging') {
813
+ if (s.shifts.size || shiftPreview(s))
814
+ previewShifts(s);
815
+ else
816
+ markSource(s, 'dim');
817
+ }
818
+ return true;
819
+ }
820
+ function onDragMove(e) {
821
+ const s = session;
822
+ if (!s || s.phase !== 'dragging' || e.pointerId !== s.pointerId)
823
+ return;
824
+ s.x = e.clientX;
825
+ s.y = e.clientY;
826
+ if (!s.armed && Math.hypot(s.x - s.startX, s.y - s.startY) >= AUTOSCROLL_ARM)
827
+ s.armed = true;
828
+ }
829
+ function onDragEnd(e) {
830
+ const s = session;
831
+ if (!s || s.phase !== 'dragging' || e.pointerId !== s.pointerId)
832
+ return;
833
+ s.x = e.clientX;
834
+ s.y = e.clientY;
835
+ hitTest(s);
836
+ suppressUntil = performance.now() + 300;
837
+ if (!s.target)
838
+ cancelDrag('spill');
839
+ else if (s.legal !== 'ok')
840
+ cancelDrag('blocked');
841
+ else
842
+ commit();
843
+ }
844
+ function onDragCancel(e) {
845
+ if (session?.phase === 'dragging' && e.pointerId === session.pointerId)
846
+ cancelDrag('pointercancel');
847
+ }
848
+ function onDragKey(e) {
849
+ if (e.key === 'Escape' && session?.phase === 'dragging' && session.mode === 'pointer') {
850
+ e.preventDefault();
851
+ e.stopPropagation();
852
+ cancelDrag('escape');
853
+ }
854
+ }
855
+ function frame() {
856
+ const s = session;
857
+ if (!s || s.phase !== 'dragging' || s.mode !== 'pointer')
858
+ return;
859
+ if (!revalidate(s)) {
860
+ cancelDrag('gone');
861
+ return;
862
+ }
863
+ if (s.armed)
864
+ autoScroll(scrollersOf(s.target ?? s.source), s.x, s.y);
865
+ hitTest(s);
866
+ if (s.ghost)
867
+ s.ghost.style.translate = `${s.x - s.offsetX}px ${s.y - s.offsetY}px`;
868
+ s.raf = requestAnimationFrame(frame);
869
+ }
870
+ function hitTest(s) {
871
+ let target = null;
872
+ const group = members(s.group, s.source);
873
+ const top = deepElementFromPoint(s.x, s.y);
874
+ for (let el = top; el; el = flatParent(el)) {
875
+ if (el instanceof TySortable && group.includes(el)) {
876
+ target = el;
877
+ break;
878
+ }
879
+ }
880
+ if (!target) {
881
+ const dialog = top ? openDialogOf(top) : null;
882
+ target = group.find((c) => {
883
+ if (dialog && openDialogOf(c) !== dialog)
884
+ return false;
885
+ const r = visibleRect(c);
886
+ return !!r && s.x >= r.left - 12 && s.x <= r.right + 12 && s.y >= r.top - 12 && s.y <= r.bottom + 12;
887
+ }) ?? null;
888
+ }
889
+ if (!target) {
890
+ setTarget(s, null, -1, 'ok');
891
+ return;
892
+ }
893
+ const others = othersIn(target, s.item);
894
+ const vertical = target.axis === 'vertical';
895
+ let slot = others.length;
896
+ for (let i = 0; i < others.length; i++) {
897
+ const r = baseRect(others[i]);
898
+ if (vertical ? s.y < r.top + r.height / 2 : s.x < r.left + r.width / 2) {
899
+ slot = i;
900
+ break;
901
+ }
902
+ }
903
+ slot = clampLocked(target, s.item, slot);
904
+ setTarget(s, target, slot, legality(s, target, slot));
905
+ }
906
+ function setTarget(s, target, slot, legal) {
907
+ const changed = target !== s.target || slot !== s.slot || legal !== s.legal;
908
+ if (s.target && s.target !== target) {
909
+ setState(s.target, 'over', false);
910
+ setState(s.target, 'blocked', false);
911
+ }
912
+ setTargetOf(s, target);
913
+ s.slot = slot;
914
+ s.legal = legal;
915
+ if (target) {
916
+ setState(target, 'over', legal === 'ok');
917
+ setState(target, 'blocked', legal === 'blocked');
918
+ }
919
+ if (changed)
920
+ previewShifts(s);
921
+ if (s.mode === 'pointer')
922
+ setCursor(s, legal === 'blocked' ? 'blocked' : 'grabbing');
923
+ paintIndicator(s);
924
+ if (changed && s.mode === 'keyboard' && target) {
925
+ const total = othersIn(target, s.item).length + 1;
926
+ const vars = { item: itemLabel(s.source, s.item), position: slot + 1, total, list: listLabel(target) };
927
+ s.source._announce(legal === 'ok' ? 'moved' : 'blocked', vars);
928
+ }
929
+ }
930
+ const LAYER_VARS = [
931
+ '--ty-sortable-indicator-color',
932
+ '--ty-sortable-blocked-color',
933
+ '--ty-sortable-ghost-shadow',
934
+ '--ty-sortable-ghost-scale',
935
+ '--ty-sortable-ghost-rotate',
936
+ '--ty-sortable-duration',
937
+ ];
938
+ function createLayer(s, rect) {
939
+ const layer = document.createElement('div');
940
+ layer.setAttribute('popover', 'manual');
941
+ layer.setAttribute('data-ty-sortable-layer', '');
942
+ layer.style.cssText = 'position:fixed;inset:0;margin:0;padding:0;border:0;background:transparent;overflow:visible;pointer-events:none;width:auto;height:auto;max-width:none;max-height:none;color:inherit';
943
+ const cs = getComputedStyle(s.source);
944
+ for (const name of LAYER_VARS) {
945
+ const v = cs.getPropertyValue(name).trim();
946
+ if (v)
947
+ layer.style.setProperty(name, v);
948
+ }
949
+ const root = s.item.getRootNode();
950
+ (root instanceof ShadowRoot ? root : document.body).appendChild(layer);
951
+ try {
952
+ layer.showPopover();
953
+ }
954
+ catch {
955
+ layer.style.zIndex = '2147483647';
956
+ }
957
+ const indicator = document.createElement('div');
958
+ indicator.style.cssText = 'position:absolute;left:0;top:0;display:none;border-radius:999px;pointer-events:none';
959
+ layer.appendChild(indicator);
960
+ s.layer = layer;
961
+ s.indicator = indicator;
962
+ if (s.mode === 'pointer')
963
+ setCursor(s, 'grabbing');
964
+ if (s.mode === 'pointer') {
965
+ addGhost(s, rect);
966
+ lift(s);
967
+ }
968
+ }
969
+ function setCursor(s, cursor) {
970
+ adoptCursorSheet();
971
+ let marker = s.layer?.parentElement === document.body ? s.layer : s.cursorMarker;
972
+ if (!marker && cursor) {
973
+ marker = document.createElement('div');
974
+ marker.setAttribute('data-ty-sortable-layer', '');
975
+ marker.hidden = true;
976
+ document.body.appendChild(marker);
977
+ s.cursorMarker = marker;
978
+ }
979
+ if (!marker)
980
+ return;
981
+ if (cursor)
982
+ marker.setAttribute('data-cursor', cursor);
983
+ else
984
+ marker.removeAttribute('data-cursor');
985
+ }
986
+ let cursorSheet = null;
987
+ function adoptCursorSheet() {
988
+ if (cursorSheet)
989
+ return;
990
+ cursorSheet = new CSSStyleSheet();
991
+ cursorSheet.replaceSync(sortableCursorStyles);
992
+ document.adoptedStyleSheets = [...document.adoptedStyleSheets, cursorSheet];
993
+ }
994
+ function addGhost(s, rect) {
995
+ const ghost = makeGhost(s.item, rect);
996
+ ghost.style.translate = `${rect.left}px ${rect.top}px`;
997
+ s.layer.appendChild(ghost);
998
+ s.ghost = ghost;
999
+ }
1000
+ function makeGhost(item, rect) {
1001
+ const ghost = item.cloneNode(true);
1002
+ ghost.removeAttribute('id');
1003
+ ghost.querySelectorAll('[id]').forEach((n) => n.removeAttribute('id'));
1004
+ ghost.inert = true;
1005
+ ghost.setAttribute('aria-hidden', 'true');
1006
+ ghost.setAttribute('data-ty-sortable-ghost', '');
1007
+ const from = item.querySelectorAll('input, textarea, select');
1008
+ ghost.querySelectorAll('input, textarea, select').forEach((n, i) => {
1009
+ const src = from[i];
1010
+ if (src)
1011
+ n.value = src.value;
1012
+ });
1013
+ const cs = getComputedStyle(item);
1014
+ ghost.style.cssText += `;position:absolute;left:0;top:0;margin:0;box-sizing:border-box;width:${rect.width}px;height:${rect.height}px;pointer-events:none;will-change:translate;transform:none;transform-origin:${Math.min(rect.width / 2, 40)}px 50%;color:${cs.color};font:${cs.font}`;
1015
+ return ghost;
1016
+ }
1017
+ function lift(s) {
1018
+ const ghost = s.ghost;
1019
+ if (!ghost)
1020
+ return;
1021
+ const scale = cssVar(s.source, '--ty-sortable-ghost-scale', '1.02');
1022
+ const rotate = cssVar(s.source, '--ty-sortable-ghost-rotate', '0deg');
1023
+ ghost.animate([{ scale: '1', rotate: '0deg' }, { scale, rotate }], { duration: reducedMotion() ? 0 : 150, easing: 'cubic-bezier(.2, 0, 0, 1)', fill: 'forwards' });
1024
+ }
1025
+ function settleGhost(ghost, x, y, ms) {
1026
+ for (const a of ghost.getAnimations()) {
1027
+ a.commitStyles?.();
1028
+ a.cancel();
1029
+ }
1030
+ ghost.style.transition = ms ? `translate ${ms}ms ease, scale ${ms}ms ease, rotate ${ms}ms ease` : '';
1031
+ ghost.getBoundingClientRect();
1032
+ ghost.style.translate = `${x}px ${y}px`;
1033
+ ghost.style.scale = '1';
1034
+ ghost.style.rotate = '0deg';
1035
+ }
1036
+ function markSource(s, how) {
1037
+ const host = s.source;
1038
+ const root = host.shadowRoot;
1039
+ let sheet = sourceSheets.get(host);
1040
+ if (!sheet) {
1041
+ sheet = new CSSStyleSheet();
1042
+ sourceSheets.set(host, sheet);
1043
+ root.adoptedStyleSheets = [...root.adoptedStyleSheets, sheet];
1044
+ }
1045
+ if (!how) {
1046
+ sheet.replaceSync('');
1047
+ return;
1048
+ }
1049
+ const attr = host.getAttribute('key-attr');
1050
+ let sel;
1051
+ if (s.key && attr && s.item.getAttribute(attr) === s.key)
1052
+ sel = `[${CSS.escape(attr)}="${CSS.escape(s.key)}"]`;
1053
+ else if (s.key && s.item.getAttribute('data-key') === s.key)
1054
+ sel = `[data-key="${CSS.escape(s.key)}"]`;
1055
+ else if (s.key && s.item.id === s.key)
1056
+ sel = `#${CSS.escape(s.key)}`;
1057
+ else
1058
+ sel = `:nth-child(${Array.from(host.children).indexOf(s.item) + 1})`;
1059
+ sheet.replaceSync(how === 'hide'
1060
+ ? `::slotted(${sel}) { opacity: 0 !important; }`
1061
+ : `::slotted(${sel}) { opacity: var(--ty-sortable-source-opacity) !important; outline: var(--ty-sortable-source-outline); outline-offset: -2px; }`);
1062
+ }
1063
+ const sourceSheets = new WeakMap();
1064
+ function shiftOffset(sh) {
1065
+ if (!sh)
1066
+ return 0;
1067
+ const p = sh.anim.effect?.getComputedTiming().progress;
1068
+ return p == null ? sh.to : sh.from + (sh.to - sh.from) * p;
1069
+ }
1070
+ function baseRect(el, s = session) {
1071
+ const r = el.getBoundingClientRect();
1072
+ const sh = s?.shifts.get(el);
1073
+ const d = shiftOffset(sh);
1074
+ if (!d)
1075
+ return r;
1076
+ const dx = sh.vertical ? 0 : d;
1077
+ const dy = sh.vertical ? d : 0;
1078
+ return { top: r.top - dy, left: r.left - dx, bottom: r.bottom - dy, right: r.right - dx, width: r.width, height: r.height };
1079
+ }
1080
+ function gapOf(c) {
1081
+ const items = c.items;
1082
+ if (items.length < 2)
1083
+ return 0;
1084
+ const a = baseRect(items[0]);
1085
+ const b = baseRect(items[1]);
1086
+ return Math.max(0, c.axis === 'vertical' ? b.top - a.bottom : b.left - a.right);
1087
+ }
1088
+ function listGap(s, c) {
1089
+ if (c.items.length > 1)
1090
+ return gapOf(c);
1091
+ if (s.source.items.length > 1)
1092
+ return gapOf(s.source);
1093
+ const vertical = c.axis === 'vertical';
1094
+ const cs = getComputedStyle(c);
1095
+ const gap = parseFloat(vertical ? cs.rowGap : cs.columnGap);
1096
+ if (gap > 0)
1097
+ return gap;
1098
+ const ms = getComputedStyle(s.item);
1099
+ return Math.max(0, parseFloat(vertical ? ms.marginBottom : ms.marginRight) || 0, parseFloat(vertical ? ms.marginTop : ms.marginLeft) || 0);
1100
+ }
1101
+ function flowKids(c) {
1102
+ return Array.from(c.children).filter((k) => k instanceof HTMLElement && !(k instanceof HTMLTemplateElement));
1103
+ }
1104
+ function slotGeometry(c, item, slot) {
1105
+ const others = othersIn(c, item);
1106
+ const vertical = c.axis === 'vertical';
1107
+ const prev = others[slot - 1] ? baseRect(others[slot - 1]) : null;
1108
+ const next = others[slot] ? baseRect(others[slot]) : null;
1109
+ if (!prev && !next) {
1110
+ const r = c.getBoundingClientRect();
1111
+ const cs = getComputedStyle(c);
1112
+ return { x: r.left + parseFloat(cs.paddingLeft), y: r.top + parseFloat(cs.paddingTop), length: vertical ? r.width : r.height, empty: true };
1113
+ }
1114
+ const gap = gapOf(c) || 4;
1115
+ const ref = (next ?? prev);
1116
+ if (vertical) {
1117
+ const y = prev && next ? (prev.bottom + next.top) / 2 : next ? next.top - gap / 2 : prev.bottom + gap / 2;
1118
+ return { x: ref.left, y, length: ref.width, empty: false };
1119
+ }
1120
+ const x = prev && next ? (prev.right + next.left) / 2 : next ? next.left - gap / 2 : prev.right + gap / 2;
1121
+ return { x, y: ref.top, length: ref.height, empty: false };
1122
+ }
1123
+ function gapOrigin(s, t) {
1124
+ const others = othersIn(t, s.item);
1125
+ const next = others[s.slot] ? baseRect(others[s.slot]) : null;
1126
+ const prev = others[s.slot - 1] ? baseRect(others[s.slot - 1]) : null;
1127
+ const g = slotGeometry(t, s.item, s.slot);
1128
+ if (g.empty)
1129
+ return { x: g.x, y: g.y };
1130
+ const gap = listGap(s, t);
1131
+ if (t.axis === 'vertical')
1132
+ return { x: (next ?? prev).left, y: next ? next.top : prev.bottom + gap };
1133
+ return { x: next ? next.left : prev.right + gap, y: (next ?? prev).top };
1134
+ }
1135
+ function shiftPreview(s) {
1136
+ return !(s.target ?? s.source).hasAttribute('drop-line');
1137
+ }
1138
+ function paintIndicator(s) {
1139
+ const ind = s.indicator;
1140
+ if (!ind)
1141
+ return;
1142
+ const c = s.target;
1143
+ if (!c || s.slot < 0 || s.phase !== 'dragging') {
1144
+ ind.style.display = 'none';
1145
+ return;
1146
+ }
1147
+ if (shiftPreview(s) && s.legal === 'ok') {
1148
+ ind.style.display = 'none';
1149
+ return;
1150
+ }
1151
+ const g = slotGeometry(c, s.item, s.slot);
1152
+ if (g.empty) {
1153
+ ind.style.display = 'none';
1154
+ return;
1155
+ }
1156
+ const size = parseFloat(cssVar(c, '--ty-sortable-indicator-size', '2px')) || 2;
1157
+ const color = s.legal === 'ok'
1158
+ ? cssVar(c, '--ty-sortable-indicator-color', '#3b82f6')
1159
+ : cssVar(c, '--ty-sortable-blocked-color', '#ef4444');
1160
+ const vertical = c.axis === 'vertical';
1161
+ ind.style.display = 'block';
1162
+ ind.style.background = color;
1163
+ ind.style.width = vertical ? `${g.length}px` : `${size}px`;
1164
+ ind.style.height = vertical ? `${size}px` : `${g.length}px`;
1165
+ ind.style.transform = vertical
1166
+ ? `translate3d(${g.x}px, ${g.y - size / 2}px, 0)`
1167
+ : `translate3d(${g.x - size / 2}px, ${g.y}px, 0)`;
1168
+ }
1169
+ function shiftsFor(s, keepSource = false) {
1170
+ const m = new Map();
1171
+ const t = s.target;
1172
+ if (!t || s.slot < 0 || s.legal !== 'ok')
1173
+ return m;
1174
+ const source = s.source;
1175
+ const kids = flowKids(source);
1176
+ const from = kids.indexOf(s.item);
1177
+ if (from < 0)
1178
+ return m;
1179
+ const along = (c, r) => c.axis === 'vertical' ? [r.top, r.bottom] : [r.left, r.right];
1180
+ const ir = baseRect(s.item);
1181
+ const [iStart, iEnd] = along(source, ir);
1182
+ const size = iEnd - iStart;
1183
+ const others = othersIn(source, s.item);
1184
+ if (t === source) {
1185
+ const fromSlot = source.items.indexOf(s.item);
1186
+ if (s.slot === fromSlot)
1187
+ return m;
1188
+ const step = size + listGap(s, source);
1189
+ if (s.slot > fromSlot) {
1190
+ const last = others[s.slot - 1];
1191
+ const passed = kids.slice(from + 1, kids.indexOf(last) + 1);
1192
+ passed.forEach((k) => m.set(k, -step));
1193
+ m.set(s.item, along(source, baseRect(last))[1] - iEnd);
1194
+ }
1195
+ else {
1196
+ const first = others[s.slot];
1197
+ const passed = kids.slice(kids.indexOf(first), from);
1198
+ passed.forEach((k) => m.set(k, step));
1199
+ m.set(s.item, along(source, baseRect(first))[0] - iStart);
1200
+ }
1201
+ return m;
1202
+ }
1203
+ if (!keepSource) {
1204
+ const close = -(size + listGap(s, source));
1205
+ kids.slice(from + 1).forEach((k) => m.set(k, close));
1206
+ }
1207
+ const tKids = flowKids(t);
1208
+ const tOthers = othersIn(t, s.item);
1209
+ const start = s.slot < tOthers.length
1210
+ ? tKids.indexOf(tOthers[s.slot])
1211
+ : tOthers.length ? tKids.indexOf(tOthers[tOthers.length - 1]) + 1 : tKids.length;
1212
+ const open = (t.axis === 'vertical' ? ir.height : ir.width) + listGap(s, t);
1213
+ tKids.slice(start).forEach((k) => m.set(k, open));
1214
+ return m;
1215
+ }
1216
+ const SHIFT_EASING = 'cubic-bezier(.2, 0, 0, 1)';
1217
+ function applyShifts(s, want, ms) {
1218
+ for (const el of new Set([...s.shifts.keys(), ...want.keys()])) {
1219
+ const to = want.get(el) ?? 0;
1220
+ const cur = s.shifts.get(el);
1221
+ if ((cur?.to ?? 0) === to)
1222
+ continue;
1223
+ const list = el.parentElement instanceof TySortable ? el.parentElement : s.source;
1224
+ const vertical = list.axis === 'vertical';
1225
+ const from = shiftOffset(cur);
1226
+ const at = (d) => (vertical ? `0 ${d}px` : `${d}px 0`);
1227
+ const anim = el.animate([{ translate: at(from) }, { translate: at(to) }], { duration: ms, easing: SHIFT_EASING, fill: 'forwards', composite: 'add' });
1228
+ cur?.anim.cancel();
1229
+ s.shifts.set(el, { from, to, vertical, anim });
1230
+ }
1231
+ }
1232
+ function cancelShifts(s) {
1233
+ s.shifts.forEach(({ anim }) => anim.cancel());
1234
+ s.shifts.clear();
1235
+ }
1236
+ function previewShifts(s) {
1237
+ if (s.phase !== 'dragging')
1238
+ return;
1239
+ const ms = Math.min(duration(s.source), 200);
1240
+ if (!shiftPreview(s)) {
1241
+ if (s.shifts.size)
1242
+ applyShifts(s, new Map(), ms);
1243
+ markSource(s, 'dim');
1244
+ return;
1245
+ }
1246
+ const crossing = !!s.target && s.target !== s.source && s.legal === 'ok';
1247
+ const keyboard = s.mode !== 'pointer';
1248
+ markSource(s, crossing && !keyboard ? 'hide' : 'dim');
1249
+ applyShifts(s, shiftsFor(s, keyboard), ms);
1250
+ if (keyboard) {
1251
+ if (crossing) {
1252
+ if (!s.ghost && s.layer)
1253
+ addGhost(s, s.item.getBoundingClientRect());
1254
+ const o = gapOrigin(s, s.target);
1255
+ s.ghost.style.display = '';
1256
+ settleGhost(s.ghost, o.x, o.y, ms);
1257
+ }
1258
+ else if (s.ghost) {
1259
+ s.ghost.style.display = 'none';
1260
+ }
1261
+ }
1262
+ }
1263
+ function clearStates(s) {
1264
+ for (const c of new Set([s.source, s.target, ...members(s.group, s.source)])) {
1265
+ if (!c)
1266
+ continue;
1267
+ for (const st of ['over', 'blocked', 'dragging', 'pending'])
1268
+ setState(c, st, false);
1269
+ }
1270
+ }
1271
+ function teardown(s) {
1272
+ cancelAnimationFrame(s.raf);
1273
+ clearTimeout(s.timer);
1274
+ s.cleanup.forEach((fn) => fn());
1275
+ s.cleanup = [];
1276
+ s.observers.forEach((o) => o.disconnect());
1277
+ s.observers = [];
1278
+ cancelShifts(s);
1279
+ s.layer?.remove();
1280
+ s.cursorMarker?.remove();
1281
+ s.cursorMarker = null;
1282
+ if (session === s)
1283
+ session = null;
1284
+ if (!session || session.source !== s.source)
1285
+ markSource(s, false);
1286
+ }
1287
+ function flyBack(s, el, done) {
1288
+ const to = el?.isConnected ? baseRect(el, s) : null;
1289
+ const ghost = s.ghost;
1290
+ const ms = duration(s.source);
1291
+ if (s.indicator)
1292
+ s.indicator.style.display = 'none';
1293
+ setCursor(s, null);
1294
+ if (s.shifts.size) {
1295
+ applyShifts(s, new Map(), ms);
1296
+ if (s.source.items.includes(s.item))
1297
+ markSource(s, 'dim');
1298
+ }
1299
+ if (!ghost || !to || !ms) {
1300
+ if (ms && s.shifts.size)
1301
+ window.setTimeout(done, ms);
1302
+ else
1303
+ done();
1304
+ return;
1305
+ }
1306
+ settleGhost(ghost, to.left, to.top, ms);
1307
+ window.setTimeout(done, ms);
1308
+ }
1309
+ function cancelDrag(reason) {
1310
+ const s = session;
1311
+ if (!s || s.phase !== 'dragging')
1312
+ return;
1313
+ cancelAnimationFrame(s.raf);
1314
+ session = null;
1315
+ if (s.mode === 'pointer' && (reason === 'escape' || reason === 'gone' || reason === 'disabled'))
1316
+ suppressNextRelease(s.pointerId);
1317
+ const source = s.source.isConnected ? s.source : resolveContainer(s.source, s.sourceId, s.group) ?? s.source;
1318
+ source.dispatchEvent(new CustomEvent('ty-sortable-cancel', {
1319
+ detail: { value: dragValue(s), item: s.item, reason },
1320
+ }));
1321
+ if (s.mode === 'keyboard' && reason !== 'gone') {
1322
+ source._announce('cancelled', { item: itemLabel(source, s.item), position: fromPos(s).index + 1, list: listLabel(source) });
1323
+ }
1324
+ s.cleanup.forEach((fn) => fn());
1325
+ s.cleanup = [];
1326
+ clearStates(s);
1327
+ flyBack(s, s.item.isConnected ? s.item : null, () => teardown(s));
1328
+ }
1329
+ function startKeyboard(source, item) {
1330
+ const s = newSession('keyboard', source, item);
1331
+ session = s;
1332
+ createLayer(s, item.getBoundingClientRect());
1333
+ markSource(s, 'dim');
1334
+ setState(source, 'dragging', true);
1335
+ addEventListener('keydown', onKeyboardKey, true);
1336
+ addEventListener('pointerdown', onKeyboardPointer, true);
1337
+ s.cleanup.push(() => {
1338
+ removeEventListener('keydown', onKeyboardKey, true);
1339
+ removeEventListener('pointerdown', onKeyboardPointer, true);
1340
+ });
1341
+ dispatchStart(s);
1342
+ setTargetOf(s, source);
1343
+ s.slot = s.fromIndex;
1344
+ s.legal = 'ok';
1345
+ setState(source, 'over', true);
1346
+ paintIndicator(s);
1347
+ source._announce('pickedUp', {
1348
+ item: itemLabel(source, item),
1349
+ position: s.fromIndex + 1,
1350
+ total: source.items.length,
1351
+ list: listLabel(source),
1352
+ });
1353
+ }
1354
+ function onKeyboardKey(e) {
1355
+ const s = session;
1356
+ if (!s || s.mode !== 'keyboard' || s.phase !== 'dragging')
1357
+ return;
1358
+ if (!checkKeyboard())
1359
+ return;
1360
+ keyboardMove(s, e);
1361
+ }
1362
+ function onKeyboardPointer() {
1363
+ if (session?.mode === 'keyboard' && session.phase === 'dragging')
1364
+ cancelDrag('blur');
1365
+ }
1366
+ function checkKeyboard() {
1367
+ const s = session;
1368
+ if (!s || s.mode !== 'keyboard' || s.phase !== 'dragging')
1369
+ return false;
1370
+ const before = s.item;
1371
+ const hadFocus = !document.activeElement || document.activeElement === document.body || before.contains(document.activeElement);
1372
+ if (!revalidate(s) || !s.target) {
1373
+ cancelDrag('gone');
1374
+ return false;
1375
+ }
1376
+ if (s.item !== before && hadFocus)
1377
+ (handleOf(s.source, s.item) ?? s.item).focus({ preventScroll: true });
1378
+ s.slot = clampLocked(s.target, s.item, Math.min(s.slot, othersIn(s.target, s.item).length));
1379
+ paintIndicator(s);
1380
+ return true;
1381
+ }
1382
+ function keyboardMove(s, e) {
1383
+ const target = s.target ?? s.source;
1384
+ const vertical = target.axis === 'vertical';
1385
+ const back = vertical ? 'ArrowUp' : 'ArrowLeft';
1386
+ const fwd = vertical ? 'ArrowDown' : 'ArrowRight';
1387
+ const prevList = vertical ? 'ArrowLeft' : 'ArrowUp';
1388
+ const nextList = vertical ? 'ArrowRight' : 'ArrowDown';
1389
+ const count = othersIn(target, s.item).length;
1390
+ switch (e.key) {
1391
+ case back:
1392
+ case fwd:
1393
+ case 'Home':
1394
+ case 'End': {
1395
+ e.preventDefault();
1396
+ const want = e.key === back ? s.slot - 1 : e.key === fwd ? s.slot + 1 : e.key === 'Home' ? 0 : count;
1397
+ const slot = clampLocked(target, s.item, Math.max(0, Math.min(want, count)));
1398
+ setTarget(s, target, slot, legality(s, target, slot));
1399
+ revealSlot(s);
1400
+ return;
1401
+ }
1402
+ case prevList:
1403
+ case nextList: {
1404
+ e.preventDefault();
1405
+ const lists = members(s.group, s.source)
1406
+ .filter((c) => !c.disabled || c === s.source)
1407
+ .sort((a, b) => {
1408
+ const ra = a.getBoundingClientRect();
1409
+ const rb = b.getBoundingClientRect();
1410
+ return vertical ? ra.left - rb.left || ra.top - rb.top : ra.top - rb.top || ra.left - rb.left;
1411
+ });
1412
+ const i = lists.indexOf(target);
1413
+ const dir = e.key === nextList ? 1 : -1;
1414
+ for (let j = i + dir; j >= 0 && j < lists.length; j += dir) {
1415
+ const c = lists[j];
1416
+ const slot = clampLocked(c, s.item, Math.min(s.slot, othersIn(c, s.item).length));
1417
+ if (legality(s, c, slot) === 'ok') {
1418
+ setTarget(s, c, slot, 'ok');
1419
+ revealSlot(s);
1420
+ return;
1421
+ }
1422
+ }
1423
+ return;
1424
+ }
1425
+ case ' ':
1426
+ case 'Enter':
1427
+ e.preventDefault();
1428
+ e.stopPropagation();
1429
+ keyHandledAt = performance.now();
1430
+ droppedBy = e;
1431
+ dropKeyboard(s);
1432
+ return;
1433
+ case 'Escape':
1434
+ e.preventDefault();
1435
+ e.stopPropagation();
1436
+ cancelDrag('escape');
1437
+ return;
1438
+ case 'Tab':
1439
+ cancelDrag('blur');
1440
+ return;
1441
+ }
1442
+ }
1443
+ function dropKeyboard(s) {
1444
+ if (!s.target || s.legal !== 'ok')
1445
+ cancelDrag('blocked');
1446
+ else
1447
+ commit();
1448
+ }
1449
+ function revealSlot(s) {
1450
+ const c = s.target;
1451
+ if (!c)
1452
+ return;
1453
+ const others = othersIn(c, s.item);
1454
+ const near = others[s.slot - 1] ?? others[s.slot] ?? c;
1455
+ near.scrollIntoView({ block: 'nearest', inline: 'nearest' });
1456
+ requestAnimationFrame(() => { if (session === s)
1457
+ paintIndicator(s); });
1458
+ }
1459
+ function liveSource(s) {
1460
+ return resolveContainer(s.source, s.sourceId, s.group) ?? s.source;
1461
+ }
1462
+ function liveTarget(s) {
1463
+ return (s.target && resolveContainer(s.target, s.targetId, s.group)) ?? s.target ?? liveSource(s);
1464
+ }
1465
+ function holdLists(s) {
1466
+ return s.group ? members(s.group, liveSource(s)) : [...new Set([liveSource(s), liveTarget(s)])];
1467
+ }
1468
+ function groupSnapshot(s) {
1469
+ const map = new Map();
1470
+ for (const c of holdLists(s))
1471
+ map.set(c.id || c, c.items.map((i) => c.keyOf(i) ?? i));
1472
+ return map;
1473
+ }
1474
+ function snapshotChanged(s) {
1475
+ const now = groupSnapshot(s);
1476
+ const before = s.snapshot;
1477
+ if (now.size !== before.size)
1478
+ return true;
1479
+ for (const [k, tokens] of before) {
1480
+ const t = now.get(k);
1481
+ if (!t || !sameTokens(t, tokens))
1482
+ return true;
1483
+ }
1484
+ return false;
1485
+ }
1486
+ function observeForHold(s, c) {
1487
+ if (s.observed.has(c))
1488
+ return;
1489
+ s.observed.add(c);
1490
+ const o = new MutationObserver(() => evaluateHold('mutation'));
1491
+ o.observe(c, { childList: true });
1492
+ const a = new MutationObserver(() => watchBusy());
1493
+ a.observe(c, { attributes: true, attributeFilter: ['aria-busy', 'class'] });
1494
+ s.observers.push(o, a);
1495
+ }
1496
+ function buildValue(s) {
1497
+ const target = s.target;
1498
+ const from = fromPos(s);
1499
+ const others = othersIn(target, s.item);
1500
+ const to = {
1501
+ list: target.id || null,
1502
+ index: s.slot,
1503
+ prev: others[s.slot - 1] ? target.keyOf(others[s.slot - 1]) : null,
1504
+ next: others[s.slot] ? target.keyOf(others[s.slot]) : null,
1505
+ };
1506
+ const order = {};
1507
+ const keys = (c, list) => list.map((i) => c.keyOf(i));
1508
+ if (target !== s.source && s.source.id)
1509
+ order[s.source.id] = keys(s.source, othersIn(s.source, s.item));
1510
+ if (target.id) {
1511
+ const after = keys(target, others);
1512
+ after.splice(s.slot, 0, s.key);
1513
+ order[target.id] = after;
1514
+ }
1515
+ return { key: s.key, group: s.group, source: s.mode, from, to, order };
1516
+ }
1517
+ function commit() {
1518
+ const s = session;
1519
+ const target = s.target;
1520
+ cancelAnimationFrame(s.raf);
1521
+ s.cleanup.forEach((fn) => fn());
1522
+ s.cleanup = [];
1523
+ if (target === s.source && s.slot === s.source.items.indexOf(s.item)) {
1524
+ session = null;
1525
+ clearStates(s);
1526
+ if (s.mode === 'keyboard') {
1527
+ s.source._announce('dropped', { item: itemLabel(s.source, s.item), position: s.slot + 1, total: target.items.length, list: listLabel(target) });
1528
+ }
1529
+ flyBack(s, s.item, () => teardown(s));
1530
+ return false;
1531
+ }
1532
+ const value = buildValue(s);
1533
+ s.value = value;
1534
+ s.snapshot = groupSnapshot(s);
1535
+ s.phase = 'holding';
1536
+ s.holdStart = performance.now();
1537
+ s.focus = document.activeElement;
1538
+ for (const c of holdLists(s)) {
1539
+ setState(c, 'over', false);
1540
+ setState(c, 'blocked', false);
1541
+ setState(c, 'dragging', false);
1542
+ setState(c, 'pending', true);
1543
+ }
1544
+ holdVisual(s);
1545
+ notePainted(s);
1546
+ const track = () => {
1547
+ if (session !== s || s.phase !== 'holding')
1548
+ return;
1549
+ notePainted(s);
1550
+ requestAnimationFrame(track);
1551
+ };
1552
+ requestAnimationFrame(track);
1553
+ for (const c of holdLists(s))
1554
+ observeForHold(s, c);
1555
+ s.busy = isBusy(s);
1556
+ const event = new CustomEvent('ty-sortable-change', {
1557
+ detail: { value, item: s.item, fromContainer: s.source, toContainer: target },
1558
+ bubbles: true,
1559
+ cancelable: true,
1560
+ });
1561
+ target.dispatchEvent(event);
1562
+ if (session !== s || s.phase !== 'holding')
1563
+ return true;
1564
+ if (event.defaultPrevented) {
1565
+ release('rejected');
1566
+ return true;
1567
+ }
1568
+ s.busy = isBusy(s);
1569
+ s.htmx = s.busy && holdLists(s).some((c) => c.classList.contains('htmx-request'));
1570
+ armTimer(s);
1571
+ return true;
1572
+ }
1573
+ function holdVisual(s) {
1574
+ const target = s.target;
1575
+ if (!s.layer)
1576
+ createLayer(s, s.item.getBoundingClientRect());
1577
+ if (!s.ghost && s.layer) {
1578
+ addGhost(s, s.item.getBoundingClientRect());
1579
+ s.ghost.getBoundingClientRect();
1580
+ }
1581
+ s.ghost.style.display = '';
1582
+ setCursor(s, null);
1583
+ if (s.indicator)
1584
+ s.indicator.style.display = 'none';
1585
+ const ms = duration(target);
1586
+ const vertical = target.axis === 'vertical';
1587
+ const keep = s.mode !== 'pointer';
1588
+ const want = shiftsFor(s, keep);
1589
+ let x;
1590
+ let y;
1591
+ if (target === s.source) {
1592
+ const r = baseRect(s.item);
1593
+ const d = want.get(s.item) ?? 0;
1594
+ x = r.left + (vertical ? 0 : d);
1595
+ y = r.top + (vertical ? d : 0);
1596
+ }
1597
+ else {
1598
+ ;
1599
+ ({ x, y } = gapOrigin(s, target));
1600
+ markSource(s, keep ? 'dim' : 'hide');
1601
+ }
1602
+ applyShifts(s, want, ms);
1603
+ settleGhost(s.ghost, x, y, ms);
1604
+ }
1605
+ function isBusy(s) {
1606
+ return holdLists(s).some((c) => c.getAttribute('aria-busy') === 'true' || c.classList.contains('htmx-request'));
1607
+ }
1608
+ function watchBusy() {
1609
+ const s = session;
1610
+ if (!s || s.phase !== 'holding')
1611
+ return;
1612
+ const busy = isBusy(s);
1613
+ if (s.busy && !busy) {
1614
+ s.busy = false;
1615
+ const decide = () => {
1616
+ if (session !== s || s.busy)
1617
+ return;
1618
+ s.observers.forEach((o) => o.takeRecords());
1619
+ evaluateHold('idle');
1620
+ };
1621
+ if (s.htmx) {
1622
+ s.htmx = false;
1623
+ const done = (e) => {
1624
+ const t = e?.target;
1625
+ if (t instanceof Element && t.isConnected && !holdLists(s).some((c) => t.contains(c) || c.contains(t)))
1626
+ return;
1627
+ document.removeEventListener('htmx:afterSettle', done);
1628
+ clearTimeout(cap);
1629
+ requestAnimationFrame(decide);
1630
+ };
1631
+ const cap = window.setTimeout(done, HTMX_SETTLE_CAP);
1632
+ document.addEventListener('htmx:afterSettle', done);
1633
+ return;
1634
+ }
1635
+ requestAnimationFrame(() => requestAnimationFrame(() => {
1636
+ window.setTimeout(decide, IDLE_GRACE);
1637
+ }));
1638
+ }
1639
+ else if (busy) {
1640
+ s.busy = true;
1641
+ s.htmx = holdLists(s).some((c) => c.classList.contains('htmx-request'));
1642
+ }
1643
+ }
1644
+ function armTimer(s) {
1645
+ clearTimeout(s.timer);
1646
+ const timeout = s.source.holdTimeout;
1647
+ s.timer = window.setTimeout(function tick() {
1648
+ if (session !== s || s.phase !== 'holding')
1649
+ return;
1650
+ if (s.busy && performance.now() - s.holdStart < BUSY_CAP) {
1651
+ s.timer = window.setTimeout(tick, 250);
1652
+ return;
1653
+ }
1654
+ release('unknown');
1655
+ }, timeout);
1656
+ }
1657
+ function locate(s) {
1658
+ let found = null;
1659
+ let count = 0;
1660
+ for (const c of holdLists(s)) {
1661
+ const items = c.items;
1662
+ items.forEach((el, i) => {
1663
+ if (s.key ? c.keyOf(el) !== s.key : el !== s.item)
1664
+ return;
1665
+ count++;
1666
+ if (found && c !== liveTarget(s))
1667
+ return;
1668
+ found = {
1669
+ list: c,
1670
+ index: i,
1671
+ prev: items[i - 1] ? c.keyOf(items[i - 1]) : null,
1672
+ next: items[i + 1] ? c.keyOf(items[i + 1]) : null,
1673
+ };
1674
+ });
1675
+ }
1676
+ return found ? { ...found, count } : null;
1677
+ }
1678
+ function evaluateHold(trigger) {
1679
+ const s = session;
1680
+ if (!s || s.phase !== 'holding')
1681
+ return;
1682
+ const settled = trigger !== 'mutation';
1683
+ if (!snapshotChanged(s)) {
1684
+ if (settled)
1685
+ release('rejected');
1686
+ return;
1687
+ }
1688
+ const v = s.value;
1689
+ const at = locate(s);
1690
+ if (!at) {
1691
+ release('reconciled');
1692
+ return;
1693
+ }
1694
+ const target = liveTarget(s);
1695
+ const source = liveSource(s);
1696
+ if (at.count === 1 && at.list === target && ((at.prev === v.to.prev && at.next === v.to.next) || at.index === v.to.index)) {
1697
+ release('accepted');
1698
+ return;
1699
+ }
1700
+ const atFrom = at.count === 1 && at.list === source && at.prev === v.from.prev && at.next === v.from.next;
1701
+ if (atFrom) {
1702
+ if (settled)
1703
+ release('rejected');
1704
+ else
1705
+ dropRenderedShifts(s);
1706
+ return;
1707
+ }
1708
+ if (at.count > 1 && !settled) {
1709
+ dropRenderedShifts(s);
1710
+ return;
1711
+ }
1712
+ release('reconciled');
1713
+ }
1714
+ function notePainted(s) {
1715
+ s.painted.clear();
1716
+ for (const el of s.shifts.keys()) {
1717
+ const list = el.parentElement instanceof TySortable ? el.parentElement : null;
1718
+ const k = list?.keyOf(el);
1719
+ if (k && k !== s.key && el.isConnected)
1720
+ s.painted.set(k, el.getBoundingClientRect());
1721
+ }
1722
+ }
1723
+ function dropRenderedShifts(s) {
1724
+ const before = s.snapshot;
1725
+ for (const c of holdLists(s)) {
1726
+ const was = before.get(c.id || c);
1727
+ if (was && sameTokens(was, c.items.map((i) => c.keyOf(i) ?? i)))
1728
+ continue;
1729
+ for (const [el, sh] of s.shifts) {
1730
+ if (el.parentElement !== c)
1731
+ continue;
1732
+ sh.anim.cancel();
1733
+ s.shifts.delete(el);
1734
+ const k = c.keyOf(el);
1735
+ if (k)
1736
+ s.painted.delete(k);
1737
+ }
1738
+ }
1739
+ }
1740
+ function release(outcome) {
1741
+ const s = session;
1742
+ if (!s || s.phase !== 'holding')
1743
+ return;
1744
+ session = null;
1745
+ clearTimeout(s.timer);
1746
+ s.observers.forEach((o) => o.disconnect());
1747
+ s.observers = [];
1748
+ clearStates(s);
1749
+ const value = s.value;
1750
+ const target = liveTarget(s);
1751
+ const source = liveSource(s);
1752
+ const keyed = (c) => (s.key ? c.items.find((i) => c.keyOf(i) === s.key) ?? null : null);
1753
+ const lists = holdLists(s);
1754
+ const keyboard = s.mode !== 'pointer';
1755
+ const findNow = () => {
1756
+ for (const c of [target, ...lists]) {
1757
+ const el = keyed(c) ?? (!s.key && s.item.parentElement === c ? s.item : null);
1758
+ if (el)
1759
+ return { list: c, el };
1760
+ }
1761
+ return null;
1762
+ };
1763
+ const unchanged = outcome === 'unknown' && !snapshotChanged(s);
1764
+ if (outcome === 'rejected' || unchanged) {
1765
+ const back = keyed(source) ?? (s.item.isConnected ? s.item : null);
1766
+ if (keyboard) {
1767
+ if (outcome === 'rejected')
1768
+ source._announce('rejected', { item: itemLabel(source, s.item), position: value.from.index + 1, list: listLabel(source) });
1769
+ else
1770
+ source._announce('unknown', { item: itemLabel(source, s.item) });
1771
+ if (back)
1772
+ restoreFocus(s, source, back);
1773
+ }
1774
+ flyBack(s, back, () => teardown(s));
1775
+ }
1776
+ else {
1777
+ const ghostRect = s.ghost?.getBoundingClientRect() ?? null;
1778
+ const seen = s.painted;
1779
+ teardown(s);
1780
+ const now = findNow();
1781
+ const ms = duration(target);
1782
+ const glide = (el, from) => {
1783
+ const r = el.getBoundingClientRect();
1784
+ const dx = from.left - r.left;
1785
+ const dy = from.top - r.top;
1786
+ if (Math.abs(dx) < 0.5 && Math.abs(dy) < 0.5)
1787
+ return;
1788
+ el.animate([{ translate: `${dx}px ${dy}px` }, { translate: '0 0' }], { duration: ms, easing: SHIFT_EASING, composite: 'add' });
1789
+ };
1790
+ if (ms && outcome !== 'unknown') {
1791
+ if (now && ghostRect && outcome === 'accepted')
1792
+ glide(now.el, ghostRect);
1793
+ for (const c of lists) {
1794
+ for (const el of c.items) {
1795
+ const k = c.keyOf(el);
1796
+ const from = k ? seen.get(k) : undefined;
1797
+ if (from)
1798
+ glide(el, from);
1799
+ }
1800
+ }
1801
+ }
1802
+ if (now && outcome !== 'unknown' && now.list.hasAttribute('flash'))
1803
+ flash(now.list, now.el);
1804
+ if (keyboard) {
1805
+ const name = itemLabel(source, now?.el ?? s.item);
1806
+ if (now) {
1807
+ const items = now.list.items;
1808
+ const vars = { item: name, position: items.indexOf(now.el) + 1, total: items.length, list: listLabel(now.list) };
1809
+ now.list._announce(outcome === 'accepted' ? 'dropped' : outcome === 'unknown' ? 'unknown' : 'reconciled', vars);
1810
+ restoreFocus(s, now.list, now.el);
1811
+ }
1812
+ else {
1813
+ source._announce(outcome === 'unknown' ? 'unknown' : 'removed', { item: name });
1814
+ const near = source.items[Math.min(value.from.index, source.items.length - 1)];
1815
+ if (near)
1816
+ restoreFocus(s, source, near);
1817
+ }
1818
+ }
1819
+ }
1820
+ target.dispatchEvent(new CustomEvent('ty-sortable-settle', { detail: { value, outcome } }));
1821
+ s.resolve?.(outcome);
1822
+ }
1823
+ function flash(c, el) {
1824
+ const color = cssVar(c, '--ty-sortable-flash-color', cssVar(c, '--ty-sortable-indicator-color', '#3b82f6'));
1825
+ el.animate([{ outline: `2px solid ${color}`, outlineOffset: '-2px' }, { outline: '2px solid transparent', outlineOffset: '-2px' }], { duration: 700, easing: 'ease-out' });
1826
+ }
1827
+ function restoreFocus(s, c, item) {
1828
+ const active = document.activeElement;
1829
+ const lost = !active || active === document.body || !s.focus || !s.focus.isConnected;
1830
+ if (!lost && active !== s.focus)
1831
+ return;
1832
+ if (active && item.contains(active))
1833
+ return;
1834
+ (handleOf(c, item) ?? item).focus({ preventScroll: true });
1835
+ }
1836
+ if (!customElements.get('ty-sortable')) {
1837
+ customElements.define('ty-sortable', TySortable);
1838
+ }