@openpeepshq/rn-components 0.21.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.
@@ -1,193 +1,409 @@
1
- import React, { forwardRef, useCallback, useState } from 'react';
1
+ import React, {
2
+ forwardRef,
3
+ useCallback,
4
+ useEffect,
5
+ useRef,
6
+ useState,
7
+ } from 'react';
2
8
  import { View, PermissionsAndroid, Platform } from 'react-native';
3
9
  import { BottomSheetModal } from '@gorhom/bottom-sheet';
4
10
  import { ThemedText } from '../../../ui/themed-text';
5
11
  import { BaseSheet, SheetFooter } from '../common';
6
12
  import { useTranslation } from 'react-i18next';
7
- import Toast from 'react-native-toast-message';
8
13
  import AudioRecorderPlayer from 'react-native-audio-recorder-player';
14
+ import RNFS from 'react-native-fs';
9
15
  import { Button } from '../../../ui/button';
10
16
  import {
11
17
  CircleIcon,
12
18
  PauseIcon,
13
19
  PlayIcon,
20
+ Repeat2Icon,
14
21
  SquareIcon,
15
22
  } from '../../../icons/index';
16
23
  import { bottomSheetDismiss } from '../../../../lib/bottom-sheet-ref';
24
+ import {
25
+ VOICE_NOTE_AUTO_STOP_SECONDS,
26
+ VOICE_NOTE_MAX_SECONDS,
27
+ } from '@openpeepshq/common';
17
28
 
18
29
  interface RecordAudioSheetProps {
19
30
  onComplete: (url: string) => Promise<void> | void;
20
31
  }
21
32
 
33
+ /**
34
+ * Records a voice note (up to VOICE_NOTE_MAX_SECONDS) for the composer.
35
+ *
36
+ * The auto-stop is driven by a wall-clock interval (Date.now() deltas) rather
37
+ * than the recorder's throttle-racy position callback — the same guard the web
38
+ * VoiceRecorderModal uses — so the take cannot overshoot the cap, and a
39
+ * completed take is confirmable from the file the stop returns even if the
40
+ * last position callback never lands.
41
+ */
22
42
  export const RecordAudioSheet = forwardRef<
23
43
  BottomSheetModal,
24
44
  RecordAudioSheetProps
