@inertiaui/vanilla 1.2.1 → 1.3.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/README.md CHANGED
@@ -411,9 +411,16 @@ Framework-neutral helpers for keyboard and pointer reordering.
411
411
  Use `createReorderableList` when you want a headless list controller that owns item registration, live pointer preview state, keyboard moves, pointer commits, optional bounds, optional auto-scroll, and cleanup. Rendering, announcements, focus handling, and animations stay in your package or framework adapter.
412
412
 
413
413
  ```typescript
414
- import { createReorderableList, REORDERABLE_LIST_HANDLE_ATTRIBUTE } from '@inertiaui/vanilla'
414
+ import {
415
+ animateFromSnapshot,
416
+ captureAnimationSnapshot,
417
+ createReorderableList,
418
+ REORDERABLE_LIST_HANDLE_ATTRIBUTE,
419
+ type AnimationSnapshot,
420
+ } from '@inertiaui/vanilla'
415
421
 
416
422
  let items = ['Apple', 'Banana', 'Cherry']
423
+ let animationSnapshot: AnimationSnapshot | null = null
417
424
 
418
425
  const controller = createReorderableList({
419
426
  getItems: () => items,
@@ -426,10 +433,12 @@ const controller = createReorderableList({
426
433
  onChange: () => render(),
427
434
  onBeforeReorder: (move, context) => {
428
435
  if (!context.alreadyPreviewed) {
429
- captureAnimationSnapshot()
436
+ animationSnapshot = captureAnimationSnapshot(itemElements)
430
437
  }
431
438
  },
432
439
  onReorder: (move) => {
440
+ animateFromSnapshot(animationSnapshot, itemElements)
441
+ animationSnapshot = null
433
442
  announce(`Moved ${move.item}`)
434
443
  },
435
444
  })
@@ -630,6 +639,10 @@ const result = positionTopLayerPopover(button, popover, {
630
639
 
631
640
  The helper also sets safe overflow styles (`max-width`, `max-height`, `overflow`, and `overscroll-behavior`) so long top-layer menus scroll instead of overflowing the viewport.
632
641
 
642
+ When CSS Anchor Positioning is available but the rendered top-layer rectangle
643
+ still overflows the viewport, the helper automatically switches to the same
644
+ manual fixed-positioning fallback used when anchors are unavailable.
645
+
633
646
  ### autoUpdateTopLayerPopover
634
647
 
635
648
  Like `autoUpdate`, but also listens to `visualViewport` scroll/resize events, which are important for top-layer popovers on mobile browsers.
@@ -899,6 +912,55 @@ Or provide a custom easing string:
899
912
  await animate(element, keyframes, { easing: 'cubic-bezier(0.68, -0.55, 0.27, 1.55)' })
900
913
  ```
901
914
 
915
+ ### captureAnimationSnapshot and animateFromSnapshot
916
+
917
+ Capture element positions before your renderer changes layout, then animate the
918
+ moved elements from their old positions to their new positions. This is useful
919
+ for FLIP-style reorder animations in framework adapters.
920
+
921
+ ```typescript
922
+ import { animateFromSnapshot, captureAnimationSnapshot } from '@inertiaui/vanilla'
923
+
924
+ const rows = () => document.querySelectorAll<HTMLElement>('[data-reorder-row]')
925
+ const snapshot = captureAnimationSnapshot(rows())
926
+
927
+ renderItemsInNewOrder()
928
+
929
+ animateFromSnapshot(snapshot, rows(), {
930
+ duration: 160,
931
+ easing: 'cubic-bezier(0.22, 1, 0.36, 1)',
932
+ fill: 'none',
933
+ minimumDelta: 0.5,
934
+ includeCurrentTransform: true,
935
+ })
936
+ ```
937
+
938
+ `captureAnimationSnapshot` returns `null` when Web Animations are unavailable or
939
+ the user prefers reduced motion. `animateFromSnapshot` only cancels previous
940
+ snapshot animations it started for the same element, leaving unrelated hover,
941
+ focus, and component animations alone.
942
+
943
+ #### Snapshot Animation Options
944
+
945
+ | Option | Type | Default | Description |
946
+ |--------|------|---------|-------------|
947
+ | `duration` | `number` | `160` | Animation duration in milliseconds |
948
+ | `easing` | `string \| EasingName` | `'out'` | Easing preset name or CSS easing string |
949
+ | `fill` | `FillMode` | `'none'` | Web Animations fill mode |
950
+ | `minimumDelta` | `number` | `0.5` | Ignore moves smaller than this many pixels |
951
+ | `includeCurrentTransform` | `boolean` | `true` | Fold the element's current translate transform into the next animation |
952
+
953
+ Use `prefersReducedMotion()` and `supportsWebAnimations()` when an adapter needs
954
+ to branch before capturing a snapshot:
955
+
956
+ ```typescript
957
+ import { prefersReducedMotion, supportsWebAnimations } from '@inertiaui/vanilla'
958
+
959
+ if (!prefersReducedMotion() && supportsWebAnimations()) {
960
+ const snapshot = captureAnimationSnapshot(rows())
961
+ }
962
+ ```
963
+
902
964
  ### cancelAnimations
903
965
 
904
966
  Cancel any running animations on an element:
package/dist/index.d.ts CHANGED
@@ -13,12 +13,25 @@
13
13
  */
14
14
  export declare function animate(element: HTMLElement, keyframes: Keyframe[], options?: AnimateOptions): Promise<Animation>;
15
15
 
16
+ /**
17
+ * Animate elements from a previously captured layout snapshot to their current
18
+ * positions. Only animations started by this helper are cancelled on later runs.
19
+ */
20
+ export declare function animateFromSnapshot(snapshot: AnimationSnapshot | null, elements: Iterable<HTMLElement | null | undefined>, options?: AnimateFromSnapshotOptions): Animation[];
21
+
22
+ export declare interface AnimateFromSnapshotOptions extends AnimateOptions {
23
+ minimumDelta?: number;
24
+ includeCurrentTransform?: boolean;
25
+ }
26
+
16
27
  export declare interface AnimateOptions {
17
28
  duration?: number;
18
29
  easing?: string | EasingName;
19
30
  fill?: FillMode;
20
31
  }
21
32
 
33
+ export declare type AnimationSnapshot = Map<HTMLElement, DOMRect>;
34
+
22
35
  export declare type AutoScrollAxis = 'x' | 'y' | 'both';
23
36
 
