@ttt-productions/media-viewer 0.10.6 → 0.10.8
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/dist/react/use-media-playback.d.ts +9 -0
- package/dist/react/use-media-playback.d.ts.map +1 -1
- package/dist/react/use-media-playback.js +59 -8
- package/dist/react/use-media-playback.js.map +1 -1
- package/dist/types.d.ts +4 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/package.json +3 -3
|
@@ -5,6 +5,15 @@ import type { MediaPlaybackControls, MediaPlaybackProps } from "../types.js";
|
|
|
5
5
|
* per this many milliseconds of active (non-paused) playback via `timeupdate`.
|
|
6
6
|
*/
|
|
7
7
|
export declare const PROGRESS_SAMPLE_INTERVAL_MS = 5000;
|
|
8
|
+
/**
|
|
9
|
+
* How far an element may have played from the start and still ADOPT a
|
|
10
|
+
* late-arriving `startAtSeconds`. Autoplay can begin playback before the app's
|
|
11
|
+
* async resume position resolves (firefox reliably loses that race); a couple
|
|
12
|
+
* of autoplayed seconds are not user intent, so the saved position still wins
|
|
13
|
+
* inside this window. Beyond it, a late value is ignored — the user is
|
|
14
|
+
* genuinely watching from where they are.
|
|
15
|
+
*/
|
|
16
|
+
export declare const LATE_RESUME_ADOPT_WINDOW_SEC = 3;
|
|
8
17
|
export type UseMediaPlaybackResult = {
|
|
9
18
|
/** Whether the media has ended (drives the end overlay). */
|
|
10
19
|
hasEnded: boolean;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-media-playback.d.ts","sourceRoot":"","sources":["../../src/react/use-media-playback.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAC;AAC/B,OAAO,KAAK,EAAE,qBAAqB,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAE7E;;;GAGG;AACH,eAAO,MAAM,2BAA2B,OAAO,CAAC;AAEhD,MAAM,MAAM,sBAAsB,GAAG;IACnC,4DAA4D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CAAC;AAE9C,MAAM,MAAM,sBAAsB,GAAG;IACnC,4DAA4D;IAC5D,QAAQ,EAAE,OAAO,CAAC;IAClB,sEAAsE;IACtE,QAAQ,EAAE;QACR,gBAAgB,EAAE,CAAC,CAAC,EAAE,KAAK,CAAC,cAAc,CAAC,gBAAgB,CAAC,KAAK,IAAI,CAAC;QACtE,YAAY,EAAE,CAAC,CAAC,EAAE,KAAK,CAAC,cAAc,CAAC,gBAAgB,CAAC,KAAK,IAAI,CAAC;QAClE,MAAM,EAAE,CAAC,CAAC,EAAE,KAAK,CAAC,cAAc,CAAC,gBAAgB,CAAC,KAAK,IAAI,CAAC;QAC5D,OAAO,EAAE,CAAC,CAAC,EAAE,KAAK,CAAC,cAAc,CAAC,gBAAgB,CAAC,KAAK,IAAI,CAAC;QAC7D,QAAQ,EAAE,CAAC,CAAC,EAAE,KAAK,CAAC,cAAc,CAAC,gBAAgB,CAAC,KAAK,IAAI,CAAC;QAC9D,OAAO,EAAE,CAAC,CAAC,EAAE,KAAK,CAAC,cAAc,CAAC,gBAAgB,CAAC,KAAK,IAAI,CAAC;KAC9D,CAAC;CACH,CAAC;AAEF;;;;;;;;;;;;GAYG;AACH,wBAAgB,gBAAgB,CAC9B,UAAU,EAAE,KAAK,CAAC,SAAS,CAAC,gBAAgB,GAAG,IAAI,CAAC,EACpD,KAAK,EAAE,kBAAkB,EACzB,mBAAmB,CAAC,EAAE,KAAK,CAAC,GAAG,CAAC,qBAAqB,CAAC;AACtD;;;;;;GAMG;AACH,QAAQ,CAAC,EAAE,MAAM,GAChB,sBAAsB,CAmOxB"}
|
|
@@ -5,6 +5,15 @@ import * as React from "react";
|
|
|
5
5
|
* per this many milliseconds of active (non-paused) playback via `timeupdate`.
|
|
6
6
|
*/
|
|
7
7
|
export const PROGRESS_SAMPLE_INTERVAL_MS = 5000;
|
|
8
|
+
/**
|
|
9
|
+
* How far an element may have played from the start and still ADOPT a
|
|
10
|
+
* late-arriving `startAtSeconds`. Autoplay can begin playback before the app's
|
|
11
|
+
* async resume position resolves (firefox reliably loses that race); a couple
|
|
12
|
+
* of autoplayed seconds are not user intent, so the saved position still wins
|
|
13
|
+
* inside this window. Beyond it, a late value is ignored — the user is
|
|
14
|
+
* genuinely watching from where they are.
|
|
15
|
+
*/
|
|
16
|
+
export const LATE_RESUME_ADOPT_WINDOW_SEC = 3;
|
|
8
17
|
/**
|
|
9
18
|
* Shared playback API for VideoViewer and AudioViewer. Owns the additive
|
|
10
19
|
* playback surface (onEnded, onProgressSample, startAtSeconds, endOverlay,
|
|
@@ -35,14 +44,22 @@ mediaKey) {
|
|
|
35
44
|
const onProgressSampleRef = React.useRef(onProgressSample);
|
|
36
45
|
onEndedRef.current = onEnded;
|
|
37
46
|
onProgressSampleRef.current = onProgressSample;
|
|
38
|
-
|
|
47
|
+
// The resume position implied by the CURRENT props: a positive
|
|
48
|
+
// startAtSeconds, or null when the caller supplies none. One declaration —
|
|
49
|
+
// the mount seed, the mediaKey reset, and the late-arrival effect all read it.
|
|
50
|
+
const seedFromProps = typeof startAtSeconds === "number" && startAtSeconds > 0 ? startAtSeconds : null;
|
|
39
51
|
// Last known playback position. Seeded from startAtSeconds, then updated once
|
|
40
52
|
// playback has actually started. Survives the unloadOnExit unload/remount
|
|
41
53
|
// cycle because it lives on the (still-mounted) component instance.
|
|
42
|
-
const lastPositionRef = React.useRef(
|
|
54
|
+
const lastPositionRef = React.useRef(seedFromProps);
|
|
43
55
|
// True once we have observed real playback progress — after this we resume
|
|
44
56
|
// from lastPositionRef, never re-apply the original startAtSeconds prop.
|
|
45
57
|
const hasStartedRef = React.useRef(false);
|
|
58
|
+
// True once a startAtSeconds seed has been ADOPTED (at mount or late-arrival).
|
|
59
|
+
// Owns the adopt-exactly-once rule for the late-arrival effect below — playback
|
|
60
|
+
// state is deliberately NOT that gate, because autoplay can start playback
|
|
61
|
+
// before an async resume position arrives (see LATE_RESUME_ADOPT_WINDOW_SEC).
|
|
62
|
+
const seededRef = React.useRef(seedFromProps !== null);
|
|
46
63
|
// Throttle bookkeeping for periodic samples (wall-clock, active playback only).
|
|
47
64
|
const lastSampleAtRef = React.useRef(0);
|
|
48
65
|
// Render-phase reset-on-source-change: when the media source (`mediaKey`)
|
|
@@ -54,8 +71,9 @@ mediaKey) {
|
|
|
54
71
|
const prevMediaKeyRef = React.useRef(mediaKey);
|
|
55
72
|
if (prevMediaKeyRef.current !== mediaKey) {
|
|
56
73
|
prevMediaKeyRef.current = mediaKey;
|
|
57
|
-
lastPositionRef.current =
|
|
74
|
+
lastPositionRef.current = seedFromProps;
|
|
58
75
|
hasStartedRef.current = false;
|
|
76
|
+
seededRef.current = seedFromProps !== null;
|
|
59
77
|
lastSampleAtRef.current = 0;
|
|
60
78
|
if (hasEnded)
|
|
61
79
|
setHasEnded(false);
|
|
@@ -72,15 +90,17 @@ mediaKey) {
|
|
|
72
90
|
lastPositionRef.current = el.currentTime;
|
|
73
91
|
}
|
|
74
92
|
}, []);
|
|
75
|
-
const applyInitialSeek = React.useCallback((el) => {
|
|
93
|
+
const applyInitialSeek = React.useCallback((el, adoptWindowSec = 0.01) => {
|
|
76
94
|
const target = lastPositionRef.current;
|
|
77
95
|
if (typeof target !== "number" || target <= 0)
|
|
78
96
|
return;
|
|
79
|
-
// Only seek
|
|
80
|
-
// handler idempotent (a metadata event on an already-positioned
|
|
81
|
-
// a no-op) and
|
|
97
|
+
// Only seek an element still near the start. The DEFAULT window keeps the
|
|
98
|
+
// metadata handler idempotent (a metadata event on an already-positioned
|
|
99
|
+
// element is a no-op) and re-applies the LAST KNOWN position to the new
|
|
82
100
|
// element created by an unloadOnExit remount — resuming, never restarting.
|
|
83
|
-
|
|
101
|
+
// The late-arrival effect widens the window (LATE_RESUME_ADOPT_WINDOW_SEC)
|
|
102
|
+
// because autoplay may have advanced a little before the seed arrived.
|
|
103
|
+
if (el.currentTime > adoptWindowSec)
|
|
84
104
|
return;
|
|
85
105
|
const dur = el.duration;
|
|
86
106
|
const clamped = Number.isFinite(dur) && dur > 0 ? Math.min(target, dur) : target;
|
|
@@ -91,6 +111,37 @@ mediaKey) {
|
|
|
91
111
|
/* setting currentTime before ready can throw in some engines; ignore */
|
|
92
112
|
}
|
|
93
113
|
}, []);
|
|
114
|
+
// Late-arriving resume position. `startAtSeconds` usually comes from an async
|
|
115
|
+
// app source (a user-prefs query); when that resolves AFTER this hook mounted,
|
|
116
|
+
// the mount-time seed above saw `undefined` and the element would silently
|
|
117
|
+
// start at 0. Adopt the value when it finally arrives — exactly ONCE
|
|
118
|
+
// (`seededRef`), and only while the element is within the small adoption
|
|
119
|
+
// window of the start, so a late value can never yank media the user is
|
|
120
|
+
// genuinely watching. Playback state is deliberately NOT the gate: under
|
|
121
|
+
// AUTOPLAY the element starts playing from 0 on its own, and by the time the
|
|
122
|
+
// prefs query resolves it has drifted a fraction of a second — firefox loses
|
|
123
|
+
// that race on every deep-link resume (live 2026-07-31, hosted path 14.4:
|
|
124
|
+
// expected ~224s, read 0.2s). A few autoplayed seconds are not user intent;
|
|
125
|
+
// jumping to the user's saved position IS the requested behavior. Beyond the
|
|
126
|
+
// window (a user genuinely re-watching from the top) the late value is
|
|
127
|
+
// ignored, same as before. A `mediaKey` change resets the refs in the
|
|
128
|
+
// render-phase block above, re-arming this for the new source; the seek is
|
|
129
|
+
// applied here because the element may already have fired `loadedmetadata`
|
|
130
|
+
// and will not fire it again — when metadata has not landed yet,
|
|
131
|
+
// `onLoadedMetadata` applies it.
|
|
132
|
+
React.useEffect(() => {
|
|
133
|
+
if (seedFromProps === null)
|
|
134
|
+
return;
|
|
135
|
+
if (seededRef.current)
|
|
136
|
+
return; // adopt exactly once; never override an applied seed
|
|
137
|
+
const el = elementRef.current;
|
|
138
|
+
if (el && el.currentTime > LATE_RESUME_ADOPT_WINDOW_SEC)
|
|
139
|
+
return;
|
|
140
|
+
seededRef.current = true;
|
|
141
|
+
lastPositionRef.current = seedFromProps;
|
|
142
|
+
if (el)
|
|
143
|
+
applyInitialSeek(el, LATE_RESUME_ADOPT_WINDOW_SEC);
|
|
144
|
+
}, [seedFromProps, applyInitialSeek, elementRef]);
|
|
94
145
|
const onLoadedMetadata = React.useCallback((e) => {
|
|
95
146
|
applyInitialSeek(e.currentTarget);
|
|
96
147
|
}, [applyInitialSeek]);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-media-playback.js","sourceRoot":"","sources":["../../src/react/use-media-playback.ts"],"names":[],"mappings":"AAAA,YAAY,CAAC;AAEb,OAAO,KAAK,KAAK,MAAM,OAAO,CAAC;AAG/B;;;GAGG;AACH,MAAM,CAAC,MAAM,2BAA2B,GAAG,IAAI,CAAC;AAgBhD;;;;;;;;;;;;GAYG;AACH,MAAM,UAAU,gBAAgB,CAC9B,UAAoD,EACpD,KAAyB,EACzB,mBAAsD;AACtD;;;;;;GAMG;AACH,QAAiB;IAEjB,MAAM,EAAE,OAAO,EAAE,gBAAgB,EAAE,cAAc,EAAE,UAAU,EAAE,GAAG,KAAK,CAAC;IAExE,MAAM,CAAC,QAAQ,EAAE,WAAW,CAAC,GAAG,KAAK,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;IAEtD,4EAA4E;IAC5E,oDAAoD;IACpD,MAAM,UAAU,GAAG,KAAK,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;IACzC,MAAM,mBAAmB,GAAG,KAAK,CAAC,MAAM,CAAC,gBAAgB,CAAC,CAAC;IAC3D,UAAU,CAAC,OAAO,GAAG,OAAO,CAAC;IAC7B,mBAAmB,CAAC,OAAO,GAAG,gBAAgB,CAAC;IAE/C,MAAM,YAAY,GAAG,GAAG,EAAE,CACxB,OAAO,cAAc,KAAK,QAAQ,IAAI,cAAc,GAAG,CAAC,CAAC,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC,IAAI,CAAC;IAEnF,8EAA8E;IAC9E,0EAA0E;IAC1E,oEAAoE;IACpE,MAAM,eAAe,GAAG,KAAK,CAAC,MAAM,CAAgB,YAAY,EAAE,CAAC,CAAC;IACpE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CAAC,OAAO,EAAE,CAAC,CAAC,CAAC;YAC/F,IAAI,CAAC;gBACH,EAAE,CAAC,WAAW,GAAG,OAAO,CAAC;YAC3B,CAAC;YAAC,MAAM,CAAC;gBACP,YAAY;YACd,CAAC;YACD,aAAa,CAAC,OAAO,GAAG,IAAI,CAAC;YAC7B,eAAe,CAAC,OAAO,GAAG,OAAO,CAAC;QACpC,CAAC;KACF,CAAC,EACF,CAAC,UAAU,CAAC,CACb,CAAC;IAEF,yEAAyE;IACzE,gEAAgE;IAChE,KAAK,UAAU,CAAC;IAEhB,OAAO;QACL,QAAQ;QACR,QAAQ,EAAE;YACR,gBAAgB;YAChB,YAAY;YACZ,MAAM;YACN,OAAO;YACP,QAAQ;YACR,OAAO,EAAE,cAAc;SACxB;KACF,CAAC;AACJ,CAAC","sourcesContent":["\"use client\";\n\nimport * as React from \"react\";\nimport type { MediaPlaybackControls, MediaPlaybackProps } from \"../types.js\";\n\n/**\n * Throttle interval for periodic progress samples. A sample fires at most once\n * per this many milliseconds of active (non-paused) playback via `timeupdate`.\n */\nexport const PROGRESS_SAMPLE_INTERVAL_MS = 5000;\n\nexport type UseMediaPlaybackResult = {\n /** Whether the media has ended (drives the end overlay). */\n hasEnded: boolean;\n /** Handlers to spread onto the underlying <video>/<audio> element. */\n handlers: {\n onLoadedMetadata: (e: React.SyntheticEvent<HTMLMediaElement>) => void;\n onTimeUpdate: (e: React.SyntheticEvent<HTMLMediaElement>) => void;\n onPlay: (e: React.SyntheticEvent<HTMLMediaElement>) => void;\n onPause: (e: React.SyntheticEvent<HTMLMediaElement>) => void;\n onSeeked: (e: React.SyntheticEvent<HTMLMediaElement>) => void;\n onEnded: (e: React.SyntheticEvent<HTMLMediaElement>) => void;\n };\n};\n\n/**\n * Shared playback API for VideoViewer and AudioViewer. Owns the additive\n * playback surface (onEnded, onProgressSample, startAtSeconds, endOverlay,\n * imperative controls) so both viewers behave identically. Adds NO observer —\n * everything is derived from native media element events (MEDIA-102).\n *\n * The element ref is supplied by the viewer (which already owns it for\n * autoplay/fullscreen). When the viewer unloads the element off-screen\n * (`unloadOnExit`) and remounts it on return, the last known playback position\n * is tracked in a component-scoped ref that outlives the element, so playback\n * resumes from where it left off — never from `startAtSeconds` again and never\n * from 0.\n */\nexport function useMediaPlayback(\n elementRef: React.RefObject<HTMLMediaElement | null>,\n props: MediaPlaybackProps,\n playbackControlsRef?: React.Ref<MediaPlaybackControls>,\n /**\n * Stable identity for the CURRENT media source (the viewer passes its `url`).\n * When this changes the media is a different asset, so all resume/progress/\n * ended tracking is reset — a stale position from the previous media must NOT\n * carry over onto the new element. Omit when the viewer never reuses one\n * instance across sources.\n */\n mediaKey?: string,\n): UseMediaPlaybackResult {\n const { onEnded, onProgressSample, startAtSeconds, endOverlay } = props;\n\n const [hasEnded, setHasEnded] = React.useState(false);\n\n // Latest callbacks/props via refs so handler identities stay stable and the\n // element event handlers always see current values.\n const onEndedRef = React.useRef(onEnded);\n const onProgressSampleRef = React.useRef(onProgressSample);\n onEndedRef.current = onEnded;\n onProgressSampleRef.current = onProgressSample;\n\n const seedPosition = () =>\n typeof startAtSeconds === \"number\" && startAtSeconds > 0 ? startAtSeconds : null;\n\n // Last known playback position. Seeded from startAtSeconds, then updated once\n // playback has actually started. Survives the unloadOnExit unload/remount\n // cycle because it lives on the (still-mounted) component instance.\n const lastPositionRef = React.useRef<number | null>(seedPosition());\n // True once we have observed real playback progress — after this we resume\n // from lastPositionRef, never re-apply the original startAtSeconds prop.\n const hasStartedRef = React.useRef(false);\n\n // Throttle bookkeeping for periodic samples (wall-clock, active playback only).\n const lastSampleAtRef = React.useRef(0);\n\n // Render-phase reset-on-source-change: when the media source (`mediaKey`)\n // changes, the same component/hook instance is being reused for a DIFFERENT\n // asset (e.g. a playlist swapping `url` in place). Reset every piece of\n // per-source tracking so the previous media's position/ended/throttle state\n // cannot bleed onto the new element. This is the sanctioned render-phase\n // reset-on-prop-change pattern (not a set-state-in-effect).\n const prevMediaKeyRef = React.useRef<string | undefined>(mediaKey);\n if (prevMediaKeyRef.current !== mediaKey) {\n prevMediaKeyRef.current = mediaKey;\n lastPositionRef.current = seedPosition();\n hasStartedRef.current = false;\n lastSampleAtRef.current = 0;\n if (hasEnded) setHasEnded(false);\n }\n\n const emitSample = React.useCallback((el: HTMLMediaElement) => {\n const cb = onProgressSampleRef.current;\n if (!cb) return;\n const duration = Number.isFinite(el.duration) ? el.duration : 0;\n cb(el.currentTime, duration);\n }, []);\n\n const trackPosition = React.useCallback((el: HTMLMediaElement) => {\n if (hasStartedRef.current) {\n lastPositionRef.current = el.currentTime;\n }\n }, []);\n\n const applyInitialSeek = React.useCallback((el: HTMLMediaElement) => {\n const target = lastPositionRef.current;\n if (typeof target !== \"number\" || target <= 0) return;\n // Only seek a freshly-loaded element sitting at the start. This makes the\n // handler idempotent (a metadata event on an already-positioned element is\n // a no-op) and, crucially, re-applies the LAST KNOWN position to the new\n // element created by an unloadOnExit remount — resuming, never restarting.\n if (el.currentTime > 0.01) return;\n const dur = el.duration;\n const clamped = Number.isFinite(dur) && dur > 0 ? Math.min(target, dur) : target;\n try {\n el.currentTime = clamped;\n } catch {\n /* setting currentTime before ready can throw in some engines; ignore */\n }\n }, []);\n\n const onLoadedMetadata = React.useCallback(\n (e: React.SyntheticEvent<HTMLMediaElement>) => {\n applyInitialSeek(e.currentTarget);\n },\n [applyInitialSeek],\n );\n\n const onTimeUpdate = React.useCallback(\n (e: React.SyntheticEvent<HTMLMediaElement>) => {\n const el = e.currentTarget;\n // Any observed timeupdate while playing means playback has started; from\n // now on we track live position for remount resume.\n if (!el.paused && !el.ended) {\n hasStartedRef.current = true;\n }\n trackPosition(el);\n if (el.paused) return; // no periodic samples while paused\n const now = Date.now();\n if (now - lastSampleAtRef.current >= PROGRESS_SAMPLE_INTERVAL_MS) {\n lastSampleAtRef.current = now;\n emitSample(el);\n }\n },\n [emitSample, trackPosition],\n );\n\n const onPlay = React.useCallback(() => {\n // Playing again after an ended state (native replay) clears the overlay.\n setHasEnded(false);\n }, []);\n\n const onPause = React.useCallback(\n (e: React.SyntheticEvent<HTMLMediaElement>) => {\n const el = e.currentTarget;\n trackPosition(el);\n // Flush a sample immediately on pause (final position for this segment).\n lastSampleAtRef.current = Date.now();\n emitSample(el);\n },\n [emitSample, trackPosition],\n );\n\n const onSeeked = React.useCallback(\n (e: React.SyntheticEvent<HTMLMediaElement>) => {\n const el = e.currentTarget;\n trackPosition(el);\n // Flush a sample on seek completion so the app sees the new position.\n lastSampleAtRef.current = Date.now();\n emitSample(el);\n },\n [emitSample, trackPosition],\n );\n\n const onEndedHandler = React.useCallback(\n (e: React.SyntheticEvent<HTMLMediaElement>) => {\n const el = e.currentTarget;\n // Ended means the play cursor reached duration; record final position.\n hasStartedRef.current = true;\n lastPositionRef.current = el.currentTime;\n // Flush a final sample with the ended position.\n lastSampleAtRef.current = Date.now();\n emitSample(el);\n setHasEnded(true);\n onEndedRef.current?.();\n },\n [emitSample],\n );\n\n // Imperative controls. restart() seeks to 0 and plays; seekTo(s) seeks.\n React.useImperativeHandle(\n playbackControlsRef,\n (): MediaPlaybackControls => ({\n restart() {\n const el = elementRef.current;\n if (!el) return;\n try {\n el.currentTime = 0;\n } catch {\n /* ignore */\n }\n lastPositionRef.current = 0;\n setHasEnded(false);\n void el.play().catch(() => {});\n },\n seekTo(seconds: number) {\n const el = elementRef.current;\n if (!el) return;\n const dur = el.duration;\n const clamped =\n Number.isFinite(dur) && dur > 0 ? Math.min(Math.max(seconds, 0), dur) : Math.max(seconds, 0);\n try {\n el.currentTime = clamped;\n } catch {\n /* ignore */\n }\n hasStartedRef.current = true;\n lastPositionRef.current = clamped;\n },\n }),\n [elementRef],\n );\n\n // Ended state is cleared by onPlay (native replay / imperative restart).\n // endOverlay itself is rendered by the viewer using `hasEnded`.\n void endOverlay;\n\n return {\n hasEnded,\n handlers: {\n onLoadedMetadata,\n onTimeUpdate,\n onPlay,\n onPause,\n onSeeked,\n onEnded: onEndedHandler,\n },\n };\n}\n"]}
|
|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AChE,KAAK,UAAU,CAAC;IAEhB,OAAO;QACL,QAAQ;QACR,QAAQ,EAAE;YACR,gBAAgB;YAChB,YAAY;YACZ,MAAM;YACN,OAAO;YACP,QAAQ;YACR,OAAO,EAAE,cAAc;SACxB;KACF,CAAC;AACJ,CAAC","sourcesContent":["\"use client\";\n\nimport * as React from \"react\";\nimport type { MediaPlaybackControls, MediaPlaybackProps } from \"../types.js\";\n\n/**\n * Throttle interval for periodic progress samples. A sample fires at most once\n * per this many milliseconds of active (non-paused) playback via `timeupdate`.\n */\nexport const PROGRESS_SAMPLE_INTERVAL_MS = 5000;\n\n/**\n * How far an element may have played from the start and still ADOPT a\n * late-arriving `startAtSeconds`. Autoplay can begin playback before the app's\n * async resume position resolves (firefox reliably loses that race); a couple\n * of autoplayed seconds are not user intent, so the saved position still wins\n * inside this window. Beyond it, a late value is ignored — the user is\n * genuinely watching from where they are.\n */\nexport const LATE_RESUME_ADOPT_WINDOW_SEC = 3;\n\nexport type UseMediaPlaybackResult = {\n /** Whether the media has ended (drives the end overlay). */\n hasEnded: boolean;\n /** Handlers to spread onto the underlying <video>/<audio> element. */\n handlers: {\n onLoadedMetadata: (e: React.SyntheticEvent<HTMLMediaElement>) => void;\n onTimeUpdate: (e: React.SyntheticEvent<HTMLMediaElement>) => void;\n onPlay: (e: React.SyntheticEvent<HTMLMediaElement>) => void;\n onPause: (e: React.SyntheticEvent<HTMLMediaElement>) => void;\n onSeeked: (e: React.SyntheticEvent<HTMLMediaElement>) => void;\n onEnded: (e: React.SyntheticEvent<HTMLMediaElement>) => void;\n };\n};\n\n/**\n * Shared playback API for VideoViewer and AudioViewer. Owns the additive\n * playback surface (onEnded, onProgressSample, startAtSeconds, endOverlay,\n * imperative controls) so both viewers behave identically. Adds NO observer —\n * everything is derived from native media element events (MEDIA-102).\n *\n * The element ref is supplied by the viewer (which already owns it for\n * autoplay/fullscreen). When the viewer unloads the element off-screen\n * (`unloadOnExit`) and remounts it on return, the last known playback position\n * is tracked in a component-scoped ref that outlives the element, so playback\n * resumes from where it left off — never from `startAtSeconds` again and never\n * from 0.\n */\nexport function useMediaPlayback(\n elementRef: React.RefObject<HTMLMediaElement | null>,\n props: MediaPlaybackProps,\n playbackControlsRef?: React.Ref<MediaPlaybackControls>,\n /**\n * Stable identity for the CURRENT media source (the viewer passes its `url`).\n * When this changes the media is a different asset, so all resume/progress/\n * ended tracking is reset — a stale position from the previous media must NOT\n * carry over onto the new element. Omit when the viewer never reuses one\n * instance across sources.\n */\n mediaKey?: string,\n): UseMediaPlaybackResult {\n const { onEnded, onProgressSample, startAtSeconds, endOverlay } = props;\n\n const [hasEnded, setHasEnded] = React.useState(false);\n\n // Latest callbacks/props via refs so handler identities stay stable and the\n // element event handlers always see current values.\n const onEndedRef = React.useRef(onEnded);\n const onProgressSampleRef = React.useRef(onProgressSample);\n onEndedRef.current = onEnded;\n onProgressSampleRef.current = onProgressSample;\n\n // The resume position implied by the CURRENT props: a positive\n // startAtSeconds, or null when the caller supplies none. One declaration —\n // the mount seed, the mediaKey reset, and the late-arrival effect all read it.\n const seedFromProps =\n typeof startAtSeconds === \"number\" && startAtSeconds > 0 ? startAtSeconds : null;\n\n // Last known playback position. Seeded from startAtSeconds, then updated once\n // playback has actually started. Survives the unloadOnExit unload/remount\n // cycle because it lives on the (still-mounted) component instance.\n const lastPositionRef = React.useRef<number | null>(seedFromProps);\n // True once we have observed real playback progress — after this we resume\n // from lastPositionRef, never re-apply the original startAtSeconds prop.\n const hasStartedRef = React.useRef(false);\n // True once a startAtSeconds seed has been ADOPTED (at mount or late-arrival).\n // Owns the adopt-exactly-once rule for the late-arrival effect below — playback\n // state is deliberately NOT that gate, because autoplay can start playback\n // before an async resume position arrives (see LATE_RESUME_ADOPT_WINDOW_SEC).\n const seededRef = React.useRef(seedFromProps !== null);\n\n // Throttle bookkeeping for periodic samples (wall-clock, active playback only).\n const lastSampleAtRef = React.useRef(0);\n\n // Render-phase reset-on-source-change: when the media source (`mediaKey`)\n // changes, the same component/hook instance is being reused for a DIFFERENT\n // asset (e.g. a playlist swapping `url` in place). Reset every piece of\n // per-source tracking so the previous media's position/ended/throttle state\n // cannot bleed onto the new element. This is the sanctioned render-phase\n // reset-on-prop-change pattern (not a set-state-in-effect).\n const prevMediaKeyRef = React.useRef<string | undefined>(mediaKey);\n if (prevMediaKeyRef.current !== mediaKey) {\n prevMediaKeyRef.current = mediaKey;\n lastPositionRef.current = seedFromProps;\n hasStartedRef.current = false;\n seededRef.current = seedFromProps !== null;\n lastSampleAtRef.current = 0;\n if (hasEnded) setHasEnded(false);\n }\n\n const emitSample = React.useCallback((el: HTMLMediaElement) => {\n const cb = onProgressSampleRef.current;\n if (!cb) return;\n const duration = Number.isFinite(el.duration) ? el.duration : 0;\n cb(el.currentTime, duration);\n }, []);\n\n const trackPosition = React.useCallback((el: HTMLMediaElement) => {\n if (hasStartedRef.current) {\n lastPositionRef.current = el.currentTime;\n }\n }, []);\n\n const applyInitialSeek = React.useCallback((el: HTMLMediaElement, adoptWindowSec = 0.01) => {\n const target = lastPositionRef.current;\n if (typeof target !== \"number\" || target <= 0) return;\n // Only seek an element still near the start. The DEFAULT window keeps the\n // metadata handler idempotent (a metadata event on an already-positioned\n // element is a no-op) and re-applies the LAST KNOWN position to the new\n // element created by an unloadOnExit remount — resuming, never restarting.\n // The late-arrival effect widens the window (LATE_RESUME_ADOPT_WINDOW_SEC)\n // because autoplay may have advanced a little before the seed arrived.\n if (el.currentTime > adoptWindowSec) return;\n const dur = el.duration;\n const clamped = Number.isFinite(dur) && dur > 0 ? Math.min(target, dur) : target;\n try {\n el.currentTime = clamped;\n } catch {\n /* setting currentTime before ready can throw in some engines; ignore */\n }\n }, []);\n\n // Late-arriving resume position. `startAtSeconds` usually comes from an async\n // app source (a user-prefs query); when that resolves AFTER this hook mounted,\n // the mount-time seed above saw `undefined` and the element would silently\n // start at 0. Adopt the value when it finally arrives — exactly ONCE\n // (`seededRef`), and only while the element is within the small adoption\n // window of the start, so a late value can never yank media the user is\n // genuinely watching. Playback state is deliberately NOT the gate: under\n // AUTOPLAY the element starts playing from 0 on its own, and by the time the\n // prefs query resolves it has drifted a fraction of a second — firefox loses\n // that race on every deep-link resume (live 2026-07-31, hosted path 14.4:\n // expected ~224s, read 0.2s). A few autoplayed seconds are not user intent;\n // jumping to the user's saved position IS the requested behavior. Beyond the\n // window (a user genuinely re-watching from the top) the late value is\n // ignored, same as before. A `mediaKey` change resets the refs in the\n // render-phase block above, re-arming this for the new source; the seek is\n // applied here because the element may already have fired `loadedmetadata`\n // and will not fire it again — when metadata has not landed yet,\n // `onLoadedMetadata` applies it.\n React.useEffect(() => {\n if (seedFromProps === null) return;\n if (seededRef.current) return; // adopt exactly once; never override an applied seed\n const el = elementRef.current;\n if (el && el.currentTime > LATE_RESUME_ADOPT_WINDOW_SEC) return;\n seededRef.current = true;\n lastPositionRef.current = seedFromProps;\n if (el) applyInitialSeek(el, LATE_RESUME_ADOPT_WINDOW_SEC);\n }, [seedFromProps, applyInitialSeek, elementRef]);\n\n const onLoadedMetadata = React.useCallback(\n (e: React.SyntheticEvent<HTMLMediaElement>) => {\n applyInitialSeek(e.currentTarget);\n },\n [applyInitialSeek],\n );\n\n const onTimeUpdate = React.useCallback(\n (e: React.SyntheticEvent<HTMLMediaElement>) => {\n const el = e.currentTarget;\n // Any observed timeupdate while playing means playback has started; from\n // now on we track live position for remount resume.\n if (!el.paused && !el.ended) {\n hasStartedRef.current = true;\n }\n trackPosition(el);\n if (el.paused) return; // no periodic samples while paused\n const now = Date.now();\n if (now - lastSampleAtRef.current >= PROGRESS_SAMPLE_INTERVAL_MS) {\n lastSampleAtRef.current = now;\n emitSample(el);\n }\n },\n [emitSample, trackPosition],\n );\n\n const onPlay = React.useCallback(() => {\n // Playing again after an ended state (native replay) clears the overlay.\n setHasEnded(false);\n }, []);\n\n const onPause = React.useCallback(\n (e: React.SyntheticEvent<HTMLMediaElement>) => {\n const el = e.currentTarget;\n trackPosition(el);\n // Flush a sample immediately on pause (final position for this segment).\n lastSampleAtRef.current = Date.now();\n emitSample(el);\n },\n [emitSample, trackPosition],\n );\n\n const onSeeked = React.useCallback(\n (e: React.SyntheticEvent<HTMLMediaElement>) => {\n const el = e.currentTarget;\n trackPosition(el);\n // Flush a sample on seek completion so the app sees the new position.\n lastSampleAtRef.current = Date.now();\n emitSample(el);\n },\n [emitSample, trackPosition],\n );\n\n const onEndedHandler = React.useCallback(\n (e: React.SyntheticEvent<HTMLMediaElement>) => {\n const el = e.currentTarget;\n // Ended means the play cursor reached duration; record final position.\n hasStartedRef.current = true;\n lastPositionRef.current = el.currentTime;\n // Flush a final sample with the ended position.\n lastSampleAtRef.current = Date.now();\n emitSample(el);\n setHasEnded(true);\n onEndedRef.current?.();\n },\n [emitSample],\n );\n\n // Imperative controls. restart() seeks to 0 and plays; seekTo(s) seeks.\n React.useImperativeHandle(\n playbackControlsRef,\n (): MediaPlaybackControls => ({\n restart() {\n const el = elementRef.current;\n if (!el) return;\n try {\n el.currentTime = 0;\n } catch {\n /* ignore */\n }\n lastPositionRef.current = 0;\n setHasEnded(false);\n void el.play().catch(() => {});\n },\n seekTo(seconds: number) {\n const el = elementRef.current;\n if (!el) return;\n const dur = el.duration;\n const clamped =\n Number.isFinite(dur) && dur > 0 ? Math.min(Math.max(seconds, 0), dur) : Math.max(seconds, 0);\n try {\n el.currentTime = clamped;\n } catch {\n /* ignore */\n }\n hasStartedRef.current = true;\n lastPositionRef.current = clamped;\n },\n }),\n [elementRef],\n );\n\n // Ended state is cleared by onPlay (native replay / imperative restart).\n // endOverlay itself is rendered by the viewer using `hasEnded`.\n void endOverlay;\n\n return {\n hasEnded,\n handlers: {\n onLoadedMetadata,\n onTimeUpdate,\n onPlay,\n onPause,\n onSeeked,\n onEnded: onEndedHandler,\n },\n };\n}\n"]}
|
package/dist/types.d.ts
CHANGED
|
@@ -40,6 +40,10 @@ export type MediaPlaybackProps = {
|
|
|
40
40
|
onProgressSample?: (currentTimeSeconds: number, durationSeconds: number) => void;
|
|
41
41
|
/**
|
|
42
42
|
* Initial playback position (seconds), applied once the element has metadata.
|
|
43
|
+
* May arrive late (e.g. from an async prefs read that resolves after the
|
|
44
|
+
* viewer mounted): a value that appears while playback has not yet begun is
|
|
45
|
+
* adopted and applied to the already-loaded element. Once real playback has
|
|
46
|
+
* begun a later value is ignored — it never yanks playing media.
|
|
43
47
|
* Survives the `unloadOnExit` unload/remount cycle: once playback has started
|
|
44
48
|
* the viewer tracks the live position internally and resumes from the LAST
|
|
45
49
|
* KNOWN position on remount — it does not re-apply this prop and does not
|
package/dist/types.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,KAAK,MAAM,OAAO,CAAC;AACpC,OAAO,KAAK,EAAE,sBAAsB,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAC7E,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AAE3D,YAAY,EAAE,sBAAsB,EAAE,eAAe,EAAE,eAAe,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AAC7G,YAAY,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AAE3D,MAAM,MAAM,eAAe,GAAG,OAAO,GAAG,OAAO,GAAG,OAAO,GAAG,OAAO,CAAC;AACpE,MAAM,MAAM,YAAY,GAAG,MAAM,GAAG,MAAM,CAAC;AAE3C;;;;GAIG;AACH,MAAM,MAAM,qBAAqB,GAAG;IAClC,iEAAiE;IACjE,OAAO,IAAI,IAAI,CAAC;IAChB,sEAAsE;IACtE,MAAM,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;CAC/B,CAAC;AAEF;;;;GAIG;AACH,MAAM,MAAM,kBAAkB,GAAG;IAC/B;;;;OAIG;IACH,OAAO,CAAC,EAAE,MAAM,IAAI,CAAC;IAErB;;;;;;;;OAQG;IACH,gBAAgB,CAAC,EA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,gBAAgB,CAAC,EAAE,kBAAkB,CAAC,kBAAkB,CAAC,CAAC;IAC1D,cAAc,CAAC,EAAE,kBAAkB,CAAC,gBAAgB,CAAC,CAAC;IACtD,UAAU,CAAC,EAAE,kBAAkB,CAAC,YAAY,CAAC,CAAC;IAC9C,mBAAmB,CAAC,EAAE,kBAAkB,CAAC,qBAAqB,CAAC,CAAC;IAIhE,mBAAmB,CAAC,EAAE,mBAAmB,CAAC;IAC1C,eAAe,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAChC,iBAAiB,CAAC,EAAE,KAAK,CAAC,SAAS,CAAC;IAEpC,YAAY,CAAC,EAAE,YAAY,CAAC;IAC5B,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,IAAI,CAAC,EAAE,MAAM,CAAC;IAKd;;;;OAIG;IACH,eAAe,CAAC,EAAE,sBAAsB,CAAC;IAEzC;;;;OAIG;IACH,eAAe,CAAC,EAAE,eAAe,CAAC;IAElC,oFAAoF;IACpF,aAAa,CAAC,EAAE,MAAM,CAAC;CACxB,CAAC;AAEF,wBAAwB;AACxB,MAAM,MAAM,gBAAgB,GAAG,iBAAiB,CAAC"}
|
package/dist/types.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"","sourcesContent":["import type * as React from \"react\";\nimport type { MediaDiagnosticAdapter, AssetStatusHint } from \"./recovery.js\";\nimport type { AudioVisualizerMode } from \"./visualizer.js\";\n\nexport type { MediaDiagnosticAdapter, AssetStatusHint, DiagnosisResult, RecoveryState } from \"./recovery.js\";\nexport type { AudioVisualizerMode } from \"./visualizer.js\";\n\nexport type MediaViewerType = \"image\" | \"video\" | \"audio\" | \"other\";\nexport type FallbackMode = \"none\" | \"link\";\n\n/**\n * Imperative playback controls, exposed via the `playbackControlsRef` prop on\n * `VideoViewer` / `AudioViewer` (and forwarded by `MediaPreview` for\n * video/audio). Obtain via `React.useRef<MediaPlaybackControls>(null)`.\n */\nexport type MediaPlaybackControls = {\n /** Seek to 0 and play from the start. Clears any end-overlay. */\n restart(): void;\n /** Seek to the given position (seconds), clamped to [0, duration]. */\n seekTo(seconds: number): void;\n};\n\n/**\n * Additive, fully optional playback API shared by `VideoViewer` and\n * `AudioViewer`. Every field is optional; when all are absent the viewers\n * behave exactly as before.\n */\nexport type MediaPlaybackProps = {\n /**\n * Fires when the media element ends (native `ended` event) with the play\n * cursor at duration. NOTE: when `loop` is set the browser restarts natively\n * and emits no `ended` event, so `onEnded` never fires in that mode.\n */\n onEnded?: () => void;\n\n /**\n * Periodic playback-position reporting. Contract:\n * - While playing, fires at most once every ~5 seconds of playback\n * (throttled off `timeupdate`).\n * - Fires once immediately on pause, on seek completion (`seeked`), and on\n * ended — each carrying the exact position at that moment.\n * - Never fires while paused (aside from the single pause-flush above).\n * `durationSeconds` is `0` until the element's duration is known.\n */\n onProgressSample?: (currentTimeSeconds: number, durationSeconds: number) => void;\n\n /**\n * Initial playback position (seconds), applied once the element has metadata.\n * Survives the `unloadOnExit` unload/remount cycle: once playback has started\n * the viewer tracks the live position internally and resumes from the LAST\n * KNOWN position on remount — it does not re-apply this prop and does not\n * restart at 0.\n */\n startAtSeconds?: number;\n\n /**\n * Rendered as an overlay covering the media area when the media has ended.\n * Removed when playback restarts (native replay or imperative `restart()`).\n * The overlay only intercepts pointer events while shown and renders above\n * the element. In a native-fullscreen exit state the overlay reappears over\n * the inline element (it is part of normal document flow, not the fullscreen\n * layer).\n */\n endOverlay?: React.ReactNode;\n\n /** Imperative controls handle — see {@link MediaPlaybackControls}. */\n playbackControlsRef?: React.Ref<MediaPlaybackControls>;\n};\n\nexport type BaseMediaProps = {\n url: string;\n className?: string;\n mediaClassName?: string;\n lazy?: boolean;\n priority?: boolean;\n skeleton?: boolean;\n onLoad?: () => void;\n onError?: () => void;\n fallback?: React.ReactNode;\n /**\n * Load-watchdog budget in ms (default LOAD_WATCHDOG_MS). A visible, loading\n * element that produces neither a load/metadata nor an error event within\n * this budget synthesizes an error so the asset resolves to a bounded\n * terminal state instead of an eternal skeleton. `0` disables.\n */\n loadTimeoutMs?: number;\n};\n\nexport type ImageViewerProps = BaseMediaProps & {\n alt?: string;\n enableZoom?: boolean;\n unloadOnExit?: boolean;\n isCircular?: boolean;\n preventGestures?: boolean;\n};\n\nexport type VideoViewerProps = BaseMediaProps & MediaPlaybackProps & {\n controls?: boolean;\n autoPlay?: boolean;\n muted?: boolean;\n loop?: boolean;\n posterUrl?: string;\n enableFullscreen?: boolean;\n unloadOnExit?: boolean;\n preload?: \"auto\" | \"metadata\" | \"none\";\n autoPlayOnVisible?: boolean;\n};\n\nexport type AudioViewerProps = BaseMediaProps & MediaPlaybackProps & {\n autoPlay?: boolean;\n loop?: boolean;\n preload?: \"auto\" | \"metadata\" | \"none\";\n onLoadChange?: (isLoading: boolean) => void;\n\n // AudioViewer always uses the package-owned control surface. Native browser\n // audio controls are intentionally not part of the public contract.\n /** Initial visualizer mode (\"line\" oscilloscope | \"bars\" EQ). A persisted user choice wins. */\n visualizerMode?: AudioVisualizerMode;\n /** localStorage key base for the minimize/mode prefs. `null` disables persistence. */\n persistKey?: string | null;\n /** App-injected action buttons rendered at the end of the player control row. */\n extraActions?: React.ReactNode;\n};\n\nexport type MediaPreviewProps = {\n url?: string | File | Blob | null;\n alt?: string;\n type?: MediaViewerType | string;\n className?: string;\n unloadOnExit?: boolean;\n isCircular?: boolean;\n priority?: boolean;\n skeleton?: boolean;\n lazy?: boolean;\n /** Video controls only. Audio always renders the canonical package-owned controls. */\n controls?: boolean;\n autoPlay?: boolean;\n muted?: boolean;\n loop?: boolean;\n posterUrl?: string;\n preload?: \"auto\" | \"metadata\" | \"none\";\n autoPlayOnVisible?: boolean;\n onLoad?: () => void;\n onError?: () => void;\n onLoadChange?: (isLoading: boolean) => void;\n\n // -------------------------------------------------------------------------\n // Playback API (additive, optional) — forwarded to the video/audio viewer.\n // Ignored for image/other types. See MediaPlaybackProps for the contract.\n // -------------------------------------------------------------------------\n onEnded?: MediaPlaybackProps[\"onEnded\"];\n onProgressSample?: MediaPlaybackProps[\"onProgressSample\"];\n startAtSeconds?: MediaPlaybackProps[\"startAtSeconds\"];\n endOverlay?: MediaPlaybackProps[\"endOverlay\"];\n playbackControlsRef?: MediaPlaybackProps[\"playbackControlsRef\"];\n\n // Audio always uses the package-owned player. These props customize that\n // single control surface and are ignored for every other media type.\n audioVisualizerMode?: AudioVisualizerMode;\n audioPersistKey?: string | null;\n audioExtraActions?: React.ReactNode;\n\n fallbackMode?: FallbackMode;\n fallbackLabel?: string;\n filename?: string;\n mime?: string;\n name?: string;\n\n // -------------------------------------------------------------------------\n // Recovery adapter (additive, optional — backward-compatible)\n // -------------------------------------------------------------------------\n /**\n * Injected diagnostic adapter. When provided, element load errors for\n * assets the app believes are live will trigger the bounded recovery state\n * machine. When omitted, the existing error fallback behavior is unchanged.\n */\n recoveryAdapter?: MediaDiagnosticAdapter;\n\n /**\n * Optional app hint about the server-side lifecycle state of the asset.\n * Drives which recovery phase is shown (e.g. processing → skeleton,\n * finalizing → spinner, failed/rejected → hard error immediately).\n */\n assetStatusHint?: AssetStatusHint;\n\n /** Load-watchdog budget forwarded to the underlying viewer — see BaseMediaProps. */\n loadTimeoutMs?: number;\n};\n\n/** Back-compat alias */\nexport type MediaViewerProps = MediaPreviewProps;\n"]}
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"","sourcesContent":["import type * as React from \"react\";\nimport type { MediaDiagnosticAdapter, AssetStatusHint } from \"./recovery.js\";\nimport type { AudioVisualizerMode } from \"./visualizer.js\";\n\nexport type { MediaDiagnosticAdapter, AssetStatusHint, DiagnosisResult, RecoveryState } from \"./recovery.js\";\nexport type { AudioVisualizerMode } from \"./visualizer.js\";\n\nexport type MediaViewerType = \"image\" | \"video\" | \"audio\" | \"other\";\nexport type FallbackMode = \"none\" | \"link\";\n\n/**\n * Imperative playback controls, exposed via the `playbackControlsRef` prop on\n * `VideoViewer` / `AudioViewer` (and forwarded by `MediaPreview` for\n * video/audio). Obtain via `React.useRef<MediaPlaybackControls>(null)`.\n */\nexport type MediaPlaybackControls = {\n /** Seek to 0 and play from the start. Clears any end-overlay. */\n restart(): void;\n /** Seek to the given position (seconds), clamped to [0, duration]. */\n seekTo(seconds: number): void;\n};\n\n/**\n * Additive, fully optional playback API shared by `VideoViewer` and\n * `AudioViewer`. Every field is optional; when all are absent the viewers\n * behave exactly as before.\n */\nexport type MediaPlaybackProps = {\n /**\n * Fires when the media element ends (native `ended` event) with the play\n * cursor at duration. NOTE: when `loop` is set the browser restarts natively\n * and emits no `ended` event, so `onEnded` never fires in that mode.\n */\n onEnded?: () => void;\n\n /**\n * Periodic playback-position reporting. Contract:\n * - While playing, fires at most once every ~5 seconds of playback\n * (throttled off `timeupdate`).\n * - Fires once immediately on pause, on seek completion (`seeked`), and on\n * ended — each carrying the exact position at that moment.\n * - Never fires while paused (aside from the single pause-flush above).\n * `durationSeconds` is `0` until the element's duration is known.\n */\n onProgressSample?: (currentTimeSeconds: number, durationSeconds: number) => void;\n\n /**\n * Initial playback position (seconds), applied once the element has metadata.\n * May arrive late (e.g. from an async prefs read that resolves after the\n * viewer mounted): a value that appears while playback has not yet begun is\n * adopted and applied to the already-loaded element. Once real playback has\n * begun a later value is ignored — it never yanks playing media.\n * Survives the `unloadOnExit` unload/remount cycle: once playback has started\n * the viewer tracks the live position internally and resumes from the LAST\n * KNOWN position on remount — it does not re-apply this prop and does not\n * restart at 0.\n */\n startAtSeconds?: number;\n\n /**\n * Rendered as an overlay covering the media area when the media has ended.\n * Removed when playback restarts (native replay or imperative `restart()`).\n * The overlay only intercepts pointer events while shown and renders above\n * the element. In a native-fullscreen exit state the overlay reappears over\n * the inline element (it is part of normal document flow, not the fullscreen\n * layer).\n */\n endOverlay?: React.ReactNode;\n\n /** Imperative controls handle — see {@link MediaPlaybackControls}. */\n playbackControlsRef?: React.Ref<MediaPlaybackControls>;\n};\n\nexport type BaseMediaProps = {\n url: string;\n className?: string;\n mediaClassName?: string;\n lazy?: boolean;\n priority?: boolean;\n skeleton?: boolean;\n onLoad?: () => void;\n onError?: () => void;\n fallback?: React.ReactNode;\n /**\n * Load-watchdog budget in ms (default LOAD_WATCHDOG_MS). A visible, loading\n * element that produces neither a load/metadata nor an error event within\n * this budget synthesizes an error so the asset resolves to a bounded\n * terminal state instead of an eternal skeleton. `0` disables.\n */\n loadTimeoutMs?: number;\n};\n\nexport type ImageViewerProps = BaseMediaProps & {\n alt?: string;\n enableZoom?: boolean;\n unloadOnExit?: boolean;\n isCircular?: boolean;\n preventGestures?: boolean;\n};\n\nexport type VideoViewerProps = BaseMediaProps & MediaPlaybackProps & {\n controls?: boolean;\n autoPlay?: boolean;\n muted?: boolean;\n loop?: boolean;\n posterUrl?: string;\n enableFullscreen?: boolean;\n unloadOnExit?: boolean;\n preload?: \"auto\" | \"metadata\" | \"none\";\n autoPlayOnVisible?: boolean;\n};\n\nexport type AudioViewerProps = BaseMediaProps & MediaPlaybackProps & {\n autoPlay?: boolean;\n loop?: boolean;\n preload?: \"auto\" | \"metadata\" | \"none\";\n onLoadChange?: (isLoading: boolean) => void;\n\n // AudioViewer always uses the package-owned control surface. Native browser\n // audio controls are intentionally not part of the public contract.\n /** Initial visualizer mode (\"line\" oscilloscope | \"bars\" EQ). A persisted user choice wins. */\n visualizerMode?: AudioVisualizerMode;\n /** localStorage key base for the minimize/mode prefs. `null` disables persistence. */\n persistKey?: string | null;\n /** App-injected action buttons rendered at the end of the player control row. */\n extraActions?: React.ReactNode;\n};\n\nexport type MediaPreviewProps = {\n url?: string | File | Blob | null;\n alt?: string;\n type?: MediaViewerType | string;\n className?: string;\n unloadOnExit?: boolean;\n isCircular?: boolean;\n priority?: boolean;\n skeleton?: boolean;\n lazy?: boolean;\n /** Video controls only. Audio always renders the canonical package-owned controls. */\n controls?: boolean;\n autoPlay?: boolean;\n muted?: boolean;\n loop?: boolean;\n posterUrl?: string;\n preload?: \"auto\" | \"metadata\" | \"none\";\n autoPlayOnVisible?: boolean;\n onLoad?: () => void;\n onError?: () => void;\n onLoadChange?: (isLoading: boolean) => void;\n\n // -------------------------------------------------------------------------\n // Playback API (additive, optional) — forwarded to the video/audio viewer.\n // Ignored for image/other types. See MediaPlaybackProps for the contract.\n // -------------------------------------------------------------------------\n onEnded?: MediaPlaybackProps[\"onEnded\"];\n onProgressSample?: MediaPlaybackProps[\"onProgressSample\"];\n startAtSeconds?: MediaPlaybackProps[\"startAtSeconds\"];\n endOverlay?: MediaPlaybackProps[\"endOverlay\"];\n playbackControlsRef?: MediaPlaybackProps[\"playbackControlsRef\"];\n\n // Audio always uses the package-owned player. These props customize that\n // single control surface and are ignored for every other media type.\n audioVisualizerMode?: AudioVisualizerMode;\n audioPersistKey?: string | null;\n audioExtraActions?: React.ReactNode;\n\n fallbackMode?: FallbackMode;\n fallbackLabel?: string;\n filename?: string;\n mime?: string;\n name?: string;\n\n // -------------------------------------------------------------------------\n // Recovery adapter (additive, optional — backward-compatible)\n // -------------------------------------------------------------------------\n /**\n * Injected diagnostic adapter. When provided, element load errors for\n * assets the app believes are live will trigger the bounded recovery state\n * machine. When omitted, the existing error fallback behavior is unchanged.\n */\n recoveryAdapter?: MediaDiagnosticAdapter;\n\n /**\n * Optional app hint about the server-side lifecycle state of the asset.\n * Drives which recovery phase is shown (e.g. processing → skeleton,\n * finalizing → spinner, failed/rejected → hard error immediately).\n */\n assetStatusHint?: AssetStatusHint;\n\n /** Load-watchdog budget forwarded to the underlying viewer — see BaseMediaProps. */\n loadTimeoutMs?: number;\n};\n\n/** Back-compat alias */\nexport type MediaViewerProps = MediaPreviewProps;\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ttt-productions/media-viewer",
|
|
3
|
-
"version": "0.10.
|
|
3
|
+
"version": "0.10.8",
|
|
4
4
|
"repository": {
|
|
5
5
|
"type": "git",
|
|
6
6
|
"url": "git+https://github.com/ttt-productions/ttt-packages.git",
|
|
@@ -33,8 +33,8 @@
|
|
|
33
33
|
"prepublishOnly": "npm run clean && npm run build"
|
|
34
34
|
},
|
|
35
35
|
"dependencies": {
|
|
36
|
-
"@ttt-productions/media-schemas": "^0.14.
|
|
37
|
-
"@ttt-productions/ui-core": "^0.11.
|
|
36
|
+
"@ttt-productions/media-schemas": "^0.14.4",
|
|
37
|
+
"@ttt-productions/ui-core": "^0.11.12"
|
|
38
38
|
},
|
|
39
39
|
"peerDependencies": {
|
|
40
40
|
"react": ">=19.0.0",
|