@ttt-productions/media-viewer 0.10.7 → 0.10.9

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/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export type { AudioVisualizerMode, MediaViewerType, FallbackMode, BaseMediaProps, ImageViewerProps, VideoViewerProps, AudioViewerProps, MediaPreviewProps, MediaViewerProps, MediaPlaybackProps, MediaPlaybackControls, MediaDiagnosticAdapter, AssetStatusHint, DiagnosisResult, RecoveryState, } from "./types.js";
1
+ export type { AudioVisualizerMode, MediaViewerType, FallbackMode, BaseMediaProps, ImageViewerProps, VideoViewerProps, AudioViewerProps, MediaPreviewProps, MediaViewerProps, MediaPlaybackProps, MediaPlaybackControls, MediaProgressSampleReason, MediaDiagnosticAdapter, AssetStatusHint, DiagnosisResult, RecoveryState, } from "./types.js";
2
2
  export { BACKOFF_SCHEDULE_MS, MAX_RECOVERY_DURATION_MS, LOAD_WATCHDOG_MS, PHASE_MAX_WAIT_MS, applyJitter, backoffForAttempt, withinBudget, } from "./recovery.js";
3
3
  export { startWaveformLoop, drawIdleFrame } from "./visualizer.js";
4
4
  export type { StartWaveformLoopOptions } from "./visualizer.js";
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EACV,mBAAmB,EACnB,eAAe,EACf,YAAY,EACZ,cAAc,EACd,gBAAgB,EAChB,gBAAgB,EAChB,gBAAgB,EAChB,iBAAiB,EACjB,gBAAgB,EAChB,kBAAkB,EAClB,qBAAqB,EACrB,sBAAsB,EACtB,eAAe,EACf,eAAe,EACf,aAAa,GACd,MAAM,YAAY,CAAC;AAEpB,OAAO,EACL,mBAAmB,EACnB,wBAAwB,EACxB,gBAAgB,EAChB,iBAAiB,EACjB,WAAW,EACX,iBAAiB,EACjB,YAAY,GACb,MAAM,eAAe,CAAC;AAEvB,OAAO,EAAE,iBAAiB,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AACnE,YAAY,EAAE,wBAAwB,EAAE,MAAM,iBAAiB,CAAC;AAEhE,OAAO,EAAE,uBAAuB,EAAE,MAAM,qBAAqB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EACV,mBAAmB,EACnB,eAAe,EACf,YAAY,EACZ,cAAc,EACd,gBAAgB,EAChB,gBAAgB,EAChB,gBAAgB,EAChB,iBAAiB,EACjB,gBAAgB,EAChB,kBAAkB,EAClB,qBAAqB,EACrB,yBAAyB,EACzB,sBAAsB,EACtB,eAAe,EACf,eAAe,EACf,aAAa,GACd,MAAM,YAAY,CAAC;AAEpB,OAAO,EACL,mBAAmB,EACnB,wBAAwB,EACxB,gBAAgB,EAChB,iBAAiB,EACjB,WAAW,EACX,iBAAiB,EACjB,YAAY,GACb,MAAM,eAAe,CAAC;AAEvB,OAAO,EAAE,iBAAiB,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AACnE,YAAY,EAAE,wBAAwB,EAAE,MAAM,iBAAiB,CAAC;AAEhE,OAAO,EAAE,uBAAuB,EAAE,MAAM,qBAAqB,CAAC"}
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAkBA,OAAO,EACL,mBAAmB,EACnB,wBAAwB,EACxB,gBAAgB,EAChB,iBAAiB,EACjB,WAAW,EACX,iBAAiB,EACjB,YAAY,GACb,MAAM,eAAe,CAAC;AAEvB,OAAO,EAAE,iBAAiB,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAGnE,OAAO,EAAE,uBAAuB,EAAE,MAAM,qBAAqB,CAAC","sourcesContent":["export type {\n AudioVisualizerMode,\n MediaViewerType,\n FallbackMode,\n BaseMediaProps,\n ImageViewerProps,\n VideoViewerProps,\n AudioViewerProps,\n MediaPreviewProps,\n MediaViewerProps,\n MediaPlaybackProps,\n MediaPlaybackControls,\n MediaDiagnosticAdapter,\n AssetStatusHint,\n DiagnosisResult,\n RecoveryState,\n} from \"./types.js\";\n\nexport {\n BACKOFF_SCHEDULE_MS,\n MAX_RECOVERY_DURATION_MS,\n LOAD_WATCHDOG_MS,\n PHASE_MAX_WAIT_MS,\n applyJitter,\n backoffForAttempt,\n withinBudget,\n} from \"./recovery.js\";\n\nexport { startWaveformLoop, drawIdleFrame } from \"./visualizer.js\";\nexport type { StartWaveformLoopOptions } from \"./visualizer.js\";\n\nexport { resolveInfiniteDuration } from \"./media-duration.js\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAmBA,OAAO,EACL,mBAAmB,EACnB,wBAAwB,EACxB,gBAAgB,EAChB,iBAAiB,EACjB,WAAW,EACX,iBAAiB,EACjB,YAAY,GACb,MAAM,eAAe,CAAC;AAEvB,OAAO,EAAE,iBAAiB,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAGnE,OAAO,EAAE,uBAAuB,EAAE,MAAM,qBAAqB,CAAC","sourcesContent":["export type {\n AudioVisualizerMode,\n MediaViewerType,\n FallbackMode,\n BaseMediaProps,\n ImageViewerProps,\n VideoViewerProps,\n AudioViewerProps,\n MediaPreviewProps,\n MediaViewerProps,\n MediaPlaybackProps,\n MediaPlaybackControls,\n MediaProgressSampleReason,\n MediaDiagnosticAdapter,\n AssetStatusHint,\n DiagnosisResult,\n RecoveryState,\n} from \"./types.js\";\n\nexport {\n BACKOFF_SCHEDULE_MS,\n MAX_RECOVERY_DURATION_MS,\n LOAD_WATCHDOG_MS,\n PHASE_MAX_WAIT_MS,\n applyJitter,\n backoffForAttempt,\n withinBudget,\n} from \"./recovery.js\";\n\nexport { startWaveformLoop, drawIdleFrame } from \"./visualizer.js\";\nexport type { StartWaveformLoopOptions } from \"./visualizer.js\";\n\nexport { resolveInfiniteDuration } from \"./media-duration.js\";\n"]}
@@ -7,6 +7,6 @@ export type { AudioPlayerProps } from "./audio-player.js";
7
7
  export { MediaFallbackLink, shouldShowFallback, EmptyFallback, ErrorFallback } from "./fallback.js";
