@zonsh/ui 0.0.0 → 0.2.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 (388) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +75 -1
  3. package/assets/illustrations/drawing/bracket-construction-dark.svg +77 -0
  4. package/assets/illustrations/drawing/bracket-construction-filled-dark.svg +50 -0
  5. package/assets/illustrations/drawing/bracket-construction-filled.svg +50 -0
  6. package/assets/illustrations/drawing/bracket-construction.svg +77 -0
  7. package/assets/illustrations/drawing/crescent-dark.svg +28 -0
  8. package/assets/illustrations/drawing/crescent-guides-dark.svg +33 -0
  9. package/assets/illustrations/drawing/crescent-guides.svg +33 -0
  10. package/assets/illustrations/drawing/crescent.svg +28 -0
  11. package/assets/illustrations/drawing/eclipse-dark.svg +187 -0
  12. package/assets/illustrations/drawing/eclipse-guides-dark.svg +191 -0
  13. package/assets/illustrations/drawing/eclipse-guides.svg +191 -0
  14. package/assets/illustrations/drawing/eclipse.svg +187 -0
  15. package/assets/illustrations/drawing/elevation-guides-dark.svg +31 -0
  16. package/assets/illustrations/drawing/elevation-guides-plain-dark.svg +9 -0
  17. package/assets/illustrations/drawing/elevation-guides-plain.svg +9 -0
  18. package/assets/illustrations/drawing/elevation-guides.svg +31 -0
  19. package/assets/illustrations/drawing/horizon-dark.svg +30 -0
  20. package/assets/illustrations/drawing/horizon.svg +30 -0
  21. package/assets/illustrations/drawing/nib-study-dark.svg +107 -0
  22. package/assets/illustrations/drawing/nib-study-plain-dark.svg +93 -0
  23. package/assets/illustrations/drawing/nib-study-plain.svg +93 -0
  24. package/assets/illustrations/drawing/nib-study.svg +107 -0
  25. package/assets/illustrations/editorial/assistant-640.webp +0 -0
  26. package/assets/illustrations/editorial/assistant.webp +0 -0
  27. package/assets/illustrations/editorial/automation-640.webp +0 -0
  28. package/assets/illustrations/editorial/automation.webp +0 -0
  29. package/assets/illustrations/editorial/bracket-left-640.webp +0 -0
  30. package/assets/illustrations/editorial/bracket-left.webp +0 -0
  31. package/assets/illustrations/editorial/bracket-right-640.webp +0 -0
  32. package/assets/illustrations/editorial/bracket-right.webp +0 -0
  33. package/assets/illustrations/editorial/custom-software-640.webp +0 -0
  34. package/assets/illustrations/editorial/custom-software.webp +0 -0
  35. package/assets/illustrations/editorial/digitalization-640.webp +0 -0
  36. package/assets/illustrations/editorial/digitalization.webp +0 -0
  37. package/assets/illustrations/editorial/integration-640.webp +0 -0
  38. package/assets/illustrations/editorial/integration.webp +0 -0
  39. package/assets/illustrations/editorial/problem-640.webp +0 -0
  40. package/assets/illustrations/editorial/problem.webp +0 -0
  41. package/assets/illustrations/editorial/process-analysis-640.webp +0 -0
  42. package/assets/illustrations/editorial/process-analysis.webp +0 -0
  43. package/assets/illustrations/editorial/process-concept-640.webp +0 -0
  44. package/assets/illustrations/editorial/process-concept.webp +0 -0
  45. package/assets/illustrations/editorial/process-development-640.webp +0 -0
  46. package/assets/illustrations/editorial/process-development.webp +0 -0
  47. package/assets/illustrations/editorial/process-discovery-640.webp +0 -0
  48. package/assets/illustrations/editorial/process-discovery.webp +0 -0
  49. package/assets/illustrations/editorial/process-maintenance-640.webp +0 -0
  50. package/assets/illustrations/editorial/process-maintenance.webp +0 -0
  51. package/assets/illustrations/editorial/process-prototype-640.webp +0 -0
  52. package/assets/illustrations/editorial/process-prototype.webp +0 -0
  53. package/assets/illustrations/editorial/process-testing-640.webp +0 -0
  54. package/assets/illustrations/editorial/process-testing.webp +0 -0
  55. package/assets/illustrations/iso/automation-dark.svg +6 -0
  56. package/assets/illustrations/iso/automation.svg +6 -0
  57. package/assets/illustrations/iso/bar-chart-dark.svg +6 -0
  58. package/assets/illustrations/iso/bar-chart.svg +6 -0
  59. package/assets/illustrations/iso/brackets-classic-dark.svg +6 -0
  60. package/assets/illustrations/iso/brackets-classic.svg +6 -0
  61. package/assets/illustrations/iso/brackets-dark.svg +6 -0
  62. package/assets/illustrations/iso/brackets.svg +6 -0
  63. package/assets/illustrations/iso/city-dark.svg +6 -0
  64. package/assets/illustrations/iso/city.svg +6 -0
  65. package/assets/illustrations/iso/conveyor-dark.svg +6 -0
  66. package/assets/illustrations/iso/conveyor.svg +6 -0
  67. package/assets/illustrations/iso/database-dark.svg +6 -0
  68. package/assets/illustrations/iso/database.svg +6 -0
  69. package/assets/illustrations/iso/documents-dark.svg +6 -0
  70. package/assets/illustrations/iso/documents.svg +6 -0
  71. package/assets/illustrations/iso/inbox-dark.svg +6 -0
  72. package/assets/illustrations/iso/inbox.svg +6 -0
  73. package/assets/illustrations/iso/laptop-dark.svg +6 -0
  74. package/assets/illustrations/iso/laptop.svg +6 -0
  75. package/assets/illustrations/iso/monitor-dark.svg +6 -0
  76. package/assets/illustrations/iso/monitor.svg +6 -0
  77. package/assets/illustrations/iso/pipeline-dark.svg +6 -0
  78. package/assets/illustrations/iso/pipeline.svg +6 -0
  79. package/assets/illustrations/iso/platform-dark.svg +6 -0
  80. package/assets/illustrations/iso/platform.svg +6 -0
  81. package/assets/illustrations/iso/server-dark.svg +6 -0
  82. package/assets/illustrations/iso/server.svg +6 -0
  83. package/assets/illustrations/iso/spreadsheet-dark.svg +6 -0
  84. package/assets/illustrations/iso/spreadsheet.svg +6 -0
  85. package/assets/illustrations/iso/timeline-dark.svg +6 -0
  86. package/assets/illustrations/iso/timeline.svg +6 -0
  87. package/assets/illustrations/sheet/construction.svg +115 -0
  88. package/assets/illustrations/sheet/crescent.svg +40 -0
  89. package/assets/illustrations/sheet/limb.svg +42 -0
  90. package/assets/illustrations/sheet/stress-axis.svg +119 -0
  91. package/assets/illustrations/sheet/totality.svg +215 -0
  92. package/assets/illustrations/sheet/vertical-metrics.svg +43 -0
  93. package/assets/logo-left.svg +1 -0
  94. package/assets/logo-right.svg +1 -0
  95. package/assets/logo.svg +1 -0
  96. package/dist/components/_overlay.d.ts +47 -0
  97. package/dist/components/_overlay.js +59 -0
  98. package/dist/components/accordion.d.ts +32 -0
  99. package/dist/components/accordion.js +39 -0
  100. package/dist/components/alert-dialog.d.ts +45 -0
  101. package/dist/components/alert-dialog.js +56 -0
  102. package/dist/components/alert.d.ts +35 -0
  103. package/dist/components/alert.js +42 -0
  104. package/dist/components/ascii-field.d.ts +34 -0
  105. package/dist/components/ascii-field.js +410 -0
  106. package/dist/components/aspect-ratio.d.ts +14 -0
  107. package/dist/components/aspect-ratio.js +17 -0
  108. package/dist/components/avatar.d.ts +42 -0
  109. package/dist/components/avatar.js +55 -0
  110. package/dist/components/badge.d.ts +70 -0
  111. package/dist/components/badge.js +62 -0
  112. package/dist/components/breadcrumb.d.ts +22 -0
  113. package/dist/components/breadcrumb.js +32 -0
  114. package/dist/components/button-group.d.ts +30 -0
  115. package/dist/components/button-group.js +47 -0
  116. package/dist/components/button.d.ts +53 -0
  117. package/dist/components/button.js +130 -0
  118. package/dist/components/calendar.d.ts +26 -0
  119. package/dist/components/calendar.js +164 -0
  120. package/dist/components/card.d.ts +42 -0
  121. package/dist/components/card.js +76 -0
  122. package/dist/components/carousel.d.ts +90 -0
  123. package/dist/components/carousel.js +213 -0
  124. package/dist/components/chart.d.ts +180 -0
  125. package/dist/components/chart.js +286 -0
  126. package/dist/components/checkbox.d.ts +23 -0
  127. package/dist/components/checkbox.js +43 -0
  128. package/dist/components/code-block.d.ts +45 -0
  129. package/dist/components/code-block.js +58 -0
  130. package/dist/components/code-highlight.d.ts +13 -0
  131. package/dist/components/code-highlight.js +107 -0
  132. package/dist/components/collapsible.d.ts +20 -0
  133. package/dist/components/collapsible.js +32 -0
  134. package/dist/components/color-picker.d.ts +85 -0
  135. package/dist/components/color-picker.js +407 -0
  136. package/dist/components/combobox.d.ts +81 -0
  137. package/dist/components/combobox.js +100 -0
  138. package/dist/components/command.d.ts +112 -0
  139. package/dist/components/command.js +212 -0
  140. package/dist/components/context-menu.d.ts +29 -0
  141. package/dist/components/context-menu.js +35 -0
  142. package/dist/components/conversation.d.ts +27 -0
  143. package/dist/components/conversation.js +293 -0
  144. package/dist/components/copy-button.d.ts +46 -0
  145. package/dist/components/copy-button.js +118 -0
  146. package/dist/components/data-table.d.ts +175 -0
  147. package/dist/components/data-table.js +302 -0
  148. package/dist/components/date-picker.d.ts +91 -0
  149. package/dist/components/date-picker.js +207 -0
  150. package/dist/components/dialog.d.ts +48 -0
  151. package/dist/components/dialog.js +92 -0
  152. package/dist/components/direction.d.ts +16 -0
  153. package/dist/components/direction.js +18 -0
  154. package/dist/components/drawer.d.ts +60 -0
  155. package/dist/components/drawer.js +76 -0
  156. package/dist/components/empty.d.ts +31 -0
  157. package/dist/components/empty.js +50 -0
  158. package/dist/components/feature-list.d.ts +54 -0
  159. package/dist/components/feature-list.js +43 -0
  160. package/dist/components/field.d.ts +15 -0
  161. package/dist/components/field.js +36 -0
  162. package/dist/components/file-drop.d.ts +55 -0
  163. package/dist/components/file-drop.js +197 -0
  164. package/dist/components/filter-bar.d.ts +106 -0
  165. package/dist/components/filter-bar.js +296 -0
  166. package/dist/components/form.d.ts +33 -0
  167. package/dist/components/form.js +34 -0
  168. package/dist/components/graph.d.ts +105 -0
  169. package/dist/components/graph.js +786 -0
  170. package/dist/components/illustration.d.ts +85 -0
  171. package/dist/components/illustration.js +165 -0
  172. package/dist/components/input-group.d.ts +127 -0
  173. package/dist/components/input-group.js +292 -0
  174. package/dist/components/input.d.ts +16 -0
  175. package/dist/components/input.js +25 -0
  176. package/dist/components/item.d.ts +64 -0
  177. package/dist/components/item.js +116 -0
  178. package/dist/components/kbd.d.ts +33 -0
  179. package/dist/components/kbd.js +38 -0
  180. package/dist/components/label.d.ts +12 -0
  181. package/dist/components/label.js +24 -0
  182. package/dist/components/layout.d.ts +136 -0
  183. package/dist/components/layout.js +162 -0
  184. package/dist/components/logo.d.ts +54 -0
  185. package/dist/components/logo.js +96 -0
  186. package/dist/components/menu.d.ts +60 -0
  187. package/dist/components/menu.js +138 -0
  188. package/dist/components/menubar.d.ts +62 -0
  189. package/dist/components/menubar.js +223 -0
  190. package/dist/components/message.d.ts +42 -0
  191. package/dist/components/message.js +56 -0
  192. package/dist/components/meter.d.ts +31 -0
  193. package/dist/components/meter.js +25 -0
  194. package/dist/components/native-select.d.ts +26 -0
  195. package/dist/components/native-select.js +35 -0
  196. package/dist/components/navigation-menu.d.ts +42 -0
  197. package/dist/components/navigation-menu.js +97 -0
  198. package/dist/components/number-field.d.ts +36 -0
  199. package/dist/components/number-field.js +153 -0
  200. package/dist/components/otp-field.d.ts +35 -0
  201. package/dist/components/otp-field.js +94 -0
  202. package/dist/components/pagination.d.ts +31 -0
  203. package/dist/components/pagination.js +70 -0
  204. package/dist/components/pdf-viewer.d.ts +69 -0
  205. package/dist/components/pdf-viewer.js +929 -0
  206. package/dist/components/popover.d.ts +33 -0
  207. package/dist/components/popover.js +48 -0
  208. package/dist/components/preview-card.d.ts +25 -0
  209. package/dist/components/preview-card.js +22 -0
  210. package/dist/components/progress.d.ts +27 -0
  211. package/dist/components/progress.js +23 -0
  212. package/dist/components/prompt-input.d.ts +131 -0
  213. package/dist/components/prompt-input.js +403 -0
  214. package/dist/components/quote.d.ts +22 -0
  215. package/dist/components/quote.js +15 -0
  216. package/dist/components/radio-group.d.ts +18 -0
  217. package/dist/components/radio-group.js +34 -0
  218. package/dist/components/reasoning.d.ts +31 -0
  219. package/dist/components/reasoning.js +70 -0
  220. package/dist/components/resizable.d.ts +38 -0
  221. package/dist/components/resizable.js +41 -0
  222. package/dist/components/response.d.ts +30 -0
  223. package/dist/components/response.js +538 -0
  224. package/dist/components/scroll-area.d.ts +33 -0
  225. package/dist/components/scroll-area.js +31 -0
  226. package/dist/components/select.d.ts +35 -0
  227. package/dist/components/select.js +60 -0
  228. package/dist/components/separator.d.ts +14 -0
  229. package/dist/components/separator.js +17 -0
  230. package/dist/components/sidebar.d.ts +147 -0
  231. package/dist/components/sidebar.js +489 -0
  232. package/dist/components/site-header.d.ts +59 -0
  233. package/dist/components/site-header.js +67 -0
  234. package/dist/components/skeleton.d.ts +31 -0
  235. package/dist/components/skeleton.js +29 -0
  236. package/dist/components/slider.d.ts +24 -0
  237. package/dist/components/slider.js +129 -0
  238. package/dist/components/sources.d.ts +25 -0
  239. package/dist/components/sources.js +35 -0
  240. package/dist/components/spinner.d.ts +36 -0
  241. package/dist/components/spinner.js +72 -0
  242. package/dist/components/suggestions.d.ts +20 -0
  243. package/dist/components/suggestions.js +18 -0
  244. package/dist/components/switch.d.ts +14 -0
  245. package/dist/components/switch.js +26 -0
  246. package/dist/components/table.d.ts +162 -0
  247. package/dist/components/table.js +758 -0
  248. package/dist/components/tabs.d.ts +25 -0
  249. package/dist/components/tabs.js +162 -0
  250. package/dist/components/tag.d.ts +41 -0
  251. package/dist/components/tag.js +88 -0
  252. package/dist/components/tags-input.d.ts +40 -0
  253. package/dist/components/tags-input.js +239 -0
  254. package/dist/components/textarea.d.ts +13 -0
  255. package/dist/components/textarea.js +16 -0
  256. package/dist/components/theme.d.ts +41 -0
  257. package/dist/components/theme.js +112 -0
  258. package/dist/components/time-field.d.ts +51 -0
  259. package/dist/components/time-field.js +437 -0
  260. package/dist/components/timeline.d.ts +76 -0
  261. package/dist/components/timeline.js +99 -0
  262. package/dist/components/toast.d.ts +72 -0
  263. package/dist/components/toast.js +196 -0
  264. package/dist/components/toggle-group.d.ts +41 -0
  265. package/dist/components/toggle-group.js +140 -0
  266. package/dist/components/toggle.d.ts +23 -0
  267. package/dist/components/toggle.js +35 -0
  268. package/dist/components/tool-call.d.ts +52 -0
  269. package/dist/components/tool-call.js +57 -0
  270. package/dist/components/toolbar.d.ts +17 -0
  271. package/dist/components/toolbar.js +34 -0
  272. package/dist/components/tooltip.d.ts +42 -0
  273. package/dist/components/tooltip.js +47 -0
  274. package/dist/components/tree.d.ts +75 -0
  275. package/dist/components/tree.js +636 -0
  276. package/dist/components/typography.d.ts +134 -0
  277. package/dist/components/typography.js +176 -0
  278. package/dist/components/video-player.d.ts +276 -0
  279. package/dist/components/video-player.js +1352 -0
  280. package/dist/components/whiteboard.d.ts +80 -0
  281. package/dist/components/whiteboard.js +389 -0
  282. package/dist/index.d.ts +85 -0
  283. package/dist/index.js +86 -0
  284. package/dist/lib/cn.d.ts +20 -0
  285. package/dist/lib/cn.js +38 -0
  286. package/dist/lib/code-highlight.d.ts +31 -0
  287. package/dist/lib/code-highlight.js +24 -0
  288. package/dist/lib/code-theme.d.ts +19 -0
  289. package/dist/lib/code-theme.js +140 -0
  290. package/dist/lib/collapse-row.d.ts +9 -0
  291. package/dist/lib/collapse-row.js +129 -0
  292. package/dist/lib/digit-roll.d.ts +21 -0
  293. package/dist/lib/digit-roll.js +31 -0
  294. package/dist/lib/editorial-assets.d.ts +16 -0
  295. package/dist/lib/editorial-assets.js +56 -0
  296. package/dist/lib/figure/catalog.d.ts +127 -0
  297. package/dist/lib/figure/catalog.js +130 -0
  298. package/dist/lib/figure/figures/automation.d.ts +7 -0
  299. package/dist/lib/figure/figures/automation.js +143 -0
  300. package/dist/lib/figure/figures/bar-chart.d.ts +7 -0
  301. package/dist/lib/figure/figures/bar-chart.js +99 -0
  302. package/dist/lib/figure/figures/brackets-classic.d.ts +11 -0
  303. package/dist/lib/figure/figures/brackets-classic.js +170 -0
  304. package/dist/lib/figure/figures/brackets.d.ts +8 -0
  305. package/dist/lib/figure/figures/brackets.js +84 -0
  306. package/dist/lib/figure/figures/city.d.ts +7 -0
  307. package/dist/lib/figure/figures/city.js +93 -0
  308. package/dist/lib/figure/figures/conveyor.d.ts +7 -0
  309. package/dist/lib/figure/figures/conveyor.js +97 -0
  310. package/dist/lib/figure/figures/database.d.ts +7 -0
  311. package/dist/lib/figure/figures/database.js +65 -0
  312. package/dist/lib/figure/figures/documents.d.ts +7 -0
  313. package/dist/lib/figure/figures/documents.js +83 -0
  314. package/dist/lib/figure/figures/inbox.d.ts +7 -0
  315. package/dist/lib/figure/figures/inbox.js +92 -0
  316. package/dist/lib/figure/figures/laptop.d.ts +7 -0
  317. package/dist/lib/figure/figures/laptop.js +67 -0
  318. package/dist/lib/figure/figures/monitor.d.ts +7 -0
  319. package/dist/lib/figure/figures/monitor.js +59 -0
  320. package/dist/lib/figure/figures/pipeline.d.ts +8 -0
  321. package/dist/lib/figure/figures/pipeline.js +117 -0
  322. package/dist/lib/figure/figures/platform.d.ts +7 -0
  323. package/dist/lib/figure/figures/platform.js +117 -0
  324. package/dist/lib/figure/figures/server.d.ts +7 -0
  325. package/dist/lib/figure/figures/server.js +115 -0
  326. package/dist/lib/figure/figures/spreadsheet.d.ts +7 -0
  327. package/dist/lib/figure/figures/spreadsheet.js +87 -0
  328. package/dist/lib/figure/figures/timeline.d.ts +7 -0
  329. package/dist/lib/figure/figures/timeline.js +65 -0
  330. package/dist/lib/figure/kernel.d.ts +152 -0
  331. package/dist/lib/figure/kernel.js +576 -0
  332. package/dist/lib/figure/parts.d.ts +42 -0
  333. package/dist/lib/figure/parts.js +126 -0
  334. package/dist/lib/form-reset.d.ts +11 -0
  335. package/dist/lib/form-reset.js +22 -0
  336. package/dist/lib/glide.d.ts +53 -0
  337. package/dist/lib/glide.js +138 -0
  338. package/dist/lib/graph-layout.d.ts +58 -0
  339. package/dist/lib/graph-layout.js +200 -0
  340. package/dist/lib/illustration-drawings.d.ts +89 -0
  341. package/dist/lib/illustration-drawings.js +539 -0
  342. package/dist/lib/illustration-info.d.ts +37 -0
  343. package/dist/lib/illustration-info.js +22 -0
  344. package/dist/lib/illustration-library.d.ts +87 -0
  345. package/dist/lib/illustration-library.js +352 -0
  346. package/dist/lib/logo-geometry.d.ts +29 -0
  347. package/dist/lib/logo-geometry.js +67 -0
  348. package/dist/lib/markdown-guard.d.ts +16 -0
  349. package/dist/lib/markdown-guard.js +123 -0
  350. package/dist/lib/merge-refs.d.ts +10 -0
  351. package/dist/lib/merge-refs.js +26 -0
  352. package/dist/lib/motion.d.ts +6 -0
  353. package/dist/lib/motion.js +12 -0
  354. package/dist/lib/pdf-worker.d.ts +1 -0
  355. package/dist/lib/pdf-worker.js +6 -0
  356. package/dist/lib/pdf.d.ts +19 -0
  357. package/dist/lib/pdf.js +58 -0
  358. package/dist/lib/platform.d.ts +33 -0
  359. package/dist/lib/platform.js +68 -0
  360. package/dist/lib/room.d.ts +25 -0
  361. package/dist/lib/room.js +46 -0
  362. package/dist/lib/table-fit.d.ts +143 -0
  363. package/dist/lib/table-fit.js +577 -0
  364. package/dist/lib/theme-script.d.ts +18 -0
  365. package/dist/lib/theme-script.js +29 -0
  366. package/dist/styles/expressive.css +188 -0
  367. package/dist/styles/fonts.css +145 -0
  368. package/dist/styles/index.css +206 -0
  369. package/dist/styles/material.css +313 -0
  370. package/dist/styles/parts/ai.css +360 -0
  371. package/dist/styles/parts/brand.css +75 -0
  372. package/dist/styles/parts/controls.css +725 -0
  373. package/dist/styles/parts/data.css +222 -0
  374. package/dist/styles/parts/editorial.css +120 -0
  375. package/dist/styles/parts/feedback.css +273 -0
  376. package/dist/styles/parts/foundations.css +166 -0
  377. package/dist/styles/parts/graph.css +214 -0
  378. package/dist/styles/parts/inputs.css +261 -0
  379. package/dist/styles/parts/isometric.css +124 -0
  380. package/dist/styles/parts/navigation.css +232 -0
  381. package/dist/styles/parts/overlays.css +250 -0
  382. package/dist/styles/parts/pdf.css +154 -0
  383. package/dist/styles/parts/react-flow.css +519 -0
  384. package/dist/styles/parts/whiteboard.css +855 -0
  385. package/dist/styles/tokens.css +290 -0
  386. package/dist/vite.d.ts +116 -0
  387. package/dist/vite.js +129 -0
  388. package/package.json +188 -5
