@mattebox/player 0.9.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/dist/announcer.d.ts +7 -0
  2. package/dist/announcer.d.ts.map +1 -0
  3. package/dist/announcer.js +44 -0
  4. package/dist/announcer.js.map +1 -0
  5. package/dist/cdn/mattebox-player.min.js +3 -3
  6. package/dist/controls/cues.d.ts.map +1 -1
  7. package/dist/controls/cues.js +11 -5
  8. package/dist/controls/cues.js.map +1 -1
  9. package/dist/controls/menu.d.ts +9 -0
  10. package/dist/controls/menu.d.ts.map +1 -1
  11. package/dist/controls/menu.js +57 -14
  12. package/dist/controls/menu.js.map +1 -1
  13. package/dist/element.d.ts +17 -0
  14. package/dist/element.d.ts.map +1 -1
  15. package/dist/element.js +71 -1
  16. package/dist/element.js.map +1 -1
  17. package/dist/elements/audio-menu.js +1 -1
  18. package/dist/elements/drm-badge.js +2 -2
  19. package/dist/elements/menu-element.d.ts.map +1 -1
  20. package/dist/elements/menu-element.js +3 -2
  21. package/dist/elements/menu-element.js.map +1 -1
  22. package/dist/elements/seek-bar.js +1 -1
  23. package/dist/elements/shared.js +1 -1
  24. package/dist/elements/skip-button.js +1 -1
  25. package/dist/elements/start-button.d.ts +7 -4
  26. package/dist/elements/start-button.d.ts.map +1 -1
  27. package/dist/elements/start-button.js +9 -6
  28. package/dist/elements/start-button.js.map +1 -1
  29. package/dist/elements/subtitles-menu.js +1 -1
  30. package/dist/es2015/_virtual/{_@oxc-project_runtime@0.152.0 → _@oxc-project_runtime@0.154.0}/helpers/esm/asyncToGenerator.js +1 -1
  31. package/dist/es2015/_virtual/{_@oxc-project_runtime@0.152.0 → _@oxc-project_runtime@0.154.0}/helpers/esm/defineProperty.js +1 -1
  32. package/dist/es2015/_virtual/{_@oxc-project_runtime@0.152.0 → _@oxc-project_runtime@0.154.0}/helpers/esm/objectSpread2.js +1 -1
  33. package/dist/es2015/_virtual/{_@oxc-project_runtime@0.152.0 → _@oxc-project_runtime@0.154.0}/helpers/esm/toPrimitive.js +1 -1
  34. package/dist/es2015/_virtual/{_@oxc-project_runtime@0.152.0 → _@oxc-project_runtime@0.154.0}/helpers/esm/toPropertyKey.js +1 -1
  35. package/dist/es2015/_virtual/{_@oxc-project_runtime@0.152.0 → _@oxc-project_runtime@0.154.0}/helpers/esm/typeof.js +1 -1
  36. package/dist/es2015/announcer.js +43 -0
  37. package/dist/es2015/controls/chapters.js +1 -1
  38. package/dist/es2015/controls/cues.js +11 -5
  39. package/dist/es2015/controls/menu.js +62 -17
  40. package/dist/es2015/element.js +79 -5
  41. package/dist/es2015/elements/audio-menu.js +1 -1
  42. package/dist/es2015/elements/drm-badge.js +2 -2
  43. package/dist/es2015/elements/menu-element.js +3 -2
  44. package/dist/es2015/elements/seek-bar.js +1 -1
  45. package/dist/es2015/elements/shared.js +1 -1
  46. package/dist/es2015/elements/skip-button.js +1 -1
  47. package/dist/es2015/elements/start-button.js +9 -6
  48. package/dist/es2015/elements/subtitles-menu.js +1 -1
  49. package/dist/es2015/presets.js +1 -1
  50. package/dist/es2015/style.js +1 -1
  51. package/dist/style.js +1 -1
  52. package/package.json +4 -4
@@ -2,9 +2,10 @@
2
2
  /**
3
3
  * Subtitles and the bar. Two things.
4
4
  *
5
- * The lift: the browser draws native cues at the bottom of the video, under
6
- * the bar. While the bar shows, every active cue the author left
7
- * unpositioned is moved above it, and put back when the bar hides. The
5
+ * The lift: the browser draws native cues on the bottom edge of the video,
6
+ * and under the bar. Every active cue the author left unpositioned is
7
+ * moved up: above the bar while it shows, and one line off the edge while
8
+ * it is hidden, so the text never sits on the picture's border. The
8
9
  * position is a negative line count, the one form every browser wraps at
9
10
  * the video's width; a percentage does not wrap in Chromium. Chromium
10
11
  * anchors the box's top on the count and Gecko its bottom, and their
@@ -43,6 +44,8 @@ const LINE_HEIGHT = 1.2;
43
44
  const CUE_WIDTH = .96;
44
45
  /** Pixels of air between the bar and the cue above it, before rounding up to a line. */
45
46
  const AIR = 6;
47
+ /** Lines of air under a cue while the bar is hidden. */
48
+ const REST = 1;
46
49
  /** Puts the cue rules in the document, once. */