8
8
  export { useMediaRecovery } from "./use-media-recovery.js";
9
9
  export type { UseMediaRecoveryOptions, UseMediaRecoveryResult } from "./use-media-recovery.js";
10
- export { useMediaPlayback, PROGRESS_SAMPLE_INTERVAL_MS } from "./use-media-playback.js";
10
+ export { useMediaPlayback, PROGRESS_SAMPLE_INTERVAL_MS, LATE_RESUME_ADOPT_WINDOW_SEC, } from "./use-media-playback.js";
11
11
  export type { UseMediaPlaybackResult } from "./use-media-playback.js";
12
12
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/react/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAC9D,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,YAAY,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AAC1D,OAAO,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AACpG,OAAO,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAC3D,YAAY,EAAE,uBAAuB,EAAE,sBAAsB,EAAE,MAAM,yBAAyB,CAAC;AAC/F,OAAO,EAAE,gBAAgB,EAAE,2BAA2B,EAAE,MAAM,yBAAyB,CAAC;AACxF,YAAY,EAAE,sBAAsB,EAAE,MAAM,yBAAyB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/react/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAC9D,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,YAAY,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AAC1D,OAAO,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AACpG,OAAO,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAC3D,YAAY,EAAE,uBAAuB,EAAE,sBAAsB,EAAE,MAAM,yBAAyB,CAAC;AAC/F,OAAO,EACL,gBAAgB,EAChB,2BAA2B,EAC3B,4BAA4B,GAC7B,MAAM,yBAAyB,CAAC;AACjC,YAAY,EAAE,sBAAsB,EAAE,MAAM,yBAAyB,CAAC"}
@@ -6,5 +6,5 @@ export { AudioViewer } from "./audio-viewer.js";
6
6
  export { AudioPlayer } from "./audio-player.js";
7
7
  export { MediaFallbackLink, shouldShowFallback, EmptyFallback, ErrorFallback } from "./fallback.js";
8
8
  export { useMediaRecovery } from "./use-media-recovery.js";
