Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: useSwipe #2337

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions config/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,7 @@ export const menus = [
'useScroll',
'useSize',
'useFocusWithin',
'useSwipe',
],
},
{
Expand Down
2 changes: 2 additions & 0 deletions packages/hooks/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ import useVirtualList from './useVirtualList';
import useWebSocket from './useWebSocket';
import useWhyDidYouUpdate from './useWhyDidYouUpdate';
import useMutationObserver from './useMutationObserver';
import useSwipe from './useSwipe';

export {
useRequest,
Expand Down Expand Up @@ -156,4 +157,5 @@ export {
useRafTimeout,
useResetState,
useMutationObserver,
useSwipe,
};
46 changes: 46 additions & 0 deletions packages/hooks/src/useSwipe/__tests__/index.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { renderHook, waitFor } from '@testing-library/react';
import useSwipe from '../index';
import { useRef } from 'react';

describe('useSwipe', () => {
function touchStart(x: number, y: number) {
document.body.dispatchEvent(
new TouchEvent('touchmove', {
touches: [
{
clientX: x,
clientY: y,
pageX: x,
pageY: y,
} as any,
],
}),
);
}

it('should return init value', () => {
const hook = renderHook(() => {
const ref = useRef(document.body);

return useSwipe(ref);
});
expect(hook.result.current).toStrictEqual({
lengthX: 0,
lengthY: 0,
direction: null,
isSwiping: false,
});
});

it('touch move direction', async () => {
const hook = renderHook(() => {
const ref = useRef(document.body);

return useSwipe(ref);
});

touchStart(-100, -50);
await waitFor(() => expect(hook.result.current.lengthX).not.toEqual(0));
expect(hook.result.current.direction).toBe('left');
});
});
94 changes: 94 additions & 0 deletions packages/hooks/src/useSwipe/demo/demo1.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
/**
* title: Basic usage
* desc: useSwipe
*
* title.zh-CN: 基础用法
* desc.zh-CN: useSwipe
*/

import React, { useEffect, useMemo, useRef, useState } from 'react';
import { useSwipe } from 'ahooks';

export default () => {
const el = useRef<HTMLDivElement>(null);
const containerWidth = useMemo(() => el.current?.offsetWidth || 1, [el.current]);
const [elStyle, setElStyle] = useState<React.CSSProperties>({
opacity: 1,
left: 0,
});

const { isSwiping, direction, lengthX, lengthY } = useSwipe(el, {
onSwipeEnd() {
if (lengthX < 0 && containerWidth && Math.abs(lengthX) / containerWidth >= 0.5) {
setElStyle({
transition: 'all',
transitionDuration: '250ms',
left: '100%',
opacity: 0,
});
} else {
setElStyle({
left: '0',
opacity: 1,
});
}
},
});

useEffect(() => {
let opacity = 1;
let left = '0';

if (lengthX < 0) {
left = `${-lengthX}px`;
opacity = 1.1 - Math.abs(lengthX) / (el.current?.offsetWidth || 1);
}

setElStyle({
left,
opacity,
});
}, [lengthX]);

return (
<div>
<div
ref={el}
style={{
position: 'relative',
border: '1px solid #e8e8e8',
padding: 8,
width: '90%',
textAlign: 'center',
background: '#4e66d1',
color: 'white',
...elStyle,
}}
>
<p>Swipe right</p>
</div>
<div
style={{
display: 'flex',
justifyContent: 'center',
marginTop: 20,
}}
onClick={() =>
setElStyle({
opacity: 1,
left: 0,
})
}
>
<button>reset</button>
</div>
<div style={{ marginTop: 20, textAlign: 'center' }}>
<p>isSwiping: {String(isSwiping)}</p>
<p>direction: {direction}</p>
<p>
lengthX: {lengthX} | lengthY: {lengthY}
</p>
</div>
</div>
);
};
115 changes: 115 additions & 0 deletions packages/hooks/src/useSwipe/index.en-US.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
---
nav:
path: /hooks
---

# useSwipe

A swipe detection based on [TouchEvents](https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent), provide some basic abilities for developer to handle swipe gesture.

## Examples

### Basic Usage

<code src="./demo/demo1.tsx" />

### API

```typescript jsx
function App() {
const el = useRef<HTMLDivElement>(null)
const { isSwiping, direction, lengthX, lengthY } = useSwipe(el, {
passive: false,
threshold: 100,
onSwipeStart(e) {},
onSwipeMove(e, direction) {},
onSwipeEnd(e, diretion) {},
})

return <>
<div ref={el}>
Swiping here
</div>
<div>
<p>isSwiping: {String(isSwiping)}</p>
<p>direction: {direction}</p>
<p>
lengthX: {lengthX} | lengthY: {lengthY}
</p>
</div>
</>
}
```

### Params

| Property | Description | Type | Default |
| -------- | ------------------------------------------------- | ------------- | ------- |
| el | DOM elements or Ref | `HTMLElement` | - |
| options | Options, for more detail please refer `Interface` | `Options` | - |

### Result

| Property | Description | Type | Default |
| --------- | ----------------- | --------- | ------- |
| isSwiping | Is swiping | `boolean` | - |
| direction | Swiping direction | `string` | - |
| lengthX | Swiping clientX | `number` | - |
| lengthY | Swiping clientY | `number` | - |

### Interface

```typescript
export type UseSwipeDirection = 'up' | 'down' | 'left' | 'right' | null;

export interface UseSwipeOptions {
/**
* Register events as passive
*
* @default true
*/
passive?: boolean;

/**
* @default 50
*/
threshold?: number;

/**
* Callback when start swipe
*/
onSwipeStart?: (e: TouchEvent) => void;

/**
* Callback on swiping
*/
onSwipe?: (e: TouchEvent, direction: UseSwipeDirection) => void;

/**
* Callback on swiping end
*/
onSwipeEnd?: (e: TouchEvent, direction: UseSwipeDirection) => void;
}

export interface UseSwipeReturn {
/**
* Is swiping
*/
isSwiping: boolean;

/**
* Touches clientX
*/
lengthX: number;

/**
* Touches clientY
*/
lengthY: number;

/**
* Swiping direction
*/
direction: UseSwipeDirection;
}
```
105 changes: 105 additions & 0 deletions packages/hooks/src/useSwipe/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
import type { UseSwipeDirection, UseSwipeOptions, UseSwipeReturn } from './types';
import type { MutableRefObject, RefObject } from 'react';
import { useCallback, useEffect, useMemo, useState } from 'react';

export default function useSwipe(
elRef: RefObject<HTMLElement> | MutableRefObject<HTMLElement>,
options: UseSwipeOptions = {},
): UseSwipeReturn {
const { threshold = 50, passive = true } = options;

const [isSwiping, setIsSwiping] = useState(false);
const [coordsStart, setCoordsStart] = useState({ x: 0, y: 0 });
const [coordsEnd, setCoordsEnd] = useState({ x: 0, y: 0 });

const diffX = useMemo(() => coordsStart.x - coordsEnd.x, [coordsStart.x, coordsEnd.y]);
const diffY = useMemo(() => coordsStart.y - coordsEnd.y, [coordsStart.y, coordsEnd.y]);

const { max, abs } = Math;

const isThresholdExceeded = useMemo(
() => max(abs(diffX), abs(diffY)) >= threshold,
[diffX, diffY],
);

const direction = useMemo<UseSwipeDirection>(() => {
if (!isThresholdExceeded) {
return null;
}

if (abs(diffX) > abs(diffY)) {
return diffX > 0 ? 'left' : 'right';
} else {
return diffY > 0 ? 'up' : 'down';
}
}, [diffX, diffY]);

const getTouchEventCoords = (e: TouchEvent) => [e.touches[0].clientX, e.touches[0].clientY];

const updateCoordsStart = (e: TouchEvent) => {
const [x, y] = getTouchEventCoords(e);
setCoordsStart({ x, y });
};

const updateCoordsEnd = (e: TouchEvent) => {
const [x, y] = getTouchEventCoords(e);

setCoordsEnd({ x, y });
};

const swipeReturn: UseSwipeReturn = {
isSwiping,
direction,
lengthX: diffX,
lengthY: diffY,
};

const touchStartListener = useCallback((event: TouchEvent) => {
updateCoordsStart(event);
updateCoordsEnd(event);
options.onSwipeStart?.(event);
}, []);

const touchMoveListener = useCallback(
(event: TouchEvent) => {
updateCoordsEnd(event);

if (!isSwiping && isThresholdExceeded) {
setIsSwiping(true);
}

console.log(isSwiping, isThresholdExceeded);

if (isSwiping) {
options.onSwipe?.(event, direction);
}
},
[isSwiping, isThresholdExceeded],
);

const touchEndListener = useCallback(
(event: TouchEvent) => {
options.onSwipeEnd?.(event, direction);
setIsSwiping(false);
},
[swipeReturn],
);

useEffect(() => {
const el = elRef.current!;

el.addEventListener('touchstart', touchStartListener, { passive });

el.addEventListener('touchmove', touchMoveListener, { passive });

el.addEventListener('touchend', touchEndListener, { passive });

return () => {
el.removeEventListener('touchstart', touchStartListener);
el.removeEventListener('touchmove', touchMoveListener);
el.removeEventListener('touchend', touchEndListener);
};
}, [swipeReturn]);

return swipeReturn;
}
Loading