MCPcopy Create free account
hub / github.com/adobe/react-spectrum / useLongPress

Function useLongPress

packages/react-aria/src/interactions/useLongPress.ts:63–155  ·  view source on GitHub ↗
(props: LongPressProps)

Source from the content-addressed store, hash-verified

61 * threshold, accessibility description, and normalizes behavior across browsers and devices.
62 */
63export function useLongPress(props: LongPressProps): LongPressResult {
64 let {
65 isDisabled,
66 pointerType,
67 onLongPressStart,
68 onLongPressEnd,
69 onLongPress,
70 threshold = DEFAULT_THRESHOLD,
71 accessibilityDescription
72 } = props;
73
74 const timeRef = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
75 let {addGlobalListener, removeAllGlobalListeners} = useGlobalListeners();
76 let isAcceptedPointerType = (e: PressEvent) =>
77 pointerType
78 ? e.pointerType === pointerType
79 : e.pointerType === 'mouse' || e.pointerType === 'touch';
80
81 let {pressProps} = usePress({
82 isDisabled,
83 onPressStart(e) {
84 e.continuePropagation();
85 if (isAcceptedPointerType(e)) {
86 if (onLongPressStart) {
87 onLongPressStart({
88 ...e,
89 type: 'longpressstart'
90 });
91 }
92
93 timeRef.current = setTimeout(() => {
94 // Prevent other usePress handlers from also handling this event.
95 e.target.dispatchEvent(new PointerEvent('pointercancel', {bubbles: true}));
96
97 // Prevent default click action (e.g. opening a link) after a long press.
98 addGlobalListener(e.target, 'click', e => e.preventDefault(), {once: true});
99
100 // Ensure target is focused. On touch devices, browsers typically focus on pointer up.
101 if (getOwnerDocument(e.target).activeElement !== e.target) {
102 focusWithoutScrolling(e.target as FocusableElement);
103 }
104
105 if (onLongPress) {
106 onLongPress({
107 ...e,
108 type: 'longpress'
109 });
110 }
111 timeRef.current = undefined;
112 }, threshold);
113
114 // Prevent context menu, which may be opened on long press on touch devices
115 if (e.pointerType === 'touch') {
116 addGlobalListener(e.target, 'contextmenu', e => e.preventDefault(), {once: true});
117 }
118
119 let ownerWindow = getOwnerWindow(e.target);
120 addGlobalListener(

Callers 6

ExampleFunction · 0.90
ExampleWithPressFunction · 0.90
useContextMenuFunction · 0.90
usePreviewTriggerFunction · 0.90
useSelectableItemFunction · 0.90
useMenuTriggerFunction · 0.90

Calls 4

useGlobalListenersFunction · 0.90
usePressFunction · 0.90
useDescriptionFunction · 0.90
mergePropsFunction · 0.90

Tested by 2

ExampleFunction · 0.72
ExampleWithPressFunction · 0.72