9
- export { useMediaPlayback, PROGRESS_SAMPLE_INTERVAL_MS } from "./use-media-playback.js";
9
+ export { useMediaPlayback, PROGRESS_SAMPLE_INTERVAL_MS, LATE_RESUME_ADOPT_WINDOW_SEC, } from "./use-media-playback.js";
10
10
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/react/index.ts"],"names":[],"mappings":"AAAA,YAAY,CAAC;AAEb,OAAO,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAC9D,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAEhD,OAAO,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AACpG,OAAO,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAE3D,OAAO,EAAE,gBAAgB,EAAE,2BAA2B,EAAE,MAAM,yBAAyB,CAAC","sourcesContent":["\"use client\";\n\nexport { MediaViewer, MediaPreview } from \"./media-viewer.js\";\nexport { ImageViewer } from \"./image-viewer.js\";\nexport { VideoViewer } from \"./video-viewer.js\";\nexport { AudioViewer } from \"./audio-viewer.js\";\nexport { AudioPlayer } from \"./audio-player.js\";\nexport type { AudioPlayerProps } from \"./audio-player.js\";\nexport { MediaFallbackLink, shouldShowFallback, EmptyFallback, ErrorFallback } from \"./fallback.js\";\nexport { useMediaRecovery } from \"./use-media-recovery.js\";\nexport type { UseMediaRecoveryOptions, UseMediaRecoveryResult } from \"./use-media-recovery.js\";\nexport { useMediaPlayback, PROGRESS_SAMPLE_INTERVAL_MS } from \"./use-media-playback.js\";\nexport type { UseMediaPlaybackResult } from \"./use-media-playback.js\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/react/index.ts"],"names":[],"mappings":"AAAA,YAAY,CAAC;AAEb,OAAO,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAC9D,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAEhD,OAAO,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AACpG,OAAO,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAE3D,OAAO,EACL,gBAAgB,EAChB,2BAA2B,EAC3B,4BAA4B,GAC7B,MAAM,yBAAyB,CAAC","sourcesContent":["\"use client\";\n\nexport { MediaViewer, MediaPreview } from \"./media-viewer.js\";\nexport { ImageViewer } from \"./image-viewer.js\";\nexport { VideoViewer } from \"./video-viewer.js\";\nexport { AudioViewer } from \"./audio-viewer.js\";\nexport { AudioPlayer } from \"./audio-player.js\";\nexport type { AudioPlayerProps } from \"./audio-player.js\";\nexport { MediaFallbackLink, shouldShowFallback, EmptyFallback, ErrorFallback } from \"./fallback.js\";\nexport { useMediaRecovery } from \"./use-media-recovery.js\";\nexport type { UseMediaRecoveryOptions, UseMediaRecoveryResult } from \"./use-media-recovery.js\";\nexport {\n useMediaPlayback,\n PROGRESS_SAMPLE_INTERVAL_MS,\n LATE_RESUME_ADOPT_WINDOW_SEC,\n} from \"./use-media-playback.js\";\nexport type { UseMediaPlaybackResult } from \"./use-media-playback.js\";\n"]}
@@ -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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GAChB,sBAAsB,CAkPxB"}
@@ -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,
@@ -46,6 +55,11 @@ mediaKey) {
46
55
  // True once we have observed real playback progress — after this we resume
47
56
  // from lastPositionRef, never re-apply the original startAtSeconds prop.
48
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);
49
63
  // Throttle bookkeeping for periodic samples (wall-clock, active playback only).
50
64
  const lastSampleAtRef = React.useRef(0);
51
65
  // Render-phase reset-on-source-change: when the media source (`mediaKey`)
@@ -59,31 +73,34 @@ mediaKey) {
59
73
  prevMediaKeyRef.current = mediaKey;
60
74
  lastPositionRef.current = seedFromProps;
61
75
  hasStartedRef.current = false;
76
+ seededRef.current = seedFromProps !== null;
62
77
  lastSampleAtRef.current = 0;
63
78
  if (hasEnded)
64
79
  setHasEnded(false);
65
80
  }
