react-use/src/useVibrate.ts
xobotyi b6993a6f95
feat(prettier): make prettier a part of eslint.
Also reduce max line width to 100. And remove `lint:types` step for
commit sequence, it bothers when committing incomplete (wip) changes.
2021-02-01 18:58:55 +03:00

42 lines
907 B
TypeScript

import { useEffect } from 'react';
import { isNavigator, noop } from './misc/util';
export type VibrationPattern = number | number[];
const isVibrationApiSupported = isNavigator && 'vibrate' in navigator;
function useVibrate(
enabled: boolean = true,
pattern: VibrationPattern = [1000, 1000],
loop: boolean = true
): void {
useEffect(() => {
let interval;
if (enabled) {
navigator.vibrate(pattern);
if (loop) {
const duration =
pattern instanceof Array ? pattern.reduce((a, b) => a + b) : (pattern as number);
interval = setInterval(() => {
navigator.vibrate(pattern);
}, duration);
}
}
return () => {
if (enabled) {
navigator.vibrate(0);
if (loop) {
clearInterval(interval);
}
}
};
}, [enabled]);
}
export default isVibrationApiSupported ? useVibrate : noop;