@banou/media-player 0.10.30 → 0.10.31

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.
Files changed (52) hide show
  1. package/README.md +20 -0
  2. package/dist/de-DphEdq0O.js +52 -0
  3. package/dist/engine/index.js +1 -1
  4. package/dist/{engine-DeEY2qao.js → engine-5XbZqrD3.js} +213 -162
  5. package/dist/es-419-D6gsvnn8.js +52 -0
  6. package/dist/fr-BqAzAJX0.js +52 -0
  7. package/dist/index.js +931 -844
  8. package/dist/it-NTcUh3Gr.js +52 -0
  9. package/dist/ja-DSmX_bxj.js +52 -0
  10. package/dist/ko-DyPzWasj.js +52 -0
  11. package/dist/labels.d.ts +71 -0
  12. package/dist/pl-C6Ow4ra5.js +52 -0
  13. package/dist/pt-BR-wudK3giz.js +52 -0
  14. package/dist/react/labels.d.ts +28 -0
  15. package/dist/react/video-player.d.ts +9 -0
  16. package/dist/ru-D5kxBkik.js +52 -0
  17. package/dist/tr-CW7R7N9k.js +52 -0
  18. package/dist/utils/track-label.d.ts +9 -8
  19. package/dist/zh-Hans-IhL1Pl78.js +52 -0
  20. package/dist/zh-Hant-C5YyFjEc.js +52 -0
  21. package/package.json +3 -1
  22. package/src/lib/engine/playback.ts +6 -5
  23. package/src/lib/engine/source-buffer.ts +3 -1
  24. package/src/lib/labels.ts +75 -0
  25. package/src/lib/locales/de.json +49 -0
  26. package/src/lib/locales/es-419.json +49 -0
  27. package/src/lib/locales/fr.json +49 -0
  28. package/src/lib/locales/it.json +49 -0
  29. package/src/lib/locales/ja.json +49 -0
  30. package/src/lib/locales/ko.json +49 -0
  31. package/src/lib/locales/pl.json +49 -0
  32. package/src/lib/locales/pt-BR.json +49 -0
  33. package/src/lib/locales/ru.json +49 -0
  34. package/src/lib/locales/tr.json +49 -0
  35. package/src/lib/locales/zh-Hans.json +49 -0
  36. package/src/lib/locales/zh-Hant.json +49 -0
  37. package/src/lib/react/components/burn-in-hint.tsx +4 -1
  38. package/src/lib/react/components/chrome.tsx +9 -0
  39. package/src/lib/react/components/control-bar.tsx +15 -26
  40. package/src/lib/react/components/errors.tsx +11 -9
  41. package/src/lib/react/components/overlay.tsx +18 -5
  42. package/src/lib/react/components/playback-slider.tsx +4 -1
  43. package/src/lib/react/components/settings.tsx +23 -31
  44. package/src/lib/react/components/skip-chapter.tsx +5 -2
  45. package/src/lib/react/components/sound.tsx +5 -2
  46. package/src/lib/react/components/subtitles.tsx +7 -4
  47. package/src/lib/react/components/track-menu.tsx +8 -4
  48. package/src/lib/react/components/volume-slider.tsx +3 -1
  49. package/src/lib/react/hooks/use-playback.ts +12 -2
  50. package/src/lib/react/labels.tsx +125 -0
  51. package/src/lib/react/video-player.tsx +14 -1
  52. package/src/lib/utils/track-label.ts +16 -11
@@ -3,6 +3,8 @@ import { css } from '@emotion/react'
3
3
  import { Captions, CaptionsOff } from 'lucide-react'
4
4
 
5
5
  import { usePlayer } from '../player'
6
+ import { useLabels } from '../labels'
7
+ import { LABELS } from '../../labels'
6
8
  import { TooltipDisplay } from './tooltip-display'
7
9
  import { TrackMenu, popoverStyle, useTrackMenu } from './track-menu'
8
10
 
