@simba-dev/react-native-media-player 1.23.0 → 2.0.1

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,564 +0,0 @@
1
- import React, {
2
- useCallback,
3
- useEffect,
4
- useMemo,
5
- useRef,
6
- useState,
7
- } from 'react';
8
- import {
9
- Animated,
10
- Easing,
11
- GestureResponderEvent,
12
- LayoutChangeEvent,
13
- PanResponder,
14
- Pressable,
15
- StyleSheet,
16
- Text,
17
- View,
18
- } from 'react-native';
19
- import { useTheme } from './PlayerProvider';
20
- import { usePlayer, usePlayerProgress } from '../types/player';
21
-
22
- /**
23
- * The default controls component.
24
- *
25
- * Layout (top → bottom):
26
- * 1. **Top bar**: close (✕) + title + spacer for future more-menu.
27
- * 2. **Center**: empty — reserved for the loading spinner / error
28
- * state / buffer indicator.
29
- * 3. **Bottom bar**: time-current / scrubber / time-total + skip
30
- * back / play-pause / skip forward.
31
- *
32
- * Interaction:
33
- * - Auto-hides after 3 seconds of inactivity (opacity fade).
34
- * - Any tap (button or empty space) shows the controls + resets
35
- * the timer.
36
- * - Scrubber supports tap-to-seek (jump to a position by tapping
37
- * the bar) and drag-to-seek (continuous follow while dragging).
38
- *
39
- * Theming: every color comes from `useTheme()`. The component has
40
- * zero hardcoded color values — even the dimmed-overlay background
41
- * is `theme.background` with reduced opacity, so it harmonises with
42
- * the consumer's theme in dark / light / brand-color modes.
43
- *
44
- * The commands are wired to the `MpvPlayerModule` bridge, so play /
45
- * pause / seek actually drive mpv. Progress comes from
46
- * `usePlayerProgress()`, which is fed by the native mpv event
47
- * stream — there is no JS-side position poll.
48
- */
49
-
50
- const AUTO_HIDE_TIMEOUT_MS = 3000;
51
- const SCRUBBER_HEIGHT = 28; // hit target height for tap/drag
52
- const SKIP_BACK_SECONDS = 10;
53
- const SKIP_FORWARD_SECONDS = 10;
54
-
55
- /**
56
- * Props accepted by `<DefaultControls>`. The component is a thin
57
- * shell: PlayerRoot (or any consumer using the `renderControls`
58
- * slot's fallback path) passes the player's title/subtitle plus
59
- * play/pause callbacks. The component reads player state +
60
- * progress from the `usePlayer()` / `usePlayerProgress()` hooks
61
- * directly, so no other state is required as props.
62
- *
63
- * Phase 30 export: previously PlayerRoot referenced this type but
64
- * it was never exported (a Phase 24 oversight that only surfaced
65
- * once the module's tsconfig was wired for standalone typecheck).
66
- */
67
- export interface DefaultControlsProps {
68
- title?: string;
69
- subtitle?: string;
70
- onPlay?: () => void;
71
- onPause?: () => void;
72
- /**
73
- * V22.0.0 / 1.5.8 (D-035 fix #4): handler for the close ✕ button
74
- * (top-left). PlayerRoot wires this to `bridge.exitPipAndFinish()`,
75
- * which dismisses the player UI and leaves PiP. When omitted, the
76
- * ✕ falls back to `onPause` (matches the V21 behaviour that had no
77
- * dedicated close).
78
- */
79
- onClose?: () => void;
80
- }
81
-
82
- /** Format milliseconds as `H:MM:SS` or `M:SS`. */
83
- function formatTime(ms: number): string {
84
- if (!Number.isFinite(ms) || ms < 0) return '0:00';
85
- const totalSeconds = Math.floor(ms / 1000);
86
- const hours = Math.floor(totalSeconds / 3600);
87
- const minutes = Math.floor((totalSeconds % 3600) / 60);
88
- const seconds = totalSeconds % 60;
89
- const mm = minutes.toString();
90
- const ss = seconds.toString().padStart(2, '0');
91
- if (hours > 0) {
92
- return `${hours}:${mm.padStart(2, '0')}:${ss}`;
93
- }
94
- return `${mm}:${ss}`;
95
- }
96
-
97
- /** Clamp a number into [min, max]. */
98
- function clamp(value: number, min: number, max: number): number {
99
- return Math.max(min, Math.min(max, value));
100
- }
101
-
102
- export function DefaultControls(props: DefaultControlsProps = {}): React.ReactElement {
103
- const { title, subtitle: subtitleProp, onPlay, onPause, onClose } = props;
104
- const theme = useTheme();
105
- const { state, commands } = usePlayer();
106
- const { positionMs, durationMs } = usePlayerProgress();
107
-
108
- // ── Auto-hide state ───────────────────────────────────────────────────
109
- const [visible, setVisible] = useState(true);
110
- const opacity = useRef(new Animated.Value(1)).current;
111
- const hideTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
112
-
113
- const showControls = useCallback(() => {
114
- setVisible(true);
115
- Animated.timing(opacity, {
116
- toValue: 1,
117
- duration: 180,
118
- easing: Easing.out(Easing.quad),
119
- useNativeDriver: true,
120
- }).start();
121
- if (hideTimerRef.current) {
122
- clearTimeout(hideTimerRef.current);
123
- }
124
- hideTimerRef.current = setTimeout(() => {
125
- setVisible(false);
126
- Animated.timing(opacity, {
127
- toValue: 0,
128
- duration: 220,
129
- easing: Easing.in(Easing.quad),
130
- useNativeDriver: true,
131
- }).start();
132
- }, AUTO_HIDE_TIMEOUT_MS);
133
- }, [opacity]);
134
-
135
- useEffect(() => {
136
- showControls();
137
- return () => {
138
- if (hideTimerRef.current) clearTimeout(hideTimerRef.current);
139
- };
140
- }, [showControls]);
141
-
142
- // ── Scrubber state ────────────────────────────────────────────────────
143
- const [scrubberWidth, setScrubberWidth] = useState(0);
144
- const [draggingPositionMs, setDraggingPositionMs] = useState<
145
- number | null
146
- >(null);
147
-
148
- const onScrubberLayout = useCallback((e: LayoutChangeEvent) => {
149
- setScrubberWidth(e.nativeEvent.layout.width);
150
- }, []);
151
-
152
- const positionFromX = useCallback(
153
- (x: number): number => {
154
- if (scrubberWidth <= 0 || durationMs <= 0) return 0;
155
- const ratio = clamp(x / scrubberWidth, 0, 1);
156
- return Math.round(ratio * durationMs);
157
- },
158
- [scrubberWidth, durationMs],
159
- );
160
-
161
- const seekTo = useCallback(
162
- (newPositionMs: number) => {
163
- const clamped = clamp(newPositionMs, 0, Math.max(0, durationMs));
164
- commands.seek(clamped);
165
- },
166
- [commands, durationMs],
167
- );
168
-
169
- const panResponder = useMemo(
170
- () =>
171
- PanResponder.create({
172
- onStartShouldSetPanResponder: () => true,
173
- onMoveShouldSetPanResponder: () => true,
174
- onPanResponderGrant: (evt: GestureResponderEvent) => {
175
- setDraggingPositionMs(positionFromX(evt.nativeEvent.locationX));
176
- showControls();
177
- },
178
- onPanResponderMove: (evt: GestureResponderEvent) => {
179
- setDraggingPositionMs(positionFromX(evt.nativeEvent.locationX));
180
- },
181
- onPanResponderRelease: (evt: GestureResponderEvent) => {
182
- const final = positionFromX(evt.nativeEvent.locationX);
183
- setDraggingPositionMs(null);
184
- seekTo(final);
185
- },
186
- onPanResponderTerminate: () => {
187
- setDraggingPositionMs(null);
188
- },
189
- }),
190
- [positionFromX, seekTo, showControls],
191
- );
192
-
193
- const onScrubberTap = useCallback(
194
- (evt: GestureResponderEvent) => {
195
- // PanResponder handles drag; this branch covers a pure tap
196
- // (grant + release at the same x). PanResponder's release
197
- // handler will fire after grant, so this is a fallback for
198
- // test environments that strip gesture responders.
199
- const x = evt.nativeEvent.locationX;
200
- seekTo(positionFromX(x));
201
- showControls();
202
- },
203
- [positionFromX, seekTo, showControls],
204
- );
205
-
206
- // ── Derived render values ─────────────────────────────────────────────
207
- const effectivePositionMs =
208
- draggingPositionMs != null ? draggingPositionMs : positionMs;
209
- const progressRatio =
210
- durationMs > 0 ? clamp(effectivePositionMs / durationMs, 0, 1) : 0;
211
- const iconColor = theme.icon ?? theme.text;
212
- // Props take precedence; otherwise derive from player state (title +
213
- // artist/album). Phase 30 wires this so PlayerRoot's fallback path
214
- // can override the default behaviour.
215
- const effectiveTitle = title ?? state.title;
216
- const effectiveOnPlay = onPlay ?? commands.play;
217
- const effectiveOnPause = onPause ?? commands.pause;
218
- const effectiveOnClose = onClose ?? effectiveOnPause;
219
- const subtitle =
220
- subtitleProp ??
221
- (state.artist && state.album
222
- ? `${state.artist} • ${state.album}`
223
- : state.artist || state.album || undefined);
224
-
225
- return (
226
- <Pressable
227
- style={styles.root}
228
- onPress={showControls}
229
- accessibilityRole="summary"
230
- accessibilityLabel="Simba Player controls"
231
- // Animated.View as the inner wrapper so opacity tweens work
232
- // without affecting tap-handling on the root Pressable.
233
- >
234
- {/*
235
- V22.0.0 / 1.5.8 (D-036 — video-not-showing fix):
236
-
237
- The previous version had `backgroundColor: 'rgba(0,0,0,0.001)'`
238
- on the `fill` View, with the comment "ensure hit-tests
239
- propagate". That hack made the Animated.View hit-testable so
240
- outer Pressable's onPress=showControls fired. BUT on Android,
241
- a near-opaque View sitting on top of the SurfaceView blocks
242
- the SurfaceView's video frames — the compositor treats the
243
- overlay as opaque and the GPU-rendered frames never reach
244
- the screen. The user sees audio + controls + black where the
245
- video should be.
246
-
247
- Fix: use `pointerEvents="box-none"` so the Animated.View
248
- never catches taps itself (only children do), and set the
249
- fill background to transparent so the SurfaceView's video
250
- frames composite through. The outer Pressable's onPress
251
- still catches every tap on the empty area — Pressable's
252
- hit-test machinery doesn't depend on its own backgroundColor
253
- for that.
254
-
255
- Previous behaviour preserved:
256
- - Buttons (close, play/pause, skip) are inner Pressables
257
- with their own hit testing — they still work.
258
- - Tap-anywhere-shows-controls still fires via the outer
259
- Pressable's onPress, identical to the rgba trick in
260
- practice.
261
- - Opacity tween is preserved (Animated.View + `opacity`
262
- style).
263
-
264
- Behaviour that's now strictly better:
265
- - Video frames visible (this is the whole point).
266
- - No "almost-opaque" hack to reason about — the View is
267
- either fully transparent or fully opaque, no in-between.
268
- */}
269
- <Animated.View
270
- pointerEvents="box-none"
271
- style={[styles.fill, { opacity }]}
272
- >
273
- {/* Top bar */}
274
- <View style={styles.topBar}>
275
- <Pressable
276
- accessibilityRole="button"
277
- accessibilityLabel="Close player"
278
- onPress={effectiveOnClose}
279
- hitSlop={8}
280
- style={({ pressed }) => [
281
- styles.iconButton,
282
- { backgroundColor: theme.surface, opacity: pressed ? 0.6 : 1 },
283
- ]}
284
- >
285
- <Text style={[styles.iconText, { color: iconColor }]}>✕</Text>
286
- </Pressable>
287
- <View style={styles.titleColumn}>
288
- <Text
289
- style={[styles.title, { color: theme.text }]}
290
- numberOfLines={1}
291
- accessibilityRole="header"
292
- >
293
- {effectiveTitle}
294
- </Text>
295
- {subtitle ? (
296
- <Text
297
- style={[styles.subtitle, { color: theme.textSecondary }]}
298
- numberOfLines={1}
299
- >
300
- {subtitle}
301
- </Text>
302
- ) : null}
303
- </View>
304
- {/* Spacer to keep the title centred; reserved for a
305
- more-menu icon. */}
306
- <View style={styles.iconButton} />
307
- </View>
308
-
309
- {/* Center: reserved for the loading / error / buffer
310
- indicator (the empty View keeps the top + bottom bars
311
- pinned to the edges via flex layout.) */}
312
- <View style={styles.center} />
313
-
314
- {/* Bottom bar */}
315
- <View style={styles.bottomBar}>
316
- <View style={styles.scrubberRow}>
317
- <Text
318
- style={[styles.timeText, { color: theme.textSecondary }]}
319
- accessibilityLabel={`Position ${formatTime(effectivePositionMs)}`}
320
- >
321
- {formatTime(effectivePositionMs)}
322
- </Text>
323
- <View
324
- style={styles.scrubberHitArea}
325
- onLayout={onScrubberLayout}
326
- {...panResponder.panHandlers}
327
- accessibilityRole="adjustable"
328
- accessibilityLabel="Seek bar"
329
- accessibilityValue={{
330
- min: 0,
331
- max: Math.round(durationMs / 1000),
332
- now: Math.round(effectivePositionMs / 1000),
333
- }}
334
- >
335
- {/* Tap-only fallback under the pan responder; invisible
336
- because the pan responder's onPanResponderRelease
337
- handles the actual seek, but it gives the bar a
338
- visible touch target on platforms where the
339
- responder takes a frame to activate. */}
340
- <Pressable
341
- style={StyleSheet.absoluteFill}
342
- onPress={onScrubberTap}
343
- />
344
- {/* Bar background */}
345
- <View
346
- style={[
347
- styles.scrubberTrack,
348
- { backgroundColor: theme.surface },
349
- ]}
350
- />
351
- {/* Filled portion */}
352
- <View
353
- style={[
354
- styles.scrubberFill,
355
- {
356
- width: `${progressRatio * 100}%`,
357
- backgroundColor: theme.accent,
358
- },
359
- ]}
360
- />
361
- {/* Thumb */}
362
- <View
363
- style={[
364
- styles.scrubberThumb,
365
- {
366
- left: `${progressRatio * 100}%`,
367
- backgroundColor: theme.accent,
368
- },
369
- ]}
370
- />
371
- </View>
372
- <Text
373
- style={[styles.timeText, { color: theme.textSecondary }]}
374
- accessibilityLabel={`Duration ${formatTime(durationMs)}`}
375
- >
376
- {formatTime(durationMs)}
377
- </Text>
378
- </View>
379
-
380
- <View style={styles.transportRow}>
381
- <Pressable
382
- accessibilityRole="button"
383
- accessibilityLabel={`Skip back ${SKIP_BACK_SECONDS} seconds`}
384
- onPress={() => commands.skipBackward(SKIP_BACK_SECONDS)}
385
- hitSlop={8}
386
- style={({ pressed }) => [
387
- styles.transportButton,
388
- { opacity: pressed ? 0.6 : 1 },
389
- ]}
390
- >
391
- <Text style={[styles.transportIcon, { color: iconColor }]}>
392
- ⏪
393
- </Text>
394
- <Text style={[styles.transportLabel, { color: iconColor }]}>
395
- {SKIP_BACK_SECONDS}
396
- </Text>
397
- </Pressable>
398
-
399
- <Pressable
400
- accessibilityRole="button"
401
- accessibilityLabel={state.isPlaying ? 'Pause' : 'Play'}
402
- onPress={state.isPlaying ? effectiveOnPause : effectiveOnPlay}
403
- hitSlop={8}
404
- style={({ pressed }) => [
405
- styles.playButton,
406
- {
407
- backgroundColor: theme.accent,
408
- opacity: pressed ? 0.7 : 1,
409
- },
410
- ]}
411
- >
412
- <Text
413
- style={[styles.playIcon, { color: theme.background }]}
414
- accessibilityElementsHidden
415
- >
416
- {state.isPlaying ? '⏸' : '▶'}
417
- </Text>
418
- </Pressable>
419
-
420
- <Pressable
421
- accessibilityRole="button"
422
- accessibilityLabel={`Skip forward ${SKIP_FORWARD_SECONDS} seconds`}
423
- onPress={() => commands.skipForward(SKIP_FORWARD_SECONDS)}
424
- hitSlop={8}
425
- style={({ pressed }) => [
426
- styles.transportButton,
427
- { opacity: pressed ? 0.6 : 1 },
428
- ]}
429
- >
430
- <Text style={[styles.transportIcon, { color: iconColor }]}>
431
- ⏩
432
- </Text>
433
- <Text style={[styles.transportLabel, { color: iconColor }]}>
434
- {SKIP_FORWARD_SECONDS}
435
- </Text>
436
- </Pressable>
437
- </View>
438
- </View>
439
- </Animated.View>
440
- </Pressable>
441
- );
442
- }
443
-
444
- const styles = StyleSheet.create({
445
- root: {
446
- flex: 1,
447
- backgroundColor: 'transparent',
448
- },
449
- fill: {
450
- flex: 1,
451
- // V22.0.0 / 1.5.8 (D-036): was 'rgba(0,0,0,0.001)' — that near-opaque
452
- // black occluded the SurfaceView's video frames on Android. See the
453
- // long-form comment on the Animated.View below for the full rationale.
454
- // Hit-tests now reach the outer Pressable's onPress via `box-none`.
455
- backgroundColor: 'transparent',
456
- justifyContent: 'space-between',
457
- },
458
- topBar: {
459
- flexDirection: 'row',
460
- alignItems: 'center',
461
- paddingHorizontal: 16,
462
- paddingTop: 16,
463
- paddingBottom: 12,
464
- gap: 12,
465
- },
466
- iconButton: {
467
- width: 40,
468
- height: 40,
469
- borderRadius: 20,
470
- alignItems: 'center',
471
- justifyContent: 'center',
472
- },
473
- iconText: {
474
- fontSize: 20,
475
- fontWeight: '600',
476
- },
477
- titleColumn: {
478
- flex: 1,
479
- alignItems: 'center',
480
- },
481
- title: {
482
- fontSize: 16,
483
- fontWeight: '700',
484
- textAlign: 'center',
485
- },
486
- subtitle: {
487
- fontSize: 12,
488
- marginTop: 2,
489
- textAlign: 'center',
490
- },
491
- center: {
492
- flex: 1,
493
- },
494
- bottomBar: {
495
- paddingHorizontal: 16,
496
- paddingBottom: 24,
497
- paddingTop: 8,
498
- gap: 16,
499
- },
500
- scrubberRow: {
501
- flexDirection: 'row',
502
- alignItems: 'center',
503
- gap: 10,
504
- },
505
- timeText: {
506
- fontSize: 12,
507
- fontVariant: ['tabular-nums'],
508
- minWidth: 48,
509
- textAlign: 'center',
510
- },
511
- scrubberHitArea: {
512
- flex: 1,
513
- height: SCRUBBER_HEIGHT,
514
- justifyContent: 'center',
515
- },
516
- scrubberTrack: {
517
- height: 4,
518
- borderRadius: 2,
519
- width: '100%',
520
- },
521
- scrubberFill: {
522
- position: 'absolute',
523
- height: 4,
524
- borderRadius: 2,
525
- left: 0,
526
- },
527
- scrubberThumb: {
528
- position: 'absolute',
529
- width: 14,
530
- height: 14,
531
- borderRadius: 7,
532
- marginLeft: -7, // center the thumb on the fill edge
533
- top: (SCRUBBER_HEIGHT - 14) / 2,
534
- },
535
- transportRow: {
536
- flexDirection: 'row',
537
- alignItems: 'center',
538
- justifyContent: 'space-evenly',
539
- },
540
- transportButton: {
541
- minWidth: 64,
542
- alignItems: 'center',
543
- justifyContent: 'center',
544
- paddingVertical: 8,
545
- },
546
- transportIcon: {
547
- fontSize: 24,
548
- },
549
- transportLabel: {
550
- fontSize: 10,
551
- marginTop: 2,
552
- },
553
- playButton: {
554
- width: 64,
555
- height: 64,
556
- borderRadius: 32,
557
- alignItems: 'center',
558
- justifyContent: 'center',
559
- },
560
- playIcon: {
561
- fontSize: 30,
562
- fontWeight: '700',
563
- },
564
- });