@lynx-js/lynx-ui-sortable 3.133.1 → 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,36 +9,127 @@ 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
- import type { SortableItemProps, SortableRootProps } from './types'
27
+ import type {
28
+ SortableData,
29
+ SortableItemProps,
30
+ SortableRootProps,
31
+ } from './types'
28
32
  import { useSortable } from './useSortable'
29
33
 
30
34
  export { DraggableArea as SortableItemArea }
31
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
+
32
95
  export function SortableRoot<T>(props: SortableRootProps<T>) {
33
96
  const {
34
97
  children,
35
98
  data,
36
99
  debugLog = false,
37
100
  boundaryId,
101
+ scrollableBoundaryId,
102
+ as,
103
+ scrollableClassName,
104
+ scrollableContentClassName,
105
+ scrollableEnableScroll = true,
106
+ scrollableStickyUpperOffset = 0,
107
+ scrollableStickyLowerOffset = 0,
38
108
  onSortEnd,
39
109
  onSortStart,
40
110
  enableSorting = true,
41
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
+ )
42
133
  const sizeMap = useMainThreadRef<Record<string, number>>({})
43
134
  const childrenRefMap = useMainThreadRef<
44
135
  Record<string, DraggableRef | null>
@@ -50,11 +141,45 @@ export function SortableRoot<T>(props: SortableRootProps<T>) {
50
141
  >(
51
142
  {},
52
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)
53
153
  const updateItemSize = useCallback((sortingKey: string, size: number) => {
54
154
  'main thread'
55
155
  sizeMap.current[sortingKey] = size
56
156
  }, [])
57
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
+
58
183
  const setChildrenRef = useCallback(
59
184
  (refI: RefObject<DraggableRef>, key: string) => {
60
185
  'main thread'
@@ -71,42 +196,140 @@ export function SortableRoot<T>(props: SortableRootProps<T>) {
71
196
  childrenMTSRefMap.current[key] = refI.current
72
197
  }, [])
73
198
 
74
- const { handleDragEnd, handleDragMove, handleDragStart } = useSortable<T>({
75
- data,
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
+
207
+ const { handleDragEnd, handleDragMove, handleDragStart } = useSortable({
208
+ data: data,
76
209
  sizeMap: sizeMap,
77
210
  itemRefMap: childrenRefMap,
78
211
  itemMTSRefMap: childrenMTSRefMap,
79
- onDragEnd: onSortEnd,
80
- onDragStart: onSortStart,
212
+ dirtyKeysRef,
213
+ onDragEnd: handleInternalSortEnd,
214
+ onDragStart: handleInternalSortStart,
81
215
  debugLog,
82
216
  })
83
217
  const sortableContextValue = useMemo(() => ({
84
218
  data,
219
+ isDragOverlay: false,
220
+ debugLog,
85
221
  enableSorting,
86
- 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,
87
239
  updateItemSize,
88
240
  setChildrenRef,
89
241
  setChildrenMTSRef,
242
+ setDragOverlayRef,
90
243
  handleDragEnd,
91
244
  handleDragMove,
92
245
  handleDragStart,
93
246
  }), [
94
247
  data,
248
+ debugLog,
95
249
  enableSorting,
96
250
  boundaryId,
251
+ scrollable,
252
+ scrollableContentId,
253
+ scrollableElementId,
254
+ scrollableBoundaryId,
255
+ scrollableBoundaryLowerEdgeRef,
256
+ scrollableBoundaryUpperEdgeRef,
257
+ scrollableScrollTopRef,
258
+ dragOverlayRefMap,
259
+ dirtyKeysRef,
260
+ scrollableStickyLowerOffset,
261
+ scrollableStickyUpperOffset,
97
262
  updateItemSize,
98
263
  setChildrenRef,
99
264
  setChildrenMTSRef,
265
+ setDragOverlayRef,
100
266
  handleDragEnd,
101
267
  handleDragMove,
102
268
  handleDragStart,
103
269
  ])
104
270
 
271
+ const sortableDragOverlayContextValue = useMemo(() => ({
272
+ ...sortableContextValue,
273
+ isDragOverlay: true,
274
+ }), [sortableContextValue])
275
+
105
276
  const renderedChildren = useMemo(
106
277
  () => data?.map(item => children(item)),
107
278
  [data, children],
108
279
  )
109
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
+
110
333
  return (
111
334
  <SortableContext.Provider
112
335
  value={sortableContextValue}
@@ -126,11 +349,65 @@ interface boundingClientRectRes {
126
349
  }
127
350
 
128
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) {
129
398
  const { className, children, sortingKey, as = 'Draggable' } = props
130
399
  const {
131
400
  data,
132
401
  enableSorting,
133
402
  boundaryId,
403
+ scrollableBoundaryId,
404
+ scrollableBoundaryUpperEdgeRef,
405
+ scrollableBoundaryLowerEdgeRef,
406
+ scrollableScrollTopRef,
407
+ dragOverlayRefMap,
408
+ dirtyKeysRef,
409
+ scrollableStickyUpperOffset,
410
+ scrollableStickyLowerOffset,
134
411
  updateItemSize,
135
412
  setChildrenRef,
136
413
  setChildrenMTSRef,
@@ -140,7 +417,6 @@ export function SortableItem(props: SortableItemProps) {
140
417
  } = useContext(SortableContext)
141
418
 
142
419
  const MTSRef = useMainThreadRef<DraggableRef>(null)
143
- const ref = useRef<NodesRef>(null)
144
420
  const [itemRect, setItemRect] = useState<boundingClientRectRes>({
145
421
  height: 0,
146
422
  width: 0,
@@ -157,40 +433,542 @@ export function SortableItem(props: SortableItemProps) {
157
433
  bottom: 0,
158
434
  right: 0,
159
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
+
160
909
  useEffect(() => {
161
910
  runOnMainThread(setChildrenMTSRef)(MTSRef, sortingKey)
162
- if (boundaryId) {
163
- ref?.current
164
- ?.invoke({
165
- method: 'boundingClientRect',
166
- params: {},
167
- success: (res) => {
168
- setItemRect(res as boundingClientRectRes)
169
- },
170
- })
171
- .exec()
172
- lynx.createSelectorQuery().select(`#${boundaryId}`)?.invoke({
173
- method: 'boundingClientRect',
174
- params: {},
175
- success: (res) => {
176
- setBoundaryRect(res as boundingClientRectRes)
177
- },
178
- })
179
- .exec()
180
- }
181
- }, [setChildrenRef, setChildrenMTSRef, sortingKey, data, boundaryId])
911
+ refreshDraggingRects()
912
+ }, [
913
+ data,
914
+ refreshDraggingRects,
915
+ setChildrenRef,
916
+ setChildrenMTSRef,
917
+ sortingKey,
918
+ ])
182
919
 
183
920
  const handleMTSLayoutChange = (e: MainThread.LayoutChangeEvent) => {
184
921
  'main thread'
185
922
  updateItemSize(sortingKey, e.detail.height)
186
923
  }
187
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
+
188
944
  const itemDragStart = (
189
945
  pagePoint: Point,
190
946
  event: MainThread.MouseEvent | MainThread.TouchEvent,
191
947
  ) => {
192
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()
193
967
  handleDragStart?.(pagePoint, sortingKey, event)
968
+ if (autoScrollStickyDirection.current !== 0) {
969
+ const visualTranslateY = getVisualTranslateY()
970
+ emitSortableDragMove(visualTranslateY, event)
971
+ }
194
972
  }
195
973
 
196
974
  const itemDragging = (
@@ -198,29 +976,106 @@ export function SortableItem(props: SortableItemProps) {
198
976
  event: MainThread.MouseEvent | MainThread.TouchEvent,
199
977
  ) => {
200
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
+
201
1020
  handleDragMove?.(translate, sortingKey, event)
202
1021
  }
203
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
+
204
1045
  const itemDragEnd = (
205
1046
  _pagePoint: Point,
206
1047
  event: MainThread.MouseEvent | MainThread.TouchEvent,
207
1048
  ) => {
208
1049
  'main thread'
209
- 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
210
1061
  }
211
1062
 
212
- const resetStyle = useMemo(
213
- () => ({ transform: 'translate(0, 0)', zIndex: '0' }),
1063
+ const dataKeyOrderSignature = useMemo(
1064
+ () => (data ?? []).map(item => item.getSortingKey()).join('|'),
214
1065
  [data],
215
1066
  )
216
1067
 
1068
+ usePreCommit(() => {
1069
+ 'main thread'
1070
+ resetLocalDragVisuals()
1071
+ }, [dataKeyOrderSignature])
1072
+
217
1073
  if (as === 'Draggable') {
218
1074
  return (
219
1075
  <Draggable
1076
+ id={itemElementId}
220
1077
  MTSRef={MTSRef}
221
- ref={ref}
222
1078
  trigger='immediate'
223
- style={resetStyle}
224
1079
  className={className}
225
1080
  enableDragging={enableSorting}
226
1081
  draggableProps={{
@@ -230,10 +1085,11 @@ export function SortableItem(props: SortableItemProps) {
230
1085
  onMTSDragEnd={itemDragEnd}
231
1086
  onMTSDragging={itemDragging}
232
1087
  allowedDirection={['up', 'down']}
233
- {...(boundaryId
1088
+ {...(!scrollableBoundaryId && boundaryId
234
1089
  && {
235
- minTranslateY: -(itemRect?.top - boundaryRect?.top),
236
- maxTranslateY: boundaryRect?.bottom - itemRect?.bottom,
1090
+ minTranslateY: -(itemRect.top - boundaryRect.top),
1091
+ maxTranslateY: boundaryRect.bottom
1092
+ - itemRect.bottom,
237
1093
  })}
238
1094
  >
239
1095
  {children}
@@ -242,10 +1098,9 @@ export function SortableItem(props: SortableItemProps) {
242
1098
  } else {
243
1099
  return (
244
1100
  <DraggableRoot
1101
+ id={itemElementId}
245
1102
  MTSRef={MTSRef}
246
- ref={ref}
247
1103
  trigger='immediate'
248
- style={resetStyle}
249
1104
  className={className}
250
1105
  draggableProps={{
251
1106
  'main-thread:bindlayoutchange': handleMTSLayoutChange,
@@ -254,10 +1109,11 @@ export function SortableItem(props: SortableItemProps) {
254
1109
  onMTSDragEnd={itemDragEnd}
255
1110
  onMTSDragging={itemDragging}
256
1111
  enableDragging={enableSorting}
257
- {...(boundaryId
1112
+ {...(!scrollableBoundaryId && boundaryId
258
1113
  && {
259
- minTranslateY: -(itemRect?.top - boundaryRect?.top),
260
- maxTranslateY: boundaryRect?.bottom - itemRect?.bottom,
1114
+ minTranslateY: -(itemRect.top - boundaryRect.top),
1115
+ maxTranslateY: boundaryRect.bottom
1116
+ - itemRect.bottom,
261
1117
  })}
262
1118
  allowedDirection={['up', 'down']}
263
1119
  >