@lynx-js/lynx-ui-sortable 3.133.0 → 3.134.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/Sortable.tsx CHANGED
@@ -9,19 +9,19 @@ import {
9
9
  useEffect,
10
10
  useMainThreadRef,
11
11
  useMemo,
12
- useRef,
13
12
  useState,
14
13
  } from '@lynx-js/react'
15
14
  import type { RefObject } from '@lynx-js/react'
16
15
 
17
16
  import type { Point } from '@lynx-js/lynx-ui-common'
17
+ import { usePreCommit } from '@lynx-js/lynx-ui-common'
18
18
  import {
19
19
  Draggable,
20
20
  DraggableArea,
21
21
  DraggableRoot,
22
22
  } from '@lynx-js/lynx-ui-draggable'
23
23
  import type { DraggableRef } from '@lynx-js/lynx-ui-draggable'
24
- import type { MainThread, NodesRef } from '@lynx-js/types'
24
+ import type { MainThread, ScrollEvent } from '@lynx-js/types'
25
25
 
26
26
  import { SortableContext } from './SortableContext'
27
27
  import type {
@@ -33,16 +33,103 @@ import { useSortable } from './useSortable'
33
33
 
34
34
  export { DraggableArea as SortableItemArea }
35
35
 
36
+ type RectTarget = 'item' | 'boundary' | 'scrollableBoundary'
37
+ interface ScrollByResult {
38
+ scrollTop?: number
39
+ detail?: { scrollTop?: number }
40
+ }
41
+ interface ScrollTranslateDelta {
42
+ dragDeltaY: number
43
+ measuredRectDeltaY: number
44
+ }
45
+ interface VerticalBounds {
46
+ top: number
47
+ bottom: number
48
+ }
49
+ interface EdgeDistance {
50
+ distanceToTop: number
51
+ distanceToBottom: number
52
+ }
53
+
54
+ function getEdgeDistance(
55
+ itemBounds: VerticalBounds,
56
+ boundaryRect: VerticalBounds,
57
+ ): EdgeDistance {
58
+ 'main thread'
59
+ return {
60
+ distanceToTop: itemBounds.top - boundaryRect.top,
61
+ distanceToBottom: boundaryRect.bottom - itemBounds.bottom,
62
+ }
63
+ }
64
+
65
+ function getAutoScrollTriggerOverflow(
66
+ edgeDistance: EdgeDistance,
67
+ upperTriggerZone: number,
68
+ lowerTriggerZone: number,
69
+ ) {
70
+ 'main thread'
71
+ if (edgeDistance.distanceToTop < upperTriggerZone) {
72
+ return edgeDistance.distanceToTop - upperTriggerZone
73
+ }
74
+ if (edgeDistance.distanceToBottom < lowerTriggerZone) {
75
+ return lowerTriggerZone - edgeDistance.distanceToBottom
76
+ }
77
+ return 0
78
+ }
79
+
80
+ const AUTO_SCROLL_MAX_STEP = 18
81
+ const AUTO_SCROLL_VELOCITY_FACTOR = 0.35
82
+
83
+ function getNormalizedElementKey(sortingKey: string) {
84
+ return String(sortingKey).replace(/[^\w-]/g, '-')
85
+ }
86
+
87
+ function getSortableItemElementId(sortingKey: string) {
88
+ return `sortable-item-${getNormalizedElementKey(sortingKey)}`
89
+ }
90
+
91
+ function getSortableDragOverlayElementId(sortingKey: string) {
92
+ return `sortable-drag-overlay-${getNormalizedElementKey(sortingKey)}`
93
+ }
94
+
36
95
  export function SortableRoot<T>(props: SortableRootProps<T>) {
37
96
  const {
38
97
  children,
39
98
  data,
40
99
  debugLog = false,
41
100
  boundaryId,
101
+ scrollableBoundaryId,
102
+ as,
103
+ scrollableClassName,
104
+ scrollableContentClassName,
105
+ scrollableEnableScroll = true,
106
+ scrollableStickyUpperOffset = 0,
107
+ scrollableStickyLowerOffset = 0,
42
108
  onSortEnd,
43
109
  onSortStart,
44
110
  enableSorting = true,
45
111
  } = props
112
+ const scrollable = as === 'ScrollView'
113
+ const [isDragging, setIsDragging] = useState(false)
114
+ const handleInternalSortStart = useCallback(() => {
115
+ setIsDragging(true)
116
+ onSortStart?.()
117
+ }, [onSortStart])
118
+ const handleInternalSortEnd = useCallback(
119
+ (sortedData: SortableData<T>[]) => {
120
+ setIsDragging(false)
121
+ onSortEnd(sortedData)
122
+ },
123
+ [onSortEnd],
124
+ )
125
+ const scrollableElementId = useMemo(
126
+ () => scrollableBoundaryId ?? 'sortable-scrollable-boundary',
127
+ [scrollableBoundaryId],
128
+ )
129
+ const scrollableContentId = useMemo(
130
+ () => boundaryId ?? 'sortable-scrollable-content',
131
+ [boundaryId],
132
+ )
46
133
  const sizeMap = useMainThreadRef<Record<string, number>>({})
47
134
  const childrenRefMap = useMainThreadRef<
48
135
  Record<string, DraggableRef | null>
@@ -54,11 +141,45 @@ export function SortableRoot<T>(props: SortableRootProps<T>) {
54
141
  >(
55
142
  {},
56
143
  )
144
+ const dragOverlayRefMap = useMainThreadRef<
145
+ Record<string, MainThread.Element | null>
146
+ >(
147
+ {},
148
+ )
149
+ const dirtyKeysRef = useMainThreadRef<Record<string, boolean>>({})
150
+ const scrollableBoundaryUpperEdgeRef = useMainThreadRef(false)
151
+ const scrollableBoundaryLowerEdgeRef = useMainThreadRef(false)
152
+ const scrollableScrollTopRef = useMainThreadRef(0)
57
153
  const updateItemSize = useCallback((sortingKey: string, size: number) => {
58
154
  'main thread'
59
155
  sizeMap.current[sortingKey] = size
60
156
  }, [])
61
157
 
158
+ const handleScrollableBoundaryScroll = useCallback((event: ScrollEvent) => {
159
+ 'main thread'
160
+ scrollableScrollTopRef.current = event.detail.scrollTop
161
+ }, [scrollableScrollTopRef])
162
+
163
+ const handleScrollableBoundaryUpperExposure = useCallback(() => {
164
+ 'main thread'
165
+ scrollableBoundaryUpperEdgeRef.current = true
166
+ }, [scrollableBoundaryUpperEdgeRef])
167
+
168
+ const handleScrollableBoundaryUpperDisexposure = useCallback(() => {
169
+ 'main thread'
170
+ scrollableBoundaryUpperEdgeRef.current = false
171
+ }, [scrollableBoundaryUpperEdgeRef])
172
+
173
+ const handleScrollableBoundaryLowerExposure = useCallback(() => {
174
+ 'main thread'
175
+ scrollableBoundaryLowerEdgeRef.current = true
176
+ }, [scrollableBoundaryLowerEdgeRef])
177
+
178
+ const handleScrollableBoundaryLowerDisexposure = useCallback(() => {
179
+ 'main thread'
180
+ scrollableBoundaryLowerEdgeRef.current = false
181
+ }, [scrollableBoundaryLowerEdgeRef])
182
+
62
183
  const setChildrenRef = useCallback(
63
184
  (refI: RefObject<DraggableRef>, key: string) => {
64
185
  'main thread'
@@ -75,42 +196,140 @@ export function SortableRoot<T>(props: SortableRootProps<T>) {
75
196
  childrenMTSRefMap.current[key] = refI.current
76
197
  }, [])
77
198
 
199
+ const setDragOverlayRef = useCallback((
200
+ refI: RefObject<MainThread.Element | null>,
201
+ key: string,
202
+ ) => {
203
+ 'main thread'
204
+ dragOverlayRefMap.current[key] = refI.current
205
+ }, [dragOverlayRefMap])
206
+
78
207
  const { handleDragEnd, handleDragMove, handleDragStart } = useSortable({
79
- data: data as SortableData<unknown>[],
208
+ data: data,
80
209
  sizeMap: sizeMap,
81
210
  itemRefMap: childrenRefMap,
82
211
  itemMTSRefMap: childrenMTSRefMap,
83
- onDragEnd: onSortEnd as (sortedData: SortableData<unknown>[]) => void,
84
- onDragStart: onSortStart,
212
+ dirtyKeysRef,
213
+ onDragEnd: handleInternalSortEnd,
214
+ onDragStart: handleInternalSortStart,
85
215
  debugLog,
86
216
  })
87
217
  const sortableContextValue = useMemo(() => ({
88
218
  data,
219
+ isDragOverlay: false,
220
+ debugLog,
89
221
  enableSorting,
90
- boundaryId,
222
+ boundaryId: scrollable ? scrollableContentId : boundaryId,
223
+ scrollableBoundaryId: scrollable
224
+ ? scrollableElementId
225
+ : scrollableBoundaryId,
226
+ scrollableBoundaryUpperEdgeRef: scrollable
227
+ ? scrollableBoundaryUpperEdgeRef
228
+ : undefined,
229
+ scrollableBoundaryLowerEdgeRef: scrollable
230
+ ? scrollableBoundaryLowerEdgeRef
231
+ : undefined,
232
+ scrollableScrollTopRef: scrollable
233
+ ? scrollableScrollTopRef
234
+ : undefined,
235
+ dragOverlayRefMap: scrollable ? dragOverlayRefMap : undefined,
236
+ dirtyKeysRef,
237
+ scrollableStickyUpperOffset,
238
+ scrollableStickyLowerOffset,
91
239
  updateItemSize,
92
240
  setChildrenRef,
93
241
  setChildrenMTSRef,
242
+ setDragOverlayRef,
94
243
  handleDragEnd,
95
244
  handleDragMove,
96
245
  handleDragStart,
97
246
  }), [
98
247
  data,
248
+ debugLog,
99
249
  enableSorting,
100
250
  boundaryId,
251
+ scrollable,
252
+ scrollableContentId,
253
+ scrollableElementId,
254
+ scrollableBoundaryId,
255
+ scrollableBoundaryLowerEdgeRef,
256
+ scrollableBoundaryUpperEdgeRef,
257
+ scrollableScrollTopRef,
258
+ dragOverlayRefMap,
259
+ dirtyKeysRef,
260
+ scrollableStickyLowerOffset,
261
+ scrollableStickyUpperOffset,
101
262
  updateItemSize,
102
263
  setChildrenRef,
103
264
  setChildrenMTSRef,
265
+ setDragOverlayRef,
104
266
  handleDragEnd,
105
267
  handleDragMove,
106
268
  handleDragStart,
107
269
  ])
108
270
 
271
+ const sortableDragOverlayContextValue = useMemo(() => ({
272
+ ...sortableContextValue,
273
+ isDragOverlay: true,
274
+ }), [sortableContextValue])
275
+
109
276
  const renderedChildren = useMemo(
110
277
  () => data?.map(item => children(item)),
111
278
  [data, children],
112
279
  )
113
280
 
281
+ const renderedDragOverlayChildren = useMemo(
282
+ () => data?.map(item => children(item)),
283
+ [data, children],
284
+ )
285
+
286
+ if (scrollable) {
287
+ return (
288
+ <>
289
+ <scroll-view
290
+ id={scrollableElementId}
291
+ className={scrollableClassName}
292
+ enable-scroll={scrollableEnableScroll && !isDragging}
293
+ scroll-orientation='vertical'
294
+ main-thread:bindscroll={handleScrollableBoundaryScroll}
295
+ >
296
+ <view
297
+ id={scrollableContentId}
298
+ className={scrollableContentClassName}
299
+ style={{ zIndex: '0' }}
300
+ >
301
+ <view
302
+ style='display: flex; flex-direction: column; overflow:hidden; height: 1ppx; width: 100%;'
303
+ exposure-scene={scrollableElementId}
304
+ exposure-id='upperExposureView'
305
+ id={`${scrollableElementId}-upperExposureView`}
306
+ main-thread:binduiappear={handleScrollableBoundaryUpperExposure}
307
+ main-thread:binduidisappear={handleScrollableBoundaryUpperDisexposure}
308
+ />
309
+ <SortableContext.Provider
310
+ value={sortableContextValue}
311
+ >
312
+ {renderedChildren}
313
+ </SortableContext.Provider>
314
+ <view
315
+ style='display: flex; flex-direction: column; overflow:hidden; height: 1ppx; width: 100%;'
316
+ exposure-scene={scrollableElementId}
317
+ exposure-id='lowerExposureView'
318
+ id={`${scrollableElementId}-lowerExposureView`}
319
+ main-thread:binduiappear={handleScrollableBoundaryLowerExposure}
320
+ main-thread:binduidisappear={handleScrollableBoundaryLowerDisexposure}
321
+ />
322
+ </view>
323
+ </scroll-view>
324
+ <SortableContext.Provider
325
+ value={sortableDragOverlayContextValue}
326
+ >
327
+ {renderedDragOverlayChildren}
328
+ </SortableContext.Provider>
329
+ </>
330
+ )
331
+ }
332
+
114
333
  return (
115
334
  <SortableContext.Provider
116
335
  value={sortableContextValue}
@@ -130,11 +349,65 @@ interface boundingClientRectRes {
130
349
  }
131
350
 
132
351
  export function SortableItem(props: SortableItemProps) {
352
+ const { isDragOverlay } = useContext(SortableContext)
353
+ if (isDragOverlay) {
354
+ return <SortableDragOverlayItem {...props} />
355
+ }
356
+
357
+ return <SortableInteractiveItem {...props} />
358
+ }
359
+
360
+ function SortableDragOverlayItem(props: SortableItemProps) {
361
+ const { className, children, sortingKey } = props
362
+ const { setDragOverlayRef } = useContext(SortableContext)
363
+ const overlayRef = useMainThreadRef<MainThread.Element | null>(null)
364
+ const overlayElementId = useMemo(
365
+ () => getSortableDragOverlayElementId(sortingKey),
366
+ [sortingKey],
367
+ )
368
+ const overlayStyle = useMemo(() => ({
369
+ position: 'fixed',
370
+ top: '0px',
371
+ left: '0px',
372
+ width: '0px',
373
+ height: '0px',
374
+ opacity: 0,
375
+ visibility: 'hidden',
376
+ zIndex: '10000',
377
+ transform: 'translate(0px, 0px)',
378
+ } as const), [])
379
+
380
+ useEffect(() => {
381
+ runOnMainThread(setDragOverlayRef)(overlayRef, sortingKey)
382
+ }, [overlayRef, setDragOverlayRef, sortingKey])
383
+
384
+ return (
385
+ <view
386
+ id={overlayElementId}
387
+ className={className}
388
+ main-thread:ref={overlayRef}
389
+ style={overlayStyle}
390
+ user-interaction-enabled={false}
391
+ >
392
+ {children}
393
+ </view>
394
+ )
395
+ }
396
+
397
+ function SortableInteractiveItem(props: SortableItemProps) {
133
398
  const { className, children, sortingKey, as = 'Draggable' } = props
134
399
  const {
135
400
  data,
136
401
  enableSorting,
137
402
  boundaryId,
403
+ scrollableBoundaryId,
404
+ scrollableBoundaryUpperEdgeRef,
405
+ scrollableBoundaryLowerEdgeRef,
406
+ scrollableScrollTopRef,
407
+ dragOverlayRefMap,
408
+ dirtyKeysRef,
409
+ scrollableStickyUpperOffset,
410
+ scrollableStickyLowerOffset,
138
411
  updateItemSize,
139
412
  setChildrenRef,
140
413
  setChildrenMTSRef,
@@ -144,7 +417,6 @@ export function SortableItem(props: SortableItemProps) {
144
417
  } = useContext(SortableContext)
145
418
 
146
419
  const MTSRef = useMainThreadRef<DraggableRef>(null)
147
- const ref = useRef<NodesRef>(null)
148
420
  const [itemRect, setItemRect] = useState<boundingClientRectRes>({
149
421
  height: 0,
150
422
  width: 0,
@@ -161,40 +433,542 @@ export function SortableItem(props: SortableItemProps) {
161
433
  bottom: 0,
162
434
  right: 0,
163
435
  })
436
+ const [scrollableBoundaryRect, setScrollableBoundaryRect] = useState<
437
+ boundingClientRectRes
438
+ >({
439
+ height: 0,
440
+ width: 0,
441
+ top: 0,
442
+ left: 0,
443
+ bottom: 0,
444
+ right: 0,
445
+ })
446
+ const autoScrollingRef = useMainThreadRef(false)
447
+ const lastAutoScrollTranslateY = useMainThreadRef(0)
448
+ const autoScrollDistanceSum = useMainThreadRef(0)
449
+ const autoScrollCompensationY = useMainThreadRef(0)
450
+ const autoScrollStartScrollTop = useMainThreadRef(0)
451
+ const itemMeasuredScrollTop = useMainThreadRef(0)
452
+ const dragStartScrollDeltaFromMeasuredRect = useMainThreadRef(0)
453
+ const autoScrollOverflow = useMainThreadRef(0)
454
+ const autoScrollDirection = useMainThreadRef(0)
455
+ const autoScrollStickyDirection = useMainThreadRef(0)
456
+ const dragSourceHidden = useMainThreadRef(false)
457
+ const latestDragTranslate = useMainThreadRef<Point>({ x: 0, y: 0 })
458
+ const latestDragEvent = useMainThreadRef<
459
+ MainThread.MouseEvent | MainThread.TouchEvent | null
460
+ >(null)
461
+ const autoScrollFrameRef = useMainThreadRef<(() => void) | null>(null)
462
+ const syncScrollDeltaForItemTranslateY = useCallback((
463
+ scrollByResult?: ScrollByResult,
464
+ fallbackScrollByOffset = 0,
465
+ ): ScrollTranslateDelta => {
466
+ 'main thread'
467
+ if (scrollableScrollTopRef) {
468
+ const previousScrollTop = scrollableScrollTopRef.current
469
+ const scrollTop = scrollByResult?.scrollTop
470
+ ?? scrollByResult?.detail?.scrollTop
471
+ if (typeof scrollTop === 'number') {
472
+ scrollableScrollTopRef.current = scrollTop
473
+ } else if (scrollByResult || fallbackScrollByOffset !== 0) {
474
+ scrollableScrollTopRef.current += fallbackScrollByOffset
475
+ }
476
+
477
+ if (scrollByResult || fallbackScrollByOffset !== 0) {
478
+ autoScrollDistanceSum.current += scrollableScrollTopRef.current
479
+ - previousScrollTop
480
+ }
481
+ autoScrollCompensationY.current = scrollableScrollTopRef.current
482
+ - autoScrollStartScrollTop.current
483
+ return {
484
+ dragDeltaY: autoScrollCompensationY.current,
485
+ measuredRectDeltaY: scrollableScrollTopRef.current
486
+ - itemMeasuredScrollTop.current,
487
+ }
488
+ }
489
+
490
+ if (fallbackScrollByOffset !== 0) {
491
+ autoScrollDistanceSum.current += fallbackScrollByOffset
492
+ autoScrollCompensationY.current += fallbackScrollByOffset
493
+ }
494
+ return {
495
+ dragDeltaY: autoScrollCompensationY.current,
496
+ measuredRectDeltaY: dragStartScrollDeltaFromMeasuredRect.current
497
+ + autoScrollDistanceSum.current,
498
+ }
499
+ }, [
500
+ autoScrollDistanceSum,
501
+ autoScrollCompensationY,
502
+ autoScrollStartScrollTop,
503
+ dragStartScrollDeltaFromMeasuredRect,
504
+ itemMeasuredScrollTop,
505
+ scrollableScrollTopRef,
506
+ ])
507
+
508
+ const itemElementId = useMemo(
509
+ () => getSortableItemElementId(sortingKey),
510
+ [sortingKey],
511
+ )
512
+ const setAutoScrolling = useCallback((isAutoScrolling: boolean) => {
513
+ 'main thread'
514
+ autoScrollingRef.current = isAutoScrolling
515
+ }, [autoScrollingRef])
516
+ const captureItemMeasuredScrollTop = useCallback(() => {
517
+ 'main thread'
518
+ itemMeasuredScrollTop.current = scrollableScrollTopRef?.current ?? 0
519
+ }, [itemMeasuredScrollTop, scrollableScrollTopRef])
520
+
521
+ const measureRectById = useCallback((
522
+ id: string | undefined,
523
+ target: RectTarget,
524
+ ) => {
525
+ if (!id) {
526
+ return
527
+ }
528
+
529
+ lynx.createSelectorQuery().select(`#${id}`)?.invoke({
530
+ method: 'boundingClientRect',
531
+ params: {},
532
+ success: (res: unknown) => {
533
+ const rect = res as boundingClientRectRes
534
+ if (target === 'item') {
535
+ setItemRect(rect)
536
+ runOnMainThread(captureItemMeasuredScrollTop)()
537
+ return
538
+ }
539
+ if (target === 'boundary') {
540
+ setBoundaryRect(rect)
541
+ return
542
+ }
543
+
544
+ setScrollableBoundaryRect(rect)
545
+ },
546
+ }).exec()
547
+ }, [captureItemMeasuredScrollTop])
548
+
549
+ const refreshDraggingRects = useCallback(() => {
550
+ measureRectById(itemElementId, 'item')
551
+ measureRectById(boundaryId, 'boundary')
552
+ measureRectById(scrollableBoundaryId, 'scrollableBoundary')
553
+ }, [
554
+ boundaryId,
555
+ itemElementId,
556
+ measureRectById,
557
+ scrollableBoundaryId,
558
+ ])
559
+
560
+ const scrollScrollableBoundaryBy = useCallback((
561
+ offset: number,
562
+ onScrolled?: () => void,
563
+ ) => {
564
+ 'main thread'
565
+ if (
566
+ !scrollableBoundaryId
567
+ || offset === 0
568
+ ) {
569
+ onScrolled?.()
570
+ return
571
+ }
572
+
573
+ const element = lynx.querySelector(`#${scrollableBoundaryId}`)
574
+ if (!element) {
575
+ onScrolled?.()
576
+ return
577
+ }
578
+
579
+ element.invoke('scrollBy', {
580
+ offset,
581
+ }).then((res) => {
582
+ 'main thread'
583
+ syncScrollDeltaForItemTranslateY(res as ScrollByResult, offset)
584
+ onScrolled?.()
585
+ })
586
+ }, [
587
+ autoScrollingRef,
588
+ scrollableBoundaryId,
589
+ sortingKey,
590
+ syncScrollDeltaForItemTranslateY,
591
+ ])
592
+
593
+ const isAutoScrollBlocked = useCallback((offset: number) => {
594
+ 'main thread'
595
+ if (offset > 0) { // block autoScroll down when at lower edge
596
+ return scrollableBoundaryLowerEdgeRef?.current === true
597
+ }
598
+ if (offset < 0) { // block autoScroll up when at upper edge
599
+ return scrollableBoundaryUpperEdgeRef?.current === true
600
+ }
601
+ return false
602
+ }, [scrollableBoundaryLowerEdgeRef, scrollableBoundaryUpperEdgeRef])
603
+
604
+ const getDragStartItemBounds = useCallback((translateY: number) => {
605
+ 'main thread'
606
+ const measuredTopAtDragStart = itemRect.top
607
+ - dragStartScrollDeltaFromMeasuredRect.current
608
+ const measuredBottomAtDragStart = itemRect.bottom
609
+ - dragStartScrollDeltaFromMeasuredRect.current
610
+
611
+ return {
612
+ top: measuredTopAtDragStart + translateY,
613
+ bottom: measuredBottomAtDragStart + translateY,
614
+ }
615
+ }, [dragStartScrollDeltaFromMeasuredRect, itemRect])
616
+
617
+ const getAutoScrollOverflow = useCallback((
618
+ distanceToTop: number,
619
+ distanceToBottom: number,
620
+ ) => {
621
+ 'main thread'
622
+ return getAutoScrollTriggerOverflow(
623
+ { distanceToTop, distanceToBottom },
624
+ scrollableStickyUpperOffset,
625
+ scrollableStickyLowerOffset,
626
+ )
627
+ }, [scrollableStickyLowerOffset, scrollableStickyUpperOffset])
628
+
629
+ const getAutoScrollDirection = useCallback((
630
+ overflowDirection: number,
631
+ translateDeltaY: number,
632
+ ) => {
633
+ 'main thread'
634
+ if (translateDeltaY === 0) {
635
+ return autoScrollDirection.current || overflowDirection
636
+ }
637
+
638
+ const dragDirection = translateDeltaY > 0 ? 1 : -1
639
+ return dragDirection === overflowDirection ? overflowDirection : 0
640
+ }, [autoScrollDirection])
641
+
642
+ const getVisualTranslateY = useCallback(() => {
643
+ 'main thread'
644
+ const scrollDelta = syncScrollDeltaForItemTranslateY()
645
+ if (autoScrollStickyDirection.current > 0) {
646
+ return scrollableBoundaryRect.bottom
647
+ - itemRect.bottom
648
+ - scrollableStickyLowerOffset
649
+ + scrollDelta.measuredRectDeltaY
650
+ }
651
+ if (autoScrollStickyDirection.current < 0) {
652
+ return scrollableBoundaryRect.top
653
+ - itemRect.top
654
+ + scrollableStickyUpperOffset
655
+ + scrollDelta.measuredRectDeltaY
656
+ }
657
+ return latestDragTranslate.current.y + scrollDelta.dragDeltaY
658
+ }, [
659
+ autoScrollStickyDirection,
660
+ itemRect,
661
+ latestDragTranslate,
662
+ scrollableBoundaryRect,
663
+ scrollableStickyLowerOffset,
664
+ scrollableStickyUpperOffset,
665
+ syncScrollDeltaForItemTranslateY,
666
+ ])
667
+
668
+ const getVisualBounds = useCallback((visualTranslateY: number) => {
669
+ 'main thread'
670
+ const scrollDelta = syncScrollDeltaForItemTranslateY()
671
+ return {
672
+ top: itemRect.top - scrollDelta.measuredRectDeltaY
673
+ + visualTranslateY,
674
+ left: itemRect.left + latestDragTranslate.current.x,
675
+ width: itemRect.width,
676
+ height: itemRect.height,
677
+ }
678
+ }, [
679
+ itemRect,
680
+ latestDragTranslate,
681
+ syncScrollDeltaForItemTranslateY,
682
+ ])
683
+
684
+ const getDragOverlayElement = useCallback(() => {
685
+ 'main thread'
686
+ return dragOverlayRefMap?.current?.[sortingKey] ?? null
687
+ }, [dragOverlayRefMap, sortingKey])
688
+
689
+ const hideDragSourceItem = useCallback(() => {
690
+ 'main thread'
691
+ if (!scrollableBoundaryId || dragSourceHidden.current) {
692
+ return
693
+ }
694
+
695
+ MTSRef.current?.MTSSetOtherStyles({
696
+ visibility: 'hidden',
697
+ opacity: '0',
698
+ })
699
+ dragSourceHidden.current = true
700
+ dirtyKeysRef.current[sortingKey] = true
701
+ }, [
702
+ MTSRef,
703
+ dragSourceHidden,
704
+ scrollableBoundaryId,
705
+ dirtyKeysRef,
706
+ sortingKey,
707
+ ])
708
+
709
+ const showDragSourceItem = useCallback(() => {
710
+ 'main thread'
711
+ if (!dragSourceHidden.current) {
712
+ return
713
+ }
714
+
715
+ MTSRef.current?.MTSSetOtherStyles({
716
+ visibility: 'visible',
717
+ opacity: '1',
718
+ })
719
+ dragSourceHidden.current = false
720
+ }, [
721
+ MTSRef,
722
+ dragSourceHidden,
723
+ ])
724
+
725
+ const updateDragOverlayTransform = useCallback((visualTranslateY: number) => {
726
+ 'main thread'
727
+ const overlay = getDragOverlayElement()
728
+ if (!overlay) {
729
+ return
730
+ }
731
+
732
+ const bounds = getVisualBounds(visualTranslateY)
733
+ overlay.setStyleProperty(
734
+ 'transform',
735
+ `translate(${bounds.left}px, ${bounds.top}px)`,
736
+ )
737
+ }, [
738
+ getDragOverlayElement,
739
+ getVisualBounds,
740
+ ])
741
+
742
+ const activateDragOverlay = useCallback(() => {
743
+ 'main thread'
744
+ if (!scrollableBoundaryId) {
745
+ return
746
+ }
747
+
748
+ hideDragSourceItem()
749
+
750
+ const overlay = getDragOverlayElement()
751
+ if (!overlay) {
752
+ return
753
+ }
754
+
755
+ const visualTranslateY = getVisualTranslateY()
756
+ const bounds = getVisualBounds(visualTranslateY)
757
+ overlay.setStyleProperties({
758
+ position: 'fixed',
759
+ top: '0px',
760
+ left: '0px',
761
+ width: `${bounds.width}px`,
762
+ height: `${bounds.height}px`,
763
+ opacity: '1',
764
+ visibility: 'visible',
765
+ 'z-index': '10000',
766
+ transform: `translate(${bounds.left}px, ${bounds.top}px)`,
767
+ })
768
+ }, [
769
+ getDragOverlayElement,
770
+ getVisualBounds,
771
+ getVisualTranslateY,
772
+ hideDragSourceItem,
773
+ scrollableBoundaryId,
774
+ ])
775
+
776
+ const applyVisualTranslate = useCallback(() => {
777
+ 'main thread'
778
+ const visualTranslateY = getVisualTranslateY()
779
+ if (scrollableBoundaryId) {
780
+ MTSRef.current?.MTSSetTransform(0, 0)
781
+ console.info('reset local drag visual')
782
+ updateDragOverlayTransform(visualTranslateY)
783
+ } else {
784
+ MTSRef.current?.MTSSetTransform(
785
+ latestDragTranslate.current.x,
786
+ visualTranslateY,
787
+ )
788
+ }
789
+ dirtyKeysRef.current[sortingKey] = true
790
+ return visualTranslateY
791
+ }, [
792
+ MTSRef,
793
+ getVisualTranslateY,
794
+ latestDragTranslate,
795
+ scrollableBoundaryId,
796
+ updateDragOverlayTransform,
797
+ dirtyKeysRef,
798
+ sortingKey,
799
+ ])
800
+
801
+ const emitSortableDragMove = useCallback((
802
+ visualTranslateY: number,
803
+ event: MainThread.MouseEvent | MainThread.TouchEvent | null,
804
+ ) => {
805
+ 'main thread'
806
+ if (!event) {
807
+ return
808
+ }
809
+
810
+ handleDragMove?.(
811
+ { x: latestDragTranslate.current.x, y: visualTranslateY },
812
+ sortingKey,
813
+ event,
814
+ )
815
+ }, [handleDragMove, latestDragTranslate, sortingKey])
816
+
817
+ const scheduleNextAutoScrollFrame = useCallback(() => {
818
+ 'main thread'
819
+ const nextFrame = autoScrollFrameRef.current
820
+ if (nextFrame) {
821
+ setTimeout(nextFrame, 8)
822
+ }
823
+ }, [autoScrollFrameRef])
824
+
825
+ const finishAutoScrollFrame = useCallback(() => {
826
+ 'main thread'
827
+ const visualTranslateY = applyVisualTranslate()
828
+
829
+ emitSortableDragMove(visualTranslateY, latestDragEvent.current)
830
+ scheduleNextAutoScrollFrame()
831
+ }, [
832
+ applyVisualTranslate,
833
+ emitSortableDragMove,
834
+ latestDragEvent,
835
+ scheduleNextAutoScrollFrame,
836
+ ])
837
+
838
+ const runAutoScrollFrame = useCallback(() => {
839
+ 'main thread'
840
+ if (!autoScrollingRef.current) {
841
+ return
842
+ }
843
+
844
+ const overflow = autoScrollOverflow.current
845
+ if (overflow === 0) {
846
+ setAutoScrolling(false)
847
+ return
848
+ }
849
+
850
+ const direction = autoScrollDirection.current || (overflow > 0 ? 1 : -1)
851
+ if (isAutoScrollBlocked(direction)) {
852
+ const visualTranslateY = applyVisualTranslate()
853
+ emitSortableDragMove(visualTranslateY, latestDragEvent.current)
854
+ setAutoScrolling(false)
855
+ return
856
+ }
857
+
858
+ const step = direction * Math.min(
859
+ AUTO_SCROLL_MAX_STEP,
860
+ Math.abs(overflow) * AUTO_SCROLL_VELOCITY_FACTOR,
861
+ )
862
+ const finishScrolledFrame = () => {
863
+ 'main thread'
864
+ finishAutoScrollFrame()
865
+ }
866
+
867
+ scrollScrollableBoundaryBy(step, finishScrolledFrame)
868
+ }, [
869
+ applyVisualTranslate,
870
+ autoScrollDirection,
871
+ autoScrollOverflow,
872
+ autoScrollingRef,
873
+ emitSortableDragMove,
874
+ finishAutoScrollFrame,
875
+ isAutoScrollBlocked,
876
+ latestDragEvent,
877
+ scrollScrollableBoundaryBy,
878
+ setAutoScrolling,
879
+ ])
880
+
881
+ const startAutoScrollLoop = useCallback(() => {
882
+ 'main thread'
883
+ if (autoScrollingRef.current) {
884
+ return
885
+ }
886
+ autoScrollFrameRef.current = runAutoScrollFrame
887
+ setAutoScrolling(true)
888
+ scheduleNextAutoScrollFrame()
889
+ }, [
890
+ autoScrollingRef,
891
+ runAutoScrollFrame,
892
+ scheduleNextAutoScrollFrame,
893
+ setAutoScrolling,
894
+ ])
895
+
896
+ const stopAutoScrollLoop = useCallback(() => {
897
+ 'main thread'
898
+ autoScrollOverflow.current = 0
899
+ autoScrollDirection.current = 0
900
+ autoScrollStickyDirection.current = 0
901
+ setAutoScrolling(false)
902
+ }, [
903
+ autoScrollDirection,
904
+ autoScrollOverflow,
905
+ autoScrollStickyDirection,
906
+ setAutoScrolling,
907
+ ])
908
+
164
909
  useEffect(() => {
165
910
  runOnMainThread(setChildrenMTSRef)(MTSRef, sortingKey)
166
- if (boundaryId) {
167
- ref?.current
168
- ?.invoke({
169
- method: 'boundingClientRect',
170
- params: {},
171
- success: (res) => {
172
- setItemRect(res as boundingClientRectRes)
173
- },
174
- })
175
- .exec()
176
- lynx.createSelectorQuery().select(`#${boundaryId}`)?.invoke({
177
- method: 'boundingClientRect',
178
- params: {},
179
- success: (res) => {
180
- setBoundaryRect(res as boundingClientRectRes)
181
- },
182
- })
183
- .exec()
184
- }
185
- }, [setChildrenRef, setChildrenMTSRef, sortingKey, data, boundaryId])
911
+ refreshDraggingRects()
912
+ }, [
913
+ data,
914
+ refreshDraggingRects,
915
+ setChildrenRef,
916
+ setChildrenMTSRef,
917
+ sortingKey,
918
+ ])
186
919
 
187
920
  const handleMTSLayoutChange = (e: MainThread.LayoutChangeEvent) => {
188
921
  'main thread'
189
922
  updateItemSize(sortingKey, e.detail.height)
190
923
  }
191
924
 
925
+ const resetAutoScrollDragState = useCallback(() => {
926
+ 'main thread'
927
+ lastAutoScrollTranslateY.current = 0
928
+ autoScrollDistanceSum.current = 0
929
+ autoScrollCompensationY.current = 0
930
+ autoScrollOverflow.current = 0
931
+ autoScrollDirection.current = 0
932
+ autoScrollStickyDirection.current = 0
933
+ latestDragTranslate.current = { x: 0, y: 0 }
934
+ }, [
935
+ autoScrollCompensationY,
936
+ autoScrollDirection,
937
+ autoScrollDistanceSum,
938
+ autoScrollOverflow,
939
+ autoScrollStickyDirection,
940
+ lastAutoScrollTranslateY,
941
+ latestDragTranslate,
942
+ ])
943
+
192
944
  const itemDragStart = (
193
945
  pagePoint: Point,
194
946
  event: MainThread.MouseEvent | MainThread.TouchEvent,
195
947
  ) => {
196
948
  'main thread'
949
+ resetAutoScrollDragState()
950
+ const scrollTop = scrollableScrollTopRef?.current ?? 0
951
+ autoScrollStartScrollTop.current = scrollTop
952
+ dragStartScrollDeltaFromMeasuredRect.current = scrollTop
953
+ - itemMeasuredScrollTop.current
954
+ latestDragEvent.current = event
955
+ if (scrollableBoundaryId && scrollableBoundaryRect.height > 0) {
956
+ const draggedItem = getDragStartItemBounds(0)
957
+ const { distanceToTop, distanceToBottom } = getEdgeDistance(
958
+ draggedItem,
959
+ scrollableBoundaryRect,
960
+ )
961
+ const overflow = getAutoScrollOverflow(distanceToTop, distanceToBottom)
962
+ if (overflow !== 0) {
963
+ autoScrollStickyDirection.current = overflow > 0 ? 1 : -1
964
+ }
965
+ }
966
+ activateDragOverlay()
197
967
  handleDragStart?.(pagePoint, sortingKey, event)
968
+ if (autoScrollStickyDirection.current !== 0) {
969
+ const visualTranslateY = getVisualTranslateY()
970
+ emitSortableDragMove(visualTranslateY, event)
971
+ }
198
972
  }
199
973
 
200
974
  const itemDragging = (
@@ -202,29 +976,106 @@ export function SortableItem(props: SortableItemProps) {
202
976
  event: MainThread.MouseEvent | MainThread.TouchEvent,
203
977
  ) => {
204
978
  'main thread'
979
+ latestDragTranslate.current = translate
980
+ latestDragEvent.current = event
981
+ if (scrollableBoundaryId && scrollableBoundaryRect.height > 0) {
982
+ const draggedItem = getDragStartItemBounds(translate.y)
983
+ const { distanceToTop, distanceToBottom } = getEdgeDistance(
984
+ draggedItem,
985
+ scrollableBoundaryRect,
986
+ )
987
+ const translateDeltaY = translate.y - lastAutoScrollTranslateY.current
988
+ const overflow = getAutoScrollOverflow(distanceToTop, distanceToBottom)
989
+
990
+ lastAutoScrollTranslateY.current = translate.y
991
+
992
+ if (overflow === 0) {
993
+ stopAutoScrollLoop()
994
+ const visualTranslateY = applyVisualTranslate()
995
+ emitSortableDragMove(visualTranslateY, event)
996
+ } else {
997
+ const overflowDirection = overflow > 0 ? 1 : -1
998
+ const scrollDirection = getAutoScrollDirection(
999
+ overflowDirection,
1000
+ translateDeltaY,
1001
+ )
1002
+ autoScrollOverflow.current = overflow
1003
+ autoScrollStickyDirection.current = overflowDirection
1004
+ autoScrollDirection.current = scrollDirection
1005
+ const visualTranslateY = applyVisualTranslate()
1006
+ const blockedByScrollableEdge = scrollDirection !== 0
1007
+ && isAutoScrollBlocked(scrollDirection)
1008
+ if (scrollDirection === 0) {
1009
+ setAutoScrolling(false)
1010
+ } else if (blockedByScrollableEdge) {
1011
+ setAutoScrolling(false)
1012
+ } else {
1013
+ startAutoScrollLoop()
1014
+ }
1015
+ emitSortableDragMove(visualTranslateY, event)
1016
+ }
1017
+ return
1018
+ }
1019
+
205
1020
  handleDragMove?.(translate, sortingKey, event)
206
1021
  }
207
1022
 
1023
+ const resetLocalDragVisuals = () => {
1024
+ 'main thread'
1025
+ if (!dirtyKeysRef.current[sortingKey]) {
1026
+ return
1027
+ }
1028
+ console.info('reset local drag visual2')
1029
+ MTSRef.current?.MTSSetTransform(0, 0)
1030
+ const overlayWasActive = dragSourceHidden.current
1031
+ showDragSourceItem()
1032
+ if (overlayWasActive) {
1033
+ const overlay = getDragOverlayElement()
1034
+ if (overlay) {
1035
+ overlay.setStyleProperties({
1036
+ opacity: '0',
1037
+ visibility: 'hidden',
1038
+ transform: 'translate(0px, 0px)',
1039
+ })
1040
+ }
1041
+ }
1042
+ dirtyKeysRef.current[sortingKey] = false
1043
+ }
1044
+
208
1045
  const itemDragEnd = (
209
1046
  _pagePoint: Point,
210
1047
  event: MainThread.MouseEvent | MainThread.TouchEvent,
211
1048
  ) => {
212
1049
  'main thread'
213
- handleDragEnd?.(sortingKey, event)
1050
+ resetAutoScrollDragState()
1051
+ autoScrollStartScrollTop.current = 0
1052
+ dragStartScrollDeltaFromMeasuredRect.current = 0
1053
+ latestDragEvent.current = null
1054
+ stopAutoScrollLoop()
1055
+ const orderChanged = handleDragEnd?.(sortingKey, event) ?? false
1056
+ if (!orderChanged) {
1057
+ // no data update -> no precommit will run -> reset locally now
1058
+ resetLocalDragVisuals()
1059
+ }
1060
+ // if orderChanged: precommit will run resetLocalDragVisuals in the same frame as setData
214
1061
  }
215
1062
 
216
- const resetStyle = useMemo(
217
- () => ({ transform: 'translate(0, 0)', zIndex: '0' }),
1063
+ const dataKeyOrderSignature = useMemo(
1064
+ () => (data ?? []).map(item => item.getSortingKey()).join('|'),
218
1065
  [data],
219
1066
  )
220
1067
 
1068
+ usePreCommit(() => {
1069
+ 'main thread'
1070
+ resetLocalDragVisuals()
1071
+ }, [dataKeyOrderSignature])
1072
+
221
1073
  if (as === 'Draggable') {
222
1074
  return (
223
1075
  <Draggable
1076
+ id={itemElementId}
224
1077
  MTSRef={MTSRef}
225
- ref={ref}
226
1078
  trigger='immediate'
227
- style={resetStyle}
228
1079
  className={className}
229
1080
  enableDragging={enableSorting}
230
1081
  draggableProps={{
@@ -234,10 +1085,11 @@ export function SortableItem(props: SortableItemProps) {
234
1085
  onMTSDragEnd={itemDragEnd}
235
1086
  onMTSDragging={itemDragging}
236
1087
  allowedDirection={['up', 'down']}
237
- {...(boundaryId
1088
+ {...(!scrollableBoundaryId && boundaryId
238
1089
  && {
239
- minTranslateY: -(itemRect?.top - boundaryRect?.top),
240
- maxTranslateY: boundaryRect?.bottom - itemRect?.bottom,
1090
+ minTranslateY: -(itemRect.top - boundaryRect.top),
1091
+ maxTranslateY: boundaryRect.bottom
1092
+ - itemRect.bottom,
241
1093
  })}
242
1094
  >
243
1095
  {children}
@@ -246,10 +1098,9 @@ export function SortableItem(props: SortableItemProps) {
246
1098
  } else {
247
1099
  return (
248
1100
  <DraggableRoot
1101
+ id={itemElementId}
249
1102
  MTSRef={MTSRef}
250
- ref={ref}
251
1103
  trigger='immediate'
252
- style={resetStyle}
253
1104
  className={className}
254
1105
  draggableProps={{
255
1106
  'main-thread:bindlayoutchange': handleMTSLayoutChange,
@@ -258,10 +1109,11 @@ export function SortableItem(props: SortableItemProps) {
258
1109
  onMTSDragEnd={itemDragEnd}
259
1110
  onMTSDragging={itemDragging}
260
1111
  enableDragging={enableSorting}
261
- {...(boundaryId
1112
+ {...(!scrollableBoundaryId && boundaryId
262
1113
  && {
263
- minTranslateY: -(itemRect?.top - boundaryRect?.top),
264
- maxTranslateY: boundaryRect?.bottom - itemRect?.bottom,
1114
+ minTranslateY: -(itemRect.top - boundaryRect.top),
1115
+ maxTranslateY: boundaryRect.bottom
1116
+ - itemRect.bottom,
265
1117
  })}
266
1118
  allowedDirection={['up', 'down']}
267
1119
  >