Skip to content

Commit

Permalink
fix: Fail testing and update doc
Browse files Browse the repository at this point in the history
  • Loading branch information
KusStar committed Jan 24, 2020
1 parent a0d61b5 commit 57b9041
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 15 deletions.
12 changes: 6 additions & 6 deletions docs/useLongPress.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,14 +33,14 @@ const {
onTouchEnd
} = useLongPress(
callback: (e: TouchEvent | MouseEvent) => void,
options: {
isPreventDefault: true,
delay: 300
options?: {
isPreventDefault?: true,
delay?: 300
}
)
```

- `callback` — callback function.
- `options` — optional parameter.
- `isPreventDefault` — whether to call `event.preventDefault()` of `touchend` event, for preventing ghost click on mobile devices in some cases, defaults to `true`.
- `delay` — delay in milliseconds after which to calls provided callback, defaults to `300`.
- `options?` — optional parameter.
- `isPreventDefault?` — whether to call `event.preventDefault()` of `touchend` event, for preventing ghost click on mobile devices in some cases, defaults to `true`.
- `delay?` — delay in milliseconds after which to calls provided callback, defaults to `300`.
18 changes: 9 additions & 9 deletions src/useLongPress.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@ interface Options {
delay?: number;
}

const DEFAULT_OPTIONS = { isPreventDefault: true, delay: 300 };

const isTouchEvent = (event: Event): event is TouchEvent => {
return 'touches' in event;
};
Expand All @@ -19,28 +17,30 @@ const preventDefault = (event: Event) => {
}
};

const useLongPress = (callback: (e: TouchEvent | MouseEvent) => void, options: Options = DEFAULT_OPTIONS) => {
const useLongPress = (
callback: (e: TouchEvent | MouseEvent) => void,
{ isPreventDefault = true, delay = 300 }: Options = {}
) => {
const timeout = useRef<ReturnType<typeof setTimeout>>();
const target = useRef<EventTarget>();

const start = useCallback(
(event: TouchEvent | MouseEvent) => {
// prevent ghost click on mobile devices
if (options.isPreventDefault && event.target) {
target.current = event.target;
if (isPreventDefault && event.target) {
event.target.addEventListener('touchend', preventDefault, { passive: false });
target.current = event.target;
}

timeout.current = setTimeout(() => callback(event), options.delay);
timeout.current = setTimeout(() => callback(event), delay);
},
[callback, options.delay]
[callback, delay]
);

const clear = useCallback(() => {
// clearTimeout and removeEventListener
timeout.current && clearTimeout(timeout.current);

if (options.isPreventDefault && target.current) {
if (isPreventDefault && target.current) {
target.current.removeEventListener('touchend', preventDefault);
}
}, []);
Expand Down

0 comments on commit 57b9041

Please sign in to comment.