@inertiaui/vanilla 1.3.0 → 1.4.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/README.md CHANGED
@@ -282,6 +282,7 @@ cleanup()
282
282
  | `orientation` | `'vertical' \| 'horizontal'` | `'vertical'` | Arrow key direction |
283
283
  | `loop` | `boolean` | `true` | Wrap focus from last to first item |
284
284
  | `typeAhead` | `boolean` | `true` | Enable type-ahead character search |
285
+ | `initialFocus` | `'first' \| 'last'` | `'first'` | Initial enabled item to focus and give the active tab stop |
285
286
  | `onActivate` | `(item: HTMLElement) => void` | `undefined` | Called when an item is activated via Enter or Space |
286
287
 
287
288
  ### Keyboard Support
@@ -687,6 +688,75 @@ function setupTooltip(trigger: HTMLElement, tooltip: HTMLElement) {
687
688
 
688
689
  ## Native Popovers
689
690
 
691
+ ### Managed popovers and menus
692
+
693
+ `createPopoverController` composes the disclosure, positioning, dismissal, and menu helpers into a framework-independent lifecycle. It supports native auto popovers and a positioned fallback. The existing `createNativePopoverDisclosure` API below remains available for consumers that need to manage each step themselves.
694
+
695
+ ```html
696
+ <button id="trigger" aria-haspopup="menu" aria-expanded="false" aria-controls="menu">Actions</button>
697
+ <div id="menu" role="menu" hidden>
698
+ <button role="menuitem">Edit</button>
699
+ <button role="menuitem">Archive</button>
700
+ </div>
701
+ ```
702
+
703
+ ```typescript
704
+ import { createPopoverController } from '@inertiaui/vanilla'
705
+
706
+ const trigger = document.querySelector<HTMLElement>('#trigger')!
707
+ const menu = document.querySelector<HTMLElement>('#menu')!
708
+ const controller = createPopoverController({
709
+ reference: () => trigger,
710
+ popover: () => menu,
711
+ position: { placement: 'bottom-start', offset: 8 },
712
+ menu: true,
713
+ onOpenChange(open) {
714
+ trigger.setAttribute('aria-expanded', String(open))
715
+ menu.hidden = !open
716
+ if (open) queueMicrotask(() => controller.mount())
717
+ },
718
+ })
719
+
720
+ if (controller.native) menu.setAttribute('popover', 'auto')
721
+ trigger.addEventListener('pointerdown', controller.onPointerDown)
722
+ trigger.addEventListener('click', controller.toggle)
723
+ trigger.addEventListener('keydown', controller.onKeydown)
724
+ trigger.addEventListener('focusout', controller.onFocusOut)
725
+
726
+ // On disposal, also remove the four trigger listeners if the trigger remains in the DOM.
727
+ // The caller owns rendering and removing the panel.
728
+ controller.cleanup()
729
+ ```
730
+
731
+ In Vue, call `mount()` after the open panel has rendered with `nextTick()`. In React, call it from a layout effect and return `cleanup()` from that effect. Cleanup preserves logical open state so an effect can safely clean up and remount. It hides the native panel and removes the controller's listeners, timers, positioning observers, menu navigation, and mount-hook resources. Use `close()` for a state change and a close notification.
732
+
733
+ Keep native panels in their original DOM ancestry: the browser places them in the top layer without losing CSS inheritance. Fallback panels need a suitable DOM container; inside a modal dialog, keep them within that dialog. The controller does not move elements, assign classes, copy theme tokens, or animate. Set the panel's `role`, trigger ARIA attributes, and `popover="auto"` when `native` is true. Without `menu: true`, callers choose initial panel focus through `onOpened`.
734
+
735
+ | Option | Description |
736
+ |--------|-------------|
737
+ | `reference`, `popover` | Getters returning the current elements or `null` while unmounted |
738
+ | `position` | `TopLayerPopoverPositionOptions`; getters can supply current placement and offset |
739
+ | `menu` | Enables menu navigation, ArrowDown/ArrowUp opening, and closing after a menu-item click |
740
+ | `onOpenChange(open)` | Updates the framework's rendering state |
741
+ | `onMount({ reference, popover, native })` | Applies consumer behavior after positioning; may return a cleanup function |
742
+ | `onOpened()` | Runs after the panel is mounted and its handlers are installed |
743
+ | `onClosed()` | Runs when explicitly closed or dismissed; cleanup alone does not call it |
744
+
745
+ The controller resolves top/bottom `start` and `end` placement against the reference element's computed direction, including local RTL scopes. It follows scrolling and resizing, constrains panels to the viewport, restores trigger focus on Escape, and preserves focus when the user moves to another control. Menu clicks finish bubbling before dismissal, allowing framework-delegated item handlers to run. ArrowUp opens at the last enabled item with a matching roving tab stop.
746
+
747
+ | Controller member | Description |
748
+ |-------------------|-------------|
749
+ | `native`, `isOpen` | Read-only native support and current logical open state |
750
+ | `open()`, `close(restoreFocus?)` | Change open state; `close()` normally restores focus only when focus is inside the panel or on the body |
751
+ | `toggle(event?)` | Toggles state; pass the click event together with the pointerdown handler to avoid reopening after native light dismissal |
752
+ | `mount()` | Attaches behavior after rendering the open panel |
753
+ | `cleanup()` | Detaches behavior without changing logical open state |
754
+ | `onPointerDown`, `onKeydown`, `onFocusOut` | Handlers to bind to the trigger |
755
+
756
+ Consumer-specific theme or animation behavior can live in `onMount`. Return its cleanup so it also runs when a panel is dismissed, unmounted, or remounted. Use `prefersReducedMotion()` before starting consumer animations.
757
+
758
+ ### Low-level native disclosure
759
+
690
760
  `createNativePopoverDisclosure` coordinates open state, native `showPopover()`/`hidePopover()`, top-layer positioning, auto-updates, toggle-event sync, and optional focus-out dismissal.
691
761
 
692
762
  ```typescript
@@ -1587,6 +1657,9 @@ import type {
1587
1657
  ListboxNavigationOptions,
1588
1658
  ListboxNavigationResult,
1589
1659
  MenuNavigationOptions,
1660
+ PopoverController,
1661
+ PopoverControllerOptions,
1662
+ PopoverMountContext,
1590
1663
  NativePopoverCloseOptions,
1591
1664
  NativePopoverDisclosureController,
1592
1665
  NativePopoverDisclosureOptions,
package/dist/index.d.ts CHANGED
@@ -94,6 +94,9 @@ export declare function createMenuNavigation(container: HTMLElement, options?: M
94
94
 
95
95
  export declare function createNativePopoverDisclosure(options: NativePopoverDisclosureOptions): NativePopoverDisclosureController;
96
96
 
97
+ /** Mount after rendering the open panel; cleanup detaches behavior without discarding open state. */
98
+ export declare function createPopoverController(options: PopoverControllerOptions): PopoverController;
99
+
97
100
  /**
98
101
  * Framework-neutral list reorder controller. It combines item registration,
99
102
  * live pointer preview ordering, keyboard moves, pointer commits, bounds, and
@@ -262,6 +265,7 @@ export declare interface MenuNavigationOptions {
262
265
  orientation?: 'vertical' | 'horizontal';
263
266
  loop?: boolean;
264
267
  typeAhead?: boolean;
268
+ initialFocus?: 'first' | 'last';
265
269
  onActivate?: (item: HTMLElement) => void;
266
270
  }
267
271
 
@@ -399,6 +403,36 @@ export declare function parseRgbColor(input: string): ParsedColor | null;
399
403
 
400
404
  export declare type Placement = 'top' | 'top-start' | 'top-end' | 'bottom' | 'bottom-start' | 'bottom-end' | 'left' | 'left-start' | 'left-end' | 'right' | 'right-start' | 'right-end';
401
405
 
406
+ export declare interface PopoverController {
407
+ readonly native: boolean;
408
+ readonly isOpen: boolean;
409
+ open: () => void;
410
+ close: (restoreFocus?: boolean) => void;
411
+ toggle: (event?: MouseEvent) => void;
412
+ mount: () => void;
413
+ cleanup: CleanupFunction;
414
+ onKeydown: (event: KeyboardEvent) => void;
415
+ onFocusOut: (event: FocusEvent) => void;
416
+ onPointerDown: () => void;
417
+ }
418
+
419
+ export declare interface PopoverControllerOptions {
420
+ reference: () => HTMLElement | null;
421
+ popover: () => HTMLElement | null;
422
+ position: TopLayerPopoverPositionOptions;
423
+ menu?: boolean;
424
+ onOpenChange?: (open: boolean) => void;
425
+ onMount?: (context: PopoverMountContext) => CleanupFunction | void;
426
+ onOpened?: () => void;
427
+ onClosed?: () => void;
428
+ }
429
+
430
+ export declare interface PopoverMountContext {
431
+ reference: HTMLElement;
432
+ popover: HTMLElement;
433
+ native: boolean;
434
+ }
435
+
402
436
  declare interface PositionOptions_2 {
403
437
  placement?: Placement;
404
438
  offset?: number;
package/dist/index.js CHANGED
@@ -490,7 +490,7 @@ function onClickOutside(elements, callback) {
490
490
  //#endregion
491
491
  //#region src/menu.ts
492
492
  function createMenuNavigation(container, options = {}) {
493
- const { itemSelector = "[role=\"menuitem\"]:not([disabled]):not([aria-disabled=\"true\"])", orientation = "vertical", loop = true, typeAhead = true, onActivate } = options;
493
+ const { itemSelector = "[role=\"menuitem\"]:not([disabled]):not([aria-disabled=\"true\"])", orientation = "vertical", loop = true, typeAhead = true, initialFocus = "first", onActivate } = options;
494
494
  let typeAheadBuffer = "";
495
495
  let typeAheadTimeout;
496
496
  function getItems() {
@@ -559,11 +559,12 @@ function createMenuNavigation(container, options = {}) {
559
559
  }
560
560
  container.addEventListener("keydown", handleKeyDown);
561
561
  const items = getItems();
562
- items.forEach((el, i) => el.setAttribute("tabindex", i === 0 ? "0" : "-1"));
562
+ const initialIndex = initialFocus === "last" ? items.length - 1 : 0;
563
+ items.forEach((el, i) => el.setAttribute("tabindex", i === initialIndex ? "0" : "-1"));
563
564
  let rafId;
564
565
  if (items.length > 0) rafId = requestAnimationFrame(() => {
565
566
  rafId = void 0;
566
- items[0].focus();
567
+ items[initialIndex].focus();
567
568
  });
568
569
  let cleaned = false;
569
570
  return function cleanup() {
@@ -1232,23 +1233,187 @@ function focusFirstEnabledElement(elements) {
1232
1233
  return false;
1233
1234
  }
1234
1235
  //#endregion
1235
- //#region src/position.ts
1236
+ //#region src/position/style.ts
1237
+ function setStyleProperty(style, property, value) {
1238
+ if (style.getPropertyValue(property) !== value) style.setProperty(property, value);
1239
+ }
1240
+ function removeStyleProperty(style, property) {
1241
+ if (style.getPropertyValue(property) !== "") style.removeProperty(property);
1242
+ }
1243
+ function captureStyleProperty(style, property) {
1244
+ 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);
1255
+ }
1256
+ //#endregion
1257
+ //#region src/position/anchor.ts
1236
1258
  var ANCHOR_CLASS_PREFIX = "iui-anchor-";
1237
1259
  var _supportsAnchor = null;
1260
+ var _supportsAnchorFlip = null;
1238
1261
  var _supportsTopLayerAnchor = null;
1239
1262
  var _supportsTopLayerAnchorSizing = null;
1263
+ var _isWebKit = null;
1240
1264
  function supportsAnchorPositioning() {
1241
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)");
1242
1266
  return _supportsAnchor;
1243
1267
  }
1244
1268
  function supportsTopLayerAnchorPositioning() {
1245
- if (_supportsTopLayerAnchor === null) _supportsTopLayerAnchor = supportsAnchorPositioning() && CSS.supports("width", "anchor-size(width)");
1269
+ if (_supportsTopLayerAnchor === null) _supportsTopLayerAnchor = supportsAnchorPositioning() && CSS.supports("width", "anchor-size(width)") && !isWebKit();
1246
1270
  return _supportsTopLayerAnchor;
1247
1271
  }
1272
+ function isWebKit() {
1273
+ if (_isWebKit === null) _isWebKit = typeof CSS !== "undefined" && typeof CSS.supports === "function" && CSS.supports("-webkit-backdrop-filter", "none");
1274
+ return _isWebKit;
1275
+ }
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;
1279
+ }
1248
1280
  function supportsTopLayerAnchorSizing() {
1249
1281
  if (_supportsTopLayerAnchorSizing === null) _supportsTopLayerAnchorSizing = supportsTopLayerAnchorPositioning() && CSS.supports("height", "max-content") && CSS.supports("max-height", "stretch");
1250
1282
  return _supportsTopLayerAnchorSizing;
1251
1283
  }
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;
1293
+ }
1294
+ function findAnchorClass(element) {
1295
+ return Array.from(element.classList).find((c) => c.startsWith(ANCHOR_CLASS_PREFIX));
1296
+ }
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
1252
1417
  function isRtl$1() {
1253
1418
  return typeof document !== "undefined" && document.documentElement.dir === "rtl";
1254
1419
  }
@@ -1314,6 +1479,11 @@ function topLayerRectOverflowsViewport(rect, viewport) {
1314
1479
  const tolerance = .5;
1315
1480
  return rect.top < viewport.top - tolerance || rect.left < viewport.left - tolerance || rect.right > viewport.right + tolerance || rect.bottom > viewport.bottom + tolerance;
1316
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
+ }
1317
1487
  function getAvailableSpace(referenceRect, viewport, side, offset, margin) {
1318
1488
  if (side === "top") return referenceRect.top - viewport.top - offset - margin;
1319
1489
  if (side === "bottom") return viewport.bottom - referenceRect.bottom - offset - margin;
@@ -1401,9 +1571,9 @@ function clampToViewport(x, y, floatingRect) {
1401
1571
  y: Math.max(margin, Math.min(y, vh - floatingRect.height - margin))
1402
1572
  };
1403
1573
  }
1404
- function computeWithFallback(reference, floating, options = {}) {
1574
+ function computeWithFallback(reference, floating, options = {}, referenceRect) {
1405
1575
  const { placement = "bottom-start", offset = 0, flip = true } = options;
1406
- const refRect = reference.getBoundingClientRect();
1576
+ const refRect = referenceRect ?? reference.getBoundingClientRect();
1407
1577
  const floatingRect = floating.getBoundingClientRect();
1408
1578
  let { x, y } = computePositionFromRect(refRect, floatingRect, placement, offset);
1409
1579
  let actualPlacement = placement;
@@ -1423,178 +1593,8 @@ function computeWithFallback(reference, floating, options = {}) {
1423
1593
  placement: actualPlacement
1424
1594
  };
1425
1595
  }
1426
- var anchorStyleId = "inertiaui-anchor-styles";
1427
- function ensureAnchorStylesheet() {
1428
- let style = document.getElementById(anchorStyleId);
1429
- if (!style) {
1430
- style = document.createElement("style");
1431
- style.id = anchorStyleId;
1432
- document.head.appendChild(style);
1433
- }
1434
- return style.sheet;
1435
- }
1436
- function findAnchorClass(element) {
1437
- return Array.from(element.classList).find((c) => c.startsWith(ANCHOR_CLASS_PREFIX));
1438
- }
1439
- function removeAnchorRule(className) {
1440
- const style = document.getElementById(anchorStyleId);
1441
- if (!style?.sheet) return;
1442
- for (let i = 0; i < style.sheet.cssRules.length; i++) if (style.sheet.cssRules[i].selectorText === `.${className}`) {
1443
- style.sheet.deleteRule(i);
1444
- return;
1445
- }
1446
- }
1447
- function setupAnchorPositioning(reference, floating, placement, offset, flip) {
1448
- const id = generateId(ANCHOR_CLASS_PREFIX);
1449
- const anchorName = `--${id}`;
1450
- reference.style.anchorName = anchorName;
1451
- floating.style.positionAnchor = anchorName;
1452
- floating.style.position = "fixed";
1453
- const [side, alignment] = placement.split("-");
1454
- const sheet = ensureAnchorStylesheet();
1455
- const className = id;
1456
- let positionRules = "";
1457
- let tryFallback = "";
1458
- switch (side) {
1459
- case "bottom":
1460
- positionRules += `top: anchor(bottom);`;
1461
- positionRules += `margin-top: ${offset}px;`;
1462
- break;
1463
- case "top":
1464
- positionRules += `bottom: anchor(top);`;
1465
- positionRules += `margin-bottom: ${offset}px;`;
1466
- break;
1467
- case "left":
1468
- positionRules += `right: anchor(left);`;
1469
- positionRules += `margin-right: ${offset}px;`;
1470
- break;
1471
- case "right":
1472
- positionRules += `left: anchor(right);`;
1473
- positionRules += `margin-left: ${offset}px;`;
1474
- break;
1475
- }
1476
- if (side === "bottom" || side === "top") switch (alignment) {
1477
- case "start":
1478
- positionRules += `left: anchor(left);`;
1479
- break;
1480
- case "end":
1481
- positionRules += `right: anchor(right);`;
1482
- break;
1483
- default:
1484
- positionRules += `left: anchor(center); translate: -50% 0;`;
1485
- break;
1486
- }
1487
- else switch (alignment) {
1488
- case "start":
1489
- positionRules += `top: anchor(top);`;
1490
- break;
1491
- case "end":
1492
- positionRules += `bottom: anchor(bottom);`;
1493
- break;
1494
- default:
1495
- positionRules += `top: anchor(center); translate: 0 -50%;`;
1496
- break;
1497
- }
1498
- if (flip) tryFallback = `position-try-fallbacks: flip-block, flip-inline;`;
1499
- const rule = `.${className} { ${positionRules} ${tryFallback} }`;
1500
- sheet.insertRule(rule, sheet.cssRules.length);
1501
- floating.classList.add(className);
1502
- return className;
1503
- }
1504
- function cleanupAnchorPositioning(reference, floating, className) {
1505
- reference.style.anchorName = "";
1506
- floating.style.positionAnchor = "";
1507
- floating.style.position = "";
1508
- floating.classList.remove(className);
1509
- removeAnchorRule(className);
1510
- }
1511
- function detachAnchorPositioning(reference, floating) {
1512
- reference.style.removeProperty("anchor-name");
1513
- floating.style.removeProperty("position-anchor");
1514
- for (const className of Array.from(floating.classList)) if (className.startsWith(ANCHOR_CLASS_PREFIX)) {
1515
- floating.classList.remove(className);
1516
- removeAnchorRule(className);
1517
- }
1518
- }
1519
- function getAnchorPositionRules(placement, offset) {
1520
- const [side, alignment] = placement.split("-");
1521
- let positionRules = "";
1522
- switch (side) {
1523
- case "bottom":
1524
- positionRules += `top: anchor(bottom);`;
1525
- positionRules += `margin-top: ${offset}px;`;
1526
- break;
1527
- case "top":
1528
- positionRules += `bottom: anchor(top);`;
1529
- positionRules += `margin-bottom: ${offset}px;`;
1530
- break;
1531
- case "left":
1532
- positionRules += `right: anchor(left);`;
1533
- positionRules += `margin-right: ${offset}px;`;
1534
- break;
1535
- case "right":
1536
- positionRules += `left: anchor(right);`;
1537
- positionRules += `margin-left: ${offset}px;`;
1538
- break;
1539
- }
1540
- if (side === "bottom" || side === "top") switch (alignment) {
1541
- case "start":
1542
- positionRules += `left: anchor(left);`;
1543
- break;
1544
- case "end":
1545
- positionRules += `right: anchor(right);`;
1546
- break;
1547
- default:
1548
- positionRules += `left: anchor(center); translate: -50% 0;`;
1549
- break;
1550
- }
1551
- else switch (alignment) {
1552
- case "start":
1553
- positionRules += `top: anchor(top);`;
1554
- break;
1555
- case "end":
1556
- positionRules += `bottom: anchor(bottom);`;
1557
- break;
1558
- default:
1559
- positionRules += `top: anchor(center); translate: 0 -50%;`;
1560
- break;
1561
- }
1562
- return positionRules;
1563
- }
1564
- function getTopLayerAnchorSizingRules(placement, viewportMargin) {
1565
- const [side] = placement.split("-");
1566
- if (side === "bottom") return `bottom: ${viewportMargin}px; height: max-content; max-height: stretch;`;
1567
- if (side === "top") return `top: ${viewportMargin}px; height: max-content; max-height: stretch; align-self: end;`;
1568
- return "";
1569
- }
1570
- function setupTopLayerAnchorPositioning(reference, floating, placement, offset, matchReferenceWidth, maxWidth, viewportMargin, stretchToAvailableHeight) {
1571
- const existingClass = findAnchorClass(floating);
1572
- const existingAnchorName = existingClass ? `--${existingClass}` : "";
1573
- const canReuseAnchor = !!existingClass && reference.style.getPropertyValue("anchor-name") === existingAnchorName && floating.style.getPropertyValue("position-anchor") === existingAnchorName;
1574
- const className = canReuseAnchor ? existingClass : generateId(ANCHOR_CLASS_PREFIX);
1575
- const anchorName = `--${className}`;
1576
- const sheet = ensureAnchorStylesheet();
1577
- if (canReuseAnchor) removeAnchorRule(className);
1578
- else detachAnchorPositioning(reference, floating);
1579
- reference.style.anchorName = anchorName;
1580
- floating.style.positionAnchor = anchorName;
1581
- floating.style.removeProperty("inset");
1582
- floating.style.removeProperty("top");
1583
- floating.style.removeProperty("right");
1584
- floating.style.removeProperty("bottom");
1585
- floating.style.removeProperty("left");
1586
- floating.style.removeProperty("margin");
1587
- floating.style.position = "fixed";
1588
- if (stretchToAvailableHeight) {
1589
- floating.style.height = "max-content";
1590
- floating.style.removeProperty("max-height");
1591
- } else floating.style.removeProperty("height");
1592
- if (matchReferenceWidth) floating.style.width = `min(anchor-size(width), ${maxWidth}px)`;
1593
- const rule = `.${className} { position: fixed; inset: auto; margin: 0; ${getAnchorPositionRules(placement, offset)} ${matchReferenceWidth ? `width: min(anchor-size(width), ${maxWidth}px);` : ""} ${stretchToAvailableHeight ? getTopLayerAnchorSizingRules(placement, viewportMargin) : ""} }`;
1594
- sheet.insertRule(rule, sheet.cssRules.length);
1595
- floating.classList.add(className);
1596
- return className;
1597
- }
1596
+ //#endregion
1597
+ //#region src/position/floating.ts
1598
1598
  var SIZE_MARGIN = 8;
1599
1599
  /**
1600
1600
  * Cap the floating element's height to the space available between its anchored
@@ -1607,8 +1607,8 @@ var SIZE_MARGIN = 8;
1607
1607
  * direction is derived from the rendered rects: a menu whose top sits above the
1608
1608
  * reference opens upward (its bottom edge is anchored); otherwise it opens downward.
1609
1609
  */
1610
- function applySize(reference, floating, offset, side) {
1611
- const refRect = reference.getBoundingClientRect();
1610
+ function applySize(reference, floating, offset, side, refRect) {
1611
+ refRect ??= reference.getBoundingClientRect();
1612
1612
  const vh = window.innerHeight;
1613
1613
  let available;
1614
1614
  if (side === "top") available = refRect.top - offset - SIZE_MARGIN;
@@ -1623,7 +1623,7 @@ function applySize(reference, floating, offset, side) {
1623
1623
  }
1624
1624
  function computePosition(reference, floating, options = {}) {
1625
1625
  const { placement = "bottom-start", offset = 0, flip = true, autoSize = false } = options;
1626
- if (supportsAnchorPositioning()) {
1626
+ if (supportsAnchorPositioning() && (!flip || supportsAnchorFlip())) {
1627
1627
  if (!findAnchorClass(floating)) setupAnchorPositioning(reference, floating, placement, offset, flip);
1628
1628
  if (autoSize) applySize(reference, floating, offset);
1629
1629
  const rect = floating.getBoundingClientRect();
@@ -1633,18 +1633,47 @@ function computePosition(reference, floating, options = {}) {
1633
1633
  placement
1634
1634
  };
1635
1635
  }
1636
- if (autoSize) applySize(reference, floating, offset, placement.split("-")[0]);
1636
+ let referenceRect;
1637
+ if (autoSize) {
1638
+ referenceRect = reference.getBoundingClientRect();
1639
+ applySize(reference, floating, offset, placement.split("-")[0], referenceRect);
1640
+ }
1637
1641
  const result = computeWithFallback(reference, floating, {
1638
1642
  placement,
1639
1643
  offset,
1640
1644
  flip
1641
- });
1645
+ }, referenceRect);
1642
1646
  floating.style.position = "fixed";
1643
1647
  floating.style.top = `${result.y}px`;
1644
1648
  floating.style.left = `${result.x}px`;
1645
- if (autoSize) applySize(reference, floating, offset, result.placement.split("-")[0]);
1649
+ if (autoSize) applySize(reference, floating, offset, result.placement.split("-")[0], referenceRect);
1646
1650
  return result;
1647
1651
  }
1652
+ function observeElementResize(reference, floating, scheduleUpdate) {
1653
+ if (typeof ResizeObserver !== "function") return () => {};
1654
+ let reobserveFrame;
1655
+ const resizeObserver = new ResizeObserver(([firstEntry]) => {
1656
+ const referenceResized = firstEntry?.target === reference;
1657
+ if (referenceResized) resizeObserver.unobserve(floating);
1658
+ scheduleUpdate();
1659
+ if (referenceResized) {
1660
+ if (reobserveFrame !== void 0) cancelAnimationFrame(reobserveFrame);
1661
+ reobserveFrame = requestAnimationFrame(() => {
1662
+ reobserveFrame = void 0;
1663
+ resizeObserver.observe(floating);
1664
+ });
1665
+ }
1666
+ });
1667
+ resizeObserver.observe(reference);
1668
+ resizeObserver.observe(floating);
1669
+ return () => {
1670
+ if (reobserveFrame !== void 0) {
1671
+ cancelAnimationFrame(reobserveFrame);
1672
+ reobserveFrame = void 0;
1673
+ }
1674
+ resizeObserver.disconnect();
1675
+ };
1676
+ }
1648
1677
  function autoUpdate(reference, floating, update) {
1649
1678
  let rafId;
1650
1679
  function scheduleUpdate() {
@@ -1655,10 +1684,11 @@ function autoUpdate(reference, floating, update) {
1655
1684
  });
1656
1685
  }
1657
1686
  window.addEventListener("resize", scheduleUpdate);
1658
- window.addEventListener("scroll", scheduleUpdate, true);
1659
- const resizeObserver = new ResizeObserver(scheduleUpdate);
1660
- resizeObserver.observe(reference);
1661
- resizeObserver.observe(floating);
1687
+ window.addEventListener("scroll", scheduleUpdate, {
1688
+ passive: true,
1689
+ capture: true
1690
+ });
1691
+ const cleanupResizeObserver = observeElementResize(reference, floating, scheduleUpdate);
1662
1692
  let cleaned = false;
1663
1693
  return function cleanup() {
1664
1694
  if (cleaned) return;
@@ -1666,25 +1696,85 @@ function autoUpdate(reference, floating, update) {
1666
1696
  if (rafId !== void 0) cancelAnimationFrame(rafId);
1667
1697
  window.removeEventListener("resize", scheduleUpdate);
1668
1698
  window.removeEventListener("scroll", scheduleUpdate, true);
1669
- resizeObserver.disconnect();
1699
+ cleanupResizeObserver();
1670
1700
  const anchorClass = findAnchorClass(floating);
1671
1701
  if (anchorClass) cleanupAnchorPositioning(reference, floating, anchorClass);
1672
1702
  };
1673
1703
  }
1704
+ //#endregion
1705
+ //#region src/position/topLayer.ts
1706
+ function observeTopLayerElementResize(reference, floating, scheduleUpdate, shouldObserveFloating) {
1707
+ if (typeof ResizeObserver !== "function") return {
1708
+ cleanup: () => {},
1709
+ syncFloatingObserver: () => {}
1710
+ };
1711
+ let floatingObserved = false;
1712
+ let floatingObserverDeferred = false;
1713
+ let reobserveFrame;
1714
+ const resizeObserver = new ResizeObserver((entries) => {
1715
+ const referenceResized = entries.some((entry) => entry.target === reference);
1716
+ if (entries.some((entry) => entry.target === floating) && !referenceResized && !shouldObserveFloating()) {
1717
+ syncFloatingObserver();
1718
+ return;
1719
+ }
1720
+ if (referenceResized && floatingObserved) {
1721
+ resizeObserver.unobserve(floating);
1722
+ floatingObserved = false;
1723
+ floatingObserverDeferred = true;
1724
+ }
1725
+ scheduleUpdate();
1726
+ if (referenceResized) {
1727
+ if (reobserveFrame !== void 0) cancelAnimationFrame(reobserveFrame);
1728
+ reobserveFrame = requestAnimationFrame(() => {
1729
+ reobserveFrame = void 0;
1730
+ floatingObserverDeferred = false;
1731
+ syncFloatingObserver();
1732
+ });
1733
+ }
1734
+ });
1735
+ const syncFloatingObserver = () => {
1736
+ if (floatingObserverDeferred) return;
1737
+ if (shouldObserveFloating()) {
1738
+ if (!floatingObserved) {
1739
+ resizeObserver.observe(floating);
1740
+ floatingObserved = true;
1741
+ }
1742
+ return;
1743
+ }
1744
+ if (floatingObserved) {
1745
+ resizeObserver.unobserve(floating);
1746
+ floatingObserved = false;
1747
+ }
1748
+ };
1749
+ resizeObserver.observe(reference);
1750
+ syncFloatingObserver();
1751
+ return {
1752
+ cleanup: () => {
1753
+ if (reobserveFrame !== void 0) {
1754
+ cancelAnimationFrame(reobserveFrame);
1755
+ reobserveFrame = void 0;
1756
+ }
1757
+ resizeObserver.disconnect();
1758
+ floatingObserved = false;
1759
+ floatingObserverDeferred = false;
1760
+ },
1761
+ syncFloatingObserver
1762
+ };
1763
+ }
1674
1764
  function positionTopLayerPopover(reference, floating, options = {}) {
1675
1765
  const { placement = "bottom-start", offset = 4, flip = true, matchReferenceWidth = false, viewportMargin = 8, anchorPositioning = true } = options;
1676
1766
  const viewport = getViewportRect();
1677
1767
  const maxWidth = Math.max(0, Math.floor(viewport.width - viewportMargin * 2));
1678
- floating.style.position = "fixed";
1679
- floating.style.boxSizing = "border-box";
1680
- floating.style.maxWidth = `${maxWidth}px`;
1681
- floating.style.overflowX = "auto";
1682
- floating.style.overflowY = "auto";
1683
- floating.style.overscrollBehavior = "contain";
1768
+ setStyleProperty(floating.style, "position", "fixed");
1769
+ setStyleProperty(floating.style, "box-sizing", "border-box");
1770
+ setStyleProperty(floating.style, "max-width", `${maxWidth}px`);
1771
+ setStyleProperty(floating.style, "overflow-x", "auto");
1772
+ setStyleProperty(floating.style, "overflow-y", "auto");
1773
+ setStyleProperty(floating.style, "overscroll-behavior", "contain");
1684
1774
  const referenceRect = reference.getBoundingClientRect();
1685
1775
  const viewportHeight = Math.max(0, Math.floor(viewport.height - viewportMargin * 2));
1686
- if (anchorPositioning && supportsTopLayerAnchorPositioning()) {
1687
- if (matchReferenceWidth) floating.style.width = `${Math.min(referenceRect.width, maxWidth)}px`;
1776
+ if (anchorPositioning && supportsTopLayerAnchorPositioning() && (!flip || supportsAnchorFlip())) {
1777
+ if (matchReferenceWidth) setStyleProperty(floating.style, "width", `${Math.min(referenceRect.width, maxWidth)}px`);
1688
1778
  const measuredRect = floating.getBoundingClientRect();
1689
1779
  const resolvedPlacement = resolveTopLayerPlacement(placement, referenceRect, {
1690
1780
  width: Math.max(measuredRect.width, floating.scrollWidth),
@@ -1692,12 +1782,12 @@ function positionTopLayerPopover(reference, floating, options = {}) {
1692
1782
  }, viewport, offset, viewportMargin, flip);
1693
1783
  const [resolvedSide] = resolvedPlacement.split("-");
1694
1784
  const stretchToAvailableHeight = (resolvedSide === "top" || resolvedSide === "bottom") && supportsTopLayerAnchorSizing();
1695
- if (stretchToAvailableHeight) floating.style.removeProperty("max-height");
1785
+ if (stretchToAvailableHeight) removeStyleProperty(floating.style, "max-height");
1696
1786
  else {
1697
1787
  const availableHeight = resolvedSide === "top" || resolvedSide === "bottom" ? Math.min(viewportHeight, Math.max(0, Math.floor(getAvailableSpace(referenceRect, viewport, resolvedSide, offset, viewportMargin)))) : viewportHeight;
1698
- floating.style.maxHeight = `${availableHeight}px`;
1788
+ setStyleProperty(floating.style, "max-height", `${availableHeight}px`);
1699
1789
  }
1700
- setupTopLayerAnchorPositioning(reference, floating, resolvedPlacement, offset, matchReferenceWidth, maxWidth, viewportMargin, stretchToAvailableHeight);
1790
+ setupTopLayerAnchorPositioning(reference, floating, resolvedPlacement, offset, flip, matchReferenceWidth, maxWidth, viewportMargin, stretchToAvailableHeight);
1701
1791
  const finalRect = floating.getBoundingClientRect();
1702
1792
  if (!topLayerRectOverflowsViewport(finalRect, viewport)) return {
1703
1793
  x: finalRect.left,
@@ -1706,12 +1796,12 @@ function positionTopLayerPopover(reference, floating, options = {}) {
1706
1796
  };
1707
1797
  }
1708
1798
  detachAnchorPositioning(reference, floating);
1709
- floating.style.inset = "auto";
1710
- floating.style.right = "auto";
1711
- floating.style.bottom = "auto";
1712
- floating.style.margin = "0";
1713
- floating.style.removeProperty("height");
1714
- if (matchReferenceWidth) floating.style.width = `${Math.min(referenceRect.width, maxWidth)}px`;
1799
+ setStyleProperty(floating.style, "inset", "auto");
1800
+ setStyleProperty(floating.style, "right", "auto");
1801
+ setStyleProperty(floating.style, "bottom", "auto");
1802
+ setStyleProperty(floating.style, "margin", "0");
1803
+ removeStyleProperty(floating.style, "height");
1804
+ if (matchReferenceWidth) setStyleProperty(floating.style, "width", `${Math.min(referenceRect.width, maxWidth)}px`);
1715
1805
  const measuredRect = floating.getBoundingClientRect();
1716
1806
  const resolvedPlacement = resolveTopLayerPlacement(placement, referenceRect, {
1717
1807
  width: Math.max(measuredRect.width, floating.scrollWidth),
@@ -1719,13 +1809,13 @@ function positionTopLayerPopover(reference, floating, options = {}) {
1719
1809
  }, viewport, offset, viewportMargin, flip);
1720
1810
  const [resolvedSide] = resolvedPlacement.split("-");
1721
1811
  const availableHeight = Math.min(viewportHeight, Math.max(0, Math.floor(getAvailableSpace(referenceRect, viewport, resolvedSide, offset, viewportMargin))));
1722
- if (resolvedSide === "top" || resolvedSide === "bottom") floating.style.maxHeight = `${availableHeight}px`;
1723
- else floating.style.maxHeight = `${viewportHeight}px`;
1812
+ if (resolvedSide === "top" || resolvedSide === "bottom") setStyleProperty(floating.style, "max-height", `${availableHeight}px`);
1813
+ else setStyleProperty(floating.style, "max-height", `${viewportHeight}px`);
1724
1814
  const floatingRect = floating.getBoundingClientRect();
1725
1815
  const coordinates = computePositionFromRect(referenceRect, floatingRect, resolvedPlacement, offset);
1726
1816
  const { x, y } = clampTopLayerCoordinates(coordinates.x, coordinates.y, floatingRect, resolvedPlacement, viewport, viewportMargin);
1727
- floating.style.left = `${Math.round(x)}px`;
1728
- floating.style.top = `${Math.round(y)}px`;
1817
+ setStyleProperty(floating.style, "left", `${Math.round(x)}px`);
1818
+ setStyleProperty(floating.style, "top", `${Math.round(y)}px`);
1729
1819
  return {
1730
1820
  x,
1731
1821
  y,
@@ -1733,30 +1823,168 @@ function positionTopLayerPopover(reference, floating, options = {}) {
1733
1823
  };
1734
1824
  }
1735
1825
  function autoUpdateTopLayerPopover(reference, floating, update) {
1736
- const cleanupAutoUpdate = autoUpdate(reference, floating, update);
1737
1826
  const visualViewport = window.visualViewport;
1738
- let rafId = null;
1827
+ const browserAnchorsPopover = () => supportsTopLayerAnchorPositioning() && findAnchorClass(floating) !== void 0;
1828
+ let rafId;
1829
+ let restoreMotionFrame;
1830
+ let scrollListenersAttached = false;
1831
+ let syncFloatingResizeObserver = () => {};
1832
+ let referenceHidden = !referenceIntersectsViewport(reference);
1833
+ let anchorParked = false;
1834
+ let parkedStyles;
1835
+ let restoreVisibilityAfterUpdate = false;
1836
+ const hasReferenceVisibilityObserver = typeof IntersectionObserver === "function";
1739
1837
  const scheduleUpdate = () => {
1740
- if (rafId !== null) return;
1838
+ if (rafId !== void 0) return;
1741
1839
  rafId = requestAnimationFrame(() => {
1742
- rafId = null;
1743
- update();
1840
+ rafId = void 0;
1841
+ syncReferenceVisibility();
1842
+ if (!anchorParked) update();
1843
+ syncScrollListeners();
1844
+ syncFloatingResizeObserver();
1845
+ if (restoreVisibilityAfterUpdate && !anchorParked) restoreParkedVisibility();
1744
1846
  });
1745
1847
  };
1848
+ const cancelMotionRestore = () => {
1849
+ if (restoreMotionFrame === void 0) return;
1850
+ cancelAnimationFrame(restoreMotionFrame);
1851
+ restoreMotionFrame = void 0;
1852
+ };
1853
+ const restoreParkedMotionStyles = () => {
1854
+ if (!parkedStyles) {
1855
+ floating.removeAttribute("data-inertiaui-top-layer-parked");
1856
+ return;
1857
+ }
1858
+ restoreStyleProperty(floating.style, "transition", parkedStyles.transition);
1859
+ restoreStyleProperty(floating.style, "animation", parkedStyles.animation);
1860
+ floating.removeAttribute("data-inertiaui-top-layer-parked");
1861
+ };
1862
+ const scheduleMotionRestore = () => {
1863
+ cancelMotionRestore();
1864
+ restoreMotionFrame = requestAnimationFrame(() => {
1865
+ restoreMotionFrame = void 0;
1866
+ restoreParkedMotionStyles();
1867
+ parkedStyles = void 0;
1868
+ });
1869
+ };
1870
+ const handleScroll = () => {
1871
+ syncReferenceVisibility();
1872
+ if (anchorParked || browserAnchorsPopover()) return;
1873
+ scheduleUpdate();
1874
+ };
1875
+ const addScrollListeners = () => {
1876
+ if (scrollListenersAttached) return;
1877
+ scrollListenersAttached = true;
1878
+ window.addEventListener("scroll", handleScroll, {
1879
+ passive: true,
1880
+ capture: true
1881
+ });
1882
+ visualViewport?.addEventListener("scroll", handleScroll, { passive: true });
1883
+ };
1884
+ const removeScrollListeners = () => {
1885
+ if (!scrollListenersAttached) return;
1886
+ scrollListenersAttached = false;
1887
+ window.removeEventListener("scroll", handleScroll, true);
1888
+ visualViewport?.removeEventListener("scroll", handleScroll);
1889
+ };
1890
+ const syncScrollListeners = () => {
1891
+ if (anchorParked && hasReferenceVisibilityObserver) {
1892
+ removeScrollListeners();
1893
+ return;
1894
+ }
1895
+ addScrollListeners();
1896
+ };
1897
+ const parkPopover = () => {
1898
+ if (anchorParked) return;
1899
+ if (restoreVisibilityAfterUpdate) restoreVisibilityAfterUpdate = false;
1900
+ else if (!parkedStyles) parkedStyles = {
1901
+ visibility: captureStyleProperty(floating.style, "visibility"),
1902
+ transition: captureStyleProperty(floating.style, "transition"),
1903
+ animation: captureStyleProperty(floating.style, "animation")
1904
+ };
1905
+ cancelMotionRestore();
1906
+ floating.setAttribute("data-inertiaui-top-layer-parked", "");
1907
+ floating.style.setProperty("transition", "none", "important");
1908
+ floating.style.setProperty("animation", "none", "important");
1909
+ floating.style.setProperty("visibility", "hidden");
1910
+ anchorParked = true;
1911
+ syncScrollListeners();
1912
+ syncFloatingResizeObserver();
1913
+ };
1914
+ const restoreParkedVisibility = () => {
1915
+ if (!parkedStyles) {
1916
+ restoreVisibilityAfterUpdate = false;
1917
+ return;
1918
+ }
1919
+ restoreStyleProperty(floating.style, "visibility", parkedStyles.visibility);
1920
+ restoreVisibilityAfterUpdate = false;
1921
+ scheduleMotionRestore();
1922
+ };
1923
+ const restoreParkedPopover = (schedule = true) => {
1924
+ if (!anchorParked) return;
1925
+ anchorParked = false;
1926
+ if (schedule) {
1927
+ restoreVisibilityAfterUpdate = true;
1928
+ scheduleUpdate();
1929
+ return;
1930
+ }
1931
+ restoreParkedVisibility();
1932
+ };
1933
+ const syncReferenceVisibility = (visible = referenceIntersectsViewport(reference)) => {
1934
+ referenceHidden = !visible;
1935
+ if (visible) {
1936
+ restoreParkedPopover();
1937
+ return;
1938
+ }
1939
+ parkPopover();
1940
+ };
1941
+ let cleanupReferenceVisibilityObserver = () => {};
1942
+ if (typeof IntersectionObserver === "function") {
1943
+ const intersectionObserver = new IntersectionObserver(([entry]) => {
1944
+ syncReferenceVisibility(Boolean(entry?.isIntersecting || (entry?.intersectionRatio ?? 0) > 0));
1945
+ });
1946
+ intersectionObserver.observe(reference);
1947
+ cleanupReferenceVisibilityObserver = () => {
1948
+ intersectionObserver.disconnect();
1949
+ };
1950
+ }
1951
+ window.addEventListener("resize", scheduleUpdate);
1746
1952
  visualViewport?.addEventListener("resize", scheduleUpdate);
1747
- visualViewport?.addEventListener("scroll", scheduleUpdate);
1953
+ syncScrollListeners();
1954
+ syncReferenceVisibility(!referenceHidden);
1955
+ const elementResizeObserver = observeTopLayerElementResize(reference, floating, scheduleUpdate, () => !anchorParked && !browserAnchorsPopover());
1956
+ syncFloatingResizeObserver = elementResizeObserver.syncFloatingObserver;
1957
+ let cleaned = false;
1748
1958
  return () => {
1749
- cleanupAutoUpdate();
1750
- if (rafId !== null) {
1959
+ if (cleaned) return;
1960
+ cleaned = true;
1961
+ if (rafId !== void 0) {
1751
1962
  cancelAnimationFrame(rafId);
1752
- rafId = null;
1963
+ rafId = void 0;
1753
1964
  }
1965
+ cancelMotionRestore();
1966
+ window.removeEventListener("resize", scheduleUpdate);
1754
1967
  visualViewport?.removeEventListener("resize", scheduleUpdate);
1755
- visualViewport?.removeEventListener("scroll", scheduleUpdate);
1968
+ cleanupReferenceVisibilityObserver();
1969
+ elementResizeObserver.cleanup();
1970
+ removeScrollListeners();
1971
+ restoreParkedPopover(false);
1972
+ cancelMotionRestore();
1973
+ restoreParkedMotionStyles();
1974
+ parkedStyles = void 0;
1975
+ const anchorClass = findAnchorClass(floating);
1976
+ if (anchorClass) cleanupAnchorPositioning(reference, floating, anchorClass);
1756
1977
  };
1757
1978
  }
1758
1979
  //#endregion
1759
1980
  //#region src/nativePopover.ts
1981
+ function restoreVisibility(popover, visibility) {
1982
+ if (visibility === void 0) {
1983
+ popover.style.removeProperty("visibility");
1984
+ return;
1985
+ }
1986
+ popover.style.setProperty("visibility", visibility);
1987
+ }
1760
1988
  function createNativePopoverDisclosure(options) {
1761
1989
  let isOpen = false;
1762
1990
  let autoUpdateCleanup = null;
@@ -1792,7 +2020,17 @@ function createNativePopoverDisclosure(options) {
1792
2020
  autoUpdateCleanup = autoUpdateTopLayerPopover(elements.reference, elements.popover, updatePosition);
1793
2021
  };
1794
2022
  const showPopover = () => {
1795
- options.popover()?.showPopover();
2023
+ const elements = getElements();
2024
+ if (!elements) return;
2025
+ const { reference, popover } = elements;
2026
+ const previousVisibility = popover.style.getPropertyValue("visibility") || void 0;
2027
+ popover.style.setProperty("visibility", "hidden");
2028
+ try {
2029
+ popover.showPopover();
2030
+ positionTopLayerPopover(reference, popover, options.position);
2031
+ } finally {
2032
+ restoreVisibility(popover, previousVisibility);
2033
+ }
1796
2034
  };
1797
2035
  const hidePopover = () => {
1798
2036
  options.popover()?.hidePopover();
@@ -1847,6 +2085,144 @@ function createNativePopoverDisclosure(options) {
1847
2085
  };
1848
2086
  }
1849
2087
  //#endregion
2088
+ //#region src/popover.ts
2089
+ /** Mount after rendering the open panel; cleanup detaches behavior without discarding open state. */
2090
+ function createPopoverController(options) {
2091
+ const native = typeof HTMLElement !== "undefined" && "showPopover" in HTMLElement.prototype;
2092
+ let cleanups = [];
2093
+ let mountedPanel = null;
2094
+ let pointerStartedOpen = false;
2095
+ let focusLast = false;
2096
+ const disclosure = createNativePopoverDisclosure({
2097
+ reference: options.reference,
2098
+ popover: options.popover,
2099
+ 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
+ return {
2104
+ ...options.position,
2105
+ placement,
2106
+ anchorPositioning: native && options.position.anchorPositioning !== false
2107
+ };
2108
+ },
2109
+ focusOut: {
2110
+ container: options.reference,
2111
+ shouldIgnore: () => !!options.popover()?.contains(document.activeElement),
2112
+ onDismiss: () => close(false)
2113
+ },
2114
+ onOpenChange: options.onOpenChange
2115
+ });
2116
+ function cleanup(hide = true) {
2117
+ cleanups.forEach((cleanup) => cleanup());
2118
+ cleanups = [];
2119
+ disclosure.cleanupPopover();
2120
+ if (hide && native && mountedPanel?.matches(":popover-open")) mountedPanel.hidePopover();
2121
+ mountedPanel = null;
2122
+ }
2123
+ function returnFocus() {
2124
+ const reference = options.reference();
2125
+ (reference?.matches("button, input, select, textarea, a[href], [tabindex]") ? reference : reference?.querySelector("button:not([disabled]), input, select, textarea, a[href], [tabindex]"))?.focus({ preventScroll: true });
2126
+ }
2127
+ function shouldReturnFocus() {
2128
+ return typeof document !== "undefined" && (!!mountedPanel?.contains(document.activeElement) || document.activeElement === document.body);
2129
+ }
2130
+ function close(restoreFocus = shouldReturnFocus()) {
2131
+ disclosure.closePopover({
2132
+ hide: false,
2133
+ onClose() {
2134
+ cleanup();
2135
+ if (restoreFocus) returnFocus();
2136
+ options.onClosed?.();
2137
+ }
2138
+ });
2139
+ }
2140
+ function onKeydown(event) {
2141
+ if (event.key === "Escape" && disclosure.isOpen) {
2142
+ event.preventDefault();
2143
+ event.stopPropagation();
2144
+ close(true);
2145
+ } else if (options.menu && !disclosure.isOpen && ["ArrowDown", "ArrowUp"].includes(event.key)) {
2146
+ event.preventDefault();
2147
+ focusLast = event.key === "ArrowUp";
2148
+ disclosure.openPopover();
2149
+ }
2150
+ }
2151
+ function mount() {
2152
+ const reference = options.reference();
2153
+ const panel = options.popover();
2154
+ if (!disclosure.isOpen || !reference || !panel) return;
2155
+ cleanup();
2156
+ mountedPanel = panel;
2157
+ const onBeforeToggle = (event) => {
2158
+ const restoreFocus = shouldReturnFocus();
2159
+ disclosure.handlePopoverToggle(event, { onClose() {
2160
+ cleanup(false);
2161
+ if (restoreFocus) returnFocus();
2162
+ options.onClosed?.();
2163
+ } });
2164
+ };
2165
+ panel.addEventListener("beforetoggle", onBeforeToggle);
2166
+ panel.addEventListener("keydown", onKeydown);
2167
+ panel.addEventListener("focusout", disclosure.handleFocusOut);
2168
+ cleanups.push(() => {
2169
+ panel.removeEventListener("beforetoggle", onBeforeToggle);
2170
+ panel.removeEventListener("keydown", onKeydown);
2171
+ panel.removeEventListener("focusout", disclosure.handleFocusOut);
2172
+ });
2173
+ if (native) disclosure.showPopover();
2174
+ else {
2175
+ disclosure.updatePosition();
2176
+ cleanups.push(onClickOutside([reference, panel], () => close()));
2177
+ cleanups.push(onEscapeKey(() => close(true)));
2178
+ }
2179
+ disclosure.startAutoUpdate();
2180
+ const cleanupMount = options.onMount?.({
2181
+ reference,
2182
+ popover: panel,
2183
+ native
2184
+ });
2185
+ if (cleanupMount) cleanups.push(cleanupMount);
2186
+ if (options.menu) {
2187
+ cleanups.push(createMenuNavigation(panel, { initialFocus: focusLast ? "last" : "first" }));
2188
+ focusLast = false;
2189
+ const onClick = (event) => {
2190
+ if (event.target.closest("[role=\"menuitem\"]")) {
2191
+ const timer = setTimeout(() => {
2192
+ if (mountedPanel === panel) close();
2193
+ }, 0);
2194
+ cleanups.push(() => clearTimeout(timer));
2195
+ }
2196
+ };
2197
+ panel.addEventListener("click", onClick);
2198
+ cleanups.push(() => panel.removeEventListener("click", onClick));
2199
+ }
2200
+ options.onOpened?.();
2201
+ }
2202
+ function toggle(event) {
2203
+ const wasOpen = !!event?.detail && pointerStartedOpen;
2204
+ pointerStartedOpen = false;
2205
+ if (wasOpen) close();
2206
+ else disclosure.togglePopover(() => disclosure.openPopover(), () => close());
2207
+ }
2208
+ return {
2209
+ native,
2210
+ get isOpen() {
2211
+ return disclosure.isOpen;
2212
+ },
2213
+ open: () => disclosure.openPopover(),
2214
+ close,
2215
+ mount,
2216
+ cleanup,
2217
+ toggle,
2218
+ onKeydown,
2219
+ onFocusOut: disclosure.handleFocusOut,
2220
+ onPointerDown: () => {
2221
+ pointerStartedOpen = disclosure.isOpen;
2222
+ }
2223
+ };
2224
+ }
2225
+ //#endregion
1850
2226
  //#region src/blank.ts
1851
2227
  /**
1852
2228
  * Port of Laravel's `blank` function.
@@ -2238,4 +2614,4 @@ function formatColor(color, format = "hex", options = {}) {
2238
2614
  return includeAlpha ? `${normalized.hex}${Math.round(normalized.alpha * 255).toString(16).padStart(2, "0")}` : normalized.hex;
2239
2615
  }
2240
2616
  //#endregion
2241
- export { REORDERABLE_LIST_HANDLE_ATTRIBUTE, animate, animateFromSnapshot, autoUpdate, autoUpdateTopLayerPopover, blank, cancelAnimations, captureAnimationSnapshot, 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, prefersReducedMotion, rejectNullValues, resolveListboxNavigation, rgbToHex, sameUrlPath, supportsAnchorPositioning, supportsTopLayerAnchorPositioning, supportsWebAnimations };
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 };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inertiaui/vanilla",
3
- "version": "1.3.0",
3
+ "version": "1.4.0",
4
4
  "author": "Pascal Baljet <pascal@protone.media>",
5
5
  "private": false,
6
6
  "license": "MIT",