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