@astryxdesign/core 0.7.6 → 0.7.7-canary.0eb44a2

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.
Files changed (272) hide show
  1. package/dist/AppShell/AppShell.d.ts.map +1 -1
  2. package/dist/AppShell/AppShell.js +23 -3
  3. package/dist/Avatar/Avatar.d.ts.map +1 -1
  4. package/dist/Avatar/Avatar.js +1 -1
  5. package/dist/BottomSheet/BottomSheetPanel.d.ts.map +1 -1
  6. package/dist/BottomSheet/BottomSheetPanel.js +16 -9
  7. package/dist/Breadcrumbs/BreadcrumbItem.d.ts.map +1 -1
  8. package/dist/Breadcrumbs/BreadcrumbItem.js +2 -1
  9. package/dist/Button/Button.d.ts.map +1 -1
  10. package/dist/Button/Button.js +3 -2
  11. package/dist/Chat/ChatComposerInput.d.ts +9 -0
  12. package/dist/Chat/ChatComposerInput.d.ts.map +1 -1
  13. package/dist/Chat/ChatComposerInput.js +2 -0
  14. package/dist/Chat/ChatMessage.js +2 -2
  15. package/dist/Chat/chatMessage.vars.stylex.d.ts +8 -8
  16. package/dist/Chat/chatMessage.vars.stylex.js +8 -8
  17. package/dist/CommandPalette/CommandPaletteInput.d.ts.map +1 -1
  18. package/dist/CommandPalette/CommandPaletteInput.js +8 -1
  19. package/dist/DateInput/MonthScroller.d.ts.map +1 -1
  20. package/dist/DateInput/MonthScroller.js +72 -2
  21. package/dist/DateInput/Wheel.d.ts +17 -1
  22. package/dist/DateInput/Wheel.d.ts.map +1 -1
  23. package/dist/DateInput/Wheel.js +179 -19
  24. package/dist/DateRangeInput/DateRangeInput.d.ts.map +1 -1
  25. package/dist/DateRangeInput/DateRangeInput.js +63 -49
  26. package/dist/Dialog/Dialog.d.ts.map +1 -1
  27. package/dist/Dialog/Dialog.js +37 -1
  28. package/dist/Drawer/Drawer.d.ts.map +1 -1
  29. package/dist/Drawer/Drawer.js +6 -0
  30. package/dist/Drawer/useDrawerDialogPresence.d.ts.map +1 -1
  31. package/dist/Drawer/useDrawerDialogPresence.js +4 -0
  32. package/dist/DropdownMenu/DropdownMenu.d.ts.map +1 -1
  33. package/dist/DropdownMenu/DropdownMenu.js +20 -4
  34. package/dist/DropdownMenu/useMenuOverflow.d.ts +13 -3
  35. package/dist/DropdownMenu/useMenuOverflow.d.ts.map +1 -1
  36. package/dist/DropdownMenu/useMenuOverflow.js +31 -8
  37. package/dist/Field/PanelSearchInput.d.ts.map +1 -1
  38. package/dist/Field/PanelSearchInput.js +8 -1
  39. package/dist/Field/textEntryTraits.d.ts +6 -6
  40. package/dist/Field/textEntryTraits.js +6 -6
  41. package/dist/Layer/layerClickBoundary.d.ts +7 -1
  42. package/dist/Layer/layerClickBoundary.d.ts.map +1 -1
  43. package/dist/Layer/layerClickBoundary.js +2 -2
  44. package/dist/Layer/usePressPin.d.ts +95 -0
  45. package/dist/Layer/usePressPin.d.ts.map +1 -0
  46. package/dist/Layer/usePressPin.js +365 -0
  47. package/dist/Layer/useTouchTrigger.d.ts +23 -1
  48. package/dist/Layer/useTouchTrigger.d.ts.map +1 -1
  49. package/dist/Layer/useTouchTrigger.js +45 -7
  50. package/dist/Lightbox/Lightbox.d.ts.map +1 -1
  51. package/dist/Lightbox/Lightbox.js +2 -1
  52. package/dist/Link/Link.d.ts.map +1 -1
  53. package/dist/Link/Link.js +1 -0
  54. package/dist/Popover/usePopover.d.ts.map +1 -1
  55. package/dist/Popover/usePopover.js +56 -7
  56. package/dist/PowerSearch/PowerSearch.d.ts.map +1 -1
  57. package/dist/PowerSearch/PowerSearch.js +38 -30
  58. package/dist/ProgressBar/ProgressBar.d.ts +1 -1
  59. package/dist/ProgressBar/ProgressBar.d.ts.map +1 -1
  60. package/dist/ProgressBar/ProgressBar.js +52 -14
  61. package/dist/ProgressBar/ProgressBarTouch.d.ts +29 -0
  62. package/dist/ProgressBar/ProgressBarTouch.d.ts.map +1 -0
  63. package/dist/ProgressBar/ProgressBarTouch.js +91 -0
  64. package/dist/SegmentedControl/SegmentedControlItem.d.ts.map +1 -1
  65. package/dist/SegmentedControl/SegmentedControlItem.js +2 -1
  66. package/dist/Selector/Selector.d.ts.map +1 -1
  67. package/dist/Selector/Selector.js +25 -13
  68. package/dist/Slider/Slider.d.ts.map +1 -1
  69. package/dist/Slider/Slider.js +404 -131
  70. package/dist/Slider/sliderTouchController.d.ts +189 -0
  71. package/dist/Slider/sliderTouchController.d.ts.map +1 -0
  72. package/dist/Slider/sliderTouchController.js +1017 -0
  73. package/dist/Slider/useSliderTouch.d.ts +22 -0
  74. package/dist/Slider/useSliderTouch.d.ts.map +1 -0
  75. package/dist/Slider/useSliderTouch.js +56 -0
  76. package/dist/Switch/Switch.d.ts +1 -1
  77. package/dist/Switch/Switch.d.ts.map +1 -1
  78. package/dist/Switch/Switch.js +200 -46
  79. package/dist/Switch/switchFill.d.ts +31 -0
  80. package/dist/Switch/switchFill.d.ts.map +1 -0
  81. package/dist/Switch/switchFill.js +88 -0
  82. package/dist/Switch/switchTouch.d.ts +81 -0
  83. package/dist/Switch/switchTouch.d.ts.map +1 -0
  84. package/dist/Switch/switchTouch.js +133 -0
  85. package/dist/Switch/useSwitchTouch.d.ts +285 -0
  86. package/dist/Switch/useSwitchTouch.d.ts.map +1 -0
  87. package/dist/Switch/useSwitchTouch.js +998 -0
  88. package/dist/TabList/Tab.d.ts.map +1 -1
  89. package/dist/TabList/Tab.js +4 -3
  90. package/dist/Tokenizer/Tokenizer.d.ts.map +1 -1
  91. package/dist/Tokenizer/Tokenizer.js +12 -5
  92. package/dist/Tokenizer/TokenizerItemRemovableContext.d.ts +3 -0
  93. package/dist/Tokenizer/TokenizerItemRemovableContext.d.ts.map +1 -0
  94. package/dist/Tokenizer/TokenizerItemRemovableContext.js +17 -0
  95. package/dist/Tooltip/Tooltip.d.ts +30 -6
  96. package/dist/Tooltip/Tooltip.d.ts.map +1 -1
  97. package/dist/Tooltip/Tooltip.js +5 -0
  98. package/dist/Tooltip/index.d.ts +1 -1
  99. package/dist/Tooltip/index.d.ts.map +1 -1
  100. package/dist/Tooltip/useTooltip.d.ts +31 -5
  101. package/dist/Tooltip/useTooltip.d.ts.map +1 -1
  102. package/dist/Tooltip/useTooltip.js +59 -18
  103. package/dist/Typeahead/BaseTypeahead.d.ts.map +1 -1
  104. package/dist/Typeahead/BaseTypeahead.js +19 -9
  105. package/dist/Typeahead/Typeahead.d.ts.map +1 -1
  106. package/dist/Typeahead/Typeahead.js +26 -15
  107. package/dist/astryx.css +91 -8
  108. package/dist/gestures/GestureArena.d.ts +21 -2
  109. package/dist/gestures/GestureArena.d.ts.map +1 -1
  110. package/dist/gestures/GestureArena.js +23 -3
  111. package/dist/gestures/GestureHost.d.ts +123 -3
  112. package/dist/gestures/GestureHost.d.ts.map +1 -1
  113. package/dist/gestures/GestureHost.js +797 -15
  114. package/dist/gestures/GestureRecognizer.d.ts +15 -1
  115. package/dist/gestures/GestureRecognizer.d.ts.map +1 -1
  116. package/dist/gestures/GestureRecognizer.js +12 -0
  117. package/dist/gestures/PanGestureRecognizer.d.ts +8 -0
  118. package/dist/gestures/PanGestureRecognizer.d.ts.map +1 -1
  119. package/dist/gestures/PinchGestureRecognizer.d.ts +5 -1
  120. package/dist/gestures/PinchGestureRecognizer.d.ts.map +1 -1
  121. package/dist/gestures/PinchGestureRecognizer.js +10 -0
  122. package/dist/gestures/PressTracker.d.ts +6 -0
  123. package/dist/gestures/PressTracker.d.ts.map +1 -1
  124. package/dist/gestures/PressTracker.js +3 -0
  125. package/dist/gestures/ScreenEdgePanGestureRecognizer.d.ts +3 -3
  126. package/dist/gestures/ScreenEdgePanGestureRecognizer.d.ts.map +1 -1
  127. package/dist/gestures/ScreenEdgePanGestureRecognizer.js +7 -5
  128. package/dist/gestures/nativeScroll.d.ts +16 -2
  129. package/dist/gestures/nativeScroll.d.ts.map +1 -1
  130. package/dist/gestures/nativeScroll.js +39 -8
  131. package/dist/gestures/recognizerInternals.d.ts +4 -2
  132. package/dist/gestures/recognizerInternals.d.ts.map +1 -1
  133. package/dist/gestures/types.d.ts +17 -0
  134. package/dist/gestures/types.d.ts.map +1 -1
  135. package/dist/gestures/types.js +7 -0
  136. package/dist/gestures/usePressTracker.d.ts.map +1 -1
  137. package/dist/gestures/usePressTracker.js +1 -0
  138. package/dist/gestures/wheelSegmenter.d.ts +56 -0
  139. package/dist/gestures/wheelSegmenter.d.ts.map +1 -0
  140. package/dist/gestures/wheelSegmenter.js +122 -0
  141. package/dist/hooks/useAttachment.d.ts +16 -8
  142. package/dist/hooks/useAttachment.d.ts.map +1 -1
  143. package/dist/hooks/useAttachment.js +35 -15
  144. package/dist/hooks/useFocusTrap.d.ts +15 -0
  145. package/dist/hooks/useFocusTrap.d.ts.map +1 -1
  146. package/dist/hooks/useFocusTrap.js +13 -2
  147. package/dist/hooks/usePager.d.ts +261 -0
  148. package/dist/hooks/usePager.d.ts.map +1 -0
  149. package/dist/hooks/usePager.js +1169 -0
  150. package/dist/motion/animator.d.ts.map +1 -1
  151. package/dist/motion/animator.js +140 -19
  152. package/dist/motion/paging.d.ts +69 -0
  153. package/dist/motion/paging.d.ts.map +1 -0
  154. package/dist/motion/paging.js +148 -0
  155. package/dist/motion/uikit/index.d.ts +8 -4
  156. package/dist/motion/uikit/index.d.ts.map +1 -1
  157. package/dist/motion/uikit/index.js +8 -4
  158. package/dist/motion/uikit/paging.d.ts +171 -0
  159. package/dist/motion/uikit/paging.d.ts.map +1 -0
  160. package/dist/motion/uikit/paging.js +192 -0
  161. package/dist/motion/uikit/progressBar.d.ts +79 -0
  162. package/dist/motion/uikit/progressBar.d.ts.map +1 -0
  163. package/dist/motion/uikit/progressBar.js +102 -0
  164. package/dist/motion/uikit/scroll.d.ts +0 -19
  165. package/dist/motion/uikit/scroll.d.ts.map +1 -1
  166. package/dist/motion/uikit/scroll.js +2 -21
  167. package/dist/motion/uikit/slider.d.ts +97 -0
  168. package/dist/motion/uikit/slider.d.ts.map +1 -0
  169. package/dist/motion/uikit/slider.js +111 -0
  170. package/dist/motion/uikit/springs.d.ts +59 -30
  171. package/dist/motion/uikit/springs.d.ts.map +1 -1
  172. package/dist/motion/uikit/springs.js +64 -34
  173. package/dist/motion/uikit/switch.d.ts +166 -0
  174. package/dist/motion/uikit/switch.d.ts.map +1 -0
  175. package/dist/motion/uikit/switch.js +186 -0
  176. package/dist/privateAttributes/pressHoldsDrag.stylex.d.ts +18 -0
  177. package/dist/privateAttributes/pressHoldsDrag.stylex.d.ts.map +1 -0
  178. package/dist/privateAttributes/pressHoldsDrag.stylex.js +28 -0
  179. package/dist/utils/pressFeedback.d.ts.map +1 -1
  180. package/dist/utils/pressFeedback.js +5 -0
  181. package/dist/utils/selectionLock.d.ts +43 -0
  182. package/dist/utils/selectionLock.d.ts.map +1 -1
  183. package/dist/utils/selectionLock.js +394 -6
  184. package/package.json +5 -5
  185. package/src/AppShell/AppShell.doc.mjs +10 -0
  186. package/src/AppShell/AppShell.tsx +48 -2
  187. package/src/Avatar/Avatar.tsx +3 -1
  188. package/src/BottomSheet/BottomSheetPanel.tsx +16 -9
  189. package/src/Breadcrumbs/BreadcrumbItem.tsx +4 -1
  190. package/src/Button/Button.tsx +3 -2
  191. package/src/Chat/Chat.doc.mjs +1 -0
  192. package/src/Chat/ChatComposerInput.doc.mjs +11 -0
  193. package/src/Chat/ChatComposerInput.tsx +11 -0
  194. package/src/Chat/ChatMessage.tsx +2 -2
  195. package/src/Chat/chatMessage.vars.stylex.ts +8 -8
  196. package/src/CommandPalette/CommandPaletteInput.tsx +6 -0
  197. package/src/DateInput/MonthScroller.tsx +63 -5
  198. package/src/DateInput/Wheel.tsx +174 -14
  199. package/src/DateRangeInput/DateRangeInput.doc.mjs +3 -2
  200. package/src/DateRangeInput/DateRangeInput.tsx +117 -71
  201. package/src/Dialog/Dialog.tsx +37 -1
  202. package/src/Drawer/Drawer.tsx +6 -0
  203. package/src/Drawer/useDrawerDialogPresence.ts +4 -0
  204. package/src/DropdownMenu/DropdownMenu.tsx +28 -6
  205. package/src/DropdownMenu/useMenuOverflow.ts +44 -8
  206. package/src/Field/PanelSearchInput.tsx +6 -0
  207. package/src/Field/textEntryTraits.ts +6 -6
  208. package/src/Layer/layerClickBoundary.ts +2 -2
  209. package/src/Layer/usePressPin.ts +516 -0
  210. package/src/Layer/useTouchTrigger.ts +56 -6
  211. package/src/Lightbox/Lightbox.tsx +2 -1
  212. package/src/Link/Link.tsx +3 -0
  213. package/src/Popover/usePopover.tsx +71 -9
  214. package/src/PowerSearch/PowerSearch.tsx +38 -31
  215. package/src/ProgressBar/ProgressBar.doc.mjs +7 -5
  216. package/src/ProgressBar/ProgressBar.tsx +147 -16
  217. package/src/ProgressBar/ProgressBarTouch.ts +109 -0
  218. package/src/SegmentedControl/SegmentedControlItem.tsx +2 -1
  219. package/src/Selector/Selector.tsx +29 -2
  220. package/src/Slider/Slider.doc.mjs +11 -7
  221. package/src/Slider/Slider.tsx +539 -132
  222. package/src/Slider/sliderTouchController.ts +1209 -0
  223. package/src/Slider/useSliderTouch.ts +78 -0
  224. package/src/Switch/Switch.doc.mjs +3 -3
  225. package/src/Switch/Switch.tsx +412 -86
  226. package/src/Switch/switchFill.ts +106 -0
  227. package/src/Switch/switchTouch.ts +194 -0
  228. package/src/Switch/useSwitchTouch.ts +1121 -0
  229. package/src/TabList/Tab.tsx +5 -3
  230. package/src/Tokenizer/Tokenizer.tsx +15 -5
  231. package/src/Tokenizer/TokenizerItemRemovableContext.ts +22 -0
  232. package/src/Tooltip/Tooltip.doc.mjs +21 -6
  233. package/src/Tooltip/Tooltip.tsx +42 -5
  234. package/src/Tooltip/index.ts +1 -0
  235. package/src/Tooltip/useTooltip.doc.mjs +4 -2
  236. package/src/Tooltip/useTooltip.tsx +84 -21
  237. package/src/Typeahead/BaseTypeahead.tsx +16 -8
  238. package/src/Typeahead/Typeahead.tsx +29 -15
  239. package/src/gestures/GestureArena.ts +45 -4
  240. package/src/gestures/GestureHost.ts +958 -15
  241. package/src/gestures/GestureRecognizer.ts +28 -0
  242. package/src/gestures/PanGestureRecognizer.ts +8 -0
  243. package/src/gestures/PinchGestureRecognizer.ts +16 -1
  244. package/src/gestures/PressTracker.ts +10 -0
  245. package/src/gestures/README.md +82 -3
  246. package/src/gestures/ScreenEdgePanGestureRecognizer.ts +7 -5
  247. package/src/gestures/nativeScroll.ts +49 -9
  248. package/src/gestures/recognizerInternals.ts +9 -2
  249. package/src/gestures/types.ts +18 -0
  250. package/src/gestures/usePressTracker.ts +2 -0
  251. package/src/gestures/wheelSegmenter.ts +143 -0
  252. package/src/hooks/useAttachment.ts +56 -14
  253. package/src/hooks/useFocusTrap.ts +26 -2
  254. package/src/hooks/usePager.ts +1446 -0
  255. package/src/motion/MEASUREMENTS.md +36 -27
  256. package/src/motion/README.md +7 -3
  257. package/src/motion/animator.ts +193 -25
  258. package/src/motion/paging.ts +161 -0
  259. package/src/motion/uikit/index.ts +7 -4
  260. package/src/motion/uikit/paging.ts +193 -0
  261. package/src/motion/uikit/progressBar.ts +102 -0
  262. package/src/motion/uikit/scroll.ts +2 -18
  263. package/src/motion/uikit/slider.ts +105 -0
  264. package/src/motion/uikit/springs.ts +53 -32
  265. package/src/motion/uikit/switch.ts +174 -0
  266. package/src/privateAttributes/pressHoldsDrag.stylex.ts +28 -0
  267. package/src/utils/pressFeedback.ts +5 -0
  268. package/src/utils/selectionLock.ts +501 -6
  269. package/dist/motion/selectPage.d.ts +0 -26
  270. package/dist/motion/selectPage.d.ts.map +0 -1
  271. package/dist/motion/selectPage.js +0 -55
  272. package/src/motion/selectPage.ts +0 -55
