@banou/media-player 0.10.28 → 0.10.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,7 @@
1
1
  /// <reference types="@emotion/react/types/css-prop" />
2
2
  import type { ReactNode, Ref } from 'react'
3
3
  import type { ViewportBox } from '../source-feature'
4
+ import type { HostFullscreen } from '../video-player'
4
5
 
5
6
  import { Children, Fragment, isValidElement, useEffect, useRef } from 'react'
6
7
  import { css } from '@emotion/react'
@@ -9,6 +10,7 @@ import { usePlayer } from '../player'
9
10
  import { Overlay } from './overlay'
10
11
  import ControlBar from './control-bar'
11
12
  import BurnInHint from './burn-in-hint'
13
+ import { HostKeepsFullscreen } from './tooltip-display'
12
14
  import SkipChapter from './skip-chapter'
13
15
 
14
16
  const AUTO_HIDE_DELAY = 3_000
@@ -133,10 +135,12 @@ export type ChromeProps = {
133
135
  /** False draws no control bar at all, leaving the picture, the title and the overlay. */
134
136
  controls?: boolean
135
137
  shortcuts?: 'window' | 'player'
138
+ /** Fullscreen kept by the host: a press calls its `request` instead of fullscreening the player. */
139
+ fullscreen?: HostFullscreen
136
140
  children?: ReactNode
137
141
  }
138
142
 
