-
Notifications
You must be signed in to change notification settings - Fork 4.8k
Expand file tree
/
Copy pathuse-interaction.ts
More file actions
223 lines (208 loc) · 6.72 KB
/
use-interaction.ts
File metadata and controls
223 lines (208 loc) · 6.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
/**
* WordPress dependencies
*/
import { useCallback, useEffect, useRef, useState } from '@wordpress/element';
/**
* Internal dependencies
*/
import type { CropperState, Size } from '../../core/types';
import {
InteractionController,
type CropperInteractionActions,
} from '../../core/interaction-controller';
/**
* The return type of the useInteraction hook.
*/
export interface UseInteractionReturn {
/** Event handler props to spread on the container element. */
handlers: {
onPointerDown: ( e: React.PointerEvent ) => void;
onTouchStart: ( e: React.TouchEvent ) => void;
onKeyDown: ( e: React.KeyboardEvent ) => void;
};
/** Native wheel handler — must be registered with { passive: false }. */
onWheelNative: ( e: WheelEvent ) => void;
/** Whether a drag (pan) interaction is in progress. */
isDragging: boolean;
/** Whether a double-tap zoom animation is in progress. */
isZooming: boolean;
/** Whether the user is currently performing a placement interaction. */
isPlacementActive: boolean;
}
/**
* Options for the useInteraction hook.
*/
export interface UseInteractionOptions {
/** Minimum zoom level. Defaults to MIN_ZOOM. */
minZoom?: number;
/** Maximum zoom level. Defaults to MAX_ZOOM. */
maxZoom?: number;
/** Zoom speed multiplier for wheel events. Defaults to 0.0025. */
zoomSpeed?: number;
/** Pan step size in normalized coords for keyboard events. Defaults to 0.05. */
keyboardStep?: number;
/** Zoom level for double-tap zoom. Defaults to 2. */
doubleTapZoom?: number;
/** Fires when a continuous gesture begins (pan drag, pinch zoom). */
onGestureStart?: () => void;
/** Fires when a continuous gesture ends (pointer release). */
onGestureEnd?: () => void;
}
/** How long keyboard placement stays active after the latest handled key. */
const KEYBOARD_INTERACTION_IDLE_MS = 300;
function isHandledKeyboardPan( event: KeyboardEvent ): boolean {
switch ( event.key ) {
case 'ArrowUp':
case 'ArrowDown':
case 'ArrowLeft':
case 'ArrowRight':
return true;
default:
return false;
}
}
/**
* Mouse, touch, and keyboard event handling for pan, zoom,
* and crop manipulation.
*
* Returns event handler props to spread on the container element.
* Uses requestAnimationFrame for drag/pinch updates to avoid
* layout thrashing.
*
* @param state The current cropper state.
* @param actions Named state updates for cropper interactions.
* @param containerSize The container dimensions in pixels.
* @param imageSize The rendered image dimensions in pixels.
* @param options Optional configuration for zoom and keyboard behavior.
* @return Event handler props for the container element.
*/
export function useInteraction(
state: CropperState,
actions: CropperInteractionActions,
containerSize: Size,
imageSize?: Size,
options?: UseInteractionOptions
): UseInteractionReturn {
const [ isDragging, setIsDragging ] = useState( false );
const [ isZooming, setIsZooming ] = useState( false );
const [ isGestureActive, setIsGestureActive ] = useState( false );
const [ isKeyboardPanning, setIsKeyboardPanning ] = useState( false );
const keyboardInteractionTimerRef =
useRef< ReturnType< typeof setTimeout > >();
// Keep mutable refs so the controller always reads fresh values
// without needing to be recreated.
const stateRef = useRef( state );
stateRef.current = state;
const containerSizeRef = useRef( containerSize );
containerSizeRef.current = containerSize;
const imageSizeRef = useRef( imageSize );
imageSizeRef.current = imageSize;
const optionsRef = useRef( options );
optionsRef.current = options;
const actionsRef = useRef( actions );
actionsRef.current = actions;
const controllerRef = useRef< InteractionController | null >( null );
const startPlacementGesture = useCallback( () => {
setIsGestureActive( true );
}, [] );
const stopPlacementGesture = useCallback( () => {
setIsGestureActive( false );
}, [] );
const signalKeyboardPlacement = useCallback( () => {
setIsKeyboardPanning( true );
clearTimeout( keyboardInteractionTimerRef.current );
keyboardInteractionTimerRef.current = setTimeout( () => {
setIsKeyboardPanning( false );
}, KEYBOARD_INTERACTION_IDLE_MS );
}, [] );
useEffect( () => {
return () => {
clearTimeout( keyboardInteractionTimerRef.current );
};
}, [] );
// Create / destroy the controller. The controller reads all volatile
// values through refs, so it can stay mounted across render updates.
useEffect( () => {
const controller = new InteractionController( {
getState: () => stateRef.current,
actions: {
setPan: ( pan ) => actionsRef.current.setPan( pan ),
setZoom: ( zoom ) => actionsRef.current.setZoom( zoom ),
setZoomAtPoint: ( zoom, pan ) =>
actionsRef.current.setZoomAtPoint( zoom, pan ),
snapRotate90: ( direction ) =>
actionsRef.current.snapRotate90( direction ),
},
getContainerSize: () => containerSizeRef.current,
getImageSize: () => imageSizeRef.current,
get minZoom() {
return optionsRef.current?.minZoom;
},
get maxZoom() {
return optionsRef.current?.maxZoom;
},
get zoomSpeed() {
return optionsRef.current?.zoomSpeed;
},
get keyboardStep() {
return optionsRef.current?.keyboardStep;
},
get doubleTapZoom() {
return optionsRef.current?.doubleTapZoom;
},
onGestureStart: () => {
startPlacementGesture();
optionsRef.current?.onGestureStart?.();
},
onGestureEnd: () => {
stopPlacementGesture();
optionsRef.current?.onGestureEnd?.();
},
onStatusChange: ( status ) => {
setIsDragging( status.isDragging );
setIsZooming( status.isZooming );
},
} );
controllerRef.current = controller;
return () => {
controller.destroy();
controllerRef.current = null;
};
}, [ startPlacementGesture, stopPlacementGesture ] );
const onPointerDown = useCallback( ( e: React.PointerEvent ) => {
const el = e.currentTarget as HTMLElement;
controllerRef.current?.handlePointerDown( e.nativeEvent, el );
}, [] );
const onTouchStart = useCallback( ( e: React.TouchEvent ) => {
const el = e.currentTarget as HTMLElement;
const rect = el.getBoundingClientRect();
controllerRef.current?.handleTouchStart(
e.nativeEvent,
rect,
el.ownerDocument
);
}, [] );
const onKeyDown = useCallback(
( e: React.KeyboardEvent ) => {
if ( isHandledKeyboardPan( e.nativeEvent ) ) {
signalKeyboardPlacement();
}
controllerRef.current?.handleKeyDown( e.nativeEvent );
},
[ signalKeyboardPlacement ]
);
const onWheelNative = useCallback( ( e: WheelEvent ) => {
controllerRef.current?.handleWheel( e );
}, [] );
return {
handlers: {
onPointerDown,
onTouchStart,
onKeyDown,
},
onWheelNative,
isDragging,
isZooming,
isPlacementActive: isGestureActive || isKeyboardPanning || isZooming,
};
}