@@ -0,0 +1,1169 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ 'use client';
4
+
5
+ /**
6
+ * @file usePager.ts
7
+ * @input A viewport and its track, a page count and gap (or the track's
8
+ * children), the gesture system and the animator
9
+ * @output Exports `createPager` (the framework-free pager), `usePager` (its
10
+ * React face) and their types
11
+ * @position Shared hook for core components that page like a UIKit paging
12
+ * scroll view, such as Carousel's paging presentation
13
+ *
14
+ * SYNC: When modified, update:
15
+ * - /packages/core/src/hooks/usePager.test.ts
16
+ * - /packages/core/src/hooks/__tests__/usePager.interaction.browser.spec.ts
17
+ */
18
+ import { useEffect, useRef, useState } from 'react';
19
+ import { getGestureHost } from "../gestures/GestureHost.js";
20
+ import { LongPressGestureRecognizer } from "../gestures/LongPressGestureRecognizer.js";
21
+ import { useAttachmentPair } from "./useAttachment.js";
22
+ import { lockSelection, locksSelectionFor } from "../gestures/selectionLock.js";
23
+ import { PanGestureRecognizer } from "../gestures/PanGestureRecognizer.js";
24
+ import { animatorFor } from "../motion/animator.js";
25
+ import { pagingSettleVelocity, solveAnimatedPageScroll, solvePaging } from "../motion/paging.js";
26
+ import { resolveMotion } from "../motion/resolveMotion.js";
27
+ import { resolveSnapPoint } from "../motion/resolveSnapPoint.js";
28
+ import { rubberBandClamp, rubberBandUnclamp } from "../motion/rubberBand.js";
29
+ import { paging, registerPagingTable } from "../motion/uikit/paging.js";
30
+ import { observeResize } from "../utils/sharedResizeObserver.js";
31
+ import { isRtlElement } from "./isRtlElement.js";
32
+ import { useIsomorphicLayoutEffect } from "./useIsomorphicLayoutEffect.js";
33
+
34
+ /** A release the pager settles: where the content is, how fast, and the page it left. */
35
+
36
+ /**
37
+ * A pan or a screen-edge pan, told apart by its kind, never by its class.
38
+ */
39
+ function isPanFamily(recognizer) {
40
+ return recognizer.kind === 'pan' || recognizer.kind === 'screenEdgePan';
41
+ }
42
+
43
+ /**
44
+ * The page a release settles on. It applies UIKit's measured paging rule
45
+ * (`release` in uikit/paging.ts) through the release policy of
46
+ * resolveSnapPoint.ts, with the pager's own pages and thresholds.
47
+ *
48
+ * - A release at `advanceSpeed` or faster is a flick: it goes to the next page
49
+ * in the direction of the velocity, from any content position.
50
+ * - A slower release goes to the page nearest the content. UIKit's measured
51
+ * `commitFraction` is half a page, the policy's nearest snap point.
52
+ * - A release whose velocity points back toward the start page settles there,
53
+ * at any travel, through the policy's `start`.
54
+ * - The page is never more than `maxPagesFromStart` from the start page
55
+ * (`maxSteps`). It is clamped to the pages unless the pager loops.
56
+ * - The policy sees only the pages within that reach of the start page. So a
57
+ * looping target may leave the range, and the owner wraps it.
58
+ *
59
+ * With children pages, positions are in pages, but the velocity stays px/s.
60
+ * The policy reads the velocity only against `advanceSpeed` and for its
61
+ * direction.
62
+ *
63
+ * @example
64
+ * ```
65
+ * // Released at rest 60 % of the way from page 1 to page 2: page 2.
66
+ * pageForRelease({position: 1.6 * 402, velocity: 0, stride: 402, count: 6, startIndex: 1});
67
+ * // Flicked forward at 600 px/s from 6 % past page 1: page 2.
68
+ * pageForRelease({position: 1.06 * 402, velocity: 600, stride: 402, count: 6, startIndex: 1});
69
+ * ```
70
+ */
71
+
72
+ export function pageForRelease({
73
+ position,
74
+ velocity,
75
+ stride,
76
+ count,
77
+ startIndex,
78
+ loop = false
79
+ }) {
80
+ if (!(stride > 0) || count < 1) {
81
+ return 0;
82
+ }
83
+ const reach = paging.release.maxPagesFromStart;
84
+ // A stale start page past either end (the count shrank, an overscrolled
85
+ // track) counts from the nearest real page.
86
+ const from = loop ? startIndex : Math.min(Math.max(startIndex, 0), count - 1);
87
+ const first = loop ? from - reach : Math.max(0, from - reach);
88
+ const last = loop ? from + reach : Math.min(count - 1, from + reach);
89
+ const points = Array.from({
90
+ length: last - first + 1
91
+ }, (_, i) => (first + i) * stride);
92
+ const {
93
+ index
94
+ } = resolveSnapPoint({
95
+ points,
96
+ position,
97
+ velocity,
98
+ flickThreshold: paging.release.advanceSpeed,
99
+ // A hair of tolerance so a release exactly on a page reads as on it.
100
+ tolerance: 1e-6 * stride,
101
+ start: from * stride,
102
+ fromIndex: from - first,
103
+ maxSteps: reach
104
+ });
105
+ return first + index;
106
+ }
107
+
108
+ /** Why the target page changed. */
109
+
110
+ /**
111
+ * The copy of page `index` nearest virtual page `from`, in a loop of `count`
112
+ * pages. Two copies can be equally near: with two pages, or half an even
113
+ * count away. Then it is `index` itself when that is one of them, so a step
114
+ * to `from + 1` always goes forward.
115
+ */
116
+ export function nearestLoopCopy(index, from, count) {
117
+ if (Math.abs(index - from) * 2 <= count) {
118
+ return index;
119
+ }
120
+ return Math.round(from + ((mod(index, count) - mod(from, count) + count + count / 2) % count - count / 2));
121
+ }
122
+
123
+ /** Whether two measured page lists are the same to within half a pixel. */
124
+ function sameOffsets(a, b) {
125
+ return b != null && a.length === b.length && a.every((offset, i) => Math.abs(offset - b[i]) < 0.5);
126
+ }
127
+ function mod(value, count) {
128
+ return (value % count + count) % count;
129
+ }
130
+
131
+ /** A position curve seen as the track's x (mirrored for LTR). */
132
+ function toTrackCurve(curve, sign) {
133
+ // `+ 0` turns a mirrored zero (−0) into 0.
134
+ return {
135
+ duration: curve.duration,
136
+ at: t => sign * curve.at(t) + 0,
137
+ velocity: t => sign * curve.velocity(t) + 0
138
+ };
139
+ }
140
+
141
+ /** What a pager runs on; tests pass their own clocked host and animator. */
142
+
143
+ /**
144
+ * The pager's pan. Its release velocity is the pan's `scrollVelocity()`, the
145
+ * one UIScrollView hands `scrollViewWillEndDragging`. Unlike UIKit's, it reads
146
+ * 0 after a still hold.
147
+ *
148
+ * Inside a scroll view, it takes UIKit's rule: a drag whose dominant axis is
149
+ * horizontal is the pager's (`paging.nestedPanAxisRatio`, the tie included).
150
+ * Any other drag is the page's. Like every pan, it cancels the touch's moves
151
+ * once it begins, at its 10 pt hysteresis. Nothing claims a touch earlier.
152
+ *
153
+ * Inside a sheet, it keeps the sheet's rule (`axisRatio`,
154
+ * `paging.panAxisRatio`). The arena shows the sheet as an enclosing vertical
155
+ * pan that takes part in the touch. Between atan(1 ÷ that ratio) and 45°,
156
+ * neither moves.
157
+ */
158
+ class PagerPanGestureRecognizer extends PanGestureRecognizer {
159
+ /**
160
+ * The kind of pointer the pan follows. Under Reduce Motion a touch's
161
+ * release cross-fades; a mouse's or a pen's lands at once on a fine
162
+ * pointer.
163
+ */
164
+ pointerType = null;
165
+ touchesBegan(touches, event) {
166
+ if (this.state === 'possible' && touches.length > 0) {
167
+ this.pointerType = touches[0].pointerType;
168
+ }
169
+ super.touchesBegan(touches, event);
170
+ }
171
+ hasEnclosingVerticalPan() {
172
+ for (const other of this.arena?.involvedRecognizers ?? []) {
173
+ if (other !== this && isPanFamily(other) && (other.direction === 'vertical' || other.direction === 'up' || other.direction === 'down')) {
174
+ return true;
175
+ }
176
+ }
177
+ return false;
178
+ }
179
+ classify(translation) {
180
+ const decided = super.classify(translation);
181
+ if (decided !== 'wait' || this.hasEnclosingVerticalPan()) {
182
+ return decided;
183
+ }
184
+ const along = Math.abs(translation.x);
185
+ const across = Math.abs(translation.y);
186
+ if (along === 0 && across === 0) {
187
+ return 'wait';
188
+ }
189
+ return along >= paging.nestedPanAxisRatio * across ? 'begin' : 'fail';
190
+ }
191
+ }
192
+
193
+ /**
194
+ * The settle catcher: a zero-duration long press that only stops the settle.
195
+ * It never claims the touch. So a vertical swipe or a pinch that starts on a
196
+ * settling track still reaches the page. UIKit also hands the outer scroll
197
+ * view a vertical drag after the paging view's content stops.
198
+ */
199
+ class SettleCatcher extends LongPressGestureRecognizer {
200
+ /** The kind of pointer that caught the settle (see the pager's pan). */
201
+ pointerType = null;
202
+ get claimsTouches() {
203
+ return false;
204
+ }
205
+ touchesBegan(touches, event) {
206
+ if (this.state === 'possible' && touches.length > 0) {
207
+ this.pointerType = touches[0].pointerType;
208
+ }
209
+ super.touchesBegan(touches, event);
210
+ }
211
+ }
212
+
213
+ /**
214
+ * A trackpad swipe that moved under this fraction of a page (in the pages'
215
+ * own spacing, children pages included) releases still, whatever its
216
+ * speed.
217
+ */
218
+ const STILL_RELEASE_FRACTION = 0.1;
219
+
220
+ /** Whether a pan's contact is a scroll (a trackpad's), not a pointer. */
221
+ function isScrollContact(recognizer) {
222
+ return recognizer.trackedTouches[0]?.scrollType != null;
223
+ }
224
+
225
+ /**
226
+ * Creates a pager: UIKit's paging scroll view, driven by the gesture system
227
+ * and played on the compositor. A native scroll-snap container does not run
228
+ * UIKit's paging integrator, and it cannot share a gesture with a pinch.
229
+ * Attach the pager to its viewport and track. It measures the page width on
230
+ * attach, on a resize and when a drag begins, never while a finger moves.
231
+ *
232
+ * - A horizontal pan moves the track 1:1, with one `translate` write per
233
+ * move, no layout read and no React render. Past the first or last page,
234
+ * the track follows UIKit's rubber band, with d = the page width.
235
+ * - At the lift, `pageForRelease` picks the page with UIKit's measured rule.
236
+ * The track then settles on UIKit's paging integrator (`solvePaging`),
237
+ * baked into keyframes.
238
+ * - A finger that lands on a settling pager catches it `paging.catchStopMs`
239
+ * after the touch, as in UIKit. A drag catches it at once, from the value
240
+ * on screen. While the pan is off, a touch does not stop the motion.
241
+ * - `goTo` runs the curve of `setContentOffset(_:animated:)` and cancels a
242
+ * drag in progress. It reads that duration and curve through
243
+ * `resolveMotion`.
244
+ * - Under Reduce Motion, the drag still follows the finger, but nothing
245
+ * travels after the lift. A touch's release cross-fades in 200 ms on any
246
+ * pointer. `goTo` and a mouse's or a pen's release cross-fade on a coarse
247
+ * pointer, and land at once on any other.
248
+ * - `onIndexChange` reports a release's page once its settle runs on the
249
+ * compositor, two frames after the frame it started in. It reports a
250
+ * `goTo` at once, and never a controlled change. A report still waiting at
251
+ * a detach or a controlled move is dropped. `onSettle` runs when the track
252
+ * rests.
253
+ * - A detach ends a drag on its start page, and an unmount calls nothing.
254
+ * When a replaced viewport or track attaches, a motion that the detach
255
+ * stopped ends on its page. Its report and `onSettle` go out from a frame.
256
+ * - A controlled `index` wins. A page that the pager reports and the owner
257
+ * does not take returns the pager to `index`, without a report.
258
+ * - The pan and the catch attach for every pointer. A mouse drags the track
259
+ * as a finger does. The pan follows a trackpad's scroll along its axis, but
260
+ * never a mouse wheel's.
261
+ * - A trackpad swipe moves the track at most one page from its start page.
262
+ * A swipe that moves under a tenth of a page releases still, at any speed.
263
+ * A swipe that lands during the last swipe's settle begins from that
264
+ * settle's page.
265
+ *
266
+ * Positions are content offsets in px, 0 at page 0 and growing toward later
267
+ * pages. The track is translated by −position, or by +position in a
268
+ * right-to-left viewport. The owner renders the pages: all of them, a window,
269
+ * or a wrapped copy for a loop. With `loop`, indexes are unbounded, and
270
+ * `index` wraps them into [0, count).
271
+ *
272
+ * Give the current page and its neighbors their own layers
273
+ * (`will-change: transform`). Through a busy main thread, Mobile Safari moves
274
+ * the track but cannot paint new content, so part of a page that slides in
275
+ * stays blank. A page on its own layer is painted whole before it moves.
276
+ */
277
+ export function createPager(initial, environment = {}) {
278
+ registerPagingTable();
279
+ // Frames and timers come from the viewport's own window, known from the
280
+ // attach. In a Picture-in-Picture window, the opener's frames stop while
281
+ // its tab is hidden.
282
+ let view = null;
283
+ const realm = () => view ?? globalThis;
284
+ const setTimer = environment.setTimeout ?? ((callback, ms) => realm().setTimeout(callback, ms));
285
+ const clearTimer = environment.clearTimeout ?? (handle => realm().clearTimeout(handle));
286
+ const requestFrame = environment.requestFrame ?? (callback => {
287
+ const frames = realm();
288
+ if (typeof frames.requestAnimationFrame === 'function') {
289
+ frames.requestAnimationFrame(() => callback());
290
+ } else {
291
+ setTimer(callback, 16);
292
+ }
293
+ });
294
+ let options = {
295
+ ...initial
296
+ };
297
+ let viewport = null;
298
+ let trackElement = null;
299
+ let animator = null;
300
+ let pageWidth = 0;
301
+ let isRtl = false;
302
+ // With `pages: 'children'`, each page's offset (px, ascending), once
303
+ // measured.
304
+ let childOffsets = null;
305
+ const isChildPages = () => options.pages === 'children';
306
+ const isLooping = () => options.loop === true && !isChildPages();
307
+ const count = () => isChildPages() && childOffsets != null ? childOffsets.length : Math.max(1, Math.floor(options.count));
308
+ const stride = () => pageWidth + (options.gap ?? 0);
309
+ const sign = () => isRtl ? 1 : -1;
310
+ const clampIndex = index => isLooping() ? index : Math.max(0, Math.min(count() - 1, index));
311
+
312
+ /** Where page `index` rests (px). */
313
+ function offsetOf(index) {
314
+ if (isChildPages() && childOffsets != null) {
315
+ return childOffsets[Math.max(0, Math.min(childOffsets.length - 1, index))];
316
+ }
317
+ return index * stride();
318
+ }
319
+
320
+ /**
321
+ * Where `position` falls, in pages: an index plus the fraction of the way
322
+ * to the next page (past either end, in the end page's spacing).
323
+ */
324
+ function pageAt(position) {
325
+ if (!(isChildPages() && childOffsets != null)) {
326
+ return position / stride();
327
+ }
328
+ const at = childOffsets;
329
+ const n = at.length;
330
+ if (n === 1) {
331
+ return (position - at[0]) / (pageWidth > 0 ? pageWidth : 1);
332
+ }
333
+ if (position < at[0]) {
334
+ return (position - at[0]) / (at[1] - at[0]);
335
+ }
336
+ for (let i = 0; i < n - 1; i++) {
337
+ if (position < at[i + 1]) {
338
+ return i + (position - at[i]) / (at[i + 1] - at[i]);
339
+ }
340
+ }
341
+ return n - 1 + (position - at[n - 1]) / (at[n - 1] - at[n - 2]);
342
+ }
343
+
344
+ /** The page nearest `position`, or the target before anything is measured. */
345
+ function nearestPage(position) {
346
+ if (!isChildPages() && !(stride() > 0)) {
347
+ return target;
348
+ }
349
+ return Math.round(pageAt(position));
350
+ }
351
+
352
+ /**
353
+ * The page a release from `position` at `velocity` settles on (UIKit's
354
+ * rule, pageForRelease), in children pages' own spacing.
355
+ */
356
+ function releasePage(position, velocity, startIndex) {
357
+ const pages = isChildPages() && childOffsets != null;
358
+ return pageForRelease({
359
+ position: pages ? pageAt(position) : position,
360
+ velocity,
361
+ stride: pages ? 1 : stride(),
362
+ count: count(),
363
+ startIndex,
364
+ loop: isLooping()
365
+ });
366
+ }
367
+
368
+ /**
369
+ * Children pages: each child's start edge, from the track's start. The
370
+ * track's own translate moves both alike, so it cancels out. Each offset is
371
+ * clamped to the travel that keeps the track's end at or past the end of
372
+ * the viewport's content box. Children clamped onto one offset share its
373
+ * page.
374
+ *
375
+ * Rects are read in the track's own CSS pixels, which its `translate` moves
376
+ * in. An ancestor's `zoom` scales the rects, so the pager divides out that
377
+ * scale: the rect's width over the track's used width.
378
+ */
379
+ function measureChildOffsets() {
380
+ const track = trackElement;
381
+ if (viewport == null || track == null || track.children.length === 0) {
382
+ return [0];
383
+ }
384
+ const box = track.getBoundingClientRect();
385
+ const used = Number.parseFloat(getComputedStyle(track).width);
386
+ const scale = used > 0 && box.width > 0 ? box.width / used : 1;
387
+ const style = getComputedStyle(viewport);
388
+ const inner = viewport.clientWidth - (Number.parseFloat(style.paddingLeft) || 0) - (Number.parseFloat(style.paddingRight) || 0);
389
+ const starts = [];
390
+ let extent = 0;
391
+ for (const child of Array.from(track.children)) {
392
+ const rect = child.getBoundingClientRect();
393
+ starts.push((isRtl ? box.right - rect.right : rect.left - box.left) / scale);
394
+ extent = Math.max(extent, (isRtl ? box.right - rect.left : rect.right - box.left) / scale);
395
+ }
396
+ const end = Math.max(0, extent - inner);
397
+ const offsets = [];
398
+ for (const start of starts) {
399
+ const offset = Math.min(Math.max(start, 0), end);
400
+ if (offsets.length === 0 || offset > offsets[offsets.length - 1] + 0.5) {
401
+ offsets.push(offset);
402
+ }
403
+ }
404
+ return offsets.length > 0 ? offsets : [0];
405
+ }
406
+
407
+ // The page the track rests on or is heading for (unbounded when looping),
408
+ // and the one it last rested on.
409
+ let target = clampIndex(Math.round(options.defaultIndex ?? 0));
410
+ let settled = target;
411
+ let settleHandle = null;
412
+ let isSwipeSettle = false;
413
+ let settleToken = 0;
414
+ let isDragging = false;
415
+ let dragStart = 0;
416
+ let dragStartIndex = 0;
417
+ let dragPosition = 0;
418
+ let suppressCancelSettle = false;
419
+ let catchTimer = null;
420
+ // Whether the finger now holding the track stopped a settle (not one that
421
+ // ended on its own inside the catch window).
422
+ let caughtSettle = false;
423
+ const pan = new PagerPanGestureRecognizer({
424
+ ...options.panOptions,
425
+ // Published, so app code can relate its own recognizers to the paging
426
+ // pan (gesture delegates). Instances are told apart by their element.
427
+ name: options.panOptions?.name ?? 'pager',
428
+ direction: 'horizontal',
429
+ axisRatio: options.panOptions?.axisRatio ?? paging.panAxisRatio,
430
+ // On the web the pan follows a trackpad's scroll along its axis and never
431
+ // a mouse wheel's.
432
+ allowedScrollTypes: options.panOptions?.allowedScrollTypes ?? ['continuous'],
433
+ shouldBegin: recognizer => {
434
+ if (options.panOptions?.shouldBegin?.(recognizer) === false) {
435
+ return false;
436
+ }
437
+ const dx = recognizer.totalTranslation().x;
438
+ const direction = dx < 0 ? 'left' : 'right';
439
+ return options.shouldBeginPan?.(direction) ?? true;
440
+ }
441
+ });
442
+
443
+ // Catches a settling track when a finger lands on it. It begins on the
444
+ // touch itself, alongside the pan, only while the track moves on its own
445
+ // and the pan is on.
446
+ const catcher = new SettleCatcher({
447
+ minimumPressDuration: 0,
448
+ allowableMovement: Number.POSITIVE_INFINITY,
449
+ // Its own hold does nothing, so it brings no selection lock: a finger on
450
+ // a resting track keeps the browser's native long press. Stopping a
451
+ // settle does something; `holdSelection` locks then.
452
+ selectionLock: null,
453
+ shouldBegin: () => settleHandle != null && !isDragging && pan.isEnabled
454
+ });
455
+ catcher.recognizeSimultaneouslyWith(pan);
456
+ function positionToX(position) {
457
+ const x = sign() * position;
458
+ return x === 0 ? 0 : x;
459
+ }
460
+ function presentation() {
461
+ if (animator == null) {
462
+ return offsetOf(target);
463
+ }
464
+ return sign() * animator.get('x');
465
+ }
466
+ function clearCatchTimer() {
467
+ if (catchTimer != null) {
468
+ clearTimer(catchTimer);
469
+ catchTimer = null;
470
+ }
471
+ }
472
+ function stopSettle() {
473
+ clearCatchTimer();
474
+ flushReport();
475
+ isSwipeSettle = false;
476
+ if (settleHandle != null) {
477
+ settleToken += 1;
478
+ settleHandle = null;
479
+ animator?.stop(['x']);
480
+ }
481
+ }
482
+ function wrapped(index) {
483
+ return isLooping() ? mod(index, count()) : index;
484
+ }
485
+
486
+ // The owner passes its own updates (setOptions, a controlled goTo) from an
487
+ // Effect. The callbacks they cause run from a frame callback, never inside
488
+ // that Effect. There, a callback that sets state would update the owner
489
+ // during its own commit. A detach drops the callbacks still waiting.
490
+ let deferDepth = 0;
491
+ let deferred = [];
492
+ let deferredToken = 0;
493
+ function deliver(callback) {
494
+ if (deferDepth > 0) {
495
+ deferred.push(callback);
496
+ } else {
497
+ callback();
498
+ }
499
+ }
500
+ function deferringCallbacks(work) {
501
+ deferDepth += 1;
502
+ try {
503
+ work();
504
+ } finally {
505
+ deferDepth -= 1;
506
+ if (deferDepth === 0 && deferred.length > 0) {
507
+ const calls = deferred;
508
+ deferred = [];
509
+ const token = deferredToken;
510
+ requestFrame(() => {
511
+ if (token === deferredToken) {
512
+ for (const call of calls) {
513
+ call();
514
+ }
515
+ }
516
+ });
517
+ }
518
+ }
519
+ }
520
+ function dropDeferred() {
521
+ deferred = [];
522
+ deferredToken += 1;
523
+ }
524
+
525
+ // A release's report waits for its settle to reach the compositor.
526
+ let reported = wrapped(target);
527
+ let pendingReport = null;
528
+ let reportToken = 0;
529
+ function report(reason) {
530
+ pendingReport = null;
531
+ reportToken += 1;
532
+ const index = wrapped(target);
533
+ if (index !== reported) {
534
+ reported = index;
535
+ // A controlled move (the owner's `index`, or a `count` that clamps the
536
+ // page) is the owner's own change: it is not reported back.
537
+ if (reason !== 'controlled') {
538
+ deliver(() => options.onIndexChange?.(index, reason));
539
+ }
540
+ }
541
+ }
542
+ function flushReport() {
543
+ if (pendingReport != null) {
544
+ report(pendingReport);
545
+ }
546
+ }
547
+
548
+ /**
549
+ * Forgets a release's report still waiting: the pager is detaching, or the
550
+ * owner's own (controlled) move replaces the page it chose. The page last
551
+ * reported stays as it was.
552
+ */
553
+ function dropReport() {
554
+ pendingReport = null;
555
+ reportToken += 1;
556
+ }
557
+
558
+ /**
559
+ * A release reports its page once the settle reaches the compositor, two
560
+ * frames after the frame it started in. In Mobile Safari, a main-thread
561
+ * block that starts within about two frames of the touch freezes a motion
562
+ * that the touch's handler started. The owner's render of the new page is
563
+ * such a block. UIKit tells its delegate at the lift
564
+ * (`scrollViewWillEndDragging`), and the page is known then too (`index`).
565
+ */
566
+ function setTarget(next, reason, whenMoving = false) {
567
+ target = next;
568
+ if (whenMoving) {
569
+ pendingReport = reason;
570
+ } else {
571
+ report(reason);
572
+ }
573
+ }
574
+
575
+ /**
576
+ * Runs `callback` in the `frames`-th animation frame after the frame that a
577
+ * motion started in. Call it when the motion's start resolves.
578
+ *
579
+ * WebKit resolves an animation's start inside that frame's rendering
580
+ * update, before the frame's animation-frame callbacks. No task runs inside
581
+ * a rendering update. So a first frame that runs before a task queued at
582
+ * the resolution is the start's own frame, and it does not count.
583
+ * Timestamps cannot tell: WebKit stamps that frame's callbacks 0–4 ms after
584
+ * the animation's start time, as far apart as two frames at 240 Hz. Where
585
+ * the start resolves after its frame, as in Chromium, the task runs before
586
+ * the next frame. The report then comes a frame later, never earlier.
587
+ */
588
+ function afterFramesPastStart(frames, callback) {
589
+ let isPastStartFrame = false;
590
+ setTimer(() => {
591
+ isPastStartFrame = true;
592
+ }, 0);
593
+ const onFrame = left => {
594
+ const remaining = isPastStartFrame ? left - 1 : left;
595
+ isPastStartFrame = true;
596
+ if (remaining <= 0) {
597
+ callback();
598
+ return;
599
+ }
600
+ requestFrame(() => onFrame(remaining));
601
+ };
602
+ requestFrame(() => onFrame(frames));
603
+ }
604
+ function rest() {
605
+ flushReport();
606
+ isSwipeSettle = false;
607
+ const previous = wrapped(settled);
608
+ settled = target;
609
+ const index = wrapped(settled);
610
+ deliver(() => options.onSettle?.(index, previous));
611
+ }
612
+
613
+ /**
614
+ * Plays `curve` on the track. Under Reduce Motion, the animator replaces the
615
+ * travel. A settle that a touch's release starts (`touchRelease`)
616
+ * cross-fades on any pointer. Any other motion, such as `goTo` or a mouse's
617
+ * or a pen's release, cross-fades on a coarse pointer. It lands at once on
618
+ * any other pointer.
619
+ */
620
+ function play(curve, touchRelease = false) {
621
+ isSwipeSettle = false;
622
+ if (animator == null) {
623
+ return;
624
+ }
625
+ follow(animator.play({
626
+ x: toTrackCurve(curve, sign())
627
+ }, {
628
+ touchRelease
629
+ }));
630
+ }
631
+ function follow(handle) {
632
+ const token = ++settleToken;
633
+ settleHandle = handle;
634
+ if (pendingReport != null) {
635
+ const reportAt = reportToken;
636
+ void handle.started.then(() => afterFramesPastStart(2, () => {
637
+ if (reportAt === reportToken) {
638
+ flushReport();
639
+ }
640
+ }));
641
+ }
642
+ void handle.finished.then(finished => {
643
+ if (token !== settleToken) {
644
+ return;
645
+ }
646
+ settleHandle = null;
647
+ if (finished) {
648
+ rest();
649
+ }
650
+ });
651
+ }
652
+
653
+ /**
654
+ * The settle after a pointer lifts (a release, or a hold let go);
655
+ * `touchRelease` when that pointer was a touch.
656
+ */
657
+ function settleFrom(position, velocity, touchRelease) {
658
+ const to = offsetOf(target);
659
+ // UIKit's integrator, as a playable curve (touch motion stays internal).
660
+ const curve = solvePaging({
661
+ from: position,
662
+ velocity,
663
+ to
664
+ });
665
+ if (curve.steps === 0) {
666
+ animator?.set({
667
+ x: positionToX(to)
668
+ });
669
+ rest();
670
+ return;
671
+ }
672
+ play(curve, touchRelease);
673
+ }
674
+ function measure() {
675
+ if (viewport == null) {
676
+ return;
677
+ }
678
+ const width = viewport.clientWidth;
679
+ const rtl = isRtlElement(viewport);
680
+ // A new writing direction mirrors the track, so it re-places it too.
681
+ let changed = width !== pageWidth || rtl !== isRtl;
682
+ isRtl = rtl;
683
+ pageWidth = width;
684
+ if (isChildPages()) {
685
+ const offsets = measureChildOffsets();
686
+ if (!sameOffsets(offsets, childOffsets)) {
687
+ childOffsets = offsets;
688
+ changed = true;
689
+ const pageCount = offsets.length;
690
+ deliver(() => options.onPagesChange?.(pageCount));
691
+ }
692
+ }
693
+ if (!changed) {
694
+ return;
695
+ }
696
+ if (!isDragging && !isLooping() && target > count() - 1) {
697
+ // Fewer pages (children clamped onto one): the last one, as a smaller
698
+ // count clamps. A loop's target is unbounded, so it keeps it.
699
+ goTo(count() - 1, {
700
+ animated: false,
701
+ reason: 'controlled'
702
+ });
703
+ return;
704
+ }
705
+ // A resize lands on the target page at its new offset (a settle in
706
+ // flight ends there), as a paging scroll view does on rotation. A finger
707
+ // that holds a caught track keeps it; its lift settles on the new offsets.
708
+ if (!isDragging && !caughtSettle) {
709
+ stopSettle();
710
+ animator?.set({
711
+ x: positionToX(offsetOf(target))
712
+ });
713
+ if (settled !== target) {
714
+ rest();
715
+ }
716
+ }
717
+ }
718
+ function onPan(recognizer) {
719
+ const state = recognizer.state;
720
+ if (state === 'began') {
721
+ // Read before measure(), which can stop the settle on a resize.
722
+ const wasSwipeSettle = settleHandle != null && isSwipeSettle;
723
+ measure();
724
+ clearCatchTimer();
725
+ const current = presentation();
726
+ stopSettle();
727
+ isDragging = true;
728
+ // A track caught past an end is shown rubber-banded: the drag starts
729
+ // from its unbanded position, so the first move keeps it under the
730
+ // finger.
731
+ dragStart = isLooping() ? current : rubberBandUnclamp(current, offsetOf(0), offsetOf(count() - 1), pageWidth > 0 ? pageWidth : 1);
732
+ dragPosition = current;
733
+ // A trackpad swipe that lands while the last swipe's settle runs
734
+ // begins from that settle's page, so back-to-back swipes page on. Any
735
+ // other motion, such as a goTo, hands over the page on screen.
736
+ dragStartIndex = wasSwipeSettle && isScrollContact(recognizer) ? target : nearestPage(current);
737
+ return;
738
+ }
739
+ if (state === 'changed') {
740
+ const dx = recognizer.translation().x;
741
+ // Finger right (dx > 0) moves content toward earlier pages in LTR.
742
+ let raw = dragStart + sign() * dx;
743
+ if (isScrollContact(recognizer) && pageWidth > 0) {
744
+ // A trackpad swipe moves the track at most one page from its start
745
+ // page, across a loop too. The window also holds where the swipe
746
+ // began, so a swipe that catches a longer move starts from the
747
+ // screen. A pager that does not loop keeps the rubber band of its
748
+ // first and last pages below.
749
+ const looping = isLooping();
750
+ const before = looping || dragStartIndex > 0 ? offsetOf(dragStartIndex - 1) : -Infinity;
751
+ const after = looping || dragStartIndex < count() - 1 ? offsetOf(dragStartIndex + 1) : Infinity;
752
+ raw = Math.min(Math.max(raw, Math.min(before, after, dragStart)), Math.max(before, after, dragStart));
753
+ }
754
+ dragPosition = isLooping() ? raw : rubberBandClamp(raw, offsetOf(0), offsetOf(count() - 1), pageWidth > 0 ? pageWidth : 1);
755
+ animator?.set({
756
+ x: positionToX(dragPosition)
757
+ });
758
+ return;
759
+ }
760
+ if (state === 'ended' || state === 'cancelled') {
761
+ isDragging = false;
762
+ if (state === 'cancelled' && suppressCancelSettle) {
763
+ suppressCancelSettle = false;
764
+ return;
765
+ }
766
+ // A still finger releases at 0, where UIScrollView keeps the speed.
767
+ let velocity = state === 'ended' ? sign() * recognizer.scrollVelocity().x : 0;
768
+ // A trackpad swipe that moved under a tenth of a page from where it
769
+ // began, in the pages' own spacing, releases still at any speed. Such a
770
+ // speed spike is not a flick. A finger's and a mouse's flick keep their
771
+ // speed.
772
+ if (isScrollContact(recognizer) && Math.abs(pageAt(dragPosition) - pageAt(dragStart)) < STILL_RELEASE_FRACTION) {
773
+ velocity = 0;
774
+ }
775
+ const next = releasePage(dragPosition, velocity, dragStartIndex);
776
+ setTarget(next, 'drag', true);
777
+ settleFrom(dragPosition, pagingSettleVelocity(velocity), pan.pointerType === 'touch');
778
+ isSwipeSettle = settleHandle != null && isScrollContact(recognizer);
779
+ }
780
+ }
781
+
782
+ // While a finger holds a caught track, the browser's long-press text
783
+ // selection and callout stay off. In UIKit, the touch that stops a scroll
784
+ // view does not reach its content. The gesture system's shared lock is
785
+ // counted per element. So this lock and the gesture host's own lock for the
786
+ // same contact release in either order.
787
+ let releaseSelection = null;
788
+ function holdSelection(on) {
789
+ if (on && releaseSelection == null && trackElement != null) {
790
+ if (locksSelectionFor(catcher.pointerType ?? 'touch')) {
791
+ releaseSelection = lockSelection([trackElement], null);
792
+ }
793
+ } else if (!on && releaseSelection != null) {
794
+ releaseSelection();
795
+ releaseSelection = null;
796
+ }
797
+ }
798
+ function onCatch(recognizer) {
799
+ if (recognizer.state === 'began') {
800
+ holdSelection(true);
801
+ clearCatchTimer();
802
+ caughtSettle = false;
803
+ catchTimer = setTimer(() => {
804
+ catchTimer = null;
805
+ if (settleHandle != null && !isDragging) {
806
+ stopSettle();
807
+ caughtSettle = true;
808
+ }
809
+ }, paging.catchStopMs);
810
+ return;
811
+ }
812
+ if (recognizer.state === 'ended' || recognizer.state === 'cancelled') {
813
+ holdSelection(false);
814
+ if (catchTimer != null) {
815
+ // Lifted before the catch took hold: the settle runs on.
816
+ clearCatchTimer();
817
+ return;
818
+ }
819
+ const wasCaught = caughtSettle;
820
+ caughtSettle = false;
821
+ if (wasCaught && !isDragging && settleHandle == null && animator != null) {
822
+ // Held, then lifted without dragging: settle on the nearest page.
823
+ const position = presentation();
824
+ const next = releasePage(position, 0, nearestPage(position));
825
+ setTarget(next, 'drag', true);
826
+ settleFrom(position, 0, catcher.pointerType === 'touch');
827
+ }
828
+ }
829
+ }
830
+ function goTo(index, goToOptions = {}) {
831
+ if (goToOptions.reason === 'controlled' && deferDepth === 0) {
832
+ // The owner's own move: what it calls back waits for a frame.
833
+ deferringCallbacks(() => goTo(index, goToOptions));
834
+ return;
835
+ }
836
+ const {
837
+ animated = true,
838
+ reason = 'goTo'
839
+ } = goToOptions;
840
+ let next = Math.round(index);
841
+ if (isLooping()) {
842
+ next = nearestLoopCopy(next, target, count());
843
+ } else {
844
+ next = clampIndex(next);
845
+ }
846
+ if (isDragging) {
847
+ suppressCancelSettle = true;
848
+ isDragging = false;
849
+ pan.cancel();
850
+ }
851
+ const from = presentation();
852
+ // A move this one retargets hands on its velocity, from its curve.
853
+ const velocity = settleHandle != null && animator != null ? sign() * animator.getVelocity('x') : undefined;
854
+ if (reason === 'controlled') {
855
+ dropReport();
856
+ }
857
+ stopSettle();
858
+ setTarget(next, reason);
859
+ const to = offsetOf(next);
860
+ if (!animated || animator == null || from === to) {
861
+ animator?.set({
862
+ x: positionToX(to)
863
+ });
864
+ rest();
865
+ return;
866
+ }
867
+ play(solveAnimatedPageScroll({
868
+ from,
869
+ to,
870
+ durationMs: resolveMotion(trackElement, paging.animatedScroll, 'durationMs'),
871
+ curve: resolveMotion(trackElement, paging.animatedScroll.curve),
872
+ velocity
873
+ }));
874
+ }
875
+ function setOptions(update) {
876
+ deferringCallbacks(() => applyOptions(update));
877
+ }
878
+ function applyOptions(update) {
879
+ const wasLooping = isLooping();
880
+ const wasChildPages = isChildPages();
881
+ const previousCount = count();
882
+ const previousOffset = offsetOf(target);
883
+ // A loop's indexes are unbounded. So the page shown and the page last at
884
+ // rest are read under the old count, before the options change.
885
+ const shownBefore = wasLooping ? mod(target, previousCount) : target;
886
+ const settledBefore = wasLooping ? mod(settled, previousCount) : settled;
887
+ options = {
888
+ ...options,
889
+ ...update
890
+ };
891
+ if (isChildPages() !== wasChildPages) {
892
+ syncTrackObserver();
893
+ }
894
+ if (isChildPages() && viewport != null && !isDragging) {
895
+ // The children may have changed with the options (a count, a gap).
896
+ const offsets = measureChildOffsets();
897
+ if (!sameOffsets(offsets, childOffsets)) {
898
+ childOffsets = offsets;
899
+ const pageCount = offsets.length;
900
+ deliver(() => options.onPagesChange?.(pageCount));
901
+ }
902
+ }
903
+ if ((wasLooping || isLooping()) && (wasLooping !== isLooping() || count() !== previousCount)) {
904
+ if (target < 0 || target > Math.min(previousCount, count()) - 1) {
905
+ rewrap(shownBefore, settledBefore);
906
+ return;
907
+ }
908
+ // The target's slot shows the same page. Only the page last at rest
909
+ // can be a virtual index, so it is read under the old count.
910
+ settled = settledBefore;
911
+ }
912
+ if (!isLooping() && (target < 0 || target > count() - 1)) {
913
+ // A smaller `count` clamps.
914
+ goTo(clampIndex(target), {
915
+ animated: false,
916
+ reason: 'controlled'
917
+ });
918
+ return;
919
+ }
920
+ if (offsetOf(target) !== previousOffset && !isDragging) {
921
+ // A new gap (or children): the target page at its new offset (a settle
922
+ // ends there).
923
+ const wasSettling = settleHandle != null;
924
+ stopSettle();
925
+ animator?.set({
926
+ x: positionToX(offsetOf(target))
927
+ });
928
+ if (wasSettling || settled !== target) {
929
+ rest();
930
+ }
931
+ }
932
+ }
933
+
934
+ /**
935
+ * Turning `loop` off, or a loop's new count, where the target's slot now
936
+ * shows another page. The page shown keeps its index, and a smaller count
937
+ * clamps it. A release's waiting report names its page under the old count.
938
+ * It reaches the owner only while that page exists.
939
+ */
940
+ function rewrap(shownBefore, settledBefore) {
941
+ const next = Math.min(shownBefore, count() - 1);
942
+ const waiting = pendingReport;
943
+ pendingReport = null;
944
+ if (isDragging) {
945
+ suppressCancelSettle = true;
946
+ isDragging = false;
947
+ pan.cancel();
948
+ }
949
+ const wasSettling = settleHandle != null;
950
+ stopSettle();
951
+ if (waiting != null && shownBefore === next) {
952
+ target = next;
953
+ report(waiting);
954
+ }
955
+ setTarget(next, 'controlled');
956
+ animator?.set({
957
+ x: positionToX(offsetOf(next))
958
+ });
959
+ settled = next;
960
+ if (wasSettling || settledBefore !== next) {
961
+ deliver(() => options.onSettle?.(next, settledBefore));
962
+ }
963
+ }
964
+ let detachAll = null;
965
+ // What a detach carries to the next attach: a release's report that still
966
+ // waits, and whether the detach stopped a motion before the track rested.
967
+ let carriedReport = null;
968
+ let carriedEnd = false;
969
+
970
+ // Children pages also move when the track's own size changes, as when a
971
+ // child is added, removed or resized. So the track is observed while the
972
+ // pages are its children, from the attach or the options change that makes
973
+ // them so.
974
+ let unobserveTrack = () => {};
975
+ function syncTrackObserver() {
976
+ unobserveTrack();
977
+ unobserveTrack = isChildPages() && trackElement != null && detachAll != null ? observeResize(trackElement, measure) : () => {};
978
+ }
979
+ function attach(nextViewport, nextTrack) {
980
+ detachAll?.();
981
+ view = nextViewport.ownerDocument.defaultView;
982
+ viewport = nextViewport;
983
+ trackElement = nextTrack;
984
+ animator = environment.animator ?? animatorFor(nextTrack);
985
+ pageWidth = 0;
986
+ isRtl = isRtlElement(nextViewport);
987
+ pageWidth = nextViewport.clientWidth;
988
+ if (isChildPages()) {
989
+ childOffsets = measureChildOffsets();
990
+ target = clampIndex(target);
991
+ settled = target;
992
+ }
993
+ animator.set({
994
+ x: positionToX(offsetOf(target))
995
+ });
996
+ // No pointer check: a mouse and a trackpad page it too.
997
+ const removePanListener = pan.addListener(onPan);
998
+ const removeCatchListener = catcher.addListener(onCatch);
999
+ const host = environment.host ?? getGestureHost(nextViewport.ownerDocument);
1000
+ const detachPan = host.attach(nextViewport, pan);
1001
+ // The catcher sits on the track, so its long-press styles (no callout, no
1002
+ // selection) stay off the pages' text. The viewport's touch-action
1003
+ // already covers the touches that land on the track.
1004
+ const detachCatch = host.attach(nextTrack, catcher, {
1005
+ manageStyle: false
1006
+ });
1007
+ const detachGestures = () => {
1008
+ detachCatch();
1009
+ detachPan();
1010
+ removeCatchListener();
1011
+ removePanListener();
1012
+ };
1013
+ const unobserve = observeResize(nextViewport, measure);
1014
+ detachAll = () => {
1015
+ unobserve();
1016
+ unobserveTrack();
1017
+ unobserveTrack = () => {};
1018
+ // A drag that the detach ends stays on its start page. The report and
1019
+ // the end of a motion that the detach stops wait for the next attach,
1020
+ // so an unmount calls nothing.
1021
+ if (isDragging) {
1022
+ suppressCancelSettle = true;
1023
+ }
1024
+ deferringCallbacks(() => detachGestures());
1025
+ suppressCancelSettle = false;
1026
+ carriedReport = pendingReport;
1027
+ carriedEnd = target !== settled;
1028
+ dropReport();
1029
+ stopSettle();
1030
+ dropDeferred();
1031
+ holdSelection(false);
1032
+ isDragging = false;
1033
+ detachAll = null;
1034
+ };
1035
+ syncTrackObserver();
1036
+ // A motion that the last detach stopped ends here: its report, if it
1037
+ // still waited, and its onSettle go out from a frame.
1038
+ if (carriedEnd && target !== settled) {
1039
+ const report = carriedReport;
1040
+ deferringCallbacks(() => {
1041
+ pendingReport = report;
1042
+ rest();
1043
+ });
1044
+ }
1045
+ carriedReport = null;
1046
+ carriedEnd = false;
1047
+ return () => detachAll?.();
1048
+ }
1049
+ return {
1050
+ pan,
1051
+ get index() {
1052
+ return wrapped(target);
1053
+ },
1054
+ get virtualIndex() {
1055
+ return target;
1056
+ },
1057
+ get pageCount() {
1058
+ return count();
1059
+ },
1060
+ get isSettling() {
1061
+ return settleHandle != null;
1062
+ },
1063
+ get isDragging() {
1064
+ return isDragging;
1065
+ },
1066
+ presentation,
1067
+ pageOffset: offsetOf,
1068
+ nearestPage: position => clampIndex(nearestPage(position)),
1069
+ goTo,
1070
+ setOptions,
1071
+ setPanEnabled(enabled) {
1072
+ deferringCallbacks(() => pan.setEnabled(enabled));
1073
+ },
1074
+ attach,
1075
+ dispose() {
1076
+ detachAll?.();
1077
+ }
1078
+ };
1079
+ }
1080
+ /**
1081
+ * A pager on two elements. Callbacks are read through a ref, so passing new
1082
+ * functions each render costs nothing; a gesture never renders.
1083
+ *
1084
+ * @example
1085
+ * ```
1086
+ * const pager = usePager({viewportRef, trackRef, count: photos.length, gap: 40,
1087
+ * onIndexChange: setCounter});
1088
+ * <div ref={viewportRef} style={{overflow: 'hidden'}}>
1089
+ * <div ref={trackRef} style={{display: 'flex', gap: 40}}>…pages…</div>
1090
+ * </div>
1091
+ * ```
1092
+ */
1093
+ export function usePager({
1094
+ viewportRef,
1095
+ trackRef,
1096
+ index,
1097
+ isPanEnabled = true,
1098
+ ...options
1099
+ }) {
1100
+ const latestRef = useRef(options);
1101
+ // The controlled `index` of the last commit, read when the pager reports.
1102
+ const indexRef = useRef(index);
1103
+ // Syncs the callback and controlled-index refs with the newest render; the
1104
+ // pager's callbacks read them.
1105
+ useIsomorphicLayoutEffect(() => {
1106
+ latestRef.current = options;
1107
+ indexRef.current = index;
1108
+ });
1109
+ // Bumped when the pager reports a page while `index` is controlled. The
1110
+ // render it causes is batched with the owner's own update. If the owner kept
1111
+ // `index`, that render returns the pager to it (the controlled sync below).
1112
+ const [reported, setReported] = useState(0);
1113
+ const [pager] = useState(() => createPager({
1114
+ ...options,
1115
+ defaultIndex: index ?? options.defaultIndex,
1116
+ onIndexChange: (i, reason) => {
1117
+ latestRef.current.onIndexChange?.(i, reason);
1118
+ if (indexRef.current != null) {
1119
+ setReported(n => n + 1);
1120
+ }
1121
+ },
1122
+ onSettle: (i, previous) => latestRef.current.onSettle?.(i, previous),
1123
+ onPagesChange: pageCount => latestRef.current.onPagesChange?.(pageCount),
1124
+ shouldBeginPan: direction => latestRef.current.shouldBeginPan?.(direction) ?? true
1125
+ }));
1126
+
1127
+ // Synchronizes the pager (the track's animation and the gesture host) with
1128
+ // these props. A clamp it causes is not reported back (reason 'controlled').
1129
+ const {
1130
+ count,
1131
+ gap,
1132
+ loop,
1133
+ pages
1134
+ } = options;
1135
+ useIsomorphicLayoutEffect(() => {
1136
+ pager.setOptions({
1137
+ count,
1138
+ gap,
1139
+ loop,
1140
+ pages
1141
+ });
1142
+ }, [pager, count, gap, loop, pages]);
1143
+
1144
+ // Attaches the pager to the viewport and track nodes, and again whenever
1145
+ // either node is replaced; detaches at unmount.
1146
+ useAttachmentPair(viewportRef, trackRef, (viewport, track) => pager.attach(viewport, track), pager);
1147
+
1148
+ // Synchronizes the pan recognizer (the gesture host) with isPanEnabled; what
1149
+ // a drag it ends calls back waits for the next frame, after this Effect.
1150
+ useEffect(() => {
1151
+ pager.setPanEnabled(isPanEnabled);
1152
+ }, [pager, isPanEnabled]);
1153
+
1154
+ // Synchronizes the pager, an imperative system outside React (the track's
1155
+ // animation and its gesture recognizers), with a controlled `index`. A new
1156
+ // `index` moves the pager there. So does the render after a page that it
1157
+ // reported and the owner did not take, such as a refused swipe. A
1158
+ // controlled input returns to its value the same way. The move is the
1159
+ // owner's own, so it is not reported back. It moves only while the two
1160
+ // differ.
1161
+ useEffect(() => {
1162
+ if (index != null && index !== pager.index) {
1163
+ pager.goTo(index, {
1164
+ reason: 'controlled'
1165
+ });
1166
+ }
1167
+ }, [pager, index, reported]);
1168
+ return pager;
1169
+ }