@inertiaui/vanilla 1.4.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) {
384
+ event.preventDefault();
385
+ lastElement.focus();
386
+ } else if (activeElement === lastElement) {
288
387
  event.preventDefault();
289
- firstElement.focus();
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
- }
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
858
  }
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
  }
@@ -1224,289 +1525,113 @@ function createPointerReorder(options) {
1224
1525
  function isDisabledElement(element) {
1225
1526
  return "disabled" in element && element.disabled === true;
1226
1527
  }
1227
- function focusFirstEnabledElement(elements) {
1528
+ function focusFirstEnabledElement(elements, options) {
1228
1529
  const control = elements.find((candidate) => candidate && !isDisabledElement(candidate));
1229
1530
  if (control) {
1230
- control.focus();
1531
+ if (options) control.focus(options);
1532
+ else control.focus();
1231
1533
  return true;
1232
1534
  }
1233
1535
  return false;
1234
1536
  }
1235
1537
  //#endregion
1236
- //#region src/position/style.ts
1237
- function setStyleProperty(style, property, value) {
1238
- if (style.getPropertyValue(property) !== value) style.setProperty(property, value);
1538
+ //#region src/position/geometry.ts
1539
+ function isRtl$1() {
1540
+ return typeof document !== "undefined" && document.documentElement.dir === "rtl";
1239
1541
  }
1240
- function removeStyleProperty(style, property) {
1241
- if (style.getPropertyValue(property) !== "") style.removeProperty(property);
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";
1242
1545
  }
1243
- function captureStyleProperty(style, property) {
1546
+ function getOppositePlacement(placement) {
1244
1547
  return {
1245
- value: style.getPropertyValue(property),
1246
- priority: style.getPropertyPriority(property)
1247
- };
1248
- }
1249
- function restoreStyleProperty(style, property, stored) {
1250
- if (stored.value === "") {
1251
- removeStyleProperty(style, property);
1252
- return;
1253
- }
1254
- style.setProperty(property, stored.value, stored.priority);
1548
+ top: "bottom",
1549
+ "top-start": "bottom-start",
1550
+ "top-end": "bottom-end",
1551
+ bottom: "top",
1552
+ "bottom-start": "top-start",
1553
+ "bottom-end": "top-end",
1554
+ left: "right",
1555
+ "left-start": "right-start",
1556
+ "left-end": "right-end",
1557
+ right: "left",
1558
+ "right-start": "left-start",
1559
+ "right-end": "left-end"
1560
+ }[placement] || placement;
1255
1561
  }
1256
- //#endregion
1257
- //#region src/position/anchor.ts
1258
- var ANCHOR_CLASS_PREFIX = "iui-anchor-";
1259
- var _supportsAnchor = null;
1260
- var _supportsAnchorFlip = null;
1261
- var _supportsTopLayerAnchor = null;
1262
- var _supportsTopLayerAnchorSizing = null;
1263
- var _isWebKit = null;
1264
- function supportsAnchorPositioning() {
1265
- 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)");
1266
- return _supportsAnchor;
1562
+ function getViewportRect() {
1563
+ const visualViewport = window.visualViewport;
1564
+ if (visualViewport) return {
1565
+ top: visualViewport.offsetTop,
1566
+ right: visualViewport.offsetLeft + visualViewport.width,
1567
+ bottom: visualViewport.offsetTop + visualViewport.height,
1568
+ left: visualViewport.offsetLeft,
1569
+ width: visualViewport.width,
1570
+ height: visualViewport.height
1571
+ };
1572
+ return {
1573
+ top: 0,
1574
+ right: window.innerWidth,
1575
+ bottom: window.innerHeight,
1576
+ left: 0,
1577
+ width: window.innerWidth,
1578
+ height: window.innerHeight
1579
+ };
1267
1580
  }
1268
- function supportsTopLayerAnchorPositioning() {
1269
- if (_supportsTopLayerAnchor === null) _supportsTopLayerAnchor = supportsAnchorPositioning() && CSS.supports("width", "anchor-size(width)") && !isWebKit();
1270
- return _supportsTopLayerAnchor;
1581
+ function clamp$1(value, min, max) {
1582
+ if (max < min) return min;
1583
+ return Math.max(min, Math.min(value, max));
1271
1584
  }
1272
- function isWebKit() {
1273
- if (_isWebKit === null) _isWebKit = typeof CSS !== "undefined" && typeof CSS.supports === "function" && CSS.supports("-webkit-backdrop-filter", "none");
1274
- return _isWebKit;
1585
+ function clampTopLayerCoordinates(x, y, floatingRect, placement, viewport, margin) {
1586
+ const [side] = placement.split("-");
1587
+ const minX = viewport.left + margin;
1588
+ const maxX = viewport.right - floatingRect.width - margin;
1589
+ const minY = viewport.top + margin;
1590
+ const maxY = viewport.bottom - floatingRect.height - margin;
1591
+ if (side === "top" || side === "bottom") return {
1592
+ x: clamp$1(x, minX, maxX),
1593
+ y
1594
+ };
1595
+ if (side === "left" || side === "right") return {
1596
+ x,
1597
+ y: clamp$1(y, minY, maxY)
1598
+ };
1599
+ return {
1600
+ x: clamp$1(x, minX, maxX),
1601
+ y: clamp$1(y, minY, maxY)
1602
+ };
1275
1603
  }
1276
- function supportsAnchorFlip() {
1277
- if (_supportsAnchorFlip === null) _supportsAnchorFlip = supportsAnchorPositioning() && (CSS.supports("position-try-fallbacks", "flip-block") || CSS.supports("position-try", "flip-block"));
1278
- return _supportsAnchorFlip;
1604
+ function topLayerRectOverflowsViewport(rect, viewport) {
1605
+ const tolerance = .5;
1606
+ return rect.top < viewport.top - tolerance || rect.left < viewport.left - tolerance || rect.right > viewport.right + tolerance || rect.bottom > viewport.bottom + tolerance;
1279
1607
  }
1280
- function supportsTopLayerAnchorSizing() {
1281
- if (_supportsTopLayerAnchorSizing === null) _supportsTopLayerAnchorSizing = supportsTopLayerAnchorPositioning() && CSS.supports("height", "max-content") && CSS.supports("max-height", "stretch");
1282
- return _supportsTopLayerAnchorSizing;
1608
+ function referenceIntersectsViewport(reference) {
1609
+ const rect = reference.getBoundingClientRect();
1610
+ const viewport = getViewportRect();
1611
+ return rect.width > 0 && rect.height > 0 && rect.bottom > viewport.top && rect.top < viewport.bottom && rect.right > viewport.left && rect.left < viewport.right;
1283
1612
  }
1284
- var anchorStyleId = "inertiaui-anchor-styles";
1285
- function ensureAnchorStylesheet() {
1286
- let style = document.getElementById(anchorStyleId);
1287
- if (!style) {
1288
- style = document.createElement("style");
1289
- style.id = anchorStyleId;
1290
- document.head.appendChild(style);
1291
- }
1292
- return style.sheet;
1613
+ function getAvailableSpace(referenceRect, viewport, side, offset, margin) {
1614
+ if (side === "top") return referenceRect.top - viewport.top - offset - margin;
1615
+ if (side === "bottom") return viewport.bottom - referenceRect.bottom - offset - margin;
1616
+ if (side === "left") return referenceRect.left - viewport.left - offset - margin;
1617
+ if (side === "right") return viewport.right - referenceRect.right - offset - margin;
1618
+ return viewport.height - margin * 2;
1293
1619
  }
1294
- function findAnchorClass(element) {
1295
- return Array.from(element.classList).find((c) => c.startsWith(ANCHOR_CLASS_PREFIX));
1620
+ function resolveTopLayerPlacement(preferredPlacement, referenceRect, floatingSize, viewport, offset, margin, flip) {
1621
+ if (!flip) return preferredPlacement;
1622
+ const [side] = preferredPlacement.split("-");
1623
+ const oppositePlacement = getOppositePlacement(preferredPlacement);
1624
+ const [oppositeSide] = oppositePlacement.split("-");
1625
+ const floatingLength = side === "left" || side === "right" ? floatingSize.width : floatingSize.height;
1626
+ const preferredSpace = getAvailableSpace(referenceRect, viewport, side, offset, margin);
1627
+ const oppositeSpace = getAvailableSpace(referenceRect, viewport, oppositeSide, offset, margin);
1628
+ if (floatingLength > preferredSpace && oppositeSpace > preferredSpace) return oppositePlacement;
1629
+ return preferredPlacement;
1296
1630
  }
1297
- function removeAnchorRule(className) {
1298
- const style = document.getElementById(anchorStyleId);
1299
- if (!style?.sheet) return;
1300
- for (let i = 0; i < style.sheet.cssRules.length; i++) if (style.sheet.cssRules[i].selectorText === `.${className}`) {
1301
- style.sheet.deleteRule(i);
1302
- return;
1303
- }
1304
- }
1305
- function setupAnchorPositioning(reference, floating, placement, offset, flip) {
1306
- const id = generateId(ANCHOR_CLASS_PREFIX);
1307
- const anchorName = `--${id}`;
1308
- reference.style.anchorName = anchorName;
1309
- floating.style.positionAnchor = anchorName;
1310
- floating.style.position = "fixed";
1311
- const sheet = ensureAnchorStylesheet();
1312
- const className = id;
1313
- const positionRules = getAnchorPositionRules(placement, offset);
1314
- let tryFallback = "";
1315
- if (flip) tryFallback = `position-try-fallbacks: flip-block, flip-inline; position-try: flip-block, flip-inline;`;
1316
- const rule = `.${className} { ${positionRules} ${tryFallback} }`;
1317
- sheet.insertRule(rule, sheet.cssRules.length);
1318
- floating.classList.add(className);
1319
- return className;
1320
- }
1321
- function cleanupAnchorPositioning(reference, floating, className) {
1322
- reference.style.anchorName = "";
1323
- floating.style.positionAnchor = "";
1324
- floating.style.position = "";
1325
- floating.classList.remove(className);
1326
- removeAnchorRule(className);
1327
- }
1328
- function detachAnchorPositioning(reference, floating) {
1329
- reference.style.removeProperty("anchor-name");
1330
- floating.style.removeProperty("position-anchor");
1331
- for (const className of Array.from(floating.classList)) if (className.startsWith(ANCHOR_CLASS_PREFIX)) {
1332
- floating.classList.remove(className);
1333
- removeAnchorRule(className);
1334
- }
1335
- }
1336
- function getAnchorPositionRules(placement, offset) {
1337
- const [side, alignment] = placement.split("-");
1338
- let positionRules = "";
1339
- switch (side) {
1340
- case "bottom":
1341
- positionRules += `top: anchor(bottom);`;
1342
- positionRules += `margin-top: ${offset}px;`;
1343
- break;
1344
- case "top":
1345
- positionRules += `bottom: anchor(top);`;
1346
- positionRules += `margin-bottom: ${offset}px;`;
1347
- break;
1348
- case "left":
1349
- positionRules += `right: anchor(left);`;
1350
- positionRules += `margin-right: ${offset}px;`;
1351
- break;
1352
- case "right":
1353
- positionRules += `left: anchor(right);`;
1354
- positionRules += `margin-left: ${offset}px;`;
1355
- break;
1356
- }
1357
- if (side === "bottom" || side === "top") switch (alignment) {
1358
- case "start":
1359
- positionRules += `left: anchor(left);`;
1360
- break;
1361
- case "end":
1362
- positionRules += `right: anchor(right);`;
1363
- break;
1364
- default:
1365
- positionRules += `left: anchor(center); translate: -50% 0;`;
1366
- break;
1367
- }
1368
- else switch (alignment) {
1369
- case "start":
1370
- positionRules += `top: anchor(top);`;
1371
- break;
1372
- case "end":
1373
- positionRules += `bottom: anchor(bottom);`;
1374
- break;
1375
- default:
1376
- positionRules += `top: anchor(center); translate: 0 -50%;`;
1377
- break;
1378
- }
1379
- return positionRules;
1380
- }
1381
- function getTopLayerAnchorSizingRules(placement, viewportMargin) {
1382
- const [side] = placement.split("-");
1383
- if (side === "bottom") return `bottom: ${viewportMargin}px; height: max-content; max-height: stretch;`;
1384
- if (side === "top") return `top: ${viewportMargin}px; height: max-content; max-height: stretch; align-self: end;`;
1385
- return "";
1386
- }
1387
- function setupTopLayerAnchorPositioning(reference, floating, placement, offset, flip, matchReferenceWidth, maxWidth, viewportMargin, stretchToAvailableHeight) {
1388
- const existingClass = findAnchorClass(floating);
1389
- const existingAnchorName = existingClass ? `--${existingClass}` : "";
1390
- const canReuseAnchor = !!existingClass && reference.style.getPropertyValue("anchor-name") === existingAnchorName && floating.style.getPropertyValue("position-anchor") === existingAnchorName;
1391
- const className = canReuseAnchor ? existingClass : generateId(ANCHOR_CLASS_PREFIX);
1392
- const anchorName = `--${className}`;
1393
- const sheet = ensureAnchorStylesheet();
1394
- if (canReuseAnchor) removeAnchorRule(className);
1395
- else detachAnchorPositioning(reference, floating);
1396
- reference.style.anchorName = anchorName;
1397
- floating.style.positionAnchor = anchorName;
1398
- removeStyleProperty(floating.style, "inset");
1399
- removeStyleProperty(floating.style, "top");
1400
- removeStyleProperty(floating.style, "right");
1401
- removeStyleProperty(floating.style, "bottom");
1402
- removeStyleProperty(floating.style, "left");
1403
- removeStyleProperty(floating.style, "margin");
1404
- setStyleProperty(floating.style, "position", "fixed");
1405
- if (stretchToAvailableHeight) {
1406
- setStyleProperty(floating.style, "height", "max-content");
1407
- removeStyleProperty(floating.style, "max-height");
1408
- } else removeStyleProperty(floating.style, "height");
1409
- if (matchReferenceWidth) setStyleProperty(floating.style, "width", `min(anchor-size(width), ${maxWidth}px)`);
1410
- 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) : ""} }`;
1411
- sheet.insertRule(rule, sheet.cssRules.length);
1412
- floating.classList.add(className);
1413
- return className;
1414
- }
1415
- //#endregion
1416
- //#region src/position/geometry.ts
1417
- function isRtl$1() {
1418
- return typeof document !== "undefined" && document.documentElement.dir === "rtl";
1419
- }
1420
- function getOppositePlacement(placement) {
1421
- return {
1422
- top: "bottom",
1423
- "top-start": "bottom-start",
1424
- "top-end": "bottom-end",
1425
- bottom: "top",
1426
- "bottom-start": "top-start",
1427
- "bottom-end": "top-end",
1428
- left: "right",
1429
- "left-start": "right-start",
1430
- "left-end": "right-end",
1431
- right: "left",
1432
- "right-start": "left-start",
1433
- "right-end": "left-end"
1434
- }[placement] || placement;
1435
- }
1436
- function getViewportRect() {
1437
- const visualViewport = window.visualViewport;
1438
- if (visualViewport) return {
1439
- top: visualViewport.offsetTop,
1440
- right: visualViewport.offsetLeft + visualViewport.width,
1441
- bottom: visualViewport.offsetTop + visualViewport.height,
1442
- left: visualViewport.offsetLeft,
1443
- width: visualViewport.width,
1444
- height: visualViewport.height
1445
- };
1446
- return {
1447
- top: 0,
1448
- right: window.innerWidth,
1449
- bottom: window.innerHeight,
1450
- left: 0,
1451
- width: window.innerWidth,
1452
- height: window.innerHeight
1453
- };
1454
- }
1455
- function clamp$1(value, min, max) {
1456
- if (max < min) return min;
1457
- return Math.max(min, Math.min(value, max));
1458
- }
1459
- function clampTopLayerCoordinates(x, y, floatingRect, placement, viewport, margin) {
1460
- const [side] = placement.split("-");
1461
- const minX = viewport.left + margin;
1462
- const maxX = viewport.right - floatingRect.width - margin;
1463
- const minY = viewport.top + margin;
1464
- const maxY = viewport.bottom - floatingRect.height - margin;
1465
- if (side === "top" || side === "bottom") return {
1466
- x: clamp$1(x, minX, maxX),
1467
- y
1468
- };
1469
- if (side === "left" || side === "right") return {
1470
- x,
1471
- y: clamp$1(y, minY, maxY)
1472
- };
1473
- return {
1474
- x: clamp$1(x, minX, maxX),
1475
- y: clamp$1(y, minY, maxY)
1476
- };
1477
- }
1478
- function topLayerRectOverflowsViewport(rect, viewport) {
1479
- const tolerance = .5;
1480
- return rect.top < viewport.top - tolerance || rect.left < viewport.left - tolerance || rect.right > viewport.right + tolerance || rect.bottom > viewport.bottom + tolerance;
1481
- }
1482
- function referenceIntersectsViewport(reference) {
1483
- const rect = reference.getBoundingClientRect();
1484
- const viewport = getViewportRect();
1485
- return rect.width > 0 && rect.height > 0 && rect.bottom > viewport.top && rect.top < viewport.bottom && rect.right > viewport.left && rect.left < viewport.right;
1486
- }
1487
- function getAvailableSpace(referenceRect, viewport, side, offset, margin) {
1488
- if (side === "top") return referenceRect.top - viewport.top - offset - margin;
1489
- if (side === "bottom") return viewport.bottom - referenceRect.bottom - offset - margin;
1490
- if (side === "left") return referenceRect.left - viewport.left - offset - margin;
1491
- if (side === "right") return viewport.right - referenceRect.right - offset - margin;
1492
- return viewport.height - margin * 2;
1493
- }
1494
- function resolveTopLayerPlacement(preferredPlacement, referenceRect, floatingSize, viewport, offset, margin, flip) {
1495
- if (!flip) return preferredPlacement;
1496
- const [side] = preferredPlacement.split("-");
1497
- const oppositePlacement = getOppositePlacement(preferredPlacement);
1498
- const [oppositeSide] = oppositePlacement.split("-");
1499
- const floatingLength = side === "left" || side === "right" ? floatingSize.width : floatingSize.height;
1500
- const preferredSpace = getAvailableSpace(referenceRect, viewport, side, offset, margin);
1501
- const oppositeSpace = getAvailableSpace(referenceRect, viewport, oppositeSide, offset, margin);
1502
- if (floatingLength > preferredSpace && oppositeSpace > preferredSpace) return oppositePlacement;
1503
- return preferredPlacement;
1504
- }
1505
- function computePositionFromRect(refRect, floatingRect, placement, offset) {
1631
+ function computePositionFromRect(refRect, floatingRect, placement, offset, rtl = isRtl$1()) {
1506
1632
  let x = 0;
1507
1633
  let y = 0;
1508
1634
  const [side, alignment] = placement.split("-");
1509
- const rtl = isRtl$1();
1510
1635
  switch (side) {
1511
1636
  case "bottom":
1512
1637
  y = refRect.bottom + offset;
@@ -1574,12 +1699,16 @@ function clampToViewport(x, y, floatingRect) {
1574
1699
  function computeWithFallback(reference, floating, options = {}, referenceRect) {
1575
1700
  const { placement = "bottom-start", offset = 0, flip = true } = options;
1576
1701
  const refRect = referenceRect ?? reference.getBoundingClientRect();
1577
- const floatingRect = floating.getBoundingClientRect();
1578
- 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);
1579
1708
  let actualPlacement = placement;
1580
1709
  if (flip && wouldOverflow(x, y, floatingRect, placement)) {
1581
1710
  const flipped = getOppositePlacement(placement);
1582
- const flippedPos = computePositionFromRect(refRect, floatingRect, flipped, offset);
1711
+ const flippedPos = computePositionFromRect(refRect, floatingRect, flipped, offset, rtl);
1583
1712
  if (!wouldOverflow(flippedPos.x, flippedPos.y, floatingRect, flipped)) {
1584
1713
  x = flippedPos.x;
1585
1714
  y = flippedPos.y;
@@ -1594,6 +1723,255 @@ function computeWithFallback(reference, floating, options = {}, referenceRect) {
1594
1723
  };
1595
1724
  }
1596
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
1597
1975
  //#region src/position/floating.ts
1598
1976
  var SIZE_MARGIN = 8;
1599
1977
  /**
@@ -1622,9 +2000,9 @@ function applySize(reference, floating, offset, side, refRect) {
1622
2000
  floating.style.overflowY = "auto";
1623
2001
  }
1624
2002
  function computePosition(reference, floating, options = {}) {
1625
- const { placement = "bottom-start", offset = 0, flip = true, autoSize = false } = options;
1626
- if (supportsAnchorPositioning() && (!flip || supportsAnchorFlip())) {
1627
- 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);
1628
2006
  if (autoSize) applySize(reference, floating, offset);
1629
2007
  const rect = floating.getBoundingClientRect();
1630
2008
  return {
@@ -1633,6 +2011,10 @@ function computePosition(reference, floating, options = {}) {
1633
2011
  placement
1634
2012
  };
1635
2013
  }
2014
+ const anchorClass = findAnchorClass(floating);
2015
+ if (anchorClass) cleanupAnchorPositioning(reference, floating, anchorClass);
2016
+ floating.style.position = "fixed";
2017
+ floating.style.inset = "auto";
1636
2018
  let referenceRect;
1637
2019
  if (autoSize) {
1638
2020
  referenceRect = reference.getBoundingClientRect();
@@ -1643,7 +2025,6 @@ function computePosition(reference, floating, options = {}) {
1643
2025
  offset,
1644
2026
  flip
1645
2027
  }, referenceRect);
1646
- floating.style.position = "fixed";
1647
2028
  floating.style.top = `${result.y}px`;
1648
2029
  floating.style.left = `${result.x}px`;
1649
2030
  if (autoSize) applySize(reference, floating, offset, result.placement.split("-")[0], referenceRect);
@@ -1773,13 +2154,19 @@ function positionTopLayerPopover(reference, floating, options = {}) {
1773
2154
  setStyleProperty(floating.style, "overscroll-behavior", "contain");
1774
2155
  const referenceRect = reference.getBoundingClientRect();
1775
2156
  const viewportHeight = Math.max(0, Math.floor(viewport.height - viewportMargin * 2));
1776
- if (anchorPositioning && supportsTopLayerAnchorPositioning() && (!flip || supportsAnchorFlip())) {
1777
- if (matchReferenceWidth) setStyleProperty(floating.style, "width", `${Math.min(referenceRect.width, maxWidth)}px`);
2157
+ function resolvePlacement() {
1778
2158
  const measuredRect = floating.getBoundingClientRect();
1779
- const resolvedPlacement = resolveTopLayerPlacement(placement, referenceRect, {
2159
+ return resolveTopLayerPlacement(placement, referenceRect, {
1780
2160
  width: Math.max(measuredRect.width, floating.scrollWidth),
1781
2161
  height: Math.max(measuredRect.height, floating.scrollHeight)
1782
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
+ }
1783
2170
  const [resolvedSide] = resolvedPlacement.split("-");
1784
2171
  const stretchToAvailableHeight = (resolvedSide === "top" || resolvedSide === "bottom") && supportsTopLayerAnchorSizing();
1785
2172
  if (stretchToAvailableHeight) removeStyleProperty(floating.style, "max-height");
@@ -1802,17 +2189,14 @@ function positionTopLayerPopover(reference, floating, options = {}) {
1802
2189
  setStyleProperty(floating.style, "margin", "0");
1803
2190
  removeStyleProperty(floating.style, "height");
1804
2191
  if (matchReferenceWidth) setStyleProperty(floating.style, "width", `${Math.min(referenceRect.width, maxWidth)}px`);
1805
- const measuredRect = floating.getBoundingClientRect();
1806
- const resolvedPlacement = resolveTopLayerPlacement(placement, referenceRect, {
1807
- width: Math.max(measuredRect.width, floating.scrollWidth),
1808
- height: Math.max(measuredRect.height, floating.scrollHeight)
1809
- }, viewport, offset, viewportMargin, flip);
2192
+ let resolvedPlacement = placement;
2193
+ if (flip) resolvedPlacement = resolvePlacement();
1810
2194
  const [resolvedSide] = resolvedPlacement.split("-");
1811
2195
  const availableHeight = Math.min(viewportHeight, Math.max(0, Math.floor(getAvailableSpace(referenceRect, viewport, resolvedSide, offset, viewportMargin))));
1812
2196
  if (resolvedSide === "top" || resolvedSide === "bottom") setStyleProperty(floating.style, "max-height", `${availableHeight}px`);
1813
2197
  else setStyleProperty(floating.style, "max-height", `${viewportHeight}px`);
1814
2198
  const floatingRect = floating.getBoundingClientRect();
1815
- const coordinates = computePositionFromRect(referenceRect, floatingRect, resolvedPlacement, offset);
2199
+ const coordinates = computePositionFromRect(referenceRect, floatingRect, resolvedPlacement, offset, isRightToLeft(reference));
1816
2200
  const { x, y } = clampTopLayerCoordinates(coordinates.x, coordinates.y, floatingRect, resolvedPlacement, viewport, viewportMargin);
1817
2201
  setStyleProperty(floating.style, "left", `${Math.round(x)}px`);
1818
2202
  setStyleProperty(floating.style, "top", `${Math.round(y)}px`);
@@ -2085,6 +2469,41 @@ function createNativePopoverDisclosure(options) {
2085
2469
  };
2086
2470
  }
2087
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
2088
2507
  //#region src/popover.ts
2089
2508
  /** Mount after rendering the open panel; cleanup detaches behavior without discarding open state. */
2090
2509
  function createPopoverController(options) {
@@ -2093,16 +2512,12 @@ function createPopoverController(options) {
2093
2512
  let mountedPanel = null;
2094
2513
  let pointerStartedOpen = false;
2095
2514
  let focusLast = false;
2096
- const disclosure = createNativePopoverDisclosure({
2515
+ const disclosureOptions = {
2097
2516
  reference: options.reference,
2098
2517
  popover: options.popover,
2099
2518
  get position() {
2100
- let placement = options.position.placement ?? "bottom-start";
2101
- const reference = options.reference();
2102
- if (reference && getComputedStyle(reference).direction === "rtl" && /^(top|bottom)-/.test(placement)) placement = placement.replace(/start|end/, (side) => side === "start" ? "end" : "start");
2103
2519
  return {
2104
2520
  ...options.position,
2105
- placement,
2106
2521
  anchorPositioning: native && options.position.anchorPositioning !== false
2107
2522
  };
2108
2523
  },
@@ -2112,11 +2527,15 @@ function createPopoverController(options) {
2112
2527
  onDismiss: () => close(false)
2113
2528
  },
2114
2529
  onOpenChange: options.onOpenChange
2115
- });
2530
+ };
2531
+ let disclosure;
2532
+ function getDisclosure() {
2533
+ return disclosure ??= createNativePopoverDisclosure(disclosureOptions);
2534
+ }
2116
2535
  function cleanup(hide = true) {
2117
2536
  cleanups.forEach((cleanup) => cleanup());
2118
2537
  cleanups = [];
2119
- disclosure.cleanupPopover();
2538
+ disclosure?.cleanupPopover();
2120
2539
  if (hide && native && mountedPanel?.matches(":popover-open")) mountedPanel.hidePopover();
2121
2540
  mountedPanel = null;
2122
2541
  }
@@ -2128,7 +2547,7 @@ function createPopoverController(options) {
2128
2547
  return typeof document !== "undefined" && (!!mountedPanel?.contains(document.activeElement) || document.activeElement === document.body);
2129
2548
  }
2130
2549
  function close(restoreFocus = shouldReturnFocus()) {
2131
- disclosure.closePopover({
2550
+ disclosure?.closePopover({
2132
2551
  hide: false,
2133
2552
  onClose() {
2134
2553
  cleanup();
@@ -2138,25 +2557,26 @@ function createPopoverController(options) {
2138
2557
  });
2139
2558
  }
2140
2559
  function onKeydown(event) {
2141
- if (event.key === "Escape" && disclosure.isOpen) {
2560
+ if (event.key === "Escape" && disclosure?.isOpen) {
2142
2561
  event.preventDefault();
2143
2562
  event.stopPropagation();
2144
2563
  close(true);
2145
- } else if (options.menu && !disclosure.isOpen && ["ArrowDown", "ArrowUp"].includes(event.key)) {
2564
+ } else if (options.menu && !disclosure?.isOpen && ["ArrowDown", "ArrowUp"].includes(event.key)) {
2146
2565
  event.preventDefault();
2147
2566
  focusLast = event.key === "ArrowUp";
2148
- disclosure.openPopover();
2567
+ getDisclosure().openPopover();
2149
2568
  }
2150
2569
  }
2151
2570
  function mount() {
2152
2571
  const reference = options.reference();
2153
2572
  const panel = options.popover();
2154
- if (!disclosure.isOpen || !reference || !panel) return;
2573
+ if (!disclosure?.isOpen || !reference || !panel) return;
2574
+ const activeDisclosure = disclosure;
2155
2575
  cleanup();
2156
2576
  mountedPanel = panel;
2157
2577
  const onBeforeToggle = (event) => {
2158
2578
  const restoreFocus = shouldReturnFocus();
2159
- disclosure.handlePopoverToggle(event, { onClose() {
2579
+ activeDisclosure.handlePopoverToggle(event, { onClose() {
2160
2580
  cleanup(false);
2161
2581
  if (restoreFocus) returnFocus();
2162
2582
  options.onClosed?.();
@@ -2164,19 +2584,20 @@ function createPopoverController(options) {
2164
2584
  };
2165
2585
  panel.addEventListener("beforetoggle", onBeforeToggle);
2166
2586
  panel.addEventListener("keydown", onKeydown);
2167
- panel.addEventListener("focusout", disclosure.handleFocusOut);
2587
+ panel.addEventListener("focusout", activeDisclosure.handleFocusOut);
2168
2588
  cleanups.push(() => {
2169
2589
  panel.removeEventListener("beforetoggle", onBeforeToggle);
2170
2590
  panel.removeEventListener("keydown", onKeydown);
2171
- panel.removeEventListener("focusout", disclosure.handleFocusOut);
2591
+ panel.removeEventListener("focusout", activeDisclosure.handleFocusOut);
2172
2592
  });
2173
- if (native) disclosure.showPopover();
2593
+ cleanups.push(followReferenceDirection(reference, panel));
2594
+ if (native) activeDisclosure.showPopover();
2174
2595
  else {
2175
- disclosure.updatePosition();
2596
+ activeDisclosure.updatePosition();
2176
2597
  cleanups.push(onClickOutside([reference, panel], () => close()));
2177
2598
  cleanups.push(onEscapeKey(() => close(true)));
2178
2599
  }
2179
- disclosure.startAutoUpdate();
2600
+ activeDisclosure.startAutoUpdate();
2180
2601
  const cleanupMount = options.onMount?.({
2181
2602
  reference,
2182
2603
  popover: panel,
@@ -2203,22 +2624,22 @@ function createPopoverController(options) {
2203
2624
  const wasOpen = !!event?.detail && pointerStartedOpen;
2204
2625
  pointerStartedOpen = false;
2205
2626
  if (wasOpen) close();
2206
- else disclosure.togglePopover(() => disclosure.openPopover(), () => close());
2627
+ else getDisclosure().togglePopover(() => getDisclosure().openPopover(), () => close());
2207
2628
  }
2208
2629
  return {
2209
2630
  native,
2210
2631
  get isOpen() {
2211
- return disclosure.isOpen;
2632
+ return disclosure?.isOpen ?? false;
2212
2633
  },
2213
- open: () => disclosure.openPopover(),
2634
+ open: () => getDisclosure().openPopover(),
2214
2635
  close,
2215
2636
  mount,
2216
2637
  cleanup,
2217
2638
  toggle,
2218
2639
  onKeydown,
2219
- onFocusOut: disclosure.handleFocusOut,
2640
+ onFocusOut: (event) => getDisclosure().handleFocusOut(event),
2220
2641
  onPointerDown: () => {
2221
- pointerStartedOpen = disclosure.isOpen;
2642
+ pointerStartedOpen = disclosure?.isOpen ?? false;
2222
2643
  }
2223
2644
  };
2224
2645
  }
@@ -2246,14 +2667,15 @@ function blank(value) {
2246
2667
  function debounce(fn) {
2247
2668
  let frame;
2248
2669
  return (...params) => {
2249
- if (frame) cancelAnimationFrame(frame);
2670
+ if (frame !== void 0) cancelAnimationFrame(frame);
2250
2671
  frame = requestAnimationFrame(() => {
2672
+ frame = void 0;
2251
2673
  fn(...params);
2252
2674
  });
2253
2675
  };
2254
2676
  }
2255
2677
  /**
2256
- * Create a {@link Debouncer} with a fixed delay.
2678
+ * Create a {@link Debouncer} with a fixed delay or a getter read on each schedule.
2257
2679
  *
2258
2680
  * @param delay - Milliseconds to wait after the latest `schedule()` call.
2259
2681
  */
@@ -2270,11 +2692,14 @@ function createDebouncer(delay) {
2270
2692
  timer = setTimeout(() => {
2271
2693
  timer = null;
2272
2694
  fn();
2273
- }, delay);
2695
+ }, typeof delay === "function" ? delay() : delay);
2274
2696
  };
2275
2697
  return {
2276
2698
  schedule,
2277
- cancel
2699
+ cancel,
2700
+ get pending() {
2701
+ return timer !== null;
2702
+ }
2278
2703
  };
2279
2704
  }
2280
2705
  /**
@@ -2293,13 +2718,14 @@ function detectFramerate() {
2293
2718
  const lastTime = timestamps.pop();
2294
2719
  const fps = Math.floor(1e3 * 10 / (now - lastTime));
2295
2720
  cancelAnimationFrame(rafId);
2721
+ clearTimeout(timeoutId);
2296
2722
  resolve(Math.min(Math.max(fps, 30), 240));
2297
2723
  return;
2298
2724
  }
2299
2725
  rafId = window.requestAnimationFrame(measure);
2300
2726
  }
2301
2727
  rafId = window.requestAnimationFrame(measure);
2302
- setTimeout(() => {
2728
+ const timeoutId = setTimeout(() => {
2303
2729
  if (rafId !== void 0) cancelAnimationFrame(rafId);
2304
2730
  resolve(60);
2305
2731
  }, 1e3);
@@ -2325,28 +2751,6 @@ function prefersDarkMode(strategy = "auto") {
2325
2751
  return containsDarkClass() || matchesDarkMediaQuery();
2326
2752
  }
2327
2753
  //#endregion
2328
- //#region src/rtl.ts
2329
- /**
2330
- * Check whether the document is currently in RTL direction.
2331
- */
2332
- function isRtl() {
2333
- return document.documentElement.dir === "rtl";
2334
- }
2335
- /**
2336
- * Observe changes to the document's `dir` attribute and invoke the callback
2337
- * whenever it changes. Returns a cleanup function to stop observing.
2338
- */
2339
- function onRtlChange(callback) {
2340
- const observer = new MutationObserver(() => {
2341
- callback(document.documentElement.dir === "rtl");
2342
- });
2343
- observer.observe(document.documentElement, {
2344
- attributes: true,
2345
- attributeFilter: ["dir"]
2346
- });
2347
- return () => observer.disconnect();
2348
- }
2349
- //#endregion
2350
2754
  //#region src/color.ts
2351
2755
  /**
2352
2756
  * Convert a hex color string to HSL values.
@@ -2394,6 +2798,8 @@ function hexToHsl(hex) {
2394
2798
  * Returns string with leading '#'.
2395
2799
  */
2396
2800
  function hslToHex(h, s, l) {
2801
+ h %= 360;
2802
+ if (h < 0) h += 360;
2397
2803
  s /= 100;
2398
2804
  l /= 100;
2399
2805
  const c = (1 - Math.abs(2 * l - 1)) * s;
@@ -2462,11 +2868,11 @@ function formatAlpha(number) {
2462
2868
  * Accepts any input understood by {@link parseHexColor}; falls back to black on invalid input.
2463
2869
  */
2464
2870
  function hexToRgb(hex) {
2465
- const normalized = parseHexColor(hex)?.hex ?? "#000000";
2871
+ const normalized = expandHex(hex) ?? "000000";
2466
2872
  return {
2467
- r: parseInt(normalized.slice(1, 3), 16),
2468
- g: parseInt(normalized.slice(3, 5), 16),
2469
- 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)
2470
2876
  };
2471
2877
  }
2472
2878
  /**
@@ -2480,6 +2886,11 @@ function rgbToHex(r, g, b) {
2480
2886
  b
2481
2887
  ].map((channel) => clamp(Math.round(channel), 0, 255).toString(16).padStart(2, "0")).join("")}`;
2482
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
+ }
2483
2894
  /**
2484
2895
  * Parse an alpha channel from a raw string as found in rgba()/hsla() notation.
2485
2896
  *
@@ -2491,8 +2902,8 @@ function rgbToHex(r, g, b) {
2491
2902
  function parseAlphaChannel(rawAlpha) {
2492
2903
  if (rawAlpha === void 0 || rawAlpha.trim() === "") return 1;
2493
2904
  const trimmed = rawAlpha.trim();
2494
- const number = Number.parseFloat(trimmed);
2495
- if (!Number.isFinite(number)) return null;
2905
+ const number = parseChannelNumber(trimmed);
2906
+ if (number === null) return null;
2496
2907
  if (trimmed.endsWith("%")) {
2497
2908
  if (number < 0 || number > 100) return null;
2498
2909
  return normalizeAlpha(number / 100);
@@ -2509,8 +2920,8 @@ function parseAlphaChannel(rawAlpha) {
2509
2920
  */
2510
2921
  function parseRgbChannel(rawChannel) {
2511
2922
  const trimmed = rawChannel.trim();
2512
- const number = Number.parseFloat(trimmed);
2513
- if (!Number.isFinite(number)) return null;
2923
+ const number = parseChannelNumber(trimmed);
2924
+ if (number === null) return null;
2514
2925
  if (trimmed.endsWith("%")) {
2515
2926
  if (number < 0 || number > 100) return null;
2516
2927
  return clamp(Math.round(number / 100 * 255), 0, 255);
@@ -2531,6 +2942,16 @@ function parsedFromHex(hex, alphaValue = 1) {
2531
2942
  alpha: normalizeAlpha(alphaValue)
2532
2943
  };
2533
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
+ }
2534
2955
  /**
2535
2956
  * Parse a hex color string into a {@link ParsedColor}.
2536
2957
  *
@@ -2538,11 +2959,8 @@ function parsedFromHex(hex, alphaValue = 1) {
2538
2959
  * 4/8 digit forms carry an alpha channel. Returns `null` on invalid input.
2539
2960
  */
2540
2961
  function parseHexColor(input) {
2541
- const trimmed = input.trim();
2542
- const match = /^#?([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i.exec(trimmed);
2543
- if (!match) return null;
2544
- const raw = match[1];
2545
- 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;
2546
2964
  const hex = `#${expanded.slice(0, 6)}`;
2547
2965
  const alphaHex = expanded.length === 8 ? expanded.slice(6, 8) : null;
2548
2966
  return parsedFromHex(hex, alphaHex ? parseInt(alphaHex, 16) / 255 : 1);
@@ -2552,7 +2970,7 @@ function parseHexColor(input) {
2552
2970
  * Channels may be numeric (0-255) or percentages. Returns `null` on invalid input.
2553
2971
  */
2554
2972
  function parseRgbColor(input) {
2555
- 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());
2556
2974
  if (!match) return null;
2557
2975
  const r = parseRgbChannel(match[1]);
2558
2976
  const g = parseRgbChannel(match[2]);
@@ -2566,7 +2984,7 @@ function parseRgbColor(input) {
2566
2984
  * Saturation and lightness must be percentages within 0-100. Returns `null` on invalid input.
2567
2985
  */
2568
2986
  function parseHslColor(input) {
2569
- 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());
2570
2988
  if (!match) return null;
2571
2989
  const h = normalizeHue(Number.parseFloat(match[1]));
2572
2990
  const s = Number.parseFloat(match[2]);
@@ -2614,4 +3032,303 @@ function formatColor(color, format = "hex", options = {}) {
2614
3032
  return includeAlpha ? `${normalized.hex}${Math.round(normalized.alpha * 255).toString(16).padStart(2, "0")}` : normalized.hex;
2615
3033
  }
2616
3034
  //#endregion
2617
- export { REORDERABLE_LIST_HANDLE_ATTRIBUTE, animate, animateFromSnapshot, autoUpdate, autoUpdateTopLayerPopover, blank, cancelAnimations, captureAnimationSnapshot, computePosition, createDebouncer, createFocusOutDismiss, createFocusTrap, createMenuNavigation, createNativePopoverDisclosure, createPopoverController, createReorderableList, debounce, detectFramerate, easings, except, focusFirstEnabledElement, formatAlpha, formatColor, generateId, hexToHsl, hexToRgb, hslToHex, 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 };
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
3056
+ //#region src/cssVariables.ts
3057
+ /** Copy selected computed custom properties and restore owned inline values on cleanup. */
3058
+ function inheritCssVariables(source, target, options) {
3059
+ const view = source.ownerDocument.defaultView;
3060
+ if (!view) return () => {};
3061
+ const original = /* @__PURE__ */ new Map();
3062
+ const applied = /* @__PURE__ */ new Map();
3063
+ function restore(name) {
3064
+ const previous = original.get(name);
3065
+ if (previous && target.style.getPropertyValue(name) === applied.get(name)) if (previous.value) target.style.setProperty(name, previous.value, previous.priority);
3066
+ else target.style.removeProperty(name);
3067
+ original.delete(name);
3068
+ applied.delete(name);
3069
+ }
3070
+ function update() {
3071
+ const computed = view.getComputedStyle(source);
3072
+ const values = /* @__PURE__ */ new Map();
3073
+ for (const name of Array.from(computed)) {
3074
+ if (!name.startsWith("--") || !options.filter(name)) continue;
3075
+ const value = computed.getPropertyValue(name).trim();
3076
+ if (!value) continue;
3077
+ values.set(name, value);
3078
+ }
3079
+ for (const [name, value] of values) {
3080
+ if (!original.has(name)) original.set(name, {
3081
+ value: target.style.getPropertyValue(name),
3082
+ priority: target.style.getPropertyPriority(name)
3083
+ });
3084
+ if (applied.get(name) !== value) {
3085
+ if (target.style.getPropertyPriority(name)) target.style.removeProperty(name);
3086
+ target.style.setProperty(name, value);
3087
+ applied.set(name, value);
3088
+ }
3089
+ }
3090
+ for (const name of applied.keys()) if (!values.has(name)) restore(name);
3091
+ }
3092
+ update();
3093
+ const observer = new MutationObserver(update);
3094
+ for (let ancestor = source; ancestor; ancestor = ancestor.parentElement) observer.observe(ancestor, {
3095
+ attributes: true,
3096
+ attributeFilter: ["class", "style"]
3097
+ });
3098
+ const media = (options.mediaQueries ?? []).map((query) => view.matchMedia(query));
3099
+ media.forEach((query) => query.addEventListener("change", update));
3100
+ return () => {
3101
+ observer.disconnect();
3102
+ media.forEach((query) => query.removeEventListener("change", update));
3103
+ for (const name of applied.keys()) restore(name);
3104
+ };
3105
+ }
3106
+ //#endregion
3107
+ //#region src/tooltip.ts
3108
+ /** Coordinates hover and focus intent without moving focus into the tooltip. */
3109
+ function createTooltipController(options) {
3110
+ const native = typeof HTMLElement !== "undefined" && "showPopover" in HTMLElement.prototype;
3111
+ const delay = options.delay ?? 300;
3112
+ let scheduler;
3113
+ let hovered = false;
3114
+ let focused = false;
3115
+ let closing = false;
3116
+ let revision = 0;
3117
+ let mounted = null;
3118
+ let cleanups = [];
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
+ }
3137
+ function cleanup() {
3138
+ revision++;
3139
+ closing = false;
3140
+ scheduler?.cancel();
3141
+ cleanups.forEach((cleanup) => cleanup());
3142
+ cleanups = [];
3143
+ disclosure?.cleanupPopover();
3144
+ if (native && mounted?.matches(":popover-open")) mounted.hidePopover();
3145
+ mounted = null;
3146
+ }
3147
+ async function hide() {
3148
+ scheduler?.cancel();
3149
+ if (!disclosure?.isOpen || closing) return;
3150
+ closing = true;
3151
+ const current = ++revision;
3152
+ await options.transition?.(false);
3153
+ if (current !== revision) return;
3154
+ disclosure.closePopover({
3155
+ hide: false,
3156
+ onClose: cleanup
3157
+ });
3158
+ }
3159
+ function requestShow() {
3160
+ if (options.enabled?.() === false) return;
3161
+ if (closing) {
3162
+ revision++;
3163
+ closing = false;
3164
+ options.transition?.(true);
3165
+ }
3166
+ if (disclosure?.isOpen) return;
3167
+ (scheduler ??= createDebouncer(delay)).schedule(() => {
3168
+ if ((hovered || focused) && options.enabled?.() !== false) getDisclosure().openPopover();
3169
+ });
3170
+ }
3171
+ function dismissIfIdle() {
3172
+ if (!hovered && !focused) hide();
3173
+ }
3174
+ function mount() {
3175
+ const reference = options.reference();
3176
+ const tooltip = options.tooltip();
3177
+ if (!disclosure?.isOpen || !reference || !tooltip) return;
3178
+ cleanup();
3179
+ mounted = tooltip;
3180
+ cleanups.push(followReferenceDirection(reference, tooltip));
3181
+ if (native) tooltip.showPopover();
3182
+ const updatePosition = () => computePosition(reference, tooltip, {
3183
+ placement: "top",
3184
+ offset: 6,
3185
+ anchorPositioning: false,
3186
+ ...options.position
3187
+ });
3188
+ updatePosition();
3189
+ cleanups.push(autoUpdateTopLayerPopover(reference, tooltip, updatePosition));
3190
+ const release = options.onMount?.({
3191
+ reference,
3192
+ popover: tooltip,
3193
+ native
3194
+ });
3195
+ if (release) cleanups.push(release);
3196
+ const escape = (event) => {
3197
+ if (event.key !== "Escape") return;
3198
+ if (event.target instanceof Node && reference.contains(event.target)) {
3199
+ event.preventDefault();
3200
+ event.stopPropagation();
3201
+ }
3202
+ hide();
3203
+ };
3204
+ reference.ownerDocument.addEventListener("keydown", escape, true);
3205
+ cleanups.push(() => reference.ownerDocument.removeEventListener("keydown", escape, true));
3206
+ options.transition?.(true);
3207
+ }
3208
+ return {
3209
+ native,
3210
+ get isOpen() {
3211
+ return disclosure?.isOpen ?? false;
3212
+ },
3213
+ mount,
3214
+ cleanup,
3215
+ hide,
3216
+ onMouseEnter() {
3217
+ hovered = true;
3218
+ requestShow();
3219
+ },
3220
+ onMouseLeave() {
3221
+ hovered = false;
3222
+ dismissIfIdle();
3223
+ },
3224
+ onFocusIn() {
3225
+ focused = true;
3226
+ requestShow();
3227
+ },
3228
+ onFocusOut(event) {
3229
+ if (event.relatedTarget instanceof Node && options.reference()?.contains(event.relatedTarget)) return;
3230
+ focused = false;
3231
+ dismissIfIdle();
3232
+ }
3233
+ };
3234
+ }
3235
+ //#endregion
3236
+ //#region src/modalDialog.ts
3237
+ var dialogs = [];
3238
+ /** Controls modal behavior while the consumer owns rendering and transitions. */
3239
+ function createDialogController(options) {
3240
+ const native = typeof HTMLDialogElement !== "undefined" && typeof HTMLDialogElement.prototype.showModal === "function";
3241
+ const entry = {};
3242
+ let open = false;
3243
+ let closing = false;
3244
+ let revision = 0;
3245
+ let mounted = null;
3246
+ let previousFocus = null;
3247
+ let cleanups = [];
3248
+ function cleanup() {
3249
+ revision++;
3250
+ closing = false;
3251
+ const top = dialogs[dialogs.length - 1] === entry;
3252
+ if (top) dialogs.pop();
3253
+ else {
3254
+ const index = dialogs.indexOf(entry);
3255
+ if (index !== -1) dialogs.splice(index, 1);
3256
+ }
3257
+ cleanups.forEach((cleanup) => cleanup());
3258
+ cleanups = [];
3259
+ if (native && mounted?.open) mounted.close();
3260
+ if (!native && top && previousFocus?.isConnected) previousFocus.focus({ preventScroll: true });
3261
+ previousFocus = null;
3262
+ mounted = null;
3263
+ }
3264
+ function show() {
3265
+ revision++;
3266
+ if (closing) {
3267
+ closing = false;
3268
+ options.transition?.(true);
3269
+ }
3270
+ if (open) return;
3271
+ open = true;
3272
+ options.onOpenChange?.(true);
3273
+ }
3274
+ async function close() {
3275
+ if (!open || closing) return;
3276
+ closing = true;
3277
+ const current = ++revision;
3278
+ await options.transition?.(false);
3279
+ if (current !== revision) return;
3280
+ open = false;
3281
+ cleanup();
3282
+ options.onOpenChange?.(false);
3283
+ }
3284
+ function mount() {
3285
+ const dialog = options.dialog();
3286
+ const panel = options.panel();
3287
+ if (!open || !dialog || !panel) return;
3288
+ cleanup();
3289
+ mounted = dialog;
3290
+ previousFocus = dialog.ownerDocument.activeElement;
3291
+ dialogs.push(entry);
3292
+ cleanups.push(lockScroll());
3293
+ if (native) {
3294
+ const cancel = (event) => {
3295
+ event.preventDefault();
3296
+ options.onCancel?.();
3297
+ };
3298
+ dialog.addEventListener("cancel", cancel);
3299
+ cleanups.push(() => dialog.removeEventListener("cancel", cancel));
3300
+ dialog.showModal();
3301
+ } else {
3302
+ for (let current = dialog; current?.parentElement; current = current.parentElement) {
3303
+ for (const sibling of Array.from(current.parentElement.children)) if (sibling !== current && sibling instanceof HTMLElement) cleanups.push(markInert(sibling));
3304
+ if (current.parentElement === dialog.ownerDocument.body) break;
3305
+ }
3306
+ cleanups.push(createFocusTrap(panel, { returnFocus: false }));
3307
+ cleanups.push(onEscapeKey((event) => {
3308
+ if (event.defaultPrevented || dialogs[dialogs.length - 1] !== entry) return;
3309
+ event.preventDefault();
3310
+ event.stopPropagation();
3311
+ options.onCancel?.();
3312
+ }));
3313
+ }
3314
+ const release = options.onMount?.({
3315
+ dialog,
3316
+ panel,
3317
+ native
3318
+ });
3319
+ if (release) cleanups.push(release);
3320
+ options.transition?.(true);
3321
+ }
3322
+ return {
3323
+ native,
3324
+ get isOpen() {
3325
+ return open;
3326
+ },
3327
+ open: show,
3328
+ close,
3329
+ mount,
3330
+ cleanup
3331
+ };
3332
+ }
3333
+ //#endregion
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 };