An open API service indexing awesome lists of open source software.

https://github.com/simformsolutionspvtltd/react-native-haptic-patterns

A React Native library to create, record, and play customizable haptic feedback patterns on iOS and Android.
https://github.com/simformsolutionspvtltd/react-native-haptic-patterns

android component haptic-feedback ios library react-native typescript vibration

Last synced: 5 months ago
JSON representation

A React Native library to create, record, and play customizable haptic feedback patterns on iOS and Android.

Awesome Lists containing this project

README

          

![React Native Haptic Patterns - Simform](./assets/react-native-haptic-patterns.png)

# react-native-haptic-patterns

[![react-native-haptic-patterns on npm](https://img.shields.io/npm/v/react-native-haptic-patterns.svg?style=flat)](https://www.npmjs.com/package/react-native-haptic-patterns) [![react-native-haptic-patterns downloads](https://img.shields.io/npm/dm/react-native-haptic-patterns)](https://www.npmtrends.com/react-native-haptic-patterns) [![react-native-haptic-patterns install size](https://packagephobia.com/badge?p=react-native-haptic-patterns)](https://packagephobia.com/result?p=react-native-haptic-patterns) [![Android](https://img.shields.io/badge/Platform-Android-green?logo=android)](https://www.android.com) [![iOS](https://img.shields.io/badge/Platform-iOS-green?logo=apple)](https://developer.apple.com/ios) [![MIT](https://img.shields.io/badge/License-MIT-green)](https://opensource.org/licenses/MIT)

A React Native library for creating and playing customizable haptic feedback patterns on iOS and Android. Supports advanced pattern recording and playback, enabling developers to deliver rich, tactile experiences in their mobile applications.

---

## ✨ Features

- ✅ **Cross-platform support** - Works seamlessly on both iOS and Android
- ✅ **Custom haptic patterns** - Create your own vibration patterns with precise control
- ✅ **Pattern recording & playback** - Record and replay complex haptic sequences
- ✅ **Core Haptics API** - Leverage iOS's advanced haptic engine (iOS 13+)
- ✅ **TypeScript support** - Full type definitions included
- ✅ **Simple API** - Easy-to-use methods with Promise-based interface
- ✅ **Lightweight** - Minimal dependencies and small bundle size

---

## Quick Access

[Features](#-features) | [Requirements](#requirements) | [Installation](#installation) | [Usage](#usage) | [Methods](#methods) | [Types](#types) | [Examples](#examples) | [Troubleshooting](#troubleshooting) | [License](#license)

---

## Requirements

- **React Native** >= 0.70.0
- **iOS** >= 13.0 (for Core Haptics support)
- **Android** API >= 29 (Android 9.0+)

### Permissions

#### Android

Add the following permission to your `android/app/src/main/AndroidManifest.xml`:

```xml

```

---

## Getting Started

Here's how to get started with `react-native-haptic-patterns` in your React Native project:

### Installation

**1. Install the package**

```sh
npm install react-native-haptic-patterns
```

Or using Yarn:

```sh
yarn add react-native-haptic-patterns
```

**2. Install iOS dependencies**

```sh
cd ios && pod install && cd ..
```

Or using npx:

```sh
npx pod-install
```

**3. Configure Android permissions**

Add the vibration permission to `android/app/src/main/AndroidManifest.xml`:

```xml

```

## Usage

### Basic Example

Import and use the library in your React Native app:

```tsx
import React from 'react';
import { Button, View } from 'react-native';
import { HapticPatterns } from 'react-native-haptic-patterns';

const MyComponent = () => {
const handlePress = async () => {
try {
// Check if device supports haptics
const isSupported = await HapticPatterns.checkForHapticSupport();

if (isSupported) {
// Play a 200ms haptic pattern
HapticPatterns.playHapticPattern(200);
} else {
console.log('Haptics not supported on this device');
}
} catch (error) {
console.error('Haptic error:', error);
}
};

return (



);
};
```

### Quick Start

```tsx
import { HapticPatterns } from 'react-native-haptic-patterns';

// Check haptic support
const isSupported = await HapticPatterns.checkForHapticSupport();

// Play a simple haptic pattern
HapticPatterns.playHapticPattern(200); // Vibrate for 200ms

// Stop the current haptic pattern
HapticPatterns.stopHapticPattern();

// Play a recorded pattern
const recordedEvents = [
{ startTime: 0, endTime: 100, isPause: false },
{ startTime: 100, endTime: 200, isPause: true },
{ startTime: 200, endTime: 400, isPause: false },
];

await HapticPatterns.playRecordedPattern(recordedEvents);
```

### Advanced Pattern Example

```tsx
import {
HapticPatterns,
RecordedEventType,
} from 'react-native-haptic-patterns';

const playCustomPattern = () => {
// Create a custom haptic pattern
const pattern: RecordedEventType[] = [
{ startTime: 0, endTime: 100, isPause: false }, // Short vibration
{ startTime: 100, endTime: 200, isPause: true }, // Pause
{ startTime: 200, endTime: 400, isPause: false }, // Longer vibration
{ startTime: 400, endTime: 500, isPause: true }, // Pause
{ startTime: 500, endTime: 600, isPause: false }, // Final vibration
];

try {
HapticPatterns.playRecordedPattern(pattern);
console.log('Pattern playback completed');
} catch (error) {
console.error('Pattern playback error:', error);
}
};

// Use in different scenarios
const provideSuccessFeedback = () => {
HapticPatterns.playHapticPattern(50); // Quick tap
};

const provideErrorFeedback = async () => {
const errorPattern: RecordedEventType[] = [
{ startTime: 0, endTime: 100, isPause: false },
{ startTime: 100, endTime: 150, isPause: true },
{ startTime: 150, endTime: 250, isPause: false },
];
await HapticPatterns.playRecordedPattern(errorPattern);
};
```

## Methods

### checkForHapticSupport

```ts
checkForHapticSupport(): Promise
```

Checks if the device supports haptic feedback.

Platform behavior:

- **Android:** Always returns `true` as Android devices support haptic feedback through the Vibration API.
- **iOS:** Queries the device's Core Haptics capabilities to determine if haptic feedback is supported.

Returns:

- A Promise that resolves to `true` if haptics are supported, `false` otherwise.

---

### playHapticPattern

```ts
playHapticPattern(vibrationDuration: number): Promise
```

Plays a custom haptic pattern for the specified duration.

Parameters:

- `vibrationDuration`: Duration of the vibration in milliseconds.

Platform behavior:

- **Android:** Uses the Vibration API.
- **iOS:** Builds and plays a haptic pattern using Core Haptics.

Returns:

- A Promise that resolves when the pattern has started playing.

---

### stopHapticPattern

```ts
stopHapticPattern(): Promise
```

Stops the currently playing haptic pattern.

Platform behavior:

- **Android:** Cancels vibration.
- **iOS:** Stops the HapticEngine player.

Returns:

- A Promise that resolves when the pattern has been stopped.

---

### playRecordedPattern

```ts
playRecordedPattern(recordedEvents: RecordedEventType[]): Promise
```

Plays a recorded haptic pattern.

Parameters:

- `recordedEvents`: An array of recorded haptic or pause events, each with `{ startTime, endTime, isPause }`.

Platform behavior:

- **Android:** Converts events to a vibration pattern array and plays it.
- **iOS:** Converts events to haptic events and plays them using Core Haptics.

Returns:

- A Promise that resolves when the entire pattern has finished playing.

---

## Types

### RecordedEventType

Represents a single event in a recorded haptic pattern.

```ts
interface RecordedEventType {
startTime: number; // Start time in milliseconds
endTime: number; // End time in milliseconds
isPause: boolean; // Whether this is a pause (true) or haptic event (false)
}
```

**Example:**

```ts
const pattern: RecordedEventType[] = [
{ startTime: 0, endTime: 100, isPause: false }, // Vibrate for 100ms
{ startTime: 100, endTime: 200, isPause: true }, // Pause for 100ms
{ startTime: 200, endTime: 300, isPause: false }, // Vibrate for 100ms
];
```

---

## Examples

To better understand how to use these methods in a real-world scenario, refer to the following full working example project:

[Example App](./example/src/App.tsx): Demonstrates how to record, play, and reset custom haptic patterns using the library's API in a React Native application.

### Common Use Cases

**Button Press Feedback**

```tsx
{
HapticPatterns.playHapticPattern(50);
// Handle button action
}}>
Press Me

```

**Success/Error Notifications**

```tsx
const showSuccessNotification = () => {
HapticPatterns.playHapticPattern(100); // Single haptic
// Show success message
};

const showErrorNotification = async () => {
const errorPattern: RecordedEventType[] = [
{ startTime: 0, endTime: 50, isPause: false },
{ startTime: 50, endTime: 100, isPause: true },
{ startTime: 100, endTime: 150, isPause: false },
];
await HapticPatterns.playRecordedPattern(errorPattern);
// Show error message
};
```

**Long Press Detection**

```tsx
{
HapticPatterns.playHapticPattern(150);
// Handle long press
}}>
Long Press Me

```

---

## Troubleshooting

### iOS

**Haptics not working on simulator**

- Core Haptics only works on physical devices. Test on a real iPhone (iPhone 8 or newer recommended for best haptic support).

**Build errors after installation**

- Run `cd ios && pod install && cd ..` to ensure CocoaPods are properly installed.
- Clean build folder in Xcode: `Product` > `Clean Build Folder` (Shift + Cmd + K)
- Delete derived data: `rm -rf ~/Library/Developer/Xcode/DerivedData`

**Haptics not working on device**

- Ensure the device supports Core Haptics (iPhone 8 and newer)
- Check that haptic feedback is enabled in device settings
- Verify iOS version is 13.0 or higher

### Android

**Vibration not working**

- Ensure you've added the `VIBRATE` permission to `AndroidManifest.xml`
- Check that vibration is enabled in device settings
- Some devices may have battery optimization that affects vibration

**Build errors**

- Try cleaning the build: `cd android && ./gradlew clean && cd ..`
- Delete build folders: `rm -rf android/app/build`
- Invalidate caches in Android Studio: `File` > `Invalidate Caches / Restart`

**Permission denied errors**

- Verify the `VIBRATE` permission is in the correct location in `AndroidManifest.xml`
- Check that the permission is not being removed by other configurations

### General

**Module not found errors**

- Ensure the package is properly installed: `npm install` or `yarn install`
- Try resetting Metro bundler cache: `npx react-native start --reset-cache`
- Rebuild the app completely: `npx react-native run-ios` or `npx react-native run-android`

---

## Acknowledgements

This library uses and modifies the iOS implementation from [react-native-core-haptics-api](https://github.com/insanj/react-native-core-haptics-api) for customization.

## Find this library useful? ❤️

Support it by joining [stargazers](https://github.com/SimformSolutionsPvtLtd/react-native-haptic-patterns/stargazers) for this repository.⭐

## Bugs / Feature requests / Feedbacks

For bugs, feature requests, and discussion please use [GitHub Issues](https://github.com/SimformSolutionsPvtLtd/react-native-haptic-patterns/issues/new?labels=bug&template=BUG_REPORT.md&title=%5BBUG%5D%3A), [GitHub New Feature](https://github.com/SimformSolutionsPvtLtd/react-native-haptic-patterns/issues/new?labels=enhancement&template=FEATURE_REQUEST.md&title=%5BFEATURE%5D%3A), [GitHub Feedback](https://github.com/SimformSolutionsPvtLtd/react-native-haptic-patterns/issues/new?labels=enhancement&template=FEATURE_REQUEST.md&title=%5BFEEDBACK%5D%3A)

## 🤝 How to Contribute

We'd love to have you improve this library or fix a problem 💪
Check out our [Contributing Guide](CONTRIBUTING.md) for ideas on contributing.

## Awesome Mobile Libraries

- Check out our other [available awesome mobile libraries](https://github.com/SimformSolutionsPvtLtd/Awesome-Mobile-Libraries)

## License

- [MIT License](./LICENSE)