@lynx-js/lynx-ui-scroll-view 3.130.0 → 3.132.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.
@@ -0,0 +1,867 @@
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 { log, mtsLog, selectorMT } from '@lynx-js/lynx-ui-common'
8
+ import type { CommonEvent, MainThread, ScrollEvent } from '@lynx-js/types'
9
+
10
+ export interface scrollToBouncesInfo {
11
+ direction: 'upper' | 'lower'
12
+ }
13
+
14
+ export interface BounceableBasicProps {
15
+ enableBounces: boolean
16
+ enableBounceEventInFling?: boolean
17
+ startBounceTriggerDistance?: number
18
+ endBounceTriggerDistance?: number
19
+ // biome-ignore lint/suspicious/noExplicitAny: expected
20
+ upperBounceItem?: any
21
+ // biome-ignore lint/suspicious/noExplicitAny: expected
22
+ lowerBounceItem?: any
23
+ alwaysBouncing?: boolean
24
+ singleSidedBounce?: 'upper' | 'lower' | 'both' | 'iOSBounces' | 'none'
25
+ estimatedHeight?: number
26
+ estimatedWidth?: number
27
+ validAnimationVersion?: boolean
28
+ onScrollToBounces?: (e: scrollToBouncesInfo) => void
29
+ }
30
+
31
+ export interface useBounceOptions {
32
+ bounceableOptions: BounceableBasicProps
33
+ debugLog?: boolean
34
+ enableRTL?: boolean
35
+ /**
36
+ * idSelector of scroll container
37
+ */
38
+ id?: string
39
+ /**
40
+ * scroll direction
41
+ */
42
+ scrollOrientation: 'vertical' | 'horizontal'
43
+ }
44
+
45
+ export interface bounceHandlers {
46
+ 'main-thread:bindtouchstart': (event: MainThread.TouchEvent) => void
47
+ 'main-thread:bindtouchend': () => void
48
+ 'main-thread:bindtouchmove': (event: MainThread.TouchEvent) => void
49
+ 'main-thread:bindlayoutchange': (event: CommonEvent) => void
50
+ 'main-thread:bindscroll': (event: ScrollEvent) => void
51
+ onUpperExposure: (_event: CommonEvent) => void
52
+ onUpperDisexposure: (_event: CommonEvent) => void
53
+ onLowerExposure: (_event: CommonEvent) => void
54
+ onLowerDisexposure: (_event: CommonEvent) => void
55
+ }
56
+
57
+ export function useBounce(options: useBounceOptions): bounceHandlers {
58
+ // Control the damping coefficient during rubber effect. The smaller it is, the harder the spring effect.
59
+ const rubberC = useMainThreadRef(0.55)
60
+ // Control the fling deceleration coefficient during dropdown. The smaller it is, the faster it stops.
61
+ const flingDeceleratingRate = useMainThreadRef(0.99)
62
+ // The rebound coefficient during bounce back, the larger it is, the faster the rebound speed.
63
+ const beta = useMainThreadRef(15)
64
+
65
+ const debugLogEnabled = Boolean(options.debugLog)
66
+
67
+ const singleSidedBounce = useMainThreadRef(
68
+ options.bounceableOptions.singleSidedBounce ?? 'both',
69
+ )
70
+
71
+ // The starting point of current touch procedure
72
+ const startTouch = useMainThreadRef<MainThread.TouchEvent['touches'] | null>(
73
+ null,
74
+ )
75
+ // Record the previous touch and clear it on touchEnd. If current is not empty, then it means that the scrollable object is being dragged.
76
+ const prevTouch = useMainThreadRef<MainThread.TouchEvent['touches'] | null>(
77
+ null,
78
+ )
79
+
80
+ // Current scroll velocity.
81
+ const scrollVelocity = useMainThreadRef(0)
82
+ // Current bouncing position.
83
+ const bouncingPositionInfo = useMainThreadRef({})
84
+
85
+ // If reaches edge and bouncing starts during dragging, save the touch point and calculate later touch delta for rubberEffect.
86
+ const startBouncingTouch = useMainThreadRef<
87
+ MainThread.TouchEvent['touches'] | null
88
+ >(null)
89
+ // If reaches edge and bouncing starts during dragging, save current bouncingPosition and continues rubberEffect's calculation from this point.
90
+ const startTouchBouncingDelta = useMainThreadRef({})
91
+ // when touch starts during bouncing, save current bouncingPosition and continues rubberEffect's calculation from this point.
92
+ const bouncingTouchStartPosition = useMainThreadRef({})
93
+
94
+ // Used to record the previous scroll position and calculate current scroll velocity.
95
+ const prevScroll = useMainThreadRef({})
96
+
97
+ // scroll container's basic info.
98
+ const height = useMainThreadRef(
99
+ options.bounceableOptions.estimatedHeight
100
+ ?? SystemInfo.pixelHeight / SystemInfo.pixelRatio,
101
+ )
102
+ const width = useMainThreadRef(
103
+ options.bounceableOptions.estimatedWidth
104
+ ?? SystemInfo.pixelWidth / SystemInfo.pixelRatio,
105
+ )
106
+ const scrollX = useMainThreadRef(0)
107
+ const scrollY = useMainThreadRef(0)
108
+
109
+ // Flags for ending bouncing animation.
110
+ const touchEndFrameEnableFlag = useMainThreadRef(false)
111
+ const touchingEndBouncingBackEnableFlag = useMainThreadRef(false)
112
+ const flingEndWithBouncingEnableFlag = useMainThreadRef(false)
113
+
114
+ // Flags for reaches upper/lower edge.
115
+ // When content's size is smaller than viewport, these two flags are both true.
116
+ const toUpper = useMainThreadRef(false)
117
+ const toLower = useMainThreadRef(false)
118
+
119
+ // Read from props
120
+ const containerID = options.id ?? 'bounceableContainer'
121
+ const { enableBounces, onScrollToBounces } = options.bounceableOptions
122
+ const alwaysBouncing = options.bounceableOptions.alwaysBouncing ?? false
123
+ const scrollOrientation = options.scrollOrientation ?? 'vertical'
124
+ const enableRTL = useMainThreadRef(options.enableRTL ?? false)
125
+ const enableBounceEventInFling =
126
+ options.bounceableOptions.enableBounceEventInFling ?? true
127
+ const startBounceTriggerDistance =
128
+ options.bounceableOptions.startBounceTriggerDistance ?? 0
129
+ const endBounceTriggerDistance =
130
+ options.bounceableOptions.endBounceTriggerDistance ?? 0
131
+ // Temporary workaround as requestAnimationFrame will crash below Lynx 2.15.2.
132
+ const temporaryValidVersionCheckForRAF = useMainThreadRef(
133
+ options.bounceableOptions.validAnimationVersion ?? false,
134
+ )
135
+ log(
136
+ debugLogEnabled,
137
+ `[lynx-ui-scroll-view][useBounce] init, enableBounces: ${enableBounces}, orientation: ${scrollOrientation}, enableRTL: ${
138
+ options.enableRTL ?? false
139
+ }`,
140
+ )
141
+
142
+ const bouncingStatus = {
143
+ inScrollingRange: 0,
144
+ upperBouncing: 1,
145
+ lowerBouncing: 2,
146
+ noBouncing: 3,
147
+ alwaysBouncing: 4,
148
+ }
149
+
150
+ function isVertical() {
151
+ 'main thread'
152
+ return scrollOrientation === 'vertical'
153
+ }
154
+
155
+ function threshold() {
156
+ 'main thread'
157
+ return 1.0 / Number(SystemInfo.pixelRatio)
158
+ }
159
+
160
+ function normalizedHorizontalValue(value: number) {
161
+ 'main thread'
162
+ return enableRTL.current ? -value : value
163
+ }
164
+
165
+ function isAndroid() {
166
+ 'main thread'
167
+ return SystemInfo.platform === 'Android'
168
+ }
169
+
170
+ function isEmpty(obj: Record<string, unknown>) {
171
+ 'main thread'
172
+ return !obj || Object.keys(obj).length === 0
173
+ }
174
+
175
+ function enableScroll(enable: boolean) {
176
+ 'main thread'
177
+ // Android will trigger scroll during bouncing, cancel it while bouncing.
178
+ if (isAndroid()) {
179
+ selectorMT(containerID)?.setAttribute('enable-scroll', enable)
180
+ }
181
+ }
182
+
183
+ // Clear all temps when a touch procedure ends.
184
+ function clearTouchInfo() {
185
+ 'main thread'
186
+ mtsLog(debugLogEnabled, '[lynx-ui-scroll-view][useBounce] clear touch info')
187
+ startTouch.current = null
188
+ bouncingTouchStartPosition.current = 0
189
+ prevTouch.current = null
190
+ startBouncingTouch.current = null
191
+ startTouchBouncingDelta.current = 0
192
+ }
193
+
194
+ // Temporary workaround as requestAnimationFrame will crash below Lynx 2.15.2.
195
+ function customRequestAnimationFrame(animationFunc: () => void) {
196
+ 'main thread'
197
+ if (temporaryValidVersionCheckForRAF.current) {
198
+ requestAnimationFrame(animationFunc)
199
+ } else {
200
+ setTimeout(animationFunc, 8)
201
+ }
202
+ }
203
+
204
+ // Calculate current touch delta based on 'startPoint'. The startPoint here should be startBouncingTouch which means this bouncing effect happens during a touch procedure.
205
+ function getCurrentDelta(event: MainThread.TouchEvent) {
206
+ 'main thread'
207
+ if (startTouch.current !== null) {
208
+ if (startBouncingTouch.current === null) {
209
+ return scrollOrientation === 'vertical'
210
+ ? event.touches[0].pageY - startTouch.current[0].pageY
211
+ : normalizedHorizontalValue(
212
+ event.touches[0].pageX - startTouch.current[0].pageX,
213
+ )
214
+ } else {
215
+ return scrollOrientation === 'vertical'
216
+ ? event.touches[0].pageY - startBouncingTouch.current[0].pageY
217
+ : normalizedHorizontalValue(
218
+ event.touches[0].pageX - startBouncingTouch.current[0].pageX,
219
+ )
220
+ }
221
+ }
222
+ return 0
223
+ }
224
+
225
+ // Key bouncing status judgement.
226
+ function getBouncingStatus() {
227
+ 'main thread'
228
+ // @ts-expect-error Expected
229
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
230
+ const currentPosition = bouncingPositionInfo.current?.bouncingOffset ?? 0
231
+ if (Boolean(toUpper.current) && Boolean(toLower.current)) {
232
+ return alwaysBouncing
233
+ ? bouncingStatus.alwaysBouncing
234
+ : bouncingStatus.noBouncing
235
+ }
236
+
237
+ // upper bouncing
238
+ const initialLayoutPosition = 0
239
+ mtsLog(
240
+ debugLogEnabled,
241
+ `[lynx-ui-scroll-view][useBounce] get bouncing status, initialLayoutPosition: ${initialLayoutPosition}, currentPosition: ${currentPosition}`,
242
+ )
243
+
244
+ if (currentPosition > initialLayoutPosition) {
245
+ return bouncingStatus.upperBouncing
246
+ }
247
+
248
+ // bottom bouncing
249
+ if (currentPosition < initialLayoutPosition) {
250
+ return bouncingStatus.lowerBouncing
251
+ }
252
+ return bouncingStatus.inScrollingRange
253
+ }
254
+
255
+ // Whether fling and bouncing back step should be triggered.
256
+ function shouldBounceWhenTouchEnd(status: number) {
257
+ 'main thread'
258
+ if (
259
+ status === bouncingStatus.inScrollingRange
260
+ || status === bouncingStatus.noBouncing
261
+ ) {
262
+ return false
263
+ }
264
+
265
+ if (
266
+ status === bouncingStatus.upperBouncing
267
+ || status === bouncingStatus.lowerBouncing
268
+ ) {
269
+ return true
270
+ }
271
+
272
+ if (status === bouncingStatus.alwaysBouncing) {
273
+ return alwaysBouncing
274
+ }
275
+ return false
276
+ }
277
+
278
+ // Use translate to implement real bouncing effect
279
+ function bouncingSetStyle(offset: number) {
280
+ 'main thread'
281
+ if (isNaN(Number(offset))) {
282
+ mtsLog(
283
+ true,
284
+ '[lynx-ui-scroll-view][useBounce] ERROR! bouncingOffset is NaN',
285
+ )
286
+ return
287
+ }
288
+ // update bouncingPositionInfo first
289
+ if (isEmpty(bouncingPositionInfo.current)) {
290
+ // @ts-expect-error expected
291
+ bouncingPositionInfo.current.velocity = 0
292
+ } else {
293
+ // @ts-expect-error expected
294
+ const timeDiff = Date.now() - bouncingPositionInfo.current.timeStamp
295
+ // @ts-expect-error expected
296
+ const offsetDiff = offset - bouncingPositionInfo.current.bouncingOffset
297
+ || 0
298
+ if (timeDiff > 0) {
299
+ // @ts-expect-error expected
300
+ bouncingPositionInfo.current.velocity = offsetDiff / timeDiff
301
+ }
302
+ // If timeDiff <= 0, we keep the previous velocity to maintain momentum continuity.
303
+ }
304
+ // @ts-expect-error expected
305
+ bouncingPositionInfo.current.bouncingOffset = offset
306
+ // @ts-expect-error expected
307
+ bouncingPositionInfo.current.timeStamp = Date.now()
308
+ // When bouncing effect ends, clear startTouch and bouncingTouchStartPosition
309
+ if (offset === 0 && prevTouch.current !== null) {
310
+ startTouch.current = prevTouch.current
311
+ bouncingTouchStartPosition.current = {}
312
+ }
313
+ // trigger translate
314
+ if (isVertical()) {
315
+ mtsLog(
316
+ debugLogEnabled,
317
+ `[lynx-ui-scroll-view][useBounce] apply transform, orientation: vertical, rawOffset: ${offset}, containerTransform: translateY(${offset}px)`,
318
+ )
319
+ selectorMT(containerID)?.setStyleProperty(
320
+ 'transform',
321
+ `translateY(${offset}px)`,
322
+ )
323
+ selectorMT(`${containerID}-upperBounceWrapper`)?.setStyleProperty(
324
+ 'transform',
325
+ `translateY(${offset}px)`,
326
+ )
327
+ selectorMT(`${containerID}-lowerBounceWrapper`)?.setStyleProperty(
328
+ 'transform',
329
+ `translateY(${offset}px)`,
330
+ )
331
+ } else {
332
+ const visualOffset = enableRTL.current ? -offset : offset
333
+ mtsLog(
334
+ debugLogEnabled,
335
+ `[lynx-ui-scroll-view][useBounce] apply transform, orientation: horizontal, rawOffset: ${offset}, enableRTL: ${
336
+ String(enableRTL.current)
337
+ }, visualOffset: ${visualOffset}, containerTransform: translateX(${visualOffset}px)`,
338
+ )
339
+ selectorMT(containerID)?.setStyleProperty(
340
+ 'transform',
341
+ `translateX(${visualOffset}px)`,
342
+ )
343
+ selectorMT(`${containerID}-upperBounceWrapper`)?.setStyleProperty(
344
+ 'transform',
345
+ `translateX(${visualOffset}px)`,
346
+ )
347
+ selectorMT(`${containerID}-lowerBounceWrapper`)?.setStyleProperty(
348
+ 'transform',
349
+ `translateX(${visualOffset}px)`,
350
+ )
351
+ }
352
+ }
353
+
354
+ function onScrollToBouncesJS(info: scrollToBouncesInfo) {
355
+ if (enableBounces && onScrollToBounces) {
356
+ onScrollToBounces(info)
357
+ }
358
+ }
359
+
360
+ // send the scrollToBounces event
361
+ function triggerScrollToBouncesEvent(isUpper: boolean) {
362
+ 'main thread'
363
+ mtsLog(
364
+ debugLogEnabled,
365
+ `[lynx-ui-scroll-view][useBounce] trigger scrollToBounces, direction: ${
366
+ isUpper ? 'upper' : 'lower'
367
+ }`,
368
+ )
369
+
370
+ const info: scrollToBouncesInfo = {
371
+ direction: isUpper ? 'upper' : 'lower',
372
+ }
373
+ runOnBackground(onScrollToBouncesJS)(info)
374
+ }
375
+
376
+ function rubberEffect(isNegative: 1 | -1, delta: number) {
377
+ 'main thread'
378
+ const scrollViewFrameSize = isVertical() ? height.current : width.current
379
+ // 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.
380
+ const touchStartPosition = Math.abs(
381
+ Number(
382
+ isEmpty(startTouchBouncingDelta.current)
383
+ ? bouncingTouchStartPosition.current
384
+ : startTouchBouncingDelta.current,
385
+ ),
386
+ )
387
+ // This deltaYForTouchStartPosition is the inverse function of rubberEffect function
388
+ const deltaYForTouchStartPosition =
389
+ (scrollViewFrameSize * touchStartPosition)
390
+ / ((scrollViewFrameSize - touchStartPosition) * rubberC.current) || 0
391
+ // Here it calculate the next touchDelta. deltaYForNextPosition = (touch point where bouncing happens + corresponding touch delta where previous bouncing position locates)
392
+ // 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.
393
+ const deltaYForNextPosition = bouncingTouchStartPosition.current
394
+ ? deltaYForTouchStartPosition + isNegative * delta
395
+ : isNegative * delta
396
+ // Real calculation. Note that we don't use the raw touchDelta for calculating, instead, we use deltaYForNextPosition.
397
+ const rubberBandingDistance = Math.max(
398
+ 0,
399
+ (1.0
400
+ - 1.0
401
+ / ((deltaYForNextPosition * rubberC.current) / scrollViewFrameSize
402
+ + 1.0))
403
+ * scrollViewFrameSize,
404
+ )
405
+ mtsLog(
406
+ debugLogEnabled,
407
+ `[lynx-ui-scroll-view][useBounce] rubber effect, scrollViewFrameSize: ${scrollViewFrameSize}, touchStartPosition: ${touchStartPosition}, deltaYForTouchStartPosition: ${deltaYForTouchStartPosition}, deltaYForNextPosition: ${deltaYForNextPosition}, rubberBandingDistance: ${rubberBandingDistance}`,
408
+ )
409
+
410
+ bouncingSetStyle(isNegative * rubberBandingDistance)
411
+ }
412
+
413
+ function triggerRubberEffectIfCrossingEdge(event: MainThread.TouchEvent) {
414
+ 'main thread'
415
+ const delta = getCurrentDelta(event)
416
+ mtsLog(
417
+ debugLogEnabled,
418
+ `[lynx-ui-scroll-view][useBounce] check crossing edge, delta: ${delta}, toUpper: ${
419
+ String(toUpper.current)
420
+ }, toLower: ${String(toLower.current)}`,
421
+ )
422
+
423
+ // Crossing top range
424
+ if (
425
+ toUpper.current === true && delta > 0
426
+ && (singleSidedBounce.current === 'both'
427
+ || singleSidedBounce.current === 'upper')
428
+ ) {
429
+ enableScroll(false)
430
+ rubberEffect(delta > 0 ? 1 : -1, delta)
431
+ }
432
+
433
+ // Crossing bottom range
434
+ if (
435
+ toLower.current === true && delta < 0
436
+ && (singleSidedBounce.current === 'both'
437
+ || singleSidedBounce.current === 'lower')
438
+ ) {
439
+ enableScroll(false)
440
+ rubberEffect(delta > 0 ? 1 : -1, delta)
441
+ }
442
+ enableScroll(true)
443
+ }
444
+
445
+ // return true if scrollToBounces should be sent
446
+ function isOverTriggerDistance() {
447
+ 'main thread'
448
+ // @ts-expect-error expected
449
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
450
+ const bouncingTop: number = bouncingPositionInfo.current.bouncingOffset ?? 0
451
+ const triggerDistance =
452
+ // @ts-expect-error expected
453
+ bouncingPositionInfo.current?.bouncingOffset > 0
454
+ ? startBounceTriggerDistance
455
+ : endBounceTriggerDistance
456
+ const delta = Math.abs(bouncingTop) - Math.abs(triggerDistance)
457
+ return delta > threshold()
458
+ }
459
+
460
+ function bouncingBack() {
461
+ 'main thread'
462
+ mtsLog(
463
+ debugLogEnabled,
464
+ '[lynx-ui-scroll-view][useBounce] fling forward end',
465
+ )
466
+ mtsLog(
467
+ debugLogEnabled,
468
+ '[lynx-ui-scroll-view][useBounce] bounce back starts',
469
+ )
470
+
471
+ // step3: bounce back
472
+ // @ts-expect-error expected
473
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
474
+ const C1 = bouncingPositionInfo.current.bouncingOffset ?? 0
475
+ const startTime = Date.now()
476
+ const touchingEndBouncingBackFrame = () => {
477
+ if (Boolean(touchingEndBouncingBackEnableFlag.current) === false) {
478
+ return
479
+ }
480
+ const currentTime = Date.now() - startTime
481
+ mtsLog(
482
+ debugLogEnabled,
483
+ '[lynx-ui-scroll-view][useBounce] touching end bouncing back frame',
484
+ )
485
+
486
+ // critical damping
487
+ const C2 = beta.current * C1
488
+ const easedDistance = (C1 + C2 * (currentTime / 1000))
489
+ * Math.pow(Math.E, -beta.current * (currentTime / 1000))
490
+ bouncingSetStyle(easedDistance)
491
+ if (Math.abs(easedDistance) < threshold()) {
492
+ // Make sure it backs to 0
493
+ bouncingSetStyle(0)
494
+ mtsLog(
495
+ debugLogEnabled,
496
+ '[lynx-ui-scroll-view][useBounce] bounce back ends',
497
+ )
498
+ } else {
499
+ customRequestAnimationFrame(touchingEndBouncingBackFrame)
500
+ }
501
+ }
502
+
503
+ customRequestAnimationFrame(touchingEndBouncingBackFrame)
504
+ touchingEndBouncingBackEnableFlag.current = true
505
+ }
506
+
507
+ // bindtouchstart. Save startTouch and bouncingPosition if a bouncing effect is happening.
508
+ function bounceableTouchStart(event: MainThread.TouchEvent) {
509
+ 'main thread'
510
+ startTouch.current = event.touches
511
+ mtsLog(debugLogEnabled, '[lynx-ui-scroll-view][useBounce] touch start')
512
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
513
+ bouncingTouchStartPosition.current =
514
+ // @ts-expect-error expected
515
+ bouncingPositionInfo.current?.bouncingOffset ?? 0
516
+ // reset all animation flags. No animation should play during a touch.
517
+ touchEndFrameEnableFlag.current = false
518
+ touchingEndBouncingBackEnableFlag.current = false
519
+ flingEndWithBouncingEnableFlag.current = false
520
+ }
521
+
522
+ function bounceableTouchMove(event: MainThread.TouchEvent) {
523
+ 'main thread'
524
+ prevTouch.current = event.touches
525
+ if (startTouch.current === null) {
526
+ // It means current situation is illegal. A touchMove event happens without a touchStart event beforehand. Or a touchMove event happens after a touchEnd event.
527
+ mtsLog(true, '[lynx-ui-scroll-view][useBounce] ERROR! touch not started')
528
+ } else {
529
+ const delta = getCurrentDelta(event)
530
+ const currentBouncingStatus = getBouncingStatus()
531
+ // Judge the status and trigger rubberEffect. The TouchMove should only consider rubberEffect and nothing else.
532
+ switch (currentBouncingStatus) {
533
+ case bouncingStatus.upperBouncing: {
534
+ enableScroll(false)
535
+ rubberEffect(1, delta)
536
+ mtsLog(
537
+ debugLogEnabled,
538
+ '[lynx-ui-scroll-view][useBounce] touch move upper bouncing',
539
+ )
540
+ break
541
+ }
542
+ case bouncingStatus.lowerBouncing: {
543
+ enableScroll(false)
544
+ rubberEffect(-1, delta)
545
+ mtsLog(
546
+ debugLogEnabled,
547
+ '[lynx-ui-scroll-view][useBounce] touch move lower bouncing',
548
+ )
549
+ break
550
+ }
551
+ case bouncingStatus.alwaysBouncing: {
552
+ mtsLog(
553
+ debugLogEnabled,
554
+ '[lynx-ui-scroll-view][useBounce] touch move always bouncing',
555
+ )
556
+ if (alwaysBouncing) {
557
+ triggerRubberEffectIfCrossingEdge(event)
558
+ }
559
+ break
560
+ }
561
+ case bouncingStatus.inScrollingRange: {
562
+ mtsLog(
563
+ debugLogEnabled,
564
+ '[lynx-ui-scroll-view][useBounce] touch move in scrolling range',
565
+ )
566
+ triggerRubberEffectIfCrossingEdge(event)
567
+ break
568
+ }
569
+ default:
570
+ break
571
+ }
572
+ }
573
+ }
574
+
575
+ // bindtouchend. In touchEnd event the fling forward animation and bouncingBack animation should be triggered if necessary.
576
+ function bounceableTouchEnd() {
577
+ 'main thread'
578
+ // Reset the state. The touch information should be reset, and we should no longer ban the enable-scroll.
579
+ clearTouchInfo()
580
+ enableScroll(true)
581
+ mtsLog(debugLogEnabled, '[lynx-ui-scroll-view][useBounce] touch end')
582
+ if (shouldBounceWhenTouchEnd(getBouncingStatus())) {
583
+ const startTime = Date.now()
584
+ // @ts-expect-error expected
585
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
586
+ const dragEndVelocity = bouncingPositionInfo.current?.velocity
587
+ // @ts-expect-error expected
588
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
589
+ const dragEndPosition = bouncingPositionInfo.current?.bouncingOffset ?? 0
590
+ // Send scrolltobounces event.
591
+ if (isOverTriggerDistance()) {
592
+ triggerScrollToBouncesEvent(
593
+ // @ts-expect-error expected
594
+ bouncingPositionInfo.current?.bouncingOffset > 0,
595
+ )
596
+ }
597
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
598
+ let currentVelocity: number = dragEndVelocity
599
+ const touchEndProcessFrame = () => {
600
+ if (Boolean(touchEndFrameEnableFlag.current) === false) {
601
+ return
602
+ }
603
+ mtsLog(
604
+ debugLogEnabled,
605
+ '[lynx-ui-scroll-view][useBounce] touch end process frame',
606
+ )
607
+ if (Math.abs(currentVelocity) <= threshold()) {
608
+ // If the velocity is already under threshold, skip fling and start step3: bounce back.
609
+ bouncingBack()
610
+ } else {
611
+ // If the drag end with a velocity, start fling to consume it.
612
+ // step 2: fling down
613
+ mtsLog(
614
+ debugLogEnabled,
615
+ '[lynx-ui-scroll-view][useBounce] fling down start',
616
+ )
617
+ // This function is obtained by integrating the velocity function with a deceleration rate of flingDeceleratingRate.
618
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
619
+ const distance: number = dragEndPosition
620
+ + (dragEndVelocity
621
+ * (Math.pow(
622
+ flingDeceleratingRate.current,
623
+ Date.now() - startTime,
624
+ )
625
+ - 1))
626
+ / Math.log(flingDeceleratingRate.current)
627
+ bouncingSetStyle(distance)
628
+ currentVelocity = dragEndVelocity
629
+ * Math.pow(flingDeceleratingRate.current, Date.now() - startTime)
630
+ if (touchEndFrameEnableFlag.current) {
631
+ customRequestAnimationFrame(touchEndProcessFrame)
632
+ }
633
+ }
634
+ }
635
+ customRequestAnimationFrame(touchEndProcessFrame)
636
+ touchEndFrameEnableFlag.current = true
637
+ }
638
+ }
639
+
640
+ // Save the bindscroll info and calculate velocity.
641
+ function bounceableHandleScroll(event: ScrollEvent) {
642
+ 'main thread'
643
+ scrollX.current = event.detail.scrollLeft
644
+ scrollY.current = event.detail.scrollTop
645
+ if (!isEmpty(prevScroll.current)) {
646
+ const prev = prevScroll.current as {
647
+ timestamp: number
648
+ detail: { scrollTop: number, scrollLeft: number }
649
+ }
650
+ const timeDuration = Date.now() - prev.timestamp
651
+ if (timeDuration > 0) {
652
+ const deltaY = isVertical()
653
+ ? event.detail.scrollTop - prev.detail.scrollTop
654
+ : normalizedHorizontalValue(
655
+ event.detail.scrollLeft - prev.detail.scrollLeft,
656
+ )
657
+ const velocity = deltaY / timeDuration
658
+ if (Number.isFinite(velocity)) {
659
+ scrollVelocity.current = velocity
660
+ }
661
+ }
662
+ }
663
+ mtsLog(
664
+ debugLogEnabled,
665
+ `[lynx-ui-scroll-view][useBounce] handle scroll near edge, scrollLeft: ${event.detail.scrollLeft}, scrollTop: ${event.detail.scrollTop}, velocity: ${scrollVelocity.current}`,
666
+ )
667
+ prevScroll.current = event
668
+ }
669
+
670
+ function onUpperDisexposure(_event: CommonEvent) {
671
+ 'main thread'
672
+ mtsLog(
673
+ debugLogEnabled,
674
+ '[lynx-ui-scroll-view][useBounce] upper disexposure',
675
+ )
676
+ toUpper.current = false
677
+ }
678
+
679
+ // Handle scrolltoupper event.
680
+ function onUpperExposure(_event: CommonEvent) {
681
+ 'main thread'
682
+ mtsLog(debugLogEnabled, '[lynx-ui-scroll-view][useBounce] upper exposure')
683
+ toUpper.current = true
684
+ if (
685
+ singleSidedBounce.current !== 'upper'
686
+ && singleSidedBounce.current !== 'both'
687
+ ) {
688
+ return
689
+ }
690
+ if (prevScroll.current) {
691
+ // reaches edge during touch
692
+ startBouncingTouch.current = prevTouch.current
693
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
694
+ startTouchBouncingDelta.current =
695
+ // @ts-expect-error expected
696
+ bouncingPositionInfo.current?.bouncingOffset ?? 0
697
+ } else if (Math.abs(scrollVelocity.current) > threshold()) {
698
+ // reaches edge during fling
699
+ const velocity = scrollVelocity.current
700
+ let currentVelocity = velocity
701
+ const startTime = Date.now()
702
+ mtsLog(
703
+ debugLogEnabled,
704
+ `[lynx-ui-scroll-view][useBounce] fling to upper event start, velocity: ${velocity}`,
705
+ )
706
+ let sentScrollToBouncesEvent = false // only sent scrollToBounces once
707
+ const flingEndWithBouncingFrame = () => {
708
+ if (Boolean(flingEndWithBouncingEnableFlag.current) === false) {
709
+ mtsLog(
710
+ debugLogEnabled,
711
+ '[lynx-ui-scroll-view][useBounce] flingEndWithBouncingEnableFlag early return',
712
+ )
713
+ return
714
+ }
715
+ if (Math.abs(currentVelocity) <= threshold()) {
716
+ flingEndWithBouncingEnableFlag.current = false
717
+ mtsLog(
718
+ debugLogEnabled,
719
+ '[lynx-ui-scroll-view][useBounce] fling to upper event end',
720
+ )
721
+ mtsLog(
722
+ debugLogEnabled,
723
+ '[lynx-ui-scroll-view][useBounce] bouncing to upper event start',
724
+ )
725
+ bouncingBack()
726
+ } else {
727
+ // step 1: fling
728
+ const distance = (currentVelocity
729
+ * (Math.pow(flingDeceleratingRate.current, Date.now() - startTime)
730
+ - 1))
731
+ / Math.log(flingDeceleratingRate.current)
732
+ bouncingSetStyle(-distance)
733
+ if (!sentScrollToBouncesEvent && isOverTriggerDistance()) {
734
+ triggerScrollToBouncesEvent(
735
+ // @ts-expect-error expected
736
+ bouncingPositionInfo.current?.bouncingOffset > 0,
737
+ )
738
+ sentScrollToBouncesEvent = true
739
+ }
740
+ currentVelocity = velocity
741
+ * Math.pow(flingDeceleratingRate.current, Date.now() - startTime)
742
+ if (flingEndWithBouncingEnableFlag.current) {
743
+ customRequestAnimationFrame(flingEndWithBouncingFrame)
744
+ }
745
+ }
746
+ }
747
+ customRequestAnimationFrame(flingEndWithBouncingFrame)
748
+ flingEndWithBouncingEnableFlag.current = true
749
+ }
750
+ }
751
+
752
+ function onLowerDisexposure(_event: CommonEvent) {
753
+ 'main thread'
754
+ mtsLog(
755
+ debugLogEnabled,
756
+ '[lynx-ui-scroll-view][useBounce] lower disexposure',
757
+ )
758
+ toLower.current = false
759
+ }
760
+
761
+ function onLowerExposure(_event: CommonEvent) {
762
+ 'main thread'
763
+ mtsLog(debugLogEnabled, '[lynx-ui-scroll-view][useBounce] lower exposure')
764
+ toLower.current = true
765
+ if (
766
+ singleSidedBounce.current !== 'lower'
767
+ && singleSidedBounce.current !== 'both'
768
+ ) {
769
+ return
770
+ }
771
+ // reaches lower during dragging
772
+ if (prevTouch.current !== null) {
773
+ startBouncingTouch.current = prevTouch.current
774
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
775
+ startTouchBouncingDelta.current =
776
+ // @ts-expect-error expected
777
+ bouncingPositionInfo.current?.bouncingOffset ?? 0
778
+ } else if (enableBounceEventInFling && scrollVelocity.current > 0) {
779
+ const velocity = scrollVelocity.current
780
+ mtsLog(
781
+ debugLogEnabled,
782
+ `[lynx-ui-scroll-view][useBounce] lower velocity: ${velocity}`,
783
+ )
784
+
785
+ // scroll to end with velocity, start bouncing effect
786
+ if (Math.abs(velocity) > threshold()) {
787
+ let currentVelocity = velocity
788
+ const startTime = Date.now()
789
+ mtsLog(
790
+ debugLogEnabled,
791
+ `[lynx-ui-scroll-view][useBounce] fling to lower event start, velocity: ${velocity}`,
792
+ )
793
+ let sentScrollToBouncesEvent = false // only sent scrollToBounces once
794
+ const flingEndWithBouncingFrame = () => {
795
+ if (Boolean(flingEndWithBouncingEnableFlag.current) === false) {
796
+ mtsLog(
797
+ debugLogEnabled,
798
+ '[lynx-ui-scroll-view][useBounce] flingEndWithBouncingEnableFlag early return',
799
+ )
800
+ return
801
+ }
802
+ if (Math.abs(currentVelocity) <= threshold()) {
803
+ flingEndWithBouncingEnableFlag.current = false
804
+ mtsLog(
805
+ debugLogEnabled,
806
+ '[lynx-ui-scroll-view][useBounce] fling to lower event end',
807
+ )
808
+ mtsLog(
809
+ debugLogEnabled,
810
+ '[lynx-ui-scroll-view][useBounce] bouncing to lower event start',
811
+ )
812
+ bouncingBack()
813
+ } else {
814
+ // step 1: fling
815
+ const distance = (currentVelocity
816
+ * (Math.pow(
817
+ flingDeceleratingRate.current,
818
+ Date.now() - startTime,
819
+ )
820
+ - 1))
821
+ / Math.log(flingDeceleratingRate.current)
822
+ bouncingSetStyle(-distance)
823
+ if (!sentScrollToBouncesEvent && isOverTriggerDistance()) {
824
+ triggerScrollToBouncesEvent(
825
+ // @ts-expect-error expected
826
+ bouncingPositionInfo.current?.bouncingOffset > 0,
827
+ )
828
+ sentScrollToBouncesEvent = true
829
+ }
830
+ currentVelocity = velocity
831
+ * Math.pow(flingDeceleratingRate.current, Date.now() - startTime)
832
+ if (flingEndWithBouncingEnableFlag) {
833
+ customRequestAnimationFrame(flingEndWithBouncingFrame)
834
+ }
835
+ }
836
+ }
837
+ customRequestAnimationFrame(flingEndWithBouncingFrame)
838
+ flingEndWithBouncingEnableFlag.current = true
839
+ }
840
+ }
841
+ }
842
+
843
+ // Used to get the size of scroll container.
844
+ function bounceableLayoutChange(event: CommonEvent) {
845
+ 'main thread'
846
+ // @ts-expect-error expected
847
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
848
+ height.current = (isAndroid() ? event.params?.height : event.detail?.height)
849
+ ?? 0
850
+ // @ts-expect-error expected
851
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
852
+ width.current = (isAndroid() ? event.params?.width : event.detail?.width)
853
+ ?? 0
854
+ }
855
+
856
+ return {
857
+ 'main-thread:bindtouchstart': bounceableTouchStart,
858
+ 'main-thread:bindtouchend': bounceableTouchEnd,
859
+ 'main-thread:bindtouchmove': bounceableTouchMove,
860
+ 'main-thread:bindlayoutchange': bounceableLayoutChange,
861
+ 'main-thread:bindscroll': bounceableHandleScroll,
862
+ onUpperExposure,
863
+ onUpperDisexposure,
864
+ onLowerExposure,
865
+ onLowerDisexposure,
866
+ }
867
+ }