@lynx-js/lynx-ui-common 0.0.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.
Files changed (215) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +28 -0
  3. package/dist/const/BaseScrollEventsMapping.d.ts +2 -0
  4. package/dist/const/BaseScrollEventsMapping.d.ts.map +1 -0
  5. package/dist/const/BaseScrollEventsMapping.jsx +13 -0
  6. package/dist/const/BaseScrollEventsMapping.jsx.map +1 -0
  7. package/dist/const/BaseUIEventsMapping.d.ts +4 -0
  8. package/dist/const/BaseUIEventsMapping.d.ts.map +1 -0
  9. package/dist/const/BaseUIEventsMapping.jsx +24 -0
  10. package/dist/const/BaseUIEventsMapping.jsx.map +1 -0
  11. package/dist/const/index.d.ts +3 -0
  12. package/dist/const/index.d.ts.map +1 -0
  13. package/dist/const/index.jsx +2 -0
  14. package/dist/hooks/docs/useBounce.jsx +0 -0
  15. package/dist/hooks/docs/useRefresh.jsx +0 -0
  16. package/dist/hooks/index.d.ts +19 -0
  17. package/dist/hooks/index.d.ts.map +1 -0
  18. package/dist/hooks/index.jsx +73 -0
  19. package/dist/hooks/index.jsx.map +1 -0
  20. package/dist/hooks/useBounce.d.ts +26 -0
  21. package/dist/hooks/useBounce.d.ts.map +1 -0
  22. package/dist/hooks/useBounce.jsx +383 -0
  23. package/dist/hooks/useBounce.jsx.map +1 -0
  24. package/dist/hooks/useGCCollector.d.ts +18 -0
  25. package/dist/hooks/useGCCollector.d.ts.map +1 -0
  26. package/dist/hooks/useGCCollector.jsx +48 -0
  27. package/dist/hooks/useGCCollector.jsx.map +1 -0
  28. package/dist/hooks/useGlobalEventListener.d.ts +9 -0
  29. package/dist/hooks/useGlobalEventListener.d.ts.map +1 -0
  30. package/dist/hooks/useGlobalEventListener.jsx +19 -0
  31. package/dist/hooks/useGlobalEventListener.jsx.map +1 -0
  32. package/dist/hooks/useLatest.d.ts +6 -0
  33. package/dist/hooks/useLatest.d.ts.map +1 -0
  34. package/dist/hooks/useLatest.jsx +9 -0
  35. package/dist/hooks/useLatest.jsx.map +1 -0
  36. package/dist/hooks/useMemoizedFn.d.ts +8 -0
  37. package/dist/hooks/useMemoizedFn.d.ts.map +1 -0
  38. package/dist/hooks/useMemoizedFn.jsx +15 -0
  39. package/dist/hooks/useMemoizedFn.jsx.map +1 -0
  40. package/dist/hooks/usePrevious.d.ts +16 -0
  41. package/dist/hooks/usePrevious.d.ts.map +1 -0
  42. package/dist/hooks/usePrevious.jsx +11 -0
  43. package/dist/hooks/usePrevious.jsx.map +1 -0
  44. package/dist/hooks/useRefresh.d.ts +24 -0
  45. package/dist/hooks/useRefresh.d.ts.map +1 -0
  46. package/dist/hooks/useRefresh.jsx +554 -0
  47. package/dist/hooks/useRefresh.jsx.map +1 -0
  48. package/dist/hooks/useRegisteredEvents.d.ts +19 -0
  49. package/dist/hooks/useRegisteredEvents.d.ts.map +1 -0
  50. package/dist/hooks/useRegisteredEvents.jsx +24 -0
  51. package/dist/hooks/useRegisteredEvents.jsx.map +1 -0
  52. package/dist/hooks/useUnmount.d.ts +2 -0
  53. package/dist/hooks/useUnmount.d.ts.map +1 -0
  54. package/dist/hooks/useUnmount.jsx +11 -0
  55. package/dist/hooks/useUnmount.jsx.map +1 -0
  56. package/dist/index.d.ts +8 -0
  57. package/dist/index.d.ts.map +1 -0
  58. package/dist/index.jsx +6 -0
  59. package/dist/reactive/hooks/useReactiveValue.d.ts +22 -0
  60. package/dist/reactive/hooks/useReactiveValue.d.ts.map +1 -0
  61. package/dist/reactive/hooks/useReactiveValue.jsx +75 -0
  62. package/dist/reactive/hooks/useReactiveValue.jsx.map +1 -0
  63. package/dist/reactive/hooks/useReactiveValueChange.d.ts +4 -0
  64. package/dist/reactive/hooks/useReactiveValueChange.d.ts.map +1 -0
  65. package/dist/reactive/hooks/useReactiveValueChange.jsx +7 -0
  66. package/dist/reactive/hooks/useReactiveValueChange.jsx.map +1 -0
  67. package/dist/reactive/hooks/useReactiveValueEvent.d.ts +5 -0
  68. package/dist/reactive/hooks/useReactiveValueEvent.d.ts.map +1 -0
  69. package/dist/reactive/hooks/useReactiveValueEvent.jsx +15 -0
  70. package/dist/reactive/hooks/useReactiveValueEvent.jsx.map +1 -0
  71. package/dist/reactive/index.d.ts +6 -0
  72. package/dist/reactive/index.d.ts.map +1 -0
  73. package/dist/reactive/index.jsx +5 -0
  74. package/dist/reactive/types.d.ts +17 -0
  75. package/dist/reactive/types.d.ts.map +1 -0
  76. package/dist/reactive/types.jsx +0 -0
  77. package/dist/reactive/updateReactive.d.ts +4 -0
  78. package/dist/reactive/updateReactive.d.ts.map +1 -0
  79. package/dist/reactive/updateReactive.jsx +8 -0
  80. package/dist/reactive/updateReactive.jsx.map +1 -0
  81. package/dist/types/index.d.ts +2 -0
  82. package/dist/types/index.d.ts.map +1 -0
  83. package/dist/types/index.jsx +0 -0
  84. package/dist/types/interfaces/BaseScrollEvents.d.ts +40 -0
  85. package/dist/types/interfaces/BaseScrollEvents.d.ts.map +1 -0
  86. package/dist/types/interfaces/BaseScrollEvents.jsx +0 -0
  87. package/dist/types/interfaces/BaseUIEvents.d.ts +132 -0
  88. package/dist/types/interfaces/BaseUIEvents.d.ts.map +1 -0
  89. package/dist/types/interfaces/BaseUIEvents.jsx +0 -0
  90. package/dist/types/interfaces/BaseUIProps.d.ts +19 -0
  91. package/dist/types/interfaces/BaseUIProps.d.ts.map +1 -0
  92. package/dist/types/interfaces/BaseUIProps.jsx +0 -0
  93. package/dist/types/interfaces/BounceableInterface.d.ts +120 -0
  94. package/dist/types/interfaces/BounceableInterface.d.ts.map +1 -0
  95. package/dist/types/interfaces/BounceableInterface.jsx +0 -0
  96. package/dist/types/interfaces/EventMTSInterface.d.ts +1 -0
  97. package/dist/types/interfaces/EventMTSInterface.d.ts.map +1 -0
  98. package/dist/types/interfaces/EventMTSInterface.jsx +0 -0
  99. package/dist/types/interfaces/LazyInterface.d.ts +72 -0
  100. package/dist/types/interfaces/LazyInterface.d.ts.map +1 -0
  101. package/dist/types/interfaces/LazyInterface.jsx +0 -0
  102. package/dist/types/interfaces/RefreshInterface.d.ts +98 -0
  103. package/dist/types/interfaces/RefreshInterface.d.ts.map +1 -0
  104. package/dist/types/interfaces/RefreshInterface.jsx +10 -0
  105. package/dist/types/interfaces/RefreshInterface.jsx.map +1 -0
  106. package/dist/types/interfaces/index.d.ts +36 -0
  107. package/dist/types/interfaces/index.d.ts.map +1 -0
  108. package/dist/types/interfaces/index.jsx +0 -0
  109. package/dist/utils/common.d.ts +15 -0
  110. package/dist/utils/common.d.ts.map +1 -0
  111. package/dist/utils/common.jsx +12 -0
  112. package/dist/utils/common.jsx.map +1 -0
  113. package/dist/utils/common.test.jsx +55 -0
  114. package/dist/utils/common.test.jsx.map +1 -0
  115. package/dist/utils/convertToPx.d.ts +4 -0
  116. package/dist/utils/convertToPx.d.ts.map +1 -0
  117. package/dist/utils/convertToPx.jsx +20 -0
  118. package/dist/utils/convertToPx.jsx.map +1 -0
  119. package/dist/utils/delayFrames.d.ts +2 -0
  120. package/dist/utils/delayFrames.d.ts.map +1 -0
  121. package/dist/utils/delayFrames.jsx +12 -0
  122. package/dist/utils/delayFrames.jsx.map +1 -0
  123. package/dist/utils/getEventDetail.d.ts +23 -0
  124. package/dist/utils/getEventDetail.d.ts.map +1 -0
  125. package/dist/utils/getEventDetail.jsx +7 -0
  126. package/dist/utils/getEventDetail.jsx.map +1 -0
  127. package/dist/utils/index.d.ts +13 -0
  128. package/dist/utils/index.d.ts.map +1 -0
  129. package/dist/utils/index.jsx +12 -0
  130. package/dist/utils/interpolation.d.ts +40 -0
  131. package/dist/utils/interpolation.d.ts.map +1 -0
  132. package/dist/utils/interpolation.jsx +86 -0
  133. package/dist/utils/interpolation.jsx.map +1 -0
  134. package/dist/utils/interpolationJS.d.ts +39 -0
  135. package/dist/utils/interpolationJS.d.ts.map +1 -0
  136. package/dist/utils/interpolationJS.jsx +80 -0
  137. package/dist/utils/interpolationJS.jsx.map +1 -0
  138. package/dist/utils/log.d.ts +3 -0
  139. package/dist/utils/log.d.ts.map +1 -0
  140. package/dist/utils/log.jsx +10 -0
  141. package/dist/utils/log.jsx.map +1 -0
  142. package/dist/utils/mainThreadify.d.ts +2 -0
  143. package/dist/utils/mainThreadify.d.ts.map +1 -0
  144. package/dist/utils/mainThreadify.jsx +11 -0
  145. package/dist/utils/mainThreadify.jsx.map +1 -0
  146. package/dist/utils/popoverUtils.d.ts +3 -0
  147. package/dist/utils/popoverUtils.d.ts.map +1 -0
  148. package/dist/utils/popoverUtils.jsx +12 -0
  149. package/dist/utils/popoverUtils.jsx.map +1 -0
  150. package/dist/utils/renderContentWithExtraProps.d.ts +5 -0
  151. package/dist/utils/renderContentWithExtraProps.d.ts.map +1 -0
  152. package/dist/utils/renderContentWithExtraProps.jsx +10 -0
  153. package/dist/utils/renderContentWithExtraProps.jsx.map +1 -0
  154. package/dist/utils/selector.d.ts +36 -0
  155. package/dist/utils/selector.d.ts.map +1 -0
  156. package/dist/utils/selector.jsx +85 -0
  157. package/dist/utils/selector.jsx.map +1 -0
  158. package/dist/utils/selector.test.jsx +215 -0
  159. package/dist/utils/selector.test.jsx.map +1 -0
  160. package/dist/utils/version.d.ts +6 -0
  161. package/dist/utils/version.d.ts.map +1 -0
  162. package/dist/utils/version.jsx +28 -0
  163. package/dist/utils/version.jsx.map +1 -0
  164. package/dist/utils/version.test.jsx +77 -0
  165. package/dist/utils/version.test.jsx.map +1 -0
  166. package/package.json +52 -0
  167. package/src/const/BaseScrollEventsMapping.ts +14 -0
  168. package/src/const/BaseUIEventsMapping.ts +25 -0
  169. package/src/const/index.ts +6 -0
  170. package/src/hooks/docs/useBounce.mdx +2 -0
  171. package/src/hooks/docs/useRefresh.mdx +2 -0
  172. package/src/hooks/index.ts +96 -0
  173. package/src/hooks/useBounce.tsx +814 -0
  174. package/src/hooks/useGCCollector.tsx +76 -0
  175. package/src/hooks/useGlobalEventListener.ts +50 -0
  176. package/src/hooks/useLatest.ts +16 -0
  177. package/src/hooks/useMemoizedFn.ts +35 -0
  178. package/src/hooks/usePrevious.ts +28 -0
  179. package/src/hooks/useRefresh.ts +1054 -0
  180. package/src/hooks/useRegisteredEvents.ts +69 -0
  181. package/src/hooks/useUnmount.ts +18 -0
  182. package/src/index.tsx +25 -0
  183. package/src/reactive/hooks/useReactiveValue.ts +132 -0
  184. package/src/reactive/hooks/useReactiveValueChange.ts +15 -0
  185. package/src/reactive/hooks/useReactiveValueEvent.ts +26 -0
  186. package/src/reactive/index.ts +20 -0
  187. package/src/reactive/types.ts +29 -0
  188. package/src/reactive/updateReactive.ts +16 -0
  189. package/src/types/index.ts +5 -0
  190. package/src/types/interfaces/BaseScrollEvents.ts +47 -0
  191. package/src/types/interfaces/BaseUIEvents.ts +142 -0
  192. package/src/types/interfaces/BaseUIProps.ts +22 -0
  193. package/src/types/interfaces/BounceableInterface.ts +125 -0
  194. package/src/types/interfaces/EventMTSInterface.ts +35 -0
  195. package/src/types/interfaces/LazyInterface.tsx +78 -0
  196. package/src/types/interfaces/RefreshInterface.ts +105 -0
  197. package/src/types/interfaces/index.ts +44 -0
  198. package/src/utils/common.test.ts +64 -0
  199. package/src/utils/common.ts +35 -0
  200. package/src/utils/convertToPx.ts +32 -0
  201. package/src/utils/delayFrames.ts +24 -0
  202. package/src/utils/getEventDetail.ts +36 -0
  203. package/src/utils/index.ts +16 -0
  204. package/src/utils/interpolation.ts +222 -0
  205. package/src/utils/interpolationJS.ts +212 -0
  206. package/src/utils/log.ts +16 -0
  207. package/src/utils/mainThreadify.ts +17 -0
  208. package/src/utils/popoverUtils.ts +25 -0
  209. package/src/utils/renderContentWithExtraProps.ts +20 -0
  210. package/src/utils/selector.test.ts +237 -0
  211. package/src/utils/selector.ts +222 -0
  212. package/src/utils/version.test.ts +98 -0
  213. package/src/utils/version.ts +50 -0
  214. package/tsconfig.docs.json +7 -0
  215. package/tsconfig.json +12 -0
