MCPcopy
hub / github.com/adobe/react-spectrum / useLongPress

Function useLongPress

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

Source from the content-addressed store, hash-verified

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

Callers 4

ExampleFunction · 0.90
ExampleWithPressFunction · 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