@@ -0,0 +1,1352 @@
1
+ "use client";
2
+ import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
+ import { Slider as BaseSlider } from "@base-ui/react/slider";
4
+ import { AirplayIcon, ArrowLeftIcon, AudioLinesIcon, CaptionsIcon, CaptionsOffIcon, ChevronLeftIcon, GalleryVerticalEndIcon, LanguagesIcon, MaximizeIcon, MinimizeIcon, PauseIcon, PictureInPicture2Icon, PlayIcon, RotateCcwIcon, RotateCwIcon, SkipForwardIcon, VideoOffIcon, Volume1Icon, Volume2Icon, VolumeXIcon, } from "lucide-react";
5
+ import * as React from "react";
6
+ import { cn } from "../lib/cn.js";
7
+ import { mergeRefs } from "../lib/merge-refs.js";
8
+ import { Button } from "./button.js";
9
+ import { DirectionProvider } from "./direction.js";
10
+ import { Menu, MenuContent, MenuGroup, MenuGroupLabel, MenuItem, MenuRadioGroup, MenuRadioItem, MenuSeparator, MenuTrigger, } from "./menu.js";
11
+ import { Skeleton } from "./skeleton.js";
12
+ import { Spinner } from "./spinner.js";
13
+ import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "./tooltip.js";
14
+ const plural = (n, unit) => `${n} ${unit}${n === 1 ? "" : "s"}`;
15
+ const DEFAULT_LABELS = {
16
+ player: "Video player",
17
+ play: "Play",
18
+ pause: "Pause",
19
+ playAgain: "Play again",
20
+ back: "Back",
21
+ skipBack: (seconds) => `Back ${seconds} seconds`,
22
+ skipForward: (seconds) => `Forward ${seconds} seconds`,
23
+ next: "Next episode",
24
+ mute: "Mute",
25
+ unmute: "Unmute",
26
+ volume: "Volume",
27
+ seek: "Seek",
28
+ duration: (seconds) => {
29
+ const s = Math.max(0, Math.floor(seconds || 0));
30
+ const h = Math.floor(s / 3600);
31
+ const m = Math.floor((s % 3600) / 60);
32
+ return [h && plural(h, "hour"), m && plural(m, "minute"), plural(s % 60, "second")]
33
+ .filter(Boolean)
34
+ .join(" ");
35
+ },
36
+ position: (time, total) => `${time} of ${total}`,
37
+ remaining: (time) => `${time} left`,
38
+ subtitles: "Subtitles",
39
+ subtitlesOff: "Off",
40
+ showSubtitles: "Show subtitles",
41
+ hideSubtitles: "Hide subtitles",
42
+ audio: "Audio",
43
+ audioAndSubtitles: "Audio and subtitles",
44
+ quality: "Quality",
45
+ speed: "Speed",
46
+ normalSpeed: "Normal",
47
+ rate: (rate) => `${rate}×`,
48
+ episodes: "Episodes",
49
+ seasons: "Seasons",
50
+ nowPlaying: "Now playing",
51
+ episodeCount: (count) => plural(count, "episode"),
52
+ pictureInPicture: "Picture in picture",
53
+ leavePictureInPicture: "Leave picture in picture",
54
+ fullScreen: "Full screen",
55
+ exitFullScreen: "Exit full screen",
56
+ loading: "Loading video",
57
+ error: "This video can't be played.",
58
+ airPlay: "AirPlay",
59
+ retry: "Try again",
60
+ tryQuality: (quality) => `Try ${quality}`,
61
+ jumped: (seconds) => `${seconds < 0 ? "−" : "+"}${Math.abs(seconds)} s`,
62
+ preparingSubtitles: "Preparing subtitles…",
63
+ };
64
+ const playerVariants = {
65
+ region: "surface-container",
66
+ card: "rounded-card surface-card [--card-padding:0]",
67
+ plain: "",
68
+ };
69
+ const DEFAULT_SPEEDS = [0.5, 0.75, 1, 1.25, 1.5, 2];
70
+ /** How long the controls stay after the pointer or keyboard was last used, while playing. */
71
+ const IDLE_MS = 2500;
72
+ /** How far the movie layout's skip buttons jump, in seconds. */
73
+ const SKIP = 10;
74
+ /** From this frame width the movie layout's controls grow to the prominent size. */
75
+ const LARGE_FRAME = 768;
76
+ /** How wide a timeline preview shows: the normal and the large movie layout. */
77
+ const PREVIEW_WIDTH = 176;
78
+ const PREVIEW_WIDTH_LARGE = 256;
79
+ /** How long the play or pause icon shows in the middle after the viewer toggles, in ms. */
80
+ const FLASH_MS = 700;
81
+ /** The last moment of a segment that still offers its skip, so it doesn't flash at the cut. */
82
+ const SEGMENT_TAIL = 0.5;
83
+ /** How long a skip stays on its own, in seconds of playback; after that it shows with the controls. */
84
+ const SEGMENT_PROMPT = 15;
85
+ /** An automatic skip's countdown, in seconds of playback. */
86
+ const AUTO_COUNTDOWN = 10;
87
+ /** How far the playhead moves before the controls show its new time (s): often enough for the eye, not every frame. */
88
+ const TIME_STEP = 0.1;
89
+ /** The scrubber's step (s). Its last value rounds to a step, so a drag to the end may land up to half a step short. */
90
+ const SCRUB_STEP = 0.1;
91
+ /** A click on the picture this soon after a menu closed only closed the menu (ms). */
92
+ const MENU_CLOSE_MS = 400;
93
+ /** Two taps this close together are a double tap (ms). */
94
+ const DOUBLE_TAP_MS = 350;
95
+ /** A double tap's jump shows this long, and taps within it add to the jump (ms). */
96
+ const JUMP_MS = 700;
97
+ /** A subtitle file still on its way after this long gets a note where the subtitles show (ms). */
98
+ const SUBTITLE_SLOW_MS = 2000;
99
+ /** Asks for a subtitle file, and the pause between them (ms): cutting one out of a whole file can outlast a request. */
100
+ const SUBTITLE_TRIES = 4;
101
+ const SUBTITLE_RETRY_MS = 15_000;
102
+ /** 75 → "1:15", 3725 → "1:02:05". */
103
+ function formatTime(seconds) {
104
+ const s = Number.isFinite(seconds) && seconds > 0 ? Math.floor(seconds) : 0;
105
+ const h = Math.floor(s / 3600);
106
+ const m = Math.floor((s % 3600) / 60);
107
+ const rest = String(s % 60).padStart(2, "0");
108
+ return h > 0 ? `${h}:${String(m).padStart(2, "0")}:${rest}` : `${m}:${rest}`;
109
+ }
110
+ /**
111
+ * A cue's lines as text. Subtitles converted from ASS (most anime) keep its override tags, such
112
+ * as `{\\fad(250,0)\\blur2}`, and its `\\N` breaks; WebVTT itself has neither.
113
+ */
114
+ function cueLines(text) {
115
+ return text
116
+ .replace(/\{\\[^}]*\}/g, "")
117
+ .replace(/\\N/gi, "\n")
118
+ .split("\n")
119
+ .map((line) => line.trim())
120
+ .filter(Boolean);
121
+ }
122
+ /** The end of the buffered range the playhead is in. */
123
+ function bufferedEnd(video) {
124
+ const { buffered, currentTime } = video;
125
+ for (let i = 0; i < buffered.length; i++) {
126
+ if (buffered.start(i) <= currentTime + 0.5 && currentTime <= buffered.end(i))
127
+ return buffered.end(i);
128
+ }
129
+ return 0;
130
+ }
131
+ /** The distinct values of one field across the versions, in the order they are listed. */
132
+ function choices(versions, field) {
133
+ return [...new Set(versions.map((v) => v[field]).filter((v) => !!v))];
134
+ }
135
+ /** The version with this audio and quality; failing that, one with the audio, then the quality. */
136
+ function pickVersion(versions, audio, quality) {
137
+ return (versions.find((v) => v.audio === audio && v.quality === quality) ??
138
+ versions.find((v) => v.audio === audio) ??
139
+ versions.find((v) => v.quality === quality) ??
140
+ versions[0]);
141
+ }
142
+ const sourceKey = (src) => src === undefined ? "" : typeof src === "string" ? src : src.map((s) => s.src).join("|");
143
+ /**
144
+ * A source with a media fragment (`#t=2712.4`): the browser loads from there. Without it, a
145
+ * stream (HLS from a media server) is fetched from its beginning only to seek away again.
146
+ */
147
+ const startingAt = (src, time) => time > 0 ? `${src.split("#")[0]}#t=${time.toFixed(1)}` : src;
148
+ const PLAYHEAD_START = { time: 0, scrub: null, buffered: 0 };
149
+ /**
150
+ * The playhead, kept outside React state. It moves ten times a second while the video plays, and
151
+ * only the parts that show it (the scrubber, the times, a segment's skip) follow it; the rest of
152
+ * the player doesn't redraw.
153
+ */
154
+ function createPlayhead() {
155
+ let state = PLAYHEAD_START;
156
+ const listeners = new Set();
157
+ return {
158
+ get: () => state,
159
+ set(next) {
160
+ if (Object.keys(next).every((key) => next[key] === state[key]))
161
+ return;
162
+ state = { ...state, ...next };
163
+ for (const listener of listeners)
164
+ listener();
165
+ },
166
+ subscribe(listener) {
167
+ listeners.add(listener);
168
+ return () => {
169
+ listeners.delete(listener);
170
+ };
171
+ },
172
+ };
173
+ }
174
+ /**
175
+ * At the end, or within a scrubber step of it, of a video with a length that doesn't loop: decided
176
+ * by position, since a stream still fetching its last part doesn't know yet that it has ended.
177
+ */
178
+ const atEnd = (video) => !video.loop && Number.isFinite(video.duration) && video.duration - video.currentTime <= SCRUB_STEP;
179
+ /** The players on the page that play with sound one at a time (`pauseOthers`). */
180
+ const soundPlayers = new Set();
181
+ const audible = (video) => !video.paused && !video.muted && video.volume > 0;
182
+ /** This player started with sound: the others that have sound pause. Muted ones play on. */
183
+ function hushOthers(video) {
184
+ if (!soundPlayers.has(video))
185
+ return;
186
+ for (const other of soundPlayers)
187
+ if (other !== video && audible(other))
188
+ other.pause();
189
+ }
190
+ /** The volume and mute stored under `volumeStorageKey`, when there are any and they're the player's own. */
191
+ function readVolume(key) {
192
+ try {
193
+ const stored = JSON.parse(window.localStorage.getItem(key) ?? "null");
194
+ const { volume, muted } = (stored ?? {});
195
+ return typeof volume === "number" && volume >= 0 && volume <= 1 && typeof muted === "boolean"
196
+ ? { volume, muted }
197
+ : null;
198
+ }
199
+ catch {
200
+ // Storage unavailable (private mode, blocked site data), or something else's under that key: the defaults stand.
201
+ return null;
202
+ }
203
+ }
204
+ function writeVolume(key, volume, muted) {
205
+ try {
206
+ window.localStorage.setItem(key, JSON.stringify({ volume, muted }));
207
+ }
208
+ catch {
209
+ // Ignore: remembering is a convenience.
210
+ }
211
+ }
212
+ /** One value from the playhead: the component redraws when that value changes, not at every tick. */
213
+ function usePlayhead(playhead, select) {
214
+ return React.useSyncExternalStore(playhead.subscribe, () => select(playhead.get()), () => select(PLAYHEAD_START));
215
+ }
216
+ /**
217
+ * The track and its thumb, shared by the scrubber and the volume. The same material as `Slider`,
218
+ * and like it in a contrast theme (Windows), which paints fills over with the page colour: the
219
+ * value takes the system highlight and the thumb an edge.
220
+ */
221
+ const trackClass = "relative h-1.5 w-full rounded-full material-field select-none";
222
+ const indicatorClass = "rounded-full bg-foreground-soft select-none forced-color-adjust-none forced-colors:bg-[Highlight]";
223
+ const thumbClass = cn("size-[18px] rounded-full bg-control-surface bg-linear-to-b from-control-inner-edge to-transparent shadow-thumb select-none forced-colors:border-2", "transition-[background-color,box-shadow] duration-(--duration) ease-brand hover:bg-control-hover data-dragging:bg-control-hover", "has-[:focus-visible]:outline-2 has-[:focus-visible]:outline-offset-0 has-[:focus-visible]:outline-control-focus");
224
+ /**
225
+ * VideoPlayer — a video in the zon material: the picture letterboxed on black, and over it
226
+ * controls set dark whatever the page's theme — play, a scrubber with the buffered range and the
227
+ * time under the pointer, the time in Licht Mono, volume, speed, subtitles, audio and quality
228
+ * versions, picture in picture and full screen.
229
+ *
230
+ * A **region** by default: a square frame, part of the page. `variant="card"` makes it a 20px
231
+ * object for a clip that stands on its own; `plain` has no surface, for a dialog.
232
+ *
233
+ * Two layouts. `default` floats one dense bar in the menu material, for a clip on a page.
234
+ * `movie` lays the controls on a dark fade with the title above them and the timeline alone on
235
+ * the bottom row, for watching something long. While the video plays the controls step back
236
+ * after a moment without input and come back with any pointer movement, key press or focus.
237
+ * Subtitles are drawn by the player in Licht Sans and rise above the controls when they show.
238
+ *
239
+ * The rule people break: autoplaying with sound. Browsers block it, and people leave. Autoplay
240
+ * only `muted`, and only where the video is the point of the page.
241
+ */
242
+ export function VideoPlayer({ src, versions = [], defaultAudio, defaultQuality, poster, title, tracks = [], subtitle: subtitleProp, onSubtitleChange, onAudioChange, onQualityChange, loading: preparing = false, overlay, previews, segments = [], subtitleScale = 1, layout = "default", variant = "region", aspectRatio = 16 / 9, startTime, autoPlay = false, loop = false, muted: startMuted = false, volumeStorageKey, pauseOthers = true, speeds = DEFAULT_SPEEDS, pictureInPicture: allowPip = true, fullscreen: allowFullscreen = true, pageShortcuts = false, onPlay, onPause, onEnded, onTimeChange, videoRef, onBack, onNext, seasons = [], currentEpisode, onSeasonOpen, onEpisodeSelect, labels: labelOverrides, className, style, ref, onKeyDown, onPointerMove, onPointerDown, onFocus, ...props }) {
243
+ const root = React.useRef(null);
244
+ // The player's own ref and the app's: in React 19 `ref` is a prop, and spread after it would replace it.
245
+ const rootRef = React.useMemo(() => mergeRefs(root, ref), [ref]);
246
+ // Whether the control in focus was clicked rather than tabbed to: its shortcuts then go to the player.
247
+ const pointerFocus = React.useRef(false);
248
+ const video = React.useRef(null);
249
+ const movie = layout === "movie";
250
+ const labels = { ...DEFAULT_LABELS, ...labelOverrides };
251
+ const [playing, setPlaying] = React.useState(false);
252
+ const [started, setStarted] = React.useState(autoPlay);
253
+ const [ended, setEnded] = React.useState(false);
254
+ const [waiting, setWaiting] = React.useState(false);
255
+ const [failed, setFailed] = React.useState(false);
256
+ const [playhead] = React.useState(createPlayhead);
257
+ const [duration, setDuration] = React.useState(0);
258
+ const [volume, setVolume] = React.useState(1);
259
+ const [muted, setMuted] = React.useState(startMuted);
260
+ const [rate, setRate] = React.useState(1);
261
+ // The scrubber's thumb is being dragged: the controls stay meanwhile.
262
+ const [scrubbing, setScrubbing] = React.useState(false);
263
+ // The frame's width, for the large layout.
264
+ const [frameWidth, setFrameWidth] = React.useState(0);
265
+ // The subtitle track shown (-1: off), and the one C brings back.
266
+ const [subtitle, setSubtitle] = React.useState(() => subtitleProp ?? tracks.findIndex((t) => t.default));
267
+ // The app's choice shows until the viewer makes one, and again whenever the app changes it.
268
+ const [appSubtitle, setAppSubtitle] = React.useState(subtitleProp);
269
+ if (appSubtitle !== subtitleProp) {
270
+ setAppSubtitle(subtitleProp);
271
+ if (subtitleProp !== undefined)
272
+ setSubtitle(subtitleProp);
273
+ }
274
+ // Other tracks (the next episode's, in the same player): the app's choice for them, or their default.
275
+ const tracksKey = tracks.map((t) => t.src).join("|");
276
+ const [shownTracks, setShownTracks] = React.useState(tracksKey);
277
+ if (shownTracks !== tracksKey) {
278
+ setShownTracks(tracksKey);
279
+ setSubtitle(subtitleProp ?? tracks.findIndex((t) => t.default));
280
+ }
281
+ const lastSubtitle = React.useRef(Math.max(0, subtitle));
282
+ React.useEffect(() => {
283
+ if (subtitle >= 0)
284
+ lastSubtitle.current = subtitle;
285
+ }, [subtitle]);
286
+ const [cue, setCue] = React.useState("");
287
+ const [isFullscreen, setFullscreen] = React.useState(false);
288
+ const [inPip, setInPip] = React.useState(false);
289
+ // The browser's own presentation (iOS full screen) or a screen elsewhere (AirPlay): only the
290
+ // browser's own subtitle drawing reaches it.
291
+ const [systemView, setSystemView] = React.useState(false);
292
+ const [airPlaying, setAirPlaying] = React.useState(false);
293
+ const [canAirPlay, setCanAirPlay] = React.useState(false);
294
+ const [canPip, setCanPip] = React.useState(false);
295
+ const [canFullscreen, setCanFullscreen] = React.useState(false);
296
+ const [menusOpen, setMenusOpen] = React.useState(0);
297
+ const [idle, setIdle] = React.useState(false);
298
+ const [overControls, setOverControls] = React.useState(false);
299
+ const audios = choices(versions, "audio");
300
+ const qualities = choices(versions, "quality");
301
+ const [audio, setAudio] = React.useState(() => defaultAudio ?? versions[0]?.audio);
302
+ const [quality, setQuality] = React.useState(() => defaultQuality ?? versions[0]?.quality);
303
+ const version = versions.length > 0 ? pickVersion(versions, audio, quality) : undefined;
304
+ const current = version?.src ?? src ?? "";
305
+ // Where a source starts: `startTime` for the first, the moment of the switch for a new version.
306
+ const [start, setStart] = React.useState(() => ({ key: sourceKey(current), time: startTime ?? 0 }));
307
+ // Another title (the next episode, in the same player) starts where the app says.
308
+ const startOf = start.key === sourceKey(current) ? start.time : (startTime ?? 0);
309
+ // ... with its own audio and quality to begin with.
310
+ const titleKey = currentEpisode ?? (versions.length > 0 ? versions.map((v) => v.src).join("|") : sourceKey(src));
311
+ const [shownTitle, setShownTitle] = React.useState(titleKey);
312
+ if (shownTitle !== titleKey) {
313
+ setShownTitle(titleKey);
314
+ setAudio(defaultAudio ?? versions[0]?.audio);
315
+ setQuality(defaultQuality ?? versions[0]?.quality);
316
+ }
317
+ // Through `mergeRefs`, so a React 19 callback ref's own cleanup runs (an hls.js `destroy()`, say).
318
+ const videoRefs = React.useMemo(() => mergeRefs(video, videoRef), [videoRef]);
319
+ // The latest callbacks, for the video's own event listeners.
320
+ const callbacks = React.useRef({ onPlay, onPause, onEnded, onTimeChange });
321
+ callbacks.current = { onPlay, onPause, onEnded, onTimeChange };
322
+ // The controls step back after IDLE_MS without input; any input brings them back.
323
+ const idleTimer = React.useRef(0);
324
+ const wake = React.useCallback(() => {
325
+ setIdle(false);
326
+ clearTimeout(idleTimer.current);
327
+ idleTimer.current = window.setTimeout(() => setIdle(true), IDLE_MS);
328
+ }, []);
329
+ React.useEffect(() => () => clearTimeout(idleTimer.current), []);
330
+ // A control in the bar (or the title's back arrow) has focus, and whether the keyboard put it there.
331
+ // The keyboard's keeps the controls, and the caption, scrim and skip that move with them; before
332
+ // the first play, any focus keeps the bar it's in, so a click on it lands.
333
+ const [focusIn, setFocusIn] = React.useState(null);
334
+ const focusProps = {
335
+ onFocus: (event) => setFocusIn(event.target.matches(":focus-visible") ? "keyboard" : "pointer"),
336
+ onBlur: (event) => {
337
+ if (!event.currentTarget.contains(event.relatedTarget))
338
+ setFocusIn(null);
339
+ },
340
+ };
341
+ const hidden = playing && idle && menusOpen === 0 && !scrubbing && !overControls && focusIn !== "keyboard";
342
+ // A click on the picture that closes a menu is only that, not a play or pause.
343
+ const menuClosedAt = React.useRef(0);
344
+ const onMenuOpenChange = React.useCallback((open) => {
345
+ if (!open)
346
+ menuClosedAt.current = performance.now();
347
+ setMenusOpen((n) => Math.max(0, n + (open ? 1 : -1)));
348
+ }, []);
349
+ React.useEffect(() => {
350
+ const el = root.current;
351
+ if (!el)
352
+ return;
353
+ const observer = new ResizeObserver(([entry]) => entry && setFrameWidth(entry.contentRect.width));
354
+ observer.observe(el);
355
+ return () => observer.disconnect();
356
+ }, []);
357
+ // What the browser offers, known only after mount.
358
+ React.useEffect(() => {
359
+ const el = video.current;
360
+ setCanPip("pictureInPictureEnabled" in document && document.pictureInPictureEnabled);
361
+ setCanFullscreen(!!document.fullscreenEnabled || !!el?.webkitEnterFullscreen);
362
+ if (!el)
363
+ return;
364
+ // Safari: AirPlay screens nearby, and whether the video plays on one; iOS: its own full screen.
365
+ const availability = (event) => setCanAirPlay(event.availability === "available");
366
+ const wireless = () => setAirPlaying(!!el.webkitCurrentPlaybackTargetIsWireless);
367
+ const begin = () => setSystemView(true);
368
+ const end = () => setSystemView(false);
369
+ const events = [
370
+ ["webkitplaybacktargetavailabilitychanged", availability],
371
+ ["webkitcurrentplaybacktargetiswirelesschanged", wireless],
372
+ ["webkitbeginfullscreen", begin],
373
+ ["webkitendfullscreen", end],
374
+ ];
375
+ for (const [type, handler] of events)
376
+ el.addEventListener(type, handler);
377
+ return () => {
378
+ for (const [type, handler] of events)
379
+ el.removeEventListener(type, handler);
380
+ };
381
+ }, []);
382
+ // Where to pick up after switching versions: the playhead, and whether it was playing.
383
+ const resume = React.useRef(null);
384
+ // What the app was last told: a version switch or a retry, which play again on the way, tells it nothing new.
385
+ const told = React.useRef("pause");
386
+ // A drag on the scrubber holds the playing video still until the thumb is let go: to the app it plays on.
387
+ const holding = React.useRef(false);
388
+ // The video can't be played. The controls go, with their menus and without a pointer leaving or a
389
+ // blur: what held them up (an open menu, the pointer, focus) would otherwise hold them up for good.
390
+ const fail = () => {
391
+ setFailed(true);
392
+ setMenusOpen(0);
393
+ setOverControls(false);
394
+ setFocusIn(null);
395
+ };
396
+ // The video's own events are the source of truth for every control.
397
+ React.useEffect(() => {
398
+ const el = video.current;
399
+ if (!el)
400
+ return;
401
+ let frame = 0;
402
+ let shownAt = -1;
403
+ // Each frame would redraw the scrubber sixty times a second; the eye needs far fewer.
404
+ const show = () => {
405
+ const now = el.currentTime;
406
+ if (!el.paused && Math.abs(now - shownAt) < TIME_STEP)
407
+ return;
408
+ shownAt = now;
409
+ playhead.set({ time: now });
410
+ callbacks.current.onTimeChange?.(now);
411
+ };
412
+ const tick = () => {
413
+ show();
414
+ frame = el.paused ? 0 : requestAnimationFrame(tick);
415
+ };
416
+ const sync = () => {
417
+ setDuration(Number.isFinite(el.duration) ? el.duration : 0);
418
+ playhead.set({ time: el.currentTime, buffered: bufferedEnd(el) });
419
+ setVolume(el.volume);
420
+ setMuted(el.muted);
421
+ setRate(el.playbackRate);
422
+ };
423
+ // Whether it could be heard: becoming so while it plays is as good as starting with sound.
424
+ let heard = !el.muted && el.volume > 0;
425
+ const handlers = {
426
+ loadedmetadata: () => {
427
+ const back = resume.current;
428
+ resume.current = null;
429
+ // The source started there already, where the browser follows its media fragment.
430
+ if (back && Math.abs(el.currentTime - back.time) > 1) {
431
+ el.currentTime = Math.min(back.time, Number.isFinite(el.duration) ? el.duration : back.time);
432
+ }
433
+ if (back?.play)
434
+ void el.play().catch(() => undefined);
435
+ sync();
436
+ },
437
+ durationchange: sync,
438
+ volumechange: () => {
439
+ setVolume(el.volume);
440
+ setMuted(el.muted);
441
+ const now = !el.muted && el.volume > 0;
442
+ if (now && !heard && !el.paused)
443
+ hushOthers(el);
444
+ heard = now;
445
+ },
446
+ ratechange: () => setRate(el.playbackRate),
447
+ progress: () => playhead.set({ buffered: bufferedEnd(el) }),
448
+ // In a hidden tab (picture in picture over another) frames stop, time doesn't: skips and countdowns go on.
449
+ timeupdate: show,
450
+ play: () => {
451
+ setPlaying(true);
452
+ setStarted(true);
453
+ setEnded(false);
454
+ cancelAnimationFrame(frame);
455
+ frame = requestAnimationFrame(tick);
456
+ // Without a pointer anywhere (autoplay, the next episode), the controls still step back.
457
+ wake();
458
+ if (told.current === "play")
459
+ return;
460
+ told.current = "play";
461
+ callbacks.current.onPlay?.();
462
+ if (audible(el))
463
+ hushOthers(el);
464
+ },
465
+ pause: () => {
466
+ setPlaying(false);
467
+ playhead.set({ time: el.currentTime });
468
+ // A version switch pauses on the way, and a drag on the scrubber holds it: not the viewer's pause.
469
+ if (resume.current || holding.current)
470
+ return;
471
+ told.current = "pause";
472
+ callbacks.current.onPause?.();
473
+ },
474
+ seeked: () => playhead.set({ time: el.currentTime, buffered: bufferedEnd(el) }),
475
+ waiting: () => setWaiting(true),
476
+ playing: () => setWaiting(false),
477
+ canplay: () => setWaiting(false),
478
+ ended: () => {
479
+ setPlaying(false);
480
+ setEnded(true);
481
+ // Declared already, when the scrubber was let go at the end.
482
+ if (told.current === "ended")
483
+ return;
484
+ told.current = "ended";
485
+ callbacks.current.onEnded?.();
486
+ },
487
+ // A `src` that fails; one of several `<source>`s tells its own element (below).
488
+ error: fail,
489
+ enterpictureinpicture: () => setInPip(true),
490
+ leavepictureinpicture: () => setInPip(false),
491
+ };
492
+ for (const [type, handler] of Object.entries(handlers))
493
+ el.addEventListener(type, handler);
494
+ el.muted = startMuted;
495
+ if (el.readyState >= 1)
496
+ sync();
497
+ return () => {
498
+ cancelAnimationFrame(frame);
499
+ for (const [type, handler] of Object.entries(handlers))
500
+ el.removeEventListener(type, handler);
501
+ };
502
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- `muted` is the starting state only.
503
+ }, []);
504
+ // The volume and mute the viewer left (`volumeStorageKey`), read once mounted, so the server's
505
+ // render and the first one here agree. A stored "unmuted" never unmutes a muted or autoplaying player.
506
+ React.useEffect(() => {
507
+ const el = video.current;
508
+ const stored = volumeStorageKey ? readVolume(volumeStorageKey) : null;
509
+ if (!el || !stored)
510
+ return;
511
+ el.volume = stored.volume;
512
+ if (stored.muted)
513
+ el.muted = true;
514
+ else if (!startMuted && !autoPlay)
515
+ el.muted = false;
516
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- the starting state, read for each key.
517
+ }, [volumeStorageKey]);
518
+ // The viewer's own change of volume or mute, kept for next time.
519
+ const remember = () => {
520
+ const el = video.current;
521
+ if (el && volumeStorageKey)
522
+ writeVolume(volumeStorageKey, el.volume, el.muted);
523
+ };
524
+ // One player with sound at a time: this one pauses the others as it starts with sound, and they it.
525
+ React.useEffect(() => {
526
+ const el = video.current;
527
+ if (!el || !pauseOthers)
528
+ return;
529
+ soundPlayers.add(el);
530
+ return () => {
531
+ soundPlayers.delete(el);
532
+ };
533
+ }, [pauseOthers]);
534
+ // A new source loads; a new video starts over, a switched version carries on (`resume`).
535
+ const srcKey = sourceKey(current);
536
+ React.useEffect(() => {
537
+ setFailed(false);
538
+ if (!resume.current) {
539
+ setEnded(false);
540
+ setStarted(autoPlay);
541
+ playhead.set({ time: 0 });
542
+ }
543
+ playhead.set({ buffered: 0 });
544
+ video.current?.load();
545
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- reload only when the source changes.
546
+ }, [srcKey]);
547
+ const switchVersion = (next) => {
548
+ const el = video.current;
549
+ const target = pickVersion(versions, next.audio ?? audio, next.quality ?? quality);
550
+ if (el && target && sourceKey(target.src) !== srcKey && (el.readyState > 0 || failed)) {
551
+ resume.current = { time: el.currentTime || startOf, play: failed || (!el.paused && !el.ended) };
552
+ setStart({ key: sourceKey(target.src), time: el.currentTime });
553
+ }
554
+ if (next.audio !== undefined)
555
+ setAudio(next.audio);
556
+ if (next.quality !== undefined)
557
+ setQuality(next.quality);
558
+ };
559
+ // Subtitles: the browser parses the track, the player draws the cue. The <track> elements are
560
+ // the tracks without a renderer of their own, in order.
561
+ const latestTracks = React.useRef(tracks);
562
+ latestTracks.current = tracks;
563
+ // The browser holds the picture back while a track it shows is still loading, and a server may
564
+ // take minutes to cut one out of the file. So the chosen track is fetched beside the video, which
565
+ // plays meanwhile, and given to its <track> from memory once it's here.
566
+ const [loaded, setLoaded] = React.useState({});
567
+ const loadedRef = React.useRef(loaded);
568
+ loadedRef.current = loaded;
569
+ // Every copy not yet let go, noted the moment it's made: one made just as the player goes never
570
+ // reaches `loaded`, and would outlive it.
571
+ const copies = React.useRef(new Set());
572
+ // The last track that couldn't be had, however often it was asked for: nothing waits for it.
573
+ const [unloadable, setUnloadable] = React.useState(null);
574
+ const chosenSrc = subtitle >= 0 && !tracks[subtitle]?.render ? tracks[subtitle]?.src : undefined;
575
+ const chosenReady = !!chosenSrc && !!loaded[chosenSrc];
576
+ React.useEffect(() => {
577
+ if (!chosenSrc || loadedRef.current[chosenSrc])
578
+ return;
579
+ const wanted = chosenSrc;
580
+ // Another track chosen, or the player gone: this one's request stops, and so do its tries.
581
+ const abort = new AbortController();
582
+ let tries = 0;
583
+ let retry = 0;
584
+ const attempt = () => {
585
+ tries += 1;
586
+ fetch(wanted, { credentials: "same-origin", signal: abort.signal })
587
+ .then((response) => {
588
+ if (response.ok)
589
+ return response.text();
590
+ // Not there, or not allowed: asking again changes nothing. A server error or a timeout may pass.
591
+ if (response.status < 500 && response.status !== 408 && response.status !== 429)
592
+ tries = SUBTITLE_TRIES;
593
+ throw new Error(String(response.status));
594
+ })
595
+ .then((text) => {
596
+ if (abort.signal.aborted)
597
+ return;
598
+ const url = URL.createObjectURL(new Blob([text], { type: "text/vtt" }));
599
+ copies.current.add(url);
600
+ setLoaded((all) => ({ ...all, [wanted]: url }));
601
+ })
602
+ .catch(() => {
603
+ if (abort.signal.aborted)
604
+ return;
605
+ // The server goes on cutting the subtitles out of the file after a request gave up
606
+ // (a tunnel waits 100 s at most): asked again later, it has them.
607
+ if (tries < SUBTITLE_TRIES)
608
+ retry = window.setTimeout(attempt, SUBTITLE_RETRY_MS);
609
+ // Chosen again later, it tries again.
610
+ else
611
+ setUnloadable(wanted);
612
+ });
613
+ };
614
+ attempt();
615
+ return () => {
616
+ abort.abort();
617
+ clearTimeout(retry);
618
+ };
619
+ }, [chosenSrc]);
620
+ // Other tracks (the next episode's): the last ones' copies go.
621
+ React.useEffect(() => {
622
+ const now = new Set(latestTracks.current.map((t) => t.src));
623
+ const stale = Object.entries(loadedRef.current).filter(([src]) => !now.has(src));
624
+ if (stale.length === 0)
625
+ return;
626
+ for (const [, url] of stale) {
627
+ URL.revokeObjectURL(url);
628
+ copies.current.delete(url);
629
+ }
630
+ setLoaded((all) => Object.fromEntries(Object.entries(all).filter(([src]) => now.has(src))));
631
+ }, [tracksKey]);
632
+ React.useEffect(() => () => {
633
+ for (const url of copies.current)
634
+ URL.revokeObjectURL(url);
635
+ copies.current.clear();
636
+ }, []);
637
+ // A subtitle file still on its way after a moment: a note where the subtitles show.
638
+ const [subtitleSlow, setSubtitleSlow] = React.useState(false);
639
+ React.useEffect(() => {
640
+ setSubtitleSlow(false);
641
+ if (!chosenSrc || chosenReady || unloadable === chosenSrc)
642
+ return;
643
+ const timer = window.setTimeout(() => setSubtitleSlow(true), SUBTITLE_SLOW_MS);
644
+ return () => clearTimeout(timer);
645
+ }, [chosenSrc, chosenReady, unloadable]);
646
+ React.useEffect(() => {
647
+ // By element, not by video.textTracks: a track given its loaded copy joins that list at the end.
648
+ const elements = video.current?.querySelectorAll("track");
649
+ if (!elements)
650
+ return;
651
+ const all = latestTracks.current;
652
+ const shown = subtitle < 0 || all[subtitle]?.render || !chosenReady
653
+ ? -1
654
+ : all.slice(0, subtitle).filter((t) => !t.render).length;
655
+ // Where the player's own drawing can't be seen, the browser draws the cues itself.
656
+ const native = systemView || inPip || airPlaying;
657
+ elements.forEach((each, i) => {
658
+ each.track.mode = i === shown ? (native ? "showing" : "hidden") : "disabled";
659
+ });
660
+ const track = shown >= 0 ? elements[shown]?.track : undefined;
661
+ if (!track) {
662
+ setCue("");
663
+ return;
664
+ }
665
+ const show = () => {
666
+ const active = track.activeCues;
667
+ const lines = [];
668
+ for (let i = 0; active && i < active.length; i++) {
669
+ const c = active[i];
670
+ const text = typeof c.getCueAsHTML === "function" ? (c.getCueAsHTML().textContent ?? "") : c.text;
671
+ lines.push(...cueLines(text));
672
+ }
673
+ // Layered effects (a glow under a lyric) repeat the same line; show it once.
674
+ setCue([...new Set(lines)].join("\n"));
675
+ };
676
+ track.addEventListener("cuechange", show);
677
+ show();
678
+ return () => track.removeEventListener("cuechange", show);
679
+ }, [subtitle, tracksKey, chosenReady, systemView, inPip, airPlaying]);
680
+ // A track with a renderer of its own draws while it's chosen.
681
+ const subtitleLayer = React.useRef(null);
682
+ React.useEffect(() => {
683
+ const el = video.current;
684
+ const layer = subtitleLayer.current;
685
+ const render = subtitle >= 0 ? latestTracks.current[subtitle]?.render : undefined;
686
+ if (!el || !layer || !render)
687
+ return;
688
+ return render(el, layer);
689
+ }, [subtitle, tracksKey]);
690
+ const chooseSubtitle = (index) => {
691
+ setSubtitle(index);
692
+ onSubtitleChange?.(index);
693
+ };
694
+ const chooseAudio = (value) => {
695
+ switchVersion({ audio: value });
696
+ onAudioChange?.(value);
697
+ };
698
+ const toggleSubtitles = () => chooseSubtitle(subtitle >= 0 ? -1 : Math.min(lastSubtitle.current, tracks.length - 1));
699
+ // Full screen is the whole player, so the controls and subtitles come along.
700
+ React.useEffect(() => {
701
+ const change = () => setFullscreen(document.fullscreenElement === root.current);
702
+ document.addEventListener("fullscreenchange", change);
703
+ return () => document.removeEventListener("fullscreenchange", change);
704
+ }, []);
705
+ // A play or pause the viewer asked for shows its icon in the middle, briefly, so they see it took.
706
+ const [flash, setFlash] = React.useState(null);
707
+ const flashRef = React.useRef(null);
708
+ React.useEffect(() => {
709
+ const el = flashRef.current;
710
+ if (!flash || !el)
711
+ return;
712
+ const still = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
713
+ const animation = el.animate(still
714
+ ? [{ opacity: 0 }, { opacity: 1, offset: 0.2 }, { opacity: 0 }]
715
+ : [
716
+ { opacity: 0, transform: "scale(0.85)" },
717
+ { opacity: 1, transform: "scale(1)", offset: 0.25 },
718
+ { opacity: 0, transform: "scale(1.15)" },
719
+ ], { duration: FLASH_MS, easing: "ease-out" });
720
+ animation.onfinish = () => setFlash(null);
721
+ return () => animation.cancel();
722
+ }, [flash]);
723
+ const togglePlay = React.useCallback(() => {
724
+ const el = video.current;
725
+ if (!el)
726
+ return;
727
+ // Mid-drag, the viewer takes over: the drag's end won't play it again.
728
+ holding.current = false;
729
+ const play = el.paused || el.ended;
730
+ setFlash((last) => ({ playing: play, n: (last?.n ?? 0) + 1 }));
731
+ if (!play)
732
+ return el.pause();
733
+ // Play again: from the start, also at an end declared while a stream still fetches its last
734
+ // part, where the element would play on from there and wait for it.
735
+ if (told.current === "ended" && atEnd(el)) {
736
+ el.currentTime = 0;
737
+ playhead.set({ time: 0 });
738
+ }
739
+ void el.play().catch(() => undefined);
740
+ }, [playhead]);
741
+ const seekTo = React.useCallback((to) => {
742
+ const el = video.current;
743
+ if (!el)
744
+ return;
745
+ // A live stream, or a recording that never wrote down its length: as far as the browser can seek.
746
+ const { seekable } = el;
747
+ const end = Number.isFinite(el.duration)
748
+ ? el.duration
749
+ : seekable.length > 0
750
+ ? seekable.end(seekable.length - 1)
751
+ : 0;
752
+ el.currentTime = Math.min(Math.max(0, to), end);
753
+ playhead.set({ time: el.currentTime });
754
+ }, [playhead]);
755
+ const seekBy = (delta) => seekTo((video.current?.currentTime ?? 0) + delta);
756
+ const changeVolume = (next) => {
757
+ const el = video.current;
758
+ if (!el)
759
+ return;
760
+ // In hundredths, so steps of 0.05 stay round: 0.9, not 0.8999999999999999.
761
+ el.volume = Math.min(1, Math.max(0, Math.round(next * 100) / 100));
762
+ el.muted = el.volume === 0;
763
+ remember();
764
+ };
765
+ // ↓: muted, it stays muted, and only the level it comes back at goes down.
766
+ const lowerVolume = () => {
767
+ const el = video.current;
768
+ if (!el)
769
+ return;
770
+ if (!el.muted)
771
+ return changeVolume(el.volume - 0.05);
772
+ el.volume = Math.max(0, Math.round((el.volume - 0.05) * 100) / 100);
773
+ remember();
774
+ };
775
+ const toggleMute = () => {
776
+ const el = video.current;
777
+ if (!el)
778
+ return;
779
+ if (el.muted && el.volume === 0)
780
+ el.volume = 0.5;
781
+ el.muted = !el.muted;
782
+ remember();
783
+ };
784
+ const changeRate = (next) => {
785
+ const el = video.current;
786
+ if (!el)
787
+ return;
788
+ // The default rate too, so a version switch (which reloads) keeps the speed.
789
+ el.defaultPlaybackRate = next;
790
+ el.playbackRate = next;
791
+ };
792
+ const toggleFullscreen = () => {
793
+ const el = root.current;
794
+ const v = video.current;
795
+ if (!el)
796
+ return;
797
+ if (document.fullscreenElement)
798
+ void document.exitFullscreen().catch(() => undefined);
799
+ else if (el.requestFullscreen)
800
+ void el.requestFullscreen().catch(() => undefined);
801
+ // iOS Safari: only the video itself goes full screen, with the system's controls.
802
+ else
803
+ v?.webkitEnterFullscreen?.();
804
+ };
805
+ const pickAirPlay = () => video.current?.webkitShowPlaybackTargetPicker?.();
806
+ // After an error: the same source again from where it stopped, or the next lower quality.
807
+ const retry = () => {
808
+ const el = video.current;
809
+ if (!el)
810
+ return;
811
+ resume.current = { time: el.currentTime || startOf, play: true };
812
+ setFailed(false);
813
+ el.load();
814
+ };
815
+ const nextQuality = qualities[qualities.indexOf(version?.quality ?? "") + 1];
816
+ const togglePip = () => {
817
+ const v = video.current;
818
+ if (!v)
819
+ return;
820
+ // Another player's picture in picture moves to this one.
821
+ if (document.pictureInPictureElement === v)
822
+ void document.exitPictureInPicture().catch(() => undefined);
823
+ else
824
+ void v.requestPictureInPicture().catch(() => undefined);
825
+ };
826
+ const shortcut = (event) => {
827
+ wake();
828
+ if (event.defaultPrevented || event.metaKey || event.ctrlKey || event.altKey)
829
+ return;
830
+ if (event.key === "Tab")
831
+ pointerFocus.current = false;
832
+ const target = event.target;
833
+ // Menus, and the sliders' own arrows, keep their keys.
834
+ if (target.closest('[role="menu"]'))
835
+ return;
836
+ // A control only clicked never shows a focus ring: its keys work the player, which takes focus.
837
+ const clicked = pointerFocus.current && target !== root.current;
838
+ const onSlider = !clicked && target instanceof HTMLInputElement && target.type === "range";
839
+ const onButton = target.closest("button") !== null;
840
+ const key = event.key.length === 1 ? event.key.toLowerCase() : event.key;
841
+ // Without a length (a live stream), there's no end or tenths to jump to.
842
+ const known = duration > 0;
843
+ const run = (action) => {
844
+ event.preventDefault();
845
+ // Quietly: the mouse was on the player, and a ring round all of it would only startle.
846
+ if (clicked)
847
+ root.current?.focus({ preventScroll: true, focusVisible: false });
848
+ action();
849
+ };
850
+ switch (key) {
851
+ case " ":
852
+ // A button only clicked would be pressed again; Space plays or pauses instead.
853
+ if (clicked || !onButton)
854
+ run(togglePlay);
855
+ break;
856
+ case "k":
857
+ run(togglePlay);
858
+ break;
859
+ case "ArrowLeft":
860
+ if (!onSlider)
861
+ run(() => seekBy(-5));
862
+ break;
863
+ case "ArrowRight":
864
+ if (!onSlider)
865
+ run(() => seekBy(5));
866
+ break;
867
+ case "j":
868
+ run(() => seekBy(-SKIP));
869
+ break;
870
+ case "l":
871
+ run(() => seekBy(SKIP));
872
+ break;
873
+ case "ArrowUp":
874
+ if (!onSlider)
875
+ run(() => changeVolume((video.current?.volume ?? 1) + 0.05));
876
+ break;
877
+ case "ArrowDown":
878
+ if (!onSlider)
879
+ run(lowerVolume);
880
+ break;
881
+ case "m":
882
+ run(toggleMute);
883
+ break;
884
+ case "c":
885
+ if (tracks.length > 0)
886
+ run(toggleSubtitles);
887
+ break;
888
+ case "f":
889
+ if (allowFullscreen && canFullscreen)
890
+ run(toggleFullscreen);
891
+ break;
892
+ case "Home":
893
+ if (!onSlider)
894
+ run(() => seekTo(0));
895
+ break;
896
+ case "End":
897
+ if (!onSlider && known)
898
+ run(() => seekTo(duration));
899
+ break;
900
+ default:
901
+ // 0–9 jump to that tenth of the video.
902
+ if (/^[0-9]$/.test(key) && known)
903
+ run(() => seekTo((duration * Number(key)) / 10));
904
+ }
905
+ };
906
+ const handleKeyDown = (event) => {
907
+ onKeyDown?.(event);
908
+ shortcut(event);
909
+ // A key on a clicked control gives it its focus ring (the browser's rule): it keeps the bar, as a tabbed one does.
910
+ if (focusIn === "pointer" && event.target.matches(":focus-visible"))
911
+ setFocusIn("keyboard");
912
+ };
913
+ // A player that is the page takes the keys pressed with nothing in focus: on arrival, and after
914
+ // a focused control went away (a skip button, an episode changed).
915
+ const pageShortcut = React.useRef(shortcut);
916
+ pageShortcut.current = shortcut;
917
+ React.useEffect(() => {
918
+ if (!pageShortcuts)
919
+ return;
920
+ const onKey = (event) => {
921
+ if (event.target === document.body || event.target === document.documentElement)
922
+ pageShortcut.current(event);
923
+ };
924
+ window.addEventListener("keydown", onKey);
925
+ return () => window.removeEventListener("keydown", onKey);
926
+ }, [pageShortcuts]);
927
+ // A click on the picture plays or pauses. A tap shows or hides the controls (play and pause wait
928
+ // in the middle then); quick taps on the left or right third jump back or ahead.
929
+ const lastTap = React.useRef(null);
930
+ const [jump, setJump] = React.useState(null);
931
+ const handleStageClick = (event) => {
932
+ if (event.button !== 0)
933
+ return;
934
+ if (performance.now() - menuClosedAt.current < MENU_CLOSE_MS)
935
+ return wake();
936
+ if (event.pointerType !== "touch") {
937
+ togglePlay();
938
+ return wake();
939
+ }
940
+ // Before the first play, a tap anywhere starts it, as a click does (only starts it: a quick
941
+ // second tap mustn't stop it again).
942
+ if (!started) {
943
+ if (video.current?.paused)
944
+ togglePlay();
945
+ return wake();
946
+ }
947
+ const box = event.currentTarget.getBoundingClientRect();
948
+ const x = (event.clientX - box.left) / box.width;
949
+ const side = x < 1 / 3 ? -1 : x > 2 / 3 ? 1 : 0;
950
+ // When the finger touched, not when this ran: a busy moment (a seek) mustn't split a double tap.
951
+ const now = event.timeStamp;
952
+ const last = lastTap.current;
953
+ lastTap.current = { at: now, side };
954
+ if (started && side !== 0 && last?.side === side && now - last.at < DOUBLE_TAP_MS) {
955
+ seekBy(side * SKIP);
956
+ setJump((before) => ({
957
+ side,
958
+ seconds: before && before.side === side && now - before.at < JUMP_MS ? before.seconds + SKIP : SKIP,
959
+ at: now,
960
+ n: (before?.n ?? 0) + 1,
961
+ }));
962
+ return;
963
+ }
964
+ if (hidden)
965
+ wake();
966
+ else if (playing) {
967
+ clearTimeout(idleTimer.current);
968
+ setIdle(true);
969
+ }
970
+ };
971
+ const jumpRef = React.useRef(null);
972
+ React.useEffect(() => {
973
+ const el = jumpRef.current;
974
+ if (!jump || !el)
975
+ return;
976
+ const animation = el.animate([{ opacity: 1 }, { opacity: 1, offset: 0.6 }, { opacity: 0 }], {
977
+ duration: JUMP_MS,
978
+ easing: "ease-out",
979
+ });
980
+ animation.onfinish = () => setJump(null);
981
+ return () => animation.cancel();
982
+ }, [jump]);
983
+ const ready = duration > 0;
984
+ // In full screen, popups have to live inside the player to be seen.
985
+ const portal = isFullscreen ? { container: root } : undefined;
986
+ const speedList = speeds === false ? [] : speeds;
987
+ const controlsHidden = hidden || (!started && !focusIn);
988
+ // A big movie frame (a film on a laptop or a TV) gets the prominent controls and a thicker timeline.
989
+ const large = movie && frameWidth >= LARGE_FRAME;
990
+ const size = movie ? "icon" : "icon-sm";
991
+ const textSize = large ? "lg" : movie ? "default" : "sm";
992
+ const timeText = large ? "text-sm" : "text-xs";
993
+ const skip = React.useCallback((s) => {
994
+ // Its button is about to go: the player keeps the keyboard.
995
+ if (root.current?.contains(document.activeElement))
996
+ root.current.focus({ preventScroll: true });
997
+ if (s.onSkip)
998
+ s.onSkip();
999
+ else
1000
+ seekTo(s.end);
1001
+ }, [seekTo]);
1002
+ // A drag on the scrubber, by pointer or touch, holds a playing video still; let go, it plays on,
1003
+ // or ends if let go at the end. The app hears of neither the hold nor the playing on.
1004
+ const scrub = React.useCallback((to) => {
1005
+ const el = video.current;
1006
+ if (to !== null && el && !holding.current && !el.paused && !el.ended) {
1007
+ holding.current = true;
1008
+ el.pause();
1009
+ }
1010
+ playhead.set({ scrub: to });
1011
+ setScrubbing(to !== null);
1012
+ if (to !== null)
1013
+ return seekTo(to);
1014
+ if (!el || !holding.current)
1015
+ return;
1016
+ holding.current = false;
1017
+ if (!atEnd(el))
1018
+ return void el.play().catch(() => undefined);
1019
+ // Let go at the end, it has ended, now, as playback would have (`onPause`, then `onEnded`). The
1020
+ // element may not know yet: a stream still fetching its last part would play on and wait for it.
1021
+ if (!el.ended && el.currentTime < el.duration)
1022
+ seekTo(el.duration);
1023
+ setEnded(true);
1024
+ if (told.current === "ended")
1025
+ return;
1026
+ told.current = "ended";
1027
+ callbacks.current.onPause?.();
1028
+ callbacks.current.onEnded?.();
1029
+ }, [playhead, seekTo]);
1030
+ /* ── The controls, placed by the layout below ── */
1031
+ const playButton = (_jsx(Control, { label: ended ? labels.playAgain : playing ? labels.pause : labels.play, portal: portal, size: size, onClick: togglePlay, children: ended ? _jsx(RotateCcwIcon, {}) : playing ? _jsx(PauseIcon, {}) : _jsx(PlayIcon, {}) }));
1032
+ const skipButtons = (_jsxs(_Fragment, { children: [_jsx(Control, { label: labels.skipBack(SKIP), portal: portal, size: size, onClick: () => seekBy(-SKIP), children: _jsx(SkipIcon, { direction: "back", large: large }) }), _jsx(Control, { label: labels.skipForward(SKIP), portal: portal, size: size, onClick: () => seekBy(SKIP), children: _jsx(SkipIcon, { direction: "forward", large: large }) })] }));
1033
+ const volumeControls = (_jsxs("div", { "data-slot": "video-player-volume",
1034
+ // In the movie layout's row, free to narrow: its slider gives way before anything overflows.
1035
+ className: cn("flex items-center", movie ? "min-w-0" : "@max-md/video:mr-auto"), children: [_jsx(Control, { label: muted || volume === 0 ? labels.unmute : labels.mute, portal: portal, size: size, onClick: toggleMute, children: muted || volume === 0 ? _jsx(VolumeXIcon, {}) : volume < 0.5 ? _jsx(Volume1Icon, {}) : _jsx(Volume2Icon, {}) }), _jsx(BaseSlider.Root, { "data-slot": "video-player-volume-slider", value: muted ? 0 : Math.round(volume * 100), min: 0, max: 100, step: 5, onValueChange: (value) => changeVolume(value / 100),
1036
+ // Touch devices (iPhone, iPad) take the volume from their buttons only: no slider there.
1037
+ className: cn("hidden pointer-coarse:hidden!",
1038
+ // In the movie layout's one row it waits for room, and gives some back when the row runs short (a next control).
1039
+ movie ? "min-w-10 @min-[38.5rem]/video:block" : "@lg/video:block", large ? "w-24" : movie ? "w-20" : "w-16"), children: _jsx(BaseSlider.Control, { className: "flex w-full cursor-pointer touch-none items-center py-2.5 pr-2.5 pl-1.5", children: _jsxs(BaseSlider.Track, { className: cn(trackClass, large && "h-2"), children: [_jsx(BaseSlider.Indicator, { className: indicatorClass }), _jsx(BaseSlider.Thumb, { "aria-label": labels.volume, className: cn(thumbClass, large && "size-5") })] }) }) })] }));
1040
+ const currentTime = _jsx(Clock, { playhead: playhead, className: timeText });
1041
+ // Without a length (a live stream) there is no total, and nothing to count down.
1042
+ const totalTime = ready ? (_jsx("span", { "data-slot": "video-player-duration", className: cn("shrink-0 font-mono text-muted-foreground tabular-nums", timeText), children: formatTime(duration) })) : null;
1043
+ const remainingTime = ready ? (_jsx(TimeLeft, { playhead: playhead, duration: duration, labels: labels, className: timeText })) : null;
1044
+ const scrubber = (_jsx(Scrubber, { playhead: playhead, duration: duration, labels: labels, previews: previews, large: large, frameWidth: frameWidth, className: timeText, onSeek: seekTo, onScrub: scrub, onStep: seekBy }));
1045
+ // One track toggles in the default layout; several, or the movie layout, get a menu. Its name
1046
+ // says what it does now, like play's, so it reports no pressed state as well.
1047
+ const subtitlesControl = tracks.length === 0 ? null : tracks.length === 1 && !movie ? (_jsx(Control, { label: subtitle >= 0 ? labels.hideSubtitles : labels.showSubtitles, portal: portal, size: size, onClick: toggleSubtitles, children: subtitle >= 0 ? _jsx(CaptionsIcon, {}) : _jsx(CaptionsOffIcon, {}) })) : (_jsx(ChoiceMenu, { label: labels.subtitles, portal: portal, onOpenChange: onMenuOpenChange, trigger: _jsx(Button, { variant: "ghost", size: size, "aria-label": `${labels.subtitles}, ${tracks[subtitle]?.label ?? labels.subtitlesOff}`, children: subtitle >= 0 ? _jsx(CaptionsIcon, {}) : _jsx(CaptionsOffIcon, {}) }), value: String(subtitle), onValueChange: (value) => chooseSubtitle(Number(value)), options: [
1048
+ { value: "-1", label: labels.subtitlesOff },
1049
+ ...tracks.map((t, i) => ({ value: String(i), label: t.label })),
1050
+ ] }));
1051
+ // The movie layout puts audio and subtitles in one menu, side by side, the way streaming apps do:
1052
+ // one place to look, whichever of the two has a choice.
1053
+ const subtitleLabel = tracks[subtitle]?.label ?? labels.subtitlesOff;
1054
+ const languageControl = tracks.length > 0 || audios.length > 1 ? (_jsxs(Menu, { onOpenChange: onMenuOpenChange, children: [_jsxs(Tooltip, { children: [_jsx(TooltipTrigger, { render: _jsx(MenuTrigger, { render: _jsx(Button, { variant: "ghost", size: size, "aria-label": `${labels.audioAndSubtitles}: ${[version?.audio, `${labels.subtitles} ${subtitleLabel}`].filter(Boolean).join(", ")}`, children: _jsx(LanguagesIcon, {}) }) }) }), _jsx(TooltipContent, { portal: portal, className: "theme-dark", children: labels.audioAndSubtitles })] }), _jsxs(MenuContent, { side: "top", align: "end", portal: portal, className: "theme-dark grid w-[min(30rem,var(--available-width))] grid-cols-[repeat(auto-fit,minmax(12rem,1fr))] gap-1 overflow-hidden", children: [audios.length > 0 && (_jsxs(MenuGroup, { className: "max-h-[min(24rem,calc(var(--available-height)-1rem))] overflow-y-auto", children: [_jsx(MenuGroupLabel, { children: labels.audio }), _jsx(MenuRadioGroup, { value: version?.audio ?? "", onValueChange: (value) => chooseAudio(String(value)), children: audios.map((a) => (_jsx(MenuRadioItem, { value: a, closeOnClick: false, children: a }, a))) })] })), _jsxs(MenuGroup, { className: "max-h-[min(24rem,calc(var(--available-height)-1rem))] overflow-y-auto", children: [_jsx(MenuGroupLabel, { children: labels.subtitles }), _jsx(MenuRadioGroup, { value: String(subtitle), onValueChange: (value) => chooseSubtitle(Number(value)), children: [
1055
+ { value: "-1", label: labels.subtitlesOff },
1056
+ ...tracks.map((t, i) => ({ value: String(i), label: t.label })),
1057
+ ].map((option) => (_jsx(MenuRadioItem, { value: option.value, closeOnClick: false, children: option.label }, option.value))) })] })] })] })) : null;
1058
+ const audioControl = audios.length > 1 ? (_jsx(ChoiceMenu, { label: labels.audio, portal: portal, onOpenChange: onMenuOpenChange, trigger: _jsx(Button, { variant: "ghost", size: size, "aria-label": `${labels.audio}, ${version?.audio ?? ""}`, children: _jsx(AudioLinesIcon, {}) }), value: version?.audio ?? "", onValueChange: (value) => chooseAudio(value), options: audios.map((a) => ({ value: a, label: a })) })) : null;
1059
+ const qualityControl = qualities.length > 1 ? (_jsx(ChoiceMenu, { label: labels.quality, portal: portal, onOpenChange: onMenuOpenChange, trigger: _jsx(Button, { variant: "ghost", size: textSize, "aria-label": `${labels.quality}, ${version?.quality ?? ""}`, className: cn("font-mono tabular-nums", timeText, movie ? "px-3" : "px-2"), children: version?.quality }), value: version?.quality ?? "", onValueChange: (value) => {
1060
+ switchVersion({ quality: value });
1061
+ onQualityChange?.(value);
1062
+ },
1063
+ // The detail of the version that would play: this audio in that quality.
1064
+ options: qualities.map((q) => ({
1065
+ value: q,
1066
+ label: q,
1067
+ detail: pickVersion(versions, audio, q)?.qualityDetail,
1068
+ })) })) : null;
1069
+ const speedControl = speedList.length > 0 ? (_jsx(ChoiceMenu, { label: labels.speed, portal: portal, onOpenChange: onMenuOpenChange, trigger: _jsx(Button, { variant: "ghost", size: textSize, "aria-label": `${labels.speed}, ${labels.rate(rate)}`, className: cn("min-w-(--control-h-sm) font-mono tabular-nums", timeText, movie ? "px-3" : "px-2"), children: labels.rate(rate) }), value: String(rate), onValueChange: (value) => changeRate(Number(value)), options: speedList.map((s) => ({
1070
+ value: String(s),
1071
+ label: s === 1 ? labels.normalSpeed : labels.rate(s),
1072
+ })) })) : null;
1073
+ const episodesControl = seasons.length > 0 && onEpisodeSelect ? (_jsx(EpisodesMenu, { seasons: seasons, current: currentEpisode, onSeasonOpen: onSeasonOpen, onSelect: onEpisodeSelect, labels: labels, portal: portal, size: size, onOpenChange: onMenuOpenChange })) : null;
1074
+ const pipControl = allowPip && canPip ? (_jsx(Control, { label: inPip ? labels.leavePictureInPicture : labels.pictureInPicture, portal: portal, size: size, onClick: togglePip, className: "hidden @md/video:inline-flex", children: _jsx(PictureInPicture2Icon, {}) })) : null;
1075
+ const airPlayControl = canAirPlay ? (_jsx(Control, { label: labels.airPlay, portal: portal, size: size, "aria-pressed": airPlaying, onClick: pickAirPlay, children: _jsx(AirplayIcon, {}) })) : null;
1076
+ const fullscreenControl = allowFullscreen && canFullscreen ? (_jsx(Control, { label: isFullscreen ? labels.exitFullScreen : labels.fullScreen, portal: portal, size: size, onClick: toggleFullscreen, children: isFullscreen ? _jsx(MinimizeIcon, {}) : _jsx(MaximizeIcon, {}) })) : null;
1077
+ // Stepped back while playing (and before the first play), unless a control has keyboard focus (`hidden`).
1078
+ const controlsMotion = cn("transition-[opacity,translate] duration-(--duration) ease-brand", "data-hidden:pointer-events-none data-hidden:opacity-0");
1079
+ const hoverProps = {
1080
+ onPointerEnter: (event) => event.pointerType !== "touch" && setOverControls(true),
1081
+ onPointerLeave: () => setOverControls(false),
1082
+ };
1083
+ return (_jsx(TooltipProvider, { children: _jsxs("div", { ref: rootRef, role: "group", "aria-label": title ?? labels.player, tabIndex: 0, "data-slot": "video-player", "data-layout": layout, "data-variant": variant, "data-playing": playing ? "" : undefined, "data-fullscreen": isFullscreen ? "" : undefined, "data-idle": hidden ? "" : undefined, onKeyDown: handleKeyDown, onPointerDown: (event) => {
1084
+ onPointerDown?.(event);
1085
+ pointerFocus.current = true;
1086
+ }, onPointerMove: (event) => {
1087
+ onPointerMove?.(event);
1088
+ if (event.pointerType !== "touch")
1089
+ wake();
1090
+ }, onFocus: (event) => {
1091
+ onFocus?.(event);
1092
+ // A click or tap on the picture focuses the player after the picture has had its say (a
1093
+ // tap that hid the controls): only other focus brings them back.
1094
+ if (event.target !== root.current || !pointerFocus.current)
1095
+ wake();
1096
+ }, className: cn(
1097
+ // Tabbed to, it takes the shortcuts and shows the focus ring like any control.
1098
+ "@container/video relative isolate w-full overflow-hidden bg-black font-body text-foreground select-none", "data-idle:cursor-none", playerVariants[variant], isFullscreen && "rounded-none border-0", className), style: { aspectRatio: isFullscreen ? undefined : aspectRatio, ...style }, ...props, children: [_jsxs("video", { ref: videoRefs, "data-slot": "video-player-video", poster: poster, autoPlay: autoPlay, loop: loop, muted: startMuted, playsInline: true, preload: "metadata", src: typeof current === "string" && current ? startingAt(current, startOf) : undefined, className: "absolute inset-0 size-full bg-black object-contain", children: [typeof current !== "string" &&
1099
+ current.map((s, i) => (_jsx("source", { src: startingAt(s.src, startOf), type: s.type, onError: i === current.length - 1 ? fail : undefined }, s.src))), tracks
1100
+ .filter((t) => !t.render)
1101
+ .map((t) => (_jsx("track", { src: loaded[t.src] ?? t.src, label: t.label, srcLang: t.srcLang, kind: t.kind ?? "subtitles" }, loaded[t.src] ?? t.src)))] }), _jsx("div", { "aria-hidden": true, "data-slot": "video-player-stage", className: "absolute inset-0", onPointerUp: handleStageClick, onDoubleClick: () => allowFullscreen && canFullscreen && toggleFullscreen() }), movie && (_jsxs(_Fragment, { children: [_jsx("div", { hidden: failed, "aria-hidden": true, "data-slot": "video-player-scrim", "data-hidden": hidden ? "" : undefined, className: cn("pointer-events-none absolute inset-0 bg-[linear-gradient(to_bottom,rgb(0_0_0/0.55),transparent_22%,transparent_40%,rgb(0_0_0/0.85))]", "transition-opacity duration-(--duration) ease-brand data-hidden:opacity-0") }), (title || onBack) && (_jsxs("div", { "data-slot": "video-player-title", "data-hidden": hidden ? "" : undefined, ...focusProps, className: cn("theme-dark pointer-events-none absolute inset-x-0 top-0 flex items-center gap-1 bg-transparent px-5 pt-4 @2xl/video:px-7 @2xl/video:pt-6", "transition-opacity duration-(--duration) ease-brand data-hidden:opacity-0 data-hidden:*:pointer-events-none!",
1102
+ // The arrow stands over the play button, in the controls' own column; the title follows it.
1103
+ onBack && "pt-3 pl-3 @2xl/video:pt-5 @2xl/video:pl-5", large && "[--icon-button:var(--control-h-lg)] [&_button_svg:not([class*='size-'])]:size-5", large && onBack && "pt-5! pl-7!"), children: [onBack && (_jsx(Control, { label: labels.back, portal: portal, size: size, onClick: onBack, className: "pointer-events-auto", children: _jsx(ArrowLeftIcon, {}) })), title && (_jsx("p", { className: "max-w-[min(100%,40rem)] min-w-0 truncate font-heading text-[17px] font-light text-foreground @2xl/video:text-2xl", children: title }))] }))] })), _jsx("div", { className: "theme-dark pointer-events-none absolute inset-0 flex items-center justify-center bg-transparent text-foreground", children: failed ? (_jsxs("div", { className: "flex flex-col items-center gap-4", children: [_jsxs("p", { "data-slot": "video-player-error", className: "flex items-center gap-2 font-mono text-xs text-muted-foreground", children: [_jsx(VideoOffIcon, { "aria-hidden": true, className: "size-4" }), labels.error] }), _jsxs("div", { className: "pointer-events-auto flex flex-wrap justify-center gap-2", children: [_jsx(Button, { variant: "secondary", size: "sm", onClick: retry, children: labels.retry }), nextQuality && (_jsx(Button, { variant: "ghost", size: "sm", onClick: () => {
1104
+ switchVersion({ quality: nextQuality });
1105
+ onQualityChange?.(nextQuality);
1106
+ }, children: labels.tryQuality(nextQuality) }))] })] })) : preparing ? (_jsx(Spinner, { size: "lg", label: labels.loading })) : !started || ended ? (_jsx(Button, { "data-slot": "video-player-start", variant: "secondary", size: "icon", "aria-label": ended ? labels.playAgain : labels.play, onClick: togglePlay, className: "pointer-events-auto size-(--control-h-lg) [&_svg:not([class*='size-'])]:size-5", children: ended ? _jsx(RotateCcwIcon, {}) : _jsx(PlayIcon, { className: "translate-x-px" }) })) : waiting ? (_jsx(Spinner, { size: "lg", label: labels.loading })) : (_jsx(Button, { "data-slot": "video-player-center", "data-hidden": controlsHidden ? "" : undefined, variant: "secondary", size: "icon", "aria-label": playing ? labels.pause : labels.play, onClick: () => {
1107
+ togglePlay();
1108
+ wake();
1109
+ }, className: cn("pointer-events-auto hidden size-(--control-h-lg) pointer-coarse:inline-flex [&_svg:not([class*='size-'])]:size-5", "transition-opacity duration-(--duration) ease-brand data-hidden:pointer-events-none data-hidden:opacity-0"), children: playing ? _jsx(PauseIcon, {}) : _jsx(PlayIcon, { className: "translate-x-px" }) })) }), jump && (_jsx("div", { "aria-hidden": true, className: cn("theme-dark pointer-events-none absolute inset-y-0 flex w-1/3 items-center justify-center bg-transparent", jump.side < 0 ? "left-0" : "right-0"), children: _jsx("div", { ref: jumpRef, "data-slot": "video-player-jump", className: "rounded-full bg-black/50 px-4 py-2 font-mono text-sm text-foreground tabular-nums", children: labels.jumped(jump.side * jump.seconds) }, jump.n) })), flash && (_jsx("div", { "aria-hidden": true, className: "theme-dark pointer-events-none absolute inset-0 flex items-center justify-center bg-transparent", children: _jsx("div", { ref: flashRef, "data-slot": "video-player-flash", className: cn("flex items-center justify-center rounded-full bg-black/50 text-foreground opacity-0", movie ? "size-20 [&_svg]:size-8" : "size-14 [&_svg]:size-6"), children: flash.playing ? _jsx(PlayIcon, { className: "translate-x-0.5" }) : _jsx(PauseIcon, {}) }, flash.n) })), _jsx("div", { ref: subtitleLayer, "aria-hidden": true, "data-slot": "video-player-subtitle-layer", className: cn("pointer-events-none absolute inset-0 transition-transform duration-(--duration) ease-brand", !controlsHidden &&
1110
+ (large
1111
+ ? "-translate-y-[calc(var(--control-h-lg)+56px)]"
1112
+ : movie
1113
+ ? "-translate-y-[calc(var(--control-h)+44px)]"
1114
+ : "-translate-y-[calc(var(--control-h-sm)+28px)]")) }), (cue || subtitleSlow) && (_jsx("div", { "data-slot": "video-player-caption", className: cn("theme-dark pointer-events-none absolute inset-x-4 flex justify-center bg-transparent text-center transition-[bottom] duration-(--duration) ease-brand",
1115
+ // Above the controls while they show; low in the frame when they step back.
1116
+ controlsHidden
1117
+ ? "bottom-4"
1118
+ : large
1119
+ ? "bottom-[calc(var(--control-h-lg)+72px)]"
1120
+ : movie
1121
+ ? "bottom-[calc(var(--control-h)+60px)]"
1122
+ : "bottom-[calc(var(--control-h-sm)+44px)] @max-md/video:bottom-[calc(var(--control-h-sm)*2+52px)]"), children: _jsx("span", { className: "text-[clamp(15px,2.2cqw,44px)]", children: _jsx("span", { className: cn("inline-block max-w-[min(90cqw,40em)] rounded-item bg-background/80 px-2 py-0.5 leading-snug [overflow-wrap:anywhere] text-foreground", !cue && "text-[0.7em] text-muted-foreground"), style: { fontSize: `${subtitleScale}em` }, children: cue
1123
+ ? cue.split("\n").map((line, i) => (_jsx("span", { dir: "auto", className: "block", children: line }, i)))
1124
+ : labels.preparingSubtitles }) }) })), _jsx(SegmentSkip, { playhead: playhead, segments: segments, live: started && !ended, failed: failed, playing: playing, titleKey: titleKey, sourceKey: srcKey, onSkip: skip, onPress: wake, controlsHidden: controlsHidden, large: large, movie: movie }), !failed &&
1125
+ (movie ? (_jsxs("div", { "data-slot": "video-player-controls", "data-hidden": controlsHidden ? "" : undefined, ...hoverProps, ...focusProps, className: cn("theme-dark absolute inset-x-0 bottom-0 flex flex-col gap-1 bg-transparent px-3 pb-2 @2xl/video:px-5 @2xl/video:pb-3",
1126
+ // The prominent size: 46px round controls with larger icons.
1127
+ large &&
1128
+ "gap-1.5 px-7! pb-5! [--icon-button:var(--control-h-lg)] [&_button_svg:not([class*='size-'])]:size-5", controlsMotion, "data-hidden:translate-y-1"), children: [_jsxs("div", { "data-slot": "video-player-buttons", className: "flex items-center gap-1", children: [playButton, _jsx("span", { className: "hidden @md/video:contents", children: skipButtons }), onNext && (_jsx("span", { className: "hidden @3xs/video:contents", children: _jsx(Control, { label: labels.next, portal: portal, size: size, onClick: onNext, children: _jsx(SkipForwardIcon, {}) }) })), volumeControls, _jsxs("span", { className: cn("ml-1.5 hidden items-center gap-1 font-mono tabular-nums @xl/video:flex", timeText), children: [currentTime, ready && (_jsx("span", { "aria-hidden": true, className: "text-muted-foreground", children: "/" })), totalTime] }), _jsxs("div", { className: "ml-auto flex items-center gap-1", children: [_jsx("span", { className: "hidden @3xs/video:contents", children: episodesControl }), languageControl, _jsx("span", { className: "hidden @md/video:contents", children: qualityControl }), _jsx("span", { className: "hidden @lg/video:contents", children: speedControl }), pipControl, airPlayControl, fullscreenControl] })] }), _jsxs("div", { "data-slot": "video-player-timeline", dir: "ltr", className: "flex items-center gap-2.5 px-2", children: [_jsx("span", { className: "contents @xl/video:hidden", children: currentTime }), scrubber, remainingTime] })] })) : (_jsxs("div", { "data-slot": "video-player-controls", "data-hidden": controlsHidden ? "" : undefined, ...hoverProps, ...focusProps, className: cn("theme-dark absolute inset-x-2 bottom-2 flex flex-wrap items-center gap-x-1 gap-y-0.5 rounded-button material-menu p-1", controlsMotion, "data-hidden:translate-y-1"), children: [playButton, _jsxs("div", { "data-slot": "video-player-timeline", dir: "ltr", className: "flex min-w-0 flex-1 items-center gap-2.5 px-1.5 @max-md/video:order-first @max-md/video:basis-full", children: [currentTime, scrubber, totalTime] }), volumeControls, episodesControl, audioControl, qualityControl, speedControl, subtitlesControl, pipControl, airPlayControl, fullscreenControl] }))), overlay && (_jsx("div", { "data-slot": "video-player-overlay", className: "theme-dark absolute inset-0 z-10 bg-transparent text-foreground", children: overlay }))] }) }));
1129
+ }
1130
+ /**
1131
+ * A round ghost button with its name in a tooltip: 30px in the bar, 38px in the movie layout. The
1132
+ * tooltips are set dark like the controls and their menus, whatever the page's theme.
1133
+ */
1134
+ function Control({ label, portal, children, ...props }) {
1135
+ return (_jsxs(Tooltip, { children: [_jsx(TooltipTrigger, { render: _jsx(Button, { variant: "ghost", "aria-label": label, ...props }), children: children }), _jsx(TooltipContent, { portal: portal, className: "theme-dark", children: label })] }));
1136
+ }
1137
+ /* ── The parts that follow the playhead: each reads it from the store and redraws on its own ── */
1138
+ /** The playhead's time, or the dragged thumb's, in Licht Mono: "1:15". It redraws once a second. */
1139
+ function Clock({ playhead, className }) {
1140
+ const time = usePlayhead(playhead, (s) => formatTime(s.scrub ?? s.time));
1141
+ return (_jsx("span", { "data-slot": "video-player-time", className: cn("shrink-0 font-mono text-foreground tabular-nums", className), children: time }));
1142
+ }
1143
+ /** What's left, at the timeline's end, the way streaming apps count down: "−18:56". */
1144
+ function TimeLeft({ playhead, duration, labels, className, }) {
1145
+ const left = usePlayhead(playhead, (s) => Math.floor(Math.max(0, duration - (s.scrub ?? s.time))));
1146
+ return (_jsxs("span", { "data-slot": "video-player-remaining", className: cn("min-w-[6ch] shrink-0 text-right font-mono text-muted-foreground tabular-nums", className), children: [_jsx("span", { className: "sr-only", children: labels.remaining(labels.duration(left)) }), _jsxs("span", { "aria-hidden": true, children: ["\u2212", formatTime(left)] })] }));
1147
+ }
1148
+ /**
1149
+ * The timeline: the part played, the buffered range, and the moment under the pointer with its
1150
+ * still. Left to right on any page, as a timeline runs: like the tape, not like the text.
1151
+ */
1152
+ function Scrubber({ playhead, duration, labels, previews, large, frameWidth, className, onSeek, onScrub, onStep, }) {
1153
+ const ready = duration > 0;
1154
+ const shown = usePlayhead(playhead, (s) => s.scrub ?? s.time);
1155
+ const scrub = usePlayhead(playhead, (s) => s.scrub);
1156
+ const buffered = usePlayhead(playhead, (s) => s.buffered);
1157
+ const [hover, setHover] = React.useState(null);
1158
+ // The scrubber's width, for keeping a preview inside it.
1159
+ const [trackWidth, setTrackWidth] = React.useState(0);
1160
+ // The moment under the pointer, or under the thumb while dragging (touch has no hover).
1161
+ const peek = hover ?? (scrub !== null && ready ? { ratio: Math.min(1, scrub / duration), time: scrub } : null);
1162
+ const still = peek && previews ? previews(peek.time) : undefined;
1163
+ const stillWidth = Math.min(large ? PREVIEW_WIDTH_LARGE : PREVIEW_WIDTH, frameWidth * 0.4);
1164
+ const stillScale = still ? stillWidth / still.width : 1;
1165
+ // A preview stays within the timeline; a bare time label is narrow enough to centre anywhere.
1166
+ const peekLeft = !peek
1167
+ ? 0
1168
+ : still && trackWidth > stillWidth
1169
+ ? Math.min(Math.max(peek.ratio * trackWidth, stillWidth / 2), trackWidth - stillWidth / 2)
1170
+ : peek.ratio * trackWidth;
1171
+ return (_jsx(DirectionProvider, { direction: "ltr", children: _jsx(BaseSlider.Root, { "data-slot": "video-player-scrubber",
1172
+ // Without a length (a live stream) the playhead has no place on the track.
1173
+ value: ready ? shown : 0, min: 0, max: ready ? duration : 1, step: SCRUB_STEP, largeStep: 10, disabled: !ready, onValueChange: (value, { reason }) => {
1174
+ // Dragged or pressed, the thumb shows where it's going and holds the controls; a key only seeks.
1175
+ if (reason === "drag" || reason === "track-press")
1176
+ onScrub(value);
1177
+ else
1178
+ onSeek(value);
1179
+ }, onValueCommitted: () => onScrub(null), className: "min-w-0 flex-1", children: _jsxs(BaseSlider.Control, { className: cn("relative flex w-full cursor-pointer touch-none items-center data-disabled:cursor-default", large ? "py-3" : "py-2.5"), onPointerDown: (event) => setTrackWidth(event.currentTarget.getBoundingClientRect().width), onPointerMove: (event) => {
1180
+ if (event.pointerType === "touch" || !ready)
1181
+ return;
1182
+ const r = event.currentTarget.getBoundingClientRect();
1183
+ const ratio = Math.min(1, Math.max(0, (event.clientX - r.left) / r.width));
1184
+ setTrackWidth(r.width);
1185
+ setHover({ ratio, time: ratio * duration });
1186
+ }, onPointerLeave: () => setHover(null), children: [_jsxs(BaseSlider.Track, { className: cn(trackClass, large && "h-2"), children: [_jsx("span", { "aria-hidden": true, "data-slot": "video-player-buffered", className: "absolute inset-y-0 left-0 rounded-full bg-foreground/20 forced-color-adjust-none forced-colors:bg-[GrayText]", style: { width: ready ? `${Math.min(100, (buffered / duration) * 100)}%` : 0 } }), _jsx(BaseSlider.Indicator, { className: indicatorClass }), _jsx(BaseSlider.Thumb, { "aria-label": labels.seek, getAriaValueText: (_, value) => ready
1187
+ ? labels.position(labels.duration(value), labels.duration(duration))
1188
+ : labels.duration(shown), className: cn(thumbClass, large && "size-5"), onKeyDown: (event) => {
1189
+ // Arrows step five seconds, the way the player's own shortcuts do.
1190
+ const forward = event.key === "ArrowRight" || event.key === "ArrowUp";
1191
+ const back = event.key === "ArrowLeft" || event.key === "ArrowDown";
1192
+ if (!forward && !back)
1193
+ return;
1194
+ event.preventDefault();
1195
+ onStep(forward ? 5 : -5);
1196
+ } })] }), peek && (_jsxs("span", { "aria-hidden": true, "data-slot": "video-player-hover-time", className: cn("pointer-events-none absolute bottom-full flex -translate-x-1/2 flex-col items-center overflow-hidden rounded-item material-menu font-mono text-foreground tabular-nums", still ? "mb-2" : "mb-1.5", className), style: { left: trackWidth ? peekLeft : `${peek.ratio * 100}%` }, children: [still && (_jsx("span", { "data-slot": "video-player-preview", className: "relative block overflow-hidden bg-black", style: { width: stillWidth, height: (stillWidth * still.height) / still.width }, children: _jsx("img", { src: still.src, alt: "", draggable: false, className: "absolute top-0 left-0 max-w-none origin-top-left", style: {
1197
+ transform: `translate(${-(still.x ?? 0) * stillScale}px, ${-(still.y ?? 0) * stillScale}px) scale(${stillScale})`,
1198
+ // A whole image is drawn at the still's size; a sheet at its own.
1199
+ ...(still.x === undefined && still.y === undefined
1200
+ ? { width: still.width, height: still.height }
1201
+ : {}),
1202
+ } }) })), _jsx("span", { className: still ? "py-1" : "px-1.5 py-0.5", children: formatTime(peek.time) })] }))] }) }) }));
1203
+ }
1204
+ /**
1205
+ * The skip over a stretch while it plays ("Skip intro"), with the fill that runs down while it's
1206
+ * offered, and the automatic skips.
1207
+ */
1208
+ function SegmentSkip({ playhead, segments, live, failed, playing, titleKey, sourceKey, onSkip, onPress, controlsHidden, large, movie, }) {
1209
+ // Without segments, the playhead is no concern of this.
1210
+ const time = usePlayhead(playhead, (s) => (segments.length > 0 ? s.time : 0));
1211
+ const segment = live ? segments.find((s) => time >= s.start && time < s.end - SEGMENT_TAIL) : undefined;
1212
+ // A skip offers itself for SEGMENT_PROMPT seconds of playback, its fill running down meanwhile
1213
+ // (and holding while paused); once the fill is empty it goes, until the next segment.
1214
+ const segmentKey = segment ? `${segment.start}-${segment.end}` : null;
1215
+ const [entry, setEntry] = React.useState(null);
1216
+ if ((entry?.key ?? null) !== segmentKey) {
1217
+ setEntry(segmentKey ? { key: segmentKey, at: time } : null);
1218
+ }
1219
+ // A countdown someone moved the playhead in is declined: they want to watch it.
1220
+ const [declined, setDeclined] = React.useState(null);
1221
+ const counting = segment?.auto === "countdown" && declined !== segmentKey;
1222
+ const prompt = counting ? AUTO_COUNTDOWN : SEGMENT_PROMPT;
1223
+ const left = entry ? Math.min(1, Math.max(0, 1 - (time - entry.at) / prompt)) : 1;
1224
+ const shown = left > 0;
1225
+ // A countdown that has run down skips; once for each time the segment comes round.
1226
+ const countedDown = React.useRef(null);
1227
+ React.useEffect(() => {
1228
+ if (!segment || !counting || left > 0 || countedDown.current === segmentKey)
1229
+ return;
1230
+ countedDown.current = segmentKey;
1231
+ onSkip(segment);
1232
+ }, [segment, segmentKey, left, counting, onSkip]);
1233
+ // Another title: its segments come round afresh, even at the same times as the last one's.
1234
+ React.useEffect(() => {
1235
+ countedDown.current = null;
1236
+ setDeclined(null);
1237
+ }, [titleKey]);
1238
+ // Playback running into an automatic segment skips it; a jump into one shows its button instead.
1239
+ const lastTime = React.useRef(time);
1240
+ // Until a source first plays: playback that begins at a segment's very start (an episode that
1241
+ // opens on its intro) has run into it as well.
1242
+ const opening = React.useRef(true);
1243
+ React.useEffect(() => {
1244
+ opening.current = true;
1245
+ }, [sourceKey]);
1246
+ React.useEffect(() => {
1247
+ const before = lastTime.current;
1248
+ lastTime.current = time;
1249
+ const jumped = time - before > 2 || time < before;
1250
+ if (jumped && segment?.auto === "countdown")
1251
+ setDeclined(segmentKey);
1252
+ if (!playing || jumped)
1253
+ return;
1254
+ const first = opening.current;
1255
+ opening.current = false;
1256
+ const reached = segments.find((s) => s.auto === "now" && time >= s.start && (before < s.start || (first && time - s.start < 1)));
1257
+ if (reached)
1258
+ onSkip(reached);
1259
+ }, [time, playing, segments, segment, segmentKey, onSkip]);
1260
+ // Its fill run out, it goes out of reach (below); the keyboard on it goes to the player first.
1261
+ const box = React.useRef(null);
1262
+ React.useLayoutEffect(() => {
1263
+ if (shown || !box.current?.contains(document.activeElement))
1264
+ return;
1265
+ box.current.closest('[data-slot="video-player"]')?.focus({ preventScroll: true });
1266
+ }, [shown]);
1267
+ if (!segment || failed)
1268
+ return null;
1269
+ return (_jsx("div", { ref: box, "data-slot": "video-player-segment", "data-hidden": shown ? undefined : "",
1270
+ // Gone for the pointer, the keyboard and screen readers alike.
1271
+ inert: !shown, className: cn("theme-dark pointer-events-none absolute right-3 flex bg-transparent transition-[bottom,opacity] duration-(--duration) ease-brand @2xl/video:right-5", "data-hidden:opacity-0", large && "right-7!", controlsHidden
1272
+ ? large
1273
+ ? "bottom-7"
1274
+ : "bottom-4"
1275
+ : large
1276
+ ? "bottom-[calc(var(--control-h-lg)+72px)]"
1277
+ : movie
1278
+ ? "bottom-[calc(var(--control-h)+60px)]"
1279
+ : "bottom-[calc(var(--control-h-sm)+44px)] @max-md/video:bottom-[calc(var(--control-h-sm)*2+52px)]"), children: _jsxs(Button, { variant: "secondary", size: large ? "lg" : movie ? "default" : "sm", onClick: () => {
1280
+ onSkip(segment);
1281
+ onPress();
1282
+ },
1283
+ // A long label ("Vorspann überspringen …") stays inside the frame, cut short.
1284
+ className: "pointer-events-auto relative max-w-[calc(100cqw-3.5rem)] overflow-hidden transition-opacity duration-(--duration) ease-brand starting:opacity-0", children: [left > 0 && (_jsx("span", { "aria-hidden": true, "data-slot": "video-player-segment-fill",
1285
+ // Gliding over one time step (0.1 s, two thirds of the motion token) to meet the next.
1286
+ className: "absolute inset-y-0 left-0 w-full origin-left bg-foreground/20 transition-transform duration-[calc(var(--duration)*2/3)] ease-linear", style: { transform: `scaleX(${left})` } })), _jsx("span", { className: "relative min-w-0 truncate", children: segment.label })] }, segmentKey) }));
1287
+ }
1288
+ /** A control that opens a short list of choices — subtitles, audio, quality, speed — named by a tooltip. */
1289
+ function ChoiceMenu({ label, portal, trigger, value, onValueChange, options, onOpenChange, }) {
1290
+ const detailed = options.some((option) => option.detail);
1291
+ return (_jsxs(Menu, { onOpenChange: onOpenChange, children: [_jsxs(Tooltip, { children: [_jsx(TooltipTrigger, { render: _jsx(MenuTrigger, { render: trigger }) }), _jsx(TooltipContent, { portal: portal, className: "theme-dark", children: label })] }), _jsx(MenuContent, { side: "top", align: "end", portal: portal, className: cn("theme-dark", detailed ? "min-w-56" : "min-w-36"), children: _jsxs(MenuGroup, { children: [_jsx(MenuGroupLabel, { children: label }), _jsx(MenuRadioGroup, { value: value, onValueChange: (next) => onValueChange(String(next)), children: options.map((option) => (_jsxs(MenuRadioItem, { value: option.value, closeOnClick: true, children: [_jsx("span", { className: "flex-1", children: option.label }), option.detail && (_jsx("span", { className: "font-mono text-[12px] text-muted-foreground tabular-nums", children: option.detail }))] }, option.value))) })] }) })] }));
1292
+ }
1293
+ /**
1294
+ * The series' episodes, a season at a time, to jump to another, the way streaming apps list them:
1295
+ * a still with how much was watched, the number and title, the length and a line or two about it.
1296
+ * It opens at the season playing with the episode playing in view; the header leads to the others.
1297
+ */
1298
+ function EpisodesMenu({ seasons, current, onSeasonOpen, onSelect, labels, portal, size, onOpenChange, }) {
1299
+ const playing = seasons.find((s) => s.episodes?.some((e) => e.id === current)) ?? seasons[0];
1300
+ const [open, setOpen] = React.useState(false);
1301
+ const [shownId, setShownId] = React.useState(playing?.id);
1302
+ const [picking, setPicking] = React.useState(false);
1303
+ const season = seasons.find((s) => s.id === shownId) ?? playing;
1304
+ const list = React.useRef(null);
1305
+ const showSeason = (id) => {
1306
+ setShownId(id);
1307
+ setPicking(false);
1308
+ if (!seasons.find((s) => s.id === id)?.episodes)
1309
+ onSeasonOpen?.(id);
1310
+ };
1311
+ // Each time it opens: the season playing, scrolled so the episode playing sits mid-list.
1312
+ React.useEffect(() => {
1313
+ if (!open)
1314
+ return;
1315
+ const frame = requestAnimationFrame(() => {
1316
+ const box = list.current;
1317
+ const item = box?.querySelector("[data-current]");
1318
+ if (box && item)
1319
+ box.scrollTop = item.offsetTop - (box.clientHeight - item.offsetHeight) / 2;
1320
+ });
1321
+ return () => cancelAnimationFrame(frame);
1322
+ }, [open]);
1323
+ // "10 episodes", from the episodes once they're there.
1324
+ const countOf = (s) => {
1325
+ const count = s.episodes?.length ?? s.count;
1326
+ return count == null ? null : (_jsx("span", { className: "shrink-0 font-mono text-[12px] text-muted-foreground tabular-nums", children: labels.episodeCount(count) }));
1327
+ };
1328
+ const header = season && (_jsxs(_Fragment, { children: [_jsx("span", { className: "min-w-0 flex-1 truncate text-foreground", children: season.label }), countOf(season)] }));
1329
+ return (_jsxs(Menu, { onOpenChange: (next) => {
1330
+ onOpenChange(next);
1331
+ setOpen(next);
1332
+ if (next && playing) {
1333
+ setShownId(playing.id);
1334
+ setPicking(false);
1335
+ if (!playing.episodes)
1336
+ onSeasonOpen?.(playing.id);
1337
+ }
1338
+ }, children: [_jsxs(Tooltip, { children: [_jsx(TooltipTrigger, { render: _jsx(MenuTrigger, { render: _jsx(Button, { variant: "ghost", size: size, "aria-label": labels.episodes, children: _jsx(GalleryVerticalEndIcon, {}) }) }) }), _jsx(TooltipContent, { portal: portal, className: "theme-dark", children: labels.episodes })] }), _jsx(MenuContent, { side: "top", align: "end", portal: portal, className: "theme-dark flex max-h-[min(36rem,var(--available-height,36rem))] w-[min(30rem,var(--available-width))] flex-col overflow-hidden", children: picking ? (_jsxs(MenuGroup, { className: "min-h-0 overflow-y-auto overscroll-contain", children: [_jsx(MenuGroupLabel, { children: labels.seasons }), _jsx(MenuRadioGroup, { value: season?.id ?? "", onValueChange: (id) => showSeason(String(id)), children: seasons.map((s) => (_jsxs(MenuRadioItem, { value: s.id, closeOnClick: false, children: [_jsx("span", { className: "flex-1", children: s.label }), countOf(s)] }, s.id))) })] })) : (_jsxs(_Fragment, { children: [seasons.length > 1 ? (_jsxs(MenuItem, { closeOnClick: false, onClick: () => setPicking(true), "aria-label": `${labels.seasons}: ${season?.label ?? ""}`, className: "shrink-0", children: [_jsx(ChevronLeftIcon, {}), header] })) : (_jsx("div", { className: "flex min-h-(--control-h) shrink-0 items-center gap-2.5 px-2.5 text-sm", children: header })), _jsx(MenuSeparator, { className: "shrink-0" }), _jsx("div", { ref: list, className: "relative min-h-0 overflow-y-auto overscroll-contain", children: _jsx(MenuGroup, { "aria-label": season?.label, "aria-busy": !season?.episodes || undefined, children: season?.episodes
1339
+ ? season.episodes.map((e) => (_jsx(EpisodeItem, { episode: e, playing: e.id === current, labels: labels, onSelect: onSelect }, e.id)))
1340
+ : // Rows the size of the ones to come, so the list doesn't jump when they do.
1341
+ Array.from({ length: Math.min(season?.count ?? 3, 6) }, (_, i) => (_jsxs("div", { className: "flex items-start gap-3 px-2.5 py-2", children: [_jsx(Skeleton, { shape: "item", className: "aspect-video w-28" }), _jsxs("div", { className: "flex flex-1 flex-col gap-2 py-1 text-sm", children: [_jsx(Skeleton, { className: "w-2/3" }), _jsx(Skeleton, { className: "w-full text-[13px]" }), _jsx(Skeleton, { className: "w-1/2 text-[13px]" })] })] }, i))) }) })] })) })] }));
1342
+ }
1343
+ /** One row of the episode list. The episode playing is marked, and choosing it only closes the list. */
1344
+ function EpisodeItem({ episode: e, playing, labels, onSelect, }) {
1345
+ const progress = Math.min(1, Math.max(0, e.progress ?? 0));
1346
+ return (_jsxs(MenuItem, { "data-current": playing ? "" : undefined, "aria-current": playing || undefined, onClick: () => !playing && onSelect(e.id), className: "items-start gap-3 py-2 data-current:bg-foreground/5", children: [_jsxs("span", { className: "relative aspect-video w-28 shrink-0 overflow-hidden rounded-item bg-black ring-1 ring-field-edge", children: [e.image && (_jsx("img", { src: e.image, alt: "", loading: "lazy", decoding: "async", draggable: false, className: "size-full object-cover" })), playing && (_jsx("span", { className: "absolute inset-0 flex items-center justify-center bg-black/45", children: _jsx(PlayIcon, { className: "size-4 translate-x-px text-foreground" }) })), progress > 0 && (_jsx("span", { className: "absolute inset-x-0 bottom-0 h-[3px] bg-foreground/25", children: _jsx("span", { className: "block h-full bg-foreground", style: { width: `${progress * 100}%` } }) }))] }), _jsxs("span", { className: "flex min-w-0 flex-1 flex-col gap-1 py-0.5", children: [_jsxs("span", { className: "flex items-baseline gap-2", children: [e.number != null && (_jsx("span", { className: "shrink-0 font-mono text-[12px] text-muted-foreground tabular-nums", children: e.number })), _jsx("span", { className: "min-w-0 flex-1 truncate text-foreground", children: e.title }), (playing || e.duration) && (_jsx("span", { className: "shrink-0 font-mono text-[12px] text-muted-foreground", children: playing ? labels.nowPlaying : e.duration }))] }), e.description && (_jsx("span", { className: "line-clamp-2 text-[13px] leading-snug text-muted-foreground", children: e.description }))] })] }));
1347
+ }
1348
+ /** A turning arrow with the seconds it skips, set in Licht Mono inside it. */
1349
+ function SkipIcon({ direction, large }) {
1350
+ const Icon = direction === "back" ? RotateCcwIcon : RotateCwIcon;
1351
+ return (_jsxs("span", { "aria-hidden": true, className: cn("relative flex items-center justify-center", large ? "size-6" : "size-5"), children: [_jsx(Icon, { className: large ? "size-6!" : "size-5!", strokeWidth: 1.5 }), _jsx("span", { className: cn("absolute inset-0 flex items-center justify-center pt-px font-mono leading-none font-medium", large ? "text-[8px]" : "text-[7px]"), children: SKIP })] }));
1352
+ }