├── .circleci
└── config.yml
├── .gitignore
├── .npmignore
├── .release-it.json
├── LICENSE
├── README.md
├── example
├── .gitignore
├── .watchmanconfig
├── App.js
├── app.json
├── assets
│ ├── demo-coil.gif
│ ├── demo-gesture-recorder.gif
│ ├── demo-multiple-gestures.gif
│ └── demo-triangle.gif
├── babel.config.js
├── package.json
├── src
│ └── Screen
│ │ ├── Coil.js
│ │ ├── CreateGesture.js
│ │ ├── MultipleGestures.js
│ │ └── Triangle.js
└── yarn.lock
├── img
├── logo-emoji.png
├── logo.png
└── social-poster.png
├── jest.config.js
├── jest
└── setupEnzymeAfterEnv.js
├── package.json
├── prettier.config.js
├── src
├── Cursor.tsx
├── GestureDetector.tsx
├── GesturePath.tsx
├── GestureRecorder.tsx
├── Types.ts
├── __tests__
│ └── useGestureStore.unit.test.js
├── index.ts
├── useDetector.ts
├── useGestureStore.ts
└── useRecorder.ts
├── tsconfig.json
└── yarn.lock
/.circleci/config.yml:
--------------------------------------------------------------------------------
1 | version: 2
2 |
3 | defaults: &defaults
4 | docker:
5 | - image: circleci/node:10.21
6 | working_directory: ~/project
7 |
8 | # dependencies:
9 | # pre:
10 | # - rm -rf ~/.yarn
11 | # - npm install -g yarn
12 | # - yarn -v
13 | # override:
14 | # - yarn
15 | # cache_directories:
16 | # - ~/.cache/yarn
17 |
18 | jobs:
19 | install-dependencies:
20 | <<: *defaults
21 | steps:
22 | - checkout
23 | - attach_workspace:
24 | at: ~/project
25 | - restore_cache:
26 | keys:
27 | - v1-dependencies-{{ checksum "package.json" }}
28 | - v1-dependencies-
29 | - run: |
30 | yarn install --frozen-lockfile
31 | - save_cache:
32 | key: v1-dependencies-{{ checksum "package.json" }}
33 | paths: node_modules
34 | - persist_to_workspace:
35 | root: .
36 | paths: .
37 | lint-and-typecheck:
38 | <<: *defaults
39 | steps:
40 | - attach_workspace:
41 | at: ~/project
42 | - run: |
43 | yarn tslint
44 | unit-tests:
45 | <<: *defaults
46 | steps:
47 | - attach_workspace:
48 | at: ~/project
49 | - run: |
50 | yarn test --coverage
51 |
52 | workflows:
53 | version: 2
54 | build-and-test:
55 | jobs:
56 | - install-dependencies
57 | - lint-and-typecheck:
58 | requires:
59 | - install-dependencies
60 | - unit-tests:
61 | requires:
62 | - install-dependencies
63 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | dist
2 | node_modules
3 | .DS_Store
4 | .jest
--------------------------------------------------------------------------------
/.npmignore:
--------------------------------------------------------------------------------
1 | tsconfig.json
2 | src
3 | example
4 | .DS_Store
5 | img
6 | .jest
7 | jest
8 | jest.config.js
9 | .circleci
10 | __tests__
--------------------------------------------------------------------------------
/.release-it.json:
--------------------------------------------------------------------------------
1 | {
2 | "git": {
3 | "commitMessage": "chore: release %s",
4 | "tagName": "v%s"
5 | },
6 | "npm": {
7 | "publish": true
8 | },
9 | "github": {
10 | "release": true
11 | },
12 | "plugins": {
13 | "@release-it/conventional-changelog": {
14 | "preset": "angular"
15 | }
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2019 Maxim Zubarev
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | React Native Gesture Detector
7 | Create and detect custom gestures on React Native.
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 | ## Demos
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 | ### Example app and usage
35 |
36 | Feel free to test [Snack Expo demo](https://snack.expo.io/@mxmzb/react-native-gesture-detector) or run the included demo app locally:
37 |
38 | ```sh
39 | $ git clone https://github.com/mxmzb/react-native-gesture-detector.git
40 | $ cd react-native-gesture-detector/example
41 | $ yarn
42 | $ yarn start
43 | ```
44 |
45 | Check [the code for the screens](https://github.com/mxmzb/react-native-gesture-detector/tree/master/example/src/Screen) to see how they are done!
46 |
47 | ## Intro
48 |
49 | This package originated from a real life **need to detect custom gestures**. The idea for implementation originated from this [stellar answer](https://stackoverflow.com/questions/20821358/gesture-detection-algorithm-based-on-discrete-points) on StackOverflow. The result is not 100% foolproof, but rock solid, performant and extremely simple to use.
50 |
51 | The package comes with another, insanely cool component `GestureRecorder`, which allows you to create gestures **on the fly**. Yep, just plug it in, paint the gesture and you will receive the coordinate data for your supercomplex, custom gesture. You can use it to just **use the data points as a predefined gesture** in your app, or **you can even let your app users create their own custom gestures**, if that fits your game plan!
52 |
53 | Because the library significantly uses React hooks, you must use at least `react@16.8.0`.
54 |
55 | ## Installation
56 |
57 | ```sh
58 | $ yarn add react-native-gesture-detector
59 | $ yarn add react-native-gesture-handler lodash # install peer dependencies
60 | ```
61 |
62 | ## Quickstart
63 |
64 | ```jsx
65 | import GestureDetector, {
66 | GestureRecorder,
67 | GesturePath,
68 | Cursor,
69 | } from "react-native-gesture-detector";
70 |
71 | const gestures = {
72 | // this will result in the gesture shown in the first demo give above
73 | Coil: [
74 | { x: 10, y: -30 }, // This is a coordinate object
75 | { x: 25, y: -15 },
76 | { x: 40, y: -10 },
77 | { x: 55, y: -15 },
78 | { x: 70, y: -30 },
79 | { x: 85, y: -45 },
80 | { x: 90, y: -65 },
81 | { x: 85, y: -85 },
82 | { x: 70, y: -100 },
83 | { x: 55, y: -115 },
84 | { x: 40, y: -130 },
85 | { x: 20, y: -130 },
86 | { x: 0, y: -130 },
87 | { x: -20, y: -130 },
88 | { x: -35, y: -115 },
89 | { x: -50, y: -100 },
90 | { x: -65, y: -85 },
91 | { x: -80, y: -70 },
92 | { x: -80, y: -55 },
93 | { x: -80, y: -30 },
94 | { x: -80, y: -15 },
95 | { x: -80, y: 0 },
96 | { x: -65, y: 15 },
97 | { x: -50, y: 30 },
98 | { x: -35, y: 45 },
99 | { x: -20, y: 60 },
100 | { x: 0, y: 65 },
101 | { x: 20, y: 70 },
102 | { x: 40, y: 70 },
103 | ],
104 | };
105 |
106 | const CoilExample = () => (
107 | console.log(`Gesture "${gesture}" finished!`)}
109 | onProgress={({ gesture, progress }) => {
110 | console.log(`Gesture: ${gesture}, progress: ${progress}`);
111 | }}
112 | onPanRelease={() => {
113 | console.log("User released finger!");
114 | }}
115 | gestures={gestures}
116 | slopRadius={35}
117 | >
118 | {({ coordinate }) => (
119 |
120 |
121 | {coordinate && }
122 |
123 | )}
124 |
125 | );
126 |
127 | const RecordGestureExample = () => {
128 | // finishedGesture will look like gestures["Coil"] from the top
129 | const [finishedGesture, setFinishedGesture] = useState([]);
130 |
131 | return (
132 | setFinishedGesture(gesture)}>
133 | {({ gesture }) => (
134 |
135 |
136 |
137 | )}
138 |
139 | );
140 | };
141 | ```
142 |
143 | ## Documentation and API
144 |
145 | ### `GestureDetector`
146 |
147 | `GestureDetector` is a render props component. The child function has the form `children({ coordinate: { x: number, y: number } })`
148 |
149 | | Prop | Default | Type | Description |
150 | | :---------------- | :-----------------------------: | :---------------------------------------------: | :------------------------------------------------------------------------------------------------------------------------------------------------ |
151 | | `slopRadius` | 50 | `number` | The radius in px from a coordinate. The resulting circle is the area in which the user can move the finger |
152 | | `gestures` | `{}` | `{ [key: string]: [{ x: number, y: number }] }` | An object with one or more gestures. A gesture is an array of `{ x, y }` objects, which symbolize the exact coordinates you want the user to pass |
153 | | `onProgress` | `({ progress, gesture }) => {}` | `function` | A callback, which is called on each predefined gesture coordinate passed by the user. |
154 | | `onGestureFinish` | `(gesture) => {}` | `function` | A callback, which is called when the user finishes a gesture. Receives the gesture key of the finished gesture. |
155 | | `onPanRelease` | `() => {}` | `function` | Callback, when the user releases the finger. Receives no arguments. |
156 |
157 | ### `GestureRecorder`
158 |
159 | `GestureRecorder` is a render props component. The child function has the form `children({ gesture: [{ x: string, y: string }, { x: string, y: string }, ...], gestureDirectionHistory: [{ x: string, y: string }, { x: string, y: string }, ...], offset: { x: number, y: number } })`.
160 |
161 | `gesture` is an array of coordinates. They are generated based on the `pointDistance` prop of the component.
162 |
163 | `gestureDirectionHistory` will tell you accordingly to `gesture` which direction the gesture is moving there. This might give somewhat unreliable data currently. A direction object looks like `{ x: "left", y: "up" }`.
164 |
165 | `offset` will artificially add an horizontal and vertical offset to the coordinates. This does not change the detection of the defined gesture at all. It's just a helper to use with the `GesturePath` component to paint the path where you actually draw. Check the [`GestureRecorder` example screen](https://github.com/mxmzb/react-native-gesture-detector/blob/master/example/src/Screen/CreateGesture.js) for more details on this.
166 |
167 | | Prop | Default | Type | Description |
168 | | :-------------- | :---------------: | :--------: | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
169 | | `pointDistance` | 20 | `number` | The minimum distance between points that you want to be recorded. So default wise, every 20px (or more, usually depending on the phone hardware and the speed of the finger moving over the display) the component will add another point to the `gesture` array |
170 | | `onCapture` | `() => {}` | `function` | A callback, which is called every time the component is adding a coordinate to the `gesture` array |
171 | | `onPanRelease` | `(gesture) => {}` | `function` | Callback, when the user releases the finger. Receives the fully drawn gesture in form of a coordinate array. |
172 |
173 | ### `GesturePath`
174 |
175 | `GesturePath` is a helper component, which paints a gesture visually in a container. The container should have `position: absolute;` set in its style property. `{ x, y }` is a coordinate object. An array of coordinate objects must be passed to paint the gesture on the screen. This component should be only used in development to define and refine gestures.
176 |
177 | | Prop | Default | Type | Description |
178 | | :----------- | :-----: | :------: | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
179 | | `path` | `[]` | `array` | An array of coordinates to paint the gesture |
180 | | `slopRadius` | `50` | `number` | The radius around each coordinate, in which the user touch event will be associated with the gesture (or rather the radius of the circle being painted for each coordinate, as this whole component has no functionality really and is purely visual) |
181 | | `color` | `black` | `string` | A string of a valid CSS color property |
182 |
183 | ### `Cursor`
184 |
185 | Paints a black, round indicator at the passed coordinate. The only useful situation is in development and you probably will use it like this, where `coordinate` is passed from the [`GestureDetector`](#gesturedetector) render props function:
186 |
187 | `{coordinate && }`
188 |
189 | | Prop | Default | Type | Description |
190 | | :----------- | :-----------------------------------------: | :------: | :--------------------------------------------------------------------------------------------------------------------------------------- |
191 | | `x` | `0` | `number` | The coordinate of the absolute center of the cursor relatively to the parent container. |
192 | | `y` | `0` | `number` | The coordinate of the absolute center of the cursor relatively to the parent container. |
193 | | `throttleMs` | `50` in dev build, `25` in production build | `number` | A performance optimization. Sets the time delay between each rerender of the repositioned cursor. You probably don't want to touch this. |
194 |
195 | ## License
196 |
197 | `react-native-gesture-detector` is licensed under the [MIT](https://github.com/mxmzb/react-native-gesture-detector/blob/master/LICENSE).
198 |
--------------------------------------------------------------------------------
/example/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules/**/*
2 | .expo/*
3 | .expo-shared/*
4 | npm-debug.*
5 | *.jks
6 | *.p8
7 | *.p12
8 | *.key
9 | *.mobileprovision
10 | *.orig.*
11 | web-build/
12 | web-report/
13 |
--------------------------------------------------------------------------------
/example/.watchmanconfig:
--------------------------------------------------------------------------------
1 | {}
2 |
--------------------------------------------------------------------------------
/example/App.js:
--------------------------------------------------------------------------------
1 | import { createAppContainer } from "react-navigation";
2 | import { createDrawerNavigator } from "react-navigation-drawer";
3 |
4 | import MultipleGesturesScreen from "./src/Screen/MultipleGestures";
5 | import TriangleScreen from "./src/Screen/Triangle";
6 | import CoilScreen from "./src/Screen/Coil";
7 | import CreateGestureScreen from "./src/Screen/CreateGesture";
8 |
9 | const DrawerNavigator = createDrawerNavigator(
10 | {
11 | MultipleGestures: {
12 | screen: MultipleGesturesScreen,
13 | },
14 | Triangle: {
15 | screen: TriangleScreen,
16 | },
17 | Coil: {
18 | screen: CoilScreen,
19 | },
20 | CreateGesture: {
21 | screen: CreateGestureScreen,
22 | },
23 | },
24 | {
25 | initialRouteName: "CreateGesture",
26 | },
27 | );
28 |
29 | const App = createAppContainer(DrawerNavigator);
30 |
31 | export default App;
32 |
--------------------------------------------------------------------------------
/example/app.json:
--------------------------------------------------------------------------------
1 | {
2 | "expo": {
3 | "name": "RNGestureDetector",
4 | "slug": "example",
5 | "privacy": "public",
6 | "sdkVersion": "34.0.0",
7 | "platforms": ["ios", "android", "web"],
8 | "version": "1.0.0",
9 | "orientation": "portrait",
10 | "updates": {
11 | "fallbackToCacheTimeout": 0
12 | },
13 | "assetBundlePatterns": ["**/*"],
14 | "ios": {
15 | "supportsTablet": true
16 | }
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/example/assets/demo-coil.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mxmzb/react-native-gesture-detector/5ce19dd60b62f20eba2800646a2e1d33d30e71a0/example/assets/demo-coil.gif
--------------------------------------------------------------------------------
/example/assets/demo-gesture-recorder.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mxmzb/react-native-gesture-detector/5ce19dd60b62f20eba2800646a2e1d33d30e71a0/example/assets/demo-gesture-recorder.gif
--------------------------------------------------------------------------------
/example/assets/demo-multiple-gestures.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mxmzb/react-native-gesture-detector/5ce19dd60b62f20eba2800646a2e1d33d30e71a0/example/assets/demo-multiple-gestures.gif
--------------------------------------------------------------------------------
/example/assets/demo-triangle.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mxmzb/react-native-gesture-detector/5ce19dd60b62f20eba2800646a2e1d33d30e71a0/example/assets/demo-triangle.gif
--------------------------------------------------------------------------------
/example/babel.config.js:
--------------------------------------------------------------------------------
1 | module.exports = function(api) {
2 | api.cache(true);
3 | return {
4 | presets: ['babel-preset-expo'],
5 | };
6 | };
7 |
--------------------------------------------------------------------------------
/example/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "main": "node_modules/expo/AppEntry.js",
3 | "scripts": {
4 | "start": "expo start",
5 | "android": "expo start --android",
6 | "ios": "expo start --ios",
7 | "web": "expo start --web",
8 | "eject": "expo eject"
9 | },
10 | "dependencies": {
11 | "expo": "^34.0.1",
12 | "lodash": "^4.17.19",
13 | "react": "16.8.3",
14 | "react-dom": "^16.8.6",
15 | "react-native": "https://github.com/expo/react-native/archive/sdk-34.0.0.tar.gz",
16 | "react-native-gesture-detector": "file:../",
17 | "react-native-gesture-handler": "~1.3.0",
18 | "react-native-reanimated": "~1.1.0",
19 | "react-native-web": "^0.11.4",
20 | "react-navigation": "^4.0.0",
21 | "react-navigation-drawer": "^2.0.1"
22 | },
23 | "devDependencies": {
24 | "babel-preset-expo": "^6.0.0"
25 | },
26 | "private": true
27 | }
28 |
--------------------------------------------------------------------------------
/example/src/Screen/Coil.js:
--------------------------------------------------------------------------------
1 | import React, { useState } from "react";
2 | import { SafeAreaView, View, Text, Alert } from "react-native";
3 | import GestureDetector, { GesturePath, Cursor } from "react-native-gesture-detector";
4 |
5 | const gestures = {
6 | Coil: [
7 | { x: 10, y: -30 },
8 | { x: 25, y: -15 },
9 | { x: 40, y: -10 },
10 | { x: 55, y: -15 },
11 | { x: 70, y: -30 },
12 | { x: 85, y: -45 },
13 | { x: 90, y: -65 },
14 | { x: 85, y: -85 },
15 | { x: 70, y: -100 },
16 | { x: 55, y: -115 },
17 | { x: 40, y: -130 },
18 | { x: 20, y: -130 },
19 | { x: 0, y: -130 },
20 | { x: -20, y: -130 },
21 | { x: -35, y: -115 },
22 | { x: -50, y: -100 },
23 | { x: -65, y: -85 },
24 | { x: -80, y: -70 },
25 | { x: -80, y: -55 },
26 | { x: -80, y: -30 },
27 | { x: -80, y: -15 },
28 | { x: -80, y: 0 },
29 | { x: -65, y: 15 },
30 | { x: -50, y: 30 },
31 | { x: -35, y: 45 },
32 | { x: -20, y: 60 },
33 | { x: 0, y: 65 },
34 | { x: 20, y: 70 },
35 | { x: 40, y: 70 },
36 | ],
37 | };
38 |
39 | const CoilScreen = () => {
40 | const [progress, setProgress] = useState(null);
41 | const [gesture, setGesture] = useState(null);
42 |
43 | return (
44 |
45 |
46 |
52 | Alert.alert(`Gesture ${gesture} finished!`)}
54 | onProgress={({ gesture, progress }) => {
55 | setProgress(progress);
56 | setGesture(gesture);
57 | }}
58 | onPanRelease={() => {
59 | setProgress(null);
60 | setGesture(null);
61 | }}
62 | gestures={gestures}
63 | >
64 | {({ coordinate }) => (
65 |
74 |
75 |
76 |
77 | {coordinate && }
78 |
79 | )}
80 |
81 |
82 |
83 |
93 | Gesture: {gesture}
94 | Progress: {progress}
95 |
96 |
97 |
98 | );
99 | };
100 |
101 | export default CoilScreen;
102 |
--------------------------------------------------------------------------------
/example/src/Screen/CreateGesture.js:
--------------------------------------------------------------------------------
1 | import React, { useState } from "react";
2 | import { SafeAreaView, View, Text, Alert } from "react-native";
3 | import _ from "lodash";
4 | import GestureDetector, {
5 | GesturePath,
6 | Cursor,
7 | GestureRecorder,
8 | } from "react-native-gesture-detector";
9 |
10 | const CreateGestureScreen = () => {
11 | const [recorderOffset, setRecorderOffset] = useState(null);
12 | const [detectorOffset, setDetectorOffset] = useState(null);
13 | const [finishedGesture, setFinishedGesture] = useState([]);
14 |
15 | return (
16 |
17 | {
19 | setFinishedGesture(gesture);
20 | setDetectorOffset(recorderOffset);
21 | }}
22 | >
23 | {({ gesture, offset }) => {
24 | if (!_.isEqual(offset, recorderOffset) && offset !== null) {
25 | setRecorderOffset(offset);
26 | }
27 |
28 | return (
29 |
38 |
39 | {
41 | if (recorderOffset) {
42 | return {
43 | x: coordinate.x + recorderOffset.x,
44 | y: coordinate.y + recorderOffset.y,
45 | };
46 | }
47 |
48 | return coordinate;
49 | })}
50 | color="green"
51 | slopRadius={30}
52 | center={false}
53 | />
54 |
55 |
56 | );
57 | }}
58 |
59 |
60 | Alert.alert(`Custom User Gesture finished!`)}
62 | gestures={{ CustomUserGesture: finishedGesture }}
63 | >
64 | {({ coordinate }) => (
65 |
74 |
75 | {
77 | if (detectorOffset) {
78 | return {
79 | x: coordinate.x + detectorOffset.x,
80 | y: coordinate.y + detectorOffset.y,
81 | };
82 | }
83 |
84 | return coordinate;
85 | })}
86 | color="green"
87 | slopRadius={30}
88 | center={false}
89 | />
90 |
91 | {coordinate && }
92 |
93 | )}
94 |
95 |
96 | );
97 | };
98 |
99 | export default CreateGestureScreen;
100 |
--------------------------------------------------------------------------------
/example/src/Screen/MultipleGestures.js:
--------------------------------------------------------------------------------
1 | import React, { useState } from "react";
2 | import { SafeAreaView, View, Text, Alert } from "react-native";
3 | import GestureDetector, { GesturePath, Cursor } from "react-native-gesture-detector";
4 |
5 | const gestures = {
6 | "Parabola Left": [
7 | { x: 0, y: 0 },
8 | { x: 0, y: 30 },
9 | { x: 0, y: 60 },
10 | { x: 0, y: 90 },
11 | { x: 0, y: 120 },
12 | { x: -15, y: 150 },
13 | { x: -45, y: 165 },
14 | { x: -75, y: 165 },
15 | { x: -105, y: 165 },
16 | ],
17 | "Straight Down": [
18 | { x: 0, y: 0 },
19 | { x: 0, y: 30 },
20 | { x: 0, y: 60 },
21 | { x: 0, y: 90 },
22 | { x: 0, y: 120 },
23 | { x: 0, y: 150 },
24 | { x: 0, y: 180 },
25 | { x: 0, y: 210 },
26 | { x: 0, y: 240 },
27 | ],
28 | "Straight Up": [
29 | { x: 0, y: 0 },
30 | { x: 0, y: -30 },
31 | { x: 0, y: -60 },
32 | { x: 0, y: -90 },
33 | { x: 0, y: -120 },
34 | { x: 0, y: -150 },
35 | { x: 0, y: -180 },
36 | { x: 0, y: -210 },
37 | { x: 0, y: -240 },
38 | { x: 0, y: -270 },
39 | ],
40 | "Parabola Right": [
41 | { x: 0, y: 0 },
42 | { x: 0, y: 30 },
43 | { x: 0, y: 60 },
44 | { x: 0, y: 90 },
45 | { x: 0, y: 120 },
46 | { x: 15, y: 150 },
47 | { x: 45, y: 165 },
48 | { x: 75, y: 165 },
49 | { x: 105, y: 165 },
50 | ],
51 | };
52 |
53 | const MultipleScreen = () => {
54 | const [progress, setProgress] = useState(null);
55 | const [gesture, setGesture] = useState(null);
56 |
57 | return (
58 |
59 |
60 |
66 | Alert.alert(`Gesture ${gesture} finished!`)}
68 | onProgress={({ gesture, progress }) => {
69 | setProgress(progress);
70 | setGesture(gesture);
71 | }}
72 | onPanRelease={() => {
73 | setProgress(null);
74 | setGesture(null);
75 | }}
76 | gestures={gestures}
77 | >
78 | {({ coordinate }) => (
79 |
88 |
89 |
90 |
91 |
92 |
93 |
94 | {coordinate && }
95 |
96 | )}
97 |
98 |
99 |
100 |
110 | Gesture: {gesture}
111 | Progress: {progress}
112 |
113 |
114 |
115 | );
116 | };
117 |
118 | export default MultipleScreen;
119 |
--------------------------------------------------------------------------------
/example/src/Screen/Triangle.js:
--------------------------------------------------------------------------------
1 | import React, { useState } from "react";
2 | import { SafeAreaView, View, Text, Alert } from "react-native";
3 | import GestureDetector, { GesturePath, Cursor } from "react-native-gesture-detector";
4 |
5 | const gestures = {
6 | Triangle: [
7 | { x: 0, y: 0 },
8 | { x: 10, y: 20 },
9 | { x: 20, y: 40 },
10 | { x: 30, y: 60 },
11 | { x: 40, y: 80 },
12 | { x: 50, y: 100 },
13 | { x: 60, y: 120 },
14 | { x: 70, y: 140 },
15 | { x: 80, y: 160 },
16 | { x: 60, y: 160 },
17 | { x: 40, y: 160 },
18 | { x: 20, y: 160 },
19 | { x: 0, y: 160 },
20 | { x: -20, y: 160 },
21 | { x: -40, y: 160 },
22 | { x: -60, y: 160 },
23 | { x: -80, y: 160 },
24 | { x: -70, y: 140 },
25 | { x: -60, y: 120 },
26 | { x: -50, y: 100 },
27 | { x: -40, y: 80 },
28 | { x: -30, y: 60 },
29 | { x: -20, y: 40 },
30 | { x: -10, y: 20 },
31 | { x: 0, y: 0 },
32 | ],
33 | };
34 |
35 | const TriangleScreen = () => {
36 | const [progress, setProgress] = useState(null);
37 | const [gesture, setGesture] = useState(null);
38 |
39 | return (
40 |
41 |
42 |
48 | Alert.alert(`Gesture ${gesture} finished!`)}
50 | onProgress={({ gesture, progress }) => {
51 | setProgress(progress);
52 | setGesture(gesture);
53 | }}
54 | onPanRelease={() => {
55 | setProgress(null);
56 | setGesture(null);
57 | }}
58 | gestures={gestures}
59 | >
60 | {({ coordinate }) => (
61 |
70 |
71 |
72 |
73 | {coordinate && }
74 |
75 | )}
76 |
77 |
78 |
79 |
89 | Gesture: {gesture}
90 | Progress: {progress}
91 |
92 |
93 |
94 | );
95 | };
96 |
97 | export default TriangleScreen;
98 |
--------------------------------------------------------------------------------
/img/logo-emoji.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mxmzb/react-native-gesture-detector/5ce19dd60b62f20eba2800646a2e1d33d30e71a0/img/logo-emoji.png
--------------------------------------------------------------------------------
/img/logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mxmzb/react-native-gesture-detector/5ce19dd60b62f20eba2800646a2e1d33d30e71a0/img/logo.png
--------------------------------------------------------------------------------
/img/social-poster.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mxmzb/react-native-gesture-detector/5ce19dd60b62f20eba2800646a2e1d33d30e71a0/img/social-poster.png
--------------------------------------------------------------------------------
/jest.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | verbose: true,
3 | preset: "react-native",
4 | transform: {
5 | "\\.jsx?$": "/node_modules/react-native/jest/preprocessor.js",
6 | "^.+\\.tsx?$": "ts-jest",
7 | },
8 | modulePaths: [""],
9 | globals: {
10 | "ts-jest": {
11 | babelConfig: true,
12 | diagnostics: false,
13 | },
14 | },
15 | transformIgnorePatterns: ["node_modules/(?!react-native|react-native-gesture-handler)/"],
16 | modulePathIgnorePatterns: [
17 | "example/node_modules/react-native/",
18 | "example/node_modules/react-native-gesture-handler/",
19 | ],
20 | testPathIgnorePatterns: ["node_modules", "dist"],
21 | setupFilesAfterEnv: ["jest-enzyme", "/jest/setupEnzymeAfterEnv.js"],
22 | testEnvironment: "enzyme",
23 | cacheDirectory: ".jest/cache",
24 | };
25 |
--------------------------------------------------------------------------------
/jest/setupEnzymeAfterEnv.js:
--------------------------------------------------------------------------------
1 | import "react-native";
2 | import "jest-enzyme";
3 | import Adapter from "enzyme-adapter-react-16";
4 | import Enzyme from "enzyme";
5 |
6 | /**
7 | * Set up Enzyme to mount to DOM, simulate events,
8 | * and inspect the DOM in tests.
9 | */
10 | Enzyme.configure({ adapter: new Adapter() });
11 |
12 | /**
13 | * Ignore some expected warnings
14 | * see: https://jestjs.io/docs/en/tutorial-react.html#snapshot-testing-with-mocks-enzyme-and-react-16
15 | * see https://github.com/Root-App/react-native-mock-render/issues/6
16 | */
17 |
18 | const originalConsoleError = console.error; // eslint-disable-line
19 | // eslint-disable-next-line
20 | console.error = (message) => {
21 | if (message.startsWith("Warning:")) {
22 | return;
23 | }
24 |
25 | originalConsoleError(message);
26 | };
27 |
28 | const originalConsoleLog = console.log; // eslint-disable-line
29 | // eslint-disable-next-line
30 | console.log = (descriptor, message) => {
31 | if (
32 | descriptor.startsWith("Warning:") ||
33 | ((typeof message === "string" || message instanceof String) && message.startsWith("Warning:"))
34 | ) {
35 | return;
36 | }
37 |
38 | if (
39 | descriptor.startsWith("TypeError:") ||
40 | ((typeof message === "string" || message instanceof String) && message.startsWith("TypeError:"))
41 | ) {
42 | return;
43 | }
44 |
45 | originalConsoleLog(message);
46 | };
47 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "react-native-gesture-detector",
3 | "version": "1.1.2",
4 | "description": "Easily define and detect custom gestures in React Native.",
5 | "homepage": "https://maximzubarev.com/projects/react-native-gesture-detector",
6 | "main": "dist/index.js",
7 | "types": "dist/index.d.ts",
8 | "repository": {
9 | "url": "git@github.com:mxmzb/react-native-gesture-detector.git",
10 | "type": "git"
11 | },
12 | "author": "Maxim Zubarev ",
13 | "license": "MIT",
14 | "scripts": {
15 | "build": "tsc -p .",
16 | "build:watch": "tsc --watch -p .",
17 | "tslint": "tsc --noEmit",
18 | "test": "jest",
19 | "release": "release-it"
20 | },
21 | "publishConfig": {
22 | "registry": "https://registry.npmjs.org/"
23 | },
24 | "peerDependencies": {
25 | "lodash": ">=0.1.0",
26 | "react": ">=16.8.0",
27 | "react-native": ">=0.59.0",
28 | "react-native-gesture-handler": ">=1.3.0"
29 | },
30 | "devDependencies": {
31 | "@release-it/conventional-changelog": "^1.1.0",
32 | "@types/enzyme": "^3.10.3",
33 | "@types/enzyme-adapter-react-16": "^1.0.5",
34 | "@types/jest": "^26.0.0",
35 | "@types/lodash": "^4.14.138",
36 | "@types/react": "^16.9.2",
37 | "@types/react-native": "^0.62.9",
38 | "babel-jest": "^26.1.0",
39 | "enzyme": "^3.10.0",
40 | "enzyme-adapter-react-16": "^1.14.0",
41 | "jest": "^26.1.0",
42 | "jest-enzyme": "^7.1.1",
43 | "react": ">=16.8.0",
44 | "react-dom": "^16.9.0",
45 | "react-native": "^0.62.2",
46 | "react-native-gesture-handler": "^1.4.1",
47 | "react-test-renderer": "^16.9.0",
48 | "release-it": "^13.6.4",
49 | "ts-jest": "^26.1.0",
50 | "typescript": "^3.6.2"
51 | },
52 | "keywords": [
53 | "react-native",
54 | "gesture",
55 | "custom-gestures",
56 | "detection",
57 | "react-native-component"
58 | ]
59 | }
60 |
--------------------------------------------------------------------------------
/prettier.config.js:
--------------------------------------------------------------------------------
1 | /* eslint-disable import/no-commonjs */
2 |
3 | module.exports = {
4 | printWidth: 100,
5 | tabWidth: 2,
6 | useTabs: false,
7 | semi: true,
8 | singleQuote: false,
9 | trailingComma: "all",
10 | bracketSpacing: true,
11 | };
12 |
--------------------------------------------------------------------------------
/src/Cursor.tsx:
--------------------------------------------------------------------------------
1 | import React, { useState, useEffect, useRef } from "react";
2 | import { Animated } from "react-native";
3 | import _ from "lodash";
4 |
5 | type CursorProps = {
6 | x: number;
7 | y: number;
8 | throttleMs: number;
9 | };
10 |
11 | const baseStyle = {
12 | position: "absolute",
13 | width: 30,
14 | height: 30,
15 | marginLeft: -15,
16 | marginTop: -15,
17 | borderRadius: 15,
18 | backgroundColor: "#555",
19 | borderWidth: 1,
20 | borderColor: "#000",
21 | zIndex: 999,
22 | };
23 |
24 | const Cursor = ({ x, y, throttleMs }: CursorProps) => {
25 | const [translateX] = useState(new Animated.Value(x));
26 | const [translateY] = useState(new Animated.Value(y));
27 |
28 | const throttledSetCoordinate = useRef(
29 | _.throttle(({ x, y }: { x: number; y: number }) => {
30 | translateX.setValue(x);
31 | translateY.setValue(y);
32 | }, throttleMs),
33 | );
34 |
35 | useEffect(() => throttledSetCoordinate.current({ x, y }), [x, y]);
36 |
37 | return (
38 |
50 | );
51 | };
52 |
53 | Cursor.defaultProps = {
54 | x: 0,
55 | y: 0,
56 | throttleMs: __DEV__ ? 50 : 25,
57 | };
58 |
59 | export default Cursor;
60 |
--------------------------------------------------------------------------------
/src/GestureDetector.tsx:
--------------------------------------------------------------------------------
1 | import React, { ReactNode } from "react";
2 | // @ts-ignore or we will break expo example
3 | import { PanGestureHandler, State } from "react-native-gesture-handler";
4 |
5 | import useDetector from "./useDetector";
6 | import useGestureStore from "./useGestureStore";
7 |
8 | import { PanGestureHandlerEventExtra, GestureDetectorsInterface, Coordinate } from "./Types";
9 |
10 | type Props = {
11 | children: (props: { coordinate: Coordinate | null; offset: Coordinate | null }) => ReactNode;
12 | slopRadius: number;
13 | gestures: { [key: string]: Coordinate[] };
14 | onProgress: (args: { progress: number; gesture: string }) => void;
15 | onGestureFinish: (gestureKey: string) => void;
16 | onPanRelease: () => void;
17 | };
18 |
19 | const GestureDetector = ({
20 | children,
21 | slopRadius,
22 | gestures,
23 | onProgress,
24 | onGestureFinish,
25 | onPanRelease,
26 | }: Props) => {
27 | const {
28 | reset: resetStore,
29 | addBreadcrumbToPath,
30 | coordinate,
31 | offset,
32 | setCoordinate,
33 | path,
34 | } = useGestureStore();
35 | const detectors: GestureDetectorsInterface = {};
36 | const gestureKeys: string[] = Object.keys(gestures);
37 |
38 | for (let i = 0; i < gestureKeys.length; i++) {
39 | const gestureKey = gestureKeys[i];
40 |
41 | const { reset: resetDetector } = useDetector({
42 | slopRadius,
43 | path,
44 | gesture: gestures[gestureKey],
45 | onProgress: progress => {
46 | onProgress({ gesture: gestureKeys[i], progress });
47 | },
48 | onGestureFinish: () => {
49 | onGestureFinish(gestureKeys[i]);
50 | },
51 | });
52 |
53 | detectors[gestureKey] = {
54 | reset: resetDetector,
55 | };
56 | }
57 |
58 | const reset = () => {
59 | resetStore();
60 | for (let i = 0; i < gestureKeys.length; i++) {
61 | const gestureKey = gestureKeys[i];
62 | detectors[gestureKey].reset();
63 | }
64 | };
65 |
66 | return (
67 | {
69 | addBreadcrumbToPath(nativeEvent);
70 | setCoordinate({ x: nativeEvent.x, y: nativeEvent.y });
71 | }}
72 | onHandlerStateChange={({ nativeEvent }: { nativeEvent: PanGestureHandlerEventExtra }) => {
73 | if (nativeEvent.state === State.END) {
74 | reset();
75 | onPanRelease();
76 | }
77 | }}
78 | >
79 | {children({ coordinate, offset })}
80 |
81 | );
82 | };
83 |
84 | GestureDetector.defaultProps = {
85 | gestures: {},
86 | slopRadius: 50,
87 | onProgress: () => {},
88 | onGestureFinish: () => {},
89 | onPanRelease: () => {},
90 | };
91 |
92 | export default GestureDetector;
93 |
--------------------------------------------------------------------------------
/src/GesturePath.tsx:
--------------------------------------------------------------------------------
1 | import React from "react";
2 | import { Animated, ViewStyle } from "react-native";
3 |
4 | interface Coordinate {
5 | x: number;
6 | y: number;
7 | }
8 |
9 | type GesturePathProps = {
10 | path: Coordinate[];
11 | color: string;
12 | slopRadius: number;
13 | center: boolean;
14 | };
15 |
16 | const GesturePath = ({ path, color, slopRadius, center = true }: GesturePathProps) => {
17 | const baseStyle: ViewStyle = {
18 | position: "absolute",
19 | top: center ? "50%" : 0,
20 | left: center ? "50%" : 0,
21 | opacity: 0.4,
22 | };
23 |
24 | return (
25 | <>
26 | {path.map((point, index) => (
27 |
38 | ))}
39 | >
40 | );
41 | };
42 |
43 | GesturePath.defaultProps = {
44 | path: [],
45 | slopRadius: 50,
46 | color: "black",
47 | };
48 |
49 | export default GesturePath;
50 |
--------------------------------------------------------------------------------
/src/GestureRecorder.tsx:
--------------------------------------------------------------------------------
1 | import React, { ReactNode } from "react";
2 | // @ts-ignore or we will break expo example
3 | import { PanGestureHandler, State } from "react-native-gesture-handler";
4 |
5 | import useGestureStore from "./useGestureStore";
6 | import useRecorder from "./useRecorder";
7 |
8 | import { PanGestureHandlerEventExtra, Coordinate, Direction } from "./Types";
9 |
10 | type Props = {
11 | children: (props: {
12 | gesture: Coordinate[];
13 | gestureDirectionHistory: Direction[];
14 | offset: Coordinate | null;
15 | }) => ReactNode;
16 | pointDistance: number;
17 | onCapture: () => void;
18 | onPanRelease: (gesture: Coordinate[]) => void;
19 | };
20 |
21 | const GestureCapture = ({ children, onCapture, onPanRelease, pointDistance }: Props) => {
22 | const { reset: resetStore, addBreadcrumbToPath, setCoordinate, path, offset } = useGestureStore();
23 | const { reset: resetRecorder, gesture, gestureDirectionHistory } = useRecorder({
24 | path,
25 | pointDistance,
26 | onCapture,
27 | });
28 |
29 | const reset = () => {
30 | resetStore();
31 | resetRecorder();
32 | };
33 |
34 | return (
35 | {
37 | addBreadcrumbToPath(nativeEvent);
38 | setCoordinate({ x: nativeEvent.x, y: nativeEvent.y });
39 | }}
40 | onHandlerStateChange={({ nativeEvent }: { nativeEvent: PanGestureHandlerEventExtra }) => {
41 | if (nativeEvent.state === State.END) {
42 | reset();
43 | onPanRelease(gesture);
44 | }
45 | }}
46 | >
47 | {children({ gesture, gestureDirectionHistory, offset })}
48 |
49 | );
50 | };
51 |
52 | GestureCapture.defaultProps = {
53 | pointDistance: 20,
54 | onCapture: () => {},
55 | onPanRelease: () => {},
56 | };
57 |
58 | export default GestureCapture;
59 |
--------------------------------------------------------------------------------
/src/Types.ts:
--------------------------------------------------------------------------------
1 | import { ReactNode } from "react";
2 | // @ts-ignore or we will break expo example
3 | import { State } from "react-native-gesture-handler";
4 |
5 | export interface PanGestureHandlerEventExtra {
6 | state: State;
7 | x: number;
8 | y: number;
9 | absoluteX: number;
10 | absoluteY: number;
11 | translationX: number;
12 | translationY: number;
13 | velocityX: number;
14 | velocityY: number;
15 | }
16 |
17 | export interface Coordinate {
18 | x: number;
19 | y: number;
20 | }
21 |
22 | export interface Direction {
23 | x: "left" | "right" | null;
24 | y: "up" | "down" | null;
25 | }
26 |
27 | export interface Detector {
28 | reset: () => void;
29 | }
30 |
31 | export interface GestureDetectorsInterface {
32 | [key: string]: Detector;
33 | }
34 |
--------------------------------------------------------------------------------
/src/__tests__/useGestureStore.unit.test.js:
--------------------------------------------------------------------------------
1 | import React from "react";
2 | import { Animated } from "react-native";
3 | import { mount } from "enzyme";
4 |
5 | import GesturePath from "../GesturePath";
6 |
7 | describe("", () => {
8 | it("renders 3 coordinate points", () => {
9 | const wrapper = mount(
10 | ,
17 | );
18 | expect(wrapper.find(Animated.View)).toHaveLength(3);
19 | });
20 | });
21 |
--------------------------------------------------------------------------------
/src/index.ts:
--------------------------------------------------------------------------------
1 | import GestureDetector from "./GestureDetector";
2 | import GesturePath from "./GesturePath";
3 | import Cursor from "./Cursor";
4 | import GestureRecorder from "./GestureRecorder";
5 |
6 | export { GesturePath, Cursor, GestureRecorder };
7 |
8 | export default GestureDetector;
9 |
--------------------------------------------------------------------------------
/src/useDetector.ts:
--------------------------------------------------------------------------------
1 | import { useState, useEffect } from "react";
2 |
3 | import { Coordinate } from "./Types";
4 |
5 | type Props = {
6 | path: Coordinate[];
7 | slopRadius: number;
8 | gesture: Coordinate[];
9 | onProgress: (progress: number) => void;
10 | onGestureFinish: () => void;
11 | };
12 |
13 | const useDetector = ({ gesture, path, slopRadius, onProgress, onGestureFinish }: Props) => {
14 | const [currentPathCoordinateIndex, setCurrentPathCoordinateIndex] = useState(0);
15 | const [matchedGestureCoordinates, setMatchedGestureCoordinates] = useState(0);
16 |
17 | useEffect(() => compute(), [
18 | gesture,
19 | path,
20 | currentPathCoordinateIndex,
21 | matchedGestureCoordinates,
22 | slopRadius,
23 | onProgress,
24 | onGestureFinish,
25 | ]);
26 |
27 | const reset = () => {
28 | setCurrentPathCoordinateIndex(0);
29 | setMatchedGestureCoordinates(0);
30 | };
31 |
32 | const compute = () => {
33 | if (
34 | currentPathCoordinateIndex < path.length - 1 &&
35 | matchedGestureCoordinates < gesture.length
36 | ) {
37 | if (
38 | coordinateIsInRange({
39 | gestureCoordinate: gesture[matchedGestureCoordinates],
40 | candidateCoordinate: path[currentPathCoordinateIndex],
41 | radius: slopRadius,
42 | })
43 | ) {
44 | onProgress((matchedGestureCoordinates + 1) / gesture.length);
45 |
46 | if (matchedGestureCoordinates + 1 === gesture.length) {
47 | onGestureFinish();
48 | }
49 |
50 | setMatchedGestureCoordinates(state => state + 1);
51 | }
52 |
53 | setCurrentPathCoordinateIndex(state => state + 1);
54 | }
55 | };
56 |
57 | const coordinateIsInRange = ({
58 | gestureCoordinate,
59 | candidateCoordinate,
60 | radius,
61 | }: {
62 | gestureCoordinate: Coordinate;
63 | candidateCoordinate: Coordinate;
64 | radius: number;
65 | }) =>
66 | Math.pow(candidateCoordinate.x - gestureCoordinate.x, 2) +
67 | Math.pow(candidateCoordinate.y - gestureCoordinate.y, 2) <
68 | Math.pow(radius, 2);
69 |
70 | return {
71 | reset,
72 | };
73 | };
74 |
75 | export default useDetector;
76 |
--------------------------------------------------------------------------------
/src/useGestureStore.ts:
--------------------------------------------------------------------------------
1 | import { useState } from "react";
2 | import { Coordinate, PanGestureHandlerEventExtra } from "./Types";
3 |
4 | const useGestureStore = () => {
5 | const [coordinate, setCoordinate] = useState(null);
6 | const [startCoordinate, setStartCoordinate] = useState(null);
7 | const [path, setPath] = useState([]);
8 |
9 | const reset = () => {
10 | setCoordinate(null);
11 | setStartCoordinate(null);
12 | setPath([]);
13 | };
14 |
15 | const addBreadcrumbToPath = ({ x, y }: PanGestureHandlerEventExtra) => {
16 | if (!startCoordinate) {
17 | setStartCoordinate({ x, y });
18 | setPath([{ x: 0, y: 0 }]);
19 | } else {
20 | const normalizedCoordinate = normalizeCoordinate({ x, y });
21 | if (normalizedCoordinate) {
22 | setPath(state => [...state, normalizedCoordinate]);
23 | }
24 | }
25 | };
26 |
27 | const normalizeCoordinate = ({ x, y }: { x: number; y: number }) =>
28 | startCoordinate
29 | ? {
30 | x: x - startCoordinate.x,
31 | y: y - startCoordinate.y,
32 | }
33 | : null;
34 |
35 | return {
36 | path,
37 | coordinate,
38 | offset: startCoordinate,
39 | addBreadcrumbToPath,
40 | setCoordinate,
41 | reset,
42 | };
43 | };
44 |
45 | export default useGestureStore;
46 |
--------------------------------------------------------------------------------
/src/useRecorder.ts:
--------------------------------------------------------------------------------
1 | import { useEffect, useState } from "react";
2 |
3 | import { Coordinate, Direction } from "./Types";
4 |
5 | type Props = {
6 | pointDistance: number;
7 | path: Coordinate[];
8 | onCapture: () => void;
9 | };
10 |
11 | // point and coordinate are essentially interface. the difference is merely,
12 | // that i find "point" more clear for the outside user (e.g. "pointDistance" sounds
13 | // clearer imho than "coordinateDistance"), while coordinate is just an internal
14 | // variable name
15 | const useRecorder = ({ path, pointDistance, onCapture }: Props) => {
16 | const [pathIndex, setPathIndex] = useState(0);
17 | const [gesture, setGesture] = useState([]);
18 | // first element is null, as we don't have a direction with only one coordinate
19 | const [gestureDirectionHistory, setGestureDirectionHistory] = useState([
20 | { x: null, y: null },
21 | ]);
22 |
23 | useEffect(() => {
24 | if (pathIndex < path.length - 1) {
25 | if (JSON.stringify(path[pathIndex]) !== JSON.stringify(path[pathIndex + 1])) {
26 | if (gesture.length === 0) {
27 | setGesture([{ x: path[0].x, y: path[0].y }]);
28 | } else {
29 | if (calculateDistance(gesture[gesture.length - 1], path[pathIndex]) >= pointDistance) {
30 | const nextDirection = calculateDirection(gesture[gesture.length - 1], path[pathIndex]);
31 | setGestureDirectionHistory(state => [...state, nextDirection]);
32 | setGesture(state => [...state, path[pathIndex]]);
33 | onCapture();
34 | }
35 | }
36 | }
37 | setPathIndex(state => state + 1);
38 | }
39 | }, [gesture, path, pointDistance, pathIndex]);
40 |
41 | const reset = () => {
42 | setPathIndex(0);
43 | setGesture([]);
44 | setGestureDirectionHistory([{ x: null, y: null }]);
45 | };
46 |
47 | const calculateDirection = (pointA: Coordinate, pointB: Coordinate): Direction => {
48 | let x = null,
49 | y = null;
50 |
51 | if (pointA.x < pointB.x) {
52 | x = "right";
53 | }
54 |
55 | if (pointA.x > pointB.x) {
56 | x = "left";
57 | }
58 |
59 | if (pointA.y < pointB.y) {
60 | y = "down";
61 | }
62 |
63 | if (pointA.y > pointB.y) {
64 | y = "up";
65 | }
66 |
67 | return {
68 | x: x as Direction["x"],
69 | y: y as Direction["y"],
70 | };
71 | };
72 |
73 | // possibly for future computation
74 | const directionHasChanged = (currentDirection: Direction, nextDirection: Direction) =>
75 | JSON.stringify(currentDirection) !== JSON.stringify(nextDirection);
76 |
77 | const calculateDistance = (pointA: Coordinate, pointB: Coordinate) => {
78 | return Math.sqrt(Math.pow(pointA.x - pointB.x, 2) + Math.pow(pointA.y - pointB.y, 2));
79 | };
80 |
81 | return {
82 | gesture,
83 | gestureDirectionHistory,
84 | reset,
85 | };
86 | };
87 |
88 | export default useRecorder;
89 |
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "target": "es5",
4 | "module": "commonjs",
5 | "lib": ["esnext"],
6 | "allowJs": false,
7 | "jsx": "react",
8 | "declaration": true,
9 | "declarationMap": true,
10 | "outDir": "dist",
11 | "rootDir": "src",
12 | "strict": true,
13 | "noImplicitAny": true,
14 | "allowSyntheticDefaultImports": true,
15 | "esModuleInterop": true
16 | }
17 | }
18 |
--------------------------------------------------------------------------------