Skip to content

Commit 42f7bad

Browse files
authored
Bug fix and TS docs for useLongPress (#2590)
1 parent 5578dfb commit 42f7bad

File tree

2 files changed

+31
-3
lines changed

2 files changed

+31
-3
lines changed

packages/@react-aria/interactions/src/useLongPress.ts

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,10 @@
1010
* governing permissions and limitations under the License.
1111
*/
1212

13+
import {HTMLAttributes, useRef} from 'react';
1314
import {LongPressEvent} from '@react-types/shared';
1415
import {mergeProps, useDescription, useGlobalListeners} from '@react-aria/utils';
1516
import {usePress} from './usePress';
16-
import {useRef} from 'react';
1717

1818
interface LongPressProps {
1919
/** Whether long press events should be disabled. */
@@ -42,9 +42,18 @@ interface LongPressProps {
4242
accessibilityDescription?: string
4343
}
4444

45+
interface LongPressResult {
46+
/** Props to spread on the target element. */
47+
longPressProps: HTMLAttributes<HTMLElement>
48+
}
49+
4550
const DEFAULT_THRESHOLD = 500;
4651

47-
export function useLongPress(props: LongPressProps) {
52+
/**
53+
* Handles long press interactions across mouse and touch devices. Supports a customizable time threshold,
54+
* accessibility description, and normalizes behavior across browsers and devices.
55+
*/
56+
export function useLongPress(props: LongPressProps): LongPressResult {
4857
let {
4958
isDisabled,
5059
onLongPressStart,
@@ -102,7 +111,7 @@ export function useLongPress(props: LongPressProps) {
102111
clearTimeout(timeRef.current);
103112
}
104113

105-
if (onLongPressEnd) {
114+
if (onLongPressEnd && (e.pointerType === 'mouse' || e.pointerType === 'touch')) {
106115
onLongPressEnd({
107116
...e,
108117
type: 'longpressend'

packages/@react-aria/interactions/test/useLongPress.test.js

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -423,4 +423,23 @@ describe('useLongPress', function () {
423423

424424
fireEvent.pointerUp(el, {pointerType: 'touch'});
425425
});
426+
427+
it('should not fire any events for keyboard interactions', function () {
428+
let events = [];
429+
let addEvent = (e) => events.push(e);
430+
let res = render(
431+
<Example
432+
onLongPressStart={addEvent}
433+
onLongPressEnd={addEvent}
434+
onLongPress={addEvent}
435+
threshold={800} />
436+
);
437+
438+
let el = res.getByText('test');
439+
fireEvent.keyDown(el, {key: ' '});
440+
act(() => jest.advanceTimersByTime(600));
441+
fireEvent.keyUp(el, {key: ' '});
442+
443+
expect(events).toHaveLength(0);
444+
});
426445
});

0 commit comments

Comments
 (0)