24
37
  export declare type AutoScrollContainer = Element | Window;
@@ -51,6 +64,12 @@ export declare function blank(value: unknown): boolean;
51
64
  */
52
65
  export declare function cancelAnimations(element: HTMLElement): void;
53
66
 
67
+ /**
68
+ * Capture current element rectangles before a renderer changes their order or
69
+ * position. Pass the snapshot to animateFromSnapshot after the DOM has updated.
70
+ */
71
+ export declare function captureAnimationSnapshot(elements: Iterable<HTMLElement | null | undefined>): AnimationSnapshot | null;
72
+
54
73
  export declare type CleanupFunction = () => void;
55
74
 
56
75
  /**
@@ -412,6 +431,8 @@ export declare function positionTopLayerPopover(reference: HTMLElement, floating
412
431
  */
413
432
  export declare function prefersDarkMode(strategy?: DarkModeStrategy): boolean;
414
433
 
434
+ export declare function prefersReducedMotion(): boolean;
435
+
415
436
  export declare function rejectNullValues<T>(target: T[]): Exclude<T, null>[];
416
437
 
417
438
  export declare function rejectNullValues<T extends Record<string, unknown>>(target: T): Partial<T>;
@@ -524,6 +545,8 @@ export declare function supportsAnchorPositioning(): boolean;
524
545
 
525
546
  export declare function supportsTopLayerAnchorPositioning(): boolean;
526
547
 