@@ -0,0 +1,1054 @@
1
+ // Copyright 2026 The Lynx Authors. All rights reserved.
2
+ // Licensed under the Apache License Version 2.0 that can be found in the
3
+ // LICENSE file in the root directory of this source tree.
4
+
5
+ import { runOnBackground, useMainThreadRef } from '@lynx-js/react'
6
+
7
+ import { NativeGesture, useGesture } from '@lynx-js/gesture-runtime'
8
+ import type { GestureChangeEvent, StateManager } from '@lynx-js/gesture-runtime'
9
+ import type { MainThread, ScrollEvent } from '@lynx-js/types'
10
+
11
+ import type {
12
+ BounceableBasicProps,
13
+ RefreshEvent,
14
+ RefreshProps,
15
+ RefreshStateChange,
16
+ headerReleased,
17
+ refreshOffsetEvent,
18
+ scrollToBouncesInfo,
19
+ } from '../types'
20
+ import { RefreshState } from '../types/interfaces/RefreshInterface'
21
+ import { selectorMT } from '../utils/selector'
22
+ import { mtsNativeLynxSDKVersionLessThan } from '../utils/version'
23
+
24
+ export interface useRefreshAndBounceOptions {
25
+ refreshOptions: RefreshProps
26
+ bounceableOptions: BounceableBasicProps
27
+ id: string
28
+ scrollOrientation: 'vertical' | 'horizontal'
29
+ }
30
+
31
+ export interface useRefreshAndBounceReturn {
32
+ refreshAndBounceGesture: NativeGesture
33
+ 'main-thread:onLayoutChange': (e: MainThread.LayoutChangeEvent) => void
34
+ 'main-thread:onScroll': (e: ScrollEvent) => void
35
+ 'main-thread:onLayoutComplete': () => void
36
+ onUpperExposure: () => void
37
+ onUpperDisexposure: () => void
38
+ onLowerExposure: () => void
39
+ onLowerDisexposure: () => void
40
+ onRefreshHeaderLayoutUpdated: (e: MainThread.LayoutChangeEvent) => void
41
+ finishRefresh: () => void
42
+ startRefreshMethod: () => void
43
+ }
44
+
45
+ export function useRefreshAndBounce(
46
+ options: useRefreshAndBounceOptions,
47
+ ): useRefreshAndBounceReturn {
48
+ // Control the damping coefficient during rubber effect. The smaller it is, the harder the spring effect.
49
+ const rubberC = useMainThreadRef(0.55)
50
+ // Control the fling deceleration coefficient during dropdown. The smaller it is, the faster it stops.
51
+ const flingDeceleratingRate = useMainThreadRef(0.98)
52
+ // The rebound coefficient during bounce back, the larger it is, the faster the rebound speed.
53
+ const beta = useMainThreadRef(15)
54
+ // The starting point of current touch procedure
55
+ const startTouchEvent = useMainThreadRef<GestureChangeEvent | null>(null)
56
+ // Record the previous touch and clear it on touchEnd. If current is not empty, then it means that the scrollable object is being dragged.
57
+ const prevTouchEvent = useMainThreadRef<GestureChangeEvent | null>(null)
58
+ // Current scroll velocity.
59
+ const scrollVelocity = useMainThreadRef(0)
60
+ // Read from options
61
+ const containerID = options.id ?? 'bounceableContainer'
62
+ // Current bouncing position.
63
+ const bouncingPositionInfo = useMainThreadRef({ currentID: containerID })
64
+ // If reaches edge and bouncing starts during dragging, save the touch point and calculate later touch delta for rubberEffect.
65
+ const startBouncingTouchEvent = useMainThreadRef<GestureChangeEvent | null>(
66
+ null,
67
+ )
68
+ // If reaches edge and bouncing starts during dragging, save current bouncingPosition and continues rubberEffect's calculation from this point.
69
+ const startTouchBouncingDelta = useMainThreadRef({})
70
+ // when touch starts during bouncing, save current bouncingPosition and continues rubberEffect's calculation from this point.
71
+ const bouncingTouchStartPosition = useMainThreadRef({})
72
+ // Used to record the previous scroll position and calculate current scroll velocity.
73
+ const prevScroll = useMainThreadRef({})
74
+ // scroll container's basic info.
75
+ const height = useMainThreadRef(0)
76
+ const width = useMainThreadRef(0)
77
+ const scrollX = useMainThreadRef(0)
78
+ const scrollY = useMainThreadRef(0)
79
+ // Flags for ending bouncing animation.
80
+ const touchEndFrameEnableFlag = useMainThreadRef(false)
81
+ const touchingEndBouncingBackEnableFlag = useMainThreadRef(false)
82
+ const flingEndWithBouncingEnableFlag = useMainThreadRef(false)
83
+ // Flags for reaches upper/lower edge.
84
+ // When content's size is smaller than viewport, these two flags are both true.
85
+ const toUpper = useMainThreadRef(false)
86
+ const toLower = useMainThreadRef(false)
87
+ const { enableBounces, onScrollToBounces } = options.bounceableOptions
88
+ const bounceableDebugLog = useMainThreadRef(
89
+ (enableBounces && options.bounceableOptions.debugLog) ?? false,
90
+ )
91
+ const alwaysBouncing = options.bounceableOptions.alwaysBouncing
92
+ ?? options.refreshOptions.enableRefresh
93
+ ?? false
94
+ const scrollOrientation = options.scrollOrientation ?? 'vertical'
95
+ const enableBounceEventInFling =
96
+ options.bounceableOptions.enableBounceEventInFling
97
+ ?? options.bounceableOptions.enableBounceEventInFling
98
+ ?? true
99
+ const startBounceTriggerDistance =
100
+ options.bounceableOptions.startBounceTriggerDistance ?? 0
101
+ const endBounceTriggerDistance =
102
+ options.bounceableOptions.endBounceTriggerDistance ?? 0
103
+ // Temporary workaround as requestAnimationFrame will crash below Lynx 2.15.2.
104
+ const temporaryValidVersionCheckForRAF = useMainThreadRef(
105
+ options.bounceableOptions.validAnimationVersion
106
+ ?? options.refreshOptions.validAnimationVersion,
107
+ )
108
+ // Refresh props
109
+ const {
110
+ enableRefresh,
111
+ onStartRefresh,
112
+ onRefreshOffsetChange,
113
+ onRefreshStateChange,
114
+ onHeaderReleased,
115
+ } = options.refreshOptions
116
+ const refreshHeaderSize = useMainThreadRef<number>(0)
117
+ const refreshDebugLog = useMainThreadRef(
118
+ options.refreshOptions.debugLog ?? false,
119
+ )
120
+ // While refresh released and finishRefresh not called, the bouncingBack should not be triggered.
121
+ const isDuringRefresh = useMainThreadRef(false)
122
+ const currentRefreshState = useMainThreadRef(RefreshState.IDLE)
123
+ const bouncingStatus = {
124
+ inScrollingRange: 0,
125
+ upperBouncing: 1,
126
+ lowerBouncing: 2,
127
+ noBouncing: 3,
128
+ alwaysBouncing: 4,
129
+ }
130
+ const bouncingBackMode = {
131
+ resetToBoundary: 0,
132
+ clampToHeader: 1,
133
+ }
134
+ function isVertical() {
135
+ 'main thread'
136
+ return scrollOrientation === 'vertical'
137
+ }
138
+ function threshold() {
139
+ 'main thread'
140
+ return 1.0 / Number(SystemInfo.pixelRatio)
141
+ }
142
+ function bouncingBackThreshold(mode: number) {
143
+ 'main thread'
144
+ switch (mode) {
145
+ case bouncingBackMode.resetToBoundary:
146
+ return threshold()
147
+ case bouncingBackMode.clampToHeader:
148
+ return refreshHeaderSize.current + threshold()
149
+ default:
150
+ return threshold()
151
+ }
152
+ }
153
+
154
+ function bouncingBackTargetPosition(mode: number) {
155
+ 'main thread'
156
+ switch (mode) {
157
+ case bouncingBackMode.resetToBoundary:
158
+ return 0
159
+ break
160
+ case bouncingBackMode.clampToHeader:
161
+ return refreshHeaderSize.current
162
+ break
163
+ default:
164
+ return 0
165
+ }
166
+ }
167
+ function isAndroid() {
168
+ 'main thread'
169
+ return SystemInfo.platform === 'Android'
170
+ }
171
+
172
+ function isEmpty(obj: Record<string, unknown>) {
173
+ 'main thread'
174
+ return !obj || Object.keys(obj).length === 0
175
+ }
176
+ function enableScroll(enable: boolean) {
177
+ 'main thread'
178
+ // Android will trigger scroll during bouncing, cancel it while bouncing.
179
+ // When refresh is enabled, disable scroll to avoid scroll during bouncing. Otherwise, scroll container may be scrolled during refresh process.
180
+ if (isAndroid() || isDuringRefresh.current) {
181
+ selectorMT(containerID)?.setAttribute('enable-scroll', enable)
182
+ }
183
+ }
184
+ // Clear all temps when a touch procedure ends.
185
+ function clearTouchInfo() {
186
+ 'main thread'
187
+ startTouchEvent.current = null
188
+ bouncingTouchStartPosition.current = 0
189
+ prevTouchEvent.current = null
190
+ startBouncingTouchEvent.current = null
191
+ startTouchBouncingDelta.current = 0
192
+ }
193
+ // Temporary workaround as requestAnimationFrame will crash below Lynx 2.15.2.
194
+ function customRequestAnimationFrame(animationFunc: () => void) {
195
+ 'main thread'
196
+ if (temporaryValidVersionCheckForRAF.current) {
197
+ requestAnimationFrame(animationFunc)
198
+ } else {
199
+ setTimeout(animationFunc, 8)
200
+ }
201
+ }
202
+
203
+ // Calculate current touch delta based on 'startPoint'. The startPoint here should be startBouncingTouchEvent which means this bouncing effect happens during a touch procedure.
204
+ function getCurrentDelta(event: GestureChangeEvent) {
205
+ 'main thread'
206
+ if (startTouchEvent.current === null) {
207
+ return 0
208
+ }
209
+ if (startBouncingTouchEvent.current === null) {
210
+ return scrollOrientation === 'vertical'
211
+ ? event.params.pageY - startTouchEvent.current.params.pageY
212
+ : event.params.pageX - startTouchEvent.current.params.pageX
213
+ } else {
214
+ return scrollOrientation === 'vertical'
215
+ ? event.params.pageY - startBouncingTouchEvent.current.params.pageY
216
+ : event.params.pageX - startBouncingTouchEvent.current.params.pageX
217
+ }
218
+ }
219
+
220
+ function onRefreshStateChangeJS(info: RefreshStateChange) {
221
+ if (enableRefresh && onRefreshStateChange) {
222
+ onRefreshStateChange(info)
223
+ }
224
+ }
225
+
226
+ function sendRefreshStateChangeEvent(state: number) {
227
+ 'main thread'
228
+ const refreshStateChangeInfo: RefreshStateChange = {
229
+ state,
230
+ }
231
+ runOnBackground(onRefreshStateChangeJS)(refreshStateChangeInfo)
232
+ }
233
+
234
+ function setRefreshState(state: RefreshState) {
235
+ 'main thread'
236
+ if (currentRefreshState.current === state) {
237
+ return
238
+ }
239
+ currentRefreshState.current = state
240
+ sendRefreshStateChangeEvent(state)
241
+ }
242
+
243
+ function onStartRefreshJS(info: RefreshEvent) {
244
+ if (enableRefresh && onStartRefresh) {
245
+ onStartRefresh(info)
246
+ }
247
+ }
248
+
249
+ function sendStartRefreshEvent(fromStartRefreshMethod: boolean) {
250
+ 'main thread'
251
+ const refreshInfo: RefreshEvent = {
252
+ triggeredBy: fromStartRefreshMethod ? 'startRefresh' : 'drag',
253
+ }
254
+ runOnBackground(onStartRefreshJS)(refreshInfo)
255
+ }
256
+
257
+ function onHeaderReleasedJS(info: headerReleased) {
258
+ if (enableRefresh && onHeaderReleased) {
259
+ onHeaderReleased(info)
260
+ }
261
+ }
262
+ function sendHeaderReleasedEvent() {
263
+ 'main thread'
264
+ if (
265
+ // @ts-expect-error expected
266
+ bouncingPositionInfo.current.bouncingOffset > 0
267
+ ) {
268
+ if (
269
+ // @ts-expect-error expected
270
+ refreshHeaderSize.current < bouncingPositionInfo.current.bouncingOffset
271
+ ) {
272
+ setRefreshState(RefreshState.OVER_DRAG_RELEASE)
273
+ }
274
+ const refreshReleaseInfo: headerReleased = {
275
+ // @ts-expect-error expected
276
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
277
+ offset: bouncingPositionInfo.current.bouncingOffset ?? 0,
278
+ headerSize: refreshHeaderSize.current,
279
+ }
280
+ runOnBackground(onHeaderReleasedJS)(refreshReleaseInfo)
281
+ }
282
+ }
283
+
284
+ function onRefreshOffsetChangeJS(info: refreshOffsetEvent) {
285
+ if (enableRefresh && onRefreshOffsetChange) {
286
+ onRefreshOffsetChange(info)
287
+ }
288
+ }
289
+
290
+ function sendHeaderOffsetChangeEvent() {
291
+ 'main thread'
292
+ if (
293
+ // @ts-expect-error expected
294
+ bouncingPositionInfo.current.bouncingOffset > 0
295
+ ) {
296
+ const refreshOffsetChangeInfo: refreshOffsetEvent = {
297
+ // @ts-expect-error expected
298
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
299
+ offset: bouncingPositionInfo.current.bouncingOffset ?? 0,
300
+ headerSize: refreshHeaderSize.current,
301
+ isDragging: startTouchEvent.current !== null,
302
+ }
303
+ runOnBackground(onRefreshOffsetChangeJS)(refreshOffsetChangeInfo)
304
+ }
305
+ }
306
+
307
+ // Key bouncing status judgement.
308
+ function getBouncingStatus() {
309
+ 'main thread'
310
+ // @ts-expect-error expected
311
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
312
+ const currentPosition = bouncingPositionInfo.current?.bouncingOffset ?? 0
313
+ if (Boolean(toUpper.current) && Boolean(toLower.current)) {
314
+ return alwaysBouncing
315
+ ? bouncingStatus.alwaysBouncing
316
+ : bouncingStatus.noBouncing
317
+ }
318
+ // upper bouncing
319
+ const initialLayoutPosition = 0
320
+ if (bounceableDebugLog.current || refreshDebugLog.current) {
321
+ console.info(
322
+ 'getBouncingStatus',
323
+ initialLayoutPosition,
324
+ 'currentPosition',
325
+ currentPosition,
326
+ )
327
+ }
328
+ if (currentPosition > initialLayoutPosition) {
329
+ return bouncingStatus.upperBouncing
330
+ }
331
+ // bottom bouncing
332
+ if (currentPosition < initialLayoutPosition) {
333
+ return bouncingStatus.lowerBouncing
334
+ }
335
+ return bouncingStatus.inScrollingRange
336
+ }
337
+
338
+ // Whether fling and bouncing back step should be triggered.
339
+ function shouldBounceWhenTouchEnd(status: number) {
340
+ 'main thread'
341
+ if (bounceableDebugLog.current || refreshDebugLog.current) {
342
+ console.info('shouldBounceWhenTouchEnd', status)
343
+ }
344
+ if (
345
+ status === bouncingStatus.inScrollingRange
346
+ || status === bouncingStatus.noBouncing
347
+ ) {
348
+ return false
349
+ }
350
+ if (
351
+ status === bouncingStatus.upperBouncing
352
+ || status === bouncingStatus.lowerBouncing
353
+ ) {
354
+ return true
355
+ }
356
+ if (status === bouncingStatus.alwaysBouncing) {
357
+ return alwaysBouncing
358
+ }
359
+ return false
360
+ }
361
+ function releasedOverHeader() {
362
+ 'main thread'
363
+ if (
364
+ // @ts-expect-error expected
365
+ bouncingPositionInfo.current.bouncingOffset > refreshHeaderSize.current
366
+ ) {
367
+ return true
368
+ }
369
+ }
370
+ function shouldBounceBackWhenRefresh(status: number) {
371
+ 'main thread'
372
+ // If not enableRefresh, follow bounceable logic.
373
+ if (!enableRefresh) {
374
+ return false
375
+ }
376
+ if (
377
+ (status === bouncingStatus.upperBouncing
378
+ || status === bouncingStatus.alwaysBouncing)
379
+ && releasedOverHeader()
380
+ ) {
381
+ return true
382
+ }
383
+ return false
384
+ }
385
+ // Use translate to implement real bouncing effect
386
+ function bouncingSetStyle(offset: number) {
387
+ 'main thread'
388
+ if (isNaN(Number(offset))) {
389
+ console.error('ERROR! bouncingOffset is NaN')
390
+ return
391
+ }
392
+ // update bouncingPositionInfo first
393
+ if (isEmpty(bouncingPositionInfo.current)) {
394
+ // @ts-expect-error expected
395
+ bouncingPositionInfo.current.velocity = 0
396
+ } else {
397
+ // @ts-expect-error expected
398
+ const timeDuration = Date.now() - bouncingPositionInfo.current.timeStamp
399
+ const offsetDiff = offset
400
+ // @ts-expect-error expected
401
+ - Number(bouncingPositionInfo.current?.bouncingOffset ?? 0)
402
+ if (timeDuration > 0) {
403
+ // @ts-expect-error expected
404
+ bouncingPositionInfo.current.velocity = offsetDiff / timeDuration
405
+ }
406
+ }
407
+ // @ts-expect-error expected
408
+ bouncingPositionInfo.current.bouncingOffset = offset
409
+ // @ts-expect-error expected
410
+ bouncingPositionInfo.current.timeStamp = Date.now()
411
+ // When bouncing effect ends, clear startTouchEvent and bouncingTouchStartPosition
412
+ if (offset === 0 && prevTouchEvent.current !== null) {
413
+ startTouchEvent.current = prevTouchEvent.current
414
+ bouncingTouchStartPosition.current = {}
415
+ }
416
+ // trigger translate
417
+ if (isVertical()) {
418
+ selectorMT(containerID)?.setStyleProperty(
419
+ 'transform',
420
+ `translateY(${offset}px)`,
421
+ )
422
+ if (refreshDebugLog.current) {
423
+ console.info('bouncingSetStyle', `translateY(${offset}px)`)
424
+ }
425
+ if (enableRefresh) {
426
+ selectorMT(`${containerID}-refreshHeaderWrapper`)?.setStyleProperty(
427
+ 'transform',
428
+ `translateY(${offset}px)`,
429
+ )
430
+ }
431
+ selectorMT(`${containerID}-refreshFooterWrapper`)?.setStyleProperty(
432
+ 'transform',
433
+ `translateY(${offset}px)`,
434
+ )
435
+ selectorMT(`${containerID}-lowerBounceWrapper`)?.setStyleProperty(
436
+ 'transform',
437
+ `translateY(${offset}px)`,
438
+ )
439
+ } else {
440
+ selectorMT(containerID)?.setStyleProperty(
441
+ 'transform',
442
+ `translateX(${offset}px)`,
443
+ )
444
+ selectorMT(`${containerID}-upperBounceWrapper`)?.setStyleProperty(
445
+ 'transform',
446
+ `translateX(${offset}px)`,
447
+ )
448
+ selectorMT(`${containerID}-lowerBounceWrapper`)?.setStyleProperty(
449
+ 'transform',
450
+ `translateX(${offset}px)`,
451
+ )
452
+ }
453
+ // Send refreshOffsetChange event
454
+ if (isVertical() && enableRefresh) {
455
+ sendHeaderOffsetChangeEvent()
456
+ }
457
+ }
458
+
459
+ function onScrollToBouncesJS(info: scrollToBouncesInfo) {
460
+ if (enableBounces && onScrollToBounces) {
461
+ onScrollToBounces(info)
462
+ }
463
+ }
464
+
465
+ // send the scrollToBounces event
466
+ function triggerScrollToBouncesEvent(isUpper: boolean) {
467
+ 'main thread'
468
+ if (bounceableDebugLog.current) {
469
+ console.info('triggerScrollToBouncesEvent', isUpper ? 'upper' : 'lower')
470
+ }
471
+
472
+ const info: scrollToBouncesInfo = {
473
+ direction: isUpper ? 'upper' : 'lower',
474
+ }
475
+ runOnBackground(onScrollToBouncesJS)(info)
476
+ }
477
+
478
+ function rubberEffect(isNegative: 1 | -1, delta: number) {
479
+ 'main thread'
480
+ const scrollViewFrameSize = isVertical() ? height.current : width.current
481
+ // If the touchStartPosition is not zero, it means this rubber effect happens during a touch or another bouncing effect. So the real 'start delta' should be recalculated.
482
+ const touchStartPosition = Math.abs(
483
+ Number(
484
+ isEmpty(startTouchBouncingDelta.current)
485
+ ? bouncingTouchStartPosition.current
486
+ : startTouchBouncingDelta.current,
487
+ ),
488
+ )
489
+ // This deltaYForTouchStartPosition is the inverse function of rubberEffect function
490
+ const deltaYForTouchStartPosition =
491
+ (scrollViewFrameSize * touchStartPosition)
492
+ / ((scrollViewFrameSize - touchStartPosition) * rubberC.current) || 0
493
+ // Here it calculate the next touchDelta. deltaYForNextPosition = (touch point where bouncing happens + corresponding touch delta where previous bouncing position locates)
494
+ // This isNegative is used to handle the upper/lower bounce. RubberEffect function is different in the range (-inf,0) and [0, inf). We only use the [0, inf) part.
495
+ const deltaYForNextPosition = bouncingTouchStartPosition.current
496
+ ? deltaYForTouchStartPosition + isNegative * delta
497
+ : isNegative * delta
498
+ // Real calculation. Note that we don't use the raw touchDelta for calculating, instead, we use deltaYForNextPosition.
499
+ const rubberBandingDistance = Math.max(
500
+ 0,
501
+ (1.0
502
+ - 1.0
503
+ / ((deltaYForNextPosition * rubberC.current) / scrollViewFrameSize
504
+ + 1.0))
505
+ * scrollViewFrameSize,
506
+ )
507
+ if (bounceableDebugLog.current || refreshDebugLog.current) {
508
+ console.info(
509
+ 'rubberEffect',
510
+ 'scrollContainerFrameSize',
511
+ scrollViewFrameSize,
512
+ 'touchStartPosition',
513
+ touchStartPosition,
514
+ 'deltaYForTouchStartPosition',
515
+ deltaYForTouchStartPosition,
516
+ 'deltaYForNextPosition',
517
+ deltaYForNextPosition,
518
+ 'rubberBandingDistance',
519
+ rubberBandingDistance,
520
+ )
521
+ }
522
+ setRefreshState(RefreshState.DRAGGING)
523
+ bouncingSetStyle(isNegative * rubberBandingDistance)
524
+ }
525
+
526
+ function onRefreshHeaderLayoutUpdated(event: MainThread.LayoutChangeEvent) {
527
+ 'main thread'
528
+ if (refreshDebugLog.current) {
529
+ console.info('onRefreshHeaderLayoutUpdated', event.detail)
530
+ }
531
+ refreshHeaderSize.current = isAndroid()
532
+ ? event.params?.height
533
+ : event.detail?.height
534
+ }
535
+
536
+ function triggerRubberEffectIfCrossingEdge(event: GestureChangeEvent) {
537
+ 'main thread'
538
+ const delta = getCurrentDelta(event) || 0
539
+ if (bounceableDebugLog.current || refreshDebugLog.current) {
540
+ console.info(
541
+ 'isCrossingEdge',
542
+ 'delta',
543
+ delta,
544
+ 'toUpper',
545
+ toUpper.current,
546
+ 'toLower',
547
+ toLower.current,
548
+ )
549
+ }
550
+ // Crossing top range
551
+ if (toUpper.current === true && delta > 0) {
552
+ enableScroll(false)
553
+ rubberEffect(1, delta)
554
+ }
555
+ // Crossing bottom range
556
+ if (toLower.current === true && delta < 0) {
557
+ enableScroll(false)
558
+ rubberEffect(-1, delta)
559
+ }
560
+ enableScroll(true)
561
+ }
562
+ // return true if scrollToBounces should be sent
563
+ function isOverTriggerDistance() {
564
+ 'main thread'
565
+ // @ts-expect-error expected
566
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
567
+ const bouncingTop: number = bouncingPositionInfo.current.bouncingOffset ?? 0
568
+ const triggerDistance =
569
+ // @ts-expect-error expected
570
+ bouncingPositionInfo.current?.bouncingOffset > 0
571
+ ? startBounceTriggerDistance
572
+ : endBounceTriggerDistance
573
+ const delta = Math.abs(bouncingTop) - Math.abs(triggerDistance)
574
+ return delta > threshold()
575
+ }
576
+ function bouncingBack(mode: number) {
577
+ 'main thread'
578
+ if (bounceableDebugLog.current || refreshDebugLog.current) {
579
+ console.info('fling forward end')
580
+ console.info('bounce back starts')
581
+ }
582
+ // step3: bounce back
583
+ // @ts-expect-error expected
584
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
585
+ const C1 = bouncingPositionInfo.current.bouncingOffset ?? 0
586
+ const startTime = Date.now()
587
+ const touchingEndBouncingBackFrame = () => {
588
+ if (Boolean(touchingEndBouncingBackEnableFlag.current) === false) {
589
+ return
590
+ }
591
+ const currentTime = Date.now() - startTime
592
+ if (bounceableDebugLog.current || refreshDebugLog.current) {
593
+ console.info('touchingEndBouncingBackFrame')
594
+ }
595
+ // critical damping
596
+ const C2 = beta.current * C1
597
+ const easedDistance = (C1 + C2 * (currentTime / 1000))
598
+ * Math.pow(Math.E, -beta.current * (currentTime / 1000))
599
+ bouncingSetStyle(easedDistance)
600
+ if (Math.abs(easedDistance) < bouncingBackThreshold(mode)) {
601
+ // Make sure it backs to targetPosition. 0 or headerSize.
602
+ if (mode === bouncingBackMode.clampToHeader) {
603
+ isDuringRefresh.current = true
604
+ sendStartRefreshEvent(false)
605
+ setRefreshState(RefreshState.REFRESHING)
606
+ }
607
+ bouncingSetStyle(bouncingBackTargetPosition(mode))
608
+ if (mode === bouncingBackMode.resetToBoundary) {
609
+ enableScroll(true)
610
+ }
611
+ if (bounceableDebugLog.current || refreshDebugLog.current) {
612
+ console.info('bounce back ends')
613
+ }
614
+ } else {
615
+ customRequestAnimationFrame(touchingEndBouncingBackFrame)
616
+ }
617
+ }
618
+ customRequestAnimationFrame(touchingEndBouncingBackFrame)
619
+ touchingEndBouncingBackEnableFlag.current = true
620
+ }
621
+ // bindtouchstart. Save startTouchEvent and bouncingPosition if a bouncing effect is happening.
622
+ function bounceableTouchStart(event: GestureChangeEvent) {
623
+ 'main thread'
624
+ startTouchEvent.current = event
625
+ prevTouchEvent.current = event
626
+ if (bounceableDebugLog.current || refreshDebugLog.current) {
627
+ console.info('bounceableTouchStart')
628
+ }
629
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
630
+ bouncingTouchStartPosition.current =
631
+ // @ts-expect-error expected
632
+ bouncingPositionInfo.current?.bouncingOffset ?? 0
633
+ // reset all animation flags. No animation should play during a touch.
634
+ touchEndFrameEnableFlag.current = false
635
+ touchingEndBouncingBackEnableFlag.current = false
636
+ flingEndWithBouncingEnableFlag.current = false
637
+ }
638
+
639
+ function bounceableTouchMove(event: GestureChangeEvent) {
640
+ 'main thread'
641
+ if (startTouchEvent.current === null) {
642
+ // It means current situation is illegal. A touchMove event happens without a touchStart event beforehand. Or a touchMove event happens after a touchEnd event.
643
+ console.error('ERROR! touch not started')
644
+ return
645
+ }
646
+ prevTouchEvent.current = event
647
+ const delta = getCurrentDelta(event)
648
+ const currentBouncingStatus = getBouncingStatus()
649
+ // Judge the status and trigger rubberEffect. The TouchMove should only consider rubberEffect and nothing else.
650
+ switch (currentBouncingStatus) {
651
+ case bouncingStatus.upperBouncing: {
652
+ enableScroll(false)
653
+ rubberEffect(1, delta)
654
+ if (bounceableDebugLog.current || refreshDebugLog.current) {
655
+ console.info('bounceableTouchMove upperBouncing')
656
+ }
657
+ break
658
+ }
659
+ case bouncingStatus.lowerBouncing: {
660
+ enableScroll(false)
661
+ rubberEffect(-1, delta)
662
+ if (bounceableDebugLog.current || refreshDebugLog.current) {
663
+ console.info('bounceableTouchMove lowerBouncing')
664
+ }
665
+ break
666
+ }
667
+ case bouncingStatus.alwaysBouncing: {
668
+ if (bounceableDebugLog.current || refreshDebugLog.current) {
669
+ console.info('bounceableTouchMove alwaysBouncing')
670
+ }
671
+ if (alwaysBouncing) {
672
+ triggerRubberEffectIfCrossingEdge(event)
673
+ }
674
+ break
675
+ }
676
+ case bouncingStatus.inScrollingRange: {
677
+ if (bounceableDebugLog.current || refreshDebugLog.current) {
678
+ console.info('bounceableTouchMove inScrollingRange')
679
+ }
680
+ triggerRubberEffectIfCrossingEdge(event)
681
+ break
682
+ }
683
+ default:
684
+ break
685
+ }
686
+ }
687
+ function bouncingBackEntrance(mode: number) {
688
+ 'main thread'
689
+ const startTime = Date.now()
690
+ // @ts-expect-error expected
691
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
692
+ const dragEndVelocity = bouncingPositionInfo.current?.velocity ?? 0
693
+ // @ts-expect-error expected
694
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
695
+ const dragEndPosition = bouncingPositionInfo.current?.bouncingOffset ?? 0
696
+ // Send scrolltobounces event.
697
+ if (isOverTriggerDistance()) {
698
+ triggerScrollToBouncesEvent(
699
+ // @ts-expect-error expected
700
+ bouncingPositionInfo.current?.bouncingOffset > 0,
701
+ )
702
+ }
703
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
704
+ let currentVelocity: number = dragEndVelocity
705
+ const touchEndProcessFrame = () => {
706
+ if (Boolean(touchEndFrameEnableFlag.current) === false) {
707
+ return
708
+ }
709
+ if (bounceableDebugLog.current || refreshDebugLog.current) {
710
+ console.info('touchEndProcessFrame')
711
+ }
712
+ if (Math.abs(currentVelocity) <= threshold()) {
713
+ // If the velocity is already under threshold, skip fling and start step3: bounce back.
714
+ bouncingBack(mode)
715
+ } else {
716
+ // If the drag end with a velocity, start fling to consume it.
717
+ // step 2: fling down
718
+ if (bounceableDebugLog.current || refreshDebugLog.current) {
719
+ console.info('fling down start')
720
+ }
721
+ // This function is obtained by integrating the velocity function with a deceleration rate of flingDeceleratingRate.
722
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
723
+ const distance: number = dragEndPosition
724
+ + (dragEndVelocity
725
+ * (Math.pow(flingDeceleratingRate.current, Date.now() - startTime)
726
+ - 1))
727
+ / Math.log(flingDeceleratingRate.current)
728
+ bouncingSetStyle(distance)
729
+ currentVelocity = dragEndVelocity
730
+ * Math.pow(flingDeceleratingRate.current, Date.now() - startTime)
731
+ if (touchEndFrameEnableFlag.current) {
732
+ customRequestAnimationFrame(touchEndProcessFrame)
733
+ }
734
+ }
735
+ }
736
+ customRequestAnimationFrame(touchEndProcessFrame)
737
+ touchEndFrameEnableFlag.current = true
738
+ }
739
+ // bindtouchend. In touchEnd event the fling forward animation and bouncingBack animation should be triggered if necessary.
740
+ function bounceableTouchEnd() {
741
+ 'main thread'
742
+ if (enableRefresh) {
743
+ sendHeaderReleasedEvent()
744
+ }
745
+ // Reset the state. The touch information should be reset, and we should no longer ban the enable-scroll.
746
+ clearTouchInfo()
747
+ enableScroll(true)
748
+ if (bounceableDebugLog.current || refreshDebugLog.current) {
749
+ console.info('bounceableTouchEnd')
750
+ }
751
+ if (shouldBounceBackWhenRefresh(getBouncingStatus())) {
752
+ bouncingBackEntrance(bouncingBackMode.clampToHeader)
753
+ } else if (
754
+ shouldBounceWhenTouchEnd(getBouncingStatus())
755
+ && !shouldBounceBackWhenRefresh(getBouncingStatus())
756
+ ) {
757
+ bouncingBackEntrance(bouncingBackMode.resetToBoundary)
758
+ }
759
+ }
760
+ // Save the bindscroll info and calculate velocity.
761
+ function bounceableHandleScroll(event: ScrollEvent) {
762
+ 'main thread'
763
+ scrollX.current = event.detail.scrollLeft
764
+ scrollY.current = event.detail.scrollTop
765
+ if (!isEmpty(prevScroll.current)) {
766
+ // @ts-expect-error expected
767
+ const timeDuration = Date.now() - prevScroll.current.timestamp
768
+ if (timeDuration > 0) {
769
+ const deltaY = isVertical() // @ts-expect-error expected
770
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
771
+ ? event.detail.scrollTop - prevScroll.current.detail.scrollTop // @ts-expect-error expected
772
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
773
+ : event.detail.scrollLeft - prevScroll.current.detail.scrollLeft
774
+ const velocity = deltaY / timeDuration
775
+ if (Number.isFinite(velocity)) {
776
+ scrollVelocity.current = velocity
777
+ }
778
+ }
779
+ }
780
+ prevScroll.current = event
781
+ }
782
+
783
+ function finishRefresh() {
784
+ 'main thread'
785
+ if (enableRefresh) {
786
+ isDuringRefresh.current = false
787
+ bouncingBack(bouncingBackMode.resetToBoundary)
788
+ setRefreshState(RefreshState.IDLE)
789
+ }
790
+ }
791
+
792
+ function startRefreshMethod() {
793
+ 'main thread'
794
+ if (enableRefresh) {
795
+ isDuringRefresh.current = true
796
+ const scrollToZero = selectorMT(containerID)
797
+ ?.invoke('scrollToPosition', {
798
+ position: 0,
799
+ smooth: false,
800
+ alignTo: 'top',
801
+ useScroller: true,
802
+ })
803
+ // Before startRefresh method, force the List to scroll to top.
804
+ void scrollToZero?.then(() => {
805
+ bouncingSetStyle(refreshHeaderSize.current)
806
+ setRefreshState(RefreshState.OVER_DRAG_RELEASE)
807
+ sendStartRefreshEvent(true)
808
+ })
809
+ }
810
+ }
811
+
812
+ function handleBounceEventInFling() {
813
+ 'main thread'
814
+ // reaches edge during fling
815
+ const startVelocity = scrollVelocity.current
816
+ let currentVelocity = startVelocity
817
+ const startTime = Date.now()
818
+ if (bounceableDebugLog.current || refreshDebugLog.current) {
819
+ console.info('fling to edge event start with velocity', startVelocity)
820
+ }
821
+ let sentScrollToBouncesEvent = false // only sent scrollToBounces once
822
+ const flingEndWithBouncingFrame = () => {
823
+ if (Boolean(flingEndWithBouncingEnableFlag.current) === false) {
824
+ if (bounceableDebugLog.current || refreshDebugLog.current) {
825
+ console.info('flingEndWithBouncingEnableFlag early return')
826
+ }
827
+ return
828
+ }
829
+ if (Math.abs(currentVelocity) <= threshold()) {
830
+ flingEndWithBouncingEnableFlag.current = false
831
+ if (bounceableDebugLog.current || refreshDebugLog.current) {
832
+ console.info('fling event end')
833
+ console.info('bouncing event start')
834
+ }
835
+ bouncingBack(bouncingBackMode.resetToBoundary)
836
+ } else {
837
+ // step 1: fling
838
+ const distance = (currentVelocity
839
+ * (Math.pow(flingDeceleratingRate.current, Date.now() - startTime)
840
+ - 1))
841
+ / Math.log(flingDeceleratingRate.current)
842
+ bouncingSetStyle(-distance)
843
+ if (!sentScrollToBouncesEvent && isOverTriggerDistance()) {
844
+ triggerScrollToBouncesEvent(
845
+ // @ts-expect-error TODO: fix this
846
+ bouncingPositionInfo.current?.bouncingOffset > 0,
847
+ )
848
+ sentScrollToBouncesEvent = true
849
+ }
850
+ currentVelocity = startVelocity
851
+ * Math.pow(flingDeceleratingRate.current, Date.now() - startTime)
852
+ if (flingEndWithBouncingEnableFlag.current) {
853
+ customRequestAnimationFrame(flingEndWithBouncingFrame)
854
+ }
855
+ }
856
+ }
857
+ customRequestAnimationFrame(flingEndWithBouncingFrame)
858
+ flingEndWithBouncingEnableFlag.current = true
859
+ }
860
+
861
+ function onUpperDisexposure() {
862
+ 'main thread'
863
+ if (bounceableDebugLog.current || refreshDebugLog.current) {
864
+ console.info('upper disexposure')
865
+ }
866
+ toUpper.current = false
867
+ }
868
+ // Handle scrolltoupper event.
869
+ function onUpperExposure() {
870
+ 'main thread'
871
+ if (bounceableDebugLog.current || refreshDebugLog.current) {
872
+ console.info('upper exposure')
873
+ }
874
+ toUpper.current = true
875
+ if (prevTouchEvent.current) {
876
+ // reaches edge during dragging
877
+ startBouncingTouchEvent.current = prevTouchEvent.current
878
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
879
+ startTouchBouncingDelta.current =
880
+ // @ts-expect-error expected
881
+ bouncingPositionInfo.current?.bouncingOffset ?? 0
882
+ } else if (
883
+ enableBounceEventInFling
884
+ && Math.abs(scrollVelocity.current) > threshold()
885
+ ) {
886
+ handleBounceEventInFling()
887
+ }
888
+ // clear scrollVelocity once it is consumed when scroll container reaches the edge.
889
+ scrollVelocity.current = 0
890
+ }
891
+
892
+ function onLowerDisexposure() {
893
+ 'main thread'
894
+ if (bounceableDebugLog.current || refreshDebugLog.current) {
895
+ console.info('lower disexposure', scrollVelocity.current)
896
+ }
897
+ toLower.current = false
898
+ }
899
+ function onLowerExposure() {
900
+ 'main thread'
901
+ if (bounceableDebugLog.current || refreshDebugLog.current) {
902
+ console.info('lower exposure')
903
+ }
904
+ toLower.current = true
905
+ // reaches lower during dragging
906
+ if (prevTouchEvent.current) {
907
+ // reaches lower during dragging
908
+ startBouncingTouchEvent.current = prevTouchEvent.current
909
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
910
+ startTouchBouncingDelta.current =
911
+ // @ts-expect-error expected
912
+ bouncingPositionInfo.current?.bouncingOffset ?? 0
913
+ } else if (
914
+ enableBounceEventInFling
915
+ && Math.abs(scrollVelocity.current) > threshold()
916
+ ) {
917
+ handleBounceEventInFling()
918
+ }
919
+ // clear scrollVelocity once it is consumed when scroll container reaches the edge.
920
+ scrollVelocity.current = 0
921
+ }
922
+
923
+ function bounceableLayoutComplete() {
924
+ 'main thread'
925
+ clearTouchInfo()
926
+ }
927
+
928
+ // Used to get the size of scroll container.
929
+ function bounceableLayoutChange(event: MainThread.LayoutChangeEvent) {
930
+ 'main thread'
931
+ height.current = (isAndroid() ? event.params?.height : event.detail?.height)
932
+ ?? 0
933
+ width.current = (isAndroid() ? event.params?.width : event.detail?.width)
934
+ ?? 0
935
+ }
936
+
937
+ const isHorizontalTouchMove = (event: GestureChangeEvent) => {
938
+ 'main thread'
939
+ if (!prevTouchEvent.current) {
940
+ return
941
+ }
942
+ const absDeltaX = Math.abs(
943
+ event.params.clientX - prevTouchEvent.current.params.clientX,
944
+ )
945
+ const absDeltaY = Math.abs(
946
+ event.params.clientY - prevTouchEvent.current.params.clientY,
947
+ )
948
+ if (absDeltaX > absDeltaY) {
949
+ return true
950
+ }
951
+ return false
952
+ }
953
+
954
+ const refreshAndBounceGesture: NativeGesture = useGesture(NativeGesture)
955
+ const isFirstJudge = useMainThreadRef(true)
956
+ refreshAndBounceGesture.onBegin(
957
+ (event: GestureChangeEvent, gestureManager: StateManager) => {
958
+ 'main thread'
959
+ isFirstJudge.current = true
960
+ bounceableTouchStart(event)
961
+ if (mtsNativeLynxSDKVersionLessThan('3.3')) {
962
+ gestureManager.consumeGesture(true)
963
+ }
964
+ },
965
+ )
966
+
967
+ refreshAndBounceGesture.onEnd(() => {
968
+ 'main thread'
969
+ isFirstJudge.current = true
970
+ bounceableTouchEnd()
971
+ })
972
+
973
+ // If the gesture was canceled by outside, we need to trigger same logic here.
974
+ refreshAndBounceGesture.onTouchesCancel(() => {
975
+ 'main thread'
976
+ isFirstJudge.current = true
977
+ bounceableTouchEnd()
978
+ })
979
+
980
+ refreshAndBounceGesture.onUpdate(
981
+ (event: GestureChangeEvent, gestureManager) => {
982
+ 'main thread'
983
+ // We only judge the first update in single touch.
984
+ // Refresh only consume vertical touch move.
985
+ if (
986
+ enableRefresh
987
+ || (enableBounces && scrollOrientation === 'vertical')
988
+ ) {
989
+ // Refresh only consume vertical touch move.
990
+ if (isFirstJudge.current) {
991
+ if (mtsNativeLynxSDKVersionLessThan('3.3')) {
992
+ if (isHorizontalTouchMove(event)) {
993
+ gestureManager.consumeGesture(false)
994
+ gestureManager.end()
995
+ } else {
996
+ gestureManager.consumeGesture(true)
997
+ }
998
+ } else {
999
+ const deltaY = prevTouchEvent.current
1000
+ ? event.params.clientY - prevTouchEvent.current.params.clientY
1001
+ : 0
1002
+ if (
1003
+ !isHorizontalTouchMove(event) && toUpper.current && deltaY > 0
1004
+ ) {
1005
+ gestureManager.interceptGesture(true)
1006
+ } else {
1007
+ gestureManager.interceptGesture(false)
1008
+ }
1009
+ }
1010
+ } else {
1011
+ if (!isHorizontalTouchMove(event)) {
1012
+ bounceableTouchMove(event)
1013
+ }
1014
+ }
1015
+ } else if (enableBounces && scrollOrientation === 'horizontal') {
1016
+ if (mtsNativeLynxSDKVersionLessThan('3.3')) {
1017
+ if (isFirstJudge.current) {
1018
+ if (isHorizontalTouchMove(event)) {
1019
+ gestureManager.consumeGesture(true)
1020
+ } else {
1021
+ gestureManager.consumeGesture(false)
1022
+ gestureManager.end()
1023
+ }
1024
+ } else {
1025
+ if (isHorizontalTouchMove(event)) {
1026
+ bounceableTouchMove(event)
1027
+ }
1028
+ }
1029
+ } else {
1030
+ if (isHorizontalTouchMove(event)) {
1031
+ gestureManager.interceptGesture(false)
1032
+ bounceableTouchMove(event)
1033
+ }
1034
+ }
1035
+ }
1036
+ prevTouchEvent.current = event
1037
+ isFirstJudge.current = false
1038
+ },
1039
+ )
1040
+
1041
+ return {
1042
+ refreshAndBounceGesture,
1043
+ 'main-thread:onLayoutChange': bounceableLayoutChange,
1044
+ 'main-thread:onScroll': bounceableHandleScroll,
1045
+ 'main-thread:onLayoutComplete': bounceableLayoutComplete,
1046
+ onUpperExposure,
1047
+ onUpperDisexposure,
1048
+ onLowerExposure,
1049
+ onLowerDisexposure,
1050
+ onRefreshHeaderLayoutUpdated,
1051
+ finishRefresh,
1052
+ startRefreshMethod,
1053
+ }
1054
+ }