@thesonicprint/haptics 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +22 -0
- package/Readme.md +204 -0
- package/dist/index.d.mts +61 -0
- package/dist/index.d.ts +61 -0
- package/dist/index.js +1 -0
- package/dist/index.mjs +1 -0
- package/package.json +40 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2014 Shantanu Bala
|
|
4
|
+
Copyright (c) 2026 Sonicprint
|
|
5
|
+
|
|
6
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
7
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
8
|
+
in the Software without restriction, including without limitation the rights
|
|
9
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
10
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
11
|
+
furnished to do so, subject to the following conditions:
|
|
12
|
+
|
|
13
|
+
The above copyright notice and this permission notice shall be included in all
|
|
14
|
+
copies or substantial portions of the Software.
|
|
15
|
+
|
|
16
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
17
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
18
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
19
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
20
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
21
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
22
|
+
SOFTWARE.
|
package/Readme.md
ADDED
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
# @thesonicprint/haptics
|
|
2
|
+
|
|
3
|
+
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.
|
|
4
|
+
|
|
5
|
+
## Features
|
|
6
|
+
|
|
7
|
+
- **Modern ES6 Core**: Lightweight and dependency-free core.
|
|
8
|
+
- **React Ready**: Full suite of hooks, context provider, and components.
|
|
9
|
+
- **Advanced Patterns**: Easily create complex tactile sequences.
|
|
10
|
+
- **PWM Support**: Fine-grained control over vibration intensity.
|
|
11
|
+
- **PWA Optimized**: Robust error handling for non-supported devices and environments.
|
|
12
|
+
- **Recording**: Record tactile patterns from user touch/mouse events.
|
|
13
|
+
|
|
14
|
+
## Installation
|
|
15
|
+
|
|
16
|
+
```bash
|
|
17
|
+
npm install @thesonicprint/haptics
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
## Quick Start
|
|
21
|
+
|
|
22
|
+
### Basic Usage
|
|
23
|
+
|
|
24
|
+
```javascript
|
|
25
|
+
import { vibrate, clunk, notification } from '@thesonicprint/haptics';
|
|
26
|
+
|
|
27
|
+
// Simple vibration
|
|
28
|
+
vibrate(50);
|
|
29
|
+
|
|
30
|
+
// Built-in patterns
|
|
31
|
+
clunk(100);
|
|
32
|
+
notification(500);
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
### React Integration
|
|
36
|
+
|
|
37
|
+
```jsx
|
|
38
|
+
import { HapticsProvider, useHaptics } from '@thesonicprint/haptics';
|
|
39
|
+
|
|
40
|
+
function App() {
|
|
41
|
+
return (
|
|
42
|
+
<HapticsProvider>
|
|
43
|
+
<MyComponent />
|
|
44
|
+
</HapticsProvider>
|
|
45
|
+
);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function MyComponent() {
|
|
49
|
+
const { clunk, fadeIn } = useHaptics();
|
|
50
|
+
|
|
51
|
+
return (
|
|
52
|
+
<button onClick={() => clunk(50)}>
|
|
53
|
+
Click Me
|
|
54
|
+
</button>
|
|
55
|
+
);
|
|
56
|
+
}
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
## Pulse Width Modulation (PWM)
|
|
60
|
+
|
|
61
|
+
PWM allows you to simulate different vibration intensities by rapidly cycling the vibration motor on and off.
|
|
62
|
+
|
|
63
|
+
### Creating PWM Patterns
|
|
64
|
+
|
|
65
|
+
```javascript
|
|
66
|
+
import { createPatternPWM } from '@thesonicprint/haptics';
|
|
67
|
+
|
|
68
|
+
// Intensity presets (on-duration, off-duration in ms)
|
|
69
|
+
const light = createPatternPWM(5, 25);
|
|
70
|
+
const medium = createPatternPWM(15, 15);
|
|
71
|
+
const strong = createPatternPWM(25, 5);
|
|
72
|
+
|
|
73
|
+
// Usage: call with total duration
|
|
74
|
+
light(300); // Soft vibration for 300ms
|
|
75
|
+
strong(500); // Intense vibration for 500ms
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
### Why use PWM?
|
|
79
|
+
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.
|
|
80
|
+
|
|
81
|
+
## Progressive Enhancement (PWA focus)
|
|
82
|
+
|
|
83
|
+
The library is designed to fail silently on unsupported devices (like desktop browsers or iOS Safari).
|
|
84
|
+
|
|
85
|
+
- **`isSupported`**: Use this flag to conditionally show/hide haptic settings or UI elements.
|
|
86
|
+
- **Silent Fail**: Calling vibration methods on unsupported devices will not throw errors; they will return `false` or return silently.
|
|
87
|
+
|
|
88
|
+
```javascript
|
|
89
|
+
import { enabled } from '@thesonicprint/haptics';
|
|
90
|
+
|
|
91
|
+
if (enabled) {
|
|
92
|
+
console.log("Haptics are supported and ready!");
|
|
93
|
+
}
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
## API Reference
|
|
97
|
+
|
|
98
|
+
### Core Methods
|
|
99
|
+
|
|
100
|
+
| Method | Description |
|
|
101
|
+
| :--- | :--- |
|
|
102
|
+
| `vibrate(pattern)` | Standard vibration. Pattern can be a `number` or `number[]`. |
|
|
103
|
+
| `record()` | Start recording a pattern from touch/mouse events. |
|
|
104
|
+
| `finish()` | Stop recording and return the pattern as an array. |
|
|
105
|
+
| `pwm(duration, on, off)` | Raw PWM vibration for intensity control. |
|
|
106
|
+
| `createPattern(...args)` | Compose higher-order pattern functions. |
|
|
107
|
+
| `createPatternPWM(on, off)` | Factory for reusable intensity-based patterns. |
|
|
108
|
+
|
|
109
|
+
### Built-in Effects
|
|
110
|
+
|
|
111
|
+
All built-in effects are factory-prepared. You can call them with a total `duration`.
|
|
112
|
+
|
|
113
|
+
- **`fadeIn(duration)`**: Gradual increase in intensity.
|
|
114
|
+
- **`fadeOut(duration)`**: Gradual decrease in intensity.
|
|
115
|
+
- **`notification(duration)`**: Triple-pulse "alert" pattern.
|
|
116
|
+
- **`heartbeat(duration)`**: Double-pulse "lub-dub" sensation.
|
|
117
|
+
- **`clunk(duration)`**: Sharp, heavy mechanical "click".
|
|
118
|
+
|
|
119
|
+
### React Extensions
|
|
120
|
+
|
|
121
|
+
The library provides fully integrated hooks and components for React/Vite projects.
|
|
122
|
+
|
|
123
|
+
- **`useHaptics()`**: Access all core haptic methods with context awareness.
|
|
124
|
+
- **`useHapticFeedback(pattern, options)`**: Declarative hook for triggering patterns based on state.
|
|
125
|
+
- **`useHapticRecorder()`**: Recording interface with built-in playback and state management.
|
|
126
|
+
- **`<HapticButton />`**, **`<HapticToggle />`**, **`<HapticSlider />`**: Specialized UI components with built-in tactile feedback.
|
|
127
|
+
|
|
128
|
+
---
|
|
129
|
+
|
|
130
|
+
## Creative Implementations
|
|
131
|
+
|
|
132
|
+
### 1. Morse Code Generator
|
|
133
|
+
Convert text into tactile signals for accessibility or covert notifications.
|
|
134
|
+
|
|
135
|
+
```javascript
|
|
136
|
+
import { createPattern } from '@thesonicprint/haptics';
|
|
137
|
+
|
|
138
|
+
const MORSE_MAP = {
|
|
139
|
+
'.': [100, 100], // Dot + pause
|
|
140
|
+
'-': [300, 100], // Dash + pause
|
|
141
|
+
' ': [0, 400] // Word gap
|
|
142
|
+
};
|
|
143
|
+
|
|
144
|
+
function textToMorse(text) {
|
|
145
|
+
const pattern = text.toLowerCase().split('').flatMap(char => {
|
|
146
|
+
if (char === ' ') return MORSE_MAP[' '];
|
|
147
|
+
return MORSE_MAP[char] || [];
|
|
148
|
+
});
|
|
149
|
+
return createPattern(pattern);
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
const sos = textToMorse('sos');
|
|
153
|
+
sos(1000); // Triggers tactile SOS (scaled to 1s)
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
### 2. Biometric "Scan" Effect
|
|
157
|
+
Simulate the feeling of a fingerprint or face scan in your PWA.
|
|
158
|
+
|
|
159
|
+
```javascript
|
|
160
|
+
import { fadeIn, clunk } from '@thesonicprint/haptics';
|
|
161
|
+
|
|
162
|
+
async function simulateScan() {
|
|
163
|
+
// Start with a 1s "scanning" ramp up
|
|
164
|
+
fadeIn(1000);
|
|
165
|
+
|
|
166
|
+
await new Promise(r => setTimeout(r, 1100));
|
|
167
|
+
|
|
168
|
+
// Confirmed hit
|
|
169
|
+
clunk(100);
|
|
170
|
+
}
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
### 3. Digital "Textures" (PWM)
|
|
174
|
+
Simulate different surface feelings by varying PWM frequency.
|
|
175
|
+
|
|
176
|
+
```javascript
|
|
177
|
+
import { createPatternPWM } from '@sonicprint/haptics';
|
|
178
|
+
|
|
179
|
+
// High frequency (Smooth/Metallic)
|
|
180
|
+
const metallic = createPatternPWM(2, 2);
|
|
181
|
+
// Low frequency (Rough/Gravel)
|
|
182
|
+
const rough = createPatternPWM(30, 30);
|
|
183
|
+
|
|
184
|
+
// Usage in interaction
|
|
185
|
+
<div onMouseMove={() => metallic(50)}>Slide over Metal</div>
|
|
186
|
+
<div onMouseMove={() => rough(50)}>Slide over Stone</div>
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
### 4. Impact Velocity (Physics FX)
|
|
190
|
+
Scale haptic feedback based on game physics or interaction speed.
|
|
191
|
+
|
|
192
|
+
```javascript
|
|
193
|
+
import { vibrate } from '@thesonicprint/haptics';
|
|
194
|
+
|
|
195
|
+
function onCollision(velocity) {
|
|
196
|
+
// Scale duration (10ms to 200ms) based on impact speed
|
|
197
|
+
const duration = Math.min(Math.max(velocity * 10, 10), 200);
|
|
198
|
+
vibrate(duration);
|
|
199
|
+
}
|
|
200
|
+
```
|
|
201
|
+
|
|
202
|
+
## License
|
|
203
|
+
|
|
204
|
+
MIT © Sonicprint
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import * as react_jsx_runtime from 'react/jsx-runtime';
|
|
2
|
+
|
|
3
|
+
declare function useHaptics(): {
|
|
4
|
+
isSupported: any;
|
|
5
|
+
vibrate: (pattern: any) => any;
|
|
6
|
+
fadeIn: (duration: any) => void;
|
|
7
|
+
fadeOut: (duration: any) => void;
|
|
8
|
+
notification: (duration: any) => void;
|
|
9
|
+
heartbeat: (duration: any) => void;
|
|
10
|
+
clunk: (duration: any) => void;
|
|
11
|
+
pwm: (duration: any, on: any, off: any) => void;
|
|
12
|
+
createPattern: (...args: any[]) => any;
|
|
13
|
+
createPatternPWM: (on: any, off: any) => any;
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
declare function useHapticFeedback(pattern?: number, options?: {}): (customPattern: any) => any;
|
|
17
|
+
|
|
18
|
+
declare function useHapticRecorder(): {
|
|
19
|
+
isRecording: boolean;
|
|
20
|
+
recordedPattern: null;
|
|
21
|
+
startRecording: () => void;
|
|
22
|
+
stopRecording: () => any;
|
|
23
|
+
playback: (pattern: any) => void;
|
|
24
|
+
reset: () => void;
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
declare function HapticsProvider({ children, defaultEnabled }: {
|
|
28
|
+
children: any;
|
|
29
|
+
defaultEnabled?: boolean | undefined;
|
|
30
|
+
}): react_jsx_runtime.JSX.Element;
|
|
31
|
+
declare function useHapticsContext(): never;
|
|
32
|
+
|
|
33
|
+
declare const enabled: boolean;
|
|
34
|
+
declare function vibrate(pattern: any): boolean;
|
|
35
|
+
declare function record(): void;
|
|
36
|
+
declare function finish(): number[];
|
|
37
|
+
declare const fadeIn: ((args: any) => void) | null;
|
|
38
|
+
declare const fadeOut: ((args: any) => void) | null;
|
|
39
|
+
declare const notification: ((args: any) => void) | null;
|
|
40
|
+
declare const heartbeat: ((args: any) => void) | null;
|
|
41
|
+
declare const clunk: ((args: any) => void) | null;
|
|
42
|
+
declare function pwm(duration: any, on: any, off: any): void;
|
|
43
|
+
declare function createPatternPWM(on: any, off: any): (args: any) => void;
|
|
44
|
+
declare function createPattern(...args: any[]): ((args: any) => void) | null;
|
|
45
|
+
|
|
46
|
+
declare namespace _default {
|
|
47
|
+
export { enabled };
|
|
48
|
+
export { vibrate };
|
|
49
|
+
export { record };
|
|
50
|
+
export { finish };
|
|
51
|
+
export { fadeIn };
|
|
52
|
+
export { fadeOut };
|
|
53
|
+
export { notification };
|
|
54
|
+
export { heartbeat };
|
|
55
|
+
export { clunk };
|
|
56
|
+
export { pwm };
|
|
57
|
+
export { createPatternPWM };
|
|
58
|
+
export { createPattern };
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export { HapticsProvider, clunk, createPattern, createPatternPWM, _default as default, enabled, fadeIn, fadeOut, finish, heartbeat, notification, pwm, record, useHapticFeedback, useHapticRecorder, useHaptics, useHapticsContext, vibrate };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import * as react_jsx_runtime from 'react/jsx-runtime';
|
|
2
|
+
|
|
3
|
+
declare function useHaptics(): {
|
|
4
|
+
isSupported: any;
|
|
5
|
+
vibrate: (pattern: any) => any;
|
|
6
|
+
fadeIn: (duration: any) => void;
|
|
7
|
+
fadeOut: (duration: any) => void;
|
|
8
|
+
notification: (duration: any) => void;
|
|
9
|
+
heartbeat: (duration: any) => void;
|
|
10
|
+
clunk: (duration: any) => void;
|
|
11
|
+
pwm: (duration: any, on: any, off: any) => void;
|
|
12
|
+
createPattern: (...args: any[]) => any;
|
|
13
|
+
createPatternPWM: (on: any, off: any) => any;
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
declare function useHapticFeedback(pattern?: number, options?: {}): (customPattern: any) => any;
|
|
17
|
+
|
|
18
|
+
declare function useHapticRecorder(): {
|
|
19
|
+
isRecording: boolean;
|
|
20
|
+
recordedPattern: null;
|
|
21
|
+
startRecording: () => void;
|
|
22
|
+
stopRecording: () => any;
|
|
23
|
+
playback: (pattern: any) => void;
|
|
24
|
+
reset: () => void;
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
declare function HapticsProvider({ children, defaultEnabled }: {
|
|
28
|
+
children: any;
|
|
29
|
+
defaultEnabled?: boolean | undefined;
|
|
30
|
+
}): react_jsx_runtime.JSX.Element;
|
|
31
|
+
declare function useHapticsContext(): never;
|
|
32
|
+
|
|
33
|
+
declare const enabled: boolean;
|
|
34
|
+
declare function vibrate(pattern: any): boolean;
|
|
35
|
+
declare function record(): void;
|
|
36
|
+
declare function finish(): number[];
|
|
37
|
+
declare const fadeIn: ((args: any) => void) | null;
|
|
38
|
+
declare const fadeOut: ((args: any) => void) | null;
|
|
39
|
+
declare const notification: ((args: any) => void) | null;
|
|
40
|
+
declare const heartbeat: ((args: any) => void) | null;
|
|
41
|
+
declare const clunk: ((args: any) => void) | null;
|
|
42
|
+
declare function pwm(duration: any, on: any, off: any): void;
|
|
43
|
+
declare function createPatternPWM(on: any, off: any): (args: any) => void;
|
|
44
|
+
declare function createPattern(...args: any[]): ((args: any) => void) | null;
|
|
45
|
+
|
|
46
|
+
declare namespace _default {
|
|
47
|
+
export { enabled };
|
|
48
|
+
export { vibrate };
|
|
49
|
+
export { record };
|
|
50
|
+
export { finish };
|
|
51
|
+
export { fadeIn };
|
|
52
|
+
export { fadeOut };
|
|
53
|
+
export { notification };
|
|
54
|
+
export { heartbeat };
|
|
55
|
+
export { clunk };
|
|
56
|
+
export { pwm };
|
|
57
|
+
export { createPatternPWM };
|
|
58
|
+
export { createPattern };
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export { HapticsProvider, clunk, createPattern, createPatternPWM, _default as default, enabled, fadeIn, fadeOut, finish, heartbeat, notification, pwm, record, useHapticFeedback, useHapticRecorder, useHaptics, useHapticsContext, vibrate };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var I=Object.defineProperty;var j=Object.getOwnPropertyDescriptor;var A=Object.getOwnPropertyNames;var B=Object.prototype.hasOwnProperty;var G=(a,e)=>{for(var t in e)I(a,t,{get:e[t],enumerable:!0})},J=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of A(e))!B.call(a,n)&&n!==t&&I(a,n,{get:()=>e[n],enumerable:!(r=j(e,n))||r.enumerable});return a};var K=a=>J(I({},"__esModule",{value:!0}),a);var S={};G(S,{HapticsProvider:()=>_,clunk:()=>P,createPattern:()=>y,createPatternPWM:()=>k,default:()=>X,enabled:()=>h,fadeIn:()=>w,fadeOut:()=>g,finish:()=>V,heartbeat:()=>R,notification:()=>x,pwm:()=>H,record:()=>E,useHapticFeedback:()=>L,useHapticRecorder:()=>W,useHaptics:()=>q,useHapticsContext:()=>z,vibrate:()=>d});module.exports=K(S);var p=require("react");function N(){let[a,e]=(0,p.useState)(h);(0,p.useEffect)(()=>{e(h)},[]);let t=(0,p.useCallback)(o=>d(o),[]),r=(0,p.useCallback)(o=>{w(o)},[]),n=(0,p.useCallback)(o=>{g(o)},[]),c=(0,p.useCallback)(o=>{x(o)},[]),f=(0,p.useCallback)(o=>{R(o)},[]),l=(0,p.useCallback)(o=>{P(o)},[]),s=(0,p.useCallback)((o,C,T)=>{H(o,C,T)},[]),u=(0,p.useCallback)((...o)=>y(...o),[]),m=(0,p.useCallback)((o,C)=>k(o,C),[]);return{isSupported:a,vibrate:t,fadeIn:r,fadeOut:n,notification:c,heartbeat:f,clunk:l,pwm:s,createPattern:u,createPatternPWM:m}}var q=N;var F=require("react");function Q(a=50,e={}){let{enabled:t=!0,onSuccess:r,onError:n}=e;return(0,F.useCallback)(f=>{if(!t||!h)return!1;try{let l=d(f||a);return l&&r&&r(),l}catch(l){return n&&n(l),!1}},[a,t,r,n])}var L=Q;var b=require("react");function U(){let[a,e]=(0,b.useState)(!1),[t,r]=(0,b.useState)(null),n=(0,b.useRef)(!1),c=(0,b.useCallback)(()=>{n.current||(E(),e(!0),n.current=!0)},[]),f=(0,b.useCallback)(()=>{if(!n.current)return;let u=V();return r(u),e(!1),n.current=!1,u},[]),l=(0,b.useCallback)(u=>{let m=u||t;m&&d(m)},[t]),s=(0,b.useCallback)(()=>{r(null)},[]);return{isRecording:a,recordedPattern:t,startRecording:c,stopRecording:f,playback:l,reset:s}}var W=U;var v=require("react");var D=require("react/jsx-runtime"),O=(0,v.createContext)(null);function _({children:a,defaultEnabled:e=!0}){let[t,r]=(0,v.useState)(e&&h),[n]=(0,v.useState)(h),c=(0,v.useCallback)(s=>t?d(s):!1,[t]),f=(0,v.useCallback)((s,u=50)=>t?{click:()=>P(u),success:()=>w(u),error:()=>d([50,50,50,50,50]),notification:()=>x(u),subtle:()=>H(u,5,25),medium:()=>H(u,15,15),strong:()=>H(u,25,5)}[s]||(()=>d(u)):()=>{},[t]),l={enabled:t,isSupported:n,setEnabled:r,vibrate:c,createFeedback:f,fadeIn:s=>t&&w(s),fadeOut:s=>t&&g(s),notification:s=>t&&x(s),heartbeat:s=>t&&R(s),clunk:s=>t&&P(s),pwm:(s,u,m)=>t&&H(s,u,m),createPattern:y,createPatternPWM:k};return(0,D.jsx)(O.Provider,{value:l,children:a})}function z(){let a=(0,v.useContext)(O);if(!a)throw new Error("useHapticsContext must be used within HapticsProvider");return a}var M=class{constructor(){this.enabled=!1,this.currentRecording=null,this.navigatorVibrate=null,this.logHistory=[],this._initialize()}_initialize(){typeof navigator>"u"||(this.navigatorVibrate=navigator.vibrate?.bind(navigator)||navigator.webkitVibrate?.bind(navigator)||navigator.mozVibrate?.bind(navigator)||navigator.msVibrate?.bind(navigator),this.enabled=!!this.navigatorVibrate)}log(...e){this.logHistory.push(e),typeof console<"u"&&console.log(...e)}vibrate(e){if(this.enabled&&this.navigatorVibrate)try{return this.navigatorVibrate(e),!0}catch(t){return this.log("Vibration failed:",t),!1}return!1}executeSequence(e,t,r){if(!this.enabled)return!1;let n=e.shift(),c=r||t;try{t(n)}catch(f){this.log("Sequence execution failed:",f)}return e.length===0?!0:setTimeout(()=>this.executeSequence(e,c,t),n)}createSequenceFunc(e){let t=e.reduce((r,n)=>r+n,0);return r=>{let n=r/t,c=e.map(f=>f*n);this.vibrate(c)}}concatenatePatternFuncs(...e){return t=>{let r=t/e.length;e.forEach((n,c)=>{setTimeout(()=>n(r),c*r)})}}patternFactory(...e){let t=e.map(n=>typeof n!="function"?this.createSequenceFunc(n):n),r=this.concatenatePatternFuncs(...t);return n=>{typeof n=="number"?r(n):this.executeSequence([...n],r,()=>{})}}createPattern(...e){let t;if(e.length>1)t=this.patternFactory(...e);else if(e[0]&&typeof e[0]!="function"&&e[0].length)t=this.createSequenceFunc(e[0]);else{if(e[0]&&typeof e[0]!="function")return null;t=e[0]}return r=>{typeof r=="number"?t(r):this.executeSequence([...r],t,()=>{})}}startRecording(){this.currentRecording=[];let e=t=>{t.preventDefault(),this.currentRecording.push(new Date)};this._recordHandlers={onRecord:e},typeof window<"u"&&(window.addEventListener("touchstart",e,!1),window.addEventListener("touchend",e,!1),window.addEventListener("mousedown",e,!1),window.addEventListener("mouseup",e,!1))}stopRecording(){if(typeof window<"u"&&this._recordHandlers){let{onRecord:t}=this._recordHandlers;window.removeEventListener("touchstart",t),window.removeEventListener("touchend",t),window.removeEventListener("mousedown",t),window.removeEventListener("mouseup",t)}if(!this.currentRecording)return[];this.currentRecording.length%2!==0&&this.currentRecording.push(new Date);let e=[];for(let t=0;t<this.currentRecording.length;t+=2){let r=t+1;if(r>=this.currentRecording.length)break;e.push(this.currentRecording[r]-this.currentRecording[t])}return e}fadeIn(e){let t=[];if(e<100){this.vibrate(e);return}let r=e/100;for(let n=1;n<=10;n++)t.push(n*r),n<10&&t.push((10-n)*r);this.vibrate(t)}fadeOut(e){let t=[];if(e<100){this.vibrate(e);return}let r=e/100;for(let n=1;n<=10;n++)t.push(n*r),n<10&&t.push((10-n)*r);this.vibrate(t.reverse())}notification(e){let t=e/27,r=2*t,n=3*t;this.vibrate([r,t,r,t,r,t*2,n,t,n,t*2,r,t,r,t,r])}heartbeat(e){let t=e/60,r=t*2,n=t*24;this.vibrate([t,r,n,r*2,n,r*2,t])}clunk(e){let t=e*4/22,r=t*2,n=t/2*5;this.vibrate([t,r,n])}pwm(e,t,r){let n=[t],c=e-t;for(;c>0;)c-=r,c-=t,n.push(r),n.push(t);this.vibrate(n)}createPatternPWM(e,t){return r=>{if(typeof r=="number")this.pwm(r,e,t);else{let n=c=>this.pwm(c,e,t);this.executeSequence([...r],n,()=>{})}}}},i=new M,h=i.enabled,d=i.vibrate.bind(i),E=i.startRecording.bind(i),V=i.stopRecording.bind(i),w=i.createPattern(i.fadeIn.bind(i)),g=i.createPattern(i.fadeOut.bind(i)),x=i.createPattern(i.notification.bind(i)),R=i.createPattern(i.heartbeat.bind(i)),P=i.createPattern(i.clunk.bind(i)),H=i.pwm.bind(i),k=i.createPatternPWM.bind(i),y=i.createPattern.bind(i),X={enabled:h,vibrate:d,record:E,finish:V,fadeIn:w,fadeOut:g,notification:x,heartbeat:R,clunk:P,pwm:H,createPatternPWM:k,createPattern:y};0&&(module.exports={HapticsProvider,clunk,createPattern,createPatternPWM,enabled,fadeIn,fadeOut,finish,heartbeat,notification,pwm,record,useHapticFeedback,useHapticRecorder,useHaptics,useHapticsContext,vibrate});
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{useCallback as l,useEffect as W,useState as O}from"react";function _(){let[u,e]=O(h);W(()=>{e(h)},[]);let t=l(c=>d(c),[]),n=l(c=>{H(c)},[]),r=l(c=>{x(c)},[]),s=l(c=>{m(c)},[]),p=l(c=>{P(c)},[]),f=l(c=>{w(c)},[]),a=l((c,S,L)=>{b(c,S,L)},[]),o=l((...c)=>R(...c),[]),v=l((c,S)=>g(c,S),[]);return{isSupported:u,vibrate:t,fadeIn:n,fadeOut:r,notification:s,heartbeat:p,clunk:f,pwm:a,createPattern:o,createPatternPWM:v}}var z=_;import{useCallback as D}from"react";function T(u=50,e={}){let{enabled:t=!0,onSuccess:n,onError:r}=e;return D(p=>{if(!t||!h)return!1;try{let f=d(p||u);return f&&n&&n(),f}catch(f){return r&&r(f),!1}},[u,t,n,r])}var j=T;import{useState as I,useCallback as y,useRef as A}from"react";function B(){let[u,e]=I(!1),[t,n]=I(null),r=A(!1),s=y(()=>{r.current||(E(),e(!0),r.current=!0)},[]),p=y(()=>{if(!r.current)return;let o=V();return n(o),e(!1),r.current=!1,o},[]),f=y(o=>{let v=o||t;v&&d(v)},[t]),a=y(()=>{n(null)},[]);return{isRecording:u,recordedPattern:t,startRecording:s,stopRecording:p,playback:f,reset:a}}var G=B;import{createContext as J,useContext as K,useState as M,useCallback as q}from"react";import{jsx as U}from"react/jsx-runtime";var F=J(null);function N({children:u,defaultEnabled:e=!0}){let[t,n]=M(e&&h),[r]=M(h),s=q(a=>t?d(a):!1,[t]),p=q((a,o=50)=>t?{click:()=>w(o),success:()=>H(o),error:()=>d([50,50,50,50,50]),notification:()=>m(o),subtle:()=>b(o,5,25),medium:()=>b(o,15,15),strong:()=>b(o,25,5)}[a]||(()=>d(o)):()=>{},[t]),f={enabled:t,isSupported:r,setEnabled:n,vibrate:s,createFeedback:p,fadeIn:a=>t&&H(a),fadeOut:a=>t&&x(a),notification:a=>t&&m(a),heartbeat:a=>t&&P(a),clunk:a=>t&&w(a),pwm:(a,o,v)=>t&&b(a,o,v),createPattern:R,createPatternPWM:g};return U(F.Provider,{value:f,children:u})}function Q(){let u=K(F);if(!u)throw new Error("useHapticsContext must be used within HapticsProvider");return u}var C=class{constructor(){this.enabled=!1,this.currentRecording=null,this.navigatorVibrate=null,this.logHistory=[],this._initialize()}_initialize(){typeof navigator>"u"||(this.navigatorVibrate=navigator.vibrate?.bind(navigator)||navigator.webkitVibrate?.bind(navigator)||navigator.mozVibrate?.bind(navigator)||navigator.msVibrate?.bind(navigator),this.enabled=!!this.navigatorVibrate)}log(...e){this.logHistory.push(e),typeof console<"u"&&console.log(...e)}vibrate(e){if(this.enabled&&this.navigatorVibrate)try{return this.navigatorVibrate(e),!0}catch(t){return this.log("Vibration failed:",t),!1}return!1}executeSequence(e,t,n){if(!this.enabled)return!1;let r=e.shift(),s=n||t;try{t(r)}catch(p){this.log("Sequence execution failed:",p)}return e.length===0?!0:setTimeout(()=>this.executeSequence(e,s,t),r)}createSequenceFunc(e){let t=e.reduce((n,r)=>n+r,0);return n=>{let r=n/t,s=e.map(p=>p*r);this.vibrate(s)}}concatenatePatternFuncs(...e){return t=>{let n=t/e.length;e.forEach((r,s)=>{setTimeout(()=>r(n),s*n)})}}patternFactory(...e){let t=e.map(r=>typeof r!="function"?this.createSequenceFunc(r):r),n=this.concatenatePatternFuncs(...t);return r=>{typeof r=="number"?n(r):this.executeSequence([...r],n,()=>{})}}createPattern(...e){let t;if(e.length>1)t=this.patternFactory(...e);else if(e[0]&&typeof e[0]!="function"&&e[0].length)t=this.createSequenceFunc(e[0]);else{if(e[0]&&typeof e[0]!="function")return null;t=e[0]}return n=>{typeof n=="number"?t(n):this.executeSequence([...n],t,()=>{})}}startRecording(){this.currentRecording=[];let e=t=>{t.preventDefault(),this.currentRecording.push(new Date)};this._recordHandlers={onRecord:e},typeof window<"u"&&(window.addEventListener("touchstart",e,!1),window.addEventListener("touchend",e,!1),window.addEventListener("mousedown",e,!1),window.addEventListener("mouseup",e,!1))}stopRecording(){if(typeof window<"u"&&this._recordHandlers){let{onRecord:t}=this._recordHandlers;window.removeEventListener("touchstart",t),window.removeEventListener("touchend",t),window.removeEventListener("mousedown",t),window.removeEventListener("mouseup",t)}if(!this.currentRecording)return[];this.currentRecording.length%2!==0&&this.currentRecording.push(new Date);let e=[];for(let t=0;t<this.currentRecording.length;t+=2){let n=t+1;if(n>=this.currentRecording.length)break;e.push(this.currentRecording[n]-this.currentRecording[t])}return e}fadeIn(e){let t=[];if(e<100){this.vibrate(e);return}let n=e/100;for(let r=1;r<=10;r++)t.push(r*n),r<10&&t.push((10-r)*n);this.vibrate(t)}fadeOut(e){let t=[];if(e<100){this.vibrate(e);return}let n=e/100;for(let r=1;r<=10;r++)t.push(r*n),r<10&&t.push((10-r)*n);this.vibrate(t.reverse())}notification(e){let t=e/27,n=2*t,r=3*t;this.vibrate([n,t,n,t,n,t*2,r,t,r,t*2,n,t,n,t,n])}heartbeat(e){let t=e/60,n=t*2,r=t*24;this.vibrate([t,n,r,n*2,r,n*2,t])}clunk(e){let t=e*4/22,n=t*2,r=t/2*5;this.vibrate([t,n,r])}pwm(e,t,n){let r=[t],s=e-t;for(;s>0;)s-=n,s-=t,r.push(n),r.push(t);this.vibrate(r)}createPatternPWM(e,t){return n=>{if(typeof n=="number")this.pwm(n,e,t);else{let r=s=>this.pwm(s,e,t);this.executeSequence([...n],r,()=>{})}}}},i=new C,h=i.enabled,d=i.vibrate.bind(i),E=i.startRecording.bind(i),V=i.stopRecording.bind(i),H=i.createPattern(i.fadeIn.bind(i)),x=i.createPattern(i.fadeOut.bind(i)),m=i.createPattern(i.notification.bind(i)),P=i.createPattern(i.heartbeat.bind(i)),w=i.createPattern(i.clunk.bind(i)),b=i.pwm.bind(i),g=i.createPatternPWM.bind(i),R=i.createPattern.bind(i),ct={enabled:h,vibrate:d,record:E,finish:V,fadeIn:H,fadeOut:x,notification:m,heartbeat:P,clunk:w,pwm:b,createPatternPWM:g,createPattern:R};export{N as HapticsProvider,w as clunk,R as createPattern,g as createPatternPWM,ct as default,h as enabled,H as fadeIn,x as fadeOut,V as finish,P as heartbeat,m as notification,b as pwm,E as record,j as useHapticFeedback,G as useHapticRecorder,z as useHaptics,Q as useHapticsContext,d as vibrate};
|
package/package.json
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@thesonicprint/haptics",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Modern haptics library for React and PWA",
|
|
5
|
+
"main": "./dist/index.js",
|
|
6
|
+
"module": "./dist/index.mjs",
|
|
7
|
+
"types": "./dist/index.d.ts",
|
|
8
|
+
"files": [
|
|
9
|
+
"dist"
|
|
10
|
+
],
|
|
11
|
+
"scripts": {
|
|
12
|
+
"build": "tsup index.js --format cjs,esm --dts --clean --minify --external react,react-dom",
|
|
13
|
+
"dev": "tsup index.js --format cjs,esm --watch --dts",
|
|
14
|
+
"lint": "eslint ."
|
|
15
|
+
},
|
|
16
|
+
"keywords": [
|
|
17
|
+
"haptics",
|
|
18
|
+
"vibrate",
|
|
19
|
+
"react",
|
|
20
|
+
"pwa",
|
|
21
|
+
"feedback"
|
|
22
|
+
],
|
|
23
|
+
"author": "Sonicprint",
|
|
24
|
+
"license": "MIT",
|
|
25
|
+
"peerDependencies": {
|
|
26
|
+
"react": ">=16.8.0",
|
|
27
|
+
"react-dom": ">=16.8.0"
|
|
28
|
+
},
|
|
29
|
+
"devDependencies": {
|
|
30
|
+
"tsup": "^8.0.0",
|
|
31
|
+
"typescript": "^5.0.0",
|
|
32
|
+
"react": "^18.2.0",
|
|
33
|
+
"react-dom": "^18.2.0",
|
|
34
|
+
"@types/react": "^18.2.0",
|
|
35
|
+
"@types/react-dom": "^18.2.0"
|
|
36
|
+
},
|
|
37
|
+
"publishConfig": {
|
|
38
|
+
"access": "public"
|
|
39
|
+
}
|
|
40
|
+
}
|