548
+ export declare function supportsWebAnimations(): boolean;
549
+
527
550
  export declare interface TopLayerPopoverPositionOptions {
528
551
  placement?: Placement;
529
552
  offset?: number;
package/dist/index.js CHANGED
@@ -83,6 +83,14 @@ var defaultOptions = {
83
83
  easing: "inOut",
84
84
  fill: "forwards"
85
85
  };
86
+ var snapshotAnimationOptions = {
87
+ duration: 160,
88
+ easing: "out",
89
+ fill: "none",
90
+ minimumDelta: .5,
91
+ includeCurrentTransform: true
92
+ };
93
+ var activeSnapshotAnimations = /* @__PURE__ */ new WeakMap();
86
94
  /**
87
95
  * Animate an element using the Web Animations API.
88
96
  * Returns a promise that resolves when the animation completes.
@@ -115,6 +123,98 @@ function animate(element, keyframes, options = {}) {
115
123
  function cancelAnimations(element) {
116
124
  element.getAnimations().forEach((animation) => animation.cancel());
117
125
  }
126
+ function prefersReducedMotion() {
127
+ return typeof window !== "undefined" && (window.matchMedia?.("(prefers-reduced-motion: reduce)").matches ?? false);
128
+ }
129
+ function supportsWebAnimations() {
130
+ return typeof Element !== "undefined" && typeof Element.prototype.animate === "function";
131
+ }
132
+ function connectedElements(elements) {
133
+ return Array.from(elements).filter((element) => element instanceof HTMLElement && element.isConnected);
134
+ }
135
+ function currentTranslate(element) {
136
+ const transform = getComputedStyle(element).transform;
137
+ if (!transform || transform === "none") return {
138
+ x: 0,
139
+ y: 0
140
+ };
141
+ try {
142
+ if (typeof DOMMatrixReadOnly === "undefined") return {
143
+ x: 0,
144
+ y: 0
145
+ };
146
+ const matrix = new DOMMatrixReadOnly(transform);
147
+ return {
148
+ x: matrix.m41,
149
+ y: matrix.m42
150
+ };
151
+ } catch {
152
+ return {
153
+ x: 0,
154
+ y: 0
155
+ };
156
+ }
157
+ }
158
+ function resolveAnimationOptions(options) {
159
+ const resolvedEasing = options.easing in easings ? easings[options.easing] : options.easing;
160
+ return {
161
+ duration: options.duration,
162
+ easing: resolvedEasing,
163
+ fill: options.fill
164
+ };
165
+ }
166
+ function cancelSnapshotAnimation(element) {
167
+ const animation = activeSnapshotAnimations.get(element);
168
+ if (animation) {
169
+ animation.cancel();
170
+ activeSnapshotAnimations.delete(element);
171
+ }
172
+ }
173
+ /**
174
+ * Capture current element rectangles before a renderer changes their order or
175
+ * position. Pass the snapshot to animateFromSnapshot after the DOM has updated.
176
+ */
177
+ function captureAnimationSnapshot(elements) {
178
+ if (typeof window === "undefined" || prefersReducedMotion() || !supportsWebAnimations()) return null;
179
+ const snapshot = /* @__PURE__ */ new Map();
180
+ for (const element of connectedElements(elements)) snapshot.set(element, element.getBoundingClientRect());
181
+ return snapshot.size > 0 ? snapshot : null;
182
+ }
183
+ /**
184
+ * Animate elements from a previously captured layout snapshot to their current
185
+ * positions. Only animations started by this helper are cancelled on later runs.
186
+ */
187
+ function animateFromSnapshot(snapshot, elements, options = {}) {
188
+ if (!snapshot || prefersReducedMotion() || !supportsWebAnimations()) return [];
189
+ const resolvedOptions = {
190
+ ...snapshotAnimationOptions,
191
+ ...options
192
+ };
193
+ const animations = [];
194
+ for (const element of connectedElements(elements)) {
195
+ const before = snapshot.get(element);
196
+ if (!before) continue;
197
+ const after = element.getBoundingClientRect();
198
+ const running = resolvedOptions.includeCurrentTransform ? currentTranslate(element) : {
199
+ x: 0,
200
+ y: 0
201
+ };
202
+ const deltaX = before.left - after.left + running.x;
203
+ const deltaY = before.top - after.top + running.y;
204
+ if (Math.abs(deltaX) < resolvedOptions.minimumDelta && Math.abs(deltaY) < resolvedOptions.minimumDelta) {
205
+ cancelSnapshotAnimation(element);
206
+ continue;
207
+ }
208
+ cancelSnapshotAnimation(element);
209
+ const animation = element.animate([{ transform: `translate3d(${deltaX}px, ${deltaY}px, 0)` }, { transform: "translate3d(0, 0, 0)" }], resolveAnimationOptions(resolvedOptions));
210
+ activeSnapshotAnimations.set(element, animation);
211
+ animations.push(animation);
212
+ animation.finished.catch(() => animation).finally(() => {
213
+ if (activeSnapshotAnimations.get(element) === animation) activeSnapshotAnimations.delete(element);
214
+ });
215
+ }
216
+ return animations;
217
+ }
118
218
  //#endregion
119
219
  //#region src/dialog.ts
120
220
  var FOCUSABLE_SELECTORS = [
@@ -1132,23 +1232,187 @@ function focusFirstEnabledElement(elements) {
1132
1232
  return false;
1133
1233
  }
1134
1234
  //#endregion
1135
- //#region src/position.ts
1235
+ //#region src/position/style.ts
1236
+ function setStyleProperty(style, property, value) {
1237
+ if (style.getPropertyValue(property) !== value) style.setProperty(property, value);
1238
+ }
1239
+ function removeStyleProperty(style, property) {
1240
+ if (style.getPropertyValue(property) !== "") style.removeProperty(property);
1241
+ }
1242
+ function captureStyleProperty(style, property) {
1243
+ return {
1244
+ value: style.getPropertyValue(property),
1245
+ priority: style.getPropertyPriority(property)
1246
+ };
1247
+ }
1248
+ function restoreStyleProperty(style, property, stored) {
1249
+ if (stored.value === "") {
1250
+ removeStyleProperty(style, property);
1251
+ return;
1252
+ }
1253
+ style.setProperty(property, stored.value, stored.priority);
1254
+ }
1255
+ //#endregion
1256
+ //#region src/position/anchor.ts
1136
1257
  var ANCHOR_CLASS_PREFIX = "iui-anchor-";
1137
1258
  var _supportsAnchor = null;
1259
+ var _supportsAnchorFlip = null;
1138
1260
  var _supportsTopLayerAnchor = null;
1139
1261
  var _supportsTopLayerAnchorSizing = null;
1262
+ var _isWebKit = null;
1140
1263
  function supportsAnchorPositioning() {
1141
1264
  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)");
1142
1265
  return _supportsAnchor;
1143
1266
  }
1144
1267
  function supportsTopLayerAnchorPositioning() {
1145
- if (_supportsTopLayerAnchor === null) _supportsTopLayerAnchor = supportsAnchorPositioning() && CSS.supports("width", "anchor-size(width)");
1268
+ if (_supportsTopLayerAnchor === null) _supportsTopLayerAnchor = supportsAnchorPositioning() && CSS.supports("width", "anchor-size(width)") && !isWebKit();
1146
1269
  return _supportsTopLayerAnchor;
1147
1270
  }
1271
+ function isWebKit() {
1272
+ if (_isWebKit === null) _isWebKit = typeof CSS !== "undefined" && typeof CSS.supports === "function" && CSS.supports("-webkit-backdrop-filter", "none");
1273
+ return _isWebKit;
1274
+ }
1275
+ function supportsAnchorFlip() {
1276
+ if (_supportsAnchorFlip === null) _supportsAnchorFlip = supportsAnchorPositioning() && (CSS.supports("position-try-fallbacks", "flip-block") || CSS.supports("position-try", "flip-block"));
1277
+ return _supportsAnchorFlip;
1278
+ }
1148
1279
  function supportsTopLayerAnchorSizing() {
1149
1280
  if (_supportsTopLayerAnchorSizing === null) _supportsTopLayerAnchorSizing = supportsTopLayerAnchorPositioning() && CSS.supports("height", "max-content") && CSS.supports("max-height", "stretch");
1150
1281
  return _supportsTopLayerAnchorSizing;
1151
1282
  }
1283
+ var anchorStyleId = "inertiaui-anchor-styles";
1284
+ function ensureAnchorStylesheet() {
1285
+ let style = document.getElementById(anchorStyleId);
1286
+ if (!style) {
1287
+ style = document.createElement("style");
1288
+ style.id = anchorStyleId;
1289
+ document.head.appendChild(style);
1290
+ }
1291
+ return style.sheet;
1292
+ }
1293
+ function findAnchorClass(element) {
1294
+ return Array.from(element.classList).find((c) => c.startsWith(ANCHOR_CLASS_PREFIX));
1295
+ }
1296
+ function removeAnchorRule(className) {
1297
+ const style = document.getElementById(anchorStyleId);
1298
+ if (!style?.sheet) return;
1299
+ for (let i = 0; i < style.sheet.cssRules.length; i++) if (style.sheet.cssRules[i].selectorText === `.${className}`) {
1300
+ style.sheet.deleteRule(i);
1301
+ return;
1302
+ }
1303
+ }
1304
+ function setupAnchorPositioning(reference, floating, placement, offset, flip) {
1305
+ const id = generateId(ANCHOR_CLASS_PREFIX);
1306
+ const anchorName = `--${id}`;
1307
+ reference.style.anchorName = anchorName;
1308
+ floating.style.positionAnchor = anchorName;
1309
+ floating.style.position = "fixed";
1310
+ const sheet = ensureAnchorStylesheet();
1311
+ const className = id;
1312
+ const positionRules = getAnchorPositionRules(placement, offset);
1313
+ let tryFallback = "";
1314
+ if (flip) tryFallback = `position-try-fallbacks: flip-block, flip-inline; position-try: flip-block, flip-inline;`;
1315
+ const rule = `.${className} { ${positionRules} ${tryFallback} }`;
1316
+ sheet.insertRule(rule, sheet.cssRules.length);
1317
+ floating.classList.add(className);
1318
+ return className;
1319
+ }
1320
+ function cleanupAnchorPositioning(reference, floating, className) {
1321
+ reference.style.anchorName = "";
1322
+ floating.style.positionAnchor = "";
1323
+ floating.style.position = "";
1324
+ floating.classList.remove(className);
1325
+ removeAnchorRule(className);
1326
+ }
1327
+ function detachAnchorPositioning(reference, floating) {
1328
+ reference.style.removeProperty("anchor-name");
1329
+ floating.style.removeProperty("position-anchor");
1330
+ for (const className of Array.from(floating.classList)) if (className.startsWith(ANCHOR_CLASS_PREFIX)) {
1331
+ floating.classList.remove(className);
1332
+ removeAnchorRule(className);
1333
+ }
1334
+ }
1335
+ function getAnchorPositionRules(placement, offset) {
1336
+ const [side, alignment] = placement.split("-");
1337
+ let positionRules = "";
1338
+ switch (side) {
1339
+ case "bottom":
1340
+ positionRules += `top: anchor(bottom);`;
1341
+ positionRules += `margin-top: ${offset}px;`;
1342
+ break;
1343
+ case "top":
1344
+ positionRules += `bottom: anchor(top);`;
1345
+ positionRules += `margin-bottom: ${offset}px;`;
1346
+ break;
1347
+ case "left":
1348
+ positionRules += `right: anchor(left);`;
1349
+ positionRules += `margin-right: ${offset}px;`;
1350
+ break;
1351
+ case "right":
1352
+ positionRules += `left: anchor(right);`;
1353
+ positionRules += `margin-left: ${offset}px;`;
1354
+ break;
1355
+ }
1356
+ if (side === "bottom" || side === "top") switch (alignment) {
1357
+ case "start":
1358
+ positionRules += `left: anchor(left);`;
1359
+ break;
1360
+ case "end":
1361
+ positionRules += `right: anchor(right);`;
1362
+ break;
1363
+ default:
1364
+ positionRules += `left: anchor(center); translate: -50% 0;`;
1365
+ break;
1366
+ }
1367
+ else switch (alignment) {
1368
+ case "start":
1369
+ positionRules += `top: anchor(top);`;
1370
+ break;
1371
+ case "end":
1372
+ positionRules += `bottom: anchor(bottom);`;
1373
+ break;
1374
+ default:
1375
+ positionRules += `top: anchor(center); translate: 0 -50%;`;
1376
+ break;
1377
+ }
1378
+ return positionRules;
1379
+ }
1380
+ function getTopLayerAnchorSizingRules(placement, viewportMargin) {
1381
+ const [side] = placement.split("-");
1382
+ if (side === "bottom") return `bottom: ${viewportMargin}px; height: max-content; max-height: stretch;`;
1383
+ if (side === "top") return `top: ${viewportMargin}px; height: max-content; max-height: stretch; align-self: end;`;
1384
+ return "";
1385
+ }
1386
+ function setupTopLayerAnchorPositioning(reference, floating, placement, offset, flip, matchReferenceWidth, maxWidth, viewportMargin, stretchToAvailableHeight) {
1387
+ const existingClass = findAnchorClass(floating);
1388
+ const existingAnchorName = existingClass ? `--${existingClass}` : "";
1389
+ const canReuseAnchor = !!existingClass && reference.style.getPropertyValue("anchor-name") === existingAnchorName && floating.style.getPropertyValue("position-anchor") === existingAnchorName;
1390
+ const className = canReuseAnchor ? existingClass : generateId(ANCHOR_CLASS_PREFIX);
1391
+ const anchorName = `--${className}`;
1392
+ const sheet = ensureAnchorStylesheet();
1393
+ if (canReuseAnchor) removeAnchorRule(className);
1394
+ else detachAnchorPositioning(reference, floating);
1395
+ reference.style.anchorName = anchorName;
1396
+ floating.style.positionAnchor = anchorName;
1397
+ removeStyleProperty(floating.style, "inset");
1398
+ removeStyleProperty(floating.style, "top");
1399
+ removeStyleProperty(floating.style, "right");
1400
+ removeStyleProperty(floating.style, "bottom");
1401
+ removeStyleProperty(floating.style, "left");
1402
+ removeStyleProperty(floating.style, "margin");
1403
+ setStyleProperty(floating.style, "position", "fixed");
1404
+ if (stretchToAvailableHeight) {
1405
+ setStyleProperty(floating.style, "height", "max-content");
1406
+ removeStyleProperty(floating.style, "max-height");
1407
+ } else removeStyleProperty(floating.style, "height");
1408
+ if (matchReferenceWidth) setStyleProperty(floating.style, "width", `min(anchor-size(width), ${maxWidth}px)`);
1409
+ 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) : ""} }`;
1410
+ sheet.insertRule(rule, sheet.cssRules.length);
1411
+ floating.classList.add(className);
1412
+ return className;
1413
+ }
1414
+ //#endregion
1415
+ //#region src/position/geometry.ts
1152
1416
  function isRtl$1() {
1153
1417
  return typeof document !== "undefined" && document.documentElement.dir === "rtl";
1154
1418
  }
@@ -1210,6 +1474,15 @@ function clampTopLayerCoordinates(x, y, floatingRect, placement, viewport, margi
1210
1474
  y: clamp$1(y, minY, maxY)
1211
1475
  };
1212
1476
  }
1477
+ function topLayerRectOverflowsViewport(rect, viewport) {
1478
+ const tolerance = .5;
1479
+ return rect.top < viewport.top - tolerance || rect.left < viewport.left - tolerance || rect.right > viewport.right + tolerance || rect.bottom > viewport.bottom + tolerance;
1480
+ }
1481
+ function referenceIntersectsViewport(reference) {
1482
+ const rect = reference.getBoundingClientRect();
1483
+ const viewport = getViewportRect();
1484
+ return rect.width > 0 && rect.height > 0 && rect.bottom > viewport.top && rect.top < viewport.bottom && rect.right > viewport.left && rect.left < viewport.right;
1485
+ }
1213
1486
  function getAvailableSpace(referenceRect, viewport, side, offset, margin) {
1214
1487
  if (side === "top") return referenceRect.top - viewport.top - offset - margin;
1215
1488
  if (side === "bottom") return viewport.bottom - referenceRect.bottom - offset - margin;
@@ -1297,9 +1570,9 @@ function clampToViewport(x, y, floatingRect) {
1297
1570
  y: Math.max(margin, Math.min(y, vh - floatingRect.height - margin))
1298
1571
  };
1299
1572
  }
1300
- function computeWithFallback(reference, floating, options = {}) {
1573
+ function computeWithFallback(reference, floating, options = {}, referenceRect) {
1301
1574
  const { placement = "bottom-start", offset = 0, flip = true } = options;
1302
- const refRect = reference.getBoundingClientRect();
1575
+ const refRect = referenceRect ?? reference.getBoundingClientRect();
1303
1576
  const floatingRect = floating.getBoundingClientRect();
1304
1577
  let { x, y } = computePositionFromRect(refRect, floatingRect, placement, offset);
1305
1578
  let actualPlacement = placement;
@@ -1319,178 +1592,8 @@ function computeWithFallback(reference, floating, options = {}) {
1319
1592
  placement: actualPlacement
1320
1593
  };
1321
1594
  }
1322
- var anchorStyleId = "inertiaui-anchor-styles";
1323
- function ensureAnchorStylesheet() {
1324
- let style = document.getElementById(anchorStyleId);
1325
- if (!style) {
1326
- style = document.createElement("style");
1327
- style.id = anchorStyleId;
1328
- document.head.appendChild(style);
1329
- }
1330
- return style.sheet;
1331
- }
1332
- function findAnchorClass(element) {
1333
- return Array.from(element.classList).find((c) => c.startsWith(ANCHOR_CLASS_PREFIX));
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
- }
1343
- function setupAnchorPositioning(reference, floating, placement, offset, flip) {
1344
- const id = generateId(ANCHOR_CLASS_PREFIX);
1345
- const anchorName = `--${id}`;
1346
- reference.style.anchorName = anchorName;
1347
- floating.style.positionAnchor = anchorName;
1348
- floating.style.position = "fixed";
1349
- const [side, alignment] = placement.split("-");
1350
- const sheet = ensureAnchorStylesheet();
1351
- const className = id;
1352
- let positionRules = "";
1353
- let tryFallback = "";
1354
- switch (side) {
1355
- case "bottom":
1356
- positionRules += `top: anchor(bottom);`;
1357
- positionRules += `margin-top: ${offset}px;`;
1358
- break;
1359
- case "top":
1360
- positionRules += `bottom: anchor(top);`;
1361
- positionRules += `margin-bottom: ${offset}px;`;
1362
- break;
1363
- case "left":
1364
- positionRules += `right: anchor(left);`;
1365
- positionRules += `margin-right: ${offset}px;`;
1366
- break;
1367
- case "right":
1368
- positionRules += `left: anchor(right);`;
1369
- positionRules += `margin-left: ${offset}px;`;
1370
- break;
1371
- }
1372
- if (side === "bottom" || side === "top") switch (alignment) {
1373
- case "start":
1374
- positionRules += `left: anchor(left);`;
1375
- break;
1376
- case "end":
1377
- positionRules += `right: anchor(right);`;
1378
- break;
1379
- default:
1380
- positionRules += `left: anchor(center); translate: -50% 0;`;
1381
- break;
1382
- }
1383
- else switch (alignment) {
1384
- case "start":
1385
- positionRules += `top: anchor(top);`;
1386
- break;
1387
- case "end":
1388
- positionRules += `bottom: anchor(bottom);`;
1389
- break;
1390
- default:
1391
- positionRules += `top: anchor(center); translate: 0 -50%;`;
1392
- break;
1393
- }
1394
- if (flip) tryFallback = `position-try-fallbacks: flip-block, flip-inline;`;
1395
- const rule = `.${className} { ${positionRules} ${tryFallback} }`;
1396
- sheet.insertRule(rule, sheet.cssRules.length);
1397
- floating.classList.add(className);
1398
- return className;
1399
- }
1400
- function cleanupAnchorPositioning(reference, floating, className) {
1401
- reference.style.anchorName = "";
1402
- floating.style.positionAnchor = "";
1403
- floating.style.position = "";
1404
- floating.classList.remove(className);
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%;`;
1456
- break;
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;
1493
- }
1595
+ //#endregion
1596
+ //#region src/position/floating.ts
1494
1597
  var SIZE_MARGIN = 8;
