bzzz 0.1.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/dist/index.js ADDED
@@ -0,0 +1,430 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ createHaptics: () => createHaptics,
24
+ defaultPatterns: () => defaultPatterns,
25
+ dispose: () => dispose,
26
+ getCapabilities: () => getCapabilityState,
27
+ haptics: () => haptics,
28
+ isEnabled: () => isEnabled,
29
+ setEnabled: () => setEnabled
30
+ });
31
+ module.exports = __toCommonJS(index_exports);
32
+
33
+ // src/capabilities.ts
34
+ function getAudioContextConstructor() {
35
+ const runtime = globalThis;
36
+ return runtime.AudioContext ?? runtime.webkitAudioContext;
37
+ }
38
+ function isIOS() {
39
+ if (typeof navigator === "undefined") return false;
40
+ const ua = navigator.userAgent;
41
+ if (/iPad|iPhone|iPod/.test(ua)) return true;
42
+ if (navigator.maxTouchPoints > 1) {
43
+ if (navigator.platform === "MacIntel") return true;
44
+ const uad = navigator.userAgentData;
45
+ if (uad?.platform === "macOS") return true;
46
+ }
47
+ return false;
48
+ }
49
+ function hasVibrationHardware() {
50
+ if (typeof navigator === "undefined") return false;
51
+ if (typeof navigator.vibrate !== "function") return false;
52
+ if (typeof matchMedia !== "undefined" && matchMedia("(pointer: coarse)").matches) {
53
+ return true;
54
+ }
55
+ return false;
56
+ }
57
+ function prefersReducedMotion() {
58
+ if (typeof matchMedia === "undefined") return false;
59
+ return matchMedia("(prefers-reduced-motion: reduce)").matches;
60
+ }
61
+ function getCapabilityState() {
62
+ return {
63
+ haptics: hasVibrationHardware(),
64
+ audio: Boolean(getAudioContextConstructor()),
65
+ ios: isIOS(),
66
+ reducedMotion: prefersReducedMotion()
67
+ };
68
+ }
69
+
70
+ // src/patterns.ts
71
+ var defaultPatterns = {
72
+ selection: [
73
+ { type: "pulse", duration: 8, intensity: 0.4 },
74
+ { type: "gap", duration: 12 },
75
+ { type: "pulse", duration: 10, intensity: 0.6 }
76
+ ],
77
+ success: [
78
+ { type: "pulse", duration: 15, intensity: 0.4 },
79
+ { type: "gap", duration: 40 },
80
+ { type: "pulse", duration: 25, intensity: 0.7 },
81
+ { type: "gap", duration: 60 },
82
+ { type: "pulse", duration: 35, intensity: 1 }
83
+ ],
84
+ error: [
85
+ { type: "pulse", duration: 30, intensity: 0.7 },
86
+ { type: "gap", duration: 30 },
87
+ { type: "pulse", duration: 30, intensity: 0.7 },
88
+ { type: "gap", duration: 30 },
89
+ { type: "pulse", duration: 35, intensity: 0.9 },
90
+ { type: "gap", duration: 30 },
91
+ { type: "pulse", duration: 40, intensity: 1 }
92
+ ],
93
+ toggle: [
94
+ { type: "pulse", duration: 12, intensity: 0.5 },
95
+ { type: "gap", duration: 24 },
96
+ { type: "pulse", duration: 18, intensity: 0.8 },
97
+ { type: "gap", duration: 24 },
98
+ { type: "pulse", duration: 12, intensity: 0.5 }
99
+ ],
100
+ snap: [
101
+ { type: "pulse", duration: 8, intensity: 0.3 },
102
+ { type: "gap", duration: 8 },
103
+ { type: "pulse", duration: 10, intensity: 0.5 },
104
+ { type: "gap", duration: 8 },
105
+ { type: "pulse", duration: 12, intensity: 0.7 },
106
+ { type: "gap", duration: 8 },
107
+ { type: "pulse", duration: 14, intensity: 0.9 },
108
+ { type: "gap", duration: 8 },
109
+ { type: "pulse", duration: 16, intensity: 1 }
110
+ ]
111
+ };
112
+ for (const pattern of Object.values(defaultPatterns)) {
113
+ Object.freeze(pattern);
114
+ for (const block of pattern) {
115
+ Object.freeze(block);
116
+ }
117
+ }
118
+ Object.freeze(defaultPatterns);
119
+ function clonePattern(pattern) {
120
+ return pattern.map((block) => ({ ...block }));
121
+ }
122
+
123
+ // src/audio.ts
124
+ var CLICK_DURATION = 5e-3;
125
+ var CLICK_GAIN = 0.3;
126
+ var FILTER_FREQ = 2200;
127
+ var FILTER_Q = 3;
128
+ var engine = null;
129
+ function getAudioEngine() {
130
+ if (engine) return engine;
131
+ try {
132
+ let createClickBuffer2 = function() {
133
+ const buffer = ctx.createBuffer(1, bufferLength, ctx.sampleRate);
134
+ const data = buffer.getChannelData(0);
135
+ for (let i = 0; i < data.length; i++) {
136
+ const t = i / data.length;
137
+ const envelope = (1 - t) * (1 - t);
138
+ data[i] = (Math.random() * 2 - 1) * envelope;
139
+ }
140
+ return buffer;
141
+ }, playTap2 = function(startTime, intensity = 1) {
142
+ if (ctx.state === "suspended") {
143
+ ctx.resume().catch(() => void 0);
144
+ }
145
+ const level = Math.max(0, Math.min(1, intensity));
146
+ if (level === 0) return;
147
+ const buffer = createClickBuffer2();
148
+ const source = ctx.createBufferSource();
149
+ source.buffer = buffer;
150
+ const filter = ctx.createBiquadFilter();
151
+ filter.type = "lowpass";
152
+ filter.frequency.setValueAtTime(
153
+ FILTER_FREQ + (Math.random() - 0.5) * 400,
154
+ startTime
155
+ );
156
+ filter.Q.setValueAtTime(FILTER_Q, startTime);
157
+ const gain = ctx.createGain();
158
+ gain.gain.setValueAtTime(CLICK_GAIN * level, startTime);
159
+ source.connect(filter);
160
+ filter.connect(gain);
161
+ gain.connect(ctx.destination);
162
+ source.start(startTime);
163
+ source.stop(startTime + CLICK_DURATION);
164
+ };
165
+ var createClickBuffer = createClickBuffer2, playTap = playTap2;
166
+ const AC = globalThis.AudioContext ?? globalThis.webkitAudioContext;
167
+ if (!AC) return null;
168
+ const ctx = new AC();
169
+ const bufferLength = Math.ceil(CLICK_DURATION * ctx.sampleRate);
170
+ engine = { playTap: playTap2, context: ctx };
171
+ return engine;
172
+ } catch {
173
+ return null;
174
+ }
175
+ }
176
+ function resetAudioEngine() {
177
+ if (engine) {
178
+ try {
179
+ engine.context.close().catch(() => {
180
+ });
181
+ } catch {
182
+ }
183
+ }
184
+ engine = null;
185
+ }
186
+
187
+ // src/safari-haptics.ts
188
+ var TAP_INTERVAL = 26;
189
+ var label = null;
190
+ function ensureDOM() {
191
+ if (label) return;
192
+ if (typeof document === "undefined") return;
193
+ label = document.createElement("label");
194
+ label.ariaHidden = "true";
195
+ Object.assign(label.style, {
196
+ position: "fixed",
197
+ left: "-9999px",
198
+ top: "-9999px",
199
+ opacity: "0.01",
200
+ pointerEvents: "none"
201
+ });
202
+ const input = document.createElement("input");
203
+ input.type = "checkbox";
204
+ input.setAttribute("switch", "");
205
+ input.ariaHidden = "true";
206
+ input.tabIndex = -1;
207
+ label.appendChild(input);
208
+ document.body.appendChild(label);
209
+ }
210
+ function triggerSafariHaptic() {
211
+ if (typeof document === "undefined") return;
212
+ ensureDOM();
213
+ label?.click();
214
+ }
215
+ var pendingTimers = [];
216
+ function playSafariPattern(pattern) {
217
+ for (const id of pendingTimers) clearTimeout(id);
218
+ pendingTimers = [];
219
+ let cursorMs = 0;
220
+ const pulseTimes = [];
221
+ for (const block of pattern) {
222
+ if (block.type === "pulse" && block.duration >= 5) {
223
+ pulseTimes.push(cursorMs);
224
+ }
225
+ cursorMs += block.duration;
226
+ }
227
+ if (pulseTimes.length === 0) return;
228
+ triggerSafariHaptic();
229
+ for (let i = 1; i < pulseTimes.length; i++) {
230
+ const delay = Math.max(pulseTimes[i] - pulseTimes[0], i * TAP_INTERVAL);
231
+ pendingTimers.push(setTimeout(() => triggerSafariHaptic(), delay));
232
+ }
233
+ }
234
+ function destroySafariHaptic() {
235
+ for (const id of pendingTimers) clearTimeout(id);
236
+ pendingTimers = [];
237
+ if (label?.parentNode) label.parentNode.removeChild(label);
238
+ label = null;
239
+ }
240
+
241
+ // src/playback.ts
242
+ var PWM_CYCLE = 20;
243
+ function modulateVibration(duration, intensity) {
244
+ if (intensity >= 1) return [duration];
245
+ if (intensity <= 0) return [];
246
+ if (duration <= PWM_CYCLE) return [duration];
247
+ const onTime = Math.max(1, Math.round(PWM_CYCLE * intensity));
248
+ const offTime = PWM_CYCLE - onTime;
249
+ const result = [];
250
+ let remaining = duration;
251
+ while (remaining >= PWM_CYCLE) {
252
+ result.push(onTime, offTime);
253
+ remaining -= PWM_CYCLE;
254
+ }
255
+ if (remaining > 0) {
256
+ const remainOn = Math.min(remaining, onTime);
257
+ result.push(remainOn);
258
+ const remainOff = remaining - remainOn;
259
+ if (remainOff > 0) {
260
+ result.push(remainOff);
261
+ }
262
+ }
263
+ return result;
264
+ }
265
+ function toVibrationPattern(pattern) {
266
+ const result = [];
267
+ for (const block of pattern) {
268
+ if (block.type === "pulse") {
269
+ const intensity = block.intensity ?? 1;
270
+ const modulated = modulateVibration(block.duration, intensity);
271
+ if (modulated.length > 0) {
272
+ if (result.length > 0 && result.length % 2 === 1) {
273
+ result.push(0, ...modulated);
274
+ } else {
275
+ result.push(...modulated);
276
+ }
277
+ }
278
+ } else if (block.type === "gap") {
279
+ if (result.length === 0) continue;
280
+ if (result.length % 2 === 0) {
281
+ result[result.length - 1] += block.duration;
282
+ } else {
283
+ result.push(block.duration);
284
+ }
285
+ }
286
+ }
287
+ return result;
288
+ }
289
+ function playAudioClicks(pattern) {
290
+ const engine2 = getAudioEngine();
291
+ if (!engine2) return false;
292
+ const startTime = engine2.context.currentTime + 0.01;
293
+ let cursorMs = 0;
294
+ let scheduled = false;
295
+ for (const block of pattern) {
296
+ if (block.type === "pulse" && block.duration >= 5) {
297
+ engine2.playTap(startTime + cursorMs / 1e3, block.intensity ?? 1);
298
+ scheduled = true;
299
+ }
300
+ cursorMs += block.duration;
301
+ }
302
+ return scheduled;
303
+ }
304
+ function validatePattern(pattern) {
305
+ return pattern.map((b) => {
306
+ const duration = Math.max(0, Number.isFinite(b.duration) ? b.duration : 0);
307
+ if (b.type === "pulse") {
308
+ return {
309
+ type: "pulse",
310
+ duration,
311
+ intensity: b.intensity != null ? Math.max(0, Math.min(1, b.intensity)) : void 0
312
+ };
313
+ }
314
+ return { type: "gap", duration };
315
+ });
316
+ }
317
+ function playPattern(pattern, options) {
318
+ const capabilities = getCapabilityState();
319
+ if (capabilities.reducedMotion || options?.enabled === false) return { mode: "none" };
320
+ const validated = validatePattern(pattern);
321
+ const vibrationPattern = toVibrationPattern(validated);
322
+ if (capabilities.ios && validated.some((b) => b.type === "pulse" && b.duration >= 5)) {
323
+ playSafariPattern(validated);
324
+ try {
325
+ playAudioClicks(validated);
326
+ } catch {
327
+ }
328
+ return { mode: "haptics" };
329
+ }
330
+ if (vibrationPattern.length > 0 && capabilities.haptics && navigator.vibrate(vibrationPattern)) {
331
+ try {
332
+ playAudioClicks(validated);
333
+ } catch {
334
+ }
335
+ return { mode: "haptics" };
336
+ }
337
+ if (capabilities.audio) {
338
+ try {
339
+ const played = playAudioClicks(validated);
340
+ return { mode: played ? "audio" : "none" };
341
+ } catch {
342
+ return { mode: "none" };
343
+ }
344
+ }
345
+ return { mode: "none" };
346
+ }
347
+
348
+ // src/runtime.ts
349
+ function createRegistry(overrides) {
350
+ const registry = /* @__PURE__ */ new Map();
351
+ for (const [name, pattern] of Object.entries(defaultPatterns)) {
352
+ registry.set(name, clonePattern(pattern));
353
+ }
354
+ if (overrides) {
355
+ for (const [name, pattern] of Object.entries(overrides)) {
356
+ registry.set(name, clonePattern(pattern));
357
+ }
358
+ }
359
+ return registry;
360
+ }
361
+ function resolvePattern(registry, nameOrPattern) {
362
+ if (typeof nameOrPattern !== "string") {
363
+ return clonePattern(nameOrPattern);
364
+ }
365
+ const pattern = registry.get(nameOrPattern);
366
+ if (!pattern) {
367
+ throw new Error(`Unknown haptics pattern: ${nameOrPattern}`);
368
+ }
369
+ return clonePattern(pattern);
370
+ }
371
+ var singletonEnabled = true;
372
+ function playNamedPattern(name) {
373
+ return playPattern(clonePattern(defaultPatterns[name]), { enabled: singletonEnabled });
374
+ }
375
+ var haptics = {
376
+ selection: () => playNamedPattern("selection"),
377
+ success: () => playNamedPattern("success"),
378
+ error: () => playNamedPattern("error"),
379
+ toggle: () => playNamedPattern("toggle"),
380
+ snap: () => playNamedPattern("snap"),
381
+ play: (pattern) => playPattern(clonePattern(pattern), { enabled: singletonEnabled }),
382
+ getCapabilities: () => getCapabilityState(),
383
+ setEnabled: (enabled) => {
384
+ singletonEnabled = enabled;
385
+ },
386
+ isEnabled: () => singletonEnabled,
387
+ dispose: () => {
388
+ resetAudioEngine();
389
+ destroySafariHaptic();
390
+ }
391
+ };
392
+ function createHaptics(options = {}) {
393
+ const registry = createRegistry(options.patterns);
394
+ let enabled = true;
395
+ return {
396
+ play: (nameOrPattern) => playPattern(resolvePattern(registry, nameOrPattern), { enabled }),
397
+ register: (name, pattern) => {
398
+ registry.set(name, clonePattern(pattern));
399
+ },
400
+ getCapabilities: () => getCapabilityState(),
401
+ setEnabled: (value) => {
402
+ enabled = value;
403
+ },
404
+ isEnabled: () => enabled,
405
+ dispose: () => {
406
+ resetAudioEngine();
407
+ destroySafariHaptic();
408
+ }
409
+ };
410
+ }
411
+ function dispose() {
412
+ resetAudioEngine();
413
+ destroySafariHaptic();
414
+ }
415
+ function setEnabled(enabled) {
416
+ haptics.setEnabled(enabled);
417
+ }
418
+ function isEnabled() {
419
+ return haptics.isEnabled();
420
+ }
421
+ // Annotate the CommonJS export names for ESM import in node:
422
+ 0 && (module.exports = {
423
+ createHaptics,
424
+ defaultPatterns,
425
+ dispose,
426
+ getCapabilities,
427
+ haptics,
428
+ isEnabled,
429
+ setEnabled
430
+ });
package/dist/index.mjs ADDED
@@ -0,0 +1,18 @@
1
+ import {
2
+ createHaptics,
3
+ defaultPatterns,
4
+ dispose,
5
+ getCapabilityState,
6
+ haptics,
7
+ isEnabled,
8
+ setEnabled
9
+ } from "./chunk-RLTRZ2WN.mjs";
10
+ export {
11
+ createHaptics,
12
+ defaultPatterns,
13
+ dispose,
14
+ getCapabilityState as getCapabilities,
15
+ haptics,
16
+ isEnabled,
17
+ setEnabled
18
+ };
@@ -0,0 +1,34 @@
1
+ import { a as CreateHapticsOptions, P as PatternBlock, e as PlaybackResult, C as CapabilityState } from './types-BRn0rP4m.mjs';
2
+
3
+ type UseHapticsReturn = {
4
+ selection: () => PlaybackResult;
5
+ success: () => PlaybackResult;
6
+ error: () => PlaybackResult;
7
+ toggle: () => PlaybackResult;
8
+ snap: () => PlaybackResult;
9
+ play: (pattern: readonly PatternBlock[]) => PlaybackResult;
10
+ getCapabilities: () => CapabilityState;
11
+ isEnabled: () => boolean;
12
+ setEnabled: (enabled: boolean) => void;
13
+ };
14
+ /**
15
+ * React hook for the bzzz singleton.
16
+ * All returned references are stable (defined on a const object), safe for
17
+ * dependency arrays. Does NOT dispose on unmount — the singleton is shared.
18
+ */
19
+ declare function useHaptics(): UseHapticsReturn;
20
+ type UseCreateHapticsReturn = {
21
+ play: (nameOrPattern: string | readonly PatternBlock[]) => PlaybackResult;
22
+ register: (name: string, pattern: readonly PatternBlock[]) => void;
23
+ getCapabilities: () => CapabilityState;
24
+ isEnabled: () => boolean;
25
+ setEnabled: (enabled: boolean) => void;
26
+ };
27
+ /**
28
+ * React hook that creates an isolated haptics instance.
29
+ * Disposes automatically on unmount. The initial `options` are captured once
30
+ * and not reactive — changing options after mount has no effect.
31
+ */
32
+ declare function useCreateHaptics(options?: CreateHapticsOptions): UseCreateHapticsReturn;
33
+
34
+ export { useCreateHaptics, useHaptics };
@@ -0,0 +1,34 @@
1
+ import { a as CreateHapticsOptions, P as PatternBlock, e as PlaybackResult, C as CapabilityState } from './types-BRn0rP4m.js';
2
+
3
+ type UseHapticsReturn = {
4
+ selection: () => PlaybackResult;
5
+ success: () => PlaybackResult;
6
+ error: () => PlaybackResult;
7
+ toggle: () => PlaybackResult;
8
+ snap: () => PlaybackResult;
9
+ play: (pattern: readonly PatternBlock[]) => PlaybackResult;
10
+ getCapabilities: () => CapabilityState;
11
+ isEnabled: () => boolean;
12
+ setEnabled: (enabled: boolean) => void;
13
+ };
14
+ /**
15
+ * React hook for the bzzz singleton.
16
+ * All returned references are stable (defined on a const object), safe for
17
+ * dependency arrays. Does NOT dispose on unmount — the singleton is shared.
18
+ */
19
+ declare function useHaptics(): UseHapticsReturn;
20
+ type UseCreateHapticsReturn = {
21
+ play: (nameOrPattern: string | readonly PatternBlock[]) => PlaybackResult;
22
+ register: (name: string, pattern: readonly PatternBlock[]) => void;
23
+ getCapabilities: () => CapabilityState;
24
+ isEnabled: () => boolean;
25
+ setEnabled: (enabled: boolean) => void;
26
+ };
27
+ /**
28
+ * React hook that creates an isolated haptics instance.
29
+ * Disposes automatically on unmount. The initial `options` are captured once
30
+ * and not reactive — changing options after mount has no effect.
31
+ */
32
+ declare function useCreateHaptics(options?: CreateHapticsOptions): UseCreateHapticsReturn;
33
+
34
+ export { useCreateHaptics, useHaptics };