@inertiaui/vanilla 1.5.0 → 1.6.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.
package/dist/index.js CHANGED
@@ -6,21 +6,20 @@ function generateId(prefix = "inertiaui_") {
6
6
  function strToLowercase(key) {
7
7
  return key.toLowerCase();
8
8
  }
9
- function except(target, keys, ignoreCase = false) {
9
+ function filterKeys(target, keys, ignoreCase, include) {
10
10
  if (ignoreCase) keys = keys.map(strToLowercase);
11
- if (Array.isArray(target)) return target.filter((key) => !keys.includes(ignoreCase ? strToLowercase(key) : key));
11
+ const keySet = new Set(keys);
12
+ if (Array.isArray(target)) return target.filter((key) => keySet.has(ignoreCase ? strToLowercase(key) : key) === include);
12
13
  return Object.keys(target).reduce((acc, key) => {
13
- if (!keys.includes(ignoreCase ? strToLowercase(key) : key)) acc[key] = target[key];
14
+ if (keySet.has(ignoreCase ? strToLowercase(key) : key) === include) acc[key] = target[key];
14
15
  return acc;
15
16
  }, {});
16
17
  }
18
+ function except(target, keys, ignoreCase = false) {
19
+ return filterKeys(target, keys, ignoreCase, false);
20
+ }
17
21
  function only(target, keys, ignoreCase = false) {
18
- if (ignoreCase) keys = keys.map(strToLowercase);
19
- if (Array.isArray(target)) return target.filter((key) => keys.includes(ignoreCase ? strToLowercase(key) : key));
20
- return Object.keys(target).reduce((acc, key) => {
21
- if (keys.includes(ignoreCase ? strToLowercase(key) : key)) acc[key] = target[key];
22
- return acc;
23
- }, {});
22
+ return filterKeys(target, keys, ignoreCase, true);
24
23
  }
25
24
  function rejectNullValues(target) {
26
25
  if (Array.isArray(target)) return target.filter((item) => item !== null);
@@ -31,21 +30,11 @@ function rejectNullValues(target) {
31
30
  }
32
31
  function kebabCase(string) {
33
32
  if (!string) return "";
34
- return string.replace(/([A-Z]+)([A-Z][a-z])/g, "$1-$2").replace(/([a-z\d])([A-Z])/g, "$1-$2").replace(/[\s_]+/g, "-").replace(/-+/g, "-").toLowerCase();
33
+ return string.replace(/([A-Z])([A-Z][a-z])/g, "$1-$2").replace(/([a-z\d])([A-Z])/g, "$1-$2").replace(/[\s_]+/g, "-").replace(/-+/g, "-").toLowerCase();
35
34
  }
35
+ var standardDomEventPattern = /* @__PURE__ */ new RegExp("^on(click|dblclick|mousedown|mouseup|mouseover|mouseout|mousemove|mouseenter|mouseleave|keydown|keyup|keypress|focus|blur|change|input|submit|reset|load|unload|error|resize|scroll|touchstart|touchend|touchmove|touchcancel|pointerdown|pointerup|pointermove|pointerenter|pointerleave|pointercancel|drag|dragstart|dragend|dragenter|dragleave|dragover|drop|animationstart|animationend|animationiteration|transitionstart|transitionend|transitionrun|transitioncancel)$");
36
36
  function isStandardDomEvent(eventName) {
37
- const lowerEventName = eventName.toLowerCase();
38
- return [
39
- /^on(click|dblclick|mousedown|mouseup|mouseover|mouseout|mousemove|mouseenter|mouseleave)$/,
40
- /^on(keydown|keyup|keypress)$/,
41
- /^on(focus|blur|change|input|submit|reset)$/,
42
- /^on(load|unload|error|resize|scroll)$/,
43
- /^on(touchstart|touchend|touchmove|touchcancel)$/,
44
- /^on(pointerdown|pointerup|pointermove|pointerenter|pointerleave|pointercancel)$/,
45
- /^on(drag|dragstart|dragend|dragenter|dragleave|dragover|drop)$/,
46
- /^on(animationstart|animationend|animationiteration)$/,
47
- /^on(transitionstart|transitionend|transitionrun|transitioncancel)$/
48
- ].some((pattern) => pattern.test(lowerEventName));
37
+ return standardDomEventPattern.test(eventName.toLowerCase());
49
38
  }
50
39
  function onceChildrenRendered(element, callback) {
51
40
  if (element.children.length > 0) {
@@ -170,6 +159,27 @@ function cancelSnapshotAnimation(element) {
170
159
  activeSnapshotAnimations.delete(element);
171
160
  }
172
161
  }
162
+ function canBatchSnapshotMeasurements(elements) {
163
+ const targets = new Set(elements);
164
+ if (targets.size !== elements.length) return false;
165
+ const checkedAncestors = /* @__PURE__ */ new Set();
166
+ for (const element of elements) {
167
+ let ancestor = element;
168
+ while (ancestor) {
169
+ let parent = ancestor.assignedSlot ?? ancestor.parentElement;
170
+ if (!parent) {
171
+ const root = ancestor.getRootNode();
172
+ parent = typeof ShadowRoot !== "undefined" && root instanceof ShadowRoot ? root.host : null;
173
+ }
174
+ ancestor = parent;
175
+ if (!ancestor) break;
176
+ if (targets.has(ancestor)) return false;
177
+ if (checkedAncestors.has(ancestor)) break;
178
+ checkedAncestors.add(ancestor);
179
+ }
180
+ }
181
+ return true;
182
+ }
173
183
  /**
174
184
  * Capture current element rectangles before a renderer changes their order or
175
185
  * position. Pass the snapshot to animateFromSnapshot after the DOM has updated.
@@ -191,22 +201,29 @@ function animateFromSnapshot(snapshot, elements, options = {}) {
191
201
  ...options
192
202
  };
193
203
  const animations = [];
194
- for (const element of connectedElements(elements)) {
204
+ const targets = connectedElements(elements).filter((element) => snapshot.has(element));
205
+ const measure = (element) => {
195
206
  const before = snapshot.get(element);
196
- if (!before) continue;
197
207
  const after = element.getBoundingClientRect();
198
208
  const running = resolvedOptions.includeCurrentTransform ? currentTranslate(element) : {
199
209
  x: 0,
200
210
  y: 0
201
211
  };
202
- const deltaX = before.left - after.left + running.x;
203
- const deltaY = before.top - after.top + running.y;
212
+ return {
213
+ deltaX: before.left - after.left + running.x,
214
+ deltaY: before.top - after.top + running.y
215
+ };
216
+ };
217
+ const measurements = canBatchSnapshotMeasurements(targets) ? targets.map(measure) : null;
218
+ const animationOptions = resolveAnimationOptions(resolvedOptions);
219
+ for (const [index, element] of targets.entries()) {
220
+ const { deltaX, deltaY } = measurements?.[index] ?? measure(element);
204
221
  if (Math.abs(deltaX) < resolvedOptions.minimumDelta && Math.abs(deltaY) < resolvedOptions.minimumDelta) {
205
222
  cancelSnapshotAnimation(element);
206
223
  continue;
207
224
  }
208
225
  cancelSnapshotAnimation(element);
209
- const animation = element.animate([{ transform: `translate3d(${deltaX}px, ${deltaY}px, 0)` }, { transform: "translate3d(0, 0, 0)" }], resolveAnimationOptions(resolvedOptions));
226
+ const animation = element.animate([{ transform: `translate3d(${deltaX}px, ${deltaY}px, 0)` }, { transform: "translate3d(0, 0, 0)" }], animationOptions);
210
227
  activeSnapshotAnimations.set(element, animation);
211
228
  animations.push(animation);
212
229
  animation.finished.catch(() => animation).finally(() => {
@@ -215,6 +232,63 @@ function animateFromSnapshot(snapshot, elements, options = {}) {
215
232
  }
216
233
  return animations;
217
234
  }
235
+ function nextFrame(run) {
236
+ if (typeof requestAnimationFrame !== "function") return run();
237
+ const frame = requestAnimationFrame(() => run());
238
+ return () => cancelAnimationFrame(frame);
239
+ }
240
+ /**
241
+ * Animate layout changes a renderer makes after a snapshot, keeping track of
242
+ * scheduled and running moves so they can be interrupted.
243
+ */
244
+ function createLayoutAnimation(options = {}) {
245
+ const { schedule = nextFrame, ...animationOptions } = options;
246
+ const pending = /* @__PURE__ */ new Set();
247
+ const running = /* @__PURE__ */ new Set();
248
+ let cleaned = false;
249
+ function animate(snapshot, getElements, callbacks = {}) {
250
+ if (cleaned) return;
251
+ const scheduled = { dropped: false };
252
+ const run = () => {
253
+ if (scheduled.dropped || cleaned) return;
254
+ scheduled.dropped = true;
255
+ pending.delete(scheduled);
256
+ const animations = animateFromSnapshot(snapshot, getElements(), animationOptions);
257
+ animations.forEach((animation) => running.add(animation));
258
+ Promise.allSettled(animations.map((animation) => animation.finished)).then(() => {
259
+ animations.forEach((animation) => running.delete(animation));
260
+ if (!cleaned) callbacks.onSettle?.();
261
+ });
262
+ callbacks.onStart?.(animations);
263
+ };
264
+ pending.add(scheduled);
265
+ try {
266
+ scheduled.cancel = schedule(run);
267
+ } catch (error) {
268
+ scheduled.dropped = true;
269
+ pending.delete(scheduled);
270
+ throw error;
271
+ }
272
+ }
273
+ function cancel() {
274
+ for (const scheduled of pending) {
275
+ scheduled.dropped = true;
276
+ scheduled.cancel?.();
277
+ }
278
+ pending.clear();
279
+ Array.from(running).forEach((animation) => animation.cancel());
280
+ }
281
+ return {
282
+ animate,
283
+ cancel,
284
+ cleanup: () => {
285
+ if (!cleaned) {
286
+ cleaned = true;
287
+ cancel();
288
+ }
289
+ }
290
+ };
291
+ }
218
292
  //#endregion
219
293
  //#region src/dialog.ts
220
294
  var FOCUSABLE_SELECTORS = [
@@ -224,7 +298,7 @@ var FOCUSABLE_SELECTORS = [
224
298
  "input:not([disabled])",
225
299
  "select:not([disabled])",
226
300
  "[tabindex]:not([tabindex=\"-1\"])"
227
- ].join(", ");
301
+ ].map((selector) => `${selector}:not([aria-hidden="true"]):not(input[type="hidden"])`).join(", ");
228
302
  var scrollLockCount = 0;
229
303
  var originalOverflow = "";
230
304
  var originalPaddingRight = "";
@@ -237,8 +311,8 @@ function lockScroll() {
237
311
  originalOverflow = document.body.style.overflow;
238
312
  originalPaddingRight = document.body.style.paddingRight;
239
313
  originalScrollbarGutter = document.documentElement.style.getPropertyValue("scrollbar-gutter");
240
- const scrollbarWidth = window.innerWidth - document.documentElement.clientWidth;
241
314
  const canReserveScrollbarGutter = supportsScrollbarGutter();
315
+ const scrollbarWidth = canReserveScrollbarGutter ? 0 : window.innerWidth - document.documentElement.clientWidth;
242
316
  if (canReserveScrollbarGutter) document.documentElement.style.setProperty("scrollbar-gutter", "stable");
243
317
  document.body.style.overflow = "hidden";
244
318
  if (!canReserveScrollbarGutter && scrollbarWidth > 0) document.body.style.paddingRight = `${scrollbarWidth}px`;
@@ -260,9 +334,27 @@ function unlockScroll() {
260
334
  else document.documentElement.style.removeProperty("scrollbar-gutter");
261
335
  }
262
336
  }
263
- function getFocusableElements(container) {
264
- if (!container) return [];
265
- return Array.from(container.querySelectorAll(FOCUSABLE_SELECTORS)).filter((el) => el.getAttribute("aria-hidden") !== "true");
337
+ function getLastFocusableElement(container) {
338
+ let element = container.lastElementChild;
339
+ let descend = true;
340
+ for (let remaining = 32; element && remaining > 0; remaining--) {
341
+ if (descend && element.lastElementChild) {
342
+ element = element.lastElementChild;
343
+ continue;
344
+ }
345
+ if (element.matches(FOCUSABLE_SELECTORS)) return element;
346
+ if (element.previousElementSibling) {
347
+ element = element.previousElementSibling;
348
+ descend = true;
349
+ } else {
350
+ element = element.parentElement;
351
+ if (element === container) return null;
352
+ descend = false;
353
+ }
354
+ }
355
+ if (!element) return null;
356
+ const elements = container.querySelectorAll(FOCUSABLE_SELECTORS);
357
+ return elements[elements.length - 1] ?? null;
266
358
  }
267
359
  var focusTrapStack = [];
268
360
  var lastPointerDownTarget = null;
@@ -275,27 +367,31 @@ function trackPointerDown(event) {
275
367
  function handleTrapKeyDown(event) {
276
368
  if (event.key !== "Tab" || focusTrapStack.length === 0) return;
277
369
  const { container } = focusTrapStack[focusTrapStack.length - 1];
278
- const focusableElements = getFocusableElements(container);
279
- if (focusableElements.length === 0) return;
280
- const firstElement = focusableElements[0];
281
- const lastElement = focusableElements[focusableElements.length - 1];
282
- if (event.shiftKey) {
283
- if (document.activeElement === firstElement || !container.contains(document.activeElement)) {
370
+ const activeElement = document.activeElement;
371
+ const outside = !container.contains(activeElement);
372
+ if (!event.shiftKey && outside) {
373
+ const firstElement = container.querySelector(FOCUSABLE_SELECTORS);
374
+ if (firstElement) {
284
375
  event.preventDefault();
285
- lastElement.focus();
376
+ firstElement.focus();
286
377
  }
287
- } else if (document.activeElement === lastElement || !container.contains(document.activeElement)) {
378
+ return;
379
+ }
380
+ if (event.shiftKey && !outside && activeElement !== container.querySelector(FOCUSABLE_SELECTORS)) return;
381
+ const lastElement = getLastFocusableElement(container);
382
+ if (!lastElement) return;
383
+ if (event.shiftKey) {
288
384
  event.preventDefault();
289
- firstElement.focus();
385
+ lastElement.focus();
386
+ } else if (activeElement === lastElement) {
387
+ event.preventDefault();
388
+ container.querySelector(FOCUSABLE_SELECTORS)?.focus();
290
389
  }
291
390
  }
292
391
  function handleTrapFocusIn(event) {
293
392
  if (focusTrapStack.length === 0) return;
294
393
  const { container } = focusTrapStack[focusTrapStack.length - 1];
295
- if (!container.contains(event.target)) {
296
- const focusableElements = getFocusableElements(container);
297
- if (focusableElements.length > 0) focusableElements[0].focus({ preventScroll: true });
298
- }
394
+ if (!container.contains(event.target)) container.querySelector(FOCUSABLE_SELECTORS)?.focus({ preventScroll: true });
299
395
  }
300
396
  function createFocusTrap(container, options = {}) {
301
397
  const { initialFocus = true, initialFocusElement = null, returnFocus = true } = options;
@@ -311,21 +407,19 @@ function createFocusTrap(container, options = {}) {
311
407
  if (event.relatedTarget !== null) return;
312
408
  const pointerTarget = lastPointerDownTarget;
313
409
  queueMicrotask(() => {
410
+ if (cleaned || focusTrapStack[focusTrapStack.length - 1] !== entry) return;
314
411
  if (container.contains(container.ownerDocument.activeElement)) return;
315
412
  if (pointerTarget instanceof Node && container.contains(pointerTarget)) return;
316
- const focusableElements = getFocusableElements(container);
317
- if (focusableElements.length > 0) focusableElements[0].focus({ preventScroll: true });
413
+ container.querySelector(FOCUSABLE_SELECTORS)?.focus({ preventScroll: true });
318
414
  });
319
415
  }
320
416
  container.addEventListener("focusout", handleFocusOut);
321
417
  let rafId;
322
418
  if (initialFocus) rafId = requestAnimationFrame(() => {
323
419
  rafId = void 0;
420
+ if (focusTrapStack[focusTrapStack.length - 1] !== entry) return;
324
421
  if (initialFocusElement && container.contains(initialFocusElement)) initialFocusElement.focus();
325
- else {
326
- const focusableElements = getFocusableElements(container);
327
- if (focusableElements.length > 0) focusableElements[0].focus();
328
- }
422
+ else container.querySelector(FOCUSABLE_SELECTORS)?.focus();
329
423
  });
330
424
  let cleaned = false;
331
425
  return function cleanup() {
@@ -333,8 +427,11 @@ function createFocusTrap(container, options = {}) {
333
427
  cleaned = true;
334
428
  if (rafId !== void 0) cancelAnimationFrame(rafId);
335
429
  container.removeEventListener("focusout", handleFocusOut);
336
- const index = focusTrapStack.indexOf(entry);
337
- if (index >= 0) focusTrapStack.splice(index, 1);
430
+ if (focusTrapStack[focusTrapStack.length - 1] === entry) focusTrapStack.pop();
431
+ else {
432
+ const index = focusTrapStack.indexOf(entry);
433
+ if (index >= 0) focusTrapStack.splice(index, 1);
434
+ }
338
435
  if (focusTrapStack.length === 0) {
339
436
  document.removeEventListener("keydown", handleTrapKeyDown);
340
437
  document.removeEventListener("focusin", handleTrapFocusIn);
@@ -371,20 +468,19 @@ function onEscapeKey(callback, options = {}) {
371
468
  else document.removeEventListener("keydown", handler);
372
469
  };
373
470
  }
374
- var ariaHiddenStack = [];
375
- var inertStack = [];
471
+ var ariaHiddenStates = /* @__PURE__ */ new WeakMap();
472
+ var inertStates = /* @__PURE__ */ new WeakMap();
376
473
  function supportsNativeInert(element) {
377
474
  return "inert" in element;
378
475
  }
379
476
  function markAriaHidden(elementOrSelector) {
380
477
  const element = typeof elementOrSelector === "string" ? document.querySelector(elementOrSelector) : elementOrSelector;
381
478
  if (!element) return function noop() {};
382
- const existingIndex = ariaHiddenStack.findIndex((item) => item.element === element);
383
- if (existingIndex >= 0) ariaHiddenStack[existingIndex].count++;
479
+ const existing = ariaHiddenStates.get(element);
480
+ if (existing) existing.count++;
384
481
  else {
385
482
  const originalValue = element.getAttribute("aria-hidden");
386
- ariaHiddenStack.push({
387
- element,
483
+ ariaHiddenStates.set(element, {
388
484
  originalValue,
389
485
  count: 1
390
486
  });
@@ -398,33 +494,29 @@ function markAriaHidden(elementOrSelector) {
398
494
  };
399
495
  }
400
496
  function unmarkAriaHidden(element) {
401
- const index = ariaHiddenStack.findIndex((item) => item.element === element);
402
- if (index < 0) return;
403
- ariaHiddenStack[index].count--;
404
- if (ariaHiddenStack[index].count <= 0) {
405
- const { originalValue } = ariaHiddenStack[index];
497
+ const item = ariaHiddenStates.get(element);
498
+ if (!item) return;
499
+ item.count--;
500
+ if (item.count <= 0) {
501
+ const { originalValue } = item;
406
502
  if (originalValue === null) element.removeAttribute("aria-hidden");
407
503
  else element.setAttribute("aria-hidden", originalValue);
408
- ariaHiddenStack.splice(index, 1);
504
+ ariaHiddenStates.delete(element);
409
505
  }
410
506
  }
411
507
  function markInert(elementOrSelector) {
412
508
  const element = typeof elementOrSelector === "string" ? document.querySelector(elementOrSelector) : elementOrSelector;
413
509
  if (!element) return function noop() {};
414
- const existingIndex = inertStack.findIndex((item) => item.element === element);
415
- if (existingIndex >= 0) inertStack[existingIndex].count++;
510
+ if (!supportsNativeInert(element)) return markAriaHidden(element);
511
+ const existing = inertStates.get(element);
512
+ if (existing) existing.count++;
416
513
  else {
417
- const originalAriaHidden = element.getAttribute("aria-hidden");
418
- const hasNativeInert = supportsNativeInert(element);
419
- const originalInert = hasNativeInert ? element.inert : false;
420
- inertStack.push({
421
- element,
422
- originalAriaHidden,
514
+ const originalInert = element.inert;
515
+ inertStates.set(element, {
423
516
  originalInert,
424
517
  count: 1
425
518
  });
426
- if (hasNativeInert) element.inert = true;
427
- else element.setAttribute("aria-hidden", "true");
519
+ element.inert = true;
428
520
  }
429
521
  let cleaned = false;
430
522
  return function cleanup() {
@@ -434,15 +526,12 @@ function markInert(elementOrSelector) {
434
526
  };
435
527
  }
436
528
  function unmarkInert(element) {
437
- const index = inertStack.findIndex((item) => item.element === element);
438
- if (index < 0) return;
439
- inertStack[index].count--;
440
- if (inertStack[index].count <= 0) {
441
- const { originalAriaHidden, originalInert } = inertStack[index];
442
- if (supportsNativeInert(element)) element.inert = originalInert;
443
- if (originalAriaHidden === null) element.removeAttribute("aria-hidden");
444
- else element.setAttribute("aria-hidden", originalAriaHidden);
445
- inertStack.splice(index, 1);
529
+ const item = inertStates.get(element);
530
+ if (!item) return;
531
+ item.count--;
532
+ if (item.count <= 0) {
533
+ element.inert = item.originalInert;
534
+ inertStates.delete(element);
446
535
  }
447
536
  }
448
537
  //#endregion
@@ -454,10 +543,12 @@ function onClickOutside(elements, callback) {
454
543
  function handler(event) {
455
544
  const target = event.target;
456
545
  for (const el of targets) if (el.contains(target)) return;
457
- let node = target;
546
+ let node = target instanceof Element ? target : target?.parentElement;
458
547
  while (node) {
459
- if (node instanceof HTMLElement && node.hasAttribute("data-inertiaui-portal")) return;
460
- node = node.parentNode;
548
+ const portal = node.closest("[data-inertiaui-portal]");
549
+ if (!portal) break;
550
+ if (portal instanceof HTMLElement) return;
551
+ node = portal.parentElement;
461
552
  }
462
553
  callback(event);
463
554
  }
@@ -496,40 +587,42 @@ function createMenuNavigation(container, options = {}) {
496
587
  function getItems() {
497
588
  return Array.from(container.querySelectorAll(itemSelector));
498
589
  }
499
- function getActiveIndex() {
500
- const items = getItems();
590
+ function getActiveIndex(items) {
501
591
  const focused = document.activeElement;
502
592
  return items.indexOf(focused);
503
593
  }
504
- function focusItem(index) {
505
- const items = getItems();
594
+ function focusItem(index, items) {
506
595
  if (items.length === 0) return;
507
596
  const item = items[loop ? (index % items.length + items.length) % items.length : Math.max(0, Math.min(index, items.length - 1))];
508
- items.forEach((el) => el.setAttribute("tabindex", "-1"));
509
- item.setAttribute("tabindex", "0");
597
+ items.forEach((el) => {
598
+ const value = el === item ? "0" : "-1";
599
+ if (el.getAttribute("tabindex") !== value) el.setAttribute("tabindex", value);
600
+ });
510
601
  item.focus();
511
602
  }
512
603
  function handleKeyDown(event) {
513
- const items = getItems();
514
- if (items.length === 0) return;
515
604
  const nextKey = orientation === "vertical" ? "ArrowDown" : "ArrowRight";
516
605
  const prevKey = orientation === "vertical" ? "ArrowUp" : "ArrowLeft";
606
+ const typeAheadKey = typeAhead && event.key.length === 1 && !event.ctrlKey && !event.metaKey && !event.altKey;
607
+ if (event.key !== nextKey && event.key !== prevKey && event.key !== "Home" && event.key !== "End" && event.key !== "Enter" && event.key !== " " && !typeAheadKey) return;
608
+ const items = getItems();
609
+ if (items.length === 0) return;
517
610
  switch (event.key) {
518
611
  case nextKey:
519
612
  event.preventDefault();
520
- focusItem(getActiveIndex() + 1);
613
+ focusItem(getActiveIndex(items) + 1, items);
521
614
  break;
522
615
  case prevKey:
523
616
  event.preventDefault();
524
- focusItem(getActiveIndex() - 1);
617
+ focusItem(getActiveIndex(items) - 1, items);
525
618
  break;
526
619
  case "Home":
527
620
  event.preventDefault();
528
- focusItem(0);
621
+ focusItem(0, items);
529
622
  break;
530
623
  case "End":
531
624
  event.preventDefault();
532
- focusItem(items.length - 1);
625
+ focusItem(items.length - 1, items);
533
626
  break;
534
627
  case "Enter":
535
628
  case " ": {
@@ -542,7 +635,7 @@ function createMenuNavigation(container, options = {}) {
542
635
  break;
543
636
  }
544
637
  default:
545
- if (typeAhead && event.key.length === 1 && !event.ctrlKey && !event.metaKey && !event.altKey) {
638
+ if (typeAheadKey) {
546
639
  event.preventDefault();
547
640
  typeAheadBuffer += event.key.toLowerCase();
548
641
  if (typeAheadTimeout) clearTimeout(typeAheadTimeout);
@@ -552,7 +645,7 @@ function createMenuNavigation(container, options = {}) {
552
645
  const match = items.find((item) => {
553
646
  return (item.textContent || "").trim().toLowerCase().startsWith(typeAheadBuffer);
554
647
  });
555
- if (match) focusItem(items.indexOf(match));
648
+ if (match) focusItem(items.indexOf(match), items);
556
649
  }
557
650
  break;
558
651
  }
@@ -695,51 +788,81 @@ function moveArrayItem(items, fromIndex, toIndex) {
695
788
  return nextItems;
696
789
  }
697
790
  function identityOrder(length) {
698
- return Array.from({ length }, (_, index) => index);
791
+ const order = new Array(length);
792
+ for (let index = 0; index < length; index++) order[index] = index;
793
+ return order;
699
794
  }
700
795
  function isHTMLElement(value) {
701
796
  return typeof HTMLElement !== "undefined" && value instanceof HTMLElement;
702
797
  }
703
- function getValidReorderHitBoxes(hitBoxes) {
704
- return hitBoxes.filter((hitBox) => Number.isFinite(hitBox.index) && Number.isFinite(hitBox.left) && Number.isFinite(hitBox.top) && Number.isFinite(hitBox.right) && Number.isFinite(hitBox.bottom) && hitBox.left <= hitBox.right && hitBox.top <= hitBox.bottom);
705
- }
706
- function getOrderedReorderHitBoxes(hitBoxes) {
707
- return getValidReorderHitBoxes(hitBoxes).sort((first, second) => first.index - second.index);
798
+ function isMeasuredHitBox(hitBox) {
799
+ return Number.isFinite(hitBox.index) && Number.isFinite(hitBox.left) && Number.isFinite(hitBox.top) && Number.isFinite(hitBox.right) && Number.isFinite(hitBox.bottom) && hitBox.left <= hitBox.right && hitBox.top <= hitBox.bottom;
800
+ }
801
+ /** Move a point inside the area the measured items cover. */
802
+ function clampToHitBoxes(hitBoxes, point) {
803
+ let left = Infinity;
804
+ let top = Infinity;
805
+ let right = -Infinity;
806
+ let bottom = -Infinity;
807
+ for (const hitBox of hitBoxes) if (isMeasuredHitBox(hitBox)) {
808
+ left = Math.min(left, hitBox.left);
809
+ top = Math.min(top, hitBox.top);
810
+ right = Math.max(right, hitBox.right);
811
+ bottom = Math.max(bottom, hitBox.bottom);
812
+ }
813
+ return {
814
+ clientX: Math.min(Math.max(point.clientX, left), right),
815
+ clientY: Math.min(Math.max(point.clientY, top), bottom)
816
+ };
708
817
  }
709
818
  /**
710
- * Given the on-screen hit boxes of each item and a pointer position, resolve the
711
- * insertion index (0..count) the pointer currently maps to, or `null` when the
712
- * point falls outside the combined bounds. Handles both single-column (vertical
713
- * midpoint) and multi-item rows (horizontal midpoint) layouts.
819
+ * Resolve the insertion index for vertical lists and multi-item rows. Select
820
+ * the first matching item by index (or left edge within a row) in one pass,
821
+ * without sorting or allocating temporary arrays on every pointer move.
714
822
  */
715
823
  function getInsertionIndexFromPoint(hitBoxes, point, options = {}) {
716
- const orderedHitBoxes = getOrderedReorderHitBoxes(hitBoxes);
717
- if (orderedHitBoxes.length === 0) return null;
718
- const left = Math.min(...orderedHitBoxes.map((hitBox) => hitBox.left));
719
- const top = Math.min(...orderedHitBoxes.map((hitBox) => hitBox.top));
720
- const right = Math.max(...orderedHitBoxes.map((hitBox) => hitBox.right));
721
- const bottom = Math.max(...orderedHitBoxes.map((hitBox) => hitBox.bottom));
722
- const bounds = options.bounds;
723
- const activeLeft = bounds ? Math.min(left, bounds.left) : left;
724
- const activeTop = bounds ? Math.min(top, bounds.top) : top;
725
- const activeRight = bounds ? Math.max(right, bounds.right) : right;
726
- const activeBottom = bounds ? Math.max(bottom, bounds.bottom) : bottom;
727
- if (point.clientX < activeLeft || point.clientX > activeRight || point.clientY < activeTop || point.clientY > activeBottom) return null;
728
- if (point.clientY < top) return orderedHitBoxes[0].index;
729
- if (point.clientY > bottom) return orderedHitBoxes[orderedHitBoxes.length - 1].index + 1;
730
- const hitBoxesOnCurrentRow = orderedHitBoxes.filter((hitBox) => point.clientY >= hitBox.top && point.clientY <= hitBox.bottom).sort((first, second) => first.left - second.left || first.index - second.index);
731
- if (hitBoxesOnCurrentRow.length > 1) {
732
- for (const hitBox of hitBoxesOnCurrentRow) {
733
- const midpoint = hitBox.left + (hitBox.right - hitBox.left) / 2;
734
- if (point.clientX <= midpoint) return hitBox.index;
824
+ let left = Infinity;
825
+ let top = Infinity;
826
+ let right = -Infinity;
827
+ let bottom = -Infinity;
828
+ let firstIndex = Infinity;
829
+ let lastIndex = -Infinity;
830
+ let verticalIndex = Infinity;
831
+ let rowCount = 0;
832
+ let rowMatch = null;
833
+ let rowLast = null;
834
+ let rowMatchStart = 0;
835
+ let rowLastStart = 0;
836
+ const reading = options.rightToLeft ? -1 : 1;
837
+ for (const hitBox of hitBoxes) {
838
+ if (!isMeasuredHitBox(hitBox)) continue;
839
+ left = Math.min(left, hitBox.left);
840
+ top = Math.min(top, hitBox.top);
841
+ right = Math.max(right, hitBox.right);
842
+ bottom = Math.max(bottom, hitBox.bottom);
843
+ firstIndex = Math.min(firstIndex, hitBox.index);
844
+ lastIndex = Math.max(lastIndex, hitBox.index);
845
+ if (point.clientY <= hitBox.top + (hitBox.bottom - hitBox.top) / 2) verticalIndex = Math.min(verticalIndex, hitBox.index);
846
+ if (point.clientY >= hitBox.top && point.clientY <= hitBox.bottom) {
847
+ rowCount++;
848
+ const start = options.rightToLeft ? -hitBox.right : hitBox.left;
849
+ if (!rowLast || start > rowLastStart || start === rowLastStart && hitBox.index > rowLast.index) {
850
+ rowLast = hitBox;
851
+ rowLastStart = start;
852
+ }
853
+ if (reading * point.clientX <= reading * (hitBox.left + (hitBox.right - hitBox.left) / 2) && (!rowMatch || start < rowMatchStart || start === rowMatchStart && hitBox.index < rowMatch.index)) {
854
+ rowMatch = hitBox;
855
+ rowMatchStart = start;
856
+ }
735
857
  }
736
- return hitBoxesOnCurrentRow[hitBoxesOnCurrentRow.length - 1].index + 1;
737
858
  }
738
- for (const hitBox of orderedHitBoxes) {
739
- const midpoint = hitBox.top + (hitBox.bottom - hitBox.top) / 2;
740
- if (point.clientY <= midpoint) return hitBox.index;
741
- }
742
- return orderedHitBoxes[orderedHitBoxes.length - 1].index + 1;
859
+ if (firstIndex === Infinity) return null;
860
+ const bounds = options.bounds;
861
+ if (point.clientX < (bounds ? Math.min(left, bounds.left) : left) || point.clientX > (bounds ? Math.max(right, bounds.right) : right) || point.clientY < (bounds ? Math.min(top, bounds.top) : top) || point.clientY > (bounds ? Math.max(bottom, bounds.bottom) : bottom)) return null;
862
+ if (point.clientY < top) return firstIndex;
863
+ if (point.clientY > bottom) return lastIndex + 1;
864
+ if (rowCount > 1) return rowMatch ? rowMatch.index : rowLast.index + 1;
865
+ return verticalIndex === Infinity ? lastIndex + 1 : verticalIndex;
743
866
  }
744
867
  /**
745
868
  * Convert an insertion index (0..count) into the destination array index for the
@@ -754,6 +877,43 @@ function resolveTargetIndexFromInsertion(fromIndex, insertionIndex, itemCount) {
754
877
  if (targetIndex < 0 || targetIndex >= itemCount) return null;
755
878
  return targetIndex;
756
879
  }
880
+ function isPermutation(order, count) {
881
+ if (order.length !== count) return false;
882
+ const seen = new Uint8Array(count);
883
+ for (const index of order) {
884
+ if (!Number.isInteger(index) || index < 0 || index >= count || seen[index]) return false;
885
+ seen[index] = 1;
886
+ }
887
+ return true;
888
+ }
889
+ /**
890
+ * Return how far each item moves along the axis when the items are laid out in
891
+ * `order`, a permutation of their indices. The offsets describe the movement
892
+ * between the items packed in their current order and packed in `order`, so items
893
+ * of different sizes line up and an unchanged order returns zero offsets. Each gap
894
+ * between neighboring slots stays in place, or is `gap` in both layouts when
895
+ * given. An order that is not a permutation of the items leaves every item where
896
+ * it is.
897
+ */
898
+ function getReorderOffsets(rects, order, options = {}) {
899
+ const offsets = rects.map(() => 0);
900
+ if (rects.length === 0 || !isPermutation(order, rects.length)) return offsets;
901
+ const [start, end] = options.axis === "x" ? ["left", "right"] : ["top", "bottom"];
902
+ const [leading, trailing] = options.reverse ? [end, start] : [start, end];
903
+ const direction = options.reverse ? -1 : 1;
904
+ let original = 0;
905
+ let target = 0;
906
+ for (const [slot, index] of order.entries()) {
907
+ const rect = rects[slot];
908
+ const next = rects[slot + 1];
909
+ const signedGap = next ? options.gap === void 0 ? next[leading] - rect[trailing] : direction * options.gap : 0;
910
+ offsets[index] += target;
911
+ offsets[slot] -= original;
912
+ target += direction * (rects[index][end] - rects[index][start]) + signedGap;
913
+ original += direction * (rect[end] - rect[start]) + signedGap;
914
+ }
915
+ return offsets;
916
+ }
757
917
  /**
758
918
  * Return true when the event target is a reorder handle carrying
759
919
  * `REORDERABLE_LIST_HANDLE_ATTRIBUTE="true"`.
@@ -765,6 +925,7 @@ function isShadowRoot(value) {
765
925
  return typeof ShadowRoot !== "undefined" && value instanceof ShadowRoot;
766
926
  }
767
927
  function getParentNodeAcrossShadowDom(node) {
928
+ if (node instanceof Element && node.assignedSlot) return node.assignedSlot;
768
929
  if (node.parentNode) return node.parentNode;
769
930
  const root = node.getRootNode?.();
770
931
  return isShadowRoot(root) ? root.host : null;
@@ -803,10 +964,10 @@ function finiteNumber(value, fallback) {
803
964
  function canOverflow(value) {
804
965
  return value === "auto" || value === "scroll" || value === "overlay";
805
966
  }
806
- function isScrollableElement(element) {
967
+ function isScrollableElement(element, axis) {
807
968
  const style = getComputedStyle(element);
808
- const canScrollY = canOverflow(style.overflowY) && element.scrollHeight > element.clientHeight;
809
- const canScrollX = canOverflow(style.overflowX) && element.scrollWidth > element.clientWidth;
969
+ const canScrollY = axis !== "x" && canOverflow(style.overflowY) && element.scrollHeight > element.clientHeight;
970
+ const canScrollX = axis !== "y" && canOverflow(style.overflowX) && element.scrollWidth > element.clientWidth;
810
971
  return canScrollY || canScrollX;
811
972
  }
812
973
  function getOwnerWindow(element) {
@@ -816,13 +977,18 @@ function getOwnerWindow(element) {
816
977
  function isWindowContainer(container) {
817
978
  return typeof Window !== "undefined" && container instanceof Window;
818
979
  }
819
- function getScrollableAncestors(element) {
980
+ /**
981
+ * Ancestors of `element` that can scroll, nearest first, followed by its window.
982
+ * Pass an axis to keep only the ancestors that scroll along it. Shadow roots are
983
+ * crossed through their hosts.
984
+ */
985
+ function getScrollableAncestors(element, axis = "both") {
820
986
  const containers = [];
821
987
  const ownerWindow = getOwnerWindow(element);
822
988
  let node = element;
823
989
  while (node) {
824
990
  node = getParentNodeAcrossShadowDom(node);
825
- if (node instanceof Element && isScrollableElement(node)) containers.push(node);
991
+ if (node instanceof Element && isScrollableElement(node, axis)) containers.push(node);
826
992
  }
827
993
  if (ownerWindow) containers.push(ownerWindow);
828
994
  return containers;
@@ -843,6 +1009,36 @@ function getScrollPosition(container, axis) {
843
1009
  if (isWindowContainer(container)) return axis === "x" ? container.scrollX : container.scrollY;
844
1010
  return axis === "x" ? container.scrollLeft : container.scrollTop;
845
1011
  }
1012
+ /** Keep initial geometry independent of preview transforms, translating only ancestor scroll displacement. */
1013
+ function createScrollAdjustedHitBox(hitBox, element) {
1014
+ const containers = [];
1015
+ const ownerWindow = getOwnerWindow(element);
1016
+ const scrollElement = ownerWindow ? getScrollElement(ownerWindow) : null;
1017
+ const windowLeft = ownerWindow?.scrollX ?? 0;
1018
+ const windowTop = ownerWindow?.scrollY ?? 0;
1019
+ let node = element;
1020
+ while (node = getParentNodeAcrossShadowDom(node)) if (node instanceof Element && node !== scrollElement) containers.push(node);
1021
+ const positions = containers.map((container) => ({
1022
+ container,
1023
+ left: container.scrollLeft,
1024
+ top: container.scrollTop
1025
+ }));
1026
+ return () => {
1027
+ let left = (ownerWindow?.scrollX ?? 0) - windowLeft;
1028
+ let top = (ownerWindow?.scrollY ?? 0) - windowTop;
1029
+ for (const position of positions) {
1030
+ left += position.container.scrollLeft - position.left;
1031
+ top += position.container.scrollTop - position.top;
1032
+ }
1033
+ return {
1034
+ index: hitBox.index,
1035
+ left: hitBox.left - left,
1036
+ top: hitBox.top - top,
1037
+ right: hitBox.right - left,
1038
+ bottom: hitBox.bottom - top
1039
+ };
1040
+ };
1041
+ }
846
1042
  function getMaxScrollPosition(container, axis) {
847
1043
  if (isWindowContainer(container)) {
848
1044
  const scrollElement = getScrollElement(container);
@@ -851,9 +1047,14 @@ function getMaxScrollPosition(container, axis) {
851
1047
  }
852
1048
  return Math.max(0, axis === "x" ? container.scrollWidth - container.clientWidth : container.scrollHeight - container.clientHeight);
853
1049
  }
854
- function canScroll(container, axis, direction) {
1050
+ function scrollsRightToLeft(container) {
1051
+ const element = isWindowContainer(container) ? getScrollElement(container) : container;
1052
+ return element !== null && getComputedStyle(element).direction === "rtl";
1053
+ }
1054
+ function canScroll(container, axis, direction, isRightToLeft) {
855
1055
  const position = getScrollPosition(container, axis);
856
1056
  const maxPosition = getMaxScrollPosition(container, axis);
1057
+ if (axis === "x" && isRightToLeft(container)) return direction < 0 ? position > -maxPosition : position < 0;
857
1058
  return direction < 0 ? position > 0 : position < maxPosition;
858
1059
  }
859
1060
  function edgeIntensity(position, start, end, threshold) {
@@ -864,7 +1065,7 @@ function edgeIntensity(position, start, end, threshold) {
864
1065
  const endIntensity = endDistance < threshold ? (threshold - endDistance) / threshold : 0;
865
1066
  return endIntensity > startIntensity ? endIntensity : -startIntensity;
866
1067
  }
867
- function getAutoScrollVector(container, point, edgeThreshold, maxStep) {
1068
+ function getAutoScrollVector(container, point, edgeThreshold, maxStep, isRightToLeft) {
868
1069
  const rect = getContainerRect(container);
869
1070
  const width = rect.right - rect.left;
870
1071
  const height = rect.bottom - rect.top;
@@ -873,8 +1074,8 @@ function getAutoScrollVector(container, point, edgeThreshold, maxStep) {
873
1074
  const xIntensity = edgeIntensity(point.clientX, rect.left, rect.right, xThreshold);
874
1075
  const yIntensity = edgeIntensity(point.clientY, rect.top, rect.bottom, yThreshold);
875
1076
  return {
876
- left: xIntensity !== 0 && canScroll(container, "x", xIntensity) ? xIntensity * maxStep : 0,
877
- top: yIntensity !== 0 && canScroll(container, "y", yIntensity) ? yIntensity * maxStep : 0
1077
+ left: xIntensity !== 0 && canScroll(container, "x", xIntensity, isRightToLeft) ? xIntensity * maxStep : 0,
1078
+ top: yIntensity !== 0 && canScroll(container, "y", yIntensity, isRightToLeft) ? yIntensity * maxStep : 0
878
1079
  };
879
1080
  }
880
1081
  function scrollContainer(container, left, top) {
@@ -907,10 +1108,19 @@ function createAutoScroller(options = {}) {
907
1108
  let frameId = null;
908
1109
  let lastTimestamp = null;
909
1110
  let cleaned = false;
1111
+ const rightToLeft = /* @__PURE__ */ new Map();
910
1112
  function queueFrame() {
911
1113
  if (cleaned || frameId !== null || typeof requestAnimationFrame !== "function") return;
912
1114
  frameId = requestAnimationFrame(step);
913
1115
  }
1116
+ function readsRightToLeft(container) {
1117
+ let value = rightToLeft.get(container);
1118
+ if (value === void 0) {
1119
+ value = scrollsRightToLeft(container);
1120
+ rightToLeft.set(container, value);
1121
+ }
1122
+ return value;
1123
+ }
914
1124
  function stop() {
915
1125
  if (frameId !== null && typeof cancelAnimationFrame === "function") cancelAnimationFrame(frameId);
916
1126
  latestPoint = null;
@@ -918,6 +1128,7 @@ function createAutoScroller(options = {}) {
918
1128
  containers = [];
919
1129
  frameId = null;
920
1130
  lastTimestamp = null;
1131
+ rightToLeft.clear();
921
1132
  }
922
1133
  function step(timestamp) {
923
1134
  frameId = null;
@@ -928,7 +1139,7 @@ function createAutoScroller(options = {}) {
928
1139
  let handledY = axis === "x";
929
1140
  lastTimestamp = timestamp;
930
1141
  for (const container of containers) {
931
- const vector = getAutoScrollVector(container, latestPoint, edgeThreshold, maxStep);
1142
+ const vector = getAutoScrollVector(container, latestPoint, edgeThreshold, maxStep, readsRightToLeft);
932
1143
  const left = handledX ? 0 : vector.left;
933
1144
  const top = handledY ? 0 : vector.top;
934
1145
  if (left === 0 && top === 0) continue;
@@ -963,8 +1174,7 @@ function createAutoScroller(options = {}) {
963
1174
  return {
964
1175
  update,
965
1176
  stop,
966
- cleanup,
967
- isScrolling: () => frameId !== null
1177
+ cleanup
968
1178
  };
969
1179
  }
970
1180
  var idleState = {
@@ -985,6 +1195,9 @@ function defaultReorderableListBounds(element) {
985
1195
  function getRegisteredItemElements(itemElements) {
986
1196
  return Array.from(itemElements.entries()).sort(([firstIndex], [secondIndex]) => firstIndex - secondIndex).map(([, element]) => element);
987
1197
  }
1198
+ function isValidReorderIndex(index, itemCount) {
1199
+ return Number.isInteger(index) && index >= 0 && index < itemCount;
1200
+ }
988
1201
  /**
989
1202
  * Framework-neutral list reorder controller. It combines item registration,
990
1203
  * live pointer preview ordering, keyboard moves, pointer commits, bounds, and
@@ -995,6 +1208,7 @@ function createReorderableList(options) {
995
1208
  let listElement = null;
996
1209
  let pointerState = idleState;
997
1210
  let dragHitBoxes = null;
1211
+ let dragRightToLeft = false;
998
1212
  let lastPreviewedPointerTargetIndex = null;
999
1213
  const itemElements = /* @__PURE__ */ new Map();
1000
1214
  const itemCount = () => options.getItems().length;
@@ -1014,10 +1228,10 @@ function createReorderableList(options) {
1014
1228
  };
1015
1229
  }).filter((hitBox) => hitBox !== null);
1016
1230
  };
1017
- const getHitBoxes = () => dragHitBoxes ?? measureItemHitBoxes();
1231
+ const getHitBoxes = () => dragHitBoxes?.map((getHitBox) => getHitBox()) ?? measureItemHitBoxes();
1018
1232
  const commitReorder = (fromIndex, toIndex, source, context) => {
1019
1233
  const items = options.getItems();
1020
- if (!canReorder() || fromIndex === toIndex || fromIndex < 0 || toIndex < 0 || fromIndex >= items.length || toIndex >= items.length) return null;
1234
+ if (!canReorder() || fromIndex === toIndex || !isValidReorderIndex(fromIndex, items.length) || !isValidReorderIndex(toIndex, items.length)) return null;
1021
1235
  const move = {
1022
1236
  item: items[fromIndex],
1023
1237
  fromIndex,
@@ -1030,11 +1244,20 @@ function createReorderableList(options) {
1030
1244
  return move;
1031
1245
  };
1032
1246
  const pointerReorder = createPointerReorder({
1247
+ onStart: () => {
1248
+ dragHitBoxes = measureItemHitBoxes().map((hitBox) => createScrollAdjustedHitBox(hitBox, itemElements.get(hitBox.index)));
1249
+ const element = listElement ?? itemElements.values().next().value;
1250
+ dragRightToLeft = !!element && getComputedStyle(element).direction === "rtl";
1251
+ },
1252
+ isRightToLeft: () => dragRightToLeft,
1033
1253
  getItemCount: itemCount,
1034
1254
  getHitBoxes,
1035
1255
  getBounds,
1036
1256
  canReorder,
1037
1257
  autoScroll: options.autoScroll ?? false,
1258
+ activationDistance: options.activationDistance,
1259
+ suppressClickAfterDrag: options.suppressClickAfterDrag,
1260
+ getCollisionPoint: options.getCollisionPoint,
1038
1261
  onChange: (state) => {
1039
1262
  if (state.draggedIndex !== null) lastPreviewedPointerTargetIndex = state.targetIndex;
1040
1263
  pointerState = state;
@@ -1077,11 +1300,9 @@ function createReorderableList(options) {
1077
1300
  moveItem: (index, direction) => {
1078
1301
  return commitReorder(index, direction === "up" ? index - 1 : index + 1, "keyboard", { alreadyPreviewed: false });
1079
1302
  },
1080
- pointerDown: (index, event) => {
1081
- dragHitBoxes = measureItemHitBoxes();
1082
- pointerReorder.pointerDown(index, event);
1083
- if (!event.defaultPrevented) dragHitBoxes = null;
1084
- },
1303
+ pointerDown: pointerReorder.pointerDown,
1304
+ getPointer: pointerReorder.getPointer,
1305
+ cancel: pointerReorder.cancel,
1085
1306
  cleanup: () => {
1086
1307
  pointerReorder.cleanup();
1087
1308
  dragHitBoxes = null;
@@ -1099,10 +1320,13 @@ function createReorderableList(options) {
1099
1320
  function createPointerReorder(options) {
1100
1321
  const canReorder = () => (options.canReorder?.() ?? true) && options.getItemCount() > 1;
1101
1322
  let activePointer = null;
1323
+ let pendingPointer = null;
1324
+ let pointer = null;
1102
1325
  let insertionIndex = null;
1103
1326
  let pointerOverReorderArea = false;
1104
1327
  let lastPoint = null;
1105
1328
  let cleaned = false;
1329
+ const activationDistance = finiteNumber(options.activationDistance, 0);
1106
1330
  const autoScrollOptions = options.autoScroll === true ? {} : options.autoScroll || null;
1107
1331
  const autoScroller = autoScrollOptions ? createAutoScroller({
1108
1332
  ...autoScrollOptions,
@@ -1125,18 +1349,32 @@ function createPointerReorder(options) {
1125
1349
  options.onChange?.(currentState());
1126
1350
  }
1127
1351
  function updateInsertionIndex(point) {
1128
- const nextInsertionIndex = getInsertionIndexFromPoint(options.getHitBoxes(), {
1352
+ const hitBoxes = options.getHitBoxes();
1353
+ const nextInsertionIndex = getInsertionIndexFromPoint(hitBoxes, {
1129
1354
  clientX: point.clientX,
1130
1355
  clientY: point.clientY
1131
- }, { bounds: options.getBounds?.() ?? null });
1356
+ }, {
1357
+ bounds: options.getBounds?.() ?? null,
1358
+ rightToLeft: options.isRightToLeft?.()
1359
+ });
1132
1360
  pointerOverReorderArea = nextInsertionIndex !== null;
1133
- if (nextInsertionIndex !== null) insertionIndex = nextInsertionIndex;
1361
+ if (nextInsertionIndex !== null) insertionIndex = getCollisionInsertionIndex(hitBoxes) ?? nextInsertionIndex;
1362
+ }
1363
+ /** The insertion index at the caller's collision point, or null to use the pointer. */
1364
+ function getCollisionInsertionIndex(hitBoxes) {
1365
+ const getCollisionPoint = options.getCollisionPoint;
1366
+ if (!getCollisionPoint || !activePointer || !pointer) return null;
1367
+ const item = activePointer.initialItemBounds;
1368
+ const point = item ? getCollisionPoint(pointer, item) : null;
1369
+ if (!point || !Number.isFinite(point.clientX) || !Number.isFinite(point.clientY)) return null;
1370
+ return getInsertionIndexFromPoint(hitBoxes, clampToHitBoxes(hitBoxes, point), { rightToLeft: options.isRightToLeft?.() });
1134
1371
  }
1135
1372
  function updatePointerPosition(event, shouldAutoScroll) {
1136
1373
  lastPoint = {
1137
1374
  clientX: event.clientX,
1138
1375
  clientY: event.clientY
1139
1376
  };
1377
+ if (pointer) pointer.position = lastPoint;
1140
1378
  updateInsertionIndex(lastPoint);
1141
1379
  if (shouldAutoScroll) autoScroller?.update(lastPoint, activePointer?.scrollElement ?? activePointer?.captureElement ?? null);
1142
1380
  }
@@ -1146,7 +1384,10 @@ function createPointerReorder(options) {
1146
1384
  window.removeEventListener("pointermove", handleWindowPointerMove);
1147
1385
  window.removeEventListener("pointerup", handleWindowPointerUp);
1148
1386
  window.removeEventListener("pointercancel", handleWindowPointerCancel);
1387
+ window.removeEventListener("blur", cancel);
1149
1388
  activePointer = null;
1389
+ pendingPointer = null;
1390
+ pointer = null;
1150
1391
  insertionIndex = null;
1151
1392
  pointerOverReorderArea = false;
1152
1393
  lastPoint = null;
@@ -1159,26 +1400,58 @@ function createPointerReorder(options) {
1159
1400
  } catch {}
1160
1401
  }
1161
1402
  function handleWindowPointerMove(event) {
1403
+ const pending = pendingPointer;
1404
+ if (pending?.pointerId === event.pointerId && pointer) {
1405
+ if (Math.hypot(event.clientX - pointer.origin.clientX, event.clientY - pointer.origin.clientY) < activationDistance) return;
1406
+ pendingPointer = null;
1407
+ if (!canReorder() || !isValidReorderIndex(pending.fromIndex, options.getItemCount())) {
1408
+ stop();
1409
+ return;
1410
+ }
1411
+ activate(pending.fromIndex, event, pending.handle);
1412
+ }
1162
1413
  if (activePointer?.pointerId !== event.pointerId) return;
1163
1414
  event.preventDefault();
1164
1415
  updatePointerPosition(event, true);
1165
1416
  emitChange();
1166
1417
  }
1167
1418
  function handleWindowPointerUp(event) {
1168
- const pointer = activePointer;
1169
- if (!pointer || pointer.pointerId !== event.pointerId) return;
1419
+ if (pendingPointer?.pointerId === event.pointerId) {
1420
+ stop();
1421
+ return;
1422
+ }
1423
+ const active = activePointer;
1424
+ if (!active || active.pointerId !== event.pointerId) return;
1170
1425
  event.preventDefault();
1171
- const fromIndex = pointer.fromIndex;
1426
+ const fromIndex = active.fromIndex;
1172
1427
  const toIndex = pointerOverReorderArea ? resolveTargetIndexFromInsertion(fromIndex, insertionIndex, options.getItemCount()) : null;
1173
- stop();
1174
- emitChange();
1428
+ end();
1175
1429
  if (toIndex !== null && fromIndex !== toIndex) options.onCommit(fromIndex, toIndex, "pointer");
1176
1430
  }
1177
1431
  function handleWindowPointerCancel(event) {
1178
- if (activePointer?.pointerId !== event.pointerId) return;
1432
+ if (pendingPointer?.pointerId === event.pointerId) stop();
1433
+ else if (activePointer?.pointerId === event.pointerId) end(false);
1434
+ }
1435
+ /** Stop an active drag and report the idle state, keeping its click from activating whatever is under the pointer. */
1436
+ function end(suppressFollowingClick = options.suppressClickAfterDrag ?? false) {
1179
1437
  stop();
1438
+ if (suppressFollowingClick) {
1439
+ window.addEventListener("click", suppressClick, { capture: true });
1440
+ window.addEventListener("pointerdown", releaseClick, { capture: true });
1441
+ window.addEventListener("keydown", releaseClick, { capture: true });
1442
+ }
1180
1443
  emitChange();
1181
1444
  }
1445
+ function suppressClick(event) {
1446
+ event.preventDefault();
1447
+ event.stopPropagation();
1448
+ releaseClick();
1449
+ }
1450
+ function releaseClick() {
1451
+ window.removeEventListener("click", suppressClick, { capture: true });
1452
+ window.removeEventListener("pointerdown", releaseClick, { capture: true });
1453
+ window.removeEventListener("keydown", releaseClick, { capture: true });
1454
+ }
1182
1455
  function bindPointerCapture(element, pointerId) {
1183
1456
  if (typeof element.setPointerCapture !== "function") return null;
1184
1457
  try {
@@ -1190,32 +1463,60 @@ function createPointerReorder(options) {
1190
1463
  }
1191
1464
  function pointerDown(index, event) {
1192
1465
  const handle = findReorderHandle(event);
1193
- if (cleaned || !canReorder() || activePointer || event.button !== 0 || event.isPrimary === false || !handle) return;
1466
+ if (cleaned || !canReorder() || !isValidReorderIndex(index, options.getItemCount()) || activePointer || pendingPointer || event.button !== 0 || event.isPrimary === false || !handle) return;
1467
+ const origin = {
1468
+ clientX: event.clientX,
1469
+ clientY: event.clientY
1470
+ };
1471
+ pointer = {
1472
+ origin,
1473
+ position: origin
1474
+ };
1475
+ window.addEventListener("pointermove", handleWindowPointerMove, { passive: false });
1476
+ window.addEventListener("pointerup", handleWindowPointerUp);
1477
+ window.addEventListener("pointercancel", handleWindowPointerCancel);
1478
+ window.addEventListener("blur", cancel);
1479
+ if (activationDistance > 0) {
1480
+ pendingPointer = {
1481
+ fromIndex: index,
1482
+ pointerId: event.pointerId,
1483
+ handle
1484
+ };
1485
+ return;
1486
+ }
1487
+ activate(index, event, handle);
1488
+ emitChange();
1489
+ }
1490
+ /** Turn an accepted press into a drag: measure, claim the pointer, and stop native defaults. */
1491
+ function activate(fromIndex, event, handle) {
1492
+ options.onStart();
1194
1493
  event.preventDefault();
1195
1494
  const captureElement = bindPointerCapture(handle, event.pointerId);
1196
1495
  activePointer = {
1197
- fromIndex: index,
1496
+ fromIndex,
1198
1497
  pointerId: event.pointerId,
1199
1498
  captureElement,
1200
- scrollElement: handle
1499
+ scrollElement: handle,
1500
+ initialItemBounds: options.getHitBoxes().find((hitBox) => hitBox.index === fromIndex) ?? null
1201
1501
  };
1202
- insertionIndex = index;
1502
+ insertionIndex = fromIndex;
1203
1503
  pointerOverReorderArea = true;
1204
- window.addEventListener("pointermove", handleWindowPointerMove, { passive: false });
1205
- window.addEventListener("pointerup", handleWindowPointerUp);
1206
- window.addEventListener("pointercancel", handleWindowPointerCancel);
1207
- emitChange();
1504
+ }
1505
+ function cancel() {
1506
+ if (activePointer) end();
1507
+ else if (pendingPointer) stop();
1208
1508
  }
1209
1509
  function cleanup() {
1210
1510
  if (cleaned) return;
1211
1511
  cleaned = true;
1212
1512
  stop();
1513
+ releaseClick();
1213
1514
  autoScroller?.cleanup();
1214
1515
  }
1215
1516
  return {
1216
1517
  pointerDown,
1217
- getState: currentState,
1218
- isDragging: () => activePointer !== null,
1518
+ getPointer: () => activePointer ? pointer : null,
1519
+ cancel,
1219
1520
  cleanup
1220
1521
  };
1221
1522
  }
@@ -1234,190 +1535,14 @@ function focusFirstEnabledElement(elements, options) {
1234
1535
  return false;
1235
1536
  }
1236
1537
  //#endregion
1237
- //#region src/position/style.ts
1238
- function setStyleProperty(style, property, value) {
1239
- if (style.getPropertyValue(property) !== value) style.setProperty(property, value);
1240
- }
1241
- function removeStyleProperty(style, property) {
1242
- if (style.getPropertyValue(property) !== "") style.removeProperty(property);
1243
- }
1244
- function captureStyleProperty(style, property) {
1245
- return {
1246
- value: style.getPropertyValue(property),
1247
- priority: style.getPropertyPriority(property)
1248
- };
1249
- }
1250
- function restoreStyleProperty(style, property, stored) {
1251
- if (stored.value === "") {
1252
- removeStyleProperty(style, property);
1253
- return;
1254
- }
1255
- style.setProperty(property, stored.value, stored.priority);
1256
- }
1257
- //#endregion
1258
- //#region src/position/anchor.ts
1259
- var ANCHOR_CLASS_PREFIX = "iui-anchor-";
1260
- var _supportsAnchor = null;
1261
- var _supportsAnchorFlip = null;
1262
- var _supportsTopLayerAnchor = null;
1263
- var _supportsTopLayerAnchorSizing = null;
1264
- var _isWebKit = null;
1265
- function supportsAnchorPositioning() {
1266
- if (_supportsAnchor === null) _supportsAnchor = typeof CSS !== "undefined" && typeof CSS.supports === "function" && CSS.supports("anchor-name", "--a") && CSS.supports("position-anchor", "--a") && CSS.supports("top", "anchor(bottom)");
1267
- return _supportsAnchor;
1268
- }
1269
- function supportsTopLayerAnchorPositioning() {
1270
- if (_supportsTopLayerAnchor === null) _supportsTopLayerAnchor = supportsAnchorPositioning() && CSS.supports("width", "anchor-size(width)") && !isWebKit();
1271
- return _supportsTopLayerAnchor;
1272
- }
1273
- function isWebKit() {
1274
- if (_isWebKit === null) _isWebKit = typeof CSS !== "undefined" && typeof CSS.supports === "function" && CSS.supports("-webkit-backdrop-filter", "none");
1275
- return _isWebKit;
1276
- }
1277
- function supportsAnchorFlip() {
1278
- if (_supportsAnchorFlip === null) _supportsAnchorFlip = supportsAnchorPositioning() && (CSS.supports("position-try-fallbacks", "flip-block") || CSS.supports("position-try", "flip-block"));
1279
- return _supportsAnchorFlip;
1280
- }
1281
- function supportsTopLayerAnchorSizing() {
1282
- if (_supportsTopLayerAnchorSizing === null) _supportsTopLayerAnchorSizing = supportsTopLayerAnchorPositioning() && CSS.supports("height", "max-content") && CSS.supports("max-height", "stretch");
1283
- return _supportsTopLayerAnchorSizing;
1284
- }
1285
- var anchorStyleId = "inertiaui-anchor-styles";
1286
- function ensureAnchorStylesheet() {
1287
- let style = document.getElementById(anchorStyleId);
1288
- if (!style) {
1289
- style = document.createElement("style");
1290
- style.id = anchorStyleId;
1291
- document.head.appendChild(style);
1292
- }
1293
- return style.sheet;
1294
- }
1295
- function findAnchorClass(element) {
1296
- return Array.from(element.classList).find((c) => c.startsWith(ANCHOR_CLASS_PREFIX));
1297
- }
1298
- function removeAnchorRule(className) {
1299
- const style = document.getElementById(anchorStyleId);
1300
- if (!style?.sheet) return;
1301
- for (let i = 0; i < style.sheet.cssRules.length; i++) if (style.sheet.cssRules[i].selectorText === `.${className}`) {
1302
- style.sheet.deleteRule(i);
1303
- return;
1304
- }
1305
- }
1306
- function setupAnchorPositioning(reference, floating, placement, offset, flip) {
1307
- const id = generateId(ANCHOR_CLASS_PREFIX);
1308
- const anchorName = `--${id}`;
1309
- reference.style.anchorName = anchorName;
1310
- floating.style.positionAnchor = anchorName;
1311
- floating.style.position = "fixed";
1312
- const sheet = ensureAnchorStylesheet();
1313
- const className = id;
1314
- const positionRules = getAnchorPositionRules(placement, offset);
1315
- let tryFallback = "";
1316
- if (flip) tryFallback = `position-try-fallbacks: flip-block, flip-inline; position-try: flip-block, flip-inline;`;
1317
- const rule = `.${className} { ${positionRules} ${tryFallback} }`;
1318
- sheet.insertRule(rule, sheet.cssRules.length);
1319
- floating.classList.add(className);
1320
- return className;
1321
- }
1322
- function cleanupAnchorPositioning(reference, floating, className) {
1323
- reference.style.anchorName = "";
1324
- floating.style.positionAnchor = "";
1325
- floating.style.position = "";
1326
- floating.classList.remove(className);
1327
- removeAnchorRule(className);
1328
- }
1329
- function detachAnchorPositioning(reference, floating) {
1330
- reference.style.removeProperty("anchor-name");
1331
- floating.style.removeProperty("position-anchor");
1332
- for (const className of Array.from(floating.classList)) if (className.startsWith(ANCHOR_CLASS_PREFIX)) {
1333
- floating.classList.remove(className);
1334
- removeAnchorRule(className);
1335
- }
1336
- }
1337
- function getAnchorPositionRules(placement, offset) {
1338
- const [side, alignment] = placement.split("-");
1339
- let positionRules = "";
1340
- switch (side) {
1341
- case "bottom":
1342
- positionRules += `top: anchor(bottom);`;
1343
- positionRules += `margin-top: ${offset}px;`;
1344
- break;
1345
- case "top":
1346
- positionRules += `bottom: anchor(top);`;
1347
- positionRules += `margin-bottom: ${offset}px;`;
1348
- break;
1349
- case "left":
1350
- positionRules += `right: anchor(left);`;
1351
- positionRules += `margin-right: ${offset}px;`;
1352
- break;
1353
- case "right":
1354
- positionRules += `left: anchor(right);`;
1355
- positionRules += `margin-left: ${offset}px;`;
1356
- break;
1357
- }
1358
- if (side === "bottom" || side === "top") switch (alignment) {
1359
- case "start":
1360
- positionRules += `left: anchor(left);`;
1361
- break;
1362
- case "end":
1363
- positionRules += `right: anchor(right);`;
1364
- break;
1365
- default:
1366
- positionRules += `left: anchor(center); translate: -50% 0;`;
1367
- break;
1368
- }
1369
- else switch (alignment) {
1370
- case "start":
1371
- positionRules += `top: anchor(top);`;
1372
- break;
1373
- case "end":
1374
- positionRules += `bottom: anchor(bottom);`;
1375
- break;
1376
- default:
1377
- positionRules += `top: anchor(center); translate: 0 -50%;`;
1378
- break;
1379
- }
1380
- return positionRules;
1381
- }
1382
- function getTopLayerAnchorSizingRules(placement, viewportMargin) {
1383
- const [side] = placement.split("-");
1384
- if (side === "bottom") return `bottom: ${viewportMargin}px; height: max-content; max-height: stretch;`;
1385
- if (side === "top") return `top: ${viewportMargin}px; height: max-content; max-height: stretch; align-self: end;`;
1386
- return "";
1387
- }
1388
- function setupTopLayerAnchorPositioning(reference, floating, placement, offset, flip, matchReferenceWidth, maxWidth, viewportMargin, stretchToAvailableHeight) {
1389
- const existingClass = findAnchorClass(floating);
1390
- const existingAnchorName = existingClass ? `--${existingClass}` : "";
1391
- const canReuseAnchor = !!existingClass && reference.style.getPropertyValue("anchor-name") === existingAnchorName && floating.style.getPropertyValue("position-anchor") === existingAnchorName;
1392
- const className = canReuseAnchor ? existingClass : generateId(ANCHOR_CLASS_PREFIX);
1393
- const anchorName = `--${className}`;
1394
- const sheet = ensureAnchorStylesheet();
1395
- if (canReuseAnchor) removeAnchorRule(className);
1396
- else detachAnchorPositioning(reference, floating);
1397
- reference.style.anchorName = anchorName;
1398
- floating.style.positionAnchor = anchorName;
1399
- removeStyleProperty(floating.style, "inset");
1400
- removeStyleProperty(floating.style, "top");
1401
- removeStyleProperty(floating.style, "right");
1402
- removeStyleProperty(floating.style, "bottom");
1403
- removeStyleProperty(floating.style, "left");
1404
- removeStyleProperty(floating.style, "margin");
1405
- setStyleProperty(floating.style, "position", "fixed");
1406
- if (stretchToAvailableHeight) {
1407
- setStyleProperty(floating.style, "height", "max-content");
1408
- removeStyleProperty(floating.style, "max-height");
1409
- } else removeStyleProperty(floating.style, "height");
1410
- if (matchReferenceWidth) setStyleProperty(floating.style, "width", `min(anchor-size(width), ${maxWidth}px)`);
1411
- const rule = `.${className} { position: fixed; inset: auto; margin: 0; ${getAnchorPositionRules(placement, offset)} ${flip ? "position-try-fallbacks: flip-block, flip-inline; position-try: flip-block, flip-inline;" : ""} ${matchReferenceWidth ? `width: min(anchor-size(width), ${maxWidth}px);` : ""} ${stretchToAvailableHeight ? getTopLayerAnchorSizingRules(placement, viewportMargin) : ""} }`;
1412
- sheet.insertRule(rule, sheet.cssRules.length);
1413
- floating.classList.add(className);
1414
- return className;
1415
- }
1416
- //#endregion
1417
1538
  //#region src/position/geometry.ts
1418
1539
  function isRtl$1() {
1419
1540
  return typeof document !== "undefined" && document.documentElement.dir === "rtl";
1420
1541
  }
1542
+ /** Whether `start` and `end` placements around the reference run from the right, following its writing direction. */
1543
+ function isRightToLeft(reference) {
1544
+ return getComputedStyle(reference).direction === "rtl";
1545
+ }
1421
1546
  function getOppositePlacement(placement) {
1422
1547
  return {
1423
1548
  top: "bottom",
@@ -1503,11 +1628,10 @@ function resolveTopLayerPlacement(preferredPlacement, referenceRect, floatingSiz
1503
1628
  if (floatingLength > preferredSpace && oppositeSpace > preferredSpace) return oppositePlacement;
1504
1629
  return preferredPlacement;
1505
1630
  }
1506
- function computePositionFromRect(refRect, floatingRect, placement, offset) {
1631
+ function computePositionFromRect(refRect, floatingRect, placement, offset, rtl = isRtl$1()) {
1507
1632
  let x = 0;
1508
1633
  let y = 0;
1509
1634
  const [side, alignment] = placement.split("-");
1510
- const rtl = isRtl$1();
1511
1635
  switch (side) {
1512
1636
  case "bottom":
1513
1637
  y = refRect.bottom + offset;
@@ -1575,12 +1699,16 @@ function clampToViewport(x, y, floatingRect) {
1575
1699
  function computeWithFallback(reference, floating, options = {}, referenceRect) {
1576
1700
  const { placement = "bottom-start", offset = 0, flip = true } = options;
1577
1701
  const refRect = referenceRect ?? reference.getBoundingClientRect();
1578
- const floatingRect = floating.getBoundingClientRect();
1579
- let { x, y } = computePositionFromRect(refRect, floatingRect, placement, offset);
1702
+ const floatingRect = {
1703
+ width: floating.offsetWidth,
1704
+ height: floating.offsetHeight
1705
+ };
1706
+ const rtl = isRightToLeft(reference);
1707
+ let { x, y } = computePositionFromRect(refRect, floatingRect, placement, offset, rtl);
1580
1708
  let actualPlacement = placement;
1581
1709
  if (flip && wouldOverflow(x, y, floatingRect, placement)) {
1582
1710
  const flipped = getOppositePlacement(placement);
1583
- const flippedPos = computePositionFromRect(refRect, floatingRect, flipped, offset);
1711
+ const flippedPos = computePositionFromRect(refRect, floatingRect, flipped, offset, rtl);
1584
1712
  if (!wouldOverflow(flippedPos.x, flippedPos.y, floatingRect, flipped)) {
1585
1713
  x = flippedPos.x;
1586
1714
  y = flippedPos.y;
@@ -1595,6 +1723,255 @@ function computeWithFallback(reference, floating, options = {}, referenceRect) {
1595
1723
  };
1596
1724
  }
1597
1725
  //#endregion
1726
+ //#region src/position/style.ts
1727
+ function setStyleProperty(style, property, value) {
1728
+ if (style.getPropertyValue(property) !== value) style.setProperty(property, value);
1729
+ }
1730
+ function removeStyleProperty(style, property) {
1731
+ if (style.getPropertyValue(property) !== "") style.removeProperty(property);
1732
+ }
1733
+ function captureStyleProperty(style, property) {
1734
+ return {
1735
+ value: style.getPropertyValue(property),
1736
+ priority: style.getPropertyPriority(property)
1737
+ };
1738
+ }
1739
+ function restoreStyleProperty(style, property, stored) {
1740
+ if (stored.value === "") {
1741
+ removeStyleProperty(style, property);
1742
+ return;
1743
+ }
1744
+ style.setProperty(property, stored.value, stored.priority);
1745
+ }
1746
+ //#endregion
1747
+ //#region src/position/anchor.ts
1748
+ var ANCHOR_CLASS_PREFIX = "iui-anchor-";
1749
+ var _supportsAnchor = null;
1750
+ var _supportsAnchorFlip = null;
1751
+ var _supportsTopLayerAnchor = null;
1752
+ var _supportsTopLayerAnchorSizing = null;
1753
+ var _isWebKit = null;
1754
+ function supportsAnchorPositioning() {
1755
+ if (_supportsAnchor === null) _supportsAnchor = typeof CSS !== "undefined" && typeof CSS.supports === "function" && CSS.supports("anchor-name", "--a") && CSS.supports("position-anchor", "--a") && CSS.supports("top", "anchor(bottom)");
1756
+ return _supportsAnchor;
1757
+ }
1758
+ function supportsTopLayerAnchorPositioning() {
1759
+ if (_supportsTopLayerAnchor === null) _supportsTopLayerAnchor = supportsAnchorPositioning() && CSS.supports("width", "anchor-size(width)") && !isWebKit();
1760
+ return _supportsTopLayerAnchor;
1761
+ }
1762
+ function isWebKit() {
1763
+ if (_isWebKit === null) _isWebKit = typeof CSS !== "undefined" && typeof CSS.supports === "function" && CSS.supports("-webkit-backdrop-filter", "none");
1764
+ return _isWebKit;
1765
+ }
1766
+ function supportsAnchorFlip() {
1767
+ if (_supportsAnchorFlip === null) _supportsAnchorFlip = supportsAnchorPositioning() && (CSS.supports("position-try-fallbacks", "flip-block") || CSS.supports("position-try", "flip-block"));
1768
+ return _supportsAnchorFlip;
1769
+ }
1770
+ function supportsTopLayerAnchorSizing() {
1771
+ if (_supportsTopLayerAnchorSizing === null) _supportsTopLayerAnchorSizing = supportsTopLayerAnchorPositioning() && CSS.supports("height", "max-content") && CSS.supports("max-height", "stretch");
1772
+ return _supportsTopLayerAnchorSizing;
1773
+ }
1774
+ var anchorStyleId = "inertiaui-anchor-styles";
1775
+ var anchorRules = /* @__PURE__ */ new WeakMap();
1776
+ var referenceAnchors = /* @__PURE__ */ new WeakMap();
1777
+ var anchorOwners = /* @__PURE__ */ new WeakMap();
1778
+ function anchorNames(value) {
1779
+ return value.split(",").map((name) => name.trim()).filter((name) => name.startsWith("--"));
1780
+ }
1781
+ function syncReferenceAnchors(reference, state) {
1782
+ const current = captureStyleProperty(reference.style, "anchor-name");
1783
+ if (current.value !== state.written.value || current.priority !== state.written.priority) state.original = {
1784
+ value: anchorNames(current.value).filter((name) => !state.names.has(name)).join(", ") || (current.value === "none" ? "none" : ""),
1785
+ priority: current.priority
1786
+ };
1787
+ return current;
1788
+ }
1789
+ function acquireReferenceAnchor(reference, floating) {
1790
+ const owner = anchorOwners.get(floating);
1791
+ const canReuse = owner?.reference === reference && floating.classList.contains(owner.className);
1792
+ if (!canReuse) detachAnchorPositioning(reference, floating);
1793
+ const className = canReuse ? owner.className : generateId(ANCHOR_CLASS_PREFIX);
1794
+ const name = `--${className}`;
1795
+ let state = referenceAnchors.get(reference);
1796
+ if (!state) {
1797
+ const original = captureStyleProperty(reference.style, "anchor-name");
1798
+ state = {
1799
+ original,
1800
+ written: original,
1801
+ names: /* @__PURE__ */ new Set()
1802
+ };
1803
+ referenceAnchors.set(reference, state);
1804
+ }
1805
+ const current = syncReferenceAnchors(reference, state);
1806
+ const names = anchorNames(current.value || getComputedStyle(reference).getPropertyValue("anchor-name"));
1807
+ if (!names.includes(name)) {
1808
+ names.push(name);
1809
+ reference.style.setProperty("anchor-name", names.join(", "), current.priority);
1810
+ }
1811
+ state.names.add(name);
1812
+ state.written = captureStyleProperty(reference.style, "anchor-name");
1813
+ anchorOwners.set(floating, {
1814
+ reference,
1815
+ className
1816
+ });
1817
+ return className;
1818
+ }
1819
+ function releaseReferenceAnchor(floating) {
1820
+ const owner = anchorOwners.get(floating);
1821
+ if (!owner) return;
1822
+ const { reference, className } = owner;
1823
+ const state = referenceAnchors.get(reference);
1824
+ const current = syncReferenceAnchors(reference, state);
1825
+ const name = `--${className}`;
1826
+ state.names.delete(name);
1827
+ if (state.names.size === 0) {
1828
+ restoreStyleProperty(reference.style, "anchor-name", state.original);
1829
+ referenceAnchors.delete(reference);
1830
+ } else {
1831
+ const names = anchorNames(current.value).filter((entry) => entry !== name);
1832
+ reference.style.setProperty("anchor-name", names.join(", "), current.priority);
1833
+ state.written = captureStyleProperty(reference.style, "anchor-name");
1834
+ }
1835
+ anchorOwners.delete(floating);
1836
+ }
1837
+ function ensureAnchorStylesheet() {
1838
+ let style = document.getElementById(anchorStyleId);
1839
+ if (!style) {
1840
+ style = document.createElement("style");
1841
+ style.id = anchorStyleId;
1842
+ document.head.appendChild(style);
1843
+ }
1844
+ return style.sheet;
1845
+ }
1846
+ function findAnchorClass(element) {
1847
+ return Array.from(element.classList).find((c) => c.startsWith(ANCHOR_CLASS_PREFIX));
1848
+ }
1849
+ function removeAnchorRule(className) {
1850
+ const style = document.getElementById(anchorStyleId);
1851
+ if (!style?.sheet) return;
1852
+ for (let i = 0; i < style.sheet.cssRules.length; i++) if (style.sheet.cssRules[i].selectorText === `.${className}`) {
1853
+ style.sheet.deleteRule(i);
1854
+ return;
1855
+ }
1856
+ }
1857
+ function updateAnchorRule(reference, floating, className, source, sheet) {
1858
+ const cached = anchorRules.get(floating);
1859
+ if (!cached || cached.reference !== reference || cached.source !== source || cached.rule.cssText !== cached.cssText || !Array.from(sheet.cssRules).includes(cached.rule)) {
1860
+ removeAnchorRule(className);
1861
+ const index = sheet.insertRule(source, sheet.cssRules.length);
1862
+ const inserted = sheet.cssRules[index];
1863
+ anchorRules.set(floating, {
1864
+ reference,
1865
+ source,
1866
+ rule: inserted,
1867
+ cssText: inserted.cssText
1868
+ });
1869
+ }
1870
+ }
1871
+ function setupAnchorPositioning(reference, floating, placement, offset, flip) {
1872
+ const className = acquireReferenceAnchor(reference, floating);
1873
+ const anchorName = `--${className}`;
1874
+ setStyleProperty(floating.style, "position-anchor", anchorName);
1875
+ removeStyleProperty(floating.style, "inset");
1876
+ setStyleProperty(floating.style, "position", "fixed");
1877
+ const sheet = ensureAnchorStylesheet();
1878
+ const positionRules = getAnchorPositionRules(placement, offset, isRightToLeft(reference));
1879
+ let tryFallback = "";
1880
+ if (flip) tryFallback = `position-try-fallbacks: flip-block, flip-inline; position-try: flip-block, flip-inline;`;
1881
+ updateAnchorRule(reference, floating, className, `.${className} { ${positionRules} ${tryFallback} }`, sheet);
1882
+ if (!floating.classList.contains(className)) floating.classList.add(className);
1883
+ return className;
1884
+ }
1885
+ function cleanupAnchorPositioning(reference, floating, className) {
1886
+ anchorRules.delete(floating);
1887
+ releaseReferenceAnchor(floating);
1888
+ removeStyleProperty(floating.style, "position-anchor");
1889
+ floating.style.position = "";
1890
+ floating.classList.remove(className);
1891
+ removeAnchorRule(className);
1892
+ }
1893
+ function detachAnchorPositioning(reference, floating) {
1894
+ anchorRules.delete(floating);
1895
+ releaseReferenceAnchor(floating);
1896
+ floating.style.removeProperty("position-anchor");
1897
+ for (const className of Array.from(floating.classList)) if (className.startsWith(ANCHOR_CLASS_PREFIX)) {
1898
+ floating.classList.remove(className);
1899
+ removeAnchorRule(className);
1900
+ }
1901
+ }
1902
+ function getAnchorPositionRules(placement, offset, rtl) {
1903
+ const [side, alignment] = placement.split("-");
1904
+ let positionRules = "";
1905
+ switch (side) {
1906
+ case "bottom":
1907
+ positionRules += `top: anchor(bottom);`;
1908
+ positionRules += `margin-top: ${offset}px;`;
1909
+ break;
1910
+ case "top":
1911
+ positionRules += `bottom: anchor(top);`;
1912
+ positionRules += `margin-bottom: ${offset}px;`;
1913
+ break;
1914
+ case "left":
1915
+ positionRules += `right: anchor(left);`;
1916
+ positionRules += `margin-right: ${offset}px;`;
1917
+ break;
1918
+ case "right":
1919
+ positionRules += `left: anchor(right);`;
1920
+ positionRules += `margin-left: ${offset}px;`;
1921
+ break;
1922
+ }
1923
+ if (side === "bottom" || side === "top") switch (alignment) {
1924
+ case "start":
1925
+ positionRules += rtl ? `right: anchor(right);` : `left: anchor(left);`;
1926
+ break;
1927
+ case "end":
1928
+ positionRules += rtl ? `left: anchor(left);` : `right: anchor(right);`;
1929
+ break;
1930
+ default:
1931
+ positionRules += `left: anchor(center); translate: -50% 0;`;
1932
+ break;
1933
+ }
1934
+ else switch (alignment) {
1935
+ case "start":
1936
+ positionRules += `top: anchor(top);`;
1937
+ break;
1938
+ case "end":
1939
+ positionRules += `bottom: anchor(bottom);`;
1940
+ break;
1941
+ default:
1942
+ positionRules += `top: anchor(center); translate: 0 -50%;`;
1943
+ break;
1944
+ }
1945
+ return positionRules;
1946
+ }
1947
+ function getTopLayerAnchorSizingRules(placement, viewportMargin) {
1948
+ const [side] = placement.split("-");
1949
+ if (side === "bottom") return `bottom: ${viewportMargin}px; height: max-content; max-height: stretch;`;
1950
+ if (side === "top") return `top: ${viewportMargin}px; height: max-content; max-height: stretch; align-self: end;`;
1951
+ return "";
1952
+ }
1953
+ function setupTopLayerAnchorPositioning(reference, floating, placement, offset, flip, matchReferenceWidth, maxWidth, viewportMargin, stretchToAvailableHeight) {
1954
+ const className = acquireReferenceAnchor(reference, floating);
1955
+ const anchorName = `--${className}`;
1956
+ const sheet = ensureAnchorStylesheet();
1957
+ setStyleProperty(floating.style, "position-anchor", anchorName);
1958
+ removeStyleProperty(floating.style, "inset");
1959
+ removeStyleProperty(floating.style, "top");
1960
+ removeStyleProperty(floating.style, "right");
1961
+ removeStyleProperty(floating.style, "bottom");
1962
+ removeStyleProperty(floating.style, "left");
1963
+ removeStyleProperty(floating.style, "margin");
1964
+ setStyleProperty(floating.style, "position", "fixed");
1965
+ if (stretchToAvailableHeight) {
1966
+ setStyleProperty(floating.style, "height", "max-content");
1967
+ removeStyleProperty(floating.style, "max-height");
1968
+ } else removeStyleProperty(floating.style, "height");
1969
+ if (matchReferenceWidth) setStyleProperty(floating.style, "width", `min(anchor-size(width), ${maxWidth}px)`);
1970
+ updateAnchorRule(reference, floating, className, `.${className} { position: fixed; inset: auto; margin: 0; ${getAnchorPositionRules(placement, offset, isRightToLeft(reference))} ${flip ? "position-try-fallbacks: flip-block, flip-inline; position-try: flip-block, flip-inline;" : ""} ${matchReferenceWidth ? `width: min(anchor-size(width), ${maxWidth}px);` : ""} ${stretchToAvailableHeight ? getTopLayerAnchorSizingRules(placement, viewportMargin) : ""} }`, sheet);
1971
+ if (!floating.classList.contains(className)) floating.classList.add(className);
1972
+ return className;
1973
+ }
1974
+ //#endregion
1598
1975
  //#region src/position/floating.ts
1599
1976
  var SIZE_MARGIN = 8;
1600
1977
  /**
@@ -1623,9 +2000,9 @@ function applySize(reference, floating, offset, side, refRect) {
1623
2000
  floating.style.overflowY = "auto";
1624
2001
  }
1625
2002
  function computePosition(reference, floating, options = {}) {
1626
- const { placement = "bottom-start", offset = 0, flip = true, autoSize = false } = options;
1627
- if (supportsAnchorPositioning() && (!flip || supportsAnchorFlip())) {
1628
- if (!findAnchorClass(floating)) setupAnchorPositioning(reference, floating, placement, offset, flip);
2003
+ const { placement = "bottom-start", offset = 0, flip = true, autoSize = false, anchorPositioning = true } = options;
2004
+ if (anchorPositioning && supportsAnchorPositioning() && (!flip || supportsAnchorFlip())) {
2005
+ setupAnchorPositioning(reference, floating, placement, offset, flip);
1629
2006
  if (autoSize) applySize(reference, floating, offset);
1630
2007
  const rect = floating.getBoundingClientRect();
1631
2008
  return {
@@ -1634,6 +2011,10 @@ function computePosition(reference, floating, options = {}) {
1634
2011
  placement
1635
2012
  };
1636
2013
  }
2014
+ const anchorClass = findAnchorClass(floating);
2015
+ if (anchorClass) cleanupAnchorPositioning(reference, floating, anchorClass);
2016
+ floating.style.position = "fixed";
2017
+ floating.style.inset = "auto";
1637
2018
  let referenceRect;
1638
2019
  if (autoSize) {
1639
2020
  referenceRect = reference.getBoundingClientRect();
@@ -1644,7 +2025,6 @@ function computePosition(reference, floating, options = {}) {
1644
2025
  offset,
1645
2026
  flip
1646
2027
  }, referenceRect);
1647
- floating.style.position = "fixed";
1648
2028
  floating.style.top = `${result.y}px`;
1649
2029
  floating.style.left = `${result.x}px`;
1650
2030
  if (autoSize) applySize(reference, floating, offset, result.placement.split("-")[0], referenceRect);
@@ -1774,13 +2154,19 @@ function positionTopLayerPopover(reference, floating, options = {}) {
1774
2154
  setStyleProperty(floating.style, "overscroll-behavior", "contain");
1775
2155
  const referenceRect = reference.getBoundingClientRect();
1776
2156
  const viewportHeight = Math.max(0, Math.floor(viewport.height - viewportMargin * 2));
1777
- if (anchorPositioning && supportsTopLayerAnchorPositioning() && (!flip || supportsAnchorFlip())) {
1778
- if (matchReferenceWidth) setStyleProperty(floating.style, "width", `${Math.min(referenceRect.width, maxWidth)}px`);
2157
+ function resolvePlacement() {
1779
2158
  const measuredRect = floating.getBoundingClientRect();
1780
- const resolvedPlacement = resolveTopLayerPlacement(placement, referenceRect, {
2159
+ return resolveTopLayerPlacement(placement, referenceRect, {
1781
2160
  width: Math.max(measuredRect.width, floating.scrollWidth),
1782
2161
  height: Math.max(measuredRect.height, floating.scrollHeight)
1783
2162
  }, viewport, offset, viewportMargin, flip);
2163
+ }
2164
+ if (anchorPositioning && supportsTopLayerAnchorPositioning() && (!flip || supportsAnchorFlip())) {
2165
+ let resolvedPlacement = placement;
2166
+ if (flip) {
2167
+ if (matchReferenceWidth) setStyleProperty(floating.style, "width", `${Math.min(referenceRect.width, maxWidth)}px`);
2168
+ resolvedPlacement = resolvePlacement();
2169
+ }
1784
2170
  const [resolvedSide] = resolvedPlacement.split("-");
1785
2171
  const stretchToAvailableHeight = (resolvedSide === "top" || resolvedSide === "bottom") && supportsTopLayerAnchorSizing();
1786
2172
  if (stretchToAvailableHeight) removeStyleProperty(floating.style, "max-height");
@@ -1803,17 +2189,14 @@ function positionTopLayerPopover(reference, floating, options = {}) {
1803
2189
  setStyleProperty(floating.style, "margin", "0");
1804
2190
  removeStyleProperty(floating.style, "height");
1805
2191
  if (matchReferenceWidth) setStyleProperty(floating.style, "width", `${Math.min(referenceRect.width, maxWidth)}px`);
1806
- const measuredRect = floating.getBoundingClientRect();
1807
- const resolvedPlacement = resolveTopLayerPlacement(placement, referenceRect, {
1808
- width: Math.max(measuredRect.width, floating.scrollWidth),
1809
- height: Math.max(measuredRect.height, floating.scrollHeight)
1810
- }, viewport, offset, viewportMargin, flip);
2192
+ let resolvedPlacement = placement;
2193
+ if (flip) resolvedPlacement = resolvePlacement();
1811
2194
  const [resolvedSide] = resolvedPlacement.split("-");
1812
2195
  const availableHeight = Math.min(viewportHeight, Math.max(0, Math.floor(getAvailableSpace(referenceRect, viewport, resolvedSide, offset, viewportMargin))));
1813
2196
  if (resolvedSide === "top" || resolvedSide === "bottom") setStyleProperty(floating.style, "max-height", `${availableHeight}px`);
1814
2197
  else setStyleProperty(floating.style, "max-height", `${viewportHeight}px`);
1815
2198
  const floatingRect = floating.getBoundingClientRect();
1816
- const coordinates = computePositionFromRect(referenceRect, floatingRect, resolvedPlacement, offset);
2199
+ const coordinates = computePositionFromRect(referenceRect, floatingRect, resolvedPlacement, offset, isRightToLeft(reference));
1817
2200
  const { x, y } = clampTopLayerCoordinates(coordinates.x, coordinates.y, floatingRect, resolvedPlacement, viewport, viewportMargin);
1818
2201
  setStyleProperty(floating.style, "left", `${Math.round(x)}px`);
1819
2202
  setStyleProperty(floating.style, "top", `${Math.round(y)}px`);
@@ -2086,6 +2469,41 @@ function createNativePopoverDisclosure(options) {
2086
2469
  };
2087
2470
  }
2088
2471
  //#endregion
2472
+ //#region src/rtl.ts
2473
+ /**
2474
+ * Check whether the document is currently in RTL direction.
2475
+ */
2476
+ function isRtl() {
2477
+ return document.documentElement.dir === "rtl";
2478
+ }
2479
+ /**
2480
+ * Observe changes to the document's `dir` attribute and invoke the callback
2481
+ * whenever it changes. Returns a cleanup function to stop observing.
2482
+ */
2483
+ function onRtlChange(callback) {
2484
+ const observer = new MutationObserver(() => {
2485
+ callback(document.documentElement.dir === "rtl");
2486
+ });
2487
+ observer.observe(document.documentElement, {
2488
+ attributes: true,
2489
+ attributeFilter: ["dir"]
2490
+ });
2491
+ return () => observer.disconnect();
2492
+ }
2493
+ /**
2494
+ * Give a panel rendered away from its reference, such as in the body, the
2495
+ * direction the reference is written in. A panel with its own `dir` keeps it.
2496
+ * Returns a cleanup function that removes the direction again.
2497
+ */
2498
+ function followReferenceDirection(reference, panel) {
2499
+ const direction = getComputedStyle(reference).direction;
2500
+ if (panel.hasAttribute("dir") || getComputedStyle(panel).direction === direction) return () => {};
2501
+ panel.setAttribute("dir", direction);
2502
+ return () => {
2503
+ if (panel.getAttribute("dir") === direction) panel.removeAttribute("dir");
2504
+ };
2505
+ }
2506
+ //#endregion
2089
2507
  //#region src/popover.ts
2090
2508
  /** Mount after rendering the open panel; cleanup detaches behavior without discarding open state. */
2091
2509
  function createPopoverController(options) {
@@ -2094,16 +2512,12 @@ function createPopoverController(options) {
2094
2512
  let mountedPanel = null;
2095
2513
  let pointerStartedOpen = false;
2096
2514
  let focusLast = false;
2097
- const disclosure = createNativePopoverDisclosure({
2515
+ const disclosureOptions = {
2098
2516
  reference: options.reference,
2099
2517
  popover: options.popover,
2100
2518
  get position() {
2101
- let placement = options.position.placement ?? "bottom-start";
2102
- const reference = options.reference();
2103
- if (reference && getComputedStyle(reference).direction === "rtl" && /^(top|bottom)-/.test(placement)) placement = placement.replace(/start|end/, (side) => side === "start" ? "end" : "start");
2104
2519
  return {
2105
2520
  ...options.position,
2106
- placement,
2107
2521
  anchorPositioning: native && options.position.anchorPositioning !== false
2108
2522
  };
2109
2523
  },
@@ -2113,11 +2527,15 @@ function createPopoverController(options) {
2113
2527
  onDismiss: () => close(false)
2114
2528
  },
2115
2529
  onOpenChange: options.onOpenChange
2116
- });
2530
+ };
2531
+ let disclosure;
2532
+ function getDisclosure() {
2533
+ return disclosure ??= createNativePopoverDisclosure(disclosureOptions);
2534
+ }
2117
2535
  function cleanup(hide = true) {
2118
2536
  cleanups.forEach((cleanup) => cleanup());
2119
2537
  cleanups = [];
2120
- disclosure.cleanupPopover();
2538
+ disclosure?.cleanupPopover();
2121
2539
  if (hide && native && mountedPanel?.matches(":popover-open")) mountedPanel.hidePopover();
2122
2540
  mountedPanel = null;
2123
2541
  }
@@ -2129,7 +2547,7 @@ function createPopoverController(options) {
2129
2547
  return typeof document !== "undefined" && (!!mountedPanel?.contains(document.activeElement) || document.activeElement === document.body);
2130
2548
  }
2131
2549
  function close(restoreFocus = shouldReturnFocus()) {
2132
- disclosure.closePopover({
2550
+ disclosure?.closePopover({
2133
2551
  hide: false,
2134
2552
  onClose() {
2135
2553
  cleanup();
@@ -2139,25 +2557,26 @@ function createPopoverController(options) {
2139
2557
  });
2140
2558
  }
2141
2559
  function onKeydown(event) {
2142
- if (event.key === "Escape" && disclosure.isOpen) {
2560
+ if (event.key === "Escape" && disclosure?.isOpen) {
2143
2561
  event.preventDefault();
2144
2562
  event.stopPropagation();
2145
2563
  close(true);
2146
- } else if (options.menu && !disclosure.isOpen && ["ArrowDown", "ArrowUp"].includes(event.key)) {
2564
+ } else if (options.menu && !disclosure?.isOpen && ["ArrowDown", "ArrowUp"].includes(event.key)) {
2147
2565
  event.preventDefault();
2148
2566
  focusLast = event.key === "ArrowUp";
2149
- disclosure.openPopover();
2567
+ getDisclosure().openPopover();
2150
2568
  }
2151
2569
  }
2152
2570
  function mount() {
2153
2571
  const reference = options.reference();
2154
2572
  const panel = options.popover();
2155
- if (!disclosure.isOpen || !reference || !panel) return;
2573
+ if (!disclosure?.isOpen || !reference || !panel) return;
2574
+ const activeDisclosure = disclosure;
2156
2575
  cleanup();
2157
2576
  mountedPanel = panel;
2158
2577
  const onBeforeToggle = (event) => {
2159
2578
  const restoreFocus = shouldReturnFocus();
2160
- disclosure.handlePopoverToggle(event, { onClose() {
2579
+ activeDisclosure.handlePopoverToggle(event, { onClose() {
2161
2580
  cleanup(false);
2162
2581
  if (restoreFocus) returnFocus();
2163
2582
  options.onClosed?.();
@@ -2165,19 +2584,20 @@ function createPopoverController(options) {
2165
2584
  };
2166
2585
  panel.addEventListener("beforetoggle", onBeforeToggle);
2167
2586
  panel.addEventListener("keydown", onKeydown);
2168
- panel.addEventListener("focusout", disclosure.handleFocusOut);
2587
+ panel.addEventListener("focusout", activeDisclosure.handleFocusOut);
2169
2588
  cleanups.push(() => {
2170
2589
  panel.removeEventListener("beforetoggle", onBeforeToggle);
2171
2590
  panel.removeEventListener("keydown", onKeydown);
2172
- panel.removeEventListener("focusout", disclosure.handleFocusOut);
2591
+ panel.removeEventListener("focusout", activeDisclosure.handleFocusOut);
2173
2592
  });
2174
- if (native) disclosure.showPopover();
2593
+ cleanups.push(followReferenceDirection(reference, panel));
2594
+ if (native) activeDisclosure.showPopover();
2175
2595
  else {
2176
- disclosure.updatePosition();
2596
+ activeDisclosure.updatePosition();
2177
2597
  cleanups.push(onClickOutside([reference, panel], () => close()));
2178
2598
  cleanups.push(onEscapeKey(() => close(true)));
2179
2599
  }
2180
- disclosure.startAutoUpdate();
2600
+ activeDisclosure.startAutoUpdate();
2181
2601
  const cleanupMount = options.onMount?.({
2182
2602
  reference,
2183
2603
  popover: panel,
@@ -2204,22 +2624,22 @@ function createPopoverController(options) {
2204
2624
  const wasOpen = !!event?.detail && pointerStartedOpen;
2205
2625
  pointerStartedOpen = false;
2206
2626
  if (wasOpen) close();
2207
- else disclosure.togglePopover(() => disclosure.openPopover(), () => close());
2627
+ else getDisclosure().togglePopover(() => getDisclosure().openPopover(), () => close());
2208
2628
  }
2209
2629
  return {
2210
2630
  native,
2211
2631
  get isOpen() {
2212
- return disclosure.isOpen;
2632
+ return disclosure?.isOpen ?? false;
2213
2633
  },
2214
- open: () => disclosure.openPopover(),
2634
+ open: () => getDisclosure().openPopover(),
2215
2635
  close,
2216
2636
  mount,
2217
2637
  cleanup,
2218
2638
  toggle,
2219
2639
  onKeydown,
2220
- onFocusOut: disclosure.handleFocusOut,
2640
+ onFocusOut: (event) => getDisclosure().handleFocusOut(event),
2221
2641
  onPointerDown: () => {
2222
- pointerStartedOpen = disclosure.isOpen;
2642
+ pointerStartedOpen = disclosure?.isOpen ?? false;
2223
2643
  }
2224
2644
  };
2225
2645
  }
@@ -2247,8 +2667,9 @@ function blank(value) {
2247
2667
  function debounce(fn) {
2248
2668
  let frame;
2249
2669
  return (...params) => {
2250
- if (frame) cancelAnimationFrame(frame);
2670
+ if (frame !== void 0) cancelAnimationFrame(frame);
2251
2671
  frame = requestAnimationFrame(() => {
2672
+ frame = void 0;
2252
2673
  fn(...params);
2253
2674
  });
2254
2675
  };
@@ -2297,13 +2718,14 @@ function detectFramerate() {
2297
2718
  const lastTime = timestamps.pop();
2298
2719
  const fps = Math.floor(1e3 * 10 / (now - lastTime));
2299
2720
  cancelAnimationFrame(rafId);
2721
+ clearTimeout(timeoutId);
2300
2722
  resolve(Math.min(Math.max(fps, 30), 240));
2301
2723
  return;
2302
2724
  }
2303
2725
  rafId = window.requestAnimationFrame(measure);
2304
2726
  }
2305
2727
  rafId = window.requestAnimationFrame(measure);
2306
- setTimeout(() => {
2728
+ const timeoutId = setTimeout(() => {
2307
2729
  if (rafId !== void 0) cancelAnimationFrame(rafId);
2308
2730
  resolve(60);
2309
2731
  }, 1e3);
@@ -2329,28 +2751,6 @@ function prefersDarkMode(strategy = "auto") {
2329
2751
  return containsDarkClass() || matchesDarkMediaQuery();
2330
2752
  }
2331
2753
  //#endregion
2332
- //#region src/rtl.ts
2333
- /**
2334
- * Check whether the document is currently in RTL direction.
2335
- */
2336
- function isRtl() {
2337
- return document.documentElement.dir === "rtl";
2338
- }
2339
- /**
2340
- * Observe changes to the document's `dir` attribute and invoke the callback
2341
- * whenever it changes. Returns a cleanup function to stop observing.
2342
- */
2343
- function onRtlChange(callback) {
2344
- const observer = new MutationObserver(() => {
2345
- callback(document.documentElement.dir === "rtl");
2346
- });
2347
- observer.observe(document.documentElement, {
2348
- attributes: true,
2349
- attributeFilter: ["dir"]
2350
- });
2351
- return () => observer.disconnect();
2352
- }
2353
- //#endregion
2354
2754
  //#region src/color.ts
2355
2755
  /**
2356
2756
  * Convert a hex color string to HSL values.
@@ -2398,6 +2798,8 @@ function hexToHsl(hex) {
2398
2798
  * Returns string with leading '#'.
2399
2799
  */
2400
2800
  function hslToHex(h, s, l) {
2801
+ h %= 360;
2802
+ if (h < 0) h += 360;
2401
2803
  s /= 100;
2402
2804
  l /= 100;
2403
2805
  const c = (1 - Math.abs(2 * l - 1)) * s;
@@ -2466,11 +2868,11 @@ function formatAlpha(number) {
2466
2868
  * Accepts any input understood by {@link parseHexColor}; falls back to black on invalid input.
2467
2869
  */
2468
2870
  function hexToRgb(hex) {
2469
- const normalized = parseHexColor(hex)?.hex ?? "#000000";
2871
+ const normalized = expandHex(hex) ?? "000000";
2470
2872
  return {
2471
- r: parseInt(normalized.slice(1, 3), 16),
2472
- g: parseInt(normalized.slice(3, 5), 16),
2473
- b: parseInt(normalized.slice(5, 7), 16)
2873
+ r: parseInt(normalized.slice(0, 2), 16),
2874
+ g: parseInt(normalized.slice(2, 4), 16),
2875
+ b: parseInt(normalized.slice(4, 6), 16)
2474
2876
  };
2475
2877
  }
2476
2878
  /**
@@ -2484,6 +2886,11 @@ function rgbToHex(r, g, b) {
2484
2886
  b
2485
2887
  ].map((channel) => clamp(Math.round(channel), 0, 255).toString(16).padStart(2, "0")).join("")}`;
2486
2888
  }
2889
+ function parseChannelNumber(token) {
2890
+ if (!/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)%?$/.test(token)) return null;
2891
+ const number = Number.parseFloat(token);
2892
+ return Number.isFinite(number) ? number : null;
2893
+ }
2487
2894
  /**
2488
2895
  * Parse an alpha channel from a raw string as found in rgba()/hsla() notation.
2489
2896
  *
@@ -2495,8 +2902,8 @@ function rgbToHex(r, g, b) {
2495
2902
  function parseAlphaChannel(rawAlpha) {
2496
2903
  if (rawAlpha === void 0 || rawAlpha.trim() === "") return 1;
2497
2904
  const trimmed = rawAlpha.trim();
2498
- const number = Number.parseFloat(trimmed);
2499
- if (!Number.isFinite(number)) return null;
2905
+ const number = parseChannelNumber(trimmed);
2906
+ if (number === null) return null;
2500
2907
  if (trimmed.endsWith("%")) {
2501
2908
  if (number < 0 || number > 100) return null;
2502
2909
  return normalizeAlpha(number / 100);
@@ -2513,8 +2920,8 @@ function parseAlphaChannel(rawAlpha) {
2513
2920
  */
2514
2921
  function parseRgbChannel(rawChannel) {
2515
2922
  const trimmed = rawChannel.trim();
2516
- const number = Number.parseFloat(trimmed);
2517
- if (!Number.isFinite(number)) return null;
2923
+ const number = parseChannelNumber(trimmed);
2924
+ if (number === null) return null;
2518
2925
  if (trimmed.endsWith("%")) {
2519
2926
  if (number < 0 || number > 100) return null;
2520
2927
  return clamp(Math.round(number / 100 * 255), 0, 255);
@@ -2535,6 +2942,16 @@ function parsedFromHex(hex, alphaValue = 1) {
2535
2942
  alpha: normalizeAlpha(alphaValue)
2536
2943
  };
2537
2944
  }
2945
+ function expandHex(input) {
2946
+ const match = /^#?([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i.exec(input.trim());
2947
+ if (!match) return null;
2948
+ const raw = match[1];
2949
+ if (raw.length === 3 || raw.length === 4) {
2950
+ const rgb = raw[0] + raw[0] + raw[1] + raw[1] + raw[2] + raw[2];
2951
+ return raw.length === 4 ? rgb + raw[3] + raw[3] : rgb;
2952
+ }
2953
+ return raw;
2954
+ }
2538
2955
  /**
2539
2956
  * Parse a hex color string into a {@link ParsedColor}.
2540
2957
  *
@@ -2542,11 +2959,8 @@ function parsedFromHex(hex, alphaValue = 1) {
2542
2959
  * 4/8 digit forms carry an alpha channel. Returns `null` on invalid input.
2543
2960
  */
2544
2961
  function parseHexColor(input) {
2545
- const trimmed = input.trim();
2546
- const match = /^#?([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i.exec(trimmed);
2547
- if (!match) return null;
2548
- const raw = match[1];
2549
- const expanded = raw.length === 3 || raw.length === 4 ? raw.split("").map((char) => char + char).join("") : raw;
2962
+ const expanded = expandHex(input);
2963
+ if (!expanded) return null;
2550
2964
  const hex = `#${expanded.slice(0, 6)}`;
2551
2965
  const alphaHex = expanded.length === 8 ? expanded.slice(6, 8) : null;
2552
2966
  return parsedFromHex(hex, alphaHex ? parseInt(alphaHex, 16) / 255 : 1);
@@ -2556,7 +2970,7 @@ function parseHexColor(input) {
2556
2970
  * Channels may be numeric (0-255) or percentages. Returns `null` on invalid input.
2557
2971
  */
2558
2972
  function parseRgbColor(input) {
2559
- const match = /^rgba?\(\s*([+-]?\d*\.?\d+%?)\s*,\s*([+-]?\d*\.?\d+%?)\s*,\s*([+-]?\d*\.?\d+%?)(?:\s*,\s*([+-]?\d*\.?\d+%?))?\s*\)$/i.exec(input.trim());
2973
+ const match = /^rgba?\(\s*([+-]?(?:\d+(?:\.\d+)?|\.\d+)%?)\s*,\s*([+-]?(?:\d+(?:\.\d+)?|\.\d+)%?)\s*,\s*([+-]?(?:\d+(?:\.\d+)?|\.\d+)%?)(?:\s*,\s*([+-]?(?:\d+(?:\.\d+)?|\.\d+)%?))?\s*\)$/i.exec(input.trim());
2560
2974
  if (!match) return null;
2561
2975
  const r = parseRgbChannel(match[1]);
2562
2976
  const g = parseRgbChannel(match[2]);
@@ -2570,7 +2984,7 @@ function parseRgbColor(input) {
2570
2984
  * Saturation and lightness must be percentages within 0-100. Returns `null` on invalid input.
2571
2985
  */
2572
2986
  function parseHslColor(input) {
2573
- const match = /^hsla?\(\s*([+-]?\d*\.?\d+)\s*,\s*([+-]?\d*\.?\d+)%\s*,\s*([+-]?\d*\.?\d+)%(?:\s*,\s*([+-]?\d*\.?\d+%?))?\s*\)$/i.exec(input.trim());
2987
+ const match = /^hsla?\(\s*([+-]?(?:\d+(?:\.\d+)?|\.\d+))\s*,\s*([+-]?(?:\d+(?:\.\d+)?|\.\d+))%\s*,\s*([+-]?(?:\d+(?:\.\d+)?|\.\d+))%(?:\s*,\s*([+-]?(?:\d+(?:\.\d+)?|\.\d+)%?))?\s*\)$/i.exec(input.trim());
2574
2988
  if (!match) return null;
2575
2989
  const h = normalizeHue(Number.parseFloat(match[1]));
2576
2990
  const s = Number.parseFloat(match[2]);
@@ -2618,6 +3032,27 @@ function formatColor(color, format = "hex", options = {}) {
2618
3032
  return includeAlpha ? `${normalized.hex}${Math.round(normalized.alpha * 255).toString(16).padStart(2, "0")}` : normalized.hex;
2619
3033
  }
2620
3034
  //#endregion
3035
+ //#region src/style.ts
3036
+ /**
3037
+ * Remember an element's inline values for some CSS properties, with their
3038
+ * priorities, so temporary changes can be undone without touching other inline
3039
+ * styles. Name properties as in CSS, such as `z-index`.
3040
+ */
3041
+ function captureInlineStyles(element, properties) {
3042
+ const names = properties.slice();
3043
+ const stored = names.map((property) => captureStyleProperty(element.style, property));
3044
+ return { restore: (only) => {
3045
+ if (!only) {
3046
+ names.forEach((property, index) => restoreStyleProperty(element.style, property, stored[index]));
3047
+ return;
3048
+ }
3049
+ for (const property of only) {
3050
+ const index = names.indexOf(property);
3051
+ if (index !== -1) restoreStyleProperty(element.style, property, stored[index]);
3052
+ }
3053
+ } };
3054
+ }
3055
+ //#endregion
2621
3056
  //#region src/cssVariables.ts
2622
3057
  /** Copy selected computed custom properties and restore owned inline values on cleanup. */
2623
3058
  function inheritCssVariables(source, target, options) {
@@ -2634,22 +3069,25 @@ function inheritCssVariables(source, target, options) {
2634
3069
  }
2635
3070
  function update() {
2636
3071
  const computed = view.getComputedStyle(source);
2637
- const names = /* @__PURE__ */ new Set();
3072
+ const values = /* @__PURE__ */ new Map();
2638
3073
  for (const name of Array.from(computed)) {
2639
3074
  if (!name.startsWith("--") || !options.filter(name)) continue;
2640
3075
  const value = computed.getPropertyValue(name).trim();
2641
3076
  if (!value) continue;
2642
- names.add(name);
3077
+ values.set(name, value);
3078
+ }
3079
+ for (const [name, value] of values) {
2643
3080
  if (!original.has(name)) original.set(name, {
2644
3081
  value: target.style.getPropertyValue(name),
2645
3082
  priority: target.style.getPropertyPriority(name)
2646
3083
  });
2647
3084
  if (applied.get(name) !== value) {
3085
+ if (target.style.getPropertyPriority(name)) target.style.removeProperty(name);
2648
3086
  target.style.setProperty(name, value);
2649
3087
  applied.set(name, value);
2650
3088
  }
2651
3089
  }
2652
- for (const name of applied.keys()) if (!names.has(name)) restore(name);
3090
+ for (const name of applied.keys()) if (!values.has(name)) restore(name);
2653
3091
  }
2654
3092
  update();
2655
3093
  const observer = new MutationObserver(update);
@@ -2670,38 +3108,45 @@ function inheritCssVariables(source, target, options) {
2670
3108
  /** Coordinates hover and focus intent without moving focus into the tooltip. */
2671
3109
  function createTooltipController(options) {
2672
3110
  const native = typeof HTMLElement !== "undefined" && "showPopover" in HTMLElement.prototype;
2673
- const scheduler = createDebouncer(options.delay ?? 300);
3111
+ const delay = options.delay ?? 300;
3112
+ let scheduler;
2674
3113
  let hovered = false;
2675
3114
  let focused = false;
2676
3115
  let closing = false;
2677
3116
  let revision = 0;
2678
3117
  let mounted = null;
2679
3118
  let cleanups = [];
2680
- const disclosure = createNativePopoverDisclosure({
2681
- reference: options.reference,
2682
- popover: options.tooltip,
2683
- get position() {
2684
- return {
2685
- placement: "top",
2686
- offset: 6,
2687
- ...options.position
2688
- };
2689
- },
2690
- onOpenChange: options.onOpenChange
2691
- });
3119
+ const reference = options.reference;
3120
+ const tooltip = options.tooltip;
3121
+ const onOpenChange = options.onOpenChange;
3122
+ let disclosure;
3123
+ function getDisclosure() {
3124
+ return disclosure ??= createNativePopoverDisclosure({
3125
+ reference,
3126
+ popover: tooltip,
3127
+ get position() {
3128
+ return {
3129
+ placement: "top",
3130
+ offset: 6,
3131
+ ...options.position
3132
+ };
3133
+ },
3134
+ onOpenChange
3135
+ });
3136
+ }
2692
3137
  function cleanup() {
2693
3138
  revision++;
2694
3139
  closing = false;
2695
- scheduler.cancel();
3140
+ scheduler?.cancel();
2696
3141
  cleanups.forEach((cleanup) => cleanup());
2697
3142
  cleanups = [];
2698
- disclosure.cleanupPopover();
3143
+ disclosure?.cleanupPopover();
2699
3144
  if (native && mounted?.matches(":popover-open")) mounted.hidePopover();
2700
3145
  mounted = null;
2701
3146
  }
2702
3147
  async function hide() {
2703
- scheduler.cancel();
2704
- if (!disclosure.isOpen || closing) return;
3148
+ scheduler?.cancel();
3149
+ if (!disclosure?.isOpen || closing) return;
2705
3150
  closing = true;
2706
3151
  const current = ++revision;
2707
3152
  await options.transition?.(false);
@@ -2718,9 +3163,9 @@ function createTooltipController(options) {
2718
3163
  closing = false;
2719
3164
  options.transition?.(true);
2720
3165
  }
2721
- if (disclosure.isOpen) return;
2722
- scheduler.schedule(() => {
2723
- if ((hovered || focused) && options.enabled?.() !== false) disclosure.openPopover();
3166
+ if (disclosure?.isOpen) return;
3167
+ (scheduler ??= createDebouncer(delay)).schedule(() => {
3168
+ if ((hovered || focused) && options.enabled?.() !== false) getDisclosure().openPopover();
2724
3169
  });
2725
3170
  }
2726
3171
  function dismissIfIdle() {
@@ -2729,13 +3174,15 @@ function createTooltipController(options) {
2729
3174
  function mount() {
2730
3175
  const reference = options.reference();
2731
3176
  const tooltip = options.tooltip();
2732
- if (!disclosure.isOpen || !reference || !tooltip) return;
3177
+ if (!disclosure?.isOpen || !reference || !tooltip) return;
2733
3178
  cleanup();
2734
3179
  mounted = tooltip;
3180
+ cleanups.push(followReferenceDirection(reference, tooltip));
2735
3181
  if (native) tooltip.showPopover();
2736
3182
  const updatePosition = () => computePosition(reference, tooltip, {
2737
3183
  placement: "top",
2738
3184
  offset: 6,
3185
+ anchorPositioning: false,
2739
3186
  ...options.position
2740
3187
  });
2741
3188
  updatePosition();
@@ -2761,7 +3208,7 @@ function createTooltipController(options) {
2761
3208
  return {
2762
3209
  native,
2763
3210
  get isOpen() {
2764
- return disclosure.isOpen;
3211
+ return disclosure?.isOpen ?? false;
2765
3212
  },
2766
3213
  mount,
2767
3214
  cleanup,
@@ -2802,8 +3249,11 @@ function createDialogController(options) {
2802
3249
  revision++;
2803
3250
  closing = false;
2804
3251
  const top = dialogs[dialogs.length - 1] === entry;
2805
- const index = dialogs.indexOf(entry);
2806
- if (index !== -1) dialogs.splice(index, 1);
3252
+ if (top) dialogs.pop();
3253
+ else {
3254
+ const index = dialogs.indexOf(entry);
3255
+ if (index !== -1) dialogs.splice(index, 1);
3256
+ }
2807
3257
  cleanups.forEach((cleanup) => cleanup());
2808
3258
  cleanups = [];
2809
3259
  if (native && mounted?.open) mounted.close();
@@ -2881,4 +3331,4 @@ function createDialogController(options) {
2881
3331
  };
2882
3332
  }
2883
3333
  //#endregion
2884
- export { REORDERABLE_LIST_HANDLE_ATTRIBUTE, animate, animateFromSnapshot, autoUpdate, autoUpdateTopLayerPopover, blank, cancelAnimations, captureAnimationSnapshot, computePosition, createDebouncer, createDialogController, createFocusOutDismiss, createFocusTrap, createMenuNavigation, createNativePopoverDisclosure, createPopoverController, createReorderableList, createTooltipController, debounce, detectFramerate, easings, except, focusFirstEnabledElement, formatAlpha, formatColor, generateId, hexToHsl, hexToRgb, hslToHex, inheritCssVariables, isRtl, isStandardDomEvent, kebabCase, lockScroll, markAriaHidden, markInert, normalizeAlpha, normalizeHue, normalizePercent, onClickOutside, onEscapeKey, onRtlChange, onceChildrenRendered, only, parseAlphaChannel, parseColorString, parseHexColor, parseHslColor, parseRgbChannel, parseRgbColor, parsedFromHex, positionTopLayerPopover, prefersDarkMode, prefersReducedMotion, rejectNullValues, resolveListboxNavigation, rgbToHex, sameUrlPath, supportsAnchorPositioning, supportsTopLayerAnchorPositioning, supportsWebAnimations };
3334
+ export { REORDERABLE_LIST_HANDLE_ATTRIBUTE, animate, animateFromSnapshot, autoUpdate, autoUpdateTopLayerPopover, blank, cancelAnimations, captureAnimationSnapshot, captureInlineStyles, computePosition, createDebouncer, createDialogController, createFocusOutDismiss, createFocusTrap, createLayoutAnimation, createMenuNavigation, createNativePopoverDisclosure, createPopoverController, createReorderableList, createTooltipController, debounce, detectFramerate, easings, except, focusFirstEnabledElement, formatAlpha, formatColor, generateId, getReorderOffsets, getScrollableAncestors, hexToHsl, hexToRgb, hslToHex, inheritCssVariables, isRtl, isStandardDomEvent, kebabCase, lockScroll, markAriaHidden, markInert, normalizeAlpha, normalizeHue, normalizePercent, onClickOutside, onEscapeKey, onRtlChange, onceChildrenRendered, only, parseAlphaChannel, parseColorString, parseHexColor, parseHslColor, parseRgbChannel, parseRgbColor, parsedFromHex, positionTopLayerPopover, prefersDarkMode, prefersReducedMotion, rejectNullValues, resolveListboxNavigation, rgbToHex, sameUrlPath, supportsAnchorPositioning, supportsTopLayerAnchorPositioning, supportsWebAnimations };