expo-haptics
Version:
Provides access to the system's haptics engine on iOS, vibration effects on Android, and Web Vibration API on web.
47 lines (43 loc) • 1.54 kB
text/typescript
import { NotificationFeedbackType, ImpactFeedbackStyle } from './Haptics.types';
/**
* The vibrate pattern holds an array of values describes alternating periods in which the device is
* vibrating and not vibrating. Each value in the array is converted to an integer, then interpreted
* alternately as the duration of milliseconds the device should and should not vibrate.
*/
const vibrationPatterns: Record<
NotificationFeedbackType | ImpactFeedbackStyle | 'selection',
VibratePattern
> = {
[]: [40, 100, 40],
[]: [50, 100, 50],
[]: [60, 100, 60, 100, 60],
[]: [40],
[]: [50],
[]: [60],
[]: [35],
[]: [45],
selection: [50],
};
function isVibrationAvailable(): boolean {
return typeof window !== 'undefined' && 'navigator' in window && 'vibrate' in navigator;
}
export default {
async notificationAsync(type: NotificationFeedbackType): Promise<void> {
if (!isVibrationAvailable()) {
return;
}
navigator.vibrate(vibrationPatterns[type]);
},
async impactAsync(style: ImpactFeedbackStyle): Promise<void> {
if (!isVibrationAvailable()) {
return;
}
navigator.vibrate(vibrationPatterns[style]);
},
async selectionAsync(): Promise<void> {
if (!isVibrationAvailable()) {
return;
}
navigator.vibrate(vibrationPatterns.selection);
},
};