@simba-dev/react-native-media-player 1.23.0 → 2.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@simba-dev/react-native-media-player",
3
- "version": "1.23.0",
3
+ "version": "2.0.0",
4
4
  "description": "React Native video & audio player powered by libmpv — Picture-in-Picture, MediaSession, foreground service, and a customizable TypeScript UI. Built for Android. Designed as a drop-in replacement for react-native-video / react-native-track-player / expo-av. See CHANGELOG.md for per-version notes.",
5
5
  "main": "src/index.ts",
6
6
  "types": "src/index.ts",
@@ -821,7 +821,7 @@ let _emitter: NativeEventEmitter | null = null;
821
821
  * V13 Phase 50: the bridge-presence check now also requires
822
822
  * `loadFile` (the cheapest method that doesn't depend on
823
823
  * `initPlayer()` having been called) — older V12 stubs only had
824
- * the 9 methods DefaultControls needed.
824
+ * the 9 methods the control bundle needed.
825
825
  */
826
826
  function resolveBridge(): MpvPlayerModuleBridge | null {
827
827
  const mod = (NativeModules as Record<string, unknown>).MpvPlayerModule;
@@ -901,9 +901,8 @@ export { dlog };
901
901
  /**
902
902
  * V13 Phase 50: live bridge (or no-op fallback). Consumers should
903
903
  * always import this getter rather than reach into `NativeModules`
904
- * directly — the no-op fallback is what keeps `DefaultControls`
905
- * and consumer code renderable in jest tests + Storybook + web
906
- * previews.
904
+ * directly — the no-op fallback is what keeps consumer code
905
+ * renderable in jest tests + Storybook + web previews.
907
906
  */
908
907
  export function getMpvPlayerModule(): MpvPlayerModuleBridge {
909
908
  const live = resolveBridge();
@@ -47,7 +47,7 @@ const PlayerConfigContext = createContext<ResolvedPlayerConfig | null>(null);
47
47
  * Function signature for the `renderControls` slot. Takes no args —
48
48
  * the consumer's controls component reads what it needs from
49
49
  * `usePlayer()` (state + commands) and `useTheme()` (colors) itself.
50
- * Returns the React tree to render in place of `DefaultControls`.
50
+ * Returns the React tree to render as the player's chrome.
51
51
  *
52
52
  * Why a function (not a component): the parent decides WHEN to call
53
53
  * it (typically inside a `PlayerRoot` component), which lets us
@@ -60,7 +60,7 @@ export type RenderControlsFn = () => React.ReactNode;
60
60
  * Context carrying the `renderControls` slot. Separate from the
61
61
  * config context so consumers that only read the config don't
62
62
  * re-render when the controls prop changes, and vice versa. `null`
63
- * means "no custom controls — fall back to `DefaultControls`".
63
+ * means "no controls" — the library draws none of its own.
64
64
  */
65
65
  const PlayerRenderControlsContext = createContext<RenderControlsFn | null>(null);
66
66
 
@@ -107,20 +107,22 @@ export function useTheme(): PlayerTheme {
107
107
 
108
108
  /**
109
109
  * Phase 23 hook: read the `renderControls` slot from the nearest
110
- * `<PlayerProvider>`. Returns `null` when no custom controls were
111
- * passed — the caller (typically `<PlayerRoot>`) should fall back to
112
- * `<DefaultControls>` in that case.
110
+ * `<PlayerProvider>`. Returns `null` when no controls were passed.
111
+ *
112
+ * **v2.0.0:** `null` means "no chrome", not "fall back to the
113
+ * library's controls" — the library no longer ships any. A consumer
114
+ * that wants controls renders them and passes them here.
113
115
  *
114
116
  * Returns `null` (not throws) when used outside a provider, because
115
- * `<PlayerRoot>` needs to gracefully render the fallback in that
116
- * case. The other hooks (`usePlayerConfig` / `useTheme`) throw
117
- * because they have no useful fallback value.
117
+ * `<PlayerRoot>` needs to render without chrome in that case. The
118
+ * other hooks (`usePlayerConfig` / `useTheme`) throw because they
119
+ * have no useful fallback value.
118
120
  *
119
121
  * @example
120
122
  * ```tsx
121
- * function PlayerRoot() {
123
+ * function MyPlayer() {
122
124
  * const renderControls = useRenderControls();
123
- * return renderControls != null ? renderControls() : <DefaultControls />;
125
+ * return renderControls != null ? renderControls() : null;
124
126
  * }
125
127
  * ```
126
128
  */
@@ -436,7 +438,7 @@ export interface PlayerProviderProps {
436
438
  config?: PlayerConfig;
437
439
  /**
438
440
  * Phase 23 slot: optional function that returns the React tree to
439
- * render in place of `<DefaultControls>`. The function takes no
441
+ * render as the player's chrome. The function takes no
440
442
  * arguments — consumers that need theme / state / commands read
441
443
  * them from `useTheme()` / `usePlayer()` inside their custom
442
444
  * component.
@@ -450,10 +452,11 @@ export interface PlayerProviderProps {
450
452
  * </PlayerProvider>
451
453
  * ```
452
454
  *
453
- * When omitted, `<PlayerRoot>` (Phase 23) falls back to rendering
454
- * `<DefaultControls>` — so consumers can adopt the player
455
- * incrementally: ship with the defaults, then swap in a custom
456
- * implementation later without touching `<PlayerProvider>`.
455
+ * **v2.0.0 — optional, and omitted means "no chrome".** The library
456
+ * draws no controls of its own, so a consumer that omits this slot
457
+ * gets a picture and nothing else. It stays optional on purpose:
458
+ * the common case is a consumer that drives the player itself and
459
+ * never renders a full-screen control bar at all.
457
460
  */
458
461
  renderControls?: RenderControlsFn;
459
462
  /**
@@ -1,18 +1,25 @@
1
1
  import React from 'react';
2
2
  import { StyleSheet, View } from 'react-native';
3
- import { DefaultControls, type DefaultControlsProps } from './DefaultControls';
4
3
  import { useRenderControls } from './PlayerProvider';
5
- import { usePlayer } from '../types/player';
6
4
  import { useLaunchPlayback } from '../hooks/useLaunchPlayback';
7
- import {
8
- getMpvPlayerModule,
9
- type LaunchParams,
10
- } from '../bridge/MpvPlayerModule';
5
+ import type { LaunchParams } from '../bridge/MpvPlayerModule';
11
6
  import { PlayerSurface } from './PlayerSurface';
12
7
 
13
8
  /**
14
- * Phase 23 + Phase 25 root component for the PlayerActivity JS
15
- * tree.
9
+ * The player's root: the surface, and the consumer's controls over it.
10
+ *
11
+ * ## v2.0.0 — the library draws no chrome
12
+ *
13
+ * Before 2.0.0 this component fell back to `<DefaultControls>` — the
14
+ * 564-line control bundle the library used to ship — whenever the
15
+ * consumer did not pass `renderControls`. That fallback is **gone**.
16
+ * The library renders **no chrome of its own**: the consumer's
17
+ * `renderControls` output, or nothing at all.
18
+ *
19
+ * The overlay is mounted only when there is something to put in it, so
20
+ * a consumer that drives the player itself (the usual case — render
21
+ * `<SimbaVideo />` in your own tree) gets no phantom container over
22
+ * the surface.
16
23
  *
17
24
  * V21 F5: `launchParams` is now an explicit prop with no implicit
18
25
  * fallback. It used to fall back to `useLaunchParams()`, which read a
@@ -26,9 +33,9 @@ import { PlayerSurface } from './PlayerSurface';
26
33
  * for the native SurfaceView that mpv draws into. Fills the
27
34
  * available space via `flex: 1`.
28
35
  * 2. **Controls overlay** (Phase 23 + 24): the consumer's custom
29
- * controls (via `renderControls`) or `<DefaultControls>` as
30
- * fallback. Absolutely positioned over the surface so the
31
- * video fills the screen and the controls layer on top.
36
+ * controls, via `renderControls`. Absolutely positioned over the
37
+ * surface so the video fills the screen and the controls layer on
38
+ * top.
32
39
  *
33
40
  * Wiring example for a consumer:
34
41
  *
@@ -52,9 +59,6 @@ import { PlayerSurface } from './PlayerSurface';
52
59
  * insets (`top / left / right / bottom: 0`) so it stretches over
53
60
  * the surface without affecting its layout. The surface owns the
54
61
  * flex layout for the tree; the controls float on top.
55
- * - The fallback path reads `usePlayer()` and passes
56
- * `state.title / state.artist` + `commands.play / pause` through
57
- * to `<DefaultControls>`.
58
62
  * - When `renderControls` is provided, we render its output
59
63
  * wrapped in the same absolutely-positioned overlay container,
60
64
  * so custom controls don't need to handle their own
@@ -84,7 +88,6 @@ export function PlayerRoot({
84
88
  launchParams,
85
89
  }: PlayerRootProps = {}): React.ReactElement {
86
90
  const renderControls = useRenderControls();
87
- const { state, commands } = usePlayer();
88
91
 
89
92
  // V22.0.0 / 1.5.8 (D-035 fix #3 + #5 + #7): feed the launch URI to
90
93
  // mpv exactly once per `(uri, startPositionMs)` payload, NOT once
@@ -94,41 +97,15 @@ export function PlayerRoot({
94
97
  // the URI actually changes.
95
98
  useLaunchPlayback(launchParams);
96
99
 
97
- const overlay: React.ReactNode = (() => {
98
- if (renderControls != null) {
99
- return renderControls();
100
- }
101
- const props: DefaultControlsProps = {
102
- title: state.title || 'Simba Player',
103
- subtitle:
104
- state.artist && state.album
105
- ? `${state.artist} • ${state.album}`
106
- : state.artist || state.album || undefined,
107
- onPlay: commands.play,
108
- onPause: commands.pause,
109
- // V22.0.0 / 1.5.8 (D-035 fix #4): the close ✕ button calls
110
- // `exitPipAndFinish` on the bridge, which dismisses the
111
- // activity + tears down the SurfaceView properly. Falls back
112
- // to the no-op `close` command when the bridge is absent
113
- // (jest / web preview).
114
- onClose:
115
- typeof (getMpvPlayerModule().exitPipAndFinish) === 'function'
116
- ? () => {
117
- try {
118
- getMpvPlayerModule().exitPipAndFinish();
119
- } catch {
120
- // ignore
121
- }
122
- }
123
- : undefined,
124
- };
125
- return <DefaultControls {...props} />;
126
- })();
100
+ // The library draws no chrome. Whatever the consumer supplied is
101
+ // what appears over the surface; if the consumer supplied nothing,
102
+ // there is nothing to draw.
103
+ const controls = renderControls != null ? renderControls() : null;
127
104
 
128
105
  return (
129
106
  <View style={styles.root}>
130
107
  <PlayerSurface />
131
- <View style={styles.overlay}>{overlay}</View>
108
+ {controls != null ? <View style={styles.overlay}>{controls}</View> : null}
132
109
  </View>
133
110
  );
134
111
  }
@@ -3,51 +3,41 @@ import { StyleSheet, View } from 'react-native';
3
3
 
4
4
  export interface PlayerSurfaceProps {
5
5
  /**
6
- * Background color for the placeholder. Defaults to
7
- * `'transparent'` so the native SurfaceView (which sits at the
8
- * activity root, beneath the React tree) shows through to the
9
- * user. V11 used `#000000` here because the placeholder WAS the
10
- * SurfaceView in that architecture — V12+ moved the SurfaceView
11
- * out of the React tree and pinned it to `android.R.id.content`,
12
- * so a black placeholder now covers every decoded frame.
13
- * Consumers that want a colored backdrop (e.g. for branded
14
- * splash screens while mpv initializes) can pass a non-transparent
15
- * value — the actual video frames paint over it once mpv's
16
- * first frame is decoded.
6
+ * Background color for the placeholder. Defaults to `'transparent'`,
7
+ * so whatever is behind it shows through to the user.
8
+ *
9
+ * **v2.0.0:** the native SurfaceView this placeholder used to stand
10
+ * in for is gone — the picture is `<SimbaVideo />`, in the React
11
+ * tree. A non-transparent value therefore paints a backdrop *over*
12
+ * the picture wherever the placeholder sits in front of it.
17
13
  */
18
14
  backgroundColor?: string;
19
15
  }
20
16
 
21
17
  /**
22
- * Phase 25: no-op JS placeholder for the natively-rendered
23
- * SurfaceView. The actual SurfaceView that mpv draws into lives on
24
- * the Kotlin side of PlayerActivity (`MpvRenderView` in the module
25
- * + `PlayerActivity.onCreate`'s `setContentView`). This JS
26
- * component exists only to reserve layout space in the React tree
27
- * so the controls overlay knows where to anchor.
18
+ * A transparent, full-size **layout placeholder**.
28
19
  *
29
- * Why a placeholder rather than a real view:
30
- * - The native SurfaceView is attached to the activity's
31
- * `android.R.id.content` FrameLayout directly (see Phase 4). It
32
- * is NOT a child of the React root view, so it doesn't need a
33
- * JS counterpart.
34
- * - The placeholder fills the same screen rectangle as the native
35
- * SurfaceView because PlayerActivity pins the React root to the
36
- * same insets the SurfaceView occupies (Phase 15 — full-screen
37
- * with status / nav bar handling).
38
- * - Adding `position: 'absolute'` here would force the controls
39
- * sibling to also be absolutely positioned. Using `flex: 1`
40
- * keeps the React tree in normal flow; the controls are placed
41
- * as a sibling with absolute positioning by `PlayerRoot`.
20
+ * ## v2.0.0 — what this is, and is not
42
21
  *
43
- * Consumers don't usually render this directly — `PlayerRoot`
44
- * (Phase 23) renders it automatically. The export is exposed so
45
- * consumers who pass a fully custom `renderControls` to
46
- * `<PlayerProvider>` can still include `<PlayerSurface />` in their
47
- * tree when they want the placeholder visible (e.g. for theming
48
- * tests).
22
+ * This component used to stand in for the native SurfaceView that mpv
23
+ * drew into. Back then the surface was a **sibling** of the React
24
+ * root — pinned to `android.R.id.content` by the library's own
25
+ * `PlayerActivity` — and this box reserved the screen rectangle the
26
+ * controls overlay was positioned against.
49
27
  *
50
- * Surface is rendered natively by PlayerActivity.
28
+ * **That arrangement is gone.** The picture is now `<SimbaVideo />`:
29
+ * a Fabric component (`SimbaVideoView`) inside the React tree, with
30
+ * React Native owning its layout, its z-order and its lifecycle.
31
+ * Neither the library nor a host app mounts a surface at the activity
32
+ * root any more — a host app's Activity says so in as many words.
33
+ *
34
+ * What is left is a transparent `flex: 1` box: a full-size rectangle
35
+ * for a controls overlay to anchor to. `<PlayerRoot>` renders it.
36
+ *
37
+ * Whether this component and `<PlayerRoot>` should exist at all is an
38
+ * open question — see `B-035` in the app's master plan. Until that is
39
+ * decided they stay: a published package cannot quietly drop a public
40
+ * export.
51
41
  */
52
42
  export function PlayerSurface({
53
43
  backgroundColor = 'transparent',
@@ -13,7 +13,7 @@
13
13
  * - useRenderControls returns null when no renderControls prop is
14
14
  * provided, the provided function otherwise
15
15
  * - useRenderControls does NOT throw outside provider (falls back to
16
- * null so DefaultControls can render)
16
+ * null so a consumer's controls can render)
17
17
  * - Provider passes resolved config to native bridge via setConfig
18
18
  * on mount and when the config prop changes
19
19
  * - Provider does NOT call setConfig when config prop is reference-
@@ -157,9 +157,9 @@ describe('useRenderControls', () => {
157
157
 
158
158
  it('returns null when called outside a provider (does NOT throw)', async () => {
159
159
  // Important behavioural difference from usePlayerConfig/useTheme:
160
- // useRenderControls is non-throwing so DefaultControls can render
161
- // unconditionally. (If a consumer uses DefaultControls directly
162
- // without a Provider, they get the default UI, not a crash.)
160
+ // useRenderControls is non-throwing so a consumer's controls can render
161
+ // unconditionally. (If a consumer renders their own controls
162
+ // without a Provider, they get no chrome, not a crash.)
163
163
  const { result } = await renderHook(() => useRenderControls());
164
164
  expect(result.current).toBeNull();
165
165
  });
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Unit tests for `src/components/PlayerRoot.tsx`.
3
+ *
4
+ * v2.0.0 (the app's register item 28) — **the library draws no chrome.**
5
+ *
6
+ * `DefaultControls` was removed, so `<PlayerRoot>` has no fallback: with
7
+ * no `renderControls`, it renders the surface and NOTHING else. Before
8
+ * 2.0.0 it fell back to a 564-line control bundle the library shipped,
9
+ * which meant the library always had a chrome implementation a consumer
10
+ * could end up using by accident.
11
+ *
12
+ * Test surface:
13
+ * - no `renderControls` → the surface, and no second child
14
+ * - `renderControls` → the consumer's controls, over the surface
15
+ * - the package does not export a default control bundle
16
+ *
17
+ * The first test is the "must not" test: it fails if a chrome fallback
18
+ * ever comes back, because a fallback is a second child of the root.
19
+ */
20
+
21
+ import React from 'react';
22
+ import { Text } from 'react-native';
23
+ import { render, screen } from '@testing-library/react-native';
24
+ import { PlayerRoot } from '../PlayerRoot';
25
+ import { PlayerProvider } from '../PlayerProvider';
26
+
27
+ describe('PlayerRoot', () => {
28
+ it('renders the surface and nothing else when the consumer supplies no controls', async () => {
29
+ await render(
30
+ <PlayerProvider>
31
+ <PlayerRoot />
32
+ </PlayerProvider>,
33
+ );
34
+
35
+ const tree = screen.toJSON();
36
+ expect(tree).not.toBeNull();
37
+
38
+ // The host tree is a plain View tree, so the root is the tree's
39
+ // root node. `children` is typed loosely on purpose: the
40
+ // `test-renderer` version has changed this shape before.
41
+ const root = tree as unknown as { type: string; children: unknown };
42
+ expect(root.type).toBe('View');
43
+
44
+ // Exactly ONE child: the surface. A chrome fallback would be a
45
+ // second child, and this is what kills the mutation.
46
+ const children = Array.isArray(root.children) ? root.children : [];
47
+ expect(children).toHaveLength(1);
48
+ });
49
+
50
+ it('renders the controls the consumer supplied, over the surface', async () => {
51
+ await render(
52
+ <PlayerProvider renderControls={() => <Text>my controls</Text>}>
53
+ <PlayerRoot />
54
+ </PlayerProvider>,
55
+ );
56
+
57
+ expect(screen.getByText('my controls')).toBeTruthy();
58
+
59
+ const tree = screen.toJSON();
60
+ expect(tree).not.toBeNull();
61
+ const root = tree as unknown as { children: unknown };
62
+ const children = Array.isArray(root.children) ? root.children : [];
63
+ expect(children).toHaveLength(2);
64
+ });
65
+
66
+ it('does not export a default control bundle', async () => {
67
+ const lib = require('../../index') as Record<string, unknown>;
68
+ expect(Object.keys(lib)).not.toContain('DefaultControls');
69
+ expect(lib.DefaultControls).toBeUndefined();
70
+ });
71
+ });
package/src/index.ts CHANGED
@@ -25,6 +25,25 @@
25
25
  * lookup for you. A consumer that drives the player itself wraps its
26
26
  * tree in `<PlayerProvider>` once and renders `<SimbaVideo>` for the
27
27
  * picture.
28
+ *
29
+ * ## v2.0.0 — the library draws no chrome
30
+ *
31
+ * `DefaultControls` and `DefaultControlsProps` are **removed**. The
32
+ * library shipped a 564-line default control bundle and wired it as
33
+ * `<PlayerRoot>`'s fallback whenever a consumer did not pass
34
+ * `renderControls` — which meant the library always had a chrome
35
+ * implementation that a consumer could end up using by accident, and
36
+ * that the library had to keep working.
37
+ *
38
+ * The contract now says what it means: **the library draws no chrome.**
39
+ * A consumer that wants controls renders them, through the
40
+ * `renderControls` slot on `<PlayerProvider>`. `<PlayerRoot>` renders
41
+ * the surface and the consumer's controls, and **nothing else** when
42
+ * `renderControls` is absent.
43
+ *
44
+ * This is a **breaking** change, hence the major version. `<PlayerRoot>`
45
+ * without `renderControls` renders no controls after 2.0.0, where it
46
+ * rendered `DefaultControls` before.
28
47
  */
29
48
 
30
49
  export {
@@ -46,11 +65,6 @@ export {
46
65
 
47
66
  export { PlayerSurface, type PlayerSurfaceProps } from './components/PlayerSurface';
48
67
 
49
- export {
50
- DefaultControls,
51
- type DefaultControlsProps,
52
- } from './components/DefaultControls';
53
-
54
68
  export {
55
69
  type AudioConfig,
56
70
  type DebugConfig,
@@ -133,7 +133,7 @@ describe('resolvePlayerConfig', () => {
133
133
  describe('DEFAULT_THEME', () => {
134
134
  it('exposes the documented dark theme', () => {
135
135
  // Lock the values so consumers can rely on them (and so the
136
- // DefaultControls visual baseline doesn't drift accidentally).
136
+ // a consumer's visual baseline doesn't drift accidentally).
137
137
  // `icon` is intentionally absent — it's an optional override in
138
138
  // PlayerTheme (see types/config.ts).
139
139
  expect(DEFAULT_THEME).toEqual({
@@ -5,7 +5,7 @@
5
5
  * tests pin the documented baseline (via `EXPECTED_DEFAULT_STATE`)
6
6
  * and verify the contract that matters for consumers:
7
7
  * - `usePlayer()` outside a provider returns the default state
8
- * (no throw — DefaultControls must be able to render anywhere)
8
+ * (no throw — a consumer's controls must be able to render anywhere)
9
9
  * - `usePlayer()` inside a provider returns the live state
10
10
  * - `usePlayer()` returns stable command references across renders
11
11
  * - `commands.<method>` delegates to the native bridge
@@ -98,7 +98,7 @@ describe('usePlayer (no provider)', () => {
98
98
 
99
99
  it('returns the documented default state', async () => {
100
100
  // Outside a <PlayerProvider>, usePlayer must NOT throw — it
101
- // returns DEFAULT_STATE so DefaultControls can render in any
101
+ // returns DEFAULT_STATE so a consumer's controls can render in any
102
102
  // environment (jest, web preview, Storybook).
103
103
  const { result } = await renderHook(() => usePlayer());
104
104
  expect(result.current.state).toEqual(DEFAULT_STATE);
@@ -107,7 +107,7 @@ describe('usePlayer (no provider)', () => {
107
107
  it('returns the expected V12 fields at their baseline', async () => {
108
108
  // Pin the V12 contract: isPlaying=false, title='Simba Player',
109
109
  // artist='', album=''. A refactor that changes the baseline
110
- // would silently break DefaultControls.
110
+ // would silently break every consumer's controls.
111
111
  const { result } = await renderHook(() => usePlayer());
112
112
  const s = result.current.state;
113
113
  expect(s.isPlaying).toBe(false);
@@ -144,7 +144,7 @@ describe('usePlayer (no provider)', () => {
144
144
 
145
145
  it('exposes the V12 commands object', async () => {
146
146
  // The five V12 methods remain on the new commands object —
147
- // DefaultControls depends on them.
147
+ // Consumer controls depend on them.
148
148
  const { result } = await renderHook(() => usePlayer());
149
149
  expect(typeof result.current.commands.play).toBe('function');
150
150
  expect(typeof result.current.commands.pause).toBe('function');
@@ -376,8 +376,8 @@ describe('usePlayer (no provider)', () => {
376
376
  });
377
377
 
378
378
  it('returns stable command references across renders', async () => {
379
- // Spec §Phase 34.5: stable command references let DefaultControls
380
- // memo its handlers. The V13 commands object is a module-scope
379
+ // Spec §Phase 34.5: stable command references let a consumer's
380
+ // controls memo their handlers. The V13 commands object is a module-scope
381
381
  // singleton, so the reference is identical for every render.
382
382
  const { result, rerender } = await renderHook(() => usePlayer());
383
383
  const firstCommands = result.current.commands;
@@ -876,7 +876,7 @@ const BUILT_COMMANDS: PlayerCommands = buildCommands();
876
876
  * driven by mpv events (via `subscribePlayerEvent`) plus a one-shot
877
877
  * hydration read at mount. Outside a provider, `state` is
878
878
  * `DEFAULT_STATE` (no throw — see Phase 24 design notes: this
879
- * hook is non-throwing so DefaultControls can render in any
879
+ * hook is non-throwing so a consumer's own controls can render in any
880
880
  * environment, including web previews and tests).
881
881
  *
882
882
  * The `commands` object is a module-singleton: the same reference
@@ -1485,7 +1485,7 @@ export function applyPlayerEvent(
1485
1485
  * `<PlayerStateProvider>` component (in `PlayerProvider.tsx`)
1486
1486
  * can import them. The component itself is a JSX component, so
1487
1487
  * it has to live in a `.tsx` file — we keep the contexts in
1488
- * this `.ts` file so non-JSX consumers (DefaultControls,
1489
- * `usePlayer`, etc.) can import them without forcing the JSX
1488
+ * this `.ts` file so non-JSX consumers (`usePlayer`, etc.) can
1489
+ * import them without forcing the JSX
1490
1490
  * transform on the whole module.
1491
1491
  */
@@ -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
- });
@@ -1,253 +0,0 @@
1
- /**
2
- * Unit tests for `src/components/DefaultControls.tsx`.
3
- *
4
- * Spec §Phase 34.7: Test DefaultControls renders correctly.
5
- *
6
- * Test surface:
7
- * - Renders inside a PlayerProvider without crashing
8
- * - Top bar shows the title (from prop) and subtitle
9
- * - Transport buttons are present (skip back, play/pause, skip forward)
10
- * - Play/pause button toggles based on state.isPlaying
11
- * - Skip buttons call the bridge
12
- * - Close button calls onPause (or commands.pause fallback)
13
- * - formatTime is correctly applied for the time labels
14
- *
15
- * What we DON'T test (deferred):
16
- * - PanResponder drag-to-seek (Phase 39 instrumented test)
17
- * - Auto-hide opacity tween (Phase 39 — needs fake timers + Animated
18
- * mock with manual frame advancement)
19
- * - Scrubber position-to-time math (covered indirectly via the
20
- * positionFromX logic in the source; pure-function tests for
21
- * that math live in Phase 39 if/when we extract it).
22
- *
23
- * The MpvPlayerModule bridge mock is installed globally in
24
- * `jest.setup.ts`.
25
- */
26
-
27
- import React from 'react';
28
- import { NativeModules } from 'react-native';
29
- import { fireEvent, render } from '@testing-library/react-native';
30
- import { PlayerProvider } from '../PlayerProvider';
31
- import { DefaultControls } from '../DefaultControls';
32
-
33
- // Helper to clear all bridge mock call counts between tests.
34
- function clearBridgeMocks() {
35
- for (const key of Object.keys(NativeModules.MpvPlayerModule)) {
36
- const fn = (NativeModules.MpvPlayerModule as Record<string, jest.Mock>)[key];
37
- if (typeof fn?.mockClear === 'function') {
38
- fn.mockClear();
39
- }
40
- }
41
- }
42
-
43
- describe('DefaultControls', () => {
44
- beforeEach(() => {
45
- clearBridgeMocks();
46
- });
47
-
48
- // ── Renders ───────────────────────────────────────────────────────────
49
-
50
- it('renders without crashing inside a PlayerProvider', async () => {
51
- const { getByLabelText } = await render(
52
- <PlayerProvider>
53
- <DefaultControls />
54
- </PlayerProvider>,
55
- );
56
- expect(getByLabelText('Simba Player controls')).toBeTruthy();
57
- });
58
-
59
- it('renders the top bar close button', async () => {
60
- const { getByLabelText } = await render(
61
- <PlayerProvider>
62
- <DefaultControls />
63
- </PlayerProvider>,
64
- );
65
- expect(getByLabelText('Close player')).toBeTruthy();
66
- });
67
-
68
- it('renders the skip-back and skip-forward transport buttons', async () => {
69
- const { getByLabelText } = await render(
70
- <PlayerProvider>
71
- <DefaultControls />
72
- </PlayerProvider>,
73
- );
74
- expect(getByLabelText('Skip back 10 seconds')).toBeTruthy();
75
- expect(getByLabelText('Skip forward 10 seconds')).toBeTruthy();
76
- });
77
-
78
- it('renders the play button in the "Play" state initially', async () => {
79
- // Phase 24 default state: isPlaying = false.
80
- const { getByLabelText } = await render(
81
- <PlayerProvider>
82
- <DefaultControls />
83
- </PlayerProvider>,
84
- );
85
- expect(getByLabelText('Play')).toBeTruthy();
86
- });
87
-
88
- it('renders the scrubber with adjustable accessibility role', async () => {
89
- const { getByLabelText } = await render(
90
- <PlayerProvider>
91
- <DefaultControls />
92
- </PlayerProvider>,
93
- );
94
- expect(getByLabelText('Seek bar')).toBeTruthy();
95
- });
96
-
97
- // ── Title / subtitle ───────────────────────────────────────────────────
98
-
99
- it('shows the title from props', async () => {
100
- const { getByText } = await render(
101
- <PlayerProvider>
102
- <DefaultControls title="My Episode" />
103
- </PlayerProvider>,
104
- );
105
- expect(getByText('My Episode')).toBeTruthy();
106
- });
107
-
108
- it('falls back to player state title when no prop is given', async () => {
109
- // DefaultControls derives `effectiveTitle = title ?? state.title`.
110
- // state.title is 'Simba Player' by default (the placeholder shown
111
- // until the first onFileLoaded event arrives; see player.ts).
112
- const { getByText } = await render(
113
- <PlayerProvider>
114
- <DefaultControls />
115
- </PlayerProvider>,
116
- );
117
- // The placeholder "Simba Player" should appear.
118
- expect(getByText('Simba Player')).toBeTruthy();
119
- });
120
-
121
- it('shows the subtitle from props', async () => {
122
- const { getByText } = await render(
123
- <PlayerProvider>
124
- <DefaultControls title="Song" subtitle="Artist • Album" />
125
- </PlayerProvider>,
126
- );
127
- expect(getByText('Artist • Album')).toBeTruthy();
128
- });
129
-
130
- // ── Transport buttons → bridge ────────────────────────────────────────
131
-
132
- it('skip-back button calls commands.skipBackward(10) on the bridge', async () => {
133
- const { getByLabelText } = await render(
134
- <PlayerProvider>
135
- <DefaultControls />
136
- </PlayerProvider>,
137
- );
138
- fireEvent.press(getByLabelText('Skip back 10 seconds'));
139
- expect(NativeModules.MpvPlayerModule.seekBackward).toHaveBeenCalledWith(10);
140
- });
141
-
142
- it('skip-forward button calls commands.skipForward(10) on the bridge', async () => {
143
- const { getByLabelText } = await render(
144
- <PlayerProvider>
145
- <DefaultControls />
146
- </PlayerProvider>,
147
- );
148
- fireEvent.press(getByLabelText('Skip forward 10 seconds'));
149
- expect(NativeModules.MpvPlayerModule.seekForward).toHaveBeenCalledWith(10);
150
- });
151
-
152
- it('play button calls commands.play on the bridge when not playing', async () => {
153
- const { getByLabelText } = await render(
154
- <PlayerProvider>
155
- <DefaultControls />
156
- </PlayerProvider>,
157
- );
158
- fireEvent.press(getByLabelText('Play'));
159
- expect(NativeModules.MpvPlayerModule.play).toHaveBeenCalledTimes(1);
160
- });
161
-
162
- it('close (✕) button calls commands.pause (the close action)', async () => {
163
- // Phase 24 design: the close button (✕) is mapped to onPause
164
- // (the consumer's hook for "the user dismissed the player"),
165
- // which falls back to commands.pause when no prop is given.
166
- const { getByLabelText } = await render(
167
- <PlayerProvider>
168
- <DefaultControls />
169
- </PlayerProvider>,
170
- );
171
- fireEvent.press(getByLabelText('Close player'));
172
- expect(NativeModules.MpvPlayerModule.pause).toHaveBeenCalled();
173
- });
174
-
175
- // ── Props override fallback commands ───────────────────────────────────
176
-
177
- it('uses onPlay prop instead of commands.play when provided', async () => {
178
- const onPlay = jest.fn();
179
- const { getByLabelText } = await render(
180
- <PlayerProvider>
181
- <DefaultControls onPlay={onPlay} />
182
- </PlayerProvider>,
183
- );
184
- fireEvent.press(getByLabelText('Play'));
185
- expect(onPlay).toHaveBeenCalledTimes(1);
186
- // The fallback bridge call should NOT fire when onPlay is given.
187
- expect(NativeModules.MpvPlayerModule.play).not.toHaveBeenCalled();
188
- });
189
-
190
- it('uses onPause prop instead of commands.pause when provided', async () => {
191
- const onPause = jest.fn();
192
- const { getByLabelText } = await render(
193
- <PlayerProvider>
194
- <DefaultControls onPause={onPause} />
195
- </PlayerProvider>,
196
- );
197
- fireEvent.press(getByLabelText('Close player'));
198
- expect(onPause).toHaveBeenCalledTimes(1);
199
- expect(NativeModules.MpvPlayerModule.pause).not.toHaveBeenCalled();
200
- });
201
-
202
- // ── formatTime helper (indirect via render) ────────────────────────────
203
-
204
- it('formats position/duration time labels as M:SS by default', async () => {
205
- // Phase 24: usePlayerProgress returns {positionMs: 0, durationMs: 0}
206
- // so both time labels render "0:00".
207
- const { getAllByText } = await render(
208
- <PlayerProvider>
209
- <DefaultControls />
210
- </PlayerProvider>,
211
- );
212
- // Two labels: one for position, one for duration.
213
- const labels = getAllByText('0:00');
214
- expect(labels.length).toBe(2);
215
- });
216
-
217
- // ── Accessibility ──────────────────────────────────────────────────────
218
-
219
- it('exposes accessibilityLabel on the root container', async () => {
220
- const { getByLabelText } = await render(
221
- <PlayerProvider>
222
- <DefaultControls />
223
- </PlayerProvider>,
224
- );
225
- expect(getByLabelText('Simba Player controls')).toBeTruthy();
226
- });
227
-
228
- it('scrubber exposes min/max/now accessibilityValue', async () => {
229
- const { getByLabelText } = await render(
230
- <PlayerProvider>
231
- <DefaultControls />
232
- </PlayerProvider>,
233
- );
234
- const scrubber = getByLabelText('Seek bar');
235
- // RNTL exposes accessibilityValue as a prop on the rendered
236
- // element. Phase 24 wires {min: 0, max: 0, now: 0} for the
237
- // 0-duration default.
238
- expect(scrubber.props.accessibilityValue).toEqual({
239
- min: 0,
240
- max: 0,
241
- now: 0,
242
- });
243
- });
244
- });
245
-
246
- // ── Pure-function: formatTime ─────────────────────────────────────────────
247
- // We don't import formatTime directly (it's not exported), but the
248
- // behaviour is fully testable via the rendered output above. The
249
- // "M:SS" format with `0:00` for zero/negative is the documented
250
- // contract.
251
- //
252
- // A more thorough test would export formatTime for unit testing
253
- // (deferred to Phase 39 if extraction is desirable).