@@ -33,6 +35,7 @@ ${popoverStyle}
33
35
  * on a source that owns its own player it is slow enough to be a considered act.
34
36
  */
35
37
  export const SubtitlesAction = () => {
38
+ const { format } = useLabels()
36
39
  const subtitleTracks = usePlayer((state) => state.subtitleTracks)
37
40
  const selectedSubtitleTrack = usePlayer((state) => state.selectedSubtitleTrack)
38
41
  const selectSubtitleTrack = usePlayer((state) => state.selectSubtitleTrack)
@@ -58,23 +61,23 @@ export const SubtitlesAction = () => {
58
61
  className='subtitles'
59
62
  type='button'
60
63
  onClick={toggle}
61
- aria-label='Subtitles'
64
+ aria-label={format(LABELS.subtitles)}
62
65
  aria-expanded={open}
63
66
  aria-pressed={on}
64
67
  >
65
68
  {on ? <Captions className='captions' /> : <CaptionsOff className='captions-off' />}
66
69
  </button>
67
70
  }
68
- toolTipText={<span>Subtitles</span>}
71
+ toolTipText={<span>{format(LABELS.subtitles)}</span>}
69
72
  />
70
73
  {
71
74
  open && (
72
75
  <TrackMenu
73
- title='Subtitles'
76
+ title={format(LABELS.subtitles)}
74
77
  tracks={subtitleTracks}
75
78
  selected={selectedSubtitleTrack}
76
79
  onSelect={(id) => runSelect(id ?? null, () => selectSubtitleTrack(id))}
77
- offLabel={subtitleOffLabel ?? 'Disable'}
80
+ offLabel={subtitleOffLabel ?? format(LABELS.subtitlesOff)}
78
81
  pending={pending}
79
82
  failed={failed}
80
83
  />
@@ -6,6 +6,8 @@ import { css } from '@emotion/react'
6
6
  import { ChevronLeft } from 'lucide-react'
7
7
 
8
8
  import { fonts } from '../../utils/fonts'
9
+ import { useLabels } from '../labels'
10
+ import { LABELS } from '../../labels'
9
11
 
10
12
  /**
11
13
  * The popover surface and the track rows, shared by every menu in the control bar.
@@ -36,9 +38,10 @@ export const popoverStyle = css`
36
38
  once subtitles moved out to its own button, and a long track list scrolls at the cap either way. */
37
39
  height: max-content;
38
40
  /* The room actually above the bar. A short player had the top of the menu clipped by that same
39
- \`overflow: hidden\`. With no size container in the ancestry this resolves against the small
40
- viewport, so it can only ever shrink the box, never grow it. */
41
- max-height: min(160px, calc(100cqh - 100% - 16px));
41
+ \`overflow: hidden\`. \`--mp-height\` is the player's own height, which the chrome writes: with no
42
+ size container in the ancestry \`100cqh\` is the small viewport's, and a translated menu whose rows
43
+ wrap reached the cap and rose 2px past a phone's 220px tall player. */
44
+ max-height: min(160px, calc(var(--mp-height, 100cqh) - 100% - 16px));
42
45
  @media (min-width: 768px) {
43
46
  right: calc(16px + env(safe-area-inset-right, 0px));
44
47
  width: 250px;
@@ -166,6 +169,7 @@ export const TrackMenu = (
166
169
  failed?: boolean
167
170
  }
168
171
  ) => {
172
+ const { format } = useLabels()
169
173
  const busy = pending !== undefined
170
174
  const row = (id: string | number | null, label: string, className?: string) => {
171
175
  const isPending = busy && pending === id
@@ -190,7 +194,7 @@ export const TrackMenu = (
190
194
  {onBack ? <ChevronLeft /> : null}
191
195
  <span>{title}</span>
192
196
  </div>
193
- {failed ? <div className="no-hover failed">Could not switch. Try again.</div> : null}
197
+ {failed ? <div className="no-hover failed">{format(LABELS.switchFailed)}</div> : null}
194
198
  {offLabel ? row(null, offLabel) : null}
195
199
  {tracks.map(({ id, label }) => row(id, label, 'description'))}
196
200
  </div>
@@ -4,6 +4,7 @@ import { css } from '@emotion/react'
4
4
 
5
5
  import { TooltipDisplay } from './tooltip-display'
6
6
  import { usePlayer } from '../player'
7
+ import { useLabels } from '../labels'
7
8
  import { useDragValue } from '../hooks/use-drag-value'
8
9
  import { logToLinearVolume } from '../../utils/volume-utils'
9
10
 
@@ -58,6 +59,7 @@ type VolumeSliderType = {
58
59
  }
59
60
 
60
61
  export const VolumeSlider = ({ value, onChange }: VolumeSliderType) => {
62
+ const { number } = useLabels()
61
63
  const volume = usePlayer((state) => state.volume)
62
64
  const muted = usePlayer((state) => state.muted)
63
65
 
@@ -132,7 +134,7 @@ export const VolumeSlider = ({ value, onChange }: VolumeSliderType) => {
132
134
  }
133
135
  toolTipText={
134
136
  <div className='volume-value'>
135
- {displayVolumePercent}%
137
+ {number(displayVolumePercent / 100, { style: 'percent' })}
136
138
  </div>
137
139
  }
138
140
  />
@@ -6,6 +6,7 @@ import { useCallback, useEffect, useRef, useState } from 'react'
6
6
 
7
7
  import { isMediaElementError, startPlayback } from '../../engine'
8
8
  import { usePlayer } from '../player'
9
+ import { useLabels } from '../labels'
9
10
  import { toNamedTracks } from '../../utils/track-label'
10
11
  import { languageOf, preferredTrack } from '../../language'
11
12
 
@@ -169,6 +170,15 @@ export const usePlayback = (
169
170
  onPlaybackErrorRef.current = options?.onPlaybackError
170
171
  const onOutputRef = useRef(onOutput)
171
172
  onOutputRef.current = onOutput
173
+ const labels = useLabels()
174
+ const labelsRef = useRef(labels)
175
+ labelsRef.current = labels
176
+ // named again when the labels change, as they do when a catalogue arrives after the streams
177
+ useEffect(() => {
178
+ const { audio, subtitles } = streams.current
179
+ if (subtitles.length) player.setSourceState({ subtitleTracks: toNamedTracks(subtitles, labels) })
180
+ if (audio.length) player.setSourceState({ audioTracks: toNamedTracks(audio, labels) })
181
+ }, [player, labels])
172
182
 
173
183
  // The store's ids are opaque, but everything this hook writes into it came from libav, so every id
174
184
  // that comes back is one of its own stream indices.
@@ -395,14 +405,14 @@ export const usePlayback = (
395
405
  if (cancelled) return
396
406
  streams.current.subtitles = subtitles
397
407
  player.setSourceState({
398
- subtitleTracks: toNamedTracks(subtitles),
408
+ subtitleTracks: toNamedTracks(subtitles, labelsRef.current),
399
409
  ...subtitleChoiceFor.current === size ? {} : { selectedSubtitleTrack: preferredSubtitle(preferredSubtitleRef.current, subtitles) },
400
410
  })
401
411
  },
402
412
  onAudioStreams: (audio, selected) => {
403
413
  if (cancelled) return
404
414
  streams.current.audio = audio
405
- player.setSourceState({ audioTracks: toNamedTracks(audio), selectedAudioTrack: selected })
415
+ player.setSourceState({ audioTracks: toNamedTracks(audio, labelsRef.current), selectedAudioTrack: selected })
406
416
  },
407
417
  })
408
418
  if (cancelled) {
@@ -0,0 +1,125 @@
1
+ import type { IntlShape } from '@formatjs/intl'
2
+ import type { ReactNode } from 'react'
3
+ import type { Label, LabelValues } from '../labels'
4
+
5
+ import { createContext, useContext, useEffect, useMemo, useState } from 'react'
6
+
7
+ import { fill } from '../labels'
8
+
9
+ type Catalogue = Readonly<Record<string, string>>
10
+
11
+ // One chunk per language, fetched with FormatJS by the first player shown in it, so a player in English loads neither.
12
+ const CATALOGUES: Readonly<Record<string, () => Promise<{ default: Catalogue }>>> = {
13
+ 'de': () => import('../locales/de.json'),
14
+ 'es-419': () => import('../locales/es-419.json'),
15
+ 'fr': () => import('../locales/fr.json'),
16
+ 'it': () => import('../locales/it.json'),
17
+ 'ja': () => import('../locales/ja.json'),
18
+ 'ko': () => import('../locales/ko.json'),
19
+ 'pl': () => import('../locales/pl.json'),
20
+ 'pt-BR': () => import('../locales/pt-BR.json'),
21
+ 'ru': () => import('../locales/ru.json'),
22
+ 'tr': () => import('../locales/tr.json'),
23
+ 'zh-Hans': () => import('../locales/zh-Hans.json'),
24
+ 'zh-Hant': () => import('../locales/zh-Hant.json'),
25
+ }
26
+
27
+ /** The languages the labels are written in besides English, one catalogue each. */
28
+ export const LANGUAGES: readonly string[] = Object.keys(CATALOGUES)
29
+
30
+ const parts = (tag: string) => {
31
+ try {
32
+ const locale = new Intl.Locale(tag)
33
+ const { language, script } = locale.maximize()
34
+ return { tag: locale.baseName, language, script }
35
+ } catch {
36
+ return undefined
37
+ }
38
+ }
39
+
40
+ /**
41
+ * The catalogue serving `language`, a BCP 47 tag: its own, else the one of its language and script once maximized
42
+ * (`es-MX` finds `es-419`, `pt-PT` finds `pt-BR`, `zh-TW` finds `zh-Hant`), else one of its language. Undefined for
43
+ * English and for a language with none.
44
+ */
45
+ export const catalogueFor = (language: string) => {
46
+ const wanted = parts(language)
47
+ if (!wanted) return undefined
48
+ const offered = LANGUAGES.map((tag) => ({ ...parts(tag)!, catalogue: tag }))
49
+ return (
50
+ offered.find(({ tag }) => tag === wanted.tag)
51
+ ?? offered.find(({ language, script }) => language === wanted.language && script === wanted.script)
52
+ ?? offered.find(({ language }) => language === wanted.language)
53
+ )?.catalogue
54
+ }
55
+
56
+ const loaded = new Map<string, IntlShape>()
57
+ const loading = new Map<string, Promise<IntlShape>>()
58
+
59
+ const load = (language: string, catalogue: string) => {
60
+ let pending = loading.get(language)
61
+ if (!pending) {
62
+ pending = Promise.all([import('@formatjs/intl'), CATALOGUES[catalogue]!()])
63
+ .then(([{ createIntl }, { default: messages }]) => {
64
+ const intl = createIntl({ locale: language, defaultLocale: 'en', messages })
65
+ loaded.set(language, intl)
66
+ return intl
67
+ })
68
+ // the next player asks again
69
+ pending.catch(() => loading.delete(language))
70
+ loading.set(language, pending)
71
+ }
72
+ return pending
73
+ }
74
+
75
+ /** The chrome's text in the language of the player around it. */
76
+ export type Labels = {
77
+ /** `label` in the player's language, with its values filled in. */
78
+ format: <L extends Label>(label: L, ...values: LabelValues<L>) => string
79
+ /** A number as `locale` writes it, as English does when it is undefined. */
80
+ number: (value: number, options?: Intl.NumberFormatOptions) => string
81
+ /**
82
+ * The tag the player was given, which its numbers and track languages are written in even when no catalogue serves
83
+ * it: `en` when Intl cannot read it, undefined when it was given none.
84
+ */
85
+ locale: string | undefined
86
+ }
87
+
88
+ // a tag Intl cannot read makes every formatter given it throw
89
+ const readable = (tag: string) => {
90
+ try {
91
+ return Intl.getCanonicalLocales(tag)[0]
92
+ } catch {
93
+ return undefined
94
+ }
95
+ }
96
+
97
+ const labelsOf = (intl: IntlShape | undefined, language: string | undefined): Labels => {
98
+ const locale = language ? readable(language) ?? 'en' : undefined
99
+ return {
100
+ format: (label, ...[values]) => intl ? intl.formatMessage({ id: label, defaultMessage: label }, values) : fill(label, values),
101
+ number: (value, options) => new Intl.NumberFormat(locale ?? 'en', options).format(value),
102
+ locale,
103
+ }
104
+ }
105
+
106
+ const ENGLISH = labelsOf(undefined, undefined)
107
+ const LabelsContext = createContext(ENGLISH)
108
+
109
+ export const useLabels = () => useContext(LabelsContext)
110
+
111
+ /** The labels of a player given `language`: English at once, then its catalogue's once that has loaded. */
112
+ export const LabelsProvider = ({ language, children }: { language?: string, children: ReactNode }) => {
113
+ const catalogue = language ? catalogueFor(language) : undefined
114
+ // the cache is what is read, this only renders again once it holds the language
115
+ const [, setLoaded] = useState<IntlShape>()
116
+ useEffect(() => {
117
+ if (!language || !catalogue || loaded.has(language)) return
118
+ let dropped = false
119
+ load(language, catalogue).then((intl) => { if (!dropped) setLoaded(intl) }, () => {})
120
+ return () => { dropped = true }
121
+ }, [language, catalogue])
122
+ const intl = language && catalogue ? loaded.get(language) : undefined
123
+ const labels = useMemo(() => language ? labelsOf(intl, language) : ENGLISH, [intl, language])
124
+ return <LabelsContext.Provider value={labels}>{children}</LabelsContext.Provider>
125
+ }
@@ -18,6 +18,7 @@ import { usePassThroughPictureInPicture } from './hooks/use-pass-through-picture
18
18
  import { useVolumeNormalizer } from './hooks/use-volume-normalizer'
19
19
  import { createPlaybackTap } from '../audio/playback-tap'
20
20
  import Chrome from './components/chrome'
21
+ import { LabelsProvider } from './labels'
21
22
  import { languageOf } from '../language'
22
23
 
23
24
  /**
@@ -94,6 +95,16 @@ type CommonOptions = {
94
95
  */
95
96
  controls?: boolean
96
97
 
98
+ /**
99
+ * The language of the player's own labels (the controls, tooltips, menus, skip offers and failures), a BCP 47 tag
100
+ * such as the host page shows (`fr`, `es-MX`, `zh-TW`). The labels are shown in the closest language the player has,
101
+ * the numbers in them written as this tag writes them, and track languages named in it, even when the labels are
102
+ * English (`en-DE` writes `0,5x`). A language's text loads the first time a player shows it, and the labels are
103
+ * English until it has. Without it, or for a language the player does not have, they are English and nothing more is
104
+ * loaded; without it, track languages are named in the browser's.
105
+ */
106
+ language?: string
107
+
97
108
  /**
98
109
  * Where the keyboard shortcuts listen. `'window'`, the default, takes keys from the whole page, which suits a
99
110
  * page that is only the player. `'player'` takes a key only when the focus is inside the player (a click on the
@@ -652,7 +663,9 @@ const rootStyle = css`
652
663
  export const MediaPlayer = (options: MediaPlayerOptions & { children?: ReactNode }) => (
653
664
  <div css={rootStyle}>
654
665
  <Player.Provider>
655
- <PlayerRoot options={options}>{options.children}</PlayerRoot>
666
+ <LabelsProvider language={options.language}>
667
+ <PlayerRoot options={options}>{options.children}</PlayerRoot>
668
+ </LabelsProvider>
656
669
  </Player.Provider>
657
670
  </div>
658
671
  )
@@ -1,3 +1,7 @@
1
+ import type { Labels } from '../react/labels'
2
+
3
+ import { LABELS, fill } from '../labels'
4
+
1
5
  export type LabelledTrack = {
2
6
  streamIndex: number
3
7
  title: string
@@ -11,13 +15,13 @@ export type NamedTrack = {
11
15
  }
12
16
 
13
17
  /**
14
- * Human name for a track's language tag. `fallback: 'none'` is what makes an unknown tag come back
15
- * undefined instead of echoing itself, so the caller can fall through to the title.
18
+ * Human name for a track's language tag, in `locale`, else in the browser's language. `fallback: 'none'` is what makes
19
+ * an unknown tag come back undefined instead of echoing itself, so the caller can fall through to the title.
16
20
  */
17
- export const displayLanguage = (language: string | undefined): string | undefined => {
21
+ export const displayLanguage = (language: string | undefined, locale?: string): string | undefined => {
18
22
  if (!language || language === 'und') return undefined
19
23
  try {
20
- return new Intl.DisplayNames([navigator.language || 'en'], { type: 'language', fallback: 'none' }).of(language) || undefined
24
+ return new Intl.DisplayNames([locale ?? (navigator.language || 'en')], { type: 'language', fallback: 'none' }).of(language) || undefined
21
25
  } catch {
22
26
  return undefined
23
27
  }
@@ -26,12 +30,13 @@ export const displayLanguage = (language: string | undefined): string | undefine
26
30
  const tidy = (title: string | undefined) => title?.replace(/_/g, ' ').trim() || undefined
27
31
 
28
32
  /**
29
- * Names a set of tracks for a menu, by language, falling back to the title then the stream index.
30
- * The title is appended only to break a tie, because on a MultiSub release every title is the same
31
- * source tag and titling every row gives nine identical entries.
33
+ * Names a set of tracks for a menu, by language, falling back to the title then the stream index, in the language of
34
+ * `labels` (English without). The title is appended only to break a tie, because on a MultiSub release every title is
35
+ * the same source tag and titling every row gives nine identical entries.
32
36
  */
33
- export const labelTracks = <T extends LabelledTrack>(tracks: T[]): { track: T, label: string }[] => {
34
- const bases = tracks.map((track) => displayLanguage(track.language) ?? tidy(track.title) ?? `Track ${track.streamIndex}`)
37
+ export const labelTracks = <T extends LabelledTrack>(tracks: T[], labels?: Labels): { track: T, label: string }[] => {
38
+ const untitled = (number: number) => labels ? labels.format(LABELS.track, { number }) : fill(LABELS.track, { number })
39
+ const bases = tracks.map((track) => displayLanguage(track.language, labels?.locale) ?? tidy(track.title) ?? untitled(track.streamIndex))
35
40
  const counts = bases.reduce<Record<string, number>>((acc, base) => ({ ...acc, [base]: (acc[base] ?? 0) + 1 }), {})
36
41
  return tracks.map((track, index) => {
37
42
  const base = bases[index]!
@@ -47,5 +52,5 @@ export const labelTracks = <T extends LabelledTrack>(tracks: T[]): { track: T, l
47
52
  * The store's ids are opaque so a source that owns its own player can use its own track ids; the id
48
53
  * here is the libav stream index, which is what this half of the code has to say.
49
54
  */
50
- export const toNamedTracks = <T extends LabelledTrack>(tracks: T[]): NamedTrack[] =>
51
- labelTracks(tracks).map(({ track, label }) => ({ id: track.streamIndex, label }))
55
+ export const toNamedTracks = <T extends LabelledTrack>(tracks: T[], labels?: Labels): NamedTrack[] =>
56
+ labelTracks(tracks, labels).map(({ track, label }) => ({ id: track.streamIndex, label }))