47
50
  function cueStyle() {
48
51
  if (document.head.querySelector(`style[${MARK}]`) !== null) return;
@@ -55,6 +58,8 @@ function cueLift(video, host, covered) {
55
58
  /** The cues moved, with what they were, so they and only they are put back. */
56
59
  const lifted = /* @__PURE__ */ new Map();
57
60
  let on = false;
61
+ /** False once disposed: the cues go back to where the author left them. */
62
+ let live = true;
58
63
  let canvas;
59
64
  function showing() {
60
65
  const out = [];
@@ -103,10 +108,10 @@ function cueLift(video, host, covered) {
103
108
  const height = box.height;
104
109
  const span = covered();
105
110
  const pixels = span.bottom - span.top;
106
- const lift = on && height > 0 && pixels > 0 && pixels < height;
111
+ const lift = live && height > 0;
107
112
  const font = fontSize(height);
108
113
  const unit = font * LINE_HEIGHT;
109
- const base = Math.ceil((pixels + AIR) / unit);
114
+ const base = on && pixels > 0 && pixels < height ? Math.ceil((pixels + AIR) / unit) : REST;
110
115
  for (const track of showing()) {
111
116
  const active = [...track.activeCues ?? []].filter((cue) => cue instanceof VTTCue).sort((a, b) => a.startTime - b.startTime);
112
117
  let previous = null;
@@ -161,6 +166,7 @@ function cueLift(video, host, covered) {
161
166
  },
162
167
  dispose() {
163
168
  on = false;
169
+ live = false;
164
170
  apply();
165
171
  video.textTracks.removeEventListener("change", watch);
166
172
  video.textTracks.removeEventListener("addtrack", watch);
@@ -1 +1 @@
1
- {"version":3,"file":"cues.js","names":[],"sources":["../../src/controls/cues.ts"],"sourcesContent":["/**\n * Subtitles and the bar. Two things.\n *\n * The lift: the browser draws native cues at the bottom of the video, under\n * the bar. While the bar shows, every active cue the author left\n * unpositioned is moved above it, and put back when the bar hides. The\n * position is a negative line count, the one form every browser wraps at\n * the video's width; a percentage does not wrap in Chromium. Chromium\n * anchors the box's top on the count and Gecko its bottom, and their\n * overlap avoidance pushes in opposite directions, so nothing is left to\n * them: subtitles often show two cues at once, and the cues stack by their\n * own measured heights, wrapping included, clear under both readings. A\n * cue with a position of its own is the author's and is not touched.\n *\n * The look: `::cue` can only be styled from the document that holds the\n * video, which is the page and not the shadow root, and it takes no custom\n * properties. So a small sheet goes into the document, once, with one rule\n * per look the host's `subtitle-size` and `subtitle-background` attributes\n * can take. Sizes are percentages of the browser's own cue size, which\n * already follows the video's height, in the page and in fullscreen alike.\n * A page that wants more writes its own `mattebox-player > video::cue`.\n */\nimport CUE_RULES from './cues.css?inline';\n/** How the sizes scale the browser's own cue size; the lift counts lines by it. */\nexport const SCALES: Readonly<Record<string, number>> = {\n small: 0.75,\n medium: 1,\n large: 1.5,\n xlarge: 2,\n};\n\n/**\n * The sheet in the document. `mattebox-player` is the element's tag. The\n * background goes on `::cue` and on the backdrop pseudo-element Chromium\n * and WebKit have, both: which of the two paints it differs by browser and\n * version, and a selector a browser does not know only voids its own rule.\n */\n\nconst MARK = 'data-mattebox-cue';\n\n/** The browser's cue size against the video's height, per WebVTT, and its line against the size. */\nconst CUE_SIZE = 0.05;\nconst LINE_HEIGHT = 1.2;\n/** What a cue box spans of the video's width by default, so wrapping is measured against it. */\nconst CUE_WIDTH = 0.96;\n/** Pixels of air between the bar and the cue above it, before rounding up to a line. */\nconst AIR = 6;\n\n/** Puts the cue rules in the document, once. */\nexport function cueStyle(): void {\n if (document.head.querySelector(`style[${MARK}]`) !== null) return;\n const style = document.createElement('style');\n style.setAttribute(MARK, '');\n style.textContent = CUE_RULES;\n document.head.append(style);\n}\n\n/** What a lifted cue looked like before, to put back. */\ninterface Placed {\n readonly line: number | 'auto';\n readonly snapToLines: boolean;\n readonly lineAlign: LineAlignSetting;\n}\n\nexport interface CueLift {\n /** Whether the bar is showing, so the cues move above it or back. */\n lifted(on: boolean): void;\n dispose(): void;\n}\n\n/** What the bar covers of the picture: from its first row's top, not its gradient run-in, to its bottom. */\nexport type Covered = () => { readonly top: number; readonly bottom: number };\n\nexport function cueLift(video: HTMLVideoElement, host: HTMLElement, covered: Covered): CueLift {\n /** The cues moved, with what they were, so they and only they are put back. */\n const lifted = new Map<VTTCue, Placed>();\n let on = false;\n let canvas: CanvasRenderingContext2D | null | undefined;\n\n function showing(): TextTrack[] {\n const out: TextTrack[] = [];\n for (const track of video.textTracks) if (track.mode === 'showing') out.push(track);\n return out;\n }\n\n /** The browser's cue font size, in pixels, from the video's height and the host's scale. */\n function fontSize(height: number): number {\n const scale = SCALES[host.getAttribute('subtitle-size') ?? ''] ?? 1;\n return height * CUE_SIZE * scale;\n }\n\n /** Measures text the way the browser draws cues, to count the lines a cue wraps into. */\n function measure(): CanvasRenderingContext2D | null {\n if (canvas === undefined) canvas = document.createElement('canvas').getContext('2d');\n return canvas;\n }\n\n /**\n * A cue's text without its tags, for measuring: `<b>`, `<c.name>`, the\n * timestamps and their closers. Brackets are counted, so a tag inside\n * another's brackets goes with it.\n */\n function plain(text: string): string {\n let out = '';\n let depth = 0;\n for (const char of text) {\n if (char === '<') depth += 1;\n else if (char === '>') depth = Math.max(0, depth - 1);\n else if (depth === 0) out += char;\n }\n return out;\n }\n\n /** The lines a cue takes: its own, each wrapped at the cue box's width. */\n function lines(cue: VTTCue, font: number, width: number): number {\n const context = measure();\n let total = 0;\n for (const line of plain(cue.text).split('\\n')) {\n if (context === null) {\n total += 1;\n continue;\n }\n context.font = `${font}px sans-serif`;\n total += Math.max(1, Math.ceil(context.measureText(line).width / (width * CUE_WIDTH)));\n }\n return total;\n }\n\n function apply(): void {\n const box = video.getBoundingClientRect();\n const height = box.height;\n const span = covered();\n const pixels = span.bottom - span.top;\n const lift = on && height > 0 && pixels > 0 && pixels < height;\n const font = fontSize(height);\n const unit = font * LINE_HEIGHT;\n // The lines the bar covers, with a little air, rounded up to whole lines.\n const base = Math.ceil((pixels + AIR) / unit);\n for (const track of showing()) {\n // Earliest first, the order the browser stacks them in, so the first\n // sits lowest and the rest climb.\n const active = [...(track.activeCues ?? [])]\n .filter((cue): cue is VTTCue => cue instanceof VTTCue)\n .sort((a, b) => a.startTime - b.startTime);\n let previous: { line: number; height: number } | null = null;\n let changed = false;\n for (const cue of active) {\n const was = lifted.get(cue);\n if (!lift) {\n if (was === undefined) continue;\n cue.line = was.line;\n cue.snapToLines = was.snapToLines;\n cue.lineAlign = was.lineAlign;\n lifted.delete(cue);\n changed = true;\n continue;\n }\n // The author's own placement is the author's.\n if (was === undefined && cue.line !== 'auto') continue;\n if (was === undefined) {\n lifted.set(cue, {\n line: cue.line,\n snapToLines: cue.snapToLines,\n lineAlign: cue.lineAlign,\n });\n }\n // A negative line count, which every browser wraps at the video's\n // width, unlike a percentage. Chromium anchors the box's top on it\n // and Gecko its bottom, so the count clears the bar and the cue\n // below under both readings, with a little air to spare in one.\n const own = lines(cue, font, box.width);\n const line: number =\n previous === null ? base + own : previous.line + Math.max(own, previous.height);\n if (cue.line !== -line || !cue.snapToLines) changed = true;\n cue.snapToLines = true;\n cue.line = -line;\n previous = { line, height: own };\n }\n // Chromium lays a changed line out again only when the track's display\n // is rebuilt, which neither time nor a seek does for a cue already\n // showing; the mode flipped off and on in one task rebuilds it with no\n // paint in between. Only on a change, so the change event this fires\n // finds nothing to do and the loop ends there.\n if (changed) {\n track.mode = 'hidden';\n track.mode = 'showing';\n }\n }\n }\n\n function watch(): void {\n for (const track of video.textTracks) {\n track.removeEventListener('cuechange', apply);\n track.addEventListener('cuechange', apply);\n }\n apply();\n }\n\n video.textTracks.addEventListener('change', watch);\n video.textTracks.addEventListener('addtrack', watch);\n watch();\n\n return {\n lifted(next: boolean): void {\n on = next;\n apply();\n },\n dispose(): void {\n on = false;\n apply();\n video.textTracks.removeEventListener('change', watch);\n video.textTracks.removeEventListener('addtrack', watch);\n for (const track of video.textTracks) track.removeEventListener('cuechange', apply);\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAsBA,MAAA,YAAA;;AAEA,MAAA,SAAA;CACA,OAAA;CACA,QAAA;CACA,OAAA;CACA,QAAA;AACA;;;;;;;AASA,MAAA,OAAA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AA;GACA;EACA;CACA;CAEA,SAAA,QAAA;EACA,KAAA,MAAA,SAAA,MAAA,YAAA;GACA,MAAA,oBAAA,aAAA,KAAA;GACA,MAAA,iBAAA,aAAA,KAAA;EACA;EACA,MAAA;CACA;CAEA,MAAA,WAAA,iBAAA,UAAA,KAAA;CACA,MAAA,WAAA,iBAAA,YAAA,KAAA;CACA,MAAA;CAEA,OAAA;EACA,OAAA,MAAA;GACA,KAAA;GACA,MAAA;EACA;EACA,UAAA;GACA,KAAA;GACA,MAAA;GACA,MAAA,WAAA,oBAAA,UAAA,KAAA;GACA,MAAA,WAAA,oBAAA,YAAA,KAAA;GACA,KAAA,MAAA,SAAA,MAAA,YAAA,MAAA,oBAAA,aAAA,KAAA;EACA;CACA;AACA"}
1
+ {"version":3,"file":"cues.js","names":[],"sources":["../../src/controls/cues.ts"],"sourcesContent":["/**\n * Subtitles and the bar. Two things.\n *\n * The lift: the browser draws native cues on the bottom edge of the video,\n * and under the bar. Every active cue the author left unpositioned is\n * moved up: above the bar while it shows, and one line off the edge while\n * it is hidden, so the text never sits on the picture's border. The\n * position is a negative line count, the one form every browser wraps at\n * the video's width; a percentage does not wrap in Chromium. Chromium\n * anchors the box's top on the count and Gecko its bottom, and their\n * overlap avoidance pushes in opposite directions, so nothing is left to\n * them: subtitles often show two cues at once, and the cues stack by their\n * own measured heights, wrapping included, clear under both readings. A\n * cue with a position of its own is the author's and is not touched.\n *\n * The look: `::cue` can only be styled from the document that holds the\n * video, which is the page and not the shadow root, and it takes no custom\n * properties. So a small sheet goes into the document, once, with one rule\n * per look the host's `subtitle-size` and `subtitle-background` attributes\n * can take. Sizes are percentages of the browser's own cue size, which\n * already follows the video's height, in the page and in fullscreen alike.\n * A page that wants more writes its own `mattebox-player > video::cue`.\n */\nimport CUE_RULES from './cues.css?inline';\n/** How the sizes scale the browser's own cue size; the lift counts lines by it. */\nexport const SCALES: Readonly<Record<string, number>> = {\n small: 0.75,\n medium: 1,\n large: 1.5,\n xlarge: 2,\n};\n\n/**\n * The sheet in the document. `mattebox-player` is the element's tag. The\n * background goes on `::cue` and on the backdrop pseudo-element Chromium\n * and WebKit have, both: which of the two paints it differs by browser and\n * version, and a selector a browser does not know only voids its own rule.\n */\n\nconst MARK = 'data-mattebox-cue';\n\n/** The browser's cue size against the video's height, per WebVTT, and its line against the size. */\nconst CUE_SIZE = 0.05;\nconst LINE_HEIGHT = 1.2;\n/** What a cue box spans of the video's width by default, so wrapping is measured against it. */\nconst CUE_WIDTH = 0.96;\n/** Pixels of air between the bar and the cue above it, before rounding up to a line. */\nconst AIR = 6;\n/** Lines of air under a cue while the bar is hidden. */\nconst REST = 1;\n\n/** Puts the cue rules in the document, once. */\nexport function cueStyle(): void {\n if (document.head.querySelector(`style[${MARK}]`) !== null) return;\n const style = document.createElement('style');\n style.setAttribute(MARK, '');\n style.textContent = CUE_RULES;\n document.head.append(style);\n}\n\n/** What a lifted cue looked like before, to put back. */\ninterface Placed {\n readonly line: number | 'auto';\n readonly snapToLines: boolean;\n readonly lineAlign: LineAlignSetting;\n}\n\nexport interface CueLift {\n /** Whether the bar is showing, so the cues move above it or back. */\n lifted(on: boolean): void;\n dispose(): void;\n}\n\n/** What the bar covers of the picture: from its first row's top, not its gradient run-in, to its bottom. */\nexport type Covered = () => { readonly top: number; readonly bottom: number };\n\nexport function cueLift(video: HTMLVideoElement, host: HTMLElement, covered: Covered): CueLift {\n /** The cues moved, with what they were, so they and only they are put back. */\n const lifted = new Map<VTTCue, Placed>();\n let on = false;\n /** False once disposed: the cues go back to where the author left them. */\n let live = true;\n let canvas: CanvasRenderingContext2D | null | undefined;\n\n function showing(): TextTrack[] {\n const out: TextTrack[] = [];\n for (const track of video.textTracks) if (track.mode === 'showing') out.push(track);\n return out;\n }\n\n /** The browser's cue font size, in pixels, from the video's height and the host's scale. */\n function fontSize(height: number): number {\n const scale = SCALES[host.getAttribute('subtitle-size') ?? ''] ?? 1;\n return height * CUE_SIZE * scale;\n }\n\n /** Measures text the way the browser draws cues, to count the lines a cue wraps into. */\n function measure(): CanvasRenderingContext2D | null {\n if (canvas === undefined) canvas = document.createElement('canvas').getContext('2d');\n return canvas;\n }\n\n /**\n * A cue's text without its tags, for measuring: `<b>`, `<c.name>`, the\n * timestamps and their closers. Brackets are counted, so a tag inside\n * another's brackets goes with it.\n */\n function plain(text: string): string {\n let out = '';\n let depth = 0;\n for (const char of text) {\n if (char === '<') depth += 1;\n else if (char === '>') depth = Math.max(0, depth - 1);\n else if (depth === 0) out += char;\n }\n return out;\n }\n\n /** The lines a cue takes: its own, each wrapped at the cue box's width. */\n function lines(cue: VTTCue, font: number, width: number): number {\n const context = measure();\n let total = 0;\n for (const line of plain(cue.text).split('\\n')) {\n if (context === null) {\n total += 1;\n continue;\n }\n context.font = `${font}px sans-serif`;\n total += Math.max(1, Math.ceil(context.measureText(line).width / (width * CUE_WIDTH)));\n }\n return total;\n }\n\n function apply(): void {\n const box = video.getBoundingClientRect();\n const height = box.height;\n const span = covered();\n const pixels = span.bottom - span.top;\n const lift = live && height > 0;\n const font = fontSize(height);\n const unit = font * LINE_HEIGHT;\n // The lines the bar covers, with a little air, rounded up to whole\n // lines. With the bar hidden, the cue rests a line off the edge.\n const barred = on && pixels > 0 && pixels < height;\n const base = barred ? Math.ceil((pixels + AIR) / unit) : REST;\n for (const track of showing()) {\n // Earliest first, the order the browser stacks them in, so the first\n // sits lowest and the rest climb.\n const active = [...(track.activeCues ?? [])]\n .filter((cue): cue is VTTCue => cue instanceof VTTCue)\n .sort((a, b) => a.startTime - b.startTime);\n let previous: { line: number; height: number } | null = null;\n let changed = false;\n for (const cue of active) {\n const was = lifted.get(cue);\n if (!lift) {\n if (was === undefined) continue;\n cue.line = was.line;\n cue.snapToLines = was.snapToLines;\n cue.lineAlign = was.lineAlign;\n lifted.delete(cue);\n changed = true;\n continue;\n }\n // The author's own placement is the author's.\n if (was === undefined && cue.line !== 'auto') continue;\n if (was === undefined) {\n lifted.set(cue, {\n line: cue.line,\n snapToLines: cue.snapToLines,\n lineAlign: cue.lineAlign,\n });\n }\n // A negative line count, which every browser wraps at the video's\n // width, unlike a percentage. Chromium anchors the box's top on it\n // and Gecko its bottom, so the count clears the bar and the cue\n // below under both readings, with a little air to spare in one.\n const own = lines(cue, font, box.width);\n const line: number =\n previous === null ? base + own : previous.line + Math.max(own, previous.height);\n if (cue.line !== -line || !cue.snapToLines) changed = true;\n cue.snapToLines = true;\n cue.line = -line;\n previous = { line, height: own };\n }\n // Chromium lays a changed line out again only when the track's display\n // is rebuilt, which neither time nor a seek does for a cue already\n // showing; the mode flipped off and on in one task rebuilds it with no\n // paint in between. Only on a change, so the change event this fires\n // finds nothing to do and the loop ends there.\n if (changed) {\n track.mode = 'hidden';\n track.mode = 'showing';\n }\n }\n }\n\n function watch(): void {\n for (const track of video.textTracks) {\n track.removeEventListener('cuechange', apply);\n track.addEventListener('cuechange', apply);\n }\n apply();\n }\n\n video.textTracks.addEventListener('change', watch);\n video.textTracks.addEventListener('addtrack', watch);\n watch();\n\n return {\n lifted(next: boolean): void {\n on = next;\n apply();\n },\n dispose(): void {\n on = false;\n live = false;\n apply();\n video.textTracks.removeEventListener('change', watch);\n video.textTracks.removeEventListener('addtrack', watch);\n for (const track of video.textTracks) track.removeEventListener('cuechange', apply);\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAuBA,MAAA,YAAA;;AAEA,MAAA,SAAA;CACA,OAAA;CACA,QAAA;CACA,OAAA;CACA,QAAA;AACA;;;;;;;AASA,MAAA,OAAA;;AAGA,MAAA,WAAA;AACA,MAAA,cAAA;;AAEA,MAAA,YAAA;;AAEA,MAAA,MAAA;;AAEA,MAAA,OAAA;;AAGA,SAAA,WAAA;CACA,IAAA,SAAA,KAAA,cAAA,SAAA,KAAA,EAAA,MAAA,MAAA;CACA,MAAA,QAAA,SAAA,cAAA,OAAA;CACA,MAAA,aAAA,MAAA,EAAA;CACA,MAAA,cAAA;CACA,SAAA,KAAA,OAAA,KAAA;AACA;A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,OAAA;EACA,OAAA,MAAA;GACA,KAAA;GACA,MAAA;EACA;EACA,UAAA;GACA,KAAA;GACA,OAAA;GACA,MAAA;GACA,MAAA,WAAA,oBAAA,UAAA,KAAA;GACA,MAAA,WAAA,oBAAA,YAAA,KAAA;GACA,KAAA,MAAA,SAAA,MAAA,YAAA,MAAA,oBAAA,aAAA,KAAA;EACA;CACA;AACA"}
@@ -35,12 +35,21 @@ export interface MenuOptions {
35
35
  readonly host: HTMLElement;
36
36
  /** The picture, in viewport pixels, which the popup never leaves. */
37
37
  readonly picture: () => DOMRect | null;
38
+ /**
39
+ * The player, whose whole box a compact player's sheet fills from the
40
+ * foot. The box can be taller than the picture: a video letterboxed in
41
+ * its player leaves bars the controls sit over. The menu watches its
42
+ * size while it is open.
43
+ */
44
+ readonly frame: () => Element | null;
38
45
  /** The name of the Back item, from the page it leaves: "Back from {page}". */
39
46
  readonly back: (page: string) => string;
40
47
  }
41
48
  export interface Menu {
42
49
  readonly button: HTMLButtonElement;
43
50
  readonly popup: HTMLElement;
51
+ /** The dim over the picture behind a compact player's sheet. A press on it closes the menu. */
52
+ readonly backdrop: HTMLElement;
44
53
  /** The accessible name of the button and the popup. */
45
54
  label(text: string): void;
46
55
  /** Replaces the entries, back at the first page. */
@@ -1 +1 @@
1
- {"version":3,"file":"menu.d.ts","sourceRoot":"","sources":["../../src/controls/menu.ts"],"names":[],"mappings":"AAwBA,MAAM,WAAW,SAAS;IACxB,wCAAwC;IACxC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,kDAAkD;IAClD,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,CAAC;IACxB,8EAA8E;IAC9E,QAAQ,CAAC,SAAS,CAAC,EAAE,OAAO,CAAC;IAC7B;;;;OAIG;IACH,QAAQ,CAAC,KAAK,EAAE,aAAa,CAC3B,SAAS,CAAC,MAAM,EAAE,MAAM,EAAE,CAAC,MAAM,GAAG,SAAS,CAAC,CAAC,EAAE,CAAC,MAAM,GAA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G,SAAS,GAAG,QAAQ,CAAC;AAE7C,MAAM,WAAW,WAAW;IAC1B,kGAAkG;IAClG,QAAQ,CAAC,IAAI,EAAE,WAAW,CAAC;IAC3B,qEAAqE;IACrE,QAAQ,CAAC,OAAO,EAAE,MAAM,OAAO,GAAG,IAAI,CAAC;IACvC;;;;;OAKG;IACH,QAAQ,CAAC,KAAK,EAAE,MAAM,OAAO,GAAG,IAAI,CAAC;IACrC,8EAA8E;IAC9E,QAAQ,CAAC,IAAI,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,MAAM,CAAC;CACzC;AAED,MAAM,WAAW,IAAI;IACnB,QAAQ,CAAC,MAAM,EAAE,iBAAiB,CAAC;IACnC,QAAQ,CAAC,KAAK,EAAE,WAAW,CAAC;IAC5B,+FAA+F;IAC/F,QAAQ,CAAC,QAAQ,EAAE,WAAW,CAAC;IAC/B,uDAAuD;IACvD,KAAK,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1B,oDAAoD;IACpD,IAAI,CAAC,OAAO,EAAE,SAAS,SAAS,EAAE,GAAG,IAAI,CAAC;IAC1C,KAAK,IAAI,IAAI,CAAC;IACd,OAAO,IAAI,IAAI,CAAC;CACjB;AA2BD,wBAAgB,IAAI,CAAC,OAAO,EAAE,WAAW,GAAG,IAAI,CAmU/C"}
@@ -49,12 +49,30 @@ function menu(options) {
49
49
  button.setAttribute("aria-haspopup", "menu");
50
50
  button.setAttribute("aria-expanded", "false");
51
51
  const popup = el("div", "popup");
52
- popup.addEventListener("scroll", () => {
53
- more();
54
- });
55
52
  popup.setAttribute("role", "menu");
56
53
  popup.hidden = true;
54
+ const backdrop = el("div", "backdrop");
55
+ backdrop.hidden = true;
56
+ backdrop.addEventListener("click", () => {
57
+ close();
58
+ });
57
59
  let open = false;
60
+ /**
61
+ * While the menu is open it follows its player: a change of tier draws
62
+ * the page again, as a popup or as a sheet, and a change of size places
63
+ * it again. A page that resizes with a menu open sees it keep up.
64
+ */
65
+ const tiers = typeof MutationObserver === "undefined" ? null : new MutationObserver(() => {
66
+ if (!open) return;
67
+ const held = popup.contains(focused());
68
+ render();
69
+ if (held) (checked() ?? items()[0])?.focus();
70
+ });
71
+ const sizes = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(() => {
72
+ if (open) fit();
73
+ });
74
+ /** Whether the page drawn last was drawn for a compact player. */
75
+ let drawnCompact = false;
58
76
  let name = "";
59
77
  let first = [];
60
78
  /** The pages opened, the first being the menu itself. */
@@ -79,25 +97,30 @@ function menu(options) {
79
97
  * left of its right edge.
80
98
  */
81
99
  function fit() {
82
- if (host.getAttribute("layout") === "compact") {
83
- popup.style.maxHeight = "";
100
+ const compact = host.getAttribute("layout") === "compact";
101
+ const picture = compact ? options.frame()?.getBoundingClientRect() ?? null : options.picture();
102
+ backdrop.hidden = !(open && compact && picture !== null);
103
+ for (const node of [popup, backdrop]) node.style.left = node.style.bottom = node.style.width = "";
104
+ backdrop.style.height = "";
105
+ if (picture === null) return;
106
+ if (compact) {
107
+ const box = host.getBoundingClientRect();
108
+ for (const node of [popup, backdrop]) {
109
+ node.style.left = `${picture.left - box.left}px`;
110
+ node.style.bottom = `${box.bottom - picture.bottom}px`;
111
+ node.style.width = `${picture.width}px`;
112
+ }
113
+ backdrop.style.height = `${picture.height}px`;
114
+ popup.style.maxHeight = `${Math.max(0, Math.floor(picture.height - AIR))}px`;
84
115
  popup.style.maxWidth = "";
85
- more();
86
116
  return;
87
117
  }
88
- const picture = options.picture();
89
- if (picture === null) return;
90
118
  const room = button.getBoundingClientRect().top - picture.top - AIR;
91
119
  const most = Number.parseFloat(getComputedStyle(host).getPropertyValue("--mbx-menu-max-height")) || MAX_HEIGHT * (Number.parseFloat(getComputedStyle(host).fontSize) || 16);
92
120
  popup.style.maxHeight = `${Math.max(0, Math.floor(Math.min(most, room)))}px`;
93
- more();
94
121
  const wide = host.getBoundingClientRect().right - picture.left - AIR;
95
122
  popup.style.maxWidth = `${Math.max(0, Math.floor(wide))}px`;
96
123
  }
97
- /** `more` on the popup while rows wait below its foot, which then fades out. */
98
- function more() {
99
- popup.toggleAttribute("more", popup.scrollTop + popup.clientHeight < popup.scrollHeight - 1);
100
- }
101
124
  function clear() {
102
125
  for (const item of items()) {
103
126
  const handler = handlers.get(item);
@@ -119,7 +142,16 @@ function menu(options) {
119
142
  const page = stack[stack.length - 1];
120
143
  if (page === void 0) return;
121
144
  let tab = true;
122
- if (stack.length === 1 && name !== "") {
145
+ drawnCompact = host.getAttribute("layout") === "compact";
146
+ if (stack.length === 1 && name !== "" && drawnCompact) {
147
+ const leave = item("item back-item", name, () => {
148
+ close();
149
+ button.focus();
150
+ });
151
+ leave.setAttribute("role", "menuitem");
152
+ leave.setAttribute("aria-label", options.back(name));
153
+ popup.append(leave);
154
+ } else if (stack.length === 1 && name !== "") {
123
155
  const title = el("div", "title", name);
124
156
  title.setAttribute("aria-hidden", "true");
125
157
  popup.append(title);
@@ -198,7 +230,10 @@ function menu(options) {
198
230
  function close() {
199
231
  if (!open) return;
200
232
  open = false;
233
+ tiers?.disconnect();
234
+ sizes?.disconnect();
201
235
  popup.hidden = true;
236
+ backdrop.hidden = true;
202
237
  button.setAttribute("aria-expanded", "false");
203
238
  host.removeAttribute("open");
204
239
  document.removeEventListener("pointerdown", outside, true);
@@ -210,10 +245,17 @@ function menu(options) {
210
245
  function show() {
211
246
  if (open) return;
212
247
  open = true;
248
+ if (host.getAttribute("layout") === "compact" !== drawnCompact) render();
213
249
  popup.hidden = false;
214
250
  button.setAttribute("aria-expanded", "true");
215
251
  host.setAttribute("open", "");
216
252
  document.addEventListener("pointerdown", outside, true);
253
+ tiers?.observe(host, {
254
+ attributes: true,
255
+ attributeFilter: ["layout"]
256
+ });
257
+ const frame = options.frame();
258
+ if (frame !== null) sizes?.observe(frame);
217
259
  fit();
218
260
  (checked() ?? items()[0])?.focus();
219
261
  }
@@ -260,6 +302,7 @@ function menu(options) {
260
302
  return {
261
303
  button,
262
304
  popup,
305
+ backdrop,
263
306
  label(text) {
264
307
  name = text;
265
308
  button.setAttribute("aria-label", text);
@@ -1 +1 @@
1
- {"version":3,"file":"menu.js","names":[],"sources":["../../src/controls/menu.ts"],"sourcesContent":["/**\n * The menu primitive the quality, audio, subtitles and speed menus share: a\n * button that opens a popup of radio items above it, in one or more groups\n * with a heading each, and pages behind entries that open them. The button\n * carries the name and `aria-expanded`; the popup is `role=\"menu\"`, every\n * choice a `menuitemradio` with `aria-checked`, the checked one also\n * carrying `checked` on its part name, because an item inside a shadow\n * root has no other seam a page can style; an entry that opens a page is\n * a `menuitem` with `aria-haspopup`, and the page starts with a Back.\n *\n * Open on click. Inside, the arrows move focus across every item, Home and\n * End jump, Enter and Space choose, Escape goes back a page or closes and\n * hands focus to the button. A choice closes the popup. A pointer down\n * anywhere else closes it too.\n *\n * The popup never leaves the picture: on opening it takes the room above\n * the button up to the top of `picture()` as its height and scrolls past\n * that, and the room from its right edge to the picture's left as its\n * width, where a long item ends in an ellipsis. The\n * element that owns the menu carries `open` while the popup shows, which\n * the bar reads to hold its fade.\n */\nimport { el, setChildren, state } from '../dom.js';\n\nexport interface MenuGroup {\n /** The part suffix: `track`, `size`. */\n readonly name: string;\n /** A heading, or none for a menu of one group. */\n readonly label?: string;\n /** The label names the group for a screen reader, and no heading is drawn. */\n readonly hideLabel?: boolean;\n /**\n * Each item's id, its text, a detail drawn at its end, such as a chapter's\n * time, the URL of a picture drawn at its start, and short badges drawn\n * after the text, such as \"AD\" on an audio description track.\n */\n readonly items: ReadonlyArray<\n readonly [string, string, (string | undefined)?, (string | undefined)?, (readonly string[])?]\n >;\n readonly value: string;\n readonly onSelect: (value: string) => void;\n /**\n * The badges drawn as a glyph, by their text. The text stays in the\n * badge for a screen reader and as its tooltip.\n */\n readonly badgeGlyphs?: Readonly<Record<string, () => SVGSVGElement>>;\n}\n\n/** An entry that opens a page of groups, with a Back at its top. */\nexport interface MenuPage {\n readonly name: string;\n readonly label: string;\n readonly entries: readonly MenuEntry[];\n /** A glyph drawn before the label of the item that opens the page. */\n readonly glyph?: () => SVGSVGElement;\n /** A detail drawn at the end of that item, such as the value chosen on the page. */\n readonly detail?: string;\n}\n\nexport type MenuEntry = MenuGroup | MenuPage;\n\nexport interface MenuOptions {\n /** The element the menu belongs to: it carries `open`, and a pointer inside it is not outside. */\n readonly host: HTMLElement;\n /** The picture, in viewport pixels, which the popup never leaves. */\n readonly picture: () => DOMRect | null;\n /** The name of the Back item, from the page it leaves: \"Back from {page}\". */\n readonly back: (page: string) => string;\n}\n\nexport interface Menu {\n readonly button: HTMLButtonElement;\n readonly popup: HTMLElement;\n /** The accessible name of the button and the popup. */\n label(text: string): void;\n /** Replaces the entries, back at the first page. */\n fill(entries: readonly MenuEntry[]): void;\n close(): void;\n dispose(): void;\n}\n\n/** Air between the popup's top and the picture's. */\nconst AIR = 8;\n\n/**\n * The tallest a popup grows, in pixels: the title and about seven and a half rows, so\n * the half row at the foot says the list goes on. A page sets its own\n * with `--mbx-menu-max-height`.\n */\n/* In em of the menu's own font size. */\nconst MAX_HEIGHT = 22;\n\n/** An item's picture. Decorative: the item's text names it. Loaded when the popup first shows it. */\nfunction picture(url: string): HTMLImageElement {\n const node = el('img', 'item-image');\n node.alt = '';\n node.loading = 'lazy';\n node.decoding = 'async';\n node.src = url;\n return node;\n}\n\nfunction isPage(entry: MenuEntry): entry is MenuPage {\n return 'entries' in entry;\n}\n\nexport function menu(options: MenuOptions): Menu {\n const { host } = options;\n const button = el('button', 'button');\n button.type = 'button';\n button.setAttribute('aria-haspopup', 'menu');\n button.setAttribute('aria-expanded', 'false');\n const popup = el('div', 'popup');\n popup.addEventListener('scroll', () => {\n more();\n });\n popup.setAttribute('role', 'menu');\n popup.hidden = true;\n\n let open = false;\n let name = '';\n let first: readonly MenuEntry[] = [];\n /** The pages opened, the first being the menu itself. */\n let stack: MenuPage[] = [];\n const handlers = new WeakMap<HTMLButtonElement, () => void>();\n\n function items(): HTMLButtonElement[] {\n return [...popup.querySelectorAll('button')];\n }\n\n function checked(): HTMLButtonElement | undefined {\n return items().find((item) => item.getAttribute('aria-checked') === 'true');\n }\n\n /** The focused element as this tree sees it: inside shadow DOM, `document.activeElement` is the host. */\n function focused(): Element | null {\n return (popup.getRootNode() as Document | ShadowRoot).activeElement;\n }\n\n function outside(event: PointerEvent): void {\n if (!event.composedPath().includes(host)) close();\n }\n\n /**\n * The popup's height: its maximum, or the room above the button if that\n * is less, so the popup never leaves the picture. Its width: the room\n * left of its right edge.\n */\n function fit(): void {\n // A compact player's menu is a sheet on the page: the stylesheet sizes it.\n if (host.getAttribute('layout') === 'compact') {\n popup.style.maxHeight = '';\n popup.style.maxWidth = '';\n more();\n return;\n }\n const picture = options.picture();\n if (picture === null) return;\n const room = button.getBoundingClientRect().top - picture.top - AIR;\n const most =\n Number.parseFloat(getComputedStyle(host).getPropertyValue('--mbx-menu-max-height')) ||\n MAX_HEIGHT * (Number.parseFloat(getComputedStyle(host).fontSize) || 16);\n popup.style.maxHeight = `${Math.max(0, Math.floor(Math.min(most, room)))}px`;\n more();\n // The popup is anchored at the host's right edge and grows leftwards.\n const wide = host.getBoundingClientRect().right - picture.left - AIR;\n popup.style.maxWidth = `${Math.max(0, Math.floor(wide))}px`;\n }\n\n /** `more` on the popup while rows wait below its foot, which then fades out. */\n function more(): void {\n popup.toggleAttribute('more', popup.scrollTop + popup.clientHeight < popup.scrollHeight - 1);\n }\n\n function clear(): void {\n for (const item of items()) {\n const handler = handlers.get(item);\n if (handler !== undefined) item.removeEventListener('click', handler);\n }\n setChildren(popup);\n }\n\n function item(part: string, text: string, handler: () => void): HTMLButtonElement {\n const node = el('button', part, text);\n node.type = 'button';\n node.tabIndex = -1;\n handlers.set(node, handler);\n node.addEventListener('click', handler);\n return node;\n }\n\n /** Draws the page on top of the stack. */\n function render(): void {\n clear();\n const page = stack[stack.length - 1];\n if (page === undefined) return;\n let tab = true;\n // The first page starts with the menu's name. The popup already carries it for a screen reader.\n if (stack.length === 1 && name !== '') {\n const title = el('div', 'title', name);\n title.setAttribute('aria-hidden', 'true');\n popup.append(title);\n }\n if (stack.length > 1) {\n const back = item('item back-item', page.label, () => {\n stack.pop();\n render();\n items()[0]?.focus();\n });\n back.setAttribute('role', 'menuitem');\n back.setAttribute('aria-label', options.back(page.label));\n popup.append(back);\n }\n for (const entry of page.entries) {\n if (isPage(entry)) {\n const link = item(`item page-item ${entry.name}-item`, entry.label, () => {\n stack.push(entry);\n render();\n items()[0]?.focus();\n });\n link.setAttribute('role', 'menuitem');\n link.setAttribute('aria-haspopup', 'menu');\n if (entry.glyph !== undefined) {\n link.prepend(entry.glyph());\n state(link, `item page-item ${entry.name}-item`, { 'glyph-item': true });\n }\n if (entry.detail !== undefined) link.append(el('span', 'item-detail', entry.detail));\n popup.append(link);\n continue;\n }\n const section = el('div', `section ${entry.name}-section`);\n section.setAttribute('role', 'group');\n if (entry.label !== undefined) {\n section.setAttribute('aria-label', entry.label);\n if (entry.hideLabel !== true) {\n section.append(el('div', `section-label ${entry.name}-label`, entry.label));\n }\n }\n for (const [id, text, detail, image, badges] of entry.items) {\n const choice = item(`item ${entry.name}-item`, text, () => {\n close();\n button.focus();\n entry.onSelect(id);\n });\n for (const badge of badges ?? []) {\n const glyph = entry.badgeGlyphs?.[badge];\n if (glyph === undefined) {\n choice.append(el('span', 'item-badge', badge));\n continue;\n }\n // The glyph is what a viewer sees, and the text is what a screen reader says.\n const drawn = el('span', 'item-badge item-glyph');\n drawn.title = badge;\n drawn.append(glyph(), el('span', 'badge-text', badge));\n choice.append(drawn);\n }\n if (detail !== undefined) choice.append(el('span', 'item-detail', detail));\n if (image !== undefined) {\n // The text in a box of its own, so a long title ends in an ellipsis beside the picture.\n const [, ...rest] = choice.childNodes;\n setChildren(choice, el('span', 'item-text', text), ...rest);\n choice.prepend(picture(image));\n }\n choice.value = id;\n choice.setAttribute('role', 'menuitemradio');\n const on = id === entry.value;\n choice.setAttribute('aria-checked', String(on));\n state(choice, `item ${entry.name}-item`, { checked: on });\n // One tab stop: the first checked item.\n if (on && tab) {\n choice.tabIndex = 0;\n tab = false;\n }\n section.append(choice);\n }\n popup.append(section);\n }\n fit();\n }\n\n function close(): void {\n if (!open) return;\n open = false;\n popup.hidden = true;\n button.setAttribute('aria-expanded', 'false');\n host.removeAttribute('open');\n document.removeEventListener('pointerdown', outside, true);\n if (stack.length > 1) {\n stack = stack.slice(0, 1);\n render();\n }\n }\n\n function show(): void {\n if (open) return;\n open = true;\n popup.hidden = false;\n button.setAttribute('aria-expanded', 'true');\n host.setAttribute('open', '');\n document.addEventListener('pointerdown', outside, true);\n fit();\n (checked() ?? items()[0])?.focus();\n }\n\n function toggle(): void {\n if (open) close();\n else show();\n }\n\n function key(event: KeyboardEvent): void {\n // Handled already, by a handler that decides first.\n if (event.defaultPrevented) return;\n const list = items();\n const index = list.indexOf(focused() as HTMLButtonElement);\n let next: number;\n switch (event.key) {\n case 'ArrowDown':\n next = (index + 1) % list.length;\n break;\n case 'ArrowUp':\n next = (index - 1 + list.length) % list.length;\n break;\n case 'Home':\n next = 0;\n break;\n case 'End':\n next = list.length - 1;\n break;\n case 'Escape':\n event.preventDefault();\n if (stack.length > 1) {\n stack.pop();\n render();\n items()[0]?.focus();\n return;\n }\n close();\n button.focus();\n return;\n default:\n return;\n }\n event.preventDefault();\n list[next]?.focus();\n }\n\n button.addEventListener('click', toggle);\n popup.addEventListener('keydown', key);\n\n return {\n button,\n popup,\n label(text: string): void {\n name = text;\n button.setAttribute('aria-label', text);\n popup.setAttribute('aria-label', text);\n const root = stack[0];\n if (root !== undefined) stack[0] = { ...root, label: text };\n },\n fill(entries): void {\n first = entries;\n stack = [{ name: 'menu', label: name, entries: first }];\n render();\n },\n close,\n dispose(): void {\n close();\n clear();\n button.removeEventListener('click', toggle);\n popup.removeEventListener('keydown', key);\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAkFA,MAAM,MAAM;;;;;;AAQZ,MAAM,aAAa;;AAGnB,SAAS,QAAQ,KAA+B;CAC9C,MA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1
+ {"version":3,"file":"menu.js","names":[],"sources":["../../src/controls/menu.ts"],"sourcesContent":["/**\n * The menu primitive the quality, audio, subtitles and speed menus share: a\n * button that opens a popup of radio items above it, in one or more groups\n * with a heading each, and pages behind entries that open them. The button\n * carries the name and `aria-expanded`; the popup is `role=\"menu\"`, every\n * choice a `menuitemradio` with `aria-checked`, the checked one also\n * carrying `checked` on its part name, because an item inside a shadow\n * root has no other seam a page can style; an entry that opens a page is\n * a `menuitem` with `aria-haspopup`, and the page starts with a Back.\n *\n * Open on click. Inside, the arrows move focus across every item, Home and\n * End jump, Enter and Space choose, Escape goes back a page or closes and\n * hands focus to the button. A choice closes the popup. A pointer down\n * anywhere else closes it too.\n *\n * The popup never leaves the picture: on opening it takes the room above\n * the button up to the top of `picture()` as its height and scrolls past\n * that, and the room from its right edge to the picture's left as its\n * width, where a long item ends in an ellipsis. The\n * element that owns the menu carries `open` while the popup shows, which\n * the bar reads to hold its fade.\n */\nimport { el, setChildren, state } from '../dom.js';\n\nexport interface MenuGroup {\n /** The part suffix: `track`, `size`. */\n readonly name: string;\n /** A heading, or none for a menu of one group. */\n readonly label?: string;\n /** The label names the group for a screen reader, and no heading is drawn. */\n readonly hideLabel?: boolean;\n /**\n * Each item's id, its text, a detail drawn at its end, such as a chapter's\n * time, the URL of a picture drawn at its start, and short badges drawn\n * after the text, such as \"AD\" on an audio description track.\n */\n readonly items: ReadonlyArray<\n readonly [string, string, (string | undefined)?, (string | undefined)?, (readonly string[])?]\n >;\n readonly value: string;\n readonly onSelect: (value: string) => void;\n /**\n * The badges drawn as a glyph, by their text. The text stays in the\n * badge for a screen reader and as its tooltip.\n */\n readonly badgeGlyphs?: Readonly<Record<string, () => SVGSVGElement>>;\n}\n\n/** An entry that opens a page of groups, with a Back at its top. */\nexport interface MenuPage {\n readonly name: string;\n readonly label: string;\n readonly entries: readonly MenuEntry[];\n /** A glyph drawn before the label of the item that opens the page. */\n readonly glyph?: () => SVGSVGElement;\n /** A detail drawn at the end of that item, such as the value chosen on the page. */\n readonly detail?: string;\n}\n\nexport type MenuEntry = MenuGroup | MenuPage;\n\nexport interface MenuOptions {\n /** The element the menu belongs to: it carries `open`, and a pointer inside it is not outside. */\n readonly host: HTMLElement;\n /** The picture, in viewport pixels, which the popup never leaves. */\n readonly picture: () => DOMRect | null;\n /**\n * The player, whose whole box a compact player's sheet fills from the\n * foot. The box can be taller than the picture: a video letterboxed in\n * its player leaves bars the controls sit over. The menu watches its\n * size while it is open.\n */\n readonly frame: () => Element | null;\n /** The name of the Back item, from the page it leaves: \"Back from {page}\". */\n readonly back: (page: string) => string;\n}\n\nexport interface Menu {\n readonly button: HTMLButtonElement;\n readonly popup: HTMLElement;\n /** The dim over the picture behind a compact player's sheet. A press on it closes the menu. */\n readonly backdrop: HTMLElement;\n /** The accessible name of the button and the popup. */\n label(text: string): void;\n /** Replaces the entries, back at the first page. */\n fill(entries: readonly MenuEntry[]): void;\n close(): void;\n dispose(): void;\n}\n\n/** Air between the popup's top and the picture's. */\nconst AIR = 8;\n\n/**\n * The tallest a popup grows, in pixels: the title and about seven and a half rows, so\n * the half row at the foot says the list goes on. A page sets its own\n * with `--mbx-menu-max-height`.\n */\n/* In em of the menu's own font size. */\nconst MAX_HEIGHT = 22;\n\n/** An item's picture. Decorative: the item's text names it. Loaded when the popup first shows it. */\nfunction picture(url: string): HTMLImageElement {\n const node = el('img', 'item-image');\n node.alt = '';\n node.loading = 'lazy';\n node.decoding = 'async';\n node.src = url;\n return node;\n}\n\nfunction isPage(entry: MenuEntry): entry is MenuPage {\n return 'entries' in entry;\n}\n\nexport function menu(options: MenuOptions): Menu {\n const { host } = options;\n const button = el('button', 'button');\n button.type = 'button';\n button.setAttribute('aria-haspopup', 'menu');\n button.setAttribute('aria-expanded', 'false');\n const popup = el('div', 'popup');\n popup.setAttribute('role', 'menu');\n popup.hidden = true;\n const backdrop = el('div', 'backdrop');\n backdrop.hidden = true;\n backdrop.addEventListener('click', () => {\n close();\n });\n\n let open = false;\n /**\n * While the menu is open it follows its player: a change of tier draws\n * the page again, as a popup or as a sheet, and a change of size places\n * it again. A page that resizes with a menu open sees it keep up.\n */\n const tiers =\n typeof MutationObserver === 'undefined'\n ? null\n : new MutationObserver(() => {\n if (!open) return;\n // The rows are drawn again, so the focus goes back to one of them.\n const held = popup.contains(focused());\n render();\n if (held) (checked() ?? items()[0])?.focus();\n });\n const sizes =\n typeof ResizeObserver === 'undefined'\n ? null\n : new ResizeObserver(() => {\n if (open) fit();\n });\n /** Whether the page drawn last was drawn for a compact player. */\n let drawnCompact = false;\n let name = '';\n let first: readonly MenuEntry[] = [];\n /** The pages opened, the first being the menu itself. */\n let stack: MenuPage[] = [];\n const handlers = new WeakMap<HTMLButtonElement, () => void>();\n\n function items(): HTMLButtonElement[] {\n return [...popup.querySelectorAll('button')];\n }\n\n function checked(): HTMLButtonElement | undefined {\n return items().find((item) => item.getAttribute('aria-checked') === 'true');\n }\n\n /** The focused element as this tree sees it: inside shadow DOM, `document.activeElement` is the host. */\n function focused(): Element | null {\n return (popup.getRootNode() as Document | ShadowRoot).activeElement;\n }\n\n function outside(event: PointerEvent): void {\n if (!event.composedPath().includes(host)) close();\n }\n\n /**\n * The popup's height: its maximum, or the room above the button if that\n * is less, so the popup never leaves the picture. Its width: the room\n * left of its right edge.\n */\n function fit(): void {\n const compact = host.getAttribute('layout') === 'compact';\n const picture = compact\n ? (options.frame()?.getBoundingClientRect() ?? null)\n : options.picture();\n backdrop.hidden = !(open && compact && picture !== null);\n for (const node of [popup, backdrop]) {\n node.style.left = node.style.bottom = node.style.width = '';\n }\n backdrop.style.height = '';\n if (picture === null) return;\n // A compact player's menu is a sheet from the foot of the player, as wide\n // as the player and never taller, over the controls. It stays inside the\n // player: a page around a small player keeps its own space. The dim\n // covers the rest of the player.\n if (compact) {\n const box = host.getBoundingClientRect();\n for (const node of [popup, backdrop]) {\n node.style.left = `${picture.left - box.left}px`;\n node.style.bottom = `${box.bottom - picture.bottom}px`;\n node.style.width = `${picture.width}px`;\n }\n backdrop.style.height = `${picture.height}px`;\n popup.style.maxHeight = `${Math.max(0, Math.floor(picture.height - AIR))}px`;\n popup.style.maxWidth = '';\n return;\n }\n const room = button.getBoundingClientRect().top - picture.top - AIR;\n const most =\n Number.parseFloat(getComputedStyle(host).getPropertyValue('--mbx-menu-max-height')) ||\n MAX_HEIGHT * (Number.parseFloat(getComputedStyle(host).fontSize) || 16);\n popup.style.maxHeight = `${Math.max(0, Math.floor(Math.min(most, room)))}px`;\n // The popup is anchored at the host's right edge and grows leftwards.\n const wide = host.getBoundingClientRect().right - picture.left - AIR;\n popup.style.maxWidth = `${Math.max(0, Math.floor(wide))}px`;\n }\n\n function clear(): void {\n for (const item of items()) {\n const handler = handlers.get(item);\n if (handler !== undefined) item.removeEventListener('click', handler);\n }\n setChildren(popup);\n }\n\n function item(part: string, text: string, handler: () => void): HTMLButtonElement {\n const node = el('button', part, text);\n node.type = 'button';\n node.tabIndex = -1;\n handlers.set(node, handler);\n node.addEventListener('click', handler);\n return node;\n }\n\n /** Draws the page on top of the stack. */\n function render(): void {\n clear();\n const page = stack[stack.length - 1];\n if (page === undefined) return;\n let tab = true;\n // The first page starts with the menu's name. On a compact player the\n // menu is a sheet over the controls, so the name is the way back: a\n // press on it closes the sheet. Elsewhere it is a title, and the popup\n // already carries the name for a screen reader.\n drawnCompact = host.getAttribute('layout') === 'compact';\n if (stack.length === 1 && name !== '' && drawnCompact) {\n const leave = item('item back-item', name, () => {\n close();\n button.focus();\n });\n leave.setAttribute('role', 'menuitem');\n leave.setAttribute('aria-label', options.back(name));\n popup.append(leave);\n } else if (stack.length === 1 && name !== '') {\n const title = el('div', 'title', name);\n title.setAttribute('aria-hidden', 'true');\n popup.append(title);\n }\n if (stack.length > 1) {\n const back = item('item back-item', page.label, () => {\n stack.pop();\n render();\n items()[0]?.focus();\n });\n back.setAttribute('role', 'menuitem');\n back.setAttribute('aria-label', options.back(page.label));\n popup.append(back);\n }\n for (const entry of page.entries) {\n if (isPage(entry)) {\n const link = item(`item page-item ${entry.name}-item`, entry.label, () => {\n stack.push(entry);\n render();\n items()[0]?.focus();\n });\n link.setAttribute('role', 'menuitem');\n link.setAttribute('aria-haspopup', 'menu');\n if (entry.glyph !== undefined) {\n link.prepend(entry.glyph());\n state(link, `item page-item ${entry.name}-item`, { 'glyph-item': true });\n }\n if (entry.detail !== undefined) link.append(el('span', 'item-detail', entry.detail));\n popup.append(link);\n continue;\n }\n const section = el('div', `section ${entry.name}-section`);\n section.setAttribute('role', 'group');\n if (entry.label !== undefined) {\n section.setAttribute('aria-label', entry.label);\n if (entry.hideLabel !== true) {\n section.append(el('div', `section-label ${entry.name}-label`, entry.label));\n }\n }\n for (const [id, text, detail, image, badges] of entry.items) {\n const choice = item(`item ${entry.name}-item`, text, () => {\n close();\n button.focus();\n entry.onSelect(id);\n });\n for (const badge of badges ?? []) {\n const glyph = entry.badgeGlyphs?.[badge];\n if (glyph === undefined) {\n choice.append(el('span', 'item-badge', badge));\n continue;\n }\n // The glyph is what a viewer sees, and the text is what a screen reader says.\n const drawn = el('span', 'item-badge item-glyph');\n drawn.title = badge;\n drawn.append(glyph(), el('span', 'badge-text', badge));\n choice.append(drawn);\n }\n if (detail !== undefined) choice.append(el('span', 'item-detail', detail));\n if (image !== undefined) {\n // The text in a box of its own, so a long title ends in an ellipsis beside the picture.\n const [, ...rest] = choice.childNodes;\n setChildren(choice, el('span', 'item-text', text), ...rest);\n choice.prepend(picture(image));\n }\n choice.value = id;\n choice.setAttribute('role', 'menuitemradio');\n const on = id === entry.value;\n choice.setAttribute('aria-checked', String(on));\n state(choice, `item ${entry.name}-item`, { checked: on });\n // One tab stop: the first checked item.\n if (on && tab) {\n choice.tabIndex = 0;\n tab = false;\n }\n section.append(choice);\n }\n popup.append(section);\n }\n fit();\n }\n\n function close(): void {\n if (!open) return;\n open = false;\n tiers?.disconnect();\n sizes?.disconnect();\n popup.hidden = true;\n backdrop.hidden = true;\n button.setAttribute('aria-expanded', 'false');\n host.removeAttribute('open');\n document.removeEventListener('pointerdown', outside, true);\n if (stack.length > 1) {\n stack = stack.slice(0, 1);\n render();\n }\n }\n\n function show(): void {\n if (open) return;\n open = true;\n // The tier may have changed since the page was drawn: its first row differs.\n if ((host.getAttribute('layout') === 'compact') !== drawnCompact) render();\n popup.hidden = false;\n button.setAttribute('aria-expanded', 'true');\n host.setAttribute('open', '');\n document.addEventListener('pointerdown', outside, true);\n tiers?.observe(host, { attributes: true, attributeFilter: ['layout'] });\n const frame = options.frame();\n if (frame !== null) sizes?.observe(frame);\n fit();\n (checked() ?? items()[0])?.focus();\n }\n\n function toggle(): void {\n if (open) close();\n else show();\n }\n\n function key(event: KeyboardEvent): void {\n // Handled already, by a handler that decides first.\n if (event.defaultPrevented) return;\n const list = items();\n const index = list.indexOf(focused() as HTMLButtonElement);\n let next: number;\n switch (event.key) {\n case 'ArrowDown':\n next = (index + 1) % list.length;\n break;\n case 'ArrowUp':\n next = (index - 1 + list.length) % list.length;\n break;\n case 'Home':\n next = 0;\n break;\n case 'End':\n next = list.length - 1;\n break;\n case 'Escape':\n event.preventDefault();\n if (stack.length > 1) {\n stack.pop();\n render();\n items()[0]?.focus();\n return;\n }\n close();\n button.focus();\n return;\n default:\n return;\n }\n event.preventDefault();\n list[next]?.focus();\n }\n\n button.addEventListener('click', toggle);\n popup.addEventListener('keydown', key);\n\n return {\n button,\n popup,\n backdrop,\n label(text: string): void {\n name = text;\n button.setAttribute('aria-label', text);\n popup.setAttribute('aria-label', text);\n const root = stack[0];\n if (root !== undefined) stack[0] = { ...root, label: text };\n },\n fill(entries): void {\n first = entries;\n stack = [{ name: 'menu', label: name, entries: first }];\n render();\n },\n close,\n dispose(): void {\n close();\n clear();\n button.removeEventListener('click', toggle);\n popup.removeEventListener('keydown', key);\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AA2FA,MAAM,MAAM;;;;;;AAQZ,MAAM,aAAa;;AAGnB,SAAS,QAAQ,KAA+B;CAC9C,M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IAAE,MAAM;IAAQ,OAAO;IAAM,SAAS;GAAM,CAAC;GACtD,OAAO;EACT;EACA;EACA,UAAgB;GACd,MAAM;GACN,MAAM;GACN,OAAO,oBAAoB,SAAS,MAAM;GAC1C,MAAM,oBAAoB,WAAW,GAAG;EAC1C;CACF;AACF"}
package/dist/element.d.ts CHANGED
@@ -85,6 +85,15 @@ export declare class MatteboxPlayerElement extends HTMLElement implements Player
85
85
  /** Whether the element gave itself a tabindex for the bar, to take back with it. */
86
86
  private focusable;
87
87
  private readonly surface;
88
+ private readonly voice;
89
+ /** Runs out when the video has waited `LOADING_MS`. */
90
+ private slow;
91
+ /** The audio track the live region last saw, so it says only a change. Undefined before the first play. */
92
+ private heardAudio;
93
+ /** The subtitle track it last saw: null for off, undefined before the first play. */
94
+ private heardText;
95
+ /** Stops listening to the current engine's track selection. */
96
+ private offTracks;
88
97
  private readonly marks;
89
98
  /** The chapters track element, while the `chapters` attribute names one and the engine takes none. */
90
99
  private track;
@@ -142,6 +151,14 @@ export declare class MatteboxPlayerElement extends HTMLElement implements Player
142
151
  private measure;
143
152
  /** The two states the video does not hold: whether it has played once, and whether it waits for data. */
144
153
  private note;
154
+ /** Says a play or a pause, and a wait once it has lasted `LOADING_MS`. */
155
+ private tell;
156
+ /**
157
+ * Says a change of the audio or the subtitle track, once the video has
158
+ * played: the tracks a load starts with are no change. A forced track
159
+ * reads as off, as in the subtitles menu.
160
+ */
161
+ private tracks;
145
162
  /** The video's state on the element, for `mattebox-player[paused]` and the like. */
146
163
  private reflect;
147
164
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"element.d.ts","sourceRoot":"","sources":["../src/element.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAEH,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAQ3F,OAAO,KAAK,EAAE,YAAY,EAAE,QAAQ,EAAE,KAAK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AAI,MAAM,IAAI,QAAQ,GAAG,IAAI,CAE5B;IAED;;;;;OAKG;IACH,IAAI,KAAK,IAAI,WAAW,GAAG,IAAI,CAE9B;IAED,iBAAiB,IAAI,IAAI;IAczB,sEAAsE;IACtE,OAAO,CAAC,OAAO;IAmBf,yGAAyG;IACzG,OAAO,CAAC,IAAI;IAmBZ,0EAA0E;IAC1E,OAAO,CAAC,IAAI;IAaZ;;;;OAIG;IACH,OAAO,CAAC,MAAM;IAkCd,oFAAoF;IACpF,OAAO,CAAC,OAAO;IAgBf;;;;;;OAMG;IACH,OAAO,CAAC,KAAK;IAUb,oBAAoB,IAAI,IAAI;IAQ5B,wBAAwB,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI;IAuC5C;;;;OAIG;IACH,OAAO,CAAC,IAAI;IAkBZ,0GAA0G;IAC1G,OAAO,CAAC,QAAQ;IAmChB,OAAO,CAAC,OAAO;IAUf,OAAO,CAAC,OAAO;IAIf;;;;OAIG;IACH,OAAO,CAAC,MAAM;IASd,OAAO,CAAC,IAAI;IAIZ,OAAO,CAAC,MAAM;YAeA,GAAG;IAqBjB;;;;OAIG;IACH,OAAO,CAAC,MAAM;IAoCd,oGAAoG;IACpG,OAAO,CAAC,KAAK;YAYC,MAAM;IAqBpB;;;;OAIG;IACH,OAAO,KAAK,OAAO,GAElB;YAEa,KAAK;IAiCnB;;;;OAIG;IACH,OAAO,CAAC,GAAG;IAeX,8EAA8E;IAC9E,OAAO,CAAC,SAAS;IA6BjB,OAAO,CAAC,OAAO;YAID,QAAQ;IAKtB,mFAAmF;YACrE,OAAO;CAMtB"}
package/dist/element.js CHANGED
@@ -1,4 +1,6 @@
1
+ import { announcer } from "./announcer.js";
1
2
  import { createMarkers } from "./controls/markers.js";
3
+ import { languageName } from "./controls/track-names.js";
2
4
  import { namespaces } from "./namespaces.js";
3
5
  import { drmGuard, resolvePreset } from "./presets.js";
4
6
  import { STYLE } from "./style.js";
@@ -91,6 +93,15 @@ const STATE_EVENTS = [
91
93
  "stalled",
92
94
  "canplay"
93
95
  ];
96
+ /**
97
+ * How long the video waits for data before the live region says so. A
98
+ * seek within the buffer waits for less, and saying it would only be noise.
99
+ */
100
+ const LOADING_MS = 1e3;
101
+ /** A track's name for the live region: its name in the stream, else its language's. */
102
+ function trackName(name, lang) {
103
+ return name || lang && (languageName(lang) ?? lang) || "";
104
+ }
94
105
  /** The stages that register a key system, which a native session's DRM offers. */
95
106
  const KEY_SYSTEMS = ["eme-fairplay", "eme-cenc"];
96
107
  /** Every stage the engine ships. A narrower preset is optimization. */
@@ -147,12 +158,22 @@ var MatteboxPlayerElement = class MatteboxPlayerElement extends HTMLElement {
147
158
  this.offs = [];
148
159
  this.queue = Promise.resolve();
149
160
  this.pending = false;
161
+ this.slow = void 0;
162
+ this.heardAudio = void 0;
163
+ this.heardText = void 0;
164
+ this.offTracks = null;
150
165
  this.media = document.createElement("video");
151
166
  this.media.controls = true;
152
167
  this.media.setAttribute(PLAYSINLINE, "");
153
168
  for (const name of STATE_EVENTS) this.media.addEventListener(name, () => {
169
+ const was = this.waiting;
154
170
  this.note(name);
155
171
  this.reflect();
172
+ this.tell(name, was);
173
+ });
174
+ const lists = this.media;
175
+ for (const list of [lists.audioTracks, lists.textTracks]) list?.addEventListener("change", () => {
176
+ this.tracks();
156
177
  });
157
178
  this.media.addEventListener("playing", () => {
158
179
  this.failure = null;
@@ -168,10 +189,11 @@ var MatteboxPlayerElement = class MatteboxPlayerElement extends HTMLElement {
168
189
  this.surface = errorSurface(() => {
169
190
  this.reload();
170
191
  });
192
+ this.voice = announcer(this);
171
193
  const root = this.attachShadow({ mode: "open" });
172
194
  const style = document.createElement("style");
173
195
  style.textContent = STYLE;
174
- root.append(style, this.stage, this.surface.root);
196
+ root.append(style, this.stage, this.surface.root, this.voice.root);
175
197
  }
176
198
  /** The media element. Everything the browser already does is here. */
177
199
  get video() {
@@ -240,6 +262,7 @@ var MatteboxPlayerElement = class MatteboxPlayerElement extends HTMLElement {
240
262
  /** The two states the video does not hold: whether it has played once, and whether it waits for data. */
241
263
  note(event) {
242
264
  if (event === "playing") {
265
+ if (!this.started) this.tracks();
243
266
  this.started = true;
244
267
  this.waiting = false;
245
268
  } else if (event === "waiting" || event === "stalled") this.waiting = true;
@@ -247,6 +270,49 @@ var MatteboxPlayerElement = class MatteboxPlayerElement extends HTMLElement {
247
270
  else if (event === "emptied") {
248
271
  this.started = false;
249
272
  this.waiting = false;
273
+ this.heardAudio = void 0;
274
+ this.heardText = void 0;
275
+ }
276
+ }
277
+ /** Says a play or a pause, and a wait once it has lasted `LOADING_MS`. */
278
+ tell(event, was) {
279
+ if (event === "play") this.voice.say("playing", "Playing");
280
+ if (event === "pause" && !this.media.ended) this.voice.say("paused", "Paused");
281
+ if (this.waiting === was) return;
282
+ clearTimeout(this.slow);
283
+ if (this.waiting) this.slow = setTimeout(() => {
284
+ this.voice.say("loading", "Loading");
285
+ }, LOADING_MS);
286
+ }
287
+ /**
288
+ * Says a change of the audio or the subtitle track, once the video has
289
+ * played: the tracks a load starts with are no change. A forced track
290
+ * reads as off, as in the subtitles menu.
291
+ */
292
+ tracks() {
293
+ const engine = this.current?.engine ?? null;
294
+ let audio;
295
+ let text;
296
+ if (engine !== null) {
297
+ const sound = engine.tracks.active("audio");
298
+ const words = engine.tracks.active("text");
299
+ audio = sound === null ? "" : trackName(sound.name, sound.lang);
300
+ text = words === null || words.forced === true ? null : trackName(words.name, words.lang);
301
+ } else {
302
+ const video = this.media;
303
+ const sound = Array.from(video.audioTracks ?? []).find((track) => track.enabled);
304
+ const words = Array.from(this.media.textTracks).find((track) => (track.kind === "subtitles" || track.kind === "captions") && track.mode === "showing");
305
+ audio = sound === void 0 ? "" : trackName(sound.label, sound.language);
306
+ text = words === void 0 ? null : trackName(words.label, words.language);
307
+ }
308
+ const { heardAudio, heardText } = this;
309
+ this.heardAudio = audio;
310
+ this.heardText = text;
311
+ if (!this.started) return;
312
+ if (heardAudio !== void 0 && audio !== heardAudio) this.voice.say("audio", "Audio: {track}", audio);
313
+ if (heardText !== void 0 && text !== heardText) {
314
+ if (text === null) this.voice.say("subtitles-off", "Subtitles off");
315
+ else this.voice.say("subtitles", "Subtitles: {track}", text);
250
316
  }
251
317
  }
252
318
  /** The video's state on the element, for `mattebox-player[paused]` and the like. */
@@ -389,6 +455,8 @@ var MatteboxPlayerElement = class MatteboxPlayerElement extends HTMLElement {
389
455
  report(error) {
390
456
  if (error.fatal) {
391
457
  this.failure = error;
458
+ clearTimeout(this.slow);
459
+ if (this.querySelector("mbx-error-screen") === null) this.voice.say("error", "Playback failed");
392
460
  if (this.getAttribute(CONTROLS) !== "custom") this.surface.show(error);
393
461
  }
394
462
  this.emit("error", error);
@@ -457,6 +525,8 @@ var MatteboxPlayerElement = class MatteboxPlayerElement extends HTMLElement {
457
525
  const core = createPlayer(this.media, { handlers: await this.chain() });
458
526
  this.offs.push(core.on("sourcechange", (session) => {
459
527
  this.current = session;
528
+ this.offTracks?.();
529
+ this.offTracks = session?.engine?.on("tracks:selected", () => this.tracks()) ?? null;
460
530
  if (session !== null && this.isConnected) this.adopt(session);
461
531
  this.emit("sourcechange", session);
462
532
  }), core.on("error", (error) => {