@inertiaui/vanilla 1.1.0 → 1.2.1

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
@@ -128,13 +128,20 @@ var FOCUSABLE_SELECTORS = [
128
128
  var scrollLockCount = 0;
129
129
  var originalOverflow = "";
130
130
  var originalPaddingRight = "";
131
+ var originalScrollbarGutter = "";
132
+ function supportsScrollbarGutter() {
133
+ return typeof CSS !== "undefined" && typeof CSS.supports === "function" && CSS.supports("scrollbar-gutter: stable");
134
+ }
131
135
  function lockScroll() {
132
136
  if (scrollLockCount === 0) {
133
137
  originalOverflow = document.body.style.overflow;
134
138
  originalPaddingRight = document.body.style.paddingRight;
139
+ originalScrollbarGutter = document.documentElement.style.getPropertyValue("scrollbar-gutter");
135
140
  const scrollbarWidth = window.innerWidth - document.documentElement.clientWidth;
141
+ const canReserveScrollbarGutter = supportsScrollbarGutter();
142
+ if (canReserveScrollbarGutter) document.documentElement.style.setProperty("scrollbar-gutter", "stable");
136
143
  document.body.style.overflow = "hidden";
137
- if (scrollbarWidth > 0) document.body.style.paddingRight = `${scrollbarWidth}px`;
144
+ if (!canReserveScrollbarGutter && scrollbarWidth > 0) document.body.style.paddingRight = `${scrollbarWidth}px`;
138
145
  }
139
146
  scrollLockCount++;
140
147
  let unlocked = false;
@@ -149,6 +156,8 @@ function unlockScroll() {
149
156
  if (scrollLockCount === 0) {
150
157
  document.body.style.overflow = originalOverflow;
151
158
  document.body.style.paddingRight = originalPaddingRight;
159
+ if (originalScrollbarGutter) document.documentElement.style.setProperty("scrollbar-gutter", originalScrollbarGutter);
160
+ else document.documentElement.style.removeProperty("scrollbar-gutter");
152
161
  }
153
162
  }
154
163
  function getFocusableElements(container) {
@@ -237,6 +246,8 @@ function createFocusTrap(container, options = {}) {
237
246
  }
238
247
  function onEscapeKey(callback, options = {}) {
239
248
  const { preventDefault = false, stopPropagation = false } = options;
249
+ let abortController = null;
250
+ let listening = false;
240
251
  function handler(event) {
241
252
  if (event.key === "Escape") {
242
253
  if (preventDefault) event.preventDefault();
@@ -244,12 +255,27 @@ function onEscapeKey(callback, options = {}) {
244
255
  callback(event);
245
256
  }
246
257
  }
247
- document.addEventListener("keydown", handler);
258
+ if (typeof AbortController !== "undefined") try {
259
+ abortController = new AbortController();
260
+ document.addEventListener("keydown", handler, { signal: abortController.signal });
261
+ listening = true;
262
+ } catch {
263
+ abortController = null;
264
+ }
265
+ if (!listening) {
266
+ document.addEventListener("keydown", handler);
267
+ listening = true;
268
+ }
248
269
  return function cleanup() {
249
- document.removeEventListener("keydown", handler);
270
+ if (abortController) abortController.abort();
271
+ else document.removeEventListener("keydown", handler);
250
272
  };
251
273
  }
252
274
  var ariaHiddenStack = [];
275
+ var inertStack = [];
276
+ function supportsNativeInert(element) {
277
+ return "inert" in element;
278
+ }
253
279
  function markAriaHidden(elementOrSelector) {
254
280
  const element = typeof elementOrSelector === "string" ? document.querySelector(elementOrSelector) : elementOrSelector;
255
281
  if (!element) return function noop() {};
@@ -282,10 +308,49 @@ function unmarkAriaHidden(element) {
282
308
  ariaHiddenStack.splice(index, 1);
283
309
  }
284
310
  }
311
+ function markInert(elementOrSelector) {
312
+ const element = typeof elementOrSelector === "string" ? document.querySelector(elementOrSelector) : elementOrSelector;
313
+ if (!element) return function noop() {};
314
+ const existingIndex = inertStack.findIndex((item) => item.element === element);
315
+ if (existingIndex >= 0) inertStack[existingIndex].count++;
316
+ else {
317
+ const originalAriaHidden = element.getAttribute("aria-hidden");
318
+ const hasNativeInert = supportsNativeInert(element);
319
+ const originalInert = hasNativeInert ? element.inert : false;
320
+ inertStack.push({
321
+ element,
322
+ originalAriaHidden,
323
+ originalInert,
324
+ count: 1
325
+ });
326
+ if (hasNativeInert) element.inert = true;
327
+ else element.setAttribute("aria-hidden", "true");
328
+ }
329
+ let cleaned = false;
330
+ return function cleanup() {
331
+ if (cleaned) return;
332
+ cleaned = true;
333
+ unmarkInert(element);
334
+ };
335
+ }
336
+ function unmarkInert(element) {
337
+ const index = inertStack.findIndex((item) => item.element === element);
338
+ if (index < 0) return;
339
+ inertStack[index].count--;
340
+ if (inertStack[index].count <= 0) {
341
+ const { originalAriaHidden, originalInert } = inertStack[index];
342
+ if (supportsNativeInert(element)) element.inert = originalInert;
343
+ if (originalAriaHidden === null) element.removeAttribute("aria-hidden");
344
+ else element.setAttribute("aria-hidden", originalAriaHidden);
345
+ inertStack.splice(index, 1);
346
+ }
347
+ }
285
348
  //#endregion
286
349
  //#region src/clickOutside.ts
287
350
  function onClickOutside(elements, callback) {
288
351
  const targets = Array.isArray(elements) ? elements : [elements];
352
+ let abortController = null;
353
+ let listening = false;
289
354
  function handler(event) {
290
355
  const target = event.target;
291
356
  for (const el of targets) if (el.contains(target)) return;
@@ -296,15 +361,30 @@ function onClickOutside(elements, callback) {
296
361
  }
297
362
  callback(event);
298
363
  }
299
- const timeoutId = setTimeout(() => {
364
+ function addListener() {
365
+ listening = true;
366
+ if (typeof AbortController !== "undefined") try {
367
+ abortController = new AbortController();
368
+ document.addEventListener("pointerdown", handler, {
369
+ capture: true,
370
+ signal: abortController.signal
371
+ });
372
+ return;
373
+ } catch {
374
+ abortController = null;
375
+ }
300
376
  document.addEventListener("pointerdown", handler, true);
377
+ }
378
+ const timeoutId = setTimeout(() => {
379
+ addListener();
301
380
  }, 0);
302
381
  let cleaned = false;
303
382
  return function cleanup() {
304
383
  if (cleaned) return;
305
384
  cleaned = true;
306
385
  clearTimeout(timeoutId);
307
- document.removeEventListener("pointerdown", handler, true);
386
+ if (abortController) abortController.abort();
387
+ else if (listening) document.removeEventListener("pointerdown", handler, true);
308
388
  };
309
389
  }
310
390
  //#endregion
@@ -395,13 +475,680 @@ function createMenuNavigation(container, options = {}) {
395
475
  };
396
476
  }
397
477
  //#endregion
478
+ //#region src/listbox.ts
479
+ function findEnabledListboxIndex(options) {
480
+ const { items, startIndex, direction, isItemDisabled, fallbackIndex = -1 } = options;
481
+ if (items.length === 0) return fallbackIndex;
482
+ let index = Math.min(Math.max(startIndex, 0), items.length - 1);
483
+ while (index >= 0 && index < items.length) {
484
+ if (!isItemDisabled?.(items[index], index)) return index;
485
+ index += direction;
486
+ }
487
+ return fallbackIndex;
488
+ }
489
+ function resolveListboxNavigation(options) {
490
+ const { items, currentIndex, key, isItemDisabled, fallbackIndex = currentIndex } = options;
491
+ if (items.length === 0) return {
492
+ handled: false,
493
+ index: fallbackIndex
494
+ };
495
+ switch (key) {
496
+ case "ArrowDown": return {
497
+ handled: true,
498
+ index: findEnabledListboxIndex({
499
+ items,
500
+ startIndex: currentIndex + 1,
501
+ direction: 1,
502
+ isItemDisabled,
503
+ fallbackIndex
504
+ })
505
+ };
506
+ case "ArrowUp": return {
507
+ handled: true,
508
+ index: findEnabledListboxIndex({
509
+ items,
510
+ startIndex: currentIndex - 1,
511
+ direction: -1,
512
+ isItemDisabled,
513
+ fallbackIndex
514
+ })
515
+ };
516
+ case "Home": return {
517
+ handled: true,
518
+ index: findEnabledListboxIndex({
519
+ items,
520
+ startIndex: 0,
521
+ direction: 1,
522
+ isItemDisabled,
523
+ fallbackIndex
524
+ })
525
+ };
526
+ case "End": return {
527
+ handled: true,
528
+ index: findEnabledListboxIndex({
529
+ items,
530
+ startIndex: items.length - 1,
531
+ direction: -1,
532
+ isItemDisabled,
533
+ fallbackIndex
534
+ })
535
+ };
536
+ default: return {
537
+ handled: false,
538
+ index: fallbackIndex
539
+ };
540
+ }
541
+ }
542
+ function createFocusOutDismiss(options) {
543
+ const { delay = 150 } = options;
544
+ let timeout = null;
545
+ let version = 0;
546
+ const cancel = () => {
547
+ if (timeout) {
548
+ clearTimeout(timeout);
549
+ timeout = null;
550
+ }
551
+ };
552
+ const markOpen = () => {
553
+ version += 1;
554
+ cancel();
555
+ };
556
+ const schedule = (event) => {
557
+ const container = options.container();
558
+ const related = event.relatedTarget;
559
+ if (container && related && container.contains(related)) return;
560
+ const scheduledVersion = version;
561
+ cancel();
562
+ timeout = setTimeout(() => {
563
+ timeout = null;
564
+ const currentContainer = options.container();
565
+ if (scheduledVersion !== version) return;
566
+ if (currentContainer?.contains(document.activeElement)) return;
567
+ if (options.shouldIgnore?.()) return;
568
+ options.onDismiss();
569
+ }, delay);
570
+ };
571
+ return {
572
+ markOpen,
573
+ cancel,
574
+ schedule,
575
+ cleanup: cancel
576
+ };
577
+ }
578
+ //#endregion
579
+ //#region src/reorder.ts
580
+ /**
581
+ * Attribute a caller places on a drag handle element so the pointer controller
582
+ * can verify that a pointer interaction started on an actual reorder handle.
583
+ */
584
+ var REORDERABLE_LIST_HANDLE_ATTRIBUTE = "data-reorderable-list-handle";
585
+ /**
586
+ * Return a new array with the item at `fromIndex` moved to `toIndex`.
587
+ * Out-of-range or no-op moves return a shallow copy unchanged.
588
+ */
589
+ function moveArrayItem(items, fromIndex, toIndex) {
590
+ if (fromIndex === toIndex || fromIndex < 0 || toIndex < 0 || fromIndex >= items.length || toIndex >= items.length) return [...items];
591
+ const nextItems = [...items];
592
+ const [item] = nextItems.splice(fromIndex, 1);
593
+ nextItems.splice(toIndex, 0, item);
594
+ return nextItems;
595
+ }
596
+ function identityOrder(length) {
597
+ return Array.from({ length }, (_, index) => index);
598
+ }
599
+ function isHTMLElement(value) {
600
+ return typeof HTMLElement !== "undefined" && value instanceof HTMLElement;
601
+ }
602
+ function getValidReorderHitBoxes(hitBoxes) {
603
+ 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);
604
+ }
605
+ function getOrderedReorderHitBoxes(hitBoxes) {
606
+ return getValidReorderHitBoxes(hitBoxes).sort((first, second) => first.index - second.index);
607
+ }
608
+ /**
609
+ * Given the on-screen hit boxes of each item and a pointer position, resolve the
610
+ * insertion index (0..count) the pointer currently maps to, or `null` when the
611
+ * point falls outside the combined bounds. Handles both single-column (vertical
612
+ * midpoint) and multi-item rows (horizontal midpoint) layouts.
613
+ */
614
+ function getInsertionIndexFromPoint(hitBoxes, point, options = {}) {
615
+ const orderedHitBoxes = getOrderedReorderHitBoxes(hitBoxes);
616
+ if (orderedHitBoxes.length === 0) return null;
617
+ const left = Math.min(...orderedHitBoxes.map((hitBox) => hitBox.left));
618
+ const top = Math.min(...orderedHitBoxes.map((hitBox) => hitBox.top));
619
+ const right = Math.max(...orderedHitBoxes.map((hitBox) => hitBox.right));
620
+ const bottom = Math.max(...orderedHitBoxes.map((hitBox) => hitBox.bottom));
621
+ const bounds = options.bounds;
622
+ const activeLeft = bounds ? Math.min(left, bounds.left) : left;
623
+ const activeTop = bounds ? Math.min(top, bounds.top) : top;
624
+ const activeRight = bounds ? Math.max(right, bounds.right) : right;
625
+ const activeBottom = bounds ? Math.max(bottom, bounds.bottom) : bottom;
626
+ if (point.clientX < activeLeft || point.clientX > activeRight || point.clientY < activeTop || point.clientY > activeBottom) return null;
627
+ if (point.clientY < top) return orderedHitBoxes[0].index;
628
+ if (point.clientY > bottom) return orderedHitBoxes[orderedHitBoxes.length - 1].index + 1;
629
+ const hitBoxesOnCurrentRow = orderedHitBoxes.filter((hitBox) => point.clientY >= hitBox.top && point.clientY <= hitBox.bottom).sort((first, second) => first.left - second.left || first.index - second.index);
630
+ if (hitBoxesOnCurrentRow.length > 1) {
631
+ for (const hitBox of hitBoxesOnCurrentRow) {
632
+ const midpoint = hitBox.left + (hitBox.right - hitBox.left) / 2;
633
+ if (point.clientX <= midpoint) return hitBox.index;
634
+ }
635
+ return hitBoxesOnCurrentRow[hitBoxesOnCurrentRow.length - 1].index + 1;
636
+ }
637
+ for (const hitBox of orderedHitBoxes) {
638
+ const midpoint = hitBox.top + (hitBox.bottom - hitBox.top) / 2;
639
+ if (point.clientY <= midpoint) return hitBox.index;
640
+ }
641
+ return orderedHitBoxes[orderedHitBoxes.length - 1].index + 1;
642
+ }
643
+ /**
644
+ * Convert an insertion index (0..count) into the destination array index for the
645
+ * item currently dragged from `fromIndex`. Returns `null` when the move is a
646
+ * no-op or out of range. Because removing the dragged item shifts everything
647
+ * after it left by one, an insertion index past `fromIndex` maps to `index - 1`.
648
+ */
649
+ function resolveTargetIndexFromInsertion(fromIndex, insertionIndex, itemCount) {
650
+ if (insertionIndex === null || itemCount < 2 || fromIndex < 0 || fromIndex >= itemCount) return null;
651
+ const boundedInsertionIndex = Math.max(0, Math.min(insertionIndex, itemCount));
652
+ const targetIndex = boundedInsertionIndex > fromIndex ? boundedInsertionIndex - 1 : boundedInsertionIndex;
653
+ if (targetIndex < 0 || targetIndex >= itemCount) return null;
654
+ return targetIndex;
655
+ }
656
+ /**
657
+ * Return true when the event target is a reorder handle carrying
658
+ * `REORDERABLE_LIST_HANDLE_ATTRIBUTE="true"`.
659
+ */
660
+ function isReorderHandle(target) {
661
+ return target instanceof HTMLElement && target.getAttribute("data-reorderable-list-handle") === "true";
662
+ }
663
+ function isShadowRoot(value) {
664
+ return typeof ShadowRoot !== "undefined" && value instanceof ShadowRoot;
665
+ }
666
+ function getParentNodeAcrossShadowDom(node) {
667
+ if (node.parentNode) return node.parentNode;
668
+ const root = node.getRootNode?.();
669
+ return isShadowRoot(root) ? root.host : null;
670
+ }
671
+ function getFallbackEventPath(event) {
672
+ const path = [];
673
+ let node = event.target instanceof Node ? event.target : null;
674
+ while (node) {
675
+ path.push(node);
676
+ node = getParentNodeAcrossShadowDom(node);
677
+ }
678
+ if (typeof document !== "undefined") path.push(document);
679
+ if (typeof window !== "undefined") path.push(window);
680
+ return path;
681
+ }
682
+ /**
683
+ * Find the reorder handle in an event path. This supports nested handle content
684
+ * and shadow-dom retargeting while preserving the same handle attribute contract.
685
+ */
686
+ function findReorderHandle(event, boundary = event.currentTarget) {
687
+ const path = typeof event.composedPath === "function" ? event.composedPath() : getFallbackEventPath(event);
688
+ for (const target of path) {
689
+ if (isReorderHandle(target)) return target;
690
+ if (boundary && target === boundary) break;
691
+ }
692
+ return isReorderHandle(boundary) ? boundary : null;
693
+ }
694
+ var autoScrollDefaults = {
695
+ edgeThreshold: 48,
696
+ maxSpeed: 720,
697
+ axis: "both"
698
+ };
699
+ function finiteNumber(value, fallback) {
700
+ return Number.isFinite(value) ? Math.max(0, value) : fallback;
701
+ }
702
+ function canOverflow(value) {
703
+ return value === "auto" || value === "scroll" || value === "overlay";
704
+ }
705
+ function isScrollableElement(element) {
706
+ const style = getComputedStyle(element);
707
+ const canScrollY = canOverflow(style.overflowY) && element.scrollHeight > element.clientHeight;
708
+ const canScrollX = canOverflow(style.overflowX) && element.scrollWidth > element.clientWidth;
709
+ return canScrollY || canScrollX;
710
+ }
711
+ function getOwnerWindow(element) {
712
+ if (element?.ownerDocument.defaultView) return element.ownerDocument.defaultView;
713
+ return typeof window !== "undefined" ? window : null;
714
+ }
715
+ function isWindowContainer(container) {
716
+ return typeof Window !== "undefined" && container instanceof Window;
717
+ }
718
+ function getScrollableAncestors(element) {
719
+ const containers = [];
720
+ const ownerWindow = getOwnerWindow(element);
721
+ let node = element;
722
+ while (node) {
723
+ node = getParentNodeAcrossShadowDom(node);
724
+ if (node instanceof Element && isScrollableElement(node)) containers.push(node);
725
+ }
726
+ if (ownerWindow) containers.push(ownerWindow);
727
+ return containers;
728
+ }
729
+ function getContainerRect(container) {
730
+ if (isWindowContainer(container)) return {
731
+ left: 0,
732
+ top: 0,
733
+ right: container.innerWidth,
734
+ bottom: container.innerHeight
735
+ };
736
+ return container.getBoundingClientRect();
737
+ }
738
+ function getScrollElement(container) {
739
+ return container.document.scrollingElement ?? container.document.documentElement;
740
+ }
741
+ function getScrollPosition(container, axis) {
742
+ if (isWindowContainer(container)) return axis === "x" ? container.scrollX : container.scrollY;
743
+ return axis === "x" ? container.scrollLeft : container.scrollTop;
744
+ }
745
+ function getMaxScrollPosition(container, axis) {
746
+ if (isWindowContainer(container)) {
747
+ const scrollElement = getScrollElement(container);
748
+ if (!scrollElement) return 0;
749
+ return Math.max(0, axis === "x" ? scrollElement.scrollWidth - container.innerWidth : scrollElement.scrollHeight - container.innerHeight);
750
+ }
751
+ return Math.max(0, axis === "x" ? container.scrollWidth - container.clientWidth : container.scrollHeight - container.clientHeight);
752
+ }
753
+ function canScroll(container, axis, direction) {
754
+ const position = getScrollPosition(container, axis);
755
+ const maxPosition = getMaxScrollPosition(container, axis);
756
+ return direction < 0 ? position > 0 : position < maxPosition;
757
+ }
758
+ function edgeIntensity(position, start, end, threshold) {
759
+ if (threshold <= 0 || position < start || position > end) return 0;
760
+ const startDistance = position - start;
761
+ const endDistance = end - position;
762
+ const startIntensity = startDistance < threshold ? (threshold - startDistance) / threshold : 0;
763
+ const endIntensity = endDistance < threshold ? (threshold - endDistance) / threshold : 0;
764
+ return endIntensity > startIntensity ? endIntensity : -startIntensity;
765
+ }
766
+ function getAutoScrollVector(container, point, edgeThreshold, maxStep) {
767
+ const rect = getContainerRect(container);
768
+ const width = rect.right - rect.left;
769
+ const height = rect.bottom - rect.top;
770
+ const xThreshold = Math.min(edgeThreshold, Math.max(0, width / 2));
771
+ const yThreshold = Math.min(edgeThreshold, Math.max(0, height / 2));
772
+ const xIntensity = edgeIntensity(point.clientX, rect.left, rect.right, xThreshold);
773
+ const yIntensity = edgeIntensity(point.clientY, rect.top, rect.bottom, yThreshold);
774
+ return {
775
+ left: xIntensity !== 0 && canScroll(container, "x", xIntensity) ? xIntensity * maxStep : 0,
776
+ top: yIntensity !== 0 && canScroll(container, "y", yIntensity) ? yIntensity * maxStep : 0
777
+ };
778
+ }
779
+ function scrollContainer(container, left, top) {
780
+ const previousLeft = getScrollPosition(container, "x");
781
+ const previousTop = getScrollPosition(container, "y");
782
+ if (isWindowContainer(container)) container.scrollBy({
783
+ left,
784
+ top,
785
+ behavior: "auto"
786
+ });
787
+ else {
788
+ if (left !== 0) container.scrollLeft += left;
789
+ if (top !== 0) container.scrollTop += top;
790
+ }
791
+ return {
792
+ x: getScrollPosition(container, "x") !== previousLeft,
793
+ y: getScrollPosition(container, "y") !== previousTop
794
+ };
795
+ }
796
+ /**
797
+ * Create a transform-free pointer auto-scroller for drag interactions.
798
+ */
799
+ function createAutoScroller(options = {}) {
800
+ const edgeThreshold = finiteNumber(options.edgeThreshold, autoScrollDefaults.edgeThreshold);
801
+ const maxSpeed = finiteNumber(options.maxSpeed, autoScrollDefaults.maxSpeed);
802
+ const axis = options.axis ?? autoScrollDefaults.axis;
803
+ let latestPoint = null;
804
+ let latestElement = null;
805
+ let containers = [];
806
+ let frameId = null;
807
+ let lastTimestamp = null;
808
+ let cleaned = false;
809
+ function queueFrame() {
810
+ if (cleaned || frameId !== null || typeof requestAnimationFrame !== "function") return;
811
+ frameId = requestAnimationFrame(step);
812
+ }
813
+ function stop() {
814
+ if (frameId !== null && typeof cancelAnimationFrame === "function") cancelAnimationFrame(frameId);
815
+ latestPoint = null;
816
+ latestElement = null;
817
+ containers = [];
818
+ frameId = null;
819
+ lastTimestamp = null;
820
+ }
821
+ function step(timestamp) {
822
+ frameId = null;
823
+ if (cleaned || !latestPoint) return;
824
+ const maxStep = maxSpeed * Math.max(1, Math.min(lastTimestamp === null ? 16 : timestamp - lastTimestamp, 32)) / 1e3;
825
+ let scrolled = false;
826
+ let handledX = axis === "y";
827
+ let handledY = axis === "x";
828
+ lastTimestamp = timestamp;
829
+ for (const container of containers) {
830
+ const vector = getAutoScrollVector(container, latestPoint, edgeThreshold, maxStep);
831
+ const left = handledX ? 0 : vector.left;
832
+ const top = handledY ? 0 : vector.top;
833
+ if (left === 0 && top === 0) continue;
834
+ const result = scrollContainer(container, left, top);
835
+ if (result.x) {
836
+ handledX = true;
837
+ scrolled = true;
838
+ }
839
+ if (result.y) {
840
+ handledY = true;
841
+ scrolled = true;
842
+ }
843
+ if (handledX && handledY) break;
844
+ }
845
+ if (scrolled) {
846
+ options.onScroll?.();
847
+ queueFrame();
848
+ } else lastTimestamp = null;
849
+ }
850
+ function update(point, element = latestElement) {
851
+ if (cleaned) return;
852
+ latestPoint = point;
853
+ latestElement = element;
854
+ containers = options.getScrollContainers?.(element) ?? getScrollableAncestors(element);
855
+ queueFrame();
856
+ }
857
+ function cleanup() {
858
+ if (cleaned) return;
859
+ cleaned = true;
860
+ stop();
861
+ }
862
+ return {
863
+ update,
864
+ stop,
865
+ cleanup,
866
+ isScrolling: () => frameId !== null
867
+ };
868
+ }
869
+ var idleState = {
870
+ draggedIndex: null,
871
+ insertionIndex: null,
872
+ targetIndex: null
873
+ };
874
+ function defaultReorderableListBounds(element) {
875
+ const rect = element?.getBoundingClientRect();
876
+ if (!rect || rect.width <= 0 || rect.height <= 0) return null;
877
+ return {
878
+ left: rect.left,
879
+ top: rect.top,
880
+ right: rect.right,
881
+ bottom: rect.bottom
882
+ };
883
+ }
884
+ function getRegisteredItemElements(itemElements) {
885
+ return Array.from(itemElements.entries()).sort(([firstIndex], [secondIndex]) => firstIndex - secondIndex).map(([, element]) => element);
886
+ }
887
+ /**
888
+ * Framework-neutral list reorder controller. It combines item registration,
889
+ * live pointer preview ordering, keyboard moves, pointer commits, bounds, and
890
+ * cleanup while leaving rendering, announcements, and animation policy to the
891
+ * consuming package.
892
+ */
893
+ function createReorderableList(options) {
894
+ let listElement = null;
895
+ let pointerState = idleState;
896
+ let dragHitBoxes = null;
897
+ let lastPreviewedPointerTargetIndex = null;
898
+ const itemElements = /* @__PURE__ */ new Map();
899
+ const itemCount = () => options.getItems().length;
900
+ const canReorder = () => (options.canReorder?.() ?? true) && itemCount() > 1;
901
+ const getBounds = () => options.getBounds?.() ?? defaultReorderableListBounds(listElement);
902
+ const measureItemHitBoxes = () => {
903
+ return options.getItems().map((_, index) => {
904
+ const element = itemElements.get(index);
905
+ if (!element) return null;
906
+ const rect = element.getBoundingClientRect();
907
+ return {
908
+ index,
909
+ left: rect.left,
910
+ top: rect.top,
911
+ right: rect.right,
912
+ bottom: rect.bottom
913
+ };
914
+ }).filter((hitBox) => hitBox !== null);
915
+ };
916
+ const getHitBoxes = () => dragHitBoxes ?? measureItemHitBoxes();
917
+ const commitReorder = (fromIndex, toIndex, source, context) => {
918
+ const items = options.getItems();
919
+ if (!canReorder() || fromIndex === toIndex || fromIndex < 0 || toIndex < 0 || fromIndex >= items.length || toIndex >= items.length) return null;
920
+ const move = {
921
+ item: items[fromIndex],
922
+ fromIndex,
923
+ toIndex,
924
+ source
925
+ };
926
+ options.onBeforeReorder?.(move, context);
927
+ options.setItems?.(moveArrayItem(items, fromIndex, toIndex));
928
+ options.onReorder?.(move, context);
929
+ return move;
930
+ };
931
+ const pointerReorder = createPointerReorder({
932
+ getItemCount: itemCount,
933
+ getHitBoxes,
934
+ getBounds,
935
+ canReorder,
936
+ autoScroll: options.autoScroll ?? false,
937
+ onChange: (state) => {
938
+ if (state.draggedIndex !== null) lastPreviewedPointerTargetIndex = state.targetIndex;
939
+ pointerState = state;
940
+ options.onChange?.(state);
941
+ if (state.draggedIndex === null) dragHitBoxes = null;
942
+ },
943
+ onCommit: (fromIndex, toIndex, source) => {
944
+ commitReorder(fromIndex, toIndex, source, { alreadyPreviewed: source === "pointer" && lastPreviewedPointerTargetIndex === toIndex });
945
+ lastPreviewedPointerTargetIndex = null;
946
+ }
947
+ });
948
+ const getPreviewOrder = () => {
949
+ const order = identityOrder(itemCount());
950
+ const fromIndex = pointerState.draggedIndex;
951
+ const toIndex = pointerState.targetIndex;
952
+ if (fromIndex === null || toIndex === null || fromIndex === toIndex) return order;
953
+ return moveArrayItem(order, fromIndex, toIndex);
954
+ };
955
+ return {
956
+ setListElement: (element) => {
957
+ listElement = isHTMLElement(element) ? element : null;
958
+ },
959
+ setItemElement: (index, element) => {
960
+ if (isHTMLElement(element)) {
961
+ itemElements.set(index, element);
962
+ return;
963
+ }
964
+ itemElements.delete(index);
965
+ },
966
+ getItemElements: () => getRegisteredItemElements(itemElements),
967
+ getPreviewOrder,
968
+ getPreviewItems: () => {
969
+ const items = options.getItems();
970
+ return getPreviewOrder().filter((index) => index >= 0 && index < items.length).map((index, visualIndex) => ({
971
+ item: items[index],
972
+ index,
973
+ visualIndex
974
+ }));
975
+ },
976
+ moveItem: (index, direction) => {
977
+ return commitReorder(index, direction === "up" ? index - 1 : index + 1, "keyboard", { alreadyPreviewed: false });
978
+ },
979
+ pointerDown: (index, event) => {
980
+ dragHitBoxes = measureItemHitBoxes();
981
+ pointerReorder.pointerDown(index, event);
982
+ if (!event.defaultPrevented) dragHitBoxes = null;
983
+ },
984
+ cleanup: () => {
985
+ pointerReorder.cleanup();
986
+ dragHitBoxes = null;
987
+ itemElements.clear();
988
+ listElement = null;
989
+ pointerState = idleState;
990
+ lastPreviewedPointerTargetIndex = null;
991
+ }
992
+ };
993
+ }
994
+ /**
995
+ * Pointer-drag reorder implementation used by createReorderableList. It owns
996
+ * the window pointer listeners and insertion-index math.
997
+ */
998
+ function createPointerReorder(options) {
999
+ const canReorder = () => (options.canReorder?.() ?? true) && options.getItemCount() > 1;
1000
+ let activePointer = null;
1001
+ let insertionIndex = null;
1002
+ let pointerOverReorderArea = false;
1003
+ let lastPoint = null;
1004
+ let cleaned = false;
1005
+ const autoScrollOptions = options.autoScroll === true ? {} : options.autoScroll || null;
1006
+ const autoScroller = autoScrollOptions ? createAutoScroller({
1007
+ ...autoScrollOptions,
1008
+ onScroll: () => {
1009
+ autoScrollOptions.onScroll?.();
1010
+ if (!activePointer || !lastPoint) return;
1011
+ updateInsertionIndex(lastPoint);
1012
+ emitChange();
1013
+ }
1014
+ }) : null;
1015
+ function currentState() {
1016
+ if (!activePointer) return idleState;
1017
+ return {
1018
+ draggedIndex: activePointer.fromIndex,
1019
+ insertionIndex,
1020
+ targetIndex: resolveTargetIndexFromInsertion(activePointer.fromIndex, insertionIndex, options.getItemCount())
1021
+ };
1022
+ }
1023
+ function emitChange() {
1024
+ options.onChange?.(currentState());
1025
+ }
1026
+ function updateInsertionIndex(point) {
1027
+ const nextInsertionIndex = getInsertionIndexFromPoint(options.getHitBoxes(), {
1028
+ clientX: point.clientX,
1029
+ clientY: point.clientY
1030
+ }, { bounds: options.getBounds?.() ?? null });
1031
+ pointerOverReorderArea = nextInsertionIndex !== null;
1032
+ if (nextInsertionIndex !== null) insertionIndex = nextInsertionIndex;
1033
+ }
1034
+ function updatePointerPosition(event, shouldAutoScroll) {
1035
+ lastPoint = {
1036
+ clientX: event.clientX,
1037
+ clientY: event.clientY
1038
+ };
1039
+ updateInsertionIndex(lastPoint);
1040
+ if (shouldAutoScroll) autoScroller?.update(lastPoint, activePointer?.scrollElement ?? activePointer?.captureElement ?? null);
1041
+ }
1042
+ function stop() {
1043
+ releasePointerCapture();
1044
+ autoScroller?.stop();
1045
+ window.removeEventListener("pointermove", handleWindowPointerMove);
1046
+ window.removeEventListener("pointerup", handleWindowPointerUp);
1047
+ window.removeEventListener("pointercancel", handleWindowPointerCancel);
1048
+ activePointer = null;
1049
+ insertionIndex = null;
1050
+ pointerOverReorderArea = false;
1051
+ lastPoint = null;
1052
+ }
1053
+ function releasePointerCapture() {
1054
+ const pointer = activePointer;
1055
+ if (!pointer?.captureElement?.isConnected) return;
1056
+ try {
1057
+ if (pointer.captureElement.hasPointerCapture?.(pointer.pointerId)) pointer.captureElement.releasePointerCapture(pointer.pointerId);
1058
+ } catch {}
1059
+ }
1060
+ function handleWindowPointerMove(event) {
1061
+ if (activePointer?.pointerId !== event.pointerId) return;
1062
+ event.preventDefault();
1063
+ updatePointerPosition(event, true);
1064
+ emitChange();
1065
+ }
1066
+ function handleWindowPointerUp(event) {
1067
+ const pointer = activePointer;
1068
+ if (!pointer || pointer.pointerId !== event.pointerId) return;
1069
+ event.preventDefault();
1070
+ const fromIndex = pointer.fromIndex;
1071
+ const toIndex = pointerOverReorderArea ? resolveTargetIndexFromInsertion(fromIndex, insertionIndex, options.getItemCount()) : null;
1072
+ stop();
1073
+ emitChange();
1074
+ if (toIndex !== null && fromIndex !== toIndex) options.onCommit(fromIndex, toIndex, "pointer");
1075
+ }
1076
+ function handleWindowPointerCancel(event) {
1077
+ if (activePointer?.pointerId !== event.pointerId) return;
1078
+ stop();
1079
+ emitChange();
1080
+ }
1081
+ function bindPointerCapture(element, pointerId) {
1082
+ if (typeof element.setPointerCapture !== "function") return null;
1083
+ try {
1084
+ element.setPointerCapture(pointerId);
1085
+ } catch {
1086
+ return null;
1087
+ }
1088
+ return element;
1089
+ }
1090
+ function pointerDown(index, event) {
1091
+ const handle = findReorderHandle(event);
1092
+ if (cleaned || !canReorder() || activePointer || event.button !== 0 || event.isPrimary === false || !handle) return;
1093
+ event.preventDefault();
1094
+ const captureElement = bindPointerCapture(handle, event.pointerId);
1095
+ activePointer = {
1096
+ fromIndex: index,
1097
+ pointerId: event.pointerId,
1098
+ captureElement,
1099
+ scrollElement: handle
1100
+ };
1101
+ insertionIndex = index;
1102
+ pointerOverReorderArea = true;
1103
+ window.addEventListener("pointermove", handleWindowPointerMove, { passive: false });
1104
+ window.addEventListener("pointerup", handleWindowPointerUp);
1105
+ window.addEventListener("pointercancel", handleWindowPointerCancel);
1106
+ emitChange();
1107
+ }
1108
+ function cleanup() {
1109
+ if (cleaned) return;
1110
+ cleaned = true;
1111
+ stop();
1112
+ autoScroller?.cleanup();
1113
+ }
1114
+ return {
1115
+ pointerDown,
1116
+ getState: currentState,
1117
+ isDragging: () => activePointer !== null,
1118
+ cleanup
1119
+ };
1120
+ }
1121
+ //#endregion
1122
+ //#region src/focus.ts
1123
+ function isDisabledElement(element) {
1124
+ return "disabled" in element && element.disabled === true;
1125
+ }
1126
+ function focusFirstEnabledElement(elements) {
1127
+ const control = elements.find((candidate) => candidate && !isDisabledElement(candidate));
1128
+ if (control) {
1129
+ control.focus();
1130
+ return true;
1131
+ }
1132
+ return false;
1133
+ }
1134
+ //#endregion
398
1135
  //#region src/position.ts
399
1136
  var ANCHOR_CLASS_PREFIX = "iui-anchor-";
400
1137
  var _supportsAnchor = null;
1138
+ var _supportsTopLayerAnchor = null;
1139
+ var _supportsTopLayerAnchorSizing = null;
401
1140
  function supportsAnchorPositioning() {
402
- if (_supportsAnchor === null) _supportsAnchor = typeof CSS !== "undefined" && typeof CSS.supports === "function" && CSS.supports("anchor-name", "--a");
1141
+ 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)");
403
1142
  return _supportsAnchor;
404
1143
  }
1144
+ function supportsTopLayerAnchorPositioning() {
1145
+ if (_supportsTopLayerAnchor === null) _supportsTopLayerAnchor = supportsAnchorPositioning() && CSS.supports("width", "anchor-size(width)");
1146
+ return _supportsTopLayerAnchor;
1147
+ }
1148
+ function supportsTopLayerAnchorSizing() {
1149
+ if (_supportsTopLayerAnchorSizing === null) _supportsTopLayerAnchorSizing = supportsTopLayerAnchorPositioning() && CSS.supports("height", "max-content") && CSS.supports("max-height", "stretch");
1150
+ return _supportsTopLayerAnchorSizing;
1151
+ }
405
1152
  function isRtl$1() {
406
1153
  return typeof document !== "undefined" && document.documentElement.dir === "rtl";
407
1154
  }
@@ -421,6 +1168,66 @@ function getOppositePlacement(placement) {
421
1168
  "right-end": "left-end"
422
1169
  }[placement] || placement;
423
1170
  }
1171
+ function getViewportRect() {
1172
+ const visualViewport = window.visualViewport;
1173
+ if (visualViewport) return {
1174
+ top: visualViewport.offsetTop,
1175
+ right: visualViewport.offsetLeft + visualViewport.width,
1176
+ bottom: visualViewport.offsetTop + visualViewport.height,
1177
+ left: visualViewport.offsetLeft,
1178
+ width: visualViewport.width,
1179
+ height: visualViewport.height
1180
+ };
1181
+ return {
1182
+ top: 0,
1183
+ right: window.innerWidth,
1184
+ bottom: window.innerHeight,
1185
+ left: 0,
1186
+ width: window.innerWidth,
1187
+ height: window.innerHeight
1188
+ };
1189
+ }
1190
+ function clamp$1(value, min, max) {
1191
+ if (max < min) return min;
1192
+ return Math.max(min, Math.min(value, max));
1193
+ }
1194
+ function clampTopLayerCoordinates(x, y, floatingRect, placement, viewport, margin) {
1195
+ const [side] = placement.split("-");
1196
+ const minX = viewport.left + margin;
1197
+ const maxX = viewport.right - floatingRect.width - margin;
1198
+ const minY = viewport.top + margin;
1199
+ const maxY = viewport.bottom - floatingRect.height - margin;
1200
+ if (side === "top" || side === "bottom") return {
1201
+ x: clamp$1(x, minX, maxX),
1202
+ y
1203
+ };
1204
+ if (side === "left" || side === "right") return {
1205
+ x,
1206
+ y: clamp$1(y, minY, maxY)
1207
+ };
1208
+ return {
1209
+ x: clamp$1(x, minX, maxX),
1210
+ y: clamp$1(y, minY, maxY)
1211
+ };
1212
+ }
1213
+ function getAvailableSpace(referenceRect, viewport, side, offset, margin) {
1214
+ if (side === "top") return referenceRect.top - viewport.top - offset - margin;
1215
+ if (side === "bottom") return viewport.bottom - referenceRect.bottom - offset - margin;
1216
+ if (side === "left") return referenceRect.left - viewport.left - offset - margin;
1217
+ if (side === "right") return viewport.right - referenceRect.right - offset - margin;
1218
+ return viewport.height - margin * 2;
1219
+ }
1220
+ function resolveTopLayerPlacement(preferredPlacement, referenceRect, floatingSize, viewport, offset, margin, flip) {
1221
+ if (!flip) return preferredPlacement;
1222
+ const [side] = preferredPlacement.split("-");
1223
+ const oppositePlacement = getOppositePlacement(preferredPlacement);
1224
+ const [oppositeSide] = oppositePlacement.split("-");
1225
+ const floatingLength = side === "left" || side === "right" ? floatingSize.width : floatingSize.height;
1226
+ const preferredSpace = getAvailableSpace(referenceRect, viewport, side, offset, margin);
1227
+ const oppositeSpace = getAvailableSpace(referenceRect, viewport, oppositeSide, offset, margin);
1228
+ if (floatingLength > preferredSpace && oppositeSpace > preferredSpace) return oppositePlacement;
1229
+ return preferredPlacement;
1230
+ }
424
1231
  function computePositionFromRect(refRect, floatingRect, placement, offset) {
425
1232
  let x = 0;
426
1233
  let y = 0;
@@ -525,6 +1332,14 @@ function ensureAnchorStylesheet() {
525
1332
  function findAnchorClass(element) {
526
1333
  return Array.from(element.classList).find((c) => c.startsWith(ANCHOR_CLASS_PREFIX));
527
1334
  }
1335
+ function removeAnchorRule(className) {
1336
+ const style = document.getElementById(anchorStyleId);
1337
+ if (!style?.sheet) return;
1338
+ for (let i = 0; i < style.sheet.cssRules.length; i++) if (style.sheet.cssRules[i].selectorText === `.${className}`) {
1339
+ style.sheet.deleteRule(i);
1340
+ return;
1341
+ }
1342
+ }
528
1343
  function setupAnchorPositioning(reference, floating, placement, offset, flip) {
529
1344
  const id = generateId(ANCHOR_CLASS_PREFIX);
530
1345
  const anchorName = `--${id}`;
@@ -587,13 +1402,94 @@ function cleanupAnchorPositioning(reference, floating, className) {
587
1402
  floating.style.positionAnchor = "";
588
1403
  floating.style.position = "";
589
1404
  floating.classList.remove(className);
590
- const style = document.getElementById(anchorStyleId);
591
- if (style?.sheet) {
592
- for (let i = 0; i < style.sheet.cssRules.length; i++) if (style.sheet.cssRules[i].selectorText === `.${className}`) {
593
- style.sheet.deleteRule(i);
1405
+ removeAnchorRule(className);
1406
+ }
1407
+ function detachAnchorPositioning(reference, floating) {
1408
+ reference.style.removeProperty("anchor-name");
1409
+ floating.style.removeProperty("position-anchor");
1410
+ for (const className of Array.from(floating.classList)) if (className.startsWith(ANCHOR_CLASS_PREFIX)) {
1411
+ floating.classList.remove(className);
1412
+ removeAnchorRule(className);
1413
+ }
1414
+ }
1415
+ function getAnchorPositionRules(placement, offset) {
1416
+ const [side, alignment] = placement.split("-");
1417
+ let positionRules = "";
1418
+ switch (side) {
1419
+ case "bottom":
1420
+ positionRules += `top: anchor(bottom);`;
1421
+ positionRules += `margin-top: ${offset}px;`;
1422
+ break;
1423
+ case "top":
1424
+ positionRules += `bottom: anchor(top);`;
1425
+ positionRules += `margin-bottom: ${offset}px;`;
1426
+ break;
1427
+ case "left":
1428
+ positionRules += `right: anchor(left);`;
1429
+ positionRules += `margin-right: ${offset}px;`;
1430
+ break;
1431
+ case "right":
1432
+ positionRules += `left: anchor(right);`;
1433
+ positionRules += `margin-left: ${offset}px;`;
1434
+ break;
1435
+ }
1436
+ if (side === "bottom" || side === "top") switch (alignment) {
1437
+ case "start":
1438
+ positionRules += `left: anchor(left);`;
1439
+ break;
1440
+ case "end":
1441
+ positionRules += `right: anchor(right);`;
1442
+ break;
1443
+ default:
1444
+ positionRules += `left: anchor(center); translate: -50% 0;`;
1445
+ break;
1446
+ }
1447
+ else switch (alignment) {
1448
+ case "start":
1449
+ positionRules += `top: anchor(top);`;
1450
+ break;
1451
+ case "end":
1452
+ positionRules += `bottom: anchor(bottom);`;
1453
+ break;
1454
+ default:
1455
+ positionRules += `top: anchor(center); translate: 0 -50%;`;
594
1456
  break;
595
- }
596
1457
  }
1458
+ return positionRules;
1459
+ }
1460
+ function getTopLayerAnchorSizingRules(placement, viewportMargin) {
1461
+ const [side] = placement.split("-");
1462
+ if (side === "bottom") return `bottom: ${viewportMargin}px; height: max-content; max-height: stretch;`;
1463
+ if (side === "top") return `top: ${viewportMargin}px; height: max-content; max-height: stretch; align-self: end;`;
1464
+ return "";
1465
+ }
1466
+ function setupTopLayerAnchorPositioning(reference, floating, placement, offset, matchReferenceWidth, maxWidth, viewportMargin, stretchToAvailableHeight) {
1467
+ const existingClass = findAnchorClass(floating);
1468
+ const existingAnchorName = existingClass ? `--${existingClass}` : "";
1469
+ const canReuseAnchor = !!existingClass && reference.style.getPropertyValue("anchor-name") === existingAnchorName && floating.style.getPropertyValue("position-anchor") === existingAnchorName;
1470
+ const className = canReuseAnchor ? existingClass : generateId(ANCHOR_CLASS_PREFIX);
1471
+ const anchorName = `--${className}`;
1472
+ const sheet = ensureAnchorStylesheet();
1473
+ if (canReuseAnchor) removeAnchorRule(className);
1474
+ else detachAnchorPositioning(reference, floating);
1475
+ reference.style.anchorName = anchorName;
1476
+ floating.style.positionAnchor = anchorName;
1477
+ floating.style.removeProperty("inset");
1478
+ floating.style.removeProperty("top");
1479
+ floating.style.removeProperty("right");
1480
+ floating.style.removeProperty("bottom");
1481
+ floating.style.removeProperty("left");
1482
+ floating.style.removeProperty("margin");
1483
+ floating.style.position = "fixed";
1484
+ if (stretchToAvailableHeight) {
1485
+ floating.style.height = "max-content";
1486
+ floating.style.removeProperty("max-height");
1487
+ } else floating.style.removeProperty("height");
1488
+ if (matchReferenceWidth) floating.style.width = `min(anchor-size(width), ${maxWidth}px)`;
1489
+ const rule = `.${className} { position: fixed; inset: auto; margin: 0; ${getAnchorPositionRules(placement, offset)} ${matchReferenceWidth ? `width: min(anchor-size(width), ${maxWidth}px);` : ""} ${stretchToAvailableHeight ? getTopLayerAnchorSizingRules(placement, viewportMargin) : ""} }`;
1490
+ sheet.insertRule(rule, sheet.cssRules.length);
1491
+ floating.classList.add(className);
1492
+ return className;
597
1493
  }
598
1494
  var SIZE_MARGIN = 8;
599
1495
  /**
@@ -671,6 +1567,181 @@ function autoUpdate(reference, floating, update) {
671
1567
  if (anchorClass) cleanupAnchorPositioning(reference, floating, anchorClass);
672
1568
  };
673
1569
  }
1570
+ function positionTopLayerPopover(reference, floating, options = {}) {
1571
+ const { placement = "bottom-start", offset = 4, flip = true, matchReferenceWidth = false, viewportMargin = 8, anchorPositioning = true } = options;
1572
+ const viewport = getViewportRect();
1573
+ const maxWidth = Math.max(0, Math.floor(viewport.width - viewportMargin * 2));
1574
+ floating.style.position = "fixed";
1575
+ floating.style.boxSizing = "border-box";
1576
+ floating.style.maxWidth = `${maxWidth}px`;
1577
+ floating.style.overflowX = "auto";
1578
+ floating.style.overflowY = "auto";
1579
+ floating.style.overscrollBehavior = "contain";
1580
+ const referenceRect = reference.getBoundingClientRect();
1581
+ const viewportHeight = Math.max(0, Math.floor(viewport.height - viewportMargin * 2));
1582
+ if (anchorPositioning && supportsTopLayerAnchorPositioning()) {
1583
+ if (matchReferenceWidth) floating.style.width = `${Math.min(referenceRect.width, maxWidth)}px`;
1584
+ const measuredRect = floating.getBoundingClientRect();
1585
+ const resolvedPlacement = resolveTopLayerPlacement(placement, referenceRect, {
1586
+ width: Math.max(measuredRect.width, floating.scrollWidth),
1587
+ height: Math.max(measuredRect.height, floating.scrollHeight)
1588
+ }, viewport, offset, viewportMargin, flip);
1589
+ const [resolvedSide] = resolvedPlacement.split("-");
1590
+ const stretchToAvailableHeight = (resolvedSide === "top" || resolvedSide === "bottom") && supportsTopLayerAnchorSizing();
1591
+ if (stretchToAvailableHeight) floating.style.removeProperty("max-height");
1592
+ else {
1593
+ const availableHeight = resolvedSide === "top" || resolvedSide === "bottom" ? Math.min(viewportHeight, Math.max(0, Math.floor(getAvailableSpace(referenceRect, viewport, resolvedSide, offset, viewportMargin)))) : viewportHeight;
1594
+ floating.style.maxHeight = `${availableHeight}px`;
1595
+ }
1596
+ setupTopLayerAnchorPositioning(reference, floating, resolvedPlacement, offset, matchReferenceWidth, maxWidth, viewportMargin, stretchToAvailableHeight);
1597
+ const finalRect = floating.getBoundingClientRect();
1598
+ return {
1599
+ x: finalRect.left,
1600
+ y: finalRect.top,
1601
+ placement: resolvedPlacement
1602
+ };
1603
+ }
1604
+ detachAnchorPositioning(reference, floating);
1605
+ floating.style.inset = "auto";
1606
+ floating.style.right = "auto";
1607
+ floating.style.bottom = "auto";
1608
+ floating.style.margin = "0";
1609
+ floating.style.removeProperty("height");
1610
+ if (matchReferenceWidth) floating.style.width = `${Math.min(referenceRect.width, maxWidth)}px`;
1611
+ const measuredRect = floating.getBoundingClientRect();
1612
+ const resolvedPlacement = resolveTopLayerPlacement(placement, referenceRect, {
1613
+ width: Math.max(measuredRect.width, floating.scrollWidth),
1614
+ height: Math.max(measuredRect.height, floating.scrollHeight)
1615
+ }, viewport, offset, viewportMargin, flip);
1616
+ const [resolvedSide] = resolvedPlacement.split("-");
1617
+ const availableHeight = Math.min(viewportHeight, Math.max(0, Math.floor(getAvailableSpace(referenceRect, viewport, resolvedSide, offset, viewportMargin))));
1618
+ if (resolvedSide === "top" || resolvedSide === "bottom") floating.style.maxHeight = `${availableHeight}px`;
1619
+ else floating.style.maxHeight = `${viewportHeight}px`;
1620
+ const floatingRect = floating.getBoundingClientRect();
1621
+ const coordinates = computePositionFromRect(referenceRect, floatingRect, resolvedPlacement, offset);
1622
+ const { x, y } = clampTopLayerCoordinates(coordinates.x, coordinates.y, floatingRect, resolvedPlacement, viewport, viewportMargin);
1623
+ floating.style.left = `${Math.round(x)}px`;
1624
+ floating.style.top = `${Math.round(y)}px`;
1625
+ return {
1626
+ x,
1627
+ y,
1628
+ placement: resolvedPlacement
1629
+ };
1630
+ }
1631
+ function autoUpdateTopLayerPopover(reference, floating, update) {
1632
+ const cleanupAutoUpdate = autoUpdate(reference, floating, update);
1633
+ const visualViewport = window.visualViewport;
1634
+ let rafId = null;
1635
+ const scheduleUpdate = () => {
1636
+ if (rafId !== null) return;
1637
+ rafId = requestAnimationFrame(() => {
1638
+ rafId = null;
1639
+ update();
1640
+ });
1641
+ };
1642
+ visualViewport?.addEventListener("resize", scheduleUpdate);
1643
+ visualViewport?.addEventListener("scroll", scheduleUpdate);
1644
+ return () => {
1645
+ cleanupAutoUpdate();
1646
+ if (rafId !== null) {
1647
+ cancelAnimationFrame(rafId);
1648
+ rafId = null;
1649
+ }
1650
+ visualViewport?.removeEventListener("resize", scheduleUpdate);
1651
+ visualViewport?.removeEventListener("scroll", scheduleUpdate);
1652
+ };
1653
+ }
1654
+ //#endregion
1655
+ //#region src/nativePopover.ts
1656
+ function createNativePopoverDisclosure(options) {
1657
+ let isOpen = false;
1658
+ let autoUpdateCleanup = null;
1659
+ const focusOutDismiss = options.focusOut ? createFocusOutDismiss(options.focusOut) : null;
1660
+ const setOpen = (open) => {
1661
+ if (isOpen === open) return;
1662
+ isOpen = open;
1663
+ options.onOpenChange?.(open);
1664
+ };
1665
+ const cleanupAutoUpdate = () => {
1666
+ autoUpdateCleanup?.();
1667
+ autoUpdateCleanup = null;
1668
+ };
1669
+ const getElements = () => {
1670
+ if (options.enabled?.() === false) return null;
1671
+ const reference = options.reference();
1672
+ const popover = options.popover();
1673
+ if (!reference || !popover) return null;
1674
+ return {
1675
+ reference,
1676
+ popover
1677
+ };
1678
+ };
1679
+ const updatePosition = () => {
1680
+ const elements = getElements();
1681
+ if (!elements) return;
1682
+ positionTopLayerPopover(elements.reference, elements.popover, options.position);
1683
+ };
1684
+ const startAutoUpdate = () => {
1685
+ cleanupAutoUpdate();
1686
+ const elements = getElements();
1687
+ if (!elements) return;
1688
+ autoUpdateCleanup = autoUpdateTopLayerPopover(elements.reference, elements.popover, updatePosition);
1689
+ };
1690
+ const showPopover = () => {
1691
+ options.popover()?.showPopover();
1692
+ };
1693
+ const hidePopover = () => {
1694
+ options.popover()?.hidePopover();
1695
+ };
1696
+ const openPopover = (openOptions = {}) => {
1697
+ focusOutDismiss?.markOpen();
1698
+ openOptions.onBeforeOpen?.();
1699
+ setOpen(true);
1700
+ };
1701
+ const closePopover = (closeOptions = {}) => {
1702
+ if (!isOpen) return false;
1703
+ focusOutDismiss?.cancel();
1704
+ setOpen(false);
1705
+ closeOptions.onClose?.();
1706
+ if (closeOptions.hide !== false) hidePopover();
1707
+ cleanupAutoUpdate();
1708
+ return true;
1709
+ };
1710
+ const togglePopover = (open, close) => {
1711
+ if (isOpen) close();
1712
+ else open();
1713
+ };
1714
+ const handlePopoverToggle = (event, toggleOptions = {}) => {
1715
+ if (event.newState !== "closed" || !isOpen) return false;
1716
+ focusOutDismiss?.cancel();
1717
+ setOpen(false);
1718
+ toggleOptions.onClose?.();
1719
+ cleanupAutoUpdate();
1720
+ return true;
1721
+ };
1722
+ const handleFocusOut = (event) => {
1723
+ focusOutDismiss?.schedule(event);
1724
+ };
1725
+ const cleanupPopover = () => {
1726
+ focusOutDismiss?.cleanup();
1727
+ cleanupAutoUpdate();
1728
+ };
1729
+ return {
1730
+ get isOpen() {
1731
+ return isOpen;
1732
+ },
1733
+ openPopover,
1734
+ closePopover,
1735
+ togglePopover,
1736
+ showPopover,
1737
+ hidePopover,
1738
+ handlePopoverToggle,
1739
+ handleFocusOut,
1740
+ updatePosition,
1741
+ startAutoUpdate,
1742
+ cleanupPopover
1743
+ };
1744
+ }
674
1745
  //#endregion
675
1746
  //#region src/blank.ts
676
1747
  /**
@@ -702,6 +1773,31 @@ function debounce(fn) {
702
1773
  };
703
1774
  }
704
1775
  /**
1776
+ * Create a {@link Debouncer} with a fixed delay.
1777
+ *
1778
+ * @param delay - Milliseconds to wait after the latest `schedule()` call.
1779
+ */
1780
+ function createDebouncer(delay) {
1781
+ let timer = null;
1782
+ const cancel = () => {
1783
+ if (timer !== null) {
1784
+ clearTimeout(timer);
1785
+ timer = null;
1786
+ }
1787
+ };
1788
+ const schedule = (fn) => {
1789
+ cancel();
1790
+ timer = setTimeout(() => {
1791
+ timer = null;
1792
+ fn();
1793
+ }, delay);
1794
+ };
1795
+ return {
1796
+ schedule,
1797
+ cancel
1798
+ };
1799
+ }
1800
+ /**
705
1801
  * Detect the browser's current framerate.
706
1802
  * Returns a Promise that resolves with the detected FPS (capped to 30–240 range).
707
1803
  * Falls back to 60 if requestAnimationFrame is unavailable or detection times out.
@@ -855,5 +1951,187 @@ function hslToHex(h, s, l) {
855
1951
  };
856
1952
  return `#${toHex(r)}${toHex(g)}${toHex(b)}`;
857
1953
  }
1954
+ var clamp = (number, min, max) => Math.min(max, Math.max(min, number));
1955
+ /**
1956
+ * Normalize a hue to an integer in the range 0-359, wrapping negatives and overflow.
1957
+ */
1958
+ function normalizeHue(number) {
1959
+ return (Math.round(number) % 360 + 360) % 360;
1960
+ }
1961
+ /**
1962
+ * Clamp and round a percentage value to an integer in the range 0-100.
1963
+ */
1964
+ function normalizePercent(number) {
1965
+ return clamp(Math.round(number), 0, 100);
1966
+ }
1967
+ /**
1968
+ * Clamp an alpha value to the range 0-1. Non-finite input falls back to 1.
1969
+ */
1970
+ function normalizeAlpha(number) {
1971
+ return clamp(Number.isFinite(number) ? number : 1, 0, 1);
1972
+ }
1973
+ /**
1974
+ * Format an alpha value as a compact decimal string (e.g. `0.5`, `1`),
1975
+ * dropping trailing zeros.
1976
+ */
1977
+ function formatAlpha(number) {
1978
+ return normalizeAlpha(number).toFixed(2).replace(/0+$/, "").replace(/\.$/, "");
1979
+ }
1980
+ /**
1981
+ * Convert a hex color string to RGB channels.
1982
+ * Accepts any input understood by {@link parseHexColor}; falls back to black on invalid input.
1983
+ */
1984
+ function hexToRgb(hex) {
1985
+ const normalized = parseHexColor(hex)?.hex ?? "#000000";
1986
+ return {
1987
+ r: parseInt(normalized.slice(1, 3), 16),
1988
+ g: parseInt(normalized.slice(3, 5), 16),
1989
+ b: parseInt(normalized.slice(5, 7), 16)
1990
+ };
1991
+ }
1992
+ /**
1993
+ * Convert RGB channels to a lowercase 6-digit hex string with a leading '#'.
1994
+ * Channels are clamped to 0-255.
1995
+ */
1996
+ function rgbToHex(r, g, b) {
1997
+ return `#${[
1998
+ r,
1999
+ g,
2000
+ b
2001
+ ].map((channel) => clamp(Math.round(channel), 0, 255).toString(16).padStart(2, "0")).join("")}`;
2002
+ }
2003
+ /**
2004
+ * Parse an alpha channel from a raw string as found in rgba()/hsla() notation.
2005
+ *
2006
+ * - `undefined` or empty means "no alpha specified" and returns 1
2007
+ * - Percentages (`50%`) must be within 0-100
2008
+ * - Decimals must be within 0-1
2009
+ * - Returns `null` for out-of-range or non-numeric input
2010
+ */
2011
+ function parseAlphaChannel(rawAlpha) {
2012
+ if (rawAlpha === void 0 || rawAlpha.trim() === "") return 1;
2013
+ const trimmed = rawAlpha.trim();
2014
+ const number = Number.parseFloat(trimmed);
2015
+ if (!Number.isFinite(number)) return null;
2016
+ if (trimmed.endsWith("%")) {
2017
+ if (number < 0 || number > 100) return null;
2018
+ return normalizeAlpha(number / 100);
2019
+ }
2020
+ if (number < 0 || number > 1) return null;
2021
+ return normalizeAlpha(number);
2022
+ }
2023
+ /**
2024
+ * Parse a single RGB channel from a raw string.
2025
+ *
2026
+ * - Percentages (`50%`) map 0-100 onto 0-255
2027
+ * - Numbers must be within 0-255
2028
+ * - Returns `null` for out-of-range or non-numeric input
2029
+ */
2030
+ function parseRgbChannel(rawChannel) {
2031
+ const trimmed = rawChannel.trim();
2032
+ const number = Number.parseFloat(trimmed);
2033
+ if (!Number.isFinite(number)) return null;
2034
+ if (trimmed.endsWith("%")) {
2035
+ if (number < 0 || number > 100) return null;
2036
+ return clamp(Math.round(number / 100 * 255), 0, 255);
2037
+ }
2038
+ if (number < 0 || number > 255) return null;
2039
+ return clamp(Math.round(number), 0, 255);
2040
+ }
2041
+ /**
2042
+ * Build a {@link ParsedColor} from a 6-digit hex string and optional alpha (0-1).
2043
+ */
2044
+ function parsedFromHex(hex, alphaValue = 1) {
2045
+ const hsl = hexToHsl(hex);
2046
+ return {
2047
+ hex: hex.toLowerCase(),
2048
+ h: normalizeHue(hsl.h),
2049
+ s: normalizePercent(hsl.s),
2050
+ l: normalizePercent(hsl.l),
2051
+ alpha: normalizeAlpha(alphaValue)
2052
+ };
2053
+ }
2054
+ /**
2055
+ * Parse a hex color string into a {@link ParsedColor}.
2056
+ *
2057
+ * Accepts 3, 4, 6, or 8 digit hex, with or without a leading '#'.
2058
+ * 4/8 digit forms carry an alpha channel. Returns `null` on invalid input.
2059
+ */
2060
+ function parseHexColor(input) {
2061
+ const trimmed = input.trim();
2062
+ const match = /^#?([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i.exec(trimmed);
2063
+ if (!match) return null;
2064
+ const raw = match[1];
2065
+ const expanded = raw.length === 3 || raw.length === 4 ? raw.split("").map((char) => char + char).join("") : raw;
2066
+ const hex = `#${expanded.slice(0, 6)}`;
2067
+ const alphaHex = expanded.length === 8 ? expanded.slice(6, 8) : null;
2068
+ return parsedFromHex(hex, alphaHex ? parseInt(alphaHex, 16) / 255 : 1);
2069
+ }
2070
+ /**
2071
+ * Parse an `rgb()`/`rgba()` color string into a {@link ParsedColor}.
2072
+ * Channels may be numeric (0-255) or percentages. Returns `null` on invalid input.
2073
+ */
2074
+ function parseRgbColor(input) {
2075
+ const match = /^rgba?\(\s*([+-]?\d*\.?\d+%?)\s*,\s*([+-]?\d*\.?\d+%?)\s*,\s*([+-]?\d*\.?\d+%?)(?:\s*,\s*([+-]?\d*\.?\d+%?))?\s*\)$/i.exec(input.trim());
2076
+ if (!match) return null;
2077
+ const r = parseRgbChannel(match[1]);
2078
+ const g = parseRgbChannel(match[2]);
2079
+ const b = parseRgbChannel(match[3]);
2080
+ const alphaValue = parseAlphaChannel(match[4]);
2081
+ if (r === null || g === null || b === null || alphaValue === null) return null;
2082
+ return parsedFromHex(rgbToHex(r, g, b), alphaValue);
2083
+ }
2084
+ /**
2085
+ * Parse an `hsl()`/`hsla()` color string into a {@link ParsedColor}.
2086
+ * Saturation and lightness must be percentages within 0-100. Returns `null` on invalid input.
2087
+ */
2088
+ function parseHslColor(input) {
2089
+ const match = /^hsla?\(\s*([+-]?\d*\.?\d+)\s*,\s*([+-]?\d*\.?\d+)%\s*,\s*([+-]?\d*\.?\d+)%(?:\s*,\s*([+-]?\d*\.?\d+%?))?\s*\)$/i.exec(input.trim());
2090
+ if (!match) return null;
2091
+ const h = normalizeHue(Number.parseFloat(match[1]));
2092
+ const s = Number.parseFloat(match[2]);
2093
+ const l = Number.parseFloat(match[3]);
2094
+ const alphaValue = parseAlphaChannel(match[4]);
2095
+ if (!Number.isFinite(s) || !Number.isFinite(l) || s < 0 || s > 100 || l < 0 || l > 100 || alphaValue === null) return null;
2096
+ return {
2097
+ hex: hslToHex(h, s, l).toLowerCase(),
2098
+ h,
2099
+ s: normalizePercent(s),
2100
+ l: normalizePercent(l),
2101
+ alpha: alphaValue
2102
+ };
2103
+ }
2104
+ /**
2105
+ * Parse any supported color string (hex, rgb/rgba, hsl/hsla) into a {@link ParsedColor}.
2106
+ * Returns `null` for empty or unrecognized input.
2107
+ */
2108
+ function parseColorString(input) {
2109
+ if (!input) return null;
2110
+ return parseHexColor(input) ?? parseRgbColor(input) ?? parseHslColor(input);
2111
+ }
2112
+ /**
2113
+ * Format a {@link ParsedColor} as a `hex`, `rgb`, or `hsl` string.
2114
+ *
2115
+ * By default the alpha channel is only included when the color is partially
2116
+ * transparent (`alpha < 1`); override with {@link FormatColorOptions.includeAlpha}.
2117
+ * Returned values are stable and normalized (hex is lowercase); callers may
2118
+ * uppercase for display.
2119
+ */
2120
+ function formatColor(color, format = "hex", options = {}) {
2121
+ const normalized = {
2122
+ hex: color.hex,
2123
+ h: normalizeHue(color.h),
2124
+ s: normalizePercent(color.s),
2125
+ l: normalizePercent(color.l),
2126
+ alpha: normalizeAlpha(color.alpha)
2127
+ };
2128
+ const includeAlpha = options.includeAlpha ?? normalized.alpha < 1;
2129
+ if (format === "rgb") {
2130
+ const { r, g, b } = hexToRgb(normalized.hex);
2131
+ return includeAlpha ? `rgba(${r}, ${g}, ${b}, ${formatAlpha(normalized.alpha)})` : `rgb(${r}, ${g}, ${b})`;
2132
+ }
2133
+ if (format === "hsl") return includeAlpha ? `hsla(${normalized.h}, ${normalized.s}%, ${normalized.l}%, ${formatAlpha(normalized.alpha)})` : `hsl(${normalized.h}, ${normalized.s}%, ${normalized.l}%)`;
2134
+ return includeAlpha ? `${normalized.hex}${Math.round(normalized.alpha * 255).toString(16).padStart(2, "0")}` : normalized.hex;
2135
+ }
858
2136
  //#endregion
859
- export { animate, autoUpdate, blank, cancelAnimations, computePosition, createFocusTrap, createMenuNavigation, debounce, detectFramerate, easings, except, generateId, hexToHsl, hslToHex, isRtl, isStandardDomEvent, kebabCase, lockScroll, markAriaHidden, onClickOutside, onEscapeKey, onRtlChange, onceChildrenRendered, only, prefersDarkMode, rejectNullValues, sameUrlPath, supportsAnchorPositioning };
2137
+ export { REORDERABLE_LIST_HANDLE_ATTRIBUTE, animate, autoUpdate, autoUpdateTopLayerPopover, blank, cancelAnimations, computePosition, createDebouncer, createFocusOutDismiss, createFocusTrap, createMenuNavigation, createNativePopoverDisclosure, 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, rejectNullValues, resolveListboxNavigation, rgbToHex, sameUrlPath, supportsAnchorPositioning, supportsTopLayerAnchorPositioning };