1
1
import { clamp , isInRange } from '@/utils'
2
- import { useCallback , useLayoutEffect , useRef , useState } from 'react'
2
+ import { startTransition , useCallback , useLayoutEffect , useRef , useState } from 'react'
3
3
4
4
export interface DargOptions {
5
5
initX : number
@@ -14,8 +14,8 @@ const useDraggable = (options: DargOptions) => {
14
14
const { initX, initY, maxX = 0 , minX = 0 , maxY = 0 , minY = 0 } = options
15
15
16
16
const mousePosition = useRef ( { x : 0 , y : 0 } )
17
-
18
- const [ position , setPosition ] = useState ( { x : clamp ( initX , minX , maxX ) , y : clamp ( initY , minY , maxY ) } )
17
+ const positionRef = useRef ( { x : clamp ( initX , minX , maxX ) , y : clamp ( initY , minY , maxY ) } )
18
+ const [ position , setPosition ] = useState ( positionRef . current )
19
19
20
20
useLayoutEffect ( ( ) => {
21
21
const newPosition = { x : clamp ( initX , minX , maxX ) , y : clamp ( initY , minY , maxY ) }
@@ -30,12 +30,13 @@ const useDraggable = (options: DargOptions) => {
30
30
( e : MouseEvent ) => {
31
31
if ( isMove . current ) {
32
32
const { clientX, clientY } = e
33
+ const prev = positionRef . current
33
34
const delta = {
34
- x : position . x + clientX - mousePosition . current . x ,
35
- y : position . y + clientY - mousePosition . current . y
35
+ x : prev . x + clientX - mousePosition . current . x ,
36
+ y : prev . y + clientY - mousePosition . current . y
36
37
}
37
38
38
- const hasChanged = delta . x !== position . x || delta . y !== position . y
39
+ const hasChanged = delta . x !== prev . x || delta . y !== prev . y
39
40
40
41
if ( isInRange ( delta . x , minX , maxX ) ) {
41
42
mousePosition . current . x = clientX
@@ -44,15 +45,14 @@ const useDraggable = (options: DargOptions) => {
44
45
mousePosition . current . y = clientY
45
46
}
46
47
if ( hasChanged ) {
47
- setPosition ( ( ) => {
48
- const x = clamp ( delta . x , minX , maxX )
49
- const y = clamp ( delta . y , minY , maxY )
50
- return { x, y }
51
- } )
48
+ const x = clamp ( delta . x , minX , maxX )
49
+ const y = clamp ( delta . y , minY , maxY )
50
+ positionRef . current = { x, y }
51
+ setPosition ( { x, y } )
52
52
}
53
53
}
54
54
} ,
55
- [ minX , maxX , minY , maxY , position ]
55
+ [ minX , maxX , minY , maxY ]
56
56
)
57
57
58
58
const handleEnd = useCallback ( ( ) => {
0 commit comments