mirror of
https://github.com/streamich/react-use.git
synced 2026-01-18 14:06:52 +00:00
useVibrate
This commit is contained in:
parent
a38f026beb
commit
9df69c6e00
0
docs/useVibrate.md
Normal file
0
docs/useVibrate.md
Normal file
20
src/__stories__/useVibrate.story.tsx
Normal file
20
src/__stories__/useVibrate.story.tsx
Normal file
@ -0,0 +1,20 @@
|
||||
import { storiesOf } from '@storybook/react';
|
||||
import * as React from 'react';
|
||||
import { useVibrate, useToggle } from '..';
|
||||
import ShowDocs from './util/ShowDocs';
|
||||
|
||||
const Demo = () => {
|
||||
const [vibrating, toggleVibrating] = useToggle(false);
|
||||
|
||||
useVibrate(vibrating, [300, 100, 200, 100, 1000, 300]);
|
||||
|
||||
return (
|
||||
<div>
|
||||
<button onClick={toggleVibrating}>{vibrating ? 'Stop' : 'Vibrate'}</button>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
storiesOf('UI|useVibrate', module)
|
||||
.add('Docs', () => <ShowDocs md={require('../../docs/useVibrate.md')} />)
|
||||
.add('Demo', () => <Demo />);
|
||||
@ -86,6 +86,7 @@ export { default as useUnmount } from './useUnmount';
|
||||
export { default as useUpdate } from './useUpdate';
|
||||
export { default as useUpdateEffect } from './useUpdateEffect';
|
||||
export { default as useUpsert } from './useUpsert';
|
||||
export { default as useVibrate } from './useVibrate';
|
||||
export { default as useVideo } from './useVideo';
|
||||
export { default as useStateValidator } from './useStateValidator';
|
||||
export { useWait, Waiter } from './useWait';
|
||||
|
||||
37
src/useVibrate.ts
Normal file
37
src/useVibrate.ts
Normal file
@ -0,0 +1,37 @@
|
||||
import { useEffect } from 'react';
|
||||
|
||||
export type VibrationPattern = number | number[];
|
||||
|
||||
const isVibrationApiSupported = typeof navigator === 'object' && 'vibrate' in navigator;
|
||||
|
||||
const useVibrateMock = () => {};
|
||||
|
||||
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 : useVibrateMock;
|
||||
Loading…
x
Reference in New Issue
Block a user