@@ -5,6 +5,7 @@ interface UseTouchLongPressOptions<T> {
55 enabled : boolean ;
66 delayMs ?: number ;
77 moveTolerancePx ?: number ;
8+ suppressTextSelection ?: boolean ;
89 onLongPress : ( value : T ) => void ;
910}
1011
@@ -18,20 +19,50 @@ export interface TouchLongPressHandlers<T> {
1819const DEFAULT_LONG_PRESS_DELAY_MS = 500 ;
1920const DEFAULT_MOVE_TOLERANCE_PX = 10 ;
2021
22+ const suppressDocumentTextSelection = (
23+ ownerDocument : Document ,
24+ ) : ( ( ) => void ) => {
25+ const root = ownerDocument . documentElement ;
26+ const previousUserSelect = root . style . userSelect ;
27+ const previousWebkitUserSelect = root . style . getPropertyValue (
28+ '-webkit-user-select' ,
29+ ) ;
30+
31+ ownerDocument . defaultView ?. getSelection ( ) ?. removeAllRanges ( ) ;
32+ root . style . userSelect = 'none' ;
33+ root . style . setProperty ( '-webkit-user-select' , 'none' ) ;
34+
35+ return ( ) => {
36+ ownerDocument . defaultView ?. getSelection ( ) ?. removeAllRanges ( ) ;
37+ root . style . userSelect = previousUserSelect ;
38+
39+ if ( previousWebkitUserSelect ) {
40+ root . style . setProperty ( '-webkit-user-select' , previousWebkitUserSelect ) ;
41+ return ;
42+ }
43+
44+ root . style . removeProperty ( '-webkit-user-select' ) ;
45+ } ;
46+ } ;
47+
2148export const useTouchLongPress = < T > ( {
2249 enabled,
2350 delayMs = DEFAULT_LONG_PRESS_DELAY_MS ,
2451 moveTolerancePx = DEFAULT_MOVE_TOLERANCE_PX ,
52+ suppressTextSelection = true ,
2553 onLongPress,
2654} : UseTouchLongPressOptions < T > ) : TouchLongPressHandlers < T > => {
2755 const timerRef = useRef < ReturnType < typeof setTimeout > | null > ( null ) ;
2856 const startPosRef = useRef < { x : number ; y : number } | null > ( null ) ;
57+ const restoreTextSelectionRef = useRef < ( ( ) => void ) | null > ( null ) ;
2958
3059 const cancelLongPress = useCallback ( ( ) : void => {
3160 if ( timerRef . current ) {
3261 clearTimeout ( timerRef . current ) ;
3362 timerRef . current = null ;
3463 }
64+ restoreTextSelectionRef . current ?.( ) ;
65+ restoreTextSelectionRef . current = null ;
3566 startPosRef . current = null ;
3667 } , [ ] ) ;
3768
@@ -55,13 +86,19 @@ export const useTouchLongPress = <T>({
5586 return ;
5687 }
5788
89+ const { ownerDocument } = event . currentTarget ;
5890 startPosRef . current = { x : touch . clientX , y : touch . clientY } ;
91+ if ( suppressTextSelection ) {
92+ restoreTextSelectionRef . current =
93+ suppressDocumentTextSelection ( ownerDocument ) ;
94+ }
5995 timerRef . current = setTimeout ( ( ) => {
6096 timerRef . current = null ;
97+ ownerDocument . defaultView ?. getSelection ( ) ?. removeAllRanges ( ) ;
6198 onLongPress ( value ) ;
6299 } , delayMs ) ;
63100 } ,
64- [ cancelLongPress , delayMs , enabled , onLongPress ] ,
101+ [ cancelLongPress , delayMs , enabled , onLongPress , suppressTextSelection ] ,
65102 ) ;
66103
67104 const onTouchMove = useCallback (
0 commit comments