25
45
  >(({ onComplete }, ref) => {
26
46
  const { t } = useTranslation();
27
47
 
28
- const getAndroidPermission = useCallback(async () => {
29
- if (Platform.OS === 'android') {
30
- try {
31
- const grants = await PermissionsAndroid.requestMultiple([
32
- PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
33
- PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE,
34
- PermissionsAndroid.PERMISSIONS.RECORD_AUDIO,
35
- ]);
36
-
37
- if (
38
- !(
39
- grants['android.permission.WRITE_EXTERNAL_STORAGE'] ===
40
- PermissionsAndroid.RESULTS.GRANTED &&
41
- grants['android.permission.READ_EXTERNAL_STORAGE'] ===
42
- PermissionsAndroid.RESULTS.GRANTED &&
43
- grants['android.permission.RECORD_AUDIO'] ===
44
- PermissionsAndroid.RESULTS.GRANTED
45
- )
46
- ) {
47
- Toast.show({
48
- text1: t('common.permissions.required'),
49
- type: 'error',
50
- });
51
- bottomSheetDismiss(ref);
52
- }
53
- } catch {
54
- Toast.show({
55
- text1: t('common.permissions.required'),
56
- type: 'error',
57
- });
58
- bottomSheetDismiss(ref);
59
- }
60
- }
61
- }, [ref, t]);
48
+ // Lazy: one native recorder per mounted sheet, not a new object per render.
49
+ const recorderRef = useRef<AudioRecorderPlayer | null>(null);
50
+ const getRecorder = () => {
51
+ if (!recorderRef.current) recorderRef.current = new AudioRecorderPlayer();
52
+ return recorderRef.current;
53
+ };
54
+
62
55
  const [url, setUrl] = useState<string | null>(null);
56
+ const [micError, setMicError] = useState<'denied' | 'failed' | null>(null);
63
57
  const [recordTime, setRecordTime] = useState('00:00');
64
- const [recordSecs, setRecordSecs] = useState(0);
65
58
  const [playTime, setPlayTime] = useState('00:00');
66
59
  const [isRecording, setIsRecording] = useState(false);
67
60
  const [isPlaying, setIsPlaying] = useState(false);
68
61
  const [isPaused, setIsPaused] = useState(false);
62
+ // True once stopRecorder has landed — the take is playable and confirmable.
63
+ const [isStopped, setIsStopped] = useState(false);
64
+ // Mirrors isRecording for the unmount/dismiss path, where the closure's
65
+ // state is stale and we still need to know whether the mic is hot.
66
+ const isRecordingRef = useRef(false);
69
67
 
70
- const audioRecorderPlayer = new AudioRecorderPlayer();
68
+ // Wall-clock tracking: the display time and the auto-stop derive from
69
+ // Date.now() deltas (minus paused spans), so a background-throttled tick
70
+ // cannot let the take overshoot the cap.
71
+ const accumulatedMsRef = useRef(0);
72
+ const segmentStartedAtRef = useRef<number | null>(null);
73
+ const stoppingRef = useRef(false);
71
74
 
72
- const onStartRecord = async () => {
73
- setUrl(await audioRecorderPlayer.startRecorder());
74
- setIsRecording(true);
75
- setRecordSecs(0);
76
- audioRecorderPlayer.addRecordBackListener((e) => {
77
- setRecordSecs(e.currentPosition);
78
- setRecordTime(
79
- audioRecorderPlayer.mmss(Math.floor(e.currentPosition / 1000))
75
+ const elapsedMs = () =>
76
+ accumulatedMsRef.current +
77
+ (segmentStartedAtRef.current !== null
78
+ ? Date.now() - segmentStartedAtRef.current
79
+ : 0);
80
+
81
+ const getRecordPermission = useCallback(async (): Promise<boolean> => {
82
+ if (Platform.OS !== 'android') return true;
83
+ try {
84
+ const status = await PermissionsAndroid.request(
85
+ PermissionsAndroid.PERMISSIONS.RECORD_AUDIO
80
86
  );
81
- return;
82
- });
87
+ return status === PermissionsAndroid.RESULTS.GRANTED;
88
+ } catch {
89
+ return false;
90
+ }
91
+ }, []);
92
+
93
+ const teardownListeners = () => {
94
+ const recorder = recorderRef.current;
95
+ if (!recorder) return;
96
+ recorder.removeRecordBackListener();
97
+ recorder.removePlayBackListener();
83
98
  };
84
99
 
100
+ // Clean up the native listeners and release the mic if the sheet unmounts
101
+ // mid-take, so the recorder/player are not left registered or running.
102
+ useEffect(
103
+ () => () => {
104
+ teardownListeners();
105
+ const recorder = recorderRef.current;
106
+ if (recorder) {
107
+ // The take is discarded, not confirmed — stop it and release the mic.
108
+ if (isRecordingRef.current) {
109
+ void recorder
110
+ .stopRecorder()
111
+ .catch(() => undefined)
112
+ .finally(() => teardownListeners());
113
+ isRecordingRef.current = false;
114
+ }
115
+ void recorder.stopPlayer().catch(() => undefined);
116
+ }
117
+ },
118
+ []
119
+ );
120
+
121
+ // The Android mic permission is requested lazily in onStartRecord (when the
122
+ // user actually starts a take) rather than on mount, so a parent remount of
123
+ // the sheet does not re-fire the system prompt before the user has asked to
124
+ // record. iOS raises its system prompt on first use.
125
+
85
126
  const reset = () => {
86
- console.log('url', url);
87
- console.log('reset');
88
127
  setIsRecording(false);
128
+ isRecordingRef.current = false;
89
129
  setIsPaused(false);
90
130
  setIsPlaying(false);
91
131
  setPlayTime('00:00');
92
- setRecordSecs(0);
93
132
  setRecordTime('00:00');
133
+ setIsStopped(false);
134
+ stoppingRef.current = false;
135
+ accumulatedMsRef.current = 0;
136
+ segmentStartedAtRef.current = null;
137
+ };
138
+
139
+ const onStartRecord = async () => {
140
+ setMicError(null);
141
+ if (!(await getRecordPermission())) {
142
+ setMicError('denied');
143
+ return;
144
+ }
145
+ const recorder = getRecorder();
146
+ try {
147
+ recorder.removeRecordBackListener();
148
+ // No explicit audioSet: the `.m4a`/`audio/mp4` name+mimetype trusted in
149
+ // `uploadMedia` (isRecordedAudio) depends on react-native-audio-recorder-player
150
+ // defaults — Android: OutputFormat.MPEG_4 + AudioEncoder.AAC → .mp4/AAC;
151
+ // iOS: AVFormatIDKeyIOS unset → ALAC → .m4a/ALAC. These defaults are for the
152
+ // version the lockfile resolves to (3.6.14); CI installs from that lock, so
153
+ // the build matches these defaults. The ALAC variant is also
154
+ // audio/mp4-shaped, so the server does not retranscode it, which some
155
+ // Android/Windows players cannot decode — a known, accepted trade (the
156
+ // dominant iOS player, AVAudioPlayer, decodes it). Do not change the
157
+ // recorder's output defaults — via an explicit audioSet or a dependency
158
+ // bump that changes them — without re-checking the `.m4a`/`audio/mp4`
159
+ // trust in `uploadMedia`'s `isRecordedAudio` branch.
160
+ //
161
+ // Unique path per take: the library's default ("DEFAULT") writes every
162
+ // take to one fixed file (sound.mp4 / sound.m4a in the cache dir), and a
163
+ // sheet is dismissed only at confirm — so a second take would overwrite
164
+ // a previously confirmed take's bytes before the picker's Done uploads
165
+ // them. `uploadMedia` copies Android `file://` bytes only at Done, i.e.
166
+ // after the overwrite. Both platforms write a caller-supplied path
167
+ // verbatim (Android uses it directly; iOS prepends the caches dir for
168
+ // plain paths), so a fresh name per take keeps the confirmed take intact.
169
+ // The `.m4a` suffix keeps the name honest on both platforms — Android's
170
+ // MPEG_4/AAC output is audio/mp4-shaped like iOS's m4a, and `uploadMedia`
171
+ // (isRecordedAudio) maps the recorded output to audio/mp4 regardless.
172
+ const outputPath = `${RNFS.CachesDirectoryPath}/voice_${Date.now()}_${Math.random()
173
+ .toString(36)
174
+ .slice(2, 9)}.m4a`;
175
+ setUrl(await recorder.startRecorder(outputPath));
176
+ setPlayTime('00:00');
177
+ setIsRecording(true);
178
+ isRecordingRef.current = true;
179
+ setIsPaused(false);
180
+ setIsStopped(false);
181
+ setRecordTime('00:00');
182
+ stoppingRef.current = false;
183
+ accumulatedMsRef.current = 0;
184
+ segmentStartedAtRef.current = Date.now();
185
+ } catch {
186
+ setMicError('failed');
187
+ }
188
+ };
189
+
190
+ const onStopRecord = async () => {
191
+ if (stoppingRef.current) return;
192
+ stoppingRef.current = true;
193
+ segmentStartedAtRef.current = null;
194
+ const recorder = recorderRef.current;
195
+ if (!recorder) return;
196
+ try {
197
+ // The returned path is the recorded file — a completed take is
198
+ // confirmable even if the last position callback never arrived.
199
+ const stoppedUrl = await recorder.stopRecorder();
200
+ // Commit the stopped UI state only once stop actually resolved, so a
201
+ // rejected stop never shows a playback section for a take that was
202
+ // never produced.
203
+ setIsStopped(true);
204
+ setIsRecording(false);
205
+ isRecordingRef.current = false;
206
+ setIsPaused(false);
207
+ if (stoppedUrl) setUrl(stoppedUrl);
208
+ } catch {
209
+ // The mic stayed hot; the take is not usable — the error path is the
210
+ // same `micError` state a failed start produces.
211
+ setMicError('failed');
212
+ setIsRecording(false);
213
+ isRecordingRef.current = false;
214
+ setIsPaused(false);
215
+ } finally {
216
+ recorder.removeRecordBackListener();
217
+ }
94
218
  };
95
219
 
96
220
  const onPauseRecord = async () => {
97
- await audioRecorderPlayer.pauseRecorder();
221
+ if (stoppingRef.current) return;
222
+ const recorder = recorderRef.current;
223
+ if (recorder) await recorder.pauseRecorder();
224
+ if (segmentStartedAtRef.current !== null) {
225
+ accumulatedMsRef.current += Date.now() - segmentStartedAtRef.current;
226
+ segmentStartedAtRef.current = null;
227
+ }
98
228
  setIsPaused(true);
99
229
  };
100
230
 
101
231
  const onResumeRecord = async () => {
102
- await audioRecorderPlayer.resumeRecorder();
232
+ const recorder = recorderRef.current;
233
+ if (recorder) await recorder.resumeRecorder();
234
+ segmentStartedAtRef.current = Date.now();
103
235
  setIsPaused(false);
104
- setIsRecording(true);
105
- };
106
-
107
- const onStopRecord = async () => {
108
- console.log('onStopRecord');
109
- setIsRecording(false);
110
- setIsPaused(false);
111
- await audioRecorderPlayer.stopRecorder();
112
- audioRecorderPlayer.removeRecordBackListener();
113
236
  };
114
237
 
115
238
  const onStartPlay = async () => {
116
- await audioRecorderPlayer.startPlayer();
117
- audioRecorderPlayer.addPlayBackListener((e) => {
118
- setPlayTime(
119
- audioRecorderPlayer.mmss(Math.floor(e.currentPosition / 1000))
120
- );
239
+ const recorder = getRecorder();
240
+ // The take's own path: startPlayer(uri) resolves a falsy uri to the
241
+ // library's "DEFAULT", a *fixed* cache file (sound.mp4/sound.m4a) — with
242
+ // per-take filenames that file is never the confirmed take, so the
243
+ // preview would play the wrong audio or error. The state holds the
244
+ // `file://`-normalized stopRecorder() result, the same value
245
+ // `handleConfirm` hands to `onComplete`.
246
+ if (!url) return;
247
+ await recorder.startPlayer(url);
248
+ recorder.addPlayBackListener((e) => {
249
+ setPlayTime(recorder.mmss(Math.floor(e.currentPosition / 1000)));
250
+ // Natural end of the take: the callback keeps firing while playing, so
251
+ // `isFinished` distinguishes the take finishing on its own from a user
252
+ // stop (which goes through `onStopPlay`/`handleReRecord`). Tear down the
253
+ // player and reset the play state so one tap replays — parity with the
254
+ // picker sheet's `isFinished` end-of-playback transition.
255
+ if (e.isFinished) void onStopPlay();
121
256
  return;
122
257
  });
258
+ setIsPlaying(true);
259
+ setIsPaused(false);
123
260
  };
124
261
 
125
262
  const onPausePlay = async () => {
126
- await audioRecorderPlayer.pausePlayer();
263
+ const recorder = recorderRef.current;
264
+ if (recorder) await recorder.pausePlayer();
265
+ setIsPaused(true);
127
266
  };
128
267
 
129
268
  const onResumePlay = async () => {
130
- await audioRecorderPlayer.resumePlayer();
269
+ const recorder = recorderRef.current;
270
+ if (recorder) await recorder.resumePlayer();
271
+ setIsPaused(false);
131
272
  };
132
273
 
133
274
  const onStopPlay = async () => {
134
- await audioRecorderPlayer.stopPlayer();
135
- audioRecorderPlayer.removePlayBackListener();
275
+ const recorder = recorderRef.current;
276
+ if (recorder) {
277
+ await recorder.stopPlayer();
278
+ recorder.removePlayBackListener();
279
+ }
280
+ setIsPlaying(false);
281
+ setIsPaused(false);
282
+ setPlayTime('00:00');
136
283
  };
137
284
 
285
+ // Display wall-clock time and enforce the hard cap from a wall-clock tick.
286
+ // The auto-stop threshold is half a second *under* the cap (`VOICE_NOTE_AUTO_STOP_SECONDS`):
287
+ // this tick is 500 ms coarse and the take's probed duration is the raw
288
+ // wall-clock span, so stopping at exactly 90 s would let ~half of honest
289
+ // cap-length takes probe above the server's `> VOICE_NOTE_MAX_SECONDS`
290
+ // check. See the constant's docs (common) for the boundary story.
291
+ useEffect(() => {
292
+ if (!isRecording || isPaused) return;
293
+ const id = setInterval(() => {
294
+ const elapsedSeconds = Math.floor(elapsedMs() / 1000);
295
+ const recorder = recorderRef.current;
296
+ if (recorder) setRecordTime(recorder.mmss(elapsedSeconds));
297
+ if (
298
+ elapsedMs() >= VOICE_NOTE_AUTO_STOP_SECONDS * 1000 &&
299
+ !stoppingRef.current
300
+ ) {
301
+ void onStopRecord();
302
+ }
303
+ }, 500);
304
+ return () => clearInterval(id);
305
+ }, [isRecording, isPaused]);
306
+
138
307
  const handleConfirm = async () => {
139
- if (url) {
308
+ if (url && isStopped) {
140
309
  await onComplete(url);
141
310
  }
142
311
  };
143
312
 
144
- // Update altText state if initialAltText prop changes
145
- React.useEffect(() => {
146
- getAndroidPermission();
147
- }, [getAndroidPermission]);
313
+ // Discard the take and return to the idle state — a bad take can be
314
+ // re-recorded without the dismiss-and-reopen round trip the web modal's
315
+ // Re-record button offers.
316
+ const handleReRecord = () => {
317
+ const recorder = recorderRef.current;
318
+ if (recorder) {
319
+ recorder.removePlayBackListener();
320
+ void recorder.stopPlayer().catch(() => undefined);
321
+ }
322
+ setUrl(null);
323
+ reset();
324
+ };
325
+
326
+ const hasTake = !!url;
327
+ const micErrorCopy =
328
+ micError === 'denied'
329
+ ? t('posts.form.voiceNote.micError')
330
+ : t('posts.form.voiceNote.micFailed');
331
+
332
+ // If the user swipes/back-dismisses the sheet while recording, the mic must
333
+ // not keep running — stop the in-progress take before the state is cleared.
334
+ const handleDismiss = () => {
335
+ const recorder = recorderRef.current;
336
+ if (recorder && isRecordingRef.current) {
337
+ void recorder
338
+ .stopRecorder()
339
+ .catch(() => undefined)
340
+ .finally(() => teardownListeners());
341
+ }
342
+ isRecordingRef.current = false;
343
+ setUrl(null);
344
+ reset();
345
+ };
148
346
 
149
347
  return (
150
- <BaseSheet
151
- ref={ref}
152
- onDismiss={() => {
153
- setUrl(null);
154
- reset();
155
- }}
156
- >
348
+ <BaseSheet ref={ref} onDismiss={handleDismiss}>
157
349
  <View className="flex-1 p-4 justify-between">
158
350
  <ThemedText>{t('common.media.audio.record')}</ThemedText>
159
- <ThemedText>
160
- {recordSecs} {String(isRecording)} {String(isPaused)}{' '}
161
- {String(isPlaying)} {playTime}
351
+ <ThemedText className="text-muted-foreground">
352
+ {t('common.media.audio.maxLength', {
353
+ seconds: VOICE_NOTE_MAX_SECONDS,
354
+ })}
162
355
  </ThemedText>
163
- <ThemedText>{url}</ThemedText>
164
- <View className="flex-row items-center justify-between">
165
- <View className="flex-row items-center gap-2">
166
- {!isRecording && !isPaused && (
167
- <Button onPress={onStartRecord} size="icon" variant={'ghost'}>
168
- <CircleIcon size={24} className="text-foreground" />
169
- </Button>
170
- )}
171
- {isRecording && !isPaused && (
172
- <Button onPress={onPauseRecord} variant={'ghost'}>
173
- <PauseIcon size={24} className="text-foreground" />
174
- </Button>
175
- )}
176
- {isRecording && isPaused && (
177
- <Button onPress={onResumeRecord} variant={'ghost'}>
178
- <CircleIcon size={24} className="text-foreground" />
179
- </Button>
180
- )}
181
- {isRecording && (
182
- <Button onPress={onStopRecord} variant={'ghost'}>
183
- <SquareIcon size={24} className="text-foreground" />
184
- </Button>
356
+ <View className="flex-1">
357
+ <View>
358
+ {/* Consent sits directly above the controls so it is read before
359
+ the user can start recording, not discovered under them. */}
360
+ <ThemedText className="text-muted-foreground">
361
+ {t('common.media.audio.whyPermission')}
362
+ </ThemedText>
363
+ {micError && (
364
+ <ThemedText className="text-destructive">
365
+ {micErrorCopy}
366
+ </ThemedText>
185
367
  )}
368
+ <View className="flex-row items-center justify-between">
369
+ <View className="flex-row items-center gap-2">
370
+ {!isRecording && !isPaused && !hasTake && (
371
+ <Button onPress={onStartRecord} size="icon" variant={'ghost'}>
372
+ <CircleIcon size={24} className="text-foreground" />
373
+ </Button>
374
+ )}
375
+ {isRecording && !isPaused && (
376
+ <Button onPress={onPauseRecord} variant={'ghost'}>
377
+ <PauseIcon size={24} className="text-foreground" />
378
+ </Button>
379
+ )}
380
+ {isRecording && isPaused && (
381
+ <Button onPress={onResumeRecord} variant={'ghost'}>
382
+ <CircleIcon size={24} className="text-foreground" />
383
+ </Button>
384
+ )}
385
+ {isRecording && (
386
+ <Button onPress={onStopRecord} variant={'ghost'}>
387
+ <SquareIcon size={24} className="text-foreground" />
388
+ </Button>
389
+ )}
390
+ </View>
391
+ {hasTake && <ThemedText>{recordTime}</ThemedText>}
392
+ </View>
186
393
  </View>
187
- {!!url && <ThemedText>{recordTime}</ThemedText>}
188
394
  </View>
189
- {!isRecording && !!url && !!recordSecs && (
395
+ {isStopped && (
190
396
  <View>
397
+ {/*
398
+ Round-17 item 1: `common.media.audio.play` was re-checked against
399
+ every repo consumer. `record-audio-sheet.tsx` (pre-existing on
400
+ main, not just this PR) and the `audio-picker-sheet` preview
401
+ button both read it; the PR's shortened "Play"/"Abspielen" copy
402
+ would have silently changed that pre-existing label. The values
403
+ were therefore restored to main's originals ("Play audio" /
404
+ "Audio abspielen") rather than introducing a dedicated key — the
405
+ preview play button is fine reading the longer copy.
406
+ */}
191
407
  <ThemedText>{t('common.media.audio.play')}</ThemedText>
192
408
  <ThemedText>
193
409
  {playTime} / {recordTime}
@@ -198,7 +414,7 @@ export const RecordAudioSheet = forwardRef<
198
414
  <PlayIcon size={24} className="text-foreground" />
199
415
  </Button>
200
416
  )}
201
- {isPlaying && (
417
+ {isPlaying && !isPaused && (
202
418
  <Button onPress={onPausePlay} variant={'ghost'}>
203
419
  <PauseIcon size={24} className="text-foreground" />
204
420
  </Button>
@@ -213,12 +429,20 @@ export const RecordAudioSheet = forwardRef<
213
429
  <SquareIcon size={24} className="text-foreground" />
214
430
  </Button>
215
431
  )}
432
+ <Button
433
+ onPress={handleReRecord}
434
+ variant={'ghost'}
435
+ accessibilityLabel={t('posts.form.voiceNote.reRecord')}
436
+ >
437
+ <Repeat2Icon size={24} className="text-foreground" />
438
+ </Button>
216
439
  </View>
217
440
  </View>
218
441
  )}
219
442
  <SheetFooter
220
443
  onCancel={() => bottomSheetDismiss(ref)}
221
444
  onConfirm={handleConfirm}
445
+ disabled={!url || !isStopped}
222
446
  confirmText={t('common.done')}
223
447
  />
224
448
  </View>
@@ -1,12 +1,19 @@
1
1
  import { Linking } from 'react-native';
2
2
 
3
- export const downloadDocument = async (url: string) => {
3
+ /**
4
+ * Open a URL in an external handler (the OS/browser) so the user can download
5
+ * it. Returns `true` when the URL could be handed off, or `false` when no app
6
+ * can open it — callers surface that to the user (e.g. Android 11+ where
7
+ * `canOpenURL` for `https` can return `false` without a `<queries>` manifest
8
+ * declaration).
9
+ */
10
+ export const downloadDocument = async (url: string): Promise<boolean> => {
4
11
  try {
5
12
  const canOpen = await Linking.canOpenURL(url);
6
- if (canOpen) {
7
- await Linking.openURL(url);
8
- }
9
- } catch (error) {
10
- console.error('Error opening URL:', error);
13
+ if (!canOpen) return false;
14
+ await Linking.openURL(url);
15
+ return true;
16
+ } catch {
17
+ return false;
11
18
  }
12
19
  };