66
- const emitSample = React.useCallback((el) => {
81
+ const emitSample = React.useCallback((el, reason) => {
67
82
  const cb = onProgressSampleRef.current;
68
83
  if (!cb)
69
84
  return;
70
85
  const duration = Number.isFinite(el.duration) ? el.duration : 0;
71
- cb(el.currentTime, duration);
86
+ cb(el.currentTime, duration, reason);
72
87
  }, []);
73
88
  const trackPosition = React.useCallback((el) => {
74
89
  if (hasStartedRef.current) {
75
90
  lastPositionRef.current = el.currentTime;
76
91
  }
77
92
  }, []);
78
- const applyInitialSeek = React.useCallback((el) => {
93
+ const applyInitialSeek = React.useCallback((el, adoptWindowSec = 0.01) => {
79
94
  const target = lastPositionRef.current;
80
95
  if (typeof target !== "number" || target <= 0)
81
96
  return;
82
- // Only seek a freshly-loaded element sitting at the start. This makes the
83
- // handler idempotent (a metadata event on an already-positioned element is
84
- // a no-op) and, crucially, re-applies the LAST KNOWN position to the new
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
85
100
  // element created by an unloadOnExit remount — resuming, never restarting.
86
- if (el.currentTime > 0.01)
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)
87
104
  return;
88
105
  const dur = el.duration;
89
106
  const clamped = Number.isFinite(dur) && dur > 0 ? Math.min(target, dur) : target;
@@ -97,27 +114,33 @@ mediaKey) {
97
114
  // Late-arriving resume position. `startAtSeconds` usually comes from an async
98
115
  // app source (a user-prefs query); when that resolves AFTER this hook mounted,
99
116
  // the mount-time seed above saw `undefined` and the element would silently
100
- // start at 0. Adopt the value when it finally arrives — but ONLY while nothing
101
- // has been seeded, no real playback has begun, and the element is still at the
102
- // start, so a late value can never yank media the user is already watching and
103
- // can never overwrite a truthful tracked position. A `mediaKey` change resets
104
- // both refs in the render-phase block above, which re-arms this for the new
105
- // source; the seek itself is applied here because the element may already have
106
- // fired `loadedmetadata` (that is exactly this defect) and will not fire it
107
- // again — when metadata has not landed yet, `onLoadedMetadata` applies it.
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.
108
132
  React.useEffect(() => {
109
133
  if (seedFromProps === null)
110
134
  return;
111
- if (hasStartedRef.current)
112
- return;
113
- if (lastPositionRef.current !== null)
114
- return;
135
+ if (seededRef.current)
136
+ return; // adopt exactly once; never override an applied seed
115
137
  const el = elementRef.current;
116
- if (el && el.currentTime > 0.01)
138
+ if (el && el.currentTime > LATE_RESUME_ADOPT_WINDOW_SEC)
117
139
  return;
140
+ seededRef.current = true;
118
141
  lastPositionRef.current = seedFromProps;
119
142
  if (el)
120
- applyInitialSeek(el);
143
+ applyInitialSeek(el, LATE_RESUME_ADOPT_WINDOW_SEC);
121
144
  }, [seedFromProps, applyInitialSeek, elementRef]);
122
145
  const onLoadedMetadata = React.useCallback((e) => {
123
146
  applyInitialSeek(e.currentTarget);
@@ -132,10 +155,21 @@ mediaKey) {
132
155
  trackPosition(el);
133
156
  if (el.paused)
134
157
  return; // no periodic samples while paused
158
+ // Pre-seed suppression: until a resume position has been adopted, an
159
+ // element still near the start may be autoplaying from 0 while the app's
160
+ // async saved position is in flight. A periodic ~0 sample here would be
161
+ // written to durable state and CLOBBER that saved position before the
162
+ // seek lands. Stay silent for the adoption window; the seek's `seeked`
163
+ // flush reports the resumed position, and with no saved position at all
164
+ // periodic sampling simply begins a few seconds in (harmless). Deliberate
165
+ // pause/seeked/ended flushes are never suppressed — a user pausing at
166
+ // 0.5 s is genuine intent.
167
+ if (!seededRef.current && el.currentTime <= LATE_RESUME_ADOPT_WINDOW_SEC)
168
+ return;
135
169
  const now = Date.now();
136
170
  if (now - lastSampleAtRef.current >= PROGRESS_SAMPLE_INTERVAL_MS) {
137
171
  lastSampleAtRef.current = now;
138
- emitSample(el);
172
+ emitSample(el, "periodic");
139
173
  }
140
174
  }, [emitSample, trackPosition]);
141
175
  const onPlay = React.useCallback(() => {
@@ -147,14 +181,16 @@ mediaKey) {
147
181
  trackPosition(el);
148
182
  // Flush a sample immediately on pause (final position for this segment).
149
183
  lastSampleAtRef.current = Date.now();
150
- emitSample(el);
184
+ emitSample(el, "pause");
151
185
  }, [emitSample, trackPosition]);
152
186
  const onSeeked = React.useCallback((e) => {
153
187
  const el = e.currentTarget;
154
188
  trackPosition(el);
155
189
  // Flush a sample on seek completion so the app sees the new position.
190
+ // This is also how the programmatic initial-resume seek reports the
191
+ // adopted position — the element fires `seeked` after applyInitialSeek.
156
192
  lastSampleAtRef.current = Date.now();
157
- emitSample(el);
193
+ emitSample(el, "seeked");
158
194
  }, [emitSample, trackPosition]);
159
195
  const onEndedHandler = React.useCallback((e) => {
160
196
  const el = e.currentTarget;
@@ -163,7 +199,7 @@ mediaKey) {
163
199
  lastPositionRef.current = el.currentTime;
164
200
  // Flush a final sample with the ended position.
165
201
  lastSampleAtRef.current = Date.now();
166
- emitSample(el);
202
+ emitSample(el, "ended");
167
203
  setHasEnded(true);
168
204
  onEndedRef.current?.();
169
205
  }, [emitSample]);
@@ -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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I,CAAC,EAAE;gBAAE,OAAO;YAChB,MAAM,GAAG,GAAG,EAAE,CAAC,QAAQ,CAAC;YACxB,MAAM,OAAO,GACX,MAAM,CAAC,QAAQ,CAAC,GAAG,CAAC,IAAI,GAAG,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,OAAO,EAAE,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,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 // 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\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 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 // 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 — but ONLY while nothing\n // has been seeded, no real playback has begun, and the element is still at the\n // start, so a late value can never yank media the user is already watching and\n // can never overwrite a truthful tracked position. A `mediaKey` change resets\n // both refs in the render-phase block above, which re-arms this for the new\n // source; the seek itself is applied here because the element may already have\n // fired `loadedmetadata` (that is exactly this defect) and will not fire it\n // again — when metadata has not landed yet, `onLoadedMetadata` applies it.\n React.useEffect(() => {\n if (seedFromProps === null) return;\n if (hasStartedRef.current) return;\n if (lastPositionRef.current !== null) return;\n const el = elementRef.current;\n if (el && el.currentTime > 0.01) return;\n lastPositionRef.current = seedFromProps;\n if (el) applyInitialSeek(el);\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"]}
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;AAO/B;;;GAGG;AACH,MAAM,CAAC,MAAM,2BAA2B,GAAG,IAAI,CAAC;AAEhD;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,4BAA4B,GAAG,CAAC,CAAC;AAgB9C;;;;;;;;;;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AEF,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 {\n MediaPlaybackControls,\n MediaPlaybackProps,\n MediaProgressSampleReason,\n} 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(\n (el: HTMLMediaElement, reason: MediaProgressSampleReason) => {\n const cb = onProgressSampleRef.current;\n if (!cb) return;\n const duration = Number.isFinite(el.duration) ? el.duration : 0;\n cb(el.currentTime, duration, reason);\n },\n [],\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 // Pre-seed suppression: until a resume position has been adopted, an\n // element still near the start may be autoplaying from 0 while the app's\n // async saved position is in flight. A periodic ~0 sample here would be\n // written to durable state and CLOBBER that saved position before the\n // seek lands. Stay silent for the adoption window; the seek's `seeked`\n // flush reports the resumed position, and with no saved position at all\n // periodic sampling simply begins a few seconds in (harmless). Deliberate\n // pause/seeked/ended flushes are never suppressed — a user pausing at\n // 0.5 s is genuine intent.\n if (!seededRef.current && el.currentTime <= LATE_RESUME_ADOPT_WINDOW_SEC) return;\n const now = Date.now();\n if (now - lastSampleAtRef.current >= PROGRESS_SAMPLE_INTERVAL_MS) {\n lastSampleAtRef.current = now;\n emitSample(el, \"periodic\");\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, \"pause\");\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 // This is also how the programmatic initial-resume seek reports the\n // adopted position — the element fires `seeked` after applyInitialSeek.\n lastSampleAtRef.current = Date.now();\n emitSample(el, \"seeked\");\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, \"ended\");\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
@@ -16,6 +16,13 @@ export type MediaPlaybackControls = {
16
16
  /** Seek to the given position (seconds), clamped to [0, duration]. */
17
17
  seekTo(seconds: number): void;
18
18
  };
19
+ /**
20
+ * Why a progress sample was emitted. `periodic` is a throttled position report
21
+ * during playback and is safe for a consumer to coalesce or drop; the other
22
+ * three mark an exact moment the user's position changed and should be
23
+ * committed as-is.
24
+ */
25
+ export type MediaProgressSampleReason = "periodic" | "pause" | "seeked" | "ended";
19
26
  /**
20
27
  * Additive, fully optional playback API shared by `VideoViewer` and
21
28
  * `AudioViewer`. Every field is optional; when all are absent the viewers
@@ -29,15 +36,22 @@ export type MediaPlaybackProps = {
29
36
  */
30
37
  onEnded?: () => void;
31
38
  /**
32
- * Periodic playback-position reporting. Contract:
33
- * - While playing, fires at most once every ~5 seconds of playback
34
- * (throttled off `timeupdate`).
35
- * - Fires once immediately on pause, on seek completion (`seeked`), and on
36
- * ended — each carrying the exact position at that moment.
37
- * - Never fires while paused (aside from the single pause-flush above).
39
+ * Playback-position reporting. Every sample carries the `reason` it was
40
+ * emitted for ({@link MediaProgressSampleReason}) as an additive third
41
+ * argument, so a consumer can throttle `periodic` reports while committing
42
+ * the exact-moment ones. Contract:
43
+ * - `periodic` — while playing, fires at most once every ~5 seconds of
44
+ * playback (throttled off `timeupdate`). Never fires while paused, and is
45
+ * SUPPRESSED near the start until the resume decision is settled: while no
46
+ * `startAtSeconds` seed has been adopted and the element is still within
47
+ * the late-resume adoption window, an autoplaying element reports nothing,
48
+ * so a position of ~0 can never overwrite a saved one.
49
+ * - `pause` / `seeked` / `ended` — fires once immediately on that event with
50
+ * the exact position, never suppressed. The programmatic resume seek that
51
+ * applies `startAtSeconds` reports as `seeked` with the resumed position.
38
52
  * `durationSeconds` is `0` until the element's duration is known.
39
53
  */
40
- onProgressSample?: (currentTimeSeconds: number, durationSeconds: number) => void;
54
+ onProgressSample?: (currentTimeSeconds: number, durationSeconds: number, reason: MediaProgressSampleReason) => void;
41
55
  /**
42
56
  * Initial playback position (seconds), applied once the element has metadata.
43
57
  * May arrive late (e.g. from an async prefs read that resolves after the
@@ -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,CA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AAE,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 * 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"]}
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 * Why a progress sample was emitted. `periodic` is a throttled position report\n * during playback and is safe for a consumer to coalesce or drop; the other\n * three mark an exact moment the user's position changed and should be\n * committed as-is.\n */\nexport type MediaProgressSampleReason = \"periodic\" | \"pause\" | \"seeked\" | \"ended\";\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 * Playback-position reporting. Every sample carries the `reason` it was\n * emitted for ({@link MediaProgressSampleReason}) as an additive third\n * argument, so a consumer can throttle `periodic` reports while committing\n * the exact-moment ones. Contract:\n * - `periodic` — while playing, fires at most once every ~5 seconds of\n * playback (throttled off `timeupdate`). Never fires while paused, and is\n * SUPPRESSED near the start until the resume decision is settled: while no\n * `startAtSeconds` seed has been adopted and the element is still within\n * the late-resume adoption window, an autoplaying element reports nothing,\n * so a position of ~0 can never overwrite a saved one.\n * - `pause` / `seeked` / `ended` — fires once immediately on that event with\n * the exact position, never suppressed. The programmatic resume seek that\n * applies `startAtSeconds` reports as `seeked` with the resumed position.\n * `durationSeconds` is `0` until the element's duration is known.\n */\n onProgressSample?: (\n currentTimeSeconds: number,\n durationSeconds: number,\n reason: MediaProgressSampleReason,\n ) => 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.7",
3
+ "version": "0.10.9",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/ttt-productions/ttt-packages.git",
@@ -33,7 +33,7 @@
33
33
  "prepublishOnly": "npm run clean && npm run build"
34
34
  },
35
35
  "dependencies": {
36
- "@ttt-productions/media-schemas": "^0.14.4",
36
+ "@ttt-productions/media-schemas": "^0.14.5",
37
37
  "@ttt-productions/ui-core": "^0.11.12"
38
38
  },
39
39
  "peerDependencies": {