139
- export const Chrome = ({ ref, onVideoRef, onSubtitleRef, overlay, controls, shortcuts, children }: ChromeProps) => {
143
+ export const Chrome = ({ ref, onVideoRef, onSubtitleRef, overlay, controls, shortcuts, fullscreen, children }: ChromeProps) => {
140
144
  const player = usePlayer()
141
145
  const hideUI = usePlayer((state) => state.hideUI)
142
146
  const setHideUI = usePlayer((state) => state.setHideUI)
@@ -268,7 +272,8 @@ export const Chrome = ({ ref, onVideoRef, onSubtitleRef, overlay, controls, shor
268
272
  if (lastPointerType.current !== 'mouse') return
269
273
  if (pausedBeforeClick.current) player.pause()
270
274
  else void player.play().catch(() => {})
271
- void player.toggleFullscreen()
275
+ if (fullscreen) fullscreen.request()
276
+ else void player.toggleFullscreen()
272
277
  }
273
278
 
274
279
  // relatedTarget alone is not enough: the browser fires mouseout with a null one while the pointer
@@ -306,7 +311,11 @@ export const Chrome = ({ ref, onVideoRef, onSubtitleRef, overlay, controls, shor
306
311
  {item}
307
312
  </div>
308
313
  ))}
309
- {controls === false ? null : <ControlBar shortcuts={shortcuts} root={root} />}
314
+ {controls === false ? null : (
315
+ <HostKeepsFullscreen value={!!fullscreen}>
316
+ <ControlBar shortcuts={shortcuts} root={root} fullscreen={fullscreen} />
317
+ </HostKeepsFullscreen>
318
+ )}
310
319
  {/* Not tied to `hideUI`: it says what to do next, and it is on screen for nine seconds. */}
311
320
  <BurnInHint />
312
321
  <SkipChapter />
@@ -1,5 +1,6 @@
1
1
  /// <reference types="@emotion/react/types/css-prop" />
2
2
  import type { RefObject } from 'react'
3
+ import type { HostFullscreen } from '../video-player'
3
4
 
4
5
  import { useCallback, useEffect, useRef, useState } from 'react'
5
6
  import { css } from '@emotion/react'
@@ -160,7 +161,11 @@ const style = css`
160
161
  `
161
162
 
162
163
  export const ControlBar = (
163
- { shortcuts = 'window', root }: { shortcuts?: 'window' | 'player', root: RefObject<HTMLDivElement | null> },
164
+ { shortcuts = 'window', root, fullscreen: host }: {
165
+ shortcuts?: 'window' | 'player'
166
+ root: RefObject<HTMLDivElement | null>
167
+ fullscreen?: HostFullscreen
168
+ },
164
169
  ) => {
165
170
  const player = usePlayer()
166
171
  const paused = usePlayer((state) => state.paused)
@@ -168,7 +173,11 @@ export const ControlBar = (
168
173
  const duration = usePlayer((state) => state.duration)
169
174
  // a seek in flight reads as its destination, so the clock answers the click at once
170
175
  const seekingTo = usePlayer((state) => state.seekingTo)
171
- const fullscreen = usePlayer((state) => state.fullscreen)
176
+ const ownFullscreen = usePlayer((state) => state.fullscreen)
177
+ const fullscreen = host ? host.active : ownFullscreen
178
+ // through a ref, so the key listener below is not re-added for a host's inline object on every render
179
+ const latestHost = useRef(host)
180
+ latestHost.current = host
172
181
  const hideUI = usePlayer((state) => state.hideUI)
173
182
  const togglePictureInPicture = usePlayer((state) => state.togglePictureInPicture)
174
183
  const pictureInPictureMode = usePlayer((state) => state.pictureInPictureMode)
@@ -207,6 +216,11 @@ export const ControlBar = (
207
216
  // Opening, once pressed) leaves the focus on the body, and the shortcuts stay with the player through that
208
217
  const engaged = useRef(false)
209
218
 
219
+ const toggleFullscreen = useCallback(() => {
220
+ if (latestHost.current) latestHost.current.request()
221
+ else void player.toggleFullscreen()
222
+ }, [player])
223
+
210
224
  useEffect(() => {
211
225
  const seek = (time: number) => requestSeek ? requestSeek(time) : player.seek(time)
212
226
  // the path, not ev.target, which a shadow root around the player retargets to its host
@@ -220,11 +234,12 @@ export const ControlBar = (
220
234
  // layouts, as Ctrl and Alt
221
235
  if ((ev.ctrlKey || ev.metaKey || ev.altKey) && !ev.getModifierState('AltGraph')) return
222
236
  const fromPlayer = root.current?.contains(target ?? null) || (target === document.body && engaged.current)
223
- if (shortcuts === 'player' && !player.fullscreen && !fromPlayer) return
237
+ const fullscreen = latestHost.current ? latestHost.current.active : player.fullscreen
238
+ if (shortcuts === 'player' && !fullscreen && !fromPlayer) return
224
239
 
225
240
  let shouldPreventDefault = true
226
241
  // space would otherwise reach the browser's own shortcut
227
- if (ev.key === 'f') player.toggleFullscreen()
242
+ if (ev.key === 'f') toggleFullscreen()
228
243
  else if (ev.key === 'k') player.togglePaused()
229
244
  else if (ev.key === ' ') player.togglePaused()
230
245
  else if (ev.key === 'm') player.toggleMuted()
@@ -258,7 +273,7 @@ export const ControlBar = (
258
273
  window.removeEventListener('pointerdown', engage, true)
259
274
  window.removeEventListener('focusin', engage, true)
260
275
  }
261
- }, [player, modifyVolume, requestSeek, stepFrame, shortcuts, root])
276
+ }, [player, modifyVolume, requestSeek, stepFrame, shortcuts, root, toggleFullscreen])
262
277
 
263
278
  const handleWheel = useCallback((e: WheelEvent) => {
264
279
  e.preventDefault()
@@ -436,7 +451,7 @@ export const ControlBar = (
436
451
  <button
437
452
  className='full-screen'
438
453
  type='button'
439
- onClick={() => player.toggleFullscreen()}
454
+ onClick={toggleFullscreen}
440
455
  aria-label='Full screen'
441
456
  aria-pressed={fullscreen}
442
457
  >
@@ -1,7 +1,7 @@
1
1
  import type { ReactNode } from 'react'
2
2
  import type { TooltipRefProps } from 'react-tooltip'
3
3
 
4
- import { useEffect, useRef } from 'react'
4
+ import { createContext, useContext, useEffect, useRef } from 'react'
5
5
  import { css } from '@emotion/react'
6
6
  import { PlacesType, Tooltip } from 'react-tooltip'
7
7
 
@@ -78,6 +78,9 @@ const watchPointer = () => {
78
78
  }
79
79
  }
80
80
 
81
+ /** Whether the host page keeps the player's fullscreen: the `fullscreen` prop, or a mirror that took it over. */
82
+ export const HostKeepsFullscreen = createContext(false)
83
+
81
84
  interface TooltipDisplayProps {
82
85
  id: string
83
86
  toolTipText: ReactNode
@@ -103,6 +106,7 @@ export const TooltipDisplay = ({
103
106
  }: TooltipDisplayProps) => {
104
107
  const anchor = useRef<HTMLDivElement>(null)
105
108
  const tooltip = useRef<TooltipRefProps>(null)
109
+ const hostKeepsFullscreen = useContext(HostKeepsFullscreen)
106
110
 
107
111
  /**
108
112
  * Close on a fullscreen transition, unless the pointer really is still on the anchor.
@@ -124,6 +128,12 @@ export const TooltipDisplay = ({
124
128
  * That is the same test chrome.tsx's onMouseOut makes when relatedTarget comes back null. The rect
125
129
  * is already the post-transition one when fullscreenchange fires, where matches(':hover') is not,
126
130
  * which is why the pointer is tracked rather than asked for.
131
+ *
132
+ * A host that keeps the fullscreen fullscreens an element of its own document, so a player in a
133
+ * frame hears no fullscreenchange (measured 2026-10-26, Chromium) and the chip stayed through any
134
+ * later pointer move. Its window resizes with the frame, after the move, so that is what this
135
+ * listens to then. The host's `active` would not do: across origins it comes by a message, and no
136
+ * rule orders a message against the frame's new size.
127
137
  */
128
138
  useEffect(() => {
129
139
  const untrack = watchPointer()
@@ -138,11 +148,13 @@ export const TooltipDisplay = ({
138
148
  // as string so the prefixed name checks against the DOM lib's event map.
139
149
  const changeEvents: string[] = ['fullscreenchange', 'webkitfullscreenchange']
140
150
  for (const type of changeEvents) document.addEventListener(type, closeIfPointerLeft)
151
+ if (hostKeepsFullscreen) window.addEventListener('resize', closeIfPointerLeft)
141
152
  return () => {
142
153
  untrack()
143
154
  for (const type of changeEvents) document.removeEventListener(type, closeIfPointerLeft)
155
+ window.removeEventListener('resize', closeIfPointerLeft)
144
156
  }
145
- }, [])
157
+ }, [hostKeepsFullscreen])
146
158
 
147
159
  return (
148
160
  <>
@@ -3,7 +3,7 @@ import type { ReactNode } from 'react'
3
3
  import type { MediaChapter } from '../engine'
4
4
  import type { DownloadedRange, VolumeNormalizerControl } from './source-feature'
5
5
  import type { DelegatedSelection, DelegatedTracks, ExternalThumbnails, PassThroughPictureInPicture, PlayerMedia } from './media'
6
- import type { ExposePlayerOptions } from '../remote'
6
+ import type { ExposePlayerOptions, ServedPlayer } from '../remote'
7
7
 
8
8
  import { useEffect, useMemo, useRef, useState } from 'react'
9
9
  import { css } from '@emotion/react'
@@ -32,6 +32,20 @@ export type MediaPlayerSource =
32
32
  | { read: (offset: number, size: number) => Promise<ArrayBuffer>, size: number, readsDownload?: boolean }
33
33
  | { read?: undefined, size?: undefined, readsDownload?: undefined }
34
34
 
35
+ /**
36
+ * Fullscreen kept by the host page rather than by the player, for a page that fullscreens an element of its own around
37
+ * the player, so that fullscreen outlasts the player in it.
38
+ */
39
+ export type HostFullscreen = {
40
+ /** Whether the host shows the player fullscreen: the button shows it, and the `'player'` shortcuts follow it. */
41
+ active: boolean
42
+ /**
43
+ * The viewer pressed fullscreen (the button, `f` or a double click): the host enters or leaves it. Called once per
44
+ * press, during that press's event, so the host's own `requestFullscreen` has the press's activation.
45
+ */
46
+ request: () => void
47
+ }
48
+
35
49
  /** Shared by both arms: nothing here depends on who owns the media. */
36
50
  type CommonOptions = {
37
51
  /**
@@ -88,6 +102,13 @@ type CommonOptions = {
88
102
  */
89
103
  shortcuts?: 'window' | 'player'
90
104
 
105
+ /**
106
+ * Hand fullscreen to the host page: the player then never calls `requestFullscreen`, each press of its fullscreen
107
+ * calls `request` once, and the button and the `'player'` shortcuts follow `active`. Read by value, so it may be
108
+ * written inline. Without it the player fullscreens itself.
109
+ */
110
+ fullscreen?: HostFullscreen
111
+
91
112
  /**
92
113
  * The app's own content over the video: a download readout, a badge, a logo, anything the player
93
114
  * itself has no opinion about.
@@ -332,6 +353,12 @@ const PlayerRoot = ({ options, children }: { options: MediaPlayerOptions, childr
332
353
  // Imported lazily, so `osra` is a dependency of `@banou/media-player/remote` and not of every app
333
354
  // that renders a player without ever exposing one.
334
355
  const { expose } = options
356
+ // What `expose` serves beside the media, the same object for the player's life. Its `onHostFullscreen` is how a
357
+ // mirror made with `fullscreen: true` takes the fullscreen over.
358
+ const [embedderFullscreen, setEmbedderFullscreen] = useState<boolean | null>(null)
359
+ const [served] = useState<ServedPlayer & { chapters: MediaChapter[] }>(
360
+ () => Object.assign(new EventTarget(), { chapters: [], onHostFullscreen: setEmbedderFullscreen }),
361
+ )
335
362
  const exposeOptions = expose === true ? {} : expose || undefined
336
363
  const latestExpose = useRef(exposeOptions)
337
364
  latestExpose.current = exposeOptions
@@ -345,12 +372,25 @@ const PlayerRoot = ({ options, children }: { options: MediaPlayerOptions, childr
345
372
  import('../remote')
346
373
  .then(({ exposePlayer }) => {
347
374
  if (dropped) return
348
- stop = exposePlayer(media, latestExpose.current ?? {})
375
+ stop = exposePlayer(media, { ...latestExpose.current, player: served })
349
376
  })
350
377
  .catch(() => {})
351
378
  return () => { dropped = true; stop?.() }
352
379
  }, [media, !!expose, exposeId, exposeOrigin, exposeChannel])
353
380
 
381
+ // by value, since a caller's inline `chapters` is a new array on every render
382
+ const playerChapters = usePlayer((state) => state.chapters)
383
+ const chaptersKey = JSON.stringify(playerChapters)
384
+ useEffect(() => {
385
+ served.chapters = playerChapters
386
+ served.dispatchEvent(new Event('chapterschange'))
387
+ }, [chaptersKey])
388
+
389
+ const fullscreen = options.fullscreen ?? (embedderFullscreen === null ? undefined : {
390
+ active: embedderFullscreen,
391
+ request: () => served.dispatchEvent(new Event('fullscreenrequest')),
392
+ })
393
+
354
394
  // one per file, as `size` is the source's identity everywhere here
355
395
  const tap = useMemo(() => createPlaybackTap(), [size])
356
396
 
@@ -529,6 +569,7 @@ const PlayerRoot = ({ options, children }: { options: MediaPlayerOptions, childr
529
569
  overlay={options.overlay}
530
570
  controls={options.controls}
531
571
  shortcuts={options.shortcuts}
572
+ fullscreen={fullscreen}
532
573
  >
533
574
  {children}
534
575
  </Chrome>
@@ -11,15 +11,16 @@
11
11
  // which is the only shape that satisfies a synchronous media over an asynchronous boundary.
12
12
 
13
13
  import type { Message, ReceiveHandler, Remote, Transport } from 'osra'
14
+ import type { MediaChapter } from '../engine'
14
15
  import type { PlayerMedia } from '../react/media'
15
16
  import type { Callable, PlayerEvent, PlayerService, PlayerSnapshot, PlayerUpdate, Writable } from './protocol'
16
17
 
17
18
  import { expose } from 'osra'
18
19
 
19
- import { CALLABLE, DEFAULT_PLAYER_ID, EMPTY_SNAPSHOT, PLAYER_CHANNEL, PLAYER_EVENTS, snapshotOf, syncEventsFor, toTimeRanges, WRITABLE } from './protocol'
20
+ import { CALLABLE, DEFAULT_PLAYER_ID, EMPTY_SNAPSHOT, PLAYER_CHANNEL, PLAYER_EVENTS, SERVED_EVENTS, snapshotOf, syncEventsFor, toTimeRanges, WRITABLE } from './protocol'
20
21
 
21
22
  export type { PlayerEvent, PlayerSnapshot, PlayerUpdate } from './protocol'
22
- export { DEFAULT_PLAYER_ID, PLAYER_CHANNEL, PLAYER_EVENTS } from './protocol'
23
+ export { DEFAULT_PLAYER_ID, PLAYER_CHANNEL, PLAYER_EVENTS, SERVED_EVENTS } from './protocol'
23
24
 
24
25
  /** How long a peer has to answer its handshake before the mirror stops waiting on it and moves on. */
25
26
  const HANDSHAKE_MS = 10_000
@@ -77,6 +78,19 @@ export type ExposePlayerOptions = {
77
78
  * and a channel that closed in between would drop every embedder listening to the others.
78
79
  */
79
80
  signal?: AbortSignal
81
+ /** What `<MediaPlayer expose>` serves beside its media. A document serving a bare element leaves it out. */
82
+ player?: ServedPlayer
83
+ }
84
+
85
+ /**
86
+ * The player around a served media, as `<MediaPlayer expose>` passes it: its chapters, sent with every snapshot and
87
+ * announced on its `chapterschange`, and its fullscreen, which a mirror made with `fullscreen: true` takes over. While
88
+ * one has it, `onHostFullscreen` is told the state that mirror sets, and null once none has it; the player then
89
+ * dispatches `fullscreenrequest` for each press of its fullscreen, which reaches the mirror.
90
+ */
91
+ export type ServedPlayer = EventTarget & {
92
+ readonly chapters: MediaChapter[]
93
+ onHostFullscreen: (active: boolean | null) => void
80
94
  }
81
95
 
82
96
  /**
@@ -138,14 +152,20 @@ const channelFor = (options: ExposePlayerOptions): Channel => {
138
152
  // connection for the document, however many players it has: a second player must not take the
139
153
  // first's embedder away, which is what one shared `current` did.
140
154
  const medias = new Map<string, PlayerMedia>()
155
+ const players = new Map<string, ServedPlayer>()
141
156
  const ports = new Map<string, Set<MessagePort>>()
142
157
  const listeners = (id: string) => ports.get(id) ?? ports.set(id, new Set()).get(id)!
158
+ // the ports whose mirror took the player's fullscreen over, and the state they last set
159
+ const hosts = new Map<string, Set<MessagePort>>()
160
+ const hostActive = new Map<string, boolean>()
161
+ const tellHost = (id: string) => players.get(id)?.onHostFullscreen(hosts.get(id)?.size ? hostActive.get(id) ?? false : null)
143
162
  const drop = (id: string, port: MessagePort) => {
144
163
  ports.get(id)?.delete(port)
164
+ if (hosts.get(id)?.delete(port)) tellHost(id)
145
165
  try { port.onmessage = null; port.close() } catch {}
146
166
  }
147
- const post = (id: string, update: PlayerUpdate, only?: MessagePort) => {
148
- for (const port of only ? [only] : [...listeners(id)]) {
167
+ const post = (id: string, update: PlayerUpdate, to: Iterable<MessagePort> = listeners(id)) => {
168
+ for (const port of [...to]) {
149
169
  // posting to a port whose peer is gone is silently dropped, which is exactly what a vanished
150
170
  // embedder deserves; a port that throws is one this document already closed
151
171
  try { port.postMessage(update) } catch { drop(id, port) }
@@ -153,18 +173,20 @@ const channelFor = (options: ExposePlayerOptions): Channel => {
153
173
  }
154
174
  const snapshotAt = (id: string) => {
155
175
  const media = medias.get(id)
156
- return media ? snapshotOf(media) : undefined
176
+ return media ? snapshotOf(media, players.get(id)?.chapters) : undefined
157
177
  }
158
178
  const announce = (id: string, event: PlayerEvent) => {
179
+ // a press of the fullscreen is for the mirrors that took it over: another one toggling too would undo it
180
+ const to = event === 'fullscreenrequest' ? hosts.get(id) : ports.get(id)
159
181
  // nobody listening is the ordinary case for a player nobody mirrors, and `timeupdate` alone is
160
182
  // four snapshots a second for the life of the document
161
- if (!ports.get(id)?.size) return
183
+ if (!to?.size) return
162
184
  const snapshot = snapshotAt(id)
163
- if (snapshot) post(id, { event, snapshot })
185
+ if (snapshot) post(id, { event, snapshot }, to)
164
186
  }
165
187
 
166
188
  const service: PlayerService = {
167
- subscribe: (id, port) => {
189
+ subscribe: (id, port, options) => {
168
190
  // The peer's arguments, so they are checked: osra revives a plain object as a plain object and
169
191
  // a function as a callable, and either would sit in this set being posted to for ever.
170
192
  // Refused LOUDLY: a mirror whose subscribe was dropped in silence waits for ever, and a caller
@@ -176,6 +198,12 @@ const channelFor = (options: ExposePlayerOptions): Channel => {
176
198
  const set = listeners(id)
177
199
  if (set.size >= MAX_SUBSCRIBERS) throw new RangeError('too many embedders for this player')
178
200
  set.add(port)
201
+ const fullscreen = (options as { fullscreen?: unknown } | undefined)?.fullscreen
202
+ if (typeof fullscreen === 'boolean') {
203
+ ;(hosts.get(id) ?? hosts.set(id, new Set()).get(id)!).add(port)
204
+ hostActive.set(id, fullscreen)
205
+ tellHost(id)
206
+ }
179
207
  // A mirror says goodbye on its own port when it closes, and the port is dropped here. Without
180
208
  // it a closed mirror's port stays in this set for the document's life and every event is
181
209
  // posted to it, one more dead port per mirror that ever connected.
@@ -185,9 +213,16 @@ const channelFor = (options: ExposePlayerOptions): Channel => {
185
213
  // its answer is missed. Nothing at all when no player has that id: the mirror waits, and hears
186
214
  // this the moment one is served.
187
215
  const snapshot = snapshotAt(id)
188
- if (snapshot) post(id, { event: 'loadstart', snapshot }, port)
216
+ if (snapshot) post(id, { event: 'loadstart', snapshot }, [port])
189
217
  },
190
218
  set: (id, name, value) => {
219
+ if (name === 'fullscreen') {
220
+ // only for an id a mirror took over: the id is the peer's, and the map would otherwise grow with it
221
+ if (typeof value !== 'boolean' || !hosts.get(id)?.size) return
222
+ hostActive.set(id, value)
223
+ tellHost(id)
224
+ return
225
+ }
191
226
  const media = medias.get(id)
192
227
  if (!media || !WRITABLE.includes(name)) return
193
228
  try { (media as unknown as Record<Writable, unknown>)[name] = value } catch {}
@@ -222,6 +257,7 @@ const channelFor = (options: ExposePlayerOptions): Channel => {
222
257
  for (const [player, set] of ports) for (const port of [...set]) drop(player, port)
223
258
  ports.clear()
224
259
  medias.clear()
260
+ players.clear()
225
261
  }, { once: true })
226
262
 
227
263
  expose<unknown>(service, {
@@ -234,18 +270,31 @@ const channelFor = (options: ExposePlayerOptions): Channel => {
234
270
  const channel: Channel = {
235
271
  serve: (media, served) => {
236
272
  const player = served.id ?? DEFAULT_PLAYER_ID
237
- const handlers = PLAYER_EVENTS.map(event => [event, () => { if (medias.get(player) === media) announce(player, event) }] as const)
238
- for (const [event, handler] of handlers) media.addEventListener(event, handler)
273
+ const around = served.player
274
+ const handlers = [
275
+ ...PLAYER_EVENTS.map(event => [media, event] as const),
276
+ ...around ? SERVED_EVENTS.map(event => [around, event] as const) : [],
277
+ ].map(([target, event]) => [target, event, () => { if (medias.get(player) === media) announce(player, event) }] as const)
278
+ for (const [target, event, handler] of handlers) target.addEventListener(event, handler)
239
279
  const replaced = medias.has(player)
280
+ const previous = players.get(player)
281
+ if (previous && previous !== around) previous.onHostFullscreen(null)
240
282
  medias.set(player, media)
283
+ if (around) players.set(player, around)
284
+ else players.delete(player)
285
+ tellHost(player)
241
286
  // the switch, told the way an element tells it: what was there is gone, and here is the new
242
287
  // one's state, ready to be synced from
243
288
  if (replaced) post(player, { event: 'emptied', snapshot: { ...EMPTY_SNAPSHOT } })
244
- for (const event of syncEventsFor(snapshotOf(media))) announce(player, event)
289
+ for (const event of syncEventsFor(snapshotAt(player)!)) announce(player, event)
245
290
  const stop = () => {
246
- for (const [event, handler] of handlers) media.removeEventListener(event, handler)
291
+ for (const [target, event, handler] of handlers) target.removeEventListener(event, handler)
247
292
  if (medias.get(player) !== media) return
248
293
  medias.delete(player)
294
+ if (around && players.get(player) === around) {
295
+ players.delete(player)
296
+ around.onHostFullscreen(null)
297
+ }
249
298
  post(player, { event: 'emptied', snapshot: { ...EMPTY_SNAPSHOT } })
250
299
  }
251
300
  // this call's own signal stops this media AND closes the channel: it is the release for the
@@ -277,6 +326,13 @@ export type MediaPlayerHandle =
277
326
  & Readonly<Required<Pick<PlayerMedia, 'src' | 'currentSrc' | 'ended' | 'buffered' | 'seekable' | 'error' | 'videoWidth' | 'videoHeight'>>>
278
327
  & Required<Pick<PlayerMedia, Writable>>
279
328
  & {
329
+ /** The far player's chapters, empty for a bare element. A `chapterschange` event follows each change. */
330
+ readonly chapters: MediaChapter[]
331
+ /**
332
+ * With the `fullscreen` option, whether this page shows the far player fullscreen: its button and its `'player'`
333
+ * shortcuts follow it. Set it on every change. Without the option it stays here.
334
+ */
335
+ fullscreen: boolean
280
336
  /**
281
337
  * Settles once the far side has first answered with its state; reads before that answer the
282
338
  * empty defaults. Stays pending for as long as nobody answers, and rejects with an AbortError on
@@ -333,6 +389,12 @@ export type MediaPlayerHandleOptions = {
333
389
  channel?: string
334
390
  /** closes the mirror: `ready` rejects with an AbortError and nothing more is heard */
335
391
  signal?: AbortSignal
392
+ /**
393
+ * Take the far player's fullscreen over, when it is a `<MediaPlayer expose>`: its button, `f` and double click then
394
+ * call no `requestFullscreen` and fire one `fullscreenrequest` on the handle each, inside the press's activation,
395
+ * and show the handle's `fullscreen`. Released on `destroy()`. A bare element ignores it.
396
+ */
397
+ fullscreen?: boolean
336
398
  }
337
399
 
338
400
  /**
@@ -349,11 +411,13 @@ type Subscriber = {
349
411
  /** the connection was replaced: whatever was asked of the old one will never be answered */
350
412
  reset: () => void
351
413
  port?: MessagePort
414
+ /** the fullscreen state to take the player's fullscreen over with, for a mirror that does */
415
+ fullscreen?: () => boolean
352
416
  }
353
417
 
354
418
  type Link = {
355
419
  attach: (subscriber: Subscriber) => () => void
356
- set: (id: string, name: Writable, value: number | boolean) => Promise<unknown> | undefined
420
+ set: (id: string, name: Writable | 'fullscreen', value: number | boolean) => Promise<unknown> | undefined
357
421
  call: (id: string, name: Callable) => Promise<void>
358
422
  }
359
423
 
@@ -389,7 +453,10 @@ const linkTo = (target: HTMLIFrameElement | Window | Transport, options: MediaPl
389
453
  // A peer that connects and then stops answering must not wedge the loop: osra leaves this
390
454
  // pending for ever if the far document was navigated away mid-handshake, and the next peer would
391
455
  // never be reached. A refusal lands here too, and takes the port with it.
392
- await withDeadline(() => service!.subscribe(subscriber.id, port2)).catch(error => {
456
+ const fullscreen = subscriber.fullscreen
457
+ await withDeadline(() => fullscreen
458
+ ? service!.subscribe(subscriber.id, port2, { fullscreen: fullscreen() })
459
+ : service!.subscribe(subscriber.id, port2)).catch(error => {
393
460
  unhook(subscriber)
394
461
  throw error
395
462
  })
@@ -494,21 +561,26 @@ export const mediaPlayer = (
494
561
  const pending = new Map<Writable, number | boolean>()
495
562
  // whether the far side has said anything about THIS player yet, which is what `ready` means
496
563
  let answered = false
564
+ let fullscreen = false
497
565
 
498
566
  const detach = linkTo(target, options).attach({
499
567
  id: playerId,
568
+ fullscreen: options.fullscreen ? () => fullscreen : undefined,
500
569
  reset: () => { answered = false; settleAll() },
501
570
  update: ({ event, snapshot }) => {
502
571
  const first = !answered
503
572
  answered = true
573
+ const chapters = JSON.stringify(state.chapters)
504
574
  Object.assign(state, snapshot)
505
575
  // a write the far side has not taken yet is the caller's intent, and outranks what the far
506
576
  // side is still reporting, first snapshot or any later one
507
577
  for (const [name, value] of pending) (state as Record<Writable, unknown>)[name] = value
508
- if (!first) { dispatch(event); return }
509
578
  // told as an element would tell it on load, so a store attached before this catches up
510
- for (const sync of syncEventsFor(state)) dispatch(sync)
511
- settleReady()
579
+ const events = first ? syncEventsFor(state) : [event]
580
+ // told for any update that changes them: a catch-up or a switch's `emptied` brings chapters with no word of them
581
+ if (!events.includes('chapterschange') && JSON.stringify(state.chapters) !== chapters) events.push('chapterschange')
582
+ for (const each of events) dispatch(each)
583
+ if (first) settleReady()
512
584
  },
513
585
  })
514
586
 
@@ -523,6 +595,7 @@ export const mediaPlayer = (
523
595
  for (const name of ['duration', 'paused', 'ended', 'seeking', 'readyState', 'src', 'currentSrc', 'error', 'videoWidth', 'videoHeight'] as const) readable(name)
524
596
  readable('buffered', toTimeRanges)
525
597
  readable('seekable', toTimeRanges)
598
+ readable('chapters')
526
599
 
527
600
  // Writes move the mirror at once, so a read in the same tick sees them (the seek bar reads its own
528
601
  // write back), and go out to be applied for real. Before the far side has answered they still go
@@ -547,6 +620,14 @@ export const mediaPlayer = (
547
620
  enumerable: true,
548
621
  })
549
622
  }
623
+ Object.defineProperty(player, 'fullscreen', {
624
+ get: () => fullscreen,
625
+ set: (value: boolean) => {
626
+ fullscreen = !!value
627
+ if (options.fullscreen) void after(() => link.set(playerId, 'fullscreen', fullscreen))
628
+ },
629
+ enumerable: true,
630
+ })
550
631
 
551
632
  const call = (name: Callable) => ready.then(() => {
552
633
  if (signal.aborted) throw abortError()
@@ -1,6 +1,7 @@
1
1
  // What crosses between a player and whoever embeds it. Pure and osra-free so the snapshot and the
2
2
  // mirror's arithmetic can be tested on values; ./index.ts is the half that talks.
3
3
 
4
+ import type { MediaChapter } from '../engine'
4
5
  import type { PlayerMedia, TimeRangesLike } from '../react/media'
5
6
 
6
7
  /**
@@ -28,6 +29,8 @@ export type PlayerSnapshot = {
28
29
  error: { code: number, message: string } | null
29
30
  videoWidth: number
30
31
  videoHeight: number
32
+ /** A `<MediaPlayer expose>`'s chapters, empty for a bare element. */
33
+ chapters: MediaChapter[]
31
34
  }
32
35
 
33
36
  /**
@@ -41,7 +44,12 @@ export const PLAYER_EVENTS = [
41
44
  'seeking', 'seeked', 'progress', 'ratechange', 'volumechange', 'ended', 'waiting', 'stalled', 'suspend',
42
45
  'canplay', 'canplaythrough', 'emptied', 'resize', 'error',
43
46
  ] as const
44
- export type PlayerEvent = typeof PLAYER_EVENTS[number]
47
+ /**
48
+ * The events a `<MediaPlayer expose>` raises beside its media's: its chapters changed, and its viewer pressed
49
+ * fullscreen while a mirror made with `fullscreen: true` has it.
50
+ */
51
+ export const SERVED_EVENTS = ['chapterschange', 'fullscreenrequest'] as const
52
+ export type PlayerEvent = typeof PLAYER_EVENTS[number] | typeof SERVED_EVENTS[number]
45
53
 
46
54
  /** The properties an embedder may set. Everything else is read-only on a media, here as there. */
47
55
  export const WRITABLE = ['currentTime', 'volume', 'muted', 'playbackRate'] as const
@@ -82,8 +90,10 @@ export type PlayerUpdate = { event: PlayerEvent, snapshot: PlayerSnapshot }
82
90
  * has not mounted yet.
83
91
  */
84
92
  export type PlayerService = {
85
- subscribe: (id: string, port: MessagePort) => void
86
- set: (id: string, name: Writable, value: number | boolean) => void
93
+ /** With `fullscreen`, the mirror takes the player's fullscreen over, in that state, until its port goes. */
94
+ subscribe: (id: string, port: MessagePort, options?: { fullscreen?: boolean }) => void
95
+ /** `fullscreen` is the state shown by a player whose fullscreen a mirror has taken over, and is ignored otherwise. */
96
+ set: (id: string, name: Writable | 'fullscreen', value: number | boolean) => void
87
97
  call: (id: string, name: Callable) => Promise<void>
88
98
  }
89
99
 
@@ -114,7 +124,7 @@ const pairs = (ranges: TimeRangesLike | undefined): [number, number][] => {
114
124
  }
115
125
 
116
126
  /** A media as a snapshot. A NaN duration, which a bare element answers before it has metadata, is sent as 0. */
117
- export const snapshotOf = (media: PlayerMedia): PlayerSnapshot => ({
127
+ export const snapshotOf = (media: PlayerMedia, chapters: MediaChapter[] = []): PlayerSnapshot => ({
118
128
  currentTime: finite(media.currentTime),
119
129
  duration: finite(media.duration),
120
130
  paused: media.paused,
@@ -131,6 +141,7 @@ export const snapshotOf = (media: PlayerMedia): PlayerSnapshot => ({
131
141
  error: media.error ? { code: media.error.code, message: media.error.message } : null,
132
142
  videoWidth: media.videoWidth ?? 0,
133
143
  videoHeight: media.videoHeight ?? 0,
144
+ chapters,
134
145
  })
135
146
 
136
147
  // NaN only. A live media reports `duration: Infinity` and means it, so sending 0 for it would mirror
@@ -141,7 +152,7 @@ const finite = (value: number): number => Number.isNaN(value) ? 0 : value
141
152
  export const EMPTY_SNAPSHOT: PlayerSnapshot = {
142
153
  currentTime: 0, duration: 0, paused: true, ended: false, seeking: false, readyState: 0,
143
154
  volume: 1, muted: false, playbackRate: 1, src: '', currentSrc: '',
144
- buffered: [], seekable: [], error: null, videoWidth: 0, videoHeight: 0,
155
+ buffered: [], seekable: [], error: null, videoWidth: 0, videoHeight: 0, chapters: [],
145
156
  }
146
157
 
147
158
  /** Plain pairs back into the structural `TimeRanges` the player reads. */