-
Notifications
You must be signed in to change notification settings - Fork 94
/
index.ts
39 lines (34 loc) · 1.01 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import {useEffect} from 'react';
import {isBrowser, noop} from '../util/const.js';
/**
* Provides vibration feedback using the Vibration API.
*
* @param enabled Whether to perform vibration or not.
* @param pattern VibrationPattern passed down to `navigator.vibrate`.
* @param loop If true - vibration will be looped using `setInterval`.
*/
export const useVibrate =
(!isBrowser || navigator.vibrate === undefined) ?
noop :
(enabled: boolean, pattern: VibratePattern, loop?: boolean): void => {
useEffect(() => {
let interval: undefined | ReturnType<typeof setInterval>;
if (enabled) {
navigator.vibrate(pattern);
if (loop) {
interval = setInterval(
() => {
navigator.vibrate(pattern);
},
Array.isArray(pattern) ? pattern.reduce((a, n) => a + n, 0) : pattern,
);
}
return () => {
navigator.vibrate(0);
if (interval) {
clearInterval(interval);
}
};
}
}, [loop, pattern, enabled]);
};