@openpeepshq/rn-components 0.22.0 → 0.23.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.
@@ -0,0 +1,913 @@
1
+ /**
2
+ * Integration test for the RN voice-note happy path (#327): the
3
+ * AudioPickerSheet "record" affordance opens the (real) RecordAudioSheet, a
4
+ * take is recorded and confirmed, and the resulting file is uploaded and
5
+ * handed to `onSelect`. `pick`, `uploadMedia`, the native recorder, and the
6
+ * bottom-sheet plumbing are mocked; both sheets are real components.
7
+ */
8
+
9
+ const React = require('react');
10
+ const ReactTestRenderer = require('react-test-renderer');
11
+
12
+ const pick = jest.fn(async () => []);
13
+ const uploadMedia = jest.fn();
14
+ // Forward to the sheet's imperative handle, like the real lib — so a
15
+ // dismiss actually drives the sheet's `onDismiss` (the record sheet's
16
+ // handleDismiss) rather than being a pure no-op that skips the reset path.
17
+ const bottomSheetClose = jest.fn((ref: unknown) =>
18
+ (ref as { current: { close: () => void } | null })?.current?.close()
19
+ );
20
+ const bottomSheetDismiss = jest.fn((ref: unknown) =>
21
+ (ref as { current: { dismiss: () => void } | null })?.current?.dismiss()
22
+ );
23
+
24
+ // The sheet-modal imperative handles, registered in mount order so a test can
25
+ // drive the inner record sheet (present/close).
26
+ const mockSheetApis: Record<string, jest.Mock>[] = [];
27
+ const recorderInstances: unknown[] = [];
28
+
29
+ jest.mock('react-native', () => ({
30
+ View: (props: { children?: unknown }) =>
31
+ React.createElement('View', null, props.children),
32
+ Text: (props: { children?: unknown }) =>
33
+ React.createElement('Text', null, props.children),
34
+ Dimensions: { get: () => ({ width: 390 }) },
35
+ ScrollView: (props: { children?: unknown }) =>
36
+ React.createElement('ScrollView', null, props.children),
37
+ PermissionsAndroid: {
38
+ PERMISSIONS: { RECORD_AUDIO: 'android.permission.RECORD_AUDIO' },
39
+ RESULTS: { GRANTED: 'granted', DENIED: 'denied' },
40
+ request: jest.fn(async () => 'granted'),
41
+ },
42
+ Platform: { OS: 'android' },
43
+ }));
44
+
45
+ // `t` resolves through the real locale bundles (mirroring i18next's
46
+ // en-fallback) instead of returning the raw key: a key missing from *both*
47
+ // bundles then surfaces as the raw key in assertions and fails them, so the
48
+ // suite pins resolved copy (a key that i18next would render verbatim to
49
+ // screen readers cannot slip in unnoticed). The bundles are required inside
50
+ // the factory because jest hoists `jest.mock` above the module's consts.
51
+ jest.mock('react-i18next', () => {
52
+ const enBundle = require('../../../../../../i18n/src/locales/en.json');
53
+ const deBundle = require('../../../../../../i18n/src/locales/de.json');
54
+ // Resolve in the base language (en) first — the app's default — then fall
55
+ // back to de, mirroring i18next's `fallbackLng: 'en'` for this locale set.
56
+ const resolveKey = (key: string): string => {
57
+ const path = key.split('.');
58
+ for (const bundle of [enBundle, deBundle]) {
59
+ let node: unknown = bundle;
60
+ for (const part of path) {
61
+ if (typeof node !== 'object' || node === null) break;
62
+ node = (node as Record<string, unknown>)[part];
63
+ }
64
+ if (typeof node === 'string') return node;
65
+ }
66
+ return key;
67
+ };
68
+ return { useTranslation: () => ({ t: resolveKey }) };
69
+ });
70
+
71
+ jest.mock('@openpeepshq/common', () => ({
72
+ VOICE_NOTE_MAX_SECONDS: 90,
73
+ VOICE_NOTE_AUTO_STOP_SECONDS: 89.5,
74
+ }));
75
+
76
+ jest.mock('react-native-fs', () => ({
77
+ __esModule: true,
78
+ default: {
79
+ // The (real) record sheet writes each take to `${CachesDirectoryPath}/voice_…`;
80
+ // the mock keeps the shape so the path join resolves. ts-jest does not
81
+ // transform RNFS's TypeScript `FS.common.js`, so it must be stubbed here,
82
+ // mirroring `record-audio-sheet.test.tsx`.
83
+ CachesDirectoryPath: '/tmp/caches',
84
+ },
85
+ }));
86
+
87
+ jest.mock('@openpeepshq/react', () => ({
88
+ useOpenpeeps: () => ({
89
+ openpeepsApi: {
90
+ createMediaAttachmentAction: () => jest.fn(),
91
+ },
92
+ }),
93
+ }));
94
+
95
+ jest.mock('@gorhom/bottom-sheet', () => ({
96
+ BottomSheetModal: 'BottomSheetModal',
97
+ }));
98
+
99
+ jest.mock('@react-native-documents/picker', () => ({
100
+ pick,
101
+ }));
102
+
103
+ jest.mock('../../../../lib/uploadMedia', () => ({
104
+ uploadMedia,
105
+ }));
106
+
107
+ jest.mock('../../../../lib/bottom-sheet-ref', () => ({
108
+ bottomSheetClose,
109
+ bottomSheetDismiss,
110
+ }));
111
+
112
+ jest.mock('react-native-audio-recorder-player', () => {
113
+ class MockRecorder {
114
+ startRecorder = jest.fn(async () => 'file:///rec.m4a');
115
+ stopRecorder = jest.fn(async () => 'file:///rec.m4a');
116
+ addRecordBackListener = jest.fn();
117
+ removeRecordBackListener = jest.fn();
118
+ addPlayBackListener = jest.fn();
119
+ removePlayBackListener = jest.fn();
120
+ pauseRecorder = jest.fn(async () => 'file:///rec.m4a');
121
+ resumeRecorder = jest.fn(async () => 'file:///rec.m4a');
122
+ startPlayer = jest.fn(async () => 'file:///rec.m4a');
123
+ stopPlayer = jest.fn(async () => 'file:///rec.m4a');
124
+ pausePlayer = jest.fn(async () => 'file:///rec.m4a');
125
+ resumePlayer = jest.fn(async () => 'file:///rec.m4a');
126
+ mmss = (s: number) =>
127
+ `00:${String(Math.max(0, Math.floor(s) % 60)).padStart(2, '0')}`;
128
+ constructor() {
129
+ recorderInstances.push(this);
130
+ }
131
+ }
132
+ return { __esModule: true, default: MockRecorder };
133
+ });
134
+
135
+ jest.mock('../common', () => ({
136
+ BaseSheet: React.forwardRef(
137
+ (props: { children?: unknown; onDismiss?: () => void }, ref: unknown) => {
138
+ // `dismiss` fires the sheet's `onDismiss` — mirroring the real
139
+ // BottomSheetModal, where a user-initiated dismiss unmounts the sheet and
140
+ // runs `onDismiss`. The record sheet wires that to `handleDismiss`, which
141
+ // clears an in-progress take so a fresh recording can start after the
142
+ // sheet is dismissed and reopened. `close` is a plain no-op (a programmatic
143
+ // close does not fire `onDismiss`, so a confirmed take is retained when
144
+ // the sheet is reopened after a confirm).
145
+ const api = {
146
+ present: jest.fn(),
147
+ close: jest.fn(),
148
+ dismiss: jest.fn(() => {
149
+ if (props.onDismiss) props.onDismiss();
150
+ }),
151
+ };
152
+ mockSheetApis.push(api);
153
+ if (typeof ref === 'function') (ref as (a: unknown) => void)(api);
154
+ else if (ref) (ref as { current: unknown }).current = api;
155
+ return React.createElement('BaseSheet', null, props.children);
156
+ }
157
+ ),
158
+ SheetFooter: (props: {
159
+ onConfirm?: () => void;
160
+ onCancel?: () => void;
161
+ disabled?: boolean;
162
+ confirmText?: string;
163
+ }) => {
164
+ return React.createElement('ConfirmButton', {
165
+ 'data-disabled': props.disabled,
166
+ 'onPress': props.onConfirm,
167
+ 'onCancel': props.onCancel,
168
+ 'confirmText': props.confirmText,
169
+ });
170
+ },
171
+ }));
172
+
173
+ jest.mock('../../../ui/button', () => ({
174
+ Button: (props: {
175
+ children?: unknown;
176
+ onPress?: () => void;
177
+ size?: string;
178
+ variant?: string;
179
+ disabled?: boolean;
180
+ accessibilityLabel?: string;
181
+ }) =>
182
+ React.createElement(
183
+ 'Button',
184
+ {
185
+ onPress: props.onPress,
186
+ disabled: props.disabled,
187
+ accessibilityLabel: props.accessibilityLabel,
188
+ },
189
+ props.children
190
+ ),
191
+ }));
192
+
193
+ jest.mock('../../../ui/themed-text', () => ({
194
+ ThemedText: (props: { children?: unknown; className?: string }) =>
195
+ React.createElement('ThemedText', null, props.children),
196
+ }));
197
+
198
+ jest.mock('../../../icons/index', () => ({
199
+ AudioLinesIcon: () => React.createElement('AudioLinesIcon'),
200
+ MicIcon: () => React.createElement('MicIcon'),
201
+ CircleIcon: () => React.createElement('CircleIcon'),
202
+ PauseIcon: () => React.createElement('PauseIcon'),
203
+ PlayIcon: () => React.createElement('PlayIcon'),
204
+ SquareIcon: () => React.createElement('SquareIcon'),
205
+ Repeat2Icon: () => React.createElement('Repeat2Icon'),
206
+ }));
207
+
208
+ import { AudioPickerSheet } from './audio-picker-sheet';
209
+
210
+ const flush = async () => {
211
+ for (let i = 0; i < 30; i++) await Promise.resolve();
212
+ };
213
+
214
+ const findButtonBy = (
215
+ tree: ReturnType<typeof ReactTestRenderer.create>,
216
+ match: (props: Record<string, unknown>) => boolean
217
+ ) => tree.root.findAll((n) => n.type === 'Button' && match(n.props));
218
+
219
+ // The mocked icon components render a host element whose type is the icon's
220
+ // string name, so a Button is identified by that icon appearing in its subtree
221
+ // (the Button's `children` prop is the un-rendered element, whose `type` is the
222
+ // icon function, not the string).
223
+ const findButtonWithIcon = (
224
+ tree: ReturnType<typeof ReactTestRenderer.create>,
225
+ icon: string
226
+ ) =>
227
+ tree.root.findAll(
228
+ (n) => n.type === 'Button' && n.findAll((d) => d.type === icon).length > 0
229
+ )[0];
230
+
231
+ const renderSheet = (
232
+ onSelect: (attachments: unknown[]) => void,
233
+ multiple = true
234
+ ) =>
235
+ ReactTestRenderer.create(
236
+ React.createElement(AudioPickerSheet, {
237
+ ref: { current: null },
238
+ onSelect,
239
+ multiple,
240
+ })
241
+ );
242
+
243
+ // Both sheets are always mounted, so the live tree has exactly two footers, in
244
+ // tree order: the outer AudioPickerSheet's (outermost/first) then the inner
245
+ // RecordAudioSheet's. Querying the tree (rather than a per-render capture)
246
+ // avoids stale entries from re-renders.
247
+ const findFooters = (tree: ReturnType<typeof ReactTestRenderer.create>) =>
248
+ tree.root.findAll((n) => n.type === 'ConfirmButton');
249
+
250
+ describe('AudioPickerSheet → RecordAudioSheet → uploadMedia (RN voice note)', () => {
251
+ beforeEach(() => {
252
+ mockSheetApis.length = 0;
253
+ recorderInstances.length = 0;
254
+ pick.mockClear();
255
+ uploadMedia.mockClear();
256
+ bottomSheetClose.mockClear();
257
+ bottomSheetDismiss.mockClear();
258
+ });
259
+
260
+ it('records a take and hands the attachment to onSelect (no file pick)', async () => {
261
+ const attachment = { id: 'att-voice', type: 'audio' };
262
+ uploadMedia.mockResolvedValue(attachment);
263
+ const onSelect = jest.fn();
264
+
265
+ const tree = await ReactTestRenderer.act(async () => {
266
+ const t = renderSheet(onSelect);
267
+ await flush();
268
+ return t;
269
+ });
270
+
271
+ // 1. The record affordance exists and opens the (real) record sheet.
272
+ const mic = findButtonBy(
273
+ tree,
274
+ (p) => p.accessibilityLabel === 'Record voice note'
275
+ )[0];
276
+ expect(mic).toBeTruthy();
277
+ // The record sheet is the second BaseSheet (outer picker first, inner
278
+ // record sheet second) — the one whose `present` the Mic button drives.
279
+ const innerApi = mockSheetApis[1];
280
+ expect(innerApi).toBeTruthy(); // the record sheet registered its handle
281
+ await ReactTestRenderer.act(async () => {
282
+ mic.props.onPress();
283
+ await flush();
284
+ });
285
+ expect(innerApi.present).toHaveBeenCalledTimes(1);
286
+ // The file picker must not be involved in the record path.
287
+ expect(pick).not.toHaveBeenCalled();
288
+
289
+ // 2. Complete a take through the real record sheet: start, stop, confirm.
290
+ const start = findButtonWithIcon(tree, 'CircleIcon');
291
+ await ReactTestRenderer.act(async () => {
292
+ start.props.onPress();
293
+ await flush();
294
+ });
295
+ const rec = recorderInstances[recorderInstances.length - 1] as {
296
+ startRecorder: jest.Mock;
297
+ stopRecorder: jest.Mock;
298
+ };
299
+ expect(rec.startRecorder).toHaveBeenCalledTimes(1);
300
+
301
+ const stop = findButtonWithIcon(tree, 'SquareIcon');
302
+ await ReactTestRenderer.act(async () => {
303
+ stop.props.onPress();
304
+ await flush();
305
+ });
306
+ expect(rec.stopRecorder).toHaveBeenCalledTimes(1);
307
+
308
+ // The inner record sheet is the second footer (tree order: outer Done
309
+ // first, then the record confirm). Before a take is confirmed, the picker's
310
+ // Done is disabled (nothing selected) and the record confirm is enabled.
311
+ const [doneBefore, confirmFooter] = findFooters(tree);
312
+ expect(doneBefore.props['data-disabled']).toBe(true);
313
+ expect(confirmFooter.props['data-disabled']).toBe(false);
314
+ await ReactTestRenderer.act(async () => {
315
+ confirmFooter.props.onPress();
316
+ await flush();
317
+ });
318
+ // Confirming routes the file into the picker's selected list: the picker's
319
+ // Done footer flips from disabled to enabled. It is not uploaded yet.
320
+ expect(uploadMedia).not.toHaveBeenCalled();
321
+ const [doneFooter] = findFooters(tree);
322
+ expect(doneFooter.props['data-disabled']).toBe(false);
323
+
324
+ // 4. The picker's Done uploads the recorded file and reports it.
325
+ // A recorded take is tagged `post-audio` (matching web's usageForFile) and
326
+ // flagged as the recorder's own .m4a output (isRecordedAudio), unlike a
327
+ // picked file.
328
+ await ReactTestRenderer.act(async () => {
329
+ doneFooter.props.onPress();
330
+ await flush();
331
+ });
332
+ expect(uploadMedia).toHaveBeenCalledWith(
333
+ expect.objectContaining({
334
+ mediaUri: 'file:///rec.m4a',
335
+ type: 'audio',
336
+ usage: 'post-audio',
337
+ isRecordedAudio: true,
338
+ // Round-18 item 2: a recording never went through the file picker, so
339
+ // it carries no picker metadata — its .m4a is the trusted recorder
340
+ // output instead.
341
+ name: null,
342
+ mimeType: null,
343
+ })
344
+ );
345
+ expect(onSelect).toHaveBeenCalledWith([attachment]);
346
+ });
347
+
348
+ // --- Round-6 rework helpers: drive one full take through the real record
349
+ // sheet (re-record first if the sheet still holds a confirmed take).
350
+ const openRecordSheet = async (tree) => {
351
+ const mic = findButtonBy(
352
+ tree,
353
+ (p) => p.accessibilityLabel === 'Record voice note'
354
+ )[0];
355
+ await ReactTestRenderer.act(async () => {
356
+ mic.props.onPress();
357
+ await flush();
358
+ });
359
+ };
360
+
361
+ const recordTake = async (tree, { rerecordFirst = false } = {}) => {
362
+ if (rerecordFirst) {
363
+ const reRecord = findButtonWithIcon(tree, 'Repeat2Icon');
364
+ expect(reRecord).toBeTruthy(); // a confirmed take shows the affordance
365
+ await ReactTestRenderer.act(async () => {
366
+ reRecord.props.onPress();
367
+ await flush();
368
+ });
369
+ }
370
+ const start = findButtonWithIcon(tree, 'CircleIcon');
371
+ await ReactTestRenderer.act(async () => {
372
+ start.props.onPress();
373
+ await flush();
374
+ });
375
+ const stop = findButtonWithIcon(tree, 'SquareIcon');
376
+ await ReactTestRenderer.act(async () => {
377
+ stop.props.onPress();
378
+ await flush();
379
+ });
380
+ const [, confirmFooter] = findFooters(tree);
381
+ await ReactTestRenderer.act(async () => {
382
+ confirmFooter.props.onPress();
383
+ await flush();
384
+ });
385
+ };
386
+
387
+ it('single mode: a second confirmed recording replaces the first (one selection, one upload)', async () => {
388
+ const attachment = { id: 'att-voice', type: 'audio' };
389
+ uploadMedia.mockResolvedValue(attachment);
390
+ const onSelect = jest.fn();
391
+
392
+ const tree = await ReactTestRenderer.act(async () => {
393
+ const t = renderSheet(onSelect, false); // multiple=false
394
+ await flush();
395
+ return t;
396
+ });
397
+
398
+ // First take.
399
+ await openRecordSheet(tree);
400
+ await recordTake(tree);
401
+ let [doneFooter] = findFooters(tree);
402
+ expect(doneFooter.props['data-disabled']).toBe(false);
403
+
404
+ // Second take: the record sheet still holds the confirmed take, so the
405
+ // re-record affordance clears it before the fresh start.
406
+ await openRecordSheet(tree);
407
+ await recordTake(tree, { rerecordFirst: true });
408
+
409
+ // Done uploads exactly one file — the second take, not both.
410
+ [doneFooter] = findFooters(tree);
411
+ await ReactTestRenderer.act(async () => {
412
+ doneFooter.props.onPress();
413
+ await flush();
414
+ });
415
+ expect(uploadMedia).toHaveBeenCalledTimes(1);
416
+ expect(onSelect).toHaveBeenCalledWith([attachment]);
417
+ });
418
+
419
+ it('keeps the sheet open when every upload fails, so the take can be retried', async () => {
420
+ const attachment = { id: 'att-voice', type: 'audio' };
421
+ uploadMedia.mockResolvedValue(null); // e.g. the server rejects it
422
+ const onSelect = jest.fn();
423
+
424
+ const tree = await ReactTestRenderer.act(async () => {
425
+ const t = renderSheet(onSelect);
426
+ await flush();
427
+ return t;
428
+ });
429
+
430
+ await openRecordSheet(tree);
431
+ await recordTake(tree);
432
+
433
+ // Done with every upload failing: nothing is handed out, the sheet is not
434
+ // closed, and the selection stays (Done remains enabled for a retry).
435
+ await ReactTestRenderer.act(async () => {
436
+ findFooters(tree)[0].props.onPress();
437
+ await flush();
438
+ });
439
+ expect(uploadMedia).toHaveBeenCalledTimes(1);
440
+ expect(onSelect).not.toHaveBeenCalled();
441
+ expect(bottomSheetClose).not.toHaveBeenCalled();
442
+ let [doneFooter] = findFooters(tree);
443
+ expect(doneFooter.props['data-disabled']).toBe(false);
444
+
445
+ // Retry: the upload now succeeds and the take is handed out.
446
+ uploadMedia.mockResolvedValue(attachment);
447
+ await ReactTestRenderer.act(async () => {
448
+ findFooters(tree)[0].props.onPress();
449
+ await flush();
450
+ });
451
+ expect(onSelect).toHaveBeenCalledWith([attachment]);
452
+ expect(bottomSheetClose).toHaveBeenCalledTimes(1);
453
+ });
454
+
455
+ it('re-record: a take can be discarded and re-recorded without dismissing the sheet', async () => {
456
+ const attachment = { id: 'att-voice', type: 'audio' };
457
+ uploadMedia.mockResolvedValue(attachment);
458
+ const onSelect = jest.fn();
459
+
460
+ const tree = await ReactTestRenderer.act(async () => {
461
+ const t = renderSheet(onSelect);
462
+ await flush();
463
+ return t;
464
+ });
465
+
466
+ await openRecordSheet(tree);
467
+ // Record a take but do NOT confirm it into the picker — the take stays
468
+ // in the record sheet (playback + confirm enabled), which is the state
469
+ // the re-record affordance replaces.
470
+ const start = findButtonWithIcon(tree, 'CircleIcon');
471
+ await ReactTestRenderer.act(async () => {
472
+ start.props.onPress();
473
+ await flush();
474
+ });
475
+ const stop = findButtonWithIcon(tree, 'SquareIcon');
476
+ await ReactTestRenderer.act(async () => {
477
+ stop.props.onPress();
478
+ await flush();
479
+ });
480
+
481
+ // The take is there (confirm enabled) and the re-record affordance sits
482
+ // next to the playback controls.
483
+ expect(findFooters(tree)[1].props['data-disabled']).toBe(false);
484
+ const reRecord = findButtonWithIcon(tree, 'Repeat2Icon');
485
+ expect(reRecord).toBeTruthy();
486
+
487
+ // Discard: the take is gone — confirm disabled, start visible again, and
488
+ // nothing was ever handed to the picker.
489
+ await ReactTestRenderer.act(async () => {
490
+ reRecord.props.onPress();
491
+ await flush();
492
+ });
493
+ expect(findFooters(tree)[1].props['data-disabled']).toBe(true);
494
+ expect(findButtonWithIcon(tree, 'CircleIcon')).toBeTruthy();
495
+ expect(uploadMedia).not.toHaveBeenCalled();
496
+ expect(onSelect).not.toHaveBeenCalled();
497
+
498
+ // A fresh take is recorded, confirmed, and handed out (exactly one).
499
+ await recordTake(tree);
500
+ await ReactTestRenderer.act(async () => {
501
+ findFooters(tree)[0].props.onPress();
502
+ await flush();
503
+ });
504
+ expect(uploadMedia).toHaveBeenCalledTimes(1);
505
+ expect(onSelect).toHaveBeenCalledWith([attachment]);
506
+ });
507
+
508
+ it('multi mode with selectMultiple off: record → confirm → Done uploads the take', async () => {
509
+ const attachment = { id: 'att-voice', type: 'audio' };
510
+ uploadMedia.mockResolvedValue(attachment);
511
+ const onSelect = jest.fn();
512
+
513
+ const tree = await ReactTestRenderer.act(async () => {
514
+ const t = renderSheet(onSelect, true); // multiple=true (the toggle is shown)
515
+ await flush();
516
+ return t;
517
+ });
518
+
519
+ // In multiple mode the selectMultiple toggle is rendered; leave it off
520
+ // (single-select within multiple mode) and drive the record → confirm →
521
+ // Done flow.
522
+ const toggle = tree.root.findAll(
523
+ (n) =>
524
+ n.type === 'Button' &&
525
+ n.findAll(
526
+ (d) =>
527
+ d.type === 'Text' &&
528
+ typeof d.props.children === 'string' &&
529
+ d.props.children.includes('Select multiple')
530
+ ).length > 0
531
+ )[0];
532
+ expect(toggle).toBeTruthy(); // the selectMultiple toggle exists in multi mode
533
+
534
+ await openRecordSheet(tree);
535
+ await recordTake(tree);
536
+
537
+ const [doneFooter] = findFooters(tree);
538
+ expect(doneFooter.props['data-disabled']).toBe(false);
539
+ await ReactTestRenderer.act(async () => {
540
+ doneFooter.props.onPress();
541
+ await flush();
542
+ });
543
+ expect(uploadMedia).toHaveBeenCalledTimes(1);
544
+ expect(onSelect).toHaveBeenCalledWith([attachment]);
545
+ expect(bottomSheetClose).toHaveBeenCalledTimes(1);
546
+ });
547
+
548
+ it('cancel while recording stops the take and a later fresh recording succeeds', async () => {
549
+ const attachment = { id: 'att-voice', type: 'audio' };
550
+ uploadMedia.mockResolvedValue(attachment);
551
+ const onSelect = jest.fn();
552
+
553
+ const tree = await ReactTestRenderer.act(async () => {
554
+ const t = renderSheet(onSelect);
555
+ await flush();
556
+ return t;
557
+ });
558
+
559
+ // Open the record sheet and start a take, then cancel (the record sheet's
560
+ // own Cancel footer) while the mic is still hot.
561
+ await openRecordSheet(tree);
562
+ const start = findButtonWithIcon(tree, 'CircleIcon');
563
+ await ReactTestRenderer.act(async () => {
564
+ start.props.onPress();
565
+ await flush();
566
+ });
567
+
568
+ // The record sheet is the second footer in tree order; its onCancel is
569
+ // wired to bottomSheetDismiss.
570
+ const [pickerFooter, recordFooter] = findFooters(tree);
571
+ expect(pickerFooter).toBeTruthy();
572
+ expect(recordFooter).toBeTruthy();
573
+ await ReactTestRenderer.act(async () => {
574
+ recordFooter.props.onCancel();
575
+ await flush();
576
+ });
577
+ expect(bottomSheetDismiss).toHaveBeenCalledTimes(1);
578
+ // No upload happened for the cancelled take.
579
+ expect(uploadMedia).not.toHaveBeenCalled();
580
+
581
+ // A later fresh recording is recorded, confirmed and uploaded successfully.
582
+ await openRecordSheet(tree);
583
+ await recordTake(tree);
584
+ await ReactTestRenderer.act(async () => {
585
+ findFooters(tree)[0].props.onPress();
586
+ await flush();
587
+ });
588
+ expect(uploadMedia).toHaveBeenCalledTimes(1);
589
+ expect(onSelect).toHaveBeenCalledWith([attachment]);
590
+ expect(bottomSheetClose).toHaveBeenCalledTimes(1);
591
+ });
592
+
593
+ it('picked audio uploads with its real extension/mimetype, usage post-audio, and isRecordedAudio false', async () => {
594
+ // Round-16 review item 9: the picked-file path (pick() at the audio
595
+ // button) was previously untested. The pick is mocked; `uploadMedia` is
596
+ // the module under observation, so this pins what a picked file is
597
+ // handed to it with.
598
+ const attachment = { id: 'att-pick', type: 'audio' };
599
+ uploadMedia.mockResolvedValue(attachment);
600
+ pick.mockResolvedValueOnce([
601
+ {
602
+ uri: 'file:///tmp/pick_note.mp3',
603
+ name: 'pick_note.mp3',
604
+ type: 'audio/mpeg',
605
+ },
606
+ {
607
+ uri: 'content://media/external/audio/media/777',
608
+ name: 'track.webm',
609
+ type: 'audio/webm',
610
+ },
611
+ ]);
612
+ const onSelect = jest.fn();
613
+
614
+ const tree = await ReactTestRenderer.act(async () => {
615
+ const t = renderSheet(onSelect);
616
+ await flush();
617
+ return t;
618
+ });
619
+
620
+ // The picker affordance is the button holding the AudioLinesIcon.
621
+ const pickButton = findButtonWithIcon(tree, 'AudioLinesIcon');
622
+ expect(pickButton).toBeTruthy();
623
+ await ReactTestRenderer.act(async () => {
624
+ pickButton.props.onPress();
625
+ await flush();
626
+ });
627
+ expect(pick).toHaveBeenCalledWith({ type: 'audio', multiple: false });
628
+
629
+ const [doneFooter] = findFooters(tree);
630
+ expect(doneFooter.props['data-disabled']).toBe(false);
631
+ await ReactTestRenderer.act(async () => {
632
+ doneFooter.props.onPress();
633
+ await flush();
634
+ });
635
+
636
+ // Both picked files upload; each keeps its own URI (uploadMedia is what
637
+ // derives the honest extension/mimetype — the real branch is covered in
638
+ // uploadMedia.test.ts), and a picked file is NOT the recorder's output.
639
+ expect(uploadMedia).toHaveBeenCalledTimes(2);
640
+ const mp3 = uploadMedia.mock.calls[0][0];
641
+ const webm = uploadMedia.mock.calls[1][0];
642
+ expect(mp3.mediaUri).toBe('file:///tmp/pick_note.mp3');
643
+ expect(webm.mediaUri).toBe('content://media/external/audio/media/777');
644
+ for (const call of [mp3, webm]) {
645
+ expect(call.type).toBe('audio');
646
+ expect(call.usage).toBe('post-audio');
647
+ expect(call.isRecordedAudio).toBe(false);
648
+ }
649
+ // Round-18 item 2: the picker's authoritative name/type are threaded to
650
+ // uploadMedia — including for the opaque content:// URI whose extension
651
+ // cannot be guessed from the URI. Without them the out-of-map .webm
652
+ // container degrades to .bin/octet-stream and the server classifies the
653
+ // attachment as a document, while the same file picked on web (mime
654
+ // audio/webm) becomes a post-audio attachment — the cross-platform
655
+ // divergence the pin closes.
656
+ expect(mp3.name).toBe('pick_note.mp3');
657
+ expect(mp3.mimeType).toBe('audio/mpeg');
658
+ expect(webm.name).toBe('track.webm');
659
+ expect(webm.mimeType).toBe('audio/webm');
660
+ expect(onSelect).toHaveBeenCalledWith([attachment, attachment]);
661
+ });
662
+
663
+ it('single mode: a re-recorded (replaced) take is not left flagged as a recording', async () => {
664
+ // Round-16 review item 10: in single mode a confirmed take is replaced by
665
+ // the next one. The replaced take's URI must not keep a stale "recorded"
666
+ // flag — so if the recorder re-emits the same URI (same fixed default, or
667
+ // an identical fresh path), the second upload must not be marked
668
+ // isRecordedAudio based on a stale entry.
669
+ const attachment = { id: 'att-voice', type: 'audio' };
670
+ uploadMedia.mockResolvedValue(attachment);
671
+ const onSelect = jest.fn();
672
+
673
+ const tree = await ReactTestRenderer.act(async () => {
674
+ const t = renderSheet(onSelect, false); // multiple=false
675
+ await flush();
676
+ return t;
677
+ });
678
+
679
+ await openRecordSheet(tree);
680
+ await recordTake(tree); // take A confirmed (flagged as recorded)
681
+
682
+ // Re-open, re-record, and confirm take B (same mock URI). Without the
683
+ // single-mode replacement removing the stale flag, take B would be
684
+ // re-flagged as "recorded" on a URI that is now a fresh take.
685
+ await openRecordSheet(tree);
686
+ await recordTake(tree, { rerecordFirst: true });
687
+
688
+ const [doneFooter] = findFooters(tree);
689
+ await ReactTestRenderer.act(async () => {
690
+ doneFooter.props.onPress();
691
+ await flush();
692
+ });
693
+
694
+ // Exactly one upload (take B), one selection. This drives the single-mode
695
+ // replace path end-to-end. (The `recordedUrls` Set-dedup from the fix is
696
+ // not observable here: the recorder mock always emits the same URI, so
697
+ // take A and take B share it and `isRecordedAudio` is true either way. The
698
+ // dedup matters when the recorder re-emits a distinct URI; it keeps the
699
+ // Set from growing unbounded and keeps a replaced take from leaking a
700
+ // stale flag.)
701
+ expect(uploadMedia).toHaveBeenCalledTimes(1);
702
+ expect(onSelect).toHaveBeenCalledWith([attachment]);
703
+ });
704
+
705
+ it('shows a playable preview (play/pause) for a confirmed take', async () => {
706
+ // Round-16 review item 2: web shows an <audio controls> preview; RN gets
707
+ // a play/pause affordance on the visible take that drives the recorder's
708
+ // player (the "small AudioPlayer instance" parity the review asked for).
709
+ const attachment = { id: 'att-voice', type: 'audio' };
710
+ uploadMedia.mockResolvedValue(attachment);
711
+ const onSelect = jest.fn();
712
+
713
+ const tree = await ReactTestRenderer.act(async () => {
714
+ const t = renderSheet(onSelect);
715
+ await flush();
716
+ return t;
717
+ });
718
+
719
+ const playLabel = 'Play audio';
720
+ // Round-19 item 1: the suite resolves through the real bundles now, so
721
+ // pin the *resolved* pause copy — if the key were missing from both
722
+ // bundles, the raw key `common.media.audio.pause` would surface here and
723
+ // fail.
724
+ const pauseLabel = 'Pause audio';
725
+ expect(pauseLabel).not.toBe('common.media.audio.pause');
726
+ // No preview before a take exists.
727
+ expect(
728
+ findButtonBy(tree, (p) => p.accessibilityLabel === playLabel).length
729
+ ).toBe(0);
730
+
731
+ await openRecordSheet(tree);
732
+ await recordTake(tree);
733
+
734
+ // The preview's play button appears once a take is selected.
735
+ const play = findButtonBy(
736
+ tree,
737
+ (p) => p.accessibilityLabel === playLabel
738
+ )[0];
739
+ expect(play).toBeTruthy();
740
+
741
+ await ReactTestRenderer.act(async () => {
742
+ play.props.onPress();
743
+ await flush();
744
+ });
745
+
746
+ // The player started with the confirmed take's URI (not a fixed default).
747
+ const rec = recorderInstances[recorderInstances.length - 1] as {
748
+ startPlayer: jest.Mock;
749
+ };
750
+ expect(rec.startPlayer).toHaveBeenCalledWith('file:///rec.m4a');
751
+
752
+ // Round-18 item 4: while playing the icon is Pause, so the accessible
753
+ // name must switch to the pause copy too — "Play audio" would
754
+ // misdescribe the control. Pressing it (found by its new pause label)
755
+ // stops the take.
756
+ const pause = findButtonBy(
757
+ tree,
758
+ (p) => p.accessibilityLabel === pauseLabel
759
+ )[0];
760
+ expect(pause).toBeTruthy();
761
+ expect(
762
+ findButtonBy(tree, (p) => p.accessibilityLabel === playLabel).length
763
+ ).toBe(0);
764
+ await ReactTestRenderer.act(async () => {
765
+ pause.props.onPress();
766
+ await flush();
767
+ });
768
+ expect(rec.stopPlayer).toHaveBeenCalled();
769
+ // Stopped: the label is back to play.
770
+ expect(
771
+ findButtonBy(tree, (p) => p.accessibilityLabel === playLabel).length
772
+ ).toBe(1);
773
+ });
774
+
775
+ it("flips back to play when the take finishes (isFinished), like web's `ended`", async () => {
776
+ // Round-19 item 2: a take that ends on its own must leave the playing
777
+ // state (label and icon back to play) instead of a stuck Pause that
778
+ // needs a manual stop-then-play. Web gets this from <audio>'s `ended`;
779
+ // RN drives the same transition off the player's `isFinished` event.
780
+ const attachment = { id: 'att-voice', type: 'audio' };
781
+ uploadMedia.mockResolvedValue(attachment);
782
+ const onSelect = jest.fn();
783
+
784
+ const tree = await ReactTestRenderer.act(async () => {
785
+ const t = renderSheet(onSelect);
786
+ await flush();
787
+ return t;
788
+ });
789
+
790
+ await openRecordSheet(tree);
791
+ await recordTake(tree);
792
+
793
+ const play = findButtonBy(
794
+ tree,
795
+ (p) => p.accessibilityLabel === 'Play audio'
796
+ )[0];
797
+ expect(play).toBeTruthy();
798
+ await ReactTestRenderer.act(async () => {
799
+ play.props.onPress();
800
+ await flush();
801
+ });
802
+ const rec = recorderInstances[recorderInstances.length - 1] as {
803
+ startPlayer: jest.Mock;
804
+ stopPlayer: jest.Mock;
805
+ addPlayBackListener: jest.Mock;
806
+ };
807
+ expect(rec.startPlayer).toHaveBeenCalledWith('file:///rec.m4a');
808
+ expect(
809
+ findButtonBy(tree, (p) => p.accessibilityLabel === 'Pause audio').length
810
+ ).toBe(1);
811
+
812
+ // The natural end of the take: the player reports `isFinished`.
813
+ expect(rec.addPlayBackListener).toHaveBeenCalled();
814
+ const playListener = rec.addPlayBackListener.mock.calls.at(-1)![0] as (e: {
815
+ isFinished: boolean;
816
+ currentPosition: number;
817
+ duration: number;
818
+ }) => void;
819
+ await ReactTestRenderer.act(async () => {
820
+ playListener({
821
+ isFinished: true,
822
+ currentPosition: 10000,
823
+ duration: 10000,
824
+ });
825
+ await flush();
826
+ });
827
+
828
+ // The take stopped and the control re-describes itself as play again —
829
+ // one tap replays it, without the stop-then-play round trip.
830
+ expect(rec.stopPlayer).toHaveBeenCalled();
831
+ expect(
832
+ findButtonBy(tree, (p) => p.accessibilityLabel === 'Pause audio').length
833
+ ).toBe(0);
834
+ expect(
835
+ findButtonBy(tree, (p) => p.accessibilityLabel === 'Play audio').length
836
+ ).toBe(1);
837
+ // A fresh play starts the player again (on a new instance, since the
838
+ // finished one was torn down by the transition).
839
+ await ReactTestRenderer.act(async () => {
840
+ findButtonBy(
841
+ tree,
842
+ (p) => p.accessibilityLabel === 'Play audio'
843
+ )[0].props.onPress();
844
+ await flush();
845
+ });
846
+ const replay = recorderInstances[recorderInstances.length - 1] as {
847
+ startPlayer: jest.Mock;
848
+ };
849
+ expect(replay.startPlayer).toHaveBeenCalledWith('file:///rec.m4a');
850
+ expect(
851
+ findButtonBy(tree, (p) => p.accessibilityLabel === 'Pause audio').length
852
+ ).toBe(1);
853
+ });
854
+
855
+ it('single mode: confirming a re-record stops a playing preview of the replaced take', async () => {
856
+ // Round-20 item 1: the record path replaces the visible take (single mode)
857
+ // but did not stop the preview that was playing the *replaced* take — the
858
+ // pick path does. Unique per-take paths mean the discarded file still
859
+ // exists, so the player would keep it audible while `visibleUri` already
860
+ // points at the new take. This pins the mirror of the pick path: a
861
+ // re-record confirmed while a preview is playing stops the preview and
862
+ // clears `playingUri` (label back to Play).
863
+ const attachment = { id: 'att-voice', type: 'audio' };
864
+ uploadMedia.mockResolvedValue(attachment);
865
+ const onSelect = jest.fn();
866
+
867
+ const tree = await ReactTestRenderer.act(async () => {
868
+ const t = renderSheet(onSelect, false); // single mode
869
+ await flush();
870
+ return t;
871
+ });
872
+
873
+ // First take confirmed → selected, preview playable.
874
+ await openRecordSheet(tree);
875
+ await recordTake(tree);
876
+
877
+ // Start the picker preview for the confirmed take.
878
+ const play = findButtonBy(
879
+ tree,
880
+ (p) => p.accessibilityLabel === 'Play audio'
881
+ )[0];
882
+ expect(play).toBeTruthy();
883
+ await ReactTestRenderer.act(async () => {
884
+ play.props.onPress();
885
+ await flush();
886
+ });
887
+ // The picker's preview player is the most recently created instance; it
888
+ // is playing the confirmed take, so the control re-describes as Pause.
889
+ const previewPlayer = recorderInstances[recorderInstances.length - 1] as {
890
+ startPlayer: jest.Mock;
891
+ stopPlayer: jest.Mock;
892
+ };
893
+ expect(previewPlayer.startPlayer).toHaveBeenCalledWith('file:///rec.m4a');
894
+ expect(
895
+ findButtonBy(tree, (p) => p.accessibilityLabel === 'Pause audio').length
896
+ ).toBe(1);
897
+
898
+ // Confirm a re-record (single mode replaces the visible take) while the
899
+ // preview of the replaced take is still playing.
900
+ await openRecordSheet(tree);
901
+ await recordTake(tree, { rerecordFirst: true });
902
+
903
+ // The discarded take's preview stopped (no ghost sound) and the control is
904
+ // back to Play — `playingUri` no longer holds the old uri.
905
+ expect(previewPlayer.stopPlayer).toHaveBeenCalled();
906
+ expect(
907
+ findButtonBy(tree, (p) => p.accessibilityLabel === 'Pause audio').length
908
+ ).toBe(0);
909
+ expect(
910
+ findButtonBy(tree, (p) => p.accessibilityLabel === 'Play audio').length
911
+ ).toBe(1);
912
+ });
913
+ });