@inertiaui/vanilla 1.2.1 → 1.3.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
@@ -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 = [
@@ -1210,6 +1310,10 @@ function clampTopLayerCoordinates(x, y, floatingRect, placement, viewport, margi
1210
1310
  y: clamp$1(y, minY, maxY)
1211
1311
  };
1212
1312
  }
1313
+ function topLayerRectOverflowsViewport(rect, viewport) {
1314
+ const tolerance = .5;
1315
+ return rect.top < viewport.top - tolerance || rect.left < viewport.left - tolerance || rect.right > viewport.right + tolerance || rect.bottom > viewport.bottom + tolerance;
1316
+ }
1213
1317
  function getAvailableSpace(referenceRect, viewport, side, offset, margin) {
1214
1318
  if (side === "top") return referenceRect.top - viewport.top - offset - margin;
1215
1319
  if (side === "bottom") return viewport.bottom - referenceRect.bottom - offset - margin;
@@ -1595,7 +1699,7 @@ function positionTopLayerPopover(reference, floating, options = {}) {
1595
1699
  }
1596
1700
  setupTopLayerAnchorPositioning(reference, floating, resolvedPlacement, offset, matchReferenceWidth, maxWidth, viewportMargin, stretchToAvailableHeight);
1597
1701
  const finalRect = floating.getBoundingClientRect();
1598
- return {
1702
+ if (!topLayerRectOverflowsViewport(finalRect, viewport)) return {
1599
1703
  x: finalRect.left,
1600
1704
  y: finalRect.top,
1601
1705
  placement: resolvedPlacement
@@ -2134,4 +2238,4 @@ function formatColor(color, format = "hex", options = {}) {
2134
2238
  return includeAlpha ? `${normalized.hex}${Math.round(normalized.alpha * 255).toString(16).padStart(2, "0")}` : normalized.hex;
2135
2239
  }
2136
2240
  //#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 };
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 };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inertiaui/vanilla",
3
- "version": "1.2.1",
3
+ "version": "1.3.0",
4
4
  "author": "Pascal Baljet <pascal@protone.media>",
5
5
  "private": false,
6
6
  "license": "MIT",