1495
1598
  /**
1496
1599
  * Cap the floating element's height to the space available between its anchored
@@ -1503,8 +1606,8 @@ var SIZE_MARGIN = 8;
1503
1606
  * direction is derived from the rendered rects: a menu whose top sits above the
1504
1607
  * reference opens upward (its bottom edge is anchored); otherwise it opens downward.
1505
1608
  */
1506
- function applySize(reference, floating, offset, side) {
1507
- const refRect = reference.getBoundingClientRect();
1609
+ function applySize(reference, floating, offset, side, refRect) {
1610
+ refRect ??= reference.getBoundingClientRect();
1508
1611
  const vh = window.innerHeight;
1509
1612
  let available;
1510
1613
  if (side === "top") available = refRect.top - offset - SIZE_MARGIN;
@@ -1519,7 +1622,7 @@ function applySize(reference, floating, offset, side) {
1519
1622
  }
1520
1623
  function computePosition(reference, floating, options = {}) {
1521
1624
  const { placement = "bottom-start", offset = 0, flip = true, autoSize = false } = options;
1522
- if (supportsAnchorPositioning()) {
1625
+ if (supportsAnchorPositioning() && (!flip || supportsAnchorFlip())) {
1523
1626
  if (!findAnchorClass(floating)) setupAnchorPositioning(reference, floating, placement, offset, flip);
1524
1627
  if (autoSize) applySize(reference, floating, offset);
1525
1628
  const rect = floating.getBoundingClientRect();
@@ -1529,18 +1632,47 @@ function computePosition(reference, floating, options = {}) {
1529
1632
  placement
1530
1633
  };
1531
1634
  }
1532
- if (autoSize) applySize(reference, floating, offset, placement.split("-")[0]);
1635
+ let referenceRect;
1636
+ if (autoSize) {
1637
+ referenceRect = reference.getBoundingClientRect();
1638
+ applySize(reference, floating, offset, placement.split("-")[0], referenceRect);
1639
+ }
1533
1640
  const result = computeWithFallback(reference, floating, {
1534
1641
  placement,
1535
1642
  offset,
1536
1643
  flip
1537
- });
1644
+ }, referenceRect);
1538
1645
  floating.style.position = "fixed";
1539
1646
  floating.style.top = `${result.y}px`;
1540
1647
  floating.style.left = `${result.x}px`;
1541
- if (autoSize) applySize(reference, floating, offset, result.placement.split("-")[0]);
1648
+ if (autoSize) applySize(reference, floating, offset, result.placement.split("-")[0], referenceRect);
1542
1649
  return result;
1543
1650
  }
1651
+ function observeElementResize(reference, floating, scheduleUpdate) {
1652
+ if (typeof ResizeObserver !== "function") return () => {};
1653
+ let reobserveFrame;
1654
+ const resizeObserver = new ResizeObserver(([firstEntry]) => {
1655
+ const referenceResized = firstEntry?.target === reference;
1656
+ if (referenceResized) resizeObserver.unobserve(floating);
1657
+ scheduleUpdate();
1658
+ if (referenceResized) {
1659
+ if (reobserveFrame !== void 0) cancelAnimationFrame(reobserveFrame);
1660
+ reobserveFrame = requestAnimationFrame(() => {
1661
+ reobserveFrame = void 0;
1662
+ resizeObserver.observe(floating);
1663
+ });
1664
+ }
1665
+ });
1666
+ resizeObserver.observe(reference);
1667
+ resizeObserver.observe(floating);
1668
+ return () => {
1669
+ if (reobserveFrame !== void 0) {
1670
+ cancelAnimationFrame(reobserveFrame);
1671
+ reobserveFrame = void 0;
1672
+ }
1673
+ resizeObserver.disconnect();
1674
+ };
1675
+ }
1544
1676
  function autoUpdate(reference, floating, update) {
1545
1677
  let rafId;
1546
1678
  function scheduleUpdate() {
@@ -1551,10 +1683,11 @@ function autoUpdate(reference, floating, update) {
1551
1683
  });
1552
1684
  }
1553
1685
  window.addEventListener("resize", scheduleUpdate);
1554
- window.addEventListener("scroll", scheduleUpdate, true);
1555
- const resizeObserver = new ResizeObserver(scheduleUpdate);
1556
- resizeObserver.observe(reference);
1557
- resizeObserver.observe(floating);
1686
+ window.addEventListener("scroll", scheduleUpdate, {
1687
+ passive: true,
1688
+ capture: true
1689
+ });
1690
+ const cleanupResizeObserver = observeElementResize(reference, floating, scheduleUpdate);
1558
1691
  let cleaned = false;
1559
1692
  return function cleanup() {
1560
1693
  if (cleaned) return;
@@ -1562,25 +1695,85 @@ function autoUpdate(reference, floating, update) {
1562
1695
  if (rafId !== void 0) cancelAnimationFrame(rafId);
1563
1696
  window.removeEventListener("resize", scheduleUpdate);
1564
1697
  window.removeEventListener("scroll", scheduleUpdate, true);
1565
- resizeObserver.disconnect();
1698
+ cleanupResizeObserver();
1566
1699
  const anchorClass = findAnchorClass(floating);
1567
1700
  if (anchorClass) cleanupAnchorPositioning(reference, floating, anchorClass);
1568
1701
  };
1569
1702
  }
1703
+ //#endregion
1704
+ //#region src/position/topLayer.ts
1705
+ function observeTopLayerElementResize(reference, floating, scheduleUpdate, shouldObserveFloating) {
1706
+ if (typeof ResizeObserver !== "function") return {
1707
+ cleanup: () => {},
1708
+ syncFloatingObserver: () => {}
1709
+ };
1710
+ let floatingObserved = false;
1711
+ let floatingObserverDeferred = false;
1712
+ let reobserveFrame;
1713
+ const resizeObserver = new ResizeObserver((entries) => {
1714
+ const referenceResized = entries.some((entry) => entry.target === reference);
1715
+ if (entries.some((entry) => entry.target === floating) && !referenceResized && !shouldObserveFloating()) {
1716
+ syncFloatingObserver();
1717
+ return;
1718
+ }
1719
+ if (referenceResized && floatingObserved) {
1720
+ resizeObserver.unobserve(floating);
1721
+ floatingObserved = false;
1722
+ floatingObserverDeferred = true;
1723
+ }
1724
+ scheduleUpdate();
1725
+ if (referenceResized) {
1726
+ if (reobserveFrame !== void 0) cancelAnimationFrame(reobserveFrame);
1727
+ reobserveFrame = requestAnimationFrame(() => {
1728
+ reobserveFrame = void 0;
1729
+ floatingObserverDeferred = false;
1730
+ syncFloatingObserver();
1731
+ });
1732
+ }
1733
+ });
1734
+ const syncFloatingObserver = () => {
1735
+ if (floatingObserverDeferred) return;
1736
+ if (shouldObserveFloating()) {
1737
+ if (!floatingObserved) {
1738
+ resizeObserver.observe(floating);
1739
+ floatingObserved = true;
1740
+ }
1741
+ return;
1742
+ }
1743
+ if (floatingObserved) {
1744
+ resizeObserver.unobserve(floating);
1745
+ floatingObserved = false;
1746
+ }
1747
+ };
1748
+ resizeObserver.observe(reference);
1749
+ syncFloatingObserver();
1750
+ return {
1751
+ cleanup: () => {
1752
+ if (reobserveFrame !== void 0) {
1753
+ cancelAnimationFrame(reobserveFrame);
1754
+ reobserveFrame = void 0;
1755
+ }
1756
+ resizeObserver.disconnect();
1757
+ floatingObserved = false;
1758
+ floatingObserverDeferred = false;
1759
+ },
1760
+ syncFloatingObserver
1761
+ };
1762
+ }
1570
1763
  function positionTopLayerPopover(reference, floating, options = {}) {
1571
1764
  const { placement = "bottom-start", offset = 4, flip = true, matchReferenceWidth = false, viewportMargin = 8, anchorPositioning = true } = options;
1572
1765
  const viewport = getViewportRect();
1573
1766
  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";
1767
+ setStyleProperty(floating.style, "position", "fixed");
1768
+ setStyleProperty(floating.style, "box-sizing", "border-box");
1769
+ setStyleProperty(floating.style, "max-width", `${maxWidth}px`);
1770
+ setStyleProperty(floating.style, "overflow-x", "auto");
1771
+ setStyleProperty(floating.style, "overflow-y", "auto");
1772
+ setStyleProperty(floating.style, "overscroll-behavior", "contain");
1580
1773
  const referenceRect = reference.getBoundingClientRect();
1581
1774
  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`;
1775
+ if (anchorPositioning && supportsTopLayerAnchorPositioning() && (!flip || supportsAnchorFlip())) {
1776
+ if (matchReferenceWidth) setStyleProperty(floating.style, "width", `${Math.min(referenceRect.width, maxWidth)}px`);
1584
1777
  const measuredRect = floating.getBoundingClientRect();
1585
1778
  const resolvedPlacement = resolveTopLayerPlacement(placement, referenceRect, {
1586
1779
  width: Math.max(measuredRect.width, floating.scrollWidth),
@@ -1588,26 +1781,26 @@ function positionTopLayerPopover(reference, floating, options = {}) {
1588
1781
  }, viewport, offset, viewportMargin, flip);
1589
1782
  const [resolvedSide] = resolvedPlacement.split("-");
1590
1783
  const stretchToAvailableHeight = (resolvedSide === "top" || resolvedSide === "bottom") && supportsTopLayerAnchorSizing();
1591
- if (stretchToAvailableHeight) floating.style.removeProperty("max-height");
1784
+ if (stretchToAvailableHeight) removeStyleProperty(floating.style, "max-height");
1592
1785
  else {
1593
1786
  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`;
1787
+ setStyleProperty(floating.style, "max-height", `${availableHeight}px`);
1595
1788
  }
1596
- setupTopLayerAnchorPositioning(reference, floating, resolvedPlacement, offset, matchReferenceWidth, maxWidth, viewportMargin, stretchToAvailableHeight);
1789
+ setupTopLayerAnchorPositioning(reference, floating, resolvedPlacement, offset, flip, matchReferenceWidth, maxWidth, viewportMargin, stretchToAvailableHeight);
1597
1790
  const finalRect = floating.getBoundingClientRect();
1598
- return {
1791
+ if (!topLayerRectOverflowsViewport(finalRect, viewport)) return {
1599
1792
  x: finalRect.left,
1600
1793
  y: finalRect.top,
1601
1794
  placement: resolvedPlacement
1602
1795
  };
1603
1796
  }
1604
1797
  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`;
1798
+ setStyleProperty(floating.style, "inset", "auto");
1799
+ setStyleProperty(floating.style, "right", "auto");
1800
+ setStyleProperty(floating.style, "bottom", "auto");
1801
+ setStyleProperty(floating.style, "margin", "0");
1802
+ removeStyleProperty(floating.style, "height");
1803
+ if (matchReferenceWidth) setStyleProperty(floating.style, "width", `${Math.min(referenceRect.width, maxWidth)}px`);
1611
1804
  const measuredRect = floating.getBoundingClientRect();
1612
1805
  const resolvedPlacement = resolveTopLayerPlacement(placement, referenceRect, {
1613
1806
  width: Math.max(measuredRect.width, floating.scrollWidth),
@@ -1615,13 +1808,13 @@ function positionTopLayerPopover(reference, floating, options = {}) {
1615
1808
  }, viewport, offset, viewportMargin, flip);
1616
1809
  const [resolvedSide] = resolvedPlacement.split("-");
1617
1810
  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`;
1811
+ if (resolvedSide === "top" || resolvedSide === "bottom") setStyleProperty(floating.style, "max-height", `${availableHeight}px`);
1812
+ else setStyleProperty(floating.style, "max-height", `${viewportHeight}px`);
1620
1813
  const floatingRect = floating.getBoundingClientRect();
1621
1814
  const coordinates = computePositionFromRect(referenceRect, floatingRect, resolvedPlacement, offset);
1622
1815
  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`;
1816
+ setStyleProperty(floating.style, "left", `${Math.round(x)}px`);
1817
+ setStyleProperty(floating.style, "top", `${Math.round(y)}px`);
1625
1818
  return {
1626
1819
  x,
1627
1820
  y,
@@ -1629,30 +1822,168 @@ function positionTopLayerPopover(reference, floating, options = {}) {
1629
1822
  };
1630
1823
  }
1631
1824
  function autoUpdateTopLayerPopover(reference, floating, update) {
1632
- const cleanupAutoUpdate = autoUpdate(reference, floating, update);
1633
1825
  const visualViewport = window.visualViewport;
1634
- let rafId = null;
1826
+ const browserAnchorsPopover = () => supportsTopLayerAnchorPositioning() && findAnchorClass(floating) !== void 0;
1827
+ let rafId;
1828
+ let restoreMotionFrame;
1829
+ let scrollListenersAttached = false;
1830
+ let syncFloatingResizeObserver = () => {};
1831
+ let referenceHidden = !referenceIntersectsViewport(reference);
1832
+ let anchorParked = false;
1833
+ let parkedStyles;
1834
+ let restoreVisibilityAfterUpdate = false;
1835
+ const hasReferenceVisibilityObserver = typeof IntersectionObserver === "function";
1635
1836
  const scheduleUpdate = () => {
1636
- if (rafId !== null) return;
1837
+ if (rafId !== void 0) return;
1637
1838
  rafId = requestAnimationFrame(() => {
1638
- rafId = null;
1639
- update();
1839
+ rafId = void 0;
1840
+ syncReferenceVisibility();
1841
+ if (!anchorParked) update();
1842
+ syncScrollListeners();
1843
+ syncFloatingResizeObserver();
1844
+ if (restoreVisibilityAfterUpdate && !anchorParked) restoreParkedVisibility();
1845
+ });
1846
+ };
1847
+ const cancelMotionRestore = () => {
1848
+ if (restoreMotionFrame === void 0) return;
1849
+ cancelAnimationFrame(restoreMotionFrame);
1850
+ restoreMotionFrame = void 0;
1851
+ };
1852
+ const restoreParkedMotionStyles = () => {
1853
+ if (!parkedStyles) {
1854
+ floating.removeAttribute("data-inertiaui-top-layer-parked");
1855
+ return;
1856
+ }
1857
+ restoreStyleProperty(floating.style, "transition", parkedStyles.transition);
1858
+ restoreStyleProperty(floating.style, "animation", parkedStyles.animation);
1859
+ floating.removeAttribute("data-inertiaui-top-layer-parked");
1860
+ };
1861
+ const scheduleMotionRestore = () => {
1862
+ cancelMotionRestore();
1863
+ restoreMotionFrame = requestAnimationFrame(() => {
1864
+ restoreMotionFrame = void 0;
1865
+ restoreParkedMotionStyles();
1866
+ parkedStyles = void 0;
1867
+ });
1868
+ };
1869
+ const handleScroll = () => {
1870
+ syncReferenceVisibility();
1871
+ if (anchorParked || browserAnchorsPopover()) return;
1872
+ scheduleUpdate();
1873
+ };
1874
+ const addScrollListeners = () => {
1875
+ if (scrollListenersAttached) return;
1876
+ scrollListenersAttached = true;
1877
+ window.addEventListener("scroll", handleScroll, {
1878
+ passive: true,
1879
+ capture: true
1640
1880
  });
1881
+ visualViewport?.addEventListener("scroll", handleScroll, { passive: true });
1882
+ };
1883
+ const removeScrollListeners = () => {
1884
+ if (!scrollListenersAttached) return;
1885
+ scrollListenersAttached = false;
1886
+ window.removeEventListener("scroll", handleScroll, true);
1887
+ visualViewport?.removeEventListener("scroll", handleScroll);
1888
+ };
1889
+ const syncScrollListeners = () => {
1890
+ if (anchorParked && hasReferenceVisibilityObserver) {
1891
+ removeScrollListeners();
1892
+ return;
1893
+ }
1894
+ addScrollListeners();
1895
+ };
1896
+ const parkPopover = () => {
1897
+ if (anchorParked) return;
1898
+ if (restoreVisibilityAfterUpdate) restoreVisibilityAfterUpdate = false;
1899
+ else if (!parkedStyles) parkedStyles = {
1900
+ visibility: captureStyleProperty(floating.style, "visibility"),
1901
+ transition: captureStyleProperty(floating.style, "transition"),
1902
+ animation: captureStyleProperty(floating.style, "animation")
1903
+ };
1904
+ cancelMotionRestore();
1905
+ floating.setAttribute("data-inertiaui-top-layer-parked", "");
1906
+ floating.style.setProperty("transition", "none", "important");
1907
+ floating.style.setProperty("animation", "none", "important");
1908
+ floating.style.setProperty("visibility", "hidden");
1909
+ anchorParked = true;
1910
+ syncScrollListeners();
1911
+ syncFloatingResizeObserver();
1912
+ };
1913
+ const restoreParkedVisibility = () => {
1914
+ if (!parkedStyles) {
1915
+ restoreVisibilityAfterUpdate = false;
1916
+ return;
1917
+ }
1918
+ restoreStyleProperty(floating.style, "visibility", parkedStyles.visibility);
1919
+ restoreVisibilityAfterUpdate = false;
1920
+ scheduleMotionRestore();
1641
1921
  };
1922
+ const restoreParkedPopover = (schedule = true) => {
1923
+ if (!anchorParked) return;
1924
+ anchorParked = false;
1925
+ if (schedule) {
1926
+ restoreVisibilityAfterUpdate = true;
1927
+ scheduleUpdate();
1928
+ return;
1929
+ }
1930
+ restoreParkedVisibility();
1931
+ };
1932
+ const syncReferenceVisibility = (visible = referenceIntersectsViewport(reference)) => {
1933
+ referenceHidden = !visible;
1934
+ if (visible) {
1935
+ restoreParkedPopover();
1936
+ return;
1937
+ }
1938
+ parkPopover();
1939
+ };
1940
+ let cleanupReferenceVisibilityObserver = () => {};
1941
+ if (typeof IntersectionObserver === "function") {
1942
+ const intersectionObserver = new IntersectionObserver(([entry]) => {
1943
+ syncReferenceVisibility(Boolean(entry?.isIntersecting || (entry?.intersectionRatio ?? 0) > 0));
1944
+ });
1945
+ intersectionObserver.observe(reference);
1946
+ cleanupReferenceVisibilityObserver = () => {
1947
+ intersectionObserver.disconnect();
1948
+ };
1949
+ }
1950
+ window.addEventListener("resize", scheduleUpdate);
1642
1951
  visualViewport?.addEventListener("resize", scheduleUpdate);
1643
- visualViewport?.addEventListener("scroll", scheduleUpdate);
1952
+ syncScrollListeners();
1953
+ syncReferenceVisibility(!referenceHidden);
1954
+ const elementResizeObserver = observeTopLayerElementResize(reference, floating, scheduleUpdate, () => !anchorParked && !browserAnchorsPopover());
1955
+ syncFloatingResizeObserver = elementResizeObserver.syncFloatingObserver;
1956
+ let cleaned = false;
1644
1957
  return () => {
1645
- cleanupAutoUpdate();
1646
- if (rafId !== null) {
1958
+ if (cleaned) return;
1959
+ cleaned = true;
1960
+ if (rafId !== void 0) {
1647
1961
  cancelAnimationFrame(rafId);
1648
- rafId = null;
1962
+ rafId = void 0;
1649
1963
  }
1964
+ cancelMotionRestore();
1965
+ window.removeEventListener("resize", scheduleUpdate);
1650
1966
  visualViewport?.removeEventListener("resize", scheduleUpdate);
1651
- visualViewport?.removeEventListener("scroll", scheduleUpdate);
1967
+ cleanupReferenceVisibilityObserver();
1968
+ elementResizeObserver.cleanup();
1969
+ removeScrollListeners();
1970
+ restoreParkedPopover(false);
1971
+ cancelMotionRestore();
1972
+ restoreParkedMotionStyles();
1973
+ parkedStyles = void 0;
1974
+ const anchorClass = findAnchorClass(floating);
1975
+ if (anchorClass) cleanupAnchorPositioning(reference, floating, anchorClass);
1652
1976
  };
1653
1977
  }
1654
1978
  //#endregion
1655
1979
  //#region src/nativePopover.ts
1980
+ function restoreVisibility(popover, visibility) {
1981
+ if (visibility === void 0) {
1982
+ popover.style.removeProperty("visibility");
1983
+ return;
1984
+ }
1985
+ popover.style.setProperty("visibility", visibility);
1986
+ }
1656
1987
  function createNativePopoverDisclosure(options) {
1657
1988
  let isOpen = false;
1658
1989
  let autoUpdateCleanup = null;
@@ -1688,7 +2019,17 @@ function createNativePopoverDisclosure(options) {
1688
2019
  autoUpdateCleanup = autoUpdateTopLayerPopover(elements.reference, elements.popover, updatePosition);
1689
2020
  };
1690
2021
  const showPopover = () => {
1691
- options.popover()?.showPopover();
2022
+ const elements = getElements();
2023
+ if (!elements) return;
2024
+ const { reference, popover } = elements;
2025
+ const previousVisibility = popover.style.getPropertyValue("visibility") || void 0;
2026
+ popover.style.setProperty("visibility", "hidden");
2027
+ try {
2028
+ popover.showPopover();
2029
+ positionTopLayerPopover(reference, popover, options.position);
2030
+ } finally {
2031
+ restoreVisibility(popover, previousVisibility);
2032
+ }
1692
2033
  };
1693
2034
  const hidePopover = () => {
1694
2035
  options.popover()?.hidePopover();
@@ -2134,4 +2475,4 @@ function formatColor(color, format = "hex", options = {}) {
2134
2475
  return includeAlpha ? `${normalized.hex}${Math.round(normalized.alpha * 255).toString(16).padStart(2, "0")}` : normalized.hex;
2135
2476
  }
2136
2477
  //#endregion
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 };
2478
+ 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 };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inertiaui/vanilla",
3
- "version": "1.2.1",
3
+ "version": "1.3.1",
4
4
  "author": "Pascal Baljet <pascal@protone.media>",
5
5
  "private": false,
6
6
  "license": "MIT",