@molecule/app-audio-recorder-react 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 +115 -0
- package/dist/AudioRecorder.d.ts +27 -0
- package/dist/AudioRecorder.d.ts.map +1 -0
- package/dist/AudioRecorder.js +263 -0
- package/dist/index.d.ts +40 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +39 -0
- package/dist/types.d.ts +46 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +6 -0
- package/package.json +52 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work.
|
|
38
|
+
|
|
39
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
40
|
+
form, that is based on (or derived from) the Work and for which the
|
|
41
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
42
|
+
represent, as a whole, an original work of authorship.
|
|
43
|
+
|
|
44
|
+
"Contribution" shall mean any work of authorship, including the
|
|
45
|
+
original version of the Work and any modifications or additions
|
|
46
|
+
to that Work, that is intentionally submitted to the Licensor for
|
|
47
|
+
inclusion in the Work by the copyright owner or by an individual or
|
|
48
|
+
Legal Entity authorized to submit on behalf of the copyright owner.
|
|
49
|
+
|
|
50
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
51
|
+
on behalf of whom a Contribution has been received by the Licensor and
|
|
52
|
+
subsequently incorporated within the Work.
|
|
53
|
+
|
|
54
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
55
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
56
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
57
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
58
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
59
|
+
Work and such Derivative Works in Source or Object form.
|
|
60
|
+
|
|
61
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
62
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
63
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
64
|
+
patent license to make, have made, use, offer to sell, sell, import,
|
|
65
|
+
and otherwise transfer the Work.
|
|
66
|
+
|
|
67
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
68
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
69
|
+
modifications, and in Source or Object form, provided that You
|
|
70
|
+
meet the following conditions:
|
|
71
|
+
|
|
72
|
+
(a) You must give any other recipients of the Work or
|
|
73
|
+
Derivative Works a copy of this License; and
|
|
74
|
+
|
|
75
|
+
(b) You must cause any modified files to carry prominent notices
|
|
76
|
+
stating that You changed the files; and
|
|
77
|
+
|
|
78
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
79
|
+
that You distribute, all copyright, patent, trademark, and
|
|
80
|
+
attribution notices from the Source form of the Work,
|
|
81
|
+
excluding those notices that do not pertain to any part of
|
|
82
|
+
the Derivative Works; and
|
|
83
|
+
|
|
84
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
85
|
+
distribution, then any Derivative Works that You distribute must
|
|
86
|
+
include a readable copy of the attribution notices contained
|
|
87
|
+
within such NOTICE file.
|
|
88
|
+
|
|
89
|
+
5. Submission of Contributions.
|
|
90
|
+
|
|
91
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
92
|
+
names, trademarks, service marks, or product names of the Licensor.
|
|
93
|
+
|
|
94
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
95
|
+
agreed to in writing, Licensor provides the Work on an "AS IS" BASIS,
|
|
96
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND.
|
|
97
|
+
|
|
98
|
+
8. Limitation of Liability. In no event and under no legal theory shall
|
|
99
|
+
any Contributor be liable to You for damages.
|
|
100
|
+
|
|
101
|
+
9. Accepting Warranty or Additional Liability.
|
|
102
|
+
|
|
103
|
+
Copyright 2026 Molecule Dev, Inc.
|
|
104
|
+
|
|
105
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
106
|
+
you may not use this file except in compliance with the License.
|
|
107
|
+
You may obtain a copy of the License at
|
|
108
|
+
|
|
109
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
110
|
+
|
|
111
|
+
Unless required by applicable law or agreed to in writing, software
|
|
112
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
113
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
114
|
+
See the License for the specific language governing permissions and
|
|
115
|
+
limitations under the License.
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import type { ReactElement } from 'react';
|
|
2
|
+
import type { AudioRecorderProps } from './types.js';
|
|
3
|
+
/**
|
|
4
|
+
* Mic-permission + MediaRecorder UI primitive — emits a `Blob` once the user
|
|
5
|
+
* finishes recording. Pure browser API; no upload, no transcription. Wire to
|
|
6
|
+
* any backend by listening to `onRecorded` and POST-ing the blob.
|
|
7
|
+
*
|
|
8
|
+
* Renders a status badge, an elapsed-time readout, and three buttons:
|
|
9
|
+
* Record (idle/processed) → Pause/Resume + Stop (recording/paused).
|
|
10
|
+
* All button labels and status text flow through `t()` with English
|
|
11
|
+
* `defaultValue` fallbacks; drop in a companion locale bond to translate.
|
|
12
|
+
*
|
|
13
|
+
* Styling is delegated to `getClassMap()` — no Tailwind / raw class names.
|
|
14
|
+
*
|
|
15
|
+
* @param props - Component props.
|
|
16
|
+
* @returns The rendered recorder element.
|
|
17
|
+
*
|
|
18
|
+
* @example
|
|
19
|
+
* ```tsx
|
|
20
|
+
* <AudioRecorder
|
|
21
|
+
* maxDurationSeconds={120}
|
|
22
|
+
* onRecorded={({ blob, mimeType }) => uploadVoiceNote(blob, mimeType)}
|
|
23
|
+
* />
|
|
24
|
+
* ```
|
|
25
|
+
*/
|
|
26
|
+
export declare function AudioRecorder({ onRecorded, onError, mimeType, maxDurationSeconds, dataMolId, className, }: AudioRecorderProps): ReactElement;
|
|
27
|
+
//# sourceMappingURL=AudioRecorder.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"AudioRecorder.d.ts","sourceRoot":"","sources":["../src/AudioRecorder.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAiB,YAAY,EAAE,MAAM,OAAO,CAAA;AAMxD,OAAO,KAAK,EAAE,kBAAkB,EAAsB,MAAM,YAAY,CAAA;AA0BxE;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,wBAAgB,aAAa,CAAC,EAC5B,UAAU,EACV,OAAO,EACP,QAAQ,EACR,kBAAsB,EACtB,SAAS,EACT,SAAS,GACV,EAAE,kBAAkB,GAAG,YAAY,CA4TnC"}
|
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
|
+
import { useCallback, useEffect, useRef, useState } from 'react';
|
|
3
|
+
import { useTranslation } from '@molecule/app-react';
|
|
4
|
+
import { getClassMap } from '@molecule/app-ui';
|
|
5
|
+
/**
|
|
6
|
+
* Format a duration (seconds) as `m:ss`.
|
|
7
|
+
*
|
|
8
|
+
* @param seconds - Duration to format.
|
|
9
|
+
* @returns A short `m:ss` string.
|
|
10
|
+
*/
|
|
11
|
+
function formatDuration(seconds) {
|
|
12
|
+
const m = Math.floor(seconds / 60);
|
|
13
|
+
const s = Math.floor(seconds % 60);
|
|
14
|
+
return `${m}:${String(s).padStart(2, '0')}`;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Resolve the MediaRecorder constructor at call time so jsdom + tests can
|
|
18
|
+
* stub `globalThis.MediaRecorder` without leaking through static imports.
|
|
19
|
+
*
|
|
20
|
+
* @returns The runtime MediaRecorder constructor or `undefined` when the
|
|
21
|
+
* browser environment lacks support.
|
|
22
|
+
*/
|
|
23
|
+
function getMediaRecorder() {
|
|
24
|
+
if (typeof globalThis === 'undefined')
|
|
25
|
+
return undefined;
|
|
26
|
+
return globalThis.MediaRecorder;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Mic-permission + MediaRecorder UI primitive — emits a `Blob` once the user
|
|
30
|
+
* finishes recording. Pure browser API; no upload, no transcription. Wire to
|
|
31
|
+
* any backend by listening to `onRecorded` and POST-ing the blob.
|
|
32
|
+
*
|
|
33
|
+
* Renders a status badge, an elapsed-time readout, and three buttons:
|
|
34
|
+
* Record (idle/processed) → Pause/Resume + Stop (recording/paused).
|
|
35
|
+
* All button labels and status text flow through `t()` with English
|
|
36
|
+
* `defaultValue` fallbacks; drop in a companion locale bond to translate.
|
|
37
|
+
*
|
|
38
|
+
* Styling is delegated to `getClassMap()` — no Tailwind / raw class names.
|
|
39
|
+
*
|
|
40
|
+
* @param props - Component props.
|
|
41
|
+
* @returns The rendered recorder element.
|
|
42
|
+
*
|
|
43
|
+
* @example
|
|
44
|
+
* ```tsx
|
|
45
|
+
* <AudioRecorder
|
|
46
|
+
* maxDurationSeconds={120}
|
|
47
|
+
* onRecorded={({ blob, mimeType }) => uploadVoiceNote(blob, mimeType)}
|
|
48
|
+
* />
|
|
49
|
+
* ```
|
|
50
|
+
*/
|
|
51
|
+
export function AudioRecorder({ onRecorded, onError, mimeType, maxDurationSeconds = 0, dataMolId, className, }) {
|
|
52
|
+
const cm = getClassMap();
|
|
53
|
+
const { t } = useTranslation();
|
|
54
|
+
const [state, setState] = useState('idle');
|
|
55
|
+
const [elapsed, setElapsed] = useState(0);
|
|
56
|
+
const [errorMessage, setErrorMessage] = useState(null);
|
|
57
|
+
const recorderRef = useRef(null);
|
|
58
|
+
const streamRef = useRef(null);
|
|
59
|
+
const chunksRef = useRef([]);
|
|
60
|
+
const tickRef = useRef(null);
|
|
61
|
+
const startedAtRef = useRef(0);
|
|
62
|
+
const pausedAccumRef = useRef(0);
|
|
63
|
+
const pausedAtRef = useRef(null);
|
|
64
|
+
// Cleanup on unmount.
|
|
65
|
+
useEffect(() => {
|
|
66
|
+
return () => {
|
|
67
|
+
if (tickRef.current)
|
|
68
|
+
clearInterval(tickRef.current);
|
|
69
|
+
streamRef.current?.getTracks().forEach((tr) => tr.stop());
|
|
70
|
+
if (recorderRef.current && recorderRef.current.state !== 'inactive') {
|
|
71
|
+
try {
|
|
72
|
+
recorderRef.current.stop();
|
|
73
|
+
}
|
|
74
|
+
catch (_error) {
|
|
75
|
+
// Best-effort cleanup on unmount; recorder may already be inactive or torn down.
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
};
|
|
79
|
+
}, []);
|
|
80
|
+
const stopTick = useCallback(() => {
|
|
81
|
+
if (tickRef.current) {
|
|
82
|
+
clearInterval(tickRef.current);
|
|
83
|
+
tickRef.current = null;
|
|
84
|
+
}
|
|
85
|
+
}, []);
|
|
86
|
+
const startTick = useCallback(() => {
|
|
87
|
+
stopTick();
|
|
88
|
+
tickRef.current = setInterval(() => {
|
|
89
|
+
const now = Date.now();
|
|
90
|
+
const totalPaused = pausedAccumRef.current + (pausedAtRef.current ? now - pausedAtRef.current : 0);
|
|
91
|
+
const sec = Math.floor((now - startedAtRef.current - totalPaused) / 1000);
|
|
92
|
+
setElapsed(sec);
|
|
93
|
+
if (maxDurationSeconds > 0 && sec >= maxDurationSeconds) {
|
|
94
|
+
// Auto-stop.
|
|
95
|
+
try {
|
|
96
|
+
recorderRef.current?.stop();
|
|
97
|
+
}
|
|
98
|
+
catch (_error) {
|
|
99
|
+
// Best-effort auto-stop at max duration; recorder may have already stopped or been torn down.
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
}, 250);
|
|
103
|
+
}, [maxDurationSeconds, stopTick]);
|
|
104
|
+
const handleStart = useCallback(async () => {
|
|
105
|
+
setErrorMessage(null);
|
|
106
|
+
chunksRef.current = [];
|
|
107
|
+
pausedAccumRef.current = 0;
|
|
108
|
+
pausedAtRef.current = null;
|
|
109
|
+
const Ctor = getMediaRecorder();
|
|
110
|
+
if (!Ctor) {
|
|
111
|
+
const err = new Error('MediaRecorder is not supported in this environment');
|
|
112
|
+
setErrorMessage(t('audioRecorder.unsupported', {}, { defaultValue: 'Audio recording is not supported in this browser' }));
|
|
113
|
+
setState('error');
|
|
114
|
+
onError?.(err);
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
try {
|
|
118
|
+
const md = globalThis.navigator?.mediaDevices;
|
|
119
|
+
if (!md?.getUserMedia) {
|
|
120
|
+
throw new Error('Microphone access (getUserMedia) is not available');
|
|
121
|
+
}
|
|
122
|
+
const stream = await md.getUserMedia({ audio: true });
|
|
123
|
+
streamRef.current = stream;
|
|
124
|
+
const opts = mimeType ? { mimeType } : undefined;
|
|
125
|
+
const rec = new Ctor(stream, opts);
|
|
126
|
+
recorderRef.current = rec;
|
|
127
|
+
rec.addEventListener('dataavailable', (e) => {
|
|
128
|
+
if (e.data && e.data.size > 0)
|
|
129
|
+
chunksRef.current.push(e.data);
|
|
130
|
+
});
|
|
131
|
+
rec.addEventListener('stop', () => {
|
|
132
|
+
stopTick();
|
|
133
|
+
const finalMime = rec.mimeType || mimeType || 'audio/webm';
|
|
134
|
+
const blob = new Blob(chunksRef.current, { type: finalMime });
|
|
135
|
+
const dur = elapsedFromRefs(startedAtRef, pausedAccumRef, pausedAtRef);
|
|
136
|
+
// Tear down stream tracks so the OS mic indicator turns off.
|
|
137
|
+
streamRef.current?.getTracks().forEach((tr) => tr.stop());
|
|
138
|
+
streamRef.current = null;
|
|
139
|
+
recorderRef.current = null;
|
|
140
|
+
setState('processed');
|
|
141
|
+
onRecorded({ blob, mimeType: finalMime, durationSeconds: dur });
|
|
142
|
+
});
|
|
143
|
+
rec.addEventListener('error', () => {
|
|
144
|
+
const err = new Error('Recording failed');
|
|
145
|
+
setErrorMessage(t('audioRecorder.error', {}, { defaultValue: 'Recording failed. Please try again.' }));
|
|
146
|
+
setState('error');
|
|
147
|
+
stopTick();
|
|
148
|
+
onError?.(err);
|
|
149
|
+
});
|
|
150
|
+
startedAtRef.current = Date.now();
|
|
151
|
+
setElapsed(0);
|
|
152
|
+
rec.start();
|
|
153
|
+
startTick();
|
|
154
|
+
setState('recording');
|
|
155
|
+
}
|
|
156
|
+
catch (err) {
|
|
157
|
+
const e = err instanceof Error ? err : new Error('Microphone permission denied');
|
|
158
|
+
setErrorMessage(t('audioRecorder.permissionDenied', {}, { defaultValue: 'Microphone permission denied. Allow access and try again.' }));
|
|
159
|
+
setState('error');
|
|
160
|
+
onError?.(e);
|
|
161
|
+
}
|
|
162
|
+
}, [mimeType, onError, onRecorded, startTick, stopTick, t]);
|
|
163
|
+
const handlePause = useCallback(() => {
|
|
164
|
+
const rec = recorderRef.current;
|
|
165
|
+
if (!rec || rec.state !== 'recording')
|
|
166
|
+
return;
|
|
167
|
+
try {
|
|
168
|
+
rec.pause();
|
|
169
|
+
pausedAtRef.current = Date.now();
|
|
170
|
+
setState('paused');
|
|
171
|
+
}
|
|
172
|
+
catch (err) {
|
|
173
|
+
onError?.(err instanceof Error ? err : new Error('Pause failed'));
|
|
174
|
+
}
|
|
175
|
+
}, [onError]);
|
|
176
|
+
const handleResume = useCallback(() => {
|
|
177
|
+
const rec = recorderRef.current;
|
|
178
|
+
if (!rec || rec.state !== 'paused')
|
|
179
|
+
return;
|
|
180
|
+
try {
|
|
181
|
+
rec.resume();
|
|
182
|
+
if (pausedAtRef.current) {
|
|
183
|
+
pausedAccumRef.current += Date.now() - pausedAtRef.current;
|
|
184
|
+
pausedAtRef.current = null;
|
|
185
|
+
}
|
|
186
|
+
setState('recording');
|
|
187
|
+
}
|
|
188
|
+
catch (err) {
|
|
189
|
+
onError?.(err instanceof Error ? err : new Error('Resume failed'));
|
|
190
|
+
}
|
|
191
|
+
}, [onError]);
|
|
192
|
+
const handleStop = useCallback(() => {
|
|
193
|
+
const rec = recorderRef.current;
|
|
194
|
+
if (!rec)
|
|
195
|
+
return;
|
|
196
|
+
if (rec.state === 'inactive')
|
|
197
|
+
return;
|
|
198
|
+
try {
|
|
199
|
+
rec.stop();
|
|
200
|
+
}
|
|
201
|
+
catch (err) {
|
|
202
|
+
onError?.(err instanceof Error ? err : new Error('Stop failed'));
|
|
203
|
+
}
|
|
204
|
+
}, [onError]);
|
|
205
|
+
const recordLabel = t('audioRecorder.record', {}, { defaultValue: 'Record' });
|
|
206
|
+
const pauseLabel = t('audioRecorder.pause', {}, { defaultValue: 'Pause' });
|
|
207
|
+
const resumeLabel = t('audioRecorder.resume', {}, { defaultValue: 'Resume' });
|
|
208
|
+
const stopLabel = t('audioRecorder.stop', {}, { defaultValue: 'Stop' });
|
|
209
|
+
const elapsedLabel = t('audioRecorder.elapsed', { time: formatDuration(elapsed) }, { defaultValue: 'Elapsed {{time}}' });
|
|
210
|
+
const stateLabel = state === 'recording'
|
|
211
|
+
? t('audioRecorder.statusRecording', {}, { defaultValue: 'Recording' })
|
|
212
|
+
: state === 'paused'
|
|
213
|
+
? t('audioRecorder.statusPaused', {}, { defaultValue: 'Paused' })
|
|
214
|
+
: state === 'processed'
|
|
215
|
+
? t('audioRecorder.statusProcessed', {}, { defaultValue: 'Recorded' })
|
|
216
|
+
: state === 'error'
|
|
217
|
+
? t('audioRecorder.statusError', {}, { defaultValue: 'Error' })
|
|
218
|
+
: t('audioRecorder.statusIdle', {}, { defaultValue: 'Ready to record' });
|
|
219
|
+
// Inline styles only for things ClassMap can't express: the live red
|
|
220
|
+
// dot, the bare button reset, and the disabled cursor.
|
|
221
|
+
const dotStyle = {
|
|
222
|
+
display: 'inline-block',
|
|
223
|
+
width: 10,
|
|
224
|
+
height: 10,
|
|
225
|
+
borderRadius: '50%',
|
|
226
|
+
background: state === 'recording'
|
|
227
|
+
? 'var(--mol-color-error, #e11)'
|
|
228
|
+
: 'var(--mol-color-on-surface-variant, #888)',
|
|
229
|
+
marginRight: 8,
|
|
230
|
+
verticalAlign: 'middle',
|
|
231
|
+
animation: state === 'recording' ? 'mol-pulse 1.2s ease-in-out infinite' : undefined,
|
|
232
|
+
};
|
|
233
|
+
const buttonBase = {
|
|
234
|
+
background: 'none',
|
|
235
|
+
border: '1px solid currentColor',
|
|
236
|
+
padding: '0.4rem 0.9rem',
|
|
237
|
+
borderRadius: 6,
|
|
238
|
+
cursor: 'pointer',
|
|
239
|
+
color: 'inherit',
|
|
240
|
+
fontSize: 'inherit',
|
|
241
|
+
lineHeight: 1.2,
|
|
242
|
+
};
|
|
243
|
+
const showRecord = state === 'idle' || state === 'processed' || state === 'error';
|
|
244
|
+
const showPause = state === 'recording';
|
|
245
|
+
const showResume = state === 'paused';
|
|
246
|
+
const showStop = state === 'recording' || state === 'paused';
|
|
247
|
+
const wrapperClass = cm.cn(cm.flex({ direction: 'col', gap: 'xs' }), className);
|
|
248
|
+
return (_jsxs("div", { className: wrapperClass, "data-mol-id": dataMolId ?? 'audio-recorder', "data-state": state, role: "group", "aria-label": t('audioRecorder.group', {}, { defaultValue: 'Audio recorder' }), children: [_jsxs("div", { className: cm.flex({ align: 'center', gap: 'sm' }), children: [_jsx("span", { "aria-hidden": true, style: dotStyle }), _jsx("span", { className: cm.cn(cm.textSize('sm'), cm.fontWeight('semibold')), "data-mol-id": "audio-recorder-status", "aria-live": "polite", children: stateLabel }), _jsx("span", { className: cm.textSize('sm'), "data-mol-id": "audio-recorder-elapsed", "aria-label": elapsedLabel, children: formatDuration(elapsed) })] }), _jsxs("div", { className: cm.flex({ align: 'center', gap: 'sm' }), children: [showRecord && (_jsx("button", { type: "button", onClick: handleStart, "aria-label": recordLabel, "data-action": "record", style: buttonBase, children: recordLabel })), showPause && (_jsx("button", { type: "button", onClick: handlePause, "aria-label": pauseLabel, "data-action": "pause", style: buttonBase, children: pauseLabel })), showResume && (_jsx("button", { type: "button", onClick: handleResume, "aria-label": resumeLabel, "data-action": "resume", style: buttonBase, children: resumeLabel })), showStop && (_jsx("button", { type: "button", onClick: handleStop, "aria-label": stopLabel, "data-action": "stop", style: buttonBase, children: stopLabel }))] }), errorMessage && (_jsx("div", { className: cm.textSize('sm'), role: "alert", "data-mol-id": "audio-recorder-error", style: { color: 'var(--mol-color-error, #e11)' }, children: errorMessage }))] }));
|
|
249
|
+
}
|
|
250
|
+
/**
|
|
251
|
+
* Compute final recording duration from refs at stop time.
|
|
252
|
+
*
|
|
253
|
+
* @param startedAtRef - Ref holding the recording start timestamp.
|
|
254
|
+
* @param pausedAccumRef - Ref holding accumulated paused milliseconds.
|
|
255
|
+
* @param pausedAtRef - Ref holding the current pause start (or null).
|
|
256
|
+
* @returns Duration in whole seconds.
|
|
257
|
+
*/
|
|
258
|
+
function elapsedFromRefs(startedAtRef, pausedAccumRef, pausedAtRef) {
|
|
259
|
+
const now = Date.now();
|
|
260
|
+
const pausedNow = pausedAtRef.current ? now - pausedAtRef.current : 0;
|
|
261
|
+
const totalPaused = pausedAccumRef.current + pausedNow;
|
|
262
|
+
return Math.max(0, Math.floor((now - startedAtRef.current - totalPaused) / 1000));
|
|
263
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Mic-permission + MediaRecorder UI primitive — emits a `Blob` once the
|
|
3
|
+
* user finishes recording. Pure browser API; no upload, no transcription.
|
|
4
|
+
*
|
|
5
|
+
* Used by AI-voice-assistant, AI-meeting-notes (manual capture), and
|
|
6
|
+
* AI-customer-service-bot. Wire to any backend by handling `onRecorded`.
|
|
7
|
+
*
|
|
8
|
+
* @example
|
|
9
|
+
* ```tsx
|
|
10
|
+
* import { AudioRecorder } from '@molecule/app-audio-recorder-react'
|
|
11
|
+
*
|
|
12
|
+
* <AudioRecorder
|
|
13
|
+
* maxDurationSeconds={300}
|
|
14
|
+
* onRecorded={({ blob, mimeType, durationSeconds }) => {
|
|
15
|
+
* console.log(`Captured ${durationSeconds}s of ${mimeType}`)
|
|
16
|
+
* uploadVoiceNote(blob)
|
|
17
|
+
* }}
|
|
18
|
+
* />
|
|
19
|
+
* ```
|
|
20
|
+
*
|
|
21
|
+
* @remarks
|
|
22
|
+
* `getUserMedia` only exists in a secure context — the recorder works on
|
|
23
|
+
* `https://` and `localhost`, and permanently shows the error state on
|
|
24
|
+
* plain HTTP. The requested `mimeType` is best-effort: unsupported types
|
|
25
|
+
* silently fall back to the browser default (the actual type is reported
|
|
26
|
+
* in `onRecorded`). Reaching `maxDurationSeconds` auto-stops and still
|
|
27
|
+
* fires `onRecorded`. The recording dot's pulse uses a `mol-pulse` CSS
|
|
28
|
+
* animation shipped in the molecule base stylesheet
|
|
29
|
+
* (`@molecule/app-ui-tailwind`'s `base.css`, loaded by every molecule app),
|
|
30
|
+
* so the dot animates out of the box; a host that does not load that
|
|
31
|
+
* stylesheet can define `@keyframes mol-pulse { 50% { opacity: .4 } }`
|
|
32
|
+
* itself (without it the dot is static but recording still works).
|
|
33
|
+
* Translations come from the companion
|
|
34
|
+
* `@molecule/app-locales-audio-recorder` locale bond.
|
|
35
|
+
*
|
|
36
|
+
* @module
|
|
37
|
+
*/
|
|
38
|
+
export * from './AudioRecorder.js';
|
|
39
|
+
export * from './types.js';
|
|
40
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoCG;AAEH,cAAc,oBAAoB,CAAA;AAClC,cAAc,YAAY,CAAA"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Mic-permission + MediaRecorder UI primitive — emits a `Blob` once the
|
|
3
|
+
* user finishes recording. Pure browser API; no upload, no transcription.
|
|
4
|
+
*
|
|
5
|
+
* Used by AI-voice-assistant, AI-meeting-notes (manual capture), and
|
|
6
|
+
* AI-customer-service-bot. Wire to any backend by handling `onRecorded`.
|
|
7
|
+
*
|
|
8
|
+
* @example
|
|
9
|
+
* ```tsx
|
|
10
|
+
* import { AudioRecorder } from '@molecule/app-audio-recorder-react'
|
|
11
|
+
*
|
|
12
|
+
* <AudioRecorder
|
|
13
|
+
* maxDurationSeconds={300}
|
|
14
|
+
* onRecorded={({ blob, mimeType, durationSeconds }) => {
|
|
15
|
+
* console.log(`Captured ${durationSeconds}s of ${mimeType}`)
|
|
16
|
+
* uploadVoiceNote(blob)
|
|
17
|
+
* }}
|
|
18
|
+
* />
|
|
19
|
+
* ```
|
|
20
|
+
*
|
|
21
|
+
* @remarks
|
|
22
|
+
* `getUserMedia` only exists in a secure context — the recorder works on
|
|
23
|
+
* `https://` and `localhost`, and permanently shows the error state on
|
|
24
|
+
* plain HTTP. The requested `mimeType` is best-effort: unsupported types
|
|
25
|
+
* silently fall back to the browser default (the actual type is reported
|
|
26
|
+
* in `onRecorded`). Reaching `maxDurationSeconds` auto-stops and still
|
|
27
|
+
* fires `onRecorded`. The recording dot's pulse uses a `mol-pulse` CSS
|
|
28
|
+
* animation shipped in the molecule base stylesheet
|
|
29
|
+
* (`@molecule/app-ui-tailwind`'s `base.css`, loaded by every molecule app),
|
|
30
|
+
* so the dot animates out of the box; a host that does not load that
|
|
31
|
+
* stylesheet can define `@keyframes mol-pulse { 50% { opacity: .4 } }`
|
|
32
|
+
* itself (without it the dot is static but recording still works).
|
|
33
|
+
* Translations come from the companion
|
|
34
|
+
* `@molecule/app-locales-audio-recorder` locale bond.
|
|
35
|
+
*
|
|
36
|
+
* @module
|
|
37
|
+
*/
|
|
38
|
+
export * from './AudioRecorder.js';
|
|
39
|
+
export * from './types.js';
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Public types for `<AudioRecorder>`.
|
|
3
|
+
*
|
|
4
|
+
* @module
|
|
5
|
+
*/
|
|
6
|
+
/** Recorder lifecycle states. */
|
|
7
|
+
export type AudioRecorderState = 'idle' | 'recording' | 'paused' | 'processed' | 'error';
|
|
8
|
+
/** Result emitted via `onRecorded` once a recording finishes. */
|
|
9
|
+
export interface AudioRecording {
|
|
10
|
+
/** The captured audio as a `Blob`. */
|
|
11
|
+
blob: Blob;
|
|
12
|
+
/** Audio MIME type (e.g. `'audio/webm'`). */
|
|
13
|
+
mimeType: string;
|
|
14
|
+
/** Recording duration in seconds (whole-second precision). */
|
|
15
|
+
durationSeconds: number;
|
|
16
|
+
}
|
|
17
|
+
/** Props for {@link AudioRecorder}. */
|
|
18
|
+
export interface AudioRecorderProps {
|
|
19
|
+
/**
|
|
20
|
+
* Called once the user stops recording and a Blob is ready. Parents are
|
|
21
|
+
* responsible for uploading or persisting the blob.
|
|
22
|
+
*/
|
|
23
|
+
onRecorded: (rec: AudioRecording) => void;
|
|
24
|
+
/**
|
|
25
|
+
* Called whenever a recording error occurs (permission denied, no
|
|
26
|
+
* MediaRecorder support, hardware failure). Optional — the component
|
|
27
|
+
* surfaces a translated error message regardless.
|
|
28
|
+
*/
|
|
29
|
+
onError?: (err: Error) => void;
|
|
30
|
+
/**
|
|
31
|
+
* Optional MIME type to request from MediaRecorder. Falls back to the
|
|
32
|
+
* browser's default if unsupported. Common values: `'audio/webm'`,
|
|
33
|
+
* `'audio/mp4'`, `'audio/ogg;codecs=opus'`.
|
|
34
|
+
*/
|
|
35
|
+
mimeType?: string;
|
|
36
|
+
/**
|
|
37
|
+
* Maximum recording duration (seconds). When reached, recording stops
|
|
38
|
+
* automatically and `onRecorded` fires. `0` (default) means unlimited.
|
|
39
|
+
*/
|
|
40
|
+
maxDurationSeconds?: number;
|
|
41
|
+
/** `data-mol-id` attribute for AI-agent selectors. */
|
|
42
|
+
dataMolId?: string;
|
|
43
|
+
/** Extra classes appended via the ClassMap `cn()` helper. */
|
|
44
|
+
className?: string;
|
|
45
|
+
}
|
|
46
|
+
//# sourceMappingURL=types.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,iCAAiC;AACjC,MAAM,MAAM,kBAAkB,GAAG,MAAM,GAAG,WAAW,GAAG,QAAQ,GAAG,WAAW,GAAG,OAAO,CAAA;AAExF,iEAAiE;AACjE,MAAM,WAAW,cAAc;IAC7B,sCAAsC;IACtC,IAAI,EAAE,IAAI,CAAA;IACV,6CAA6C;IAC7C,QAAQ,EAAE,MAAM,CAAA;IAChB,8DAA8D;IAC9D,eAAe,EAAE,MAAM,CAAA;CACxB;AAED,uCAAuC;AACvC,MAAM,WAAW,kBAAkB;IACjC;;;OAGG;IACH,UAAU,EAAE,CAAC,GAAG,EAAE,cAAc,KAAK,IAAI,CAAA;IACzC;;;;OAIG;IACH,OAAO,CAAC,EAAE,CAAC,GAAG,EAAE,KAAK,KAAK,IAAI,CAAA;IAC9B;;;;OAIG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB;;;OAGG;IACH,kBAAkB,CAAC,EAAE,MAAM,CAAA;IAC3B,sDAAsD;IACtD,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,6DAA6D;IAC7D,SAAS,CAAC,EAAE,MAAM,CAAA;CACnB"}
|
package/dist/types.js
ADDED
package/package.json
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@molecule/app-audio-recorder-react",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Mic permission + MediaRecorder wrapper that emits a Blob — voice notes, meeting capture, AI voice agents",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "dist/index.js",
|
|
7
|
+
"types": "dist/index.d.ts",
|
|
8
|
+
"scripts": {
|
|
9
|
+
"build": "tsc",
|
|
10
|
+
"test": "vitest run",
|
|
11
|
+
"test:watch": "vitest"
|
|
12
|
+
},
|
|
13
|
+
"exports": {
|
|
14
|
+
".": {
|
|
15
|
+
"types": "./dist/index.d.ts",
|
|
16
|
+
"import": "./dist/index.js"
|
|
17
|
+
}
|
|
18
|
+
},
|
|
19
|
+
"files": [
|
|
20
|
+
"dist"
|
|
21
|
+
],
|
|
22
|
+
"keywords": [
|
|
23
|
+
"molecule",
|
|
24
|
+
"audio-recorder",
|
|
25
|
+
"mediarecorder",
|
|
26
|
+
"voice",
|
|
27
|
+
"react"
|
|
28
|
+
],
|
|
29
|
+
"license": "Apache-2.0",
|
|
30
|
+
"peerDependencies": {
|
|
31
|
+
"@molecule/app-i18n": "^1.0.0",
|
|
32
|
+
"@molecule/app-react": "^1.0.0",
|
|
33
|
+
"@molecule/app-ui": "^1.0.0",
|
|
34
|
+
"react": "^18.0.0 || ^19.0.0"
|
|
35
|
+
},
|
|
36
|
+
"devDependencies": {
|
|
37
|
+
"@molecule/app-i18n": "1.0.0",
|
|
38
|
+
"@molecule/app-react": "1.0.0",
|
|
39
|
+
"@molecule/app-ui": "1.0.0",
|
|
40
|
+
"@molecule/app-ui-tailwind": "1.0.0",
|
|
41
|
+
"@testing-library/dom": "10.4.1",
|
|
42
|
+
"@testing-library/react": "16.3.2",
|
|
43
|
+
"@types/node": "26.1.2",
|
|
44
|
+
"@types/react": "19.2.17",
|
|
45
|
+
"@types/react-dom": "19.2.3",
|
|
46
|
+
"jsdom": "30.0.1",
|
|
47
|
+
"react": "19.2.8",
|
|
48
|
+
"react-dom": "19.2.8",
|
|
49
|
+
"typescript": "6.0.3",
|
|
50
|
+
"vitest": "4.1.10"
|
|
51
|
+
}
|
|
52
|
+
}
|