@thesonicprint/haptics
v1.0.1
Published
Modern haptics library for React and PWA
Maintainers
Readme
@thesonicprint/haptics
A modern haptics library for React and Progressive Web Apps (PWA). Provides a declarative way to interact with the Vibration API with advanced patterns, pulse-width modulation (PWM), and built-in React hooks/components.
Features
- Modern ES6 Core: Lightweight and dependency-free core.
- React Ready: Full suite of hooks, context provider, and components.
- Advanced Patterns: Easily create complex tactile sequences.
- PWM Support: Fine-grained control over vibration intensity.
- PWA Optimized: Robust error handling for non-supported devices and environments.
- Recording: Record tactile patterns from user touch/mouse events.
Installation
npm install @thesonicprint/hapticsQuick Start
Basic Usage
import { vibrate, clunk, notification } from '@thesonicprint/haptics';
// Simple vibration
vibrate(50);
// Built-in patterns
clunk(100);
notification(500);React Integration
import { HapticsProvider, useHaptics } from '@thesonicprint/haptics';
function App() {
return (
<HapticsProvider>
<MyComponent />
</HapticsProvider>
);
}
function MyComponent() {
const { clunk, fadeIn } = useHaptics();
return (
<button onClick={() => clunk(50)}>
Click Me
</button>
);
}Pulse Width Modulation (PWM)
PWM allows you to simulate different vibration intensities by rapidly cycling the vibration motor on and off.
Creating PWM Patterns
import { createPatternPWM } from '@thesonicprint/haptics';
// Intensity presets (on-duration, off-duration in ms)
const light = createPatternPWM(5, 25);
const medium = createPatternPWM(15, 15);
const strong = createPatternPWM(25, 5);
// Usage: call with total duration
light(300); // Soft vibration for 300ms
strong(500); // Intense vibration for 500msWhy use PWM?
Hardware vibration motors are binary (on or off). PWM is the standard technique to create "soft" or "sharp" tactile sensations, essential for premium UX in PWAs.
Progressive Enhancement (PWA focus)
The library is designed to fail silently on unsupported devices (like desktop browsers or iOS Safari).
isSupported: Use this flag to conditionally show/hide haptic settings or UI elements.- Silent Fail: Calling vibration methods on unsupported devices will not throw errors; they will return
falseor return silently.
import { enabled } from '@thesonicprint/haptics';
if (enabled) {
console.log("Haptics are supported and ready!");
}API Reference
Core Methods
| Method | Description |
| :--- | :--- |
| vibrate(pattern) | Standard vibration. Pattern can be a number or number[]. |
| record() | Start recording a pattern from touch/mouse events. |
| finish() | Stop recording and return the pattern as an array. |
| pwm(duration, on, off) | Raw PWM vibration for intensity control. |
| createPattern(...args) | Compose higher-order pattern functions. |
| createPatternPWM(on, off) | Factory for reusable intensity-based patterns. |
Built-in Effects
All built-in effects are factory-prepared. You can call them with a total duration.
fadeIn(duration): Gradual increase in intensity.fadeOut(duration): Gradual decrease in intensity.notification(duration): Triple-pulse "alert" pattern.heartbeat(duration): Double-pulse "lub-dub" sensation.clunk(duration): Sharp, heavy mechanical "click".
React Extensions
The library provides fully integrated hooks and components for React/Vite projects.
useHaptics(): Access all core haptic methods with context awareness.useHapticFeedback(pattern, options): Declarative hook for triggering patterns based on state.useHapticRecorder(): Recording interface with built-in playback and state management.<HapticButton />,<HapticToggle />,<HapticSlider />: Specialized UI components with built-in tactile feedback.
Creative Implementations
1. Morse Code Generator
Convert text into tactile signals for accessibility or covert notifications.
import { createPattern } from '@thesonicprint/haptics';
const MORSE_MAP = {
'.': [100, 100], // Dot + pause
'-': [300, 100], // Dash + pause
' ': [0, 400] // Word gap
};
function textToMorse(text) {
const pattern = text.toLowerCase().split('').flatMap(char => {
if (char === ' ') return MORSE_MAP[' '];
return MORSE_MAP[char] || [];
});
return createPattern(pattern);
}
const sos = textToMorse('sos');
sos(1000); // Triggers tactile SOS (scaled to 1s)2. Biometric "Scan" Effect
Simulate the feeling of a fingerprint or face scan in your PWA.
import { fadeIn, clunk } from '@thesonicprint/haptics';
async function simulateScan() {
// Start with a 1s "scanning" ramp up
fadeIn(1000);
await new Promise(r => setTimeout(r, 1100));
// Confirmed hit
clunk(100);
}3. Digital "Textures" (PWM)
Simulate different surface feelings by varying PWM frequency.
import { createPatternPWM } from '@sonicprint/haptics';
// High frequency (Smooth/Metallic)
const metallic = createPatternPWM(2, 2);
// Low frequency (Rough/Gravel)
const rough = createPatternPWM(30, 30);
// Usage in interaction
<div onMouseMove={() => metallic(50)}>Slide over Metal</div>
<div onMouseMove={() => rough(50)}>Slide over Stone</div>4. Impact Velocity (Physics FX)
Scale haptic feedback based on game physics or interaction speed.
import { vibrate } from '@thesonicprint/haptics';
function onCollision(velocity) {
// Scale duration (10ms to 200ms) based on impact speed
const duration = Math.min(Math.max(velocity * 10, 10), 200);
vibrate(duration);
}License
MIT © Sonicprint
