@brightlocal/ui-components 3.2.0 → 3.3.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 (428) hide show
  1. package/AI_USAGE.md +10 -0
  2. package/README.md +3 -1
  3. package/component-meta.json +1271 -428
  4. package/deprecations.json +44 -0
  5. package/dist/_virtual/_rolldown/runtime.cjs +1 -0
  6. package/dist/accordion.cjs +1 -1
  7. package/dist/accordion.js +73 -102
  8. package/dist/alert-dialog.cjs +1 -1
  9. package/dist/alert-dialog.d.ts +6 -4
  10. package/dist/alert-dialog.d.ts.map +1 -1
  11. package/dist/alert-dialog.js +85 -133
  12. package/dist/alert.cjs +1 -1
  13. package/dist/alert.d.ts +4 -4
  14. package/dist/alert.d.ts.map +1 -1
  15. package/dist/alert.js +106 -168
  16. package/dist/aspect-ratio.cjs +1 -1
  17. package/dist/aspect-ratio.js +13 -16
  18. package/dist/avatar.cjs +1 -1
  19. package/dist/avatar.js +30 -45
  20. package/dist/badge.cjs +1 -1
  21. package/dist/badge.d.ts +23 -1
  22. package/dist/badge.d.ts.map +1 -1
  23. package/dist/badge.js +90 -91
  24. package/dist/banner.cjs +1 -1
  25. package/dist/banner.js +102 -148
  26. package/dist/blocks/empty-state.cjs +1 -1
  27. package/dist/blocks/empty-state.d.ts +20 -3
  28. package/dist/blocks/empty-state.d.ts.map +1 -1
  29. package/dist/blocks/empty-state.js +73 -140
  30. package/dist/blocks/input-list.cjs +2 -2
  31. package/dist/blocks/input-list.d.ts +2 -2
  32. package/dist/blocks/input-list.d.ts.map +1 -1
  33. package/dist/blocks/input-list.js +136 -176
  34. package/dist/blocks/progress-state.cjs +1 -1
  35. package/dist/blocks/progress-state.js +223 -347
  36. package/dist/blocks/sidebar.cjs +1 -1
  37. package/dist/blocks/sidebar.d.ts +11 -6
  38. package/dist/blocks/sidebar.d.ts.map +1 -1
  39. package/dist/blocks/sidebar.js +763 -1092
  40. package/dist/brand-illustration-motif.cjs +1 -1
  41. package/dist/brand-illustration-motif.js +40 -61
  42. package/dist/breadcrumb.cjs +1 -1
  43. package/dist/breadcrumb.js +62 -102
  44. package/dist/button-group.cjs +1 -1
  45. package/dist/button-group.js +23 -31
  46. package/dist/button.cjs +1 -1
  47. package/dist/button.d.ts +4 -2
  48. package/dist/button.d.ts.map +1 -1
  49. package/dist/button.js +149 -189
  50. package/dist/calendar.cjs +1 -1
  51. package/dist/calendar.d.ts +87 -3
  52. package/dist/calendar.d.ts.map +1 -1
  53. package/dist/calendar.js +116 -173
  54. package/dist/callout.cjs +1 -1
  55. package/dist/callout.js +73 -96
  56. package/dist/card.cjs +1 -1
  57. package/dist/card.d.ts +10 -4
  58. package/dist/card.d.ts.map +1 -1
  59. package/dist/card.js +233 -316
  60. package/dist/carousel.cjs +1 -1
  61. package/dist/carousel.d.ts +3 -3
  62. package/dist/carousel.d.ts.map +1 -1
  63. package/dist/carousel.js +174 -268
  64. package/dist/centred-layout.cjs +1 -1
  65. package/dist/centred-layout.js +27 -48
  66. package/dist/chart-empty.cjs +1 -1
  67. package/dist/chart-empty.js +18 -27
  68. package/dist/chart.cjs +7 -7
  69. package/dist/chart.d.ts +23 -13
  70. package/dist/chart.d.ts.map +1 -1
  71. package/dist/chart.js +445 -651
  72. package/dist/checkbox.cjs +1 -1
  73. package/dist/checkbox.js +36 -69
  74. package/dist/chip.cjs +1 -1
  75. package/dist/chip.js +116 -173
  76. package/dist/collapsible.cjs +1 -1
  77. package/dist/collapsible.d.ts.map +1 -1
  78. package/dist/collapsible.js +35 -41
  79. package/dist/combobox.cjs +3 -3
  80. package/dist/combobox.d.ts +14 -4
  81. package/dist/combobox.d.ts.map +1 -1
  82. package/dist/combobox.js +439 -638
  83. package/dist/command.cjs +1 -1
  84. package/dist/command.d.ts.map +1 -1
  85. package/dist/command.js +273 -420
  86. package/dist/context-menu.cjs +1 -1
  87. package/dist/context-menu.d.ts +5 -5
  88. package/dist/context-menu.d.ts.map +1 -1
  89. package/dist/context-menu.js +121 -191
  90. package/dist/data-table.cjs +1 -1
  91. package/dist/data-table.d.ts +280 -129
  92. package/dist/data-table.d.ts.map +1 -1
  93. package/dist/data-table.js +687 -948
  94. package/dist/date-picker.cjs +1 -1
  95. package/dist/date-picker.d.ts +15 -4
  96. package/dist/date-picker.d.ts.map +1 -1
  97. package/dist/date-picker.js +156 -231
  98. package/dist/delta.cjs +1 -0
  99. package/dist/delta.d.ts +79 -0
  100. package/dist/delta.d.ts.map +1 -0
  101. package/dist/delta.js +62 -0
  102. package/dist/description.cjs +1 -1
  103. package/dist/description.js +11 -20
  104. package/dist/dialog.cjs +1 -1
  105. package/dist/dialog.d.ts +1 -1
  106. package/dist/dialog.d.ts.map +1 -1
  107. package/dist/dialog.js +76 -116
  108. package/dist/drawer.cjs +1 -1
  109. package/dist/drawer.d.ts +11 -11
  110. package/dist/drawer.d.ts.map +1 -1
  111. package/dist/drawer.js +76 -134
  112. package/dist/dropdown-menu.cjs +1 -1
  113. package/dist/dropdown-menu.d.ts +6 -6
  114. package/dist/dropdown-menu.d.ts.map +1 -1
  115. package/dist/dropdown-menu.js +179 -300
  116. package/dist/field.cjs +1 -1
  117. package/dist/field.d.ts +9 -9
  118. package/dist/field.d.ts.map +1 -1
  119. package/dist/field.js +166 -286
  120. package/dist/global-layout.cjs +1 -1
  121. package/dist/global-layout.js +203 -342
  122. package/dist/grid.cjs +1 -1
  123. package/dist/grid.js +16 -29
  124. package/dist/header.cjs +1 -1
  125. package/dist/header.js +21 -38
  126. package/dist/height-transition.cjs +1 -1
  127. package/dist/height-transition.js +38 -55
  128. package/dist/hooks/use-breakpoint.cjs +1 -1
  129. package/dist/hooks/use-breakpoint.js +9 -9
  130. package/dist/hooks/use-debounce.cjs +1 -1
  131. package/dist/hooks/use-debounce.js +12 -11
  132. package/dist/hooks/use-delayed-pending.cjs +1 -1
  133. package/dist/hooks/use-delayed-pending.js +8 -9
  134. package/dist/hooks/use-filter-search-params.cjs +1 -0
  135. package/dist/hooks/use-filter-search-params.d.ts +93 -0
  136. package/dist/hooks/use-filter-search-params.d.ts.map +1 -0
  137. package/dist/hooks/use-filter-search-params.js +122 -0
  138. package/dist/hooks/use-mobile.cjs +1 -1
  139. package/dist/hooks/use-mobile.js +6 -6
  140. package/dist/hooks/use-overlay-pointer-lock.cjs +1 -1
  141. package/dist/hooks/use-overlay-pointer-lock.js +8 -9
  142. package/dist/hooks/use-prefers-reduced-motion.cjs +1 -1
  143. package/dist/hooks/use-prefers-reduced-motion.js +5 -8
  144. package/dist/hover-card.cjs +1 -1
  145. package/dist/hover-card.d.ts +1 -1
  146. package/dist/hover-card.d.ts.map +1 -1
  147. package/dist/hover-card.js +30 -62
  148. package/dist/index.cjs +1 -1
  149. package/dist/index.d.ts +6 -0
  150. package/dist/index.d.ts.map +1 -1
  151. package/dist/index.js +630 -608
  152. package/dist/info-tooltip.cjs +1 -1
  153. package/dist/info-tooltip.js +22 -36
  154. package/dist/input-chip.cjs +1 -1
  155. package/dist/input-chip.d.ts +32 -3
  156. package/dist/input-chip.d.ts.map +1 -1
  157. package/dist/input-chip.js +181 -230
  158. package/dist/input-group.cjs +1 -1
  159. package/dist/input-group.js +174 -221
  160. package/dist/input-otp.cjs +1 -1
  161. package/dist/input-otp.d.ts +3 -3
  162. package/dist/input-otp.d.ts.map +1 -1
  163. package/dist/input-otp.js +102 -146
  164. package/dist/input-password.cjs +1 -1
  165. package/dist/input-password.d.ts +12 -16
  166. package/dist/input-password.d.ts.map +1 -1
  167. package/dist/input-password.js +139 -171
  168. package/dist/input.cjs +1 -1
  169. package/dist/input.d.ts.map +1 -1
  170. package/dist/input.js +51 -73
  171. package/dist/label.cjs +1 -1
  172. package/dist/label.js +20 -38
  173. package/dist/lib/block-illustration.cjs +1 -1
  174. package/dist/lib/block-illustration.d.ts +1 -1
  175. package/dist/lib/block-illustration.d.ts.map +1 -1
  176. package/dist/lib/block-illustration.js +16 -18
  177. package/dist/lib/compose-event-handlers.cjs +1 -0
  178. package/dist/lib/compose-event-handlers.d.ts +9 -0
  179. package/dist/lib/compose-event-handlers.d.ts.map +1 -0
  180. package/dist/lib/compose-event-handlers.js +8 -0
  181. package/dist/lib/download-file.cjs +1 -0
  182. package/dist/lib/download-file.d.ts +14 -0
  183. package/dist/lib/download-file.d.ts.map +1 -0
  184. package/dist/lib/download-file.js +40 -0
  185. package/dist/lib/empty-canvas.cjs +1 -1
  186. package/dist/lib/empty-canvas.js +28 -56
  187. package/dist/lib/empty-chip.cjs +1 -1
  188. package/dist/lib/empty-chip.d.ts +14 -3
  189. package/dist/lib/empty-chip.d.ts.map +1 -1
  190. package/dist/lib/empty-chip.js +15 -11
  191. package/dist/lib/field-aria.cjs +1 -0
  192. package/dist/lib/field-aria.d.ts +34 -0
  193. package/dist/lib/field-aria.d.ts.map +1 -0
  194. package/dist/lib/field-aria.js +52 -0
  195. package/dist/lib/image-file-info.cjs +1 -0
  196. package/dist/lib/image-file-info.d.ts +25 -0
  197. package/dist/lib/image-file-info.d.ts.map +1 -0
  198. package/dist/lib/image-file-info.js +67 -0
  199. package/dist/lib/media-viewer-content.cjs +1 -0
  200. package/dist/lib/media-viewer-content.d.ts +102 -0
  201. package/dist/lib/media-viewer-content.d.ts.map +1 -0
  202. package/dist/lib/media-viewer-content.js +650 -0
  203. package/dist/lib/media-viewer-internal.cjs +1 -0
  204. package/dist/lib/media-viewer-internal.d.ts +98 -0
  205. package/dist/lib/media-viewer-internal.d.ts.map +1 -0
  206. package/dist/lib/media-viewer-internal.js +61 -0
  207. package/dist/lib/media-viewer-motion.cjs +1 -0
  208. package/dist/lib/media-viewer-motion.d.ts +40 -0
  209. package/dist/lib/media-viewer-motion.d.ts.map +1 -0
  210. package/dist/lib/media-viewer-motion.js +37 -0
  211. package/dist/lib/motion.cjs +1 -1
  212. package/dist/lib/motion.d.ts +8 -0
  213. package/dist/lib/motion.d.ts.map +1 -1
  214. package/dist/lib/motion.js +11 -10
  215. package/dist/lib/optical-center.cjs +1 -1
  216. package/dist/lib/optical-center.d.ts +1 -1
  217. package/dist/lib/optical-center.d.ts.map +1 -1
  218. package/dist/lib/optical-center.js +12 -5
  219. package/dist/lib/spring-settle.cjs +1 -1
  220. package/dist/lib/spring-settle.js +1 -1
  221. package/dist/lib/table-internal.cjs +1 -0
  222. package/dist/lib/table-internal.d.ts +62 -0
  223. package/dist/lib/table-internal.d.ts.map +1 -0
  224. package/dist/lib/table-internal.js +18 -0
  225. package/dist/lib/use-controllable.cjs +1 -0
  226. package/dist/lib/use-controllable.d.ts +12 -0
  227. package/dist/lib/use-controllable.d.ts.map +1 -0
  228. package/dist/lib/use-controllable.js +15 -0
  229. package/dist/lib/use-dev-warning.cjs +1 -1
  230. package/dist/lib/utils.cjs +1 -1
  231. package/dist/lib/utils.js +26 -33
  232. package/dist/link.cjs +1 -1
  233. package/dist/link.d.ts +1 -1
  234. package/dist/link.js +78 -124
  235. package/dist/list.cjs +1 -1
  236. package/dist/list.d.ts +8 -0
  237. package/dist/list.d.ts.map +1 -1
  238. package/dist/list.js +94 -156
  239. package/dist/loading.cjs +1 -1
  240. package/dist/loading.js +124 -151
  241. package/dist/logo-mark.cjs +1 -0
  242. package/dist/logo-mark.d.ts +79 -0
  243. package/dist/logo-mark.d.ts.map +1 -0
  244. package/dist/logo-mark.js +219 -0
  245. package/dist/logo.cjs +1 -1
  246. package/dist/logo.d.ts +1 -1
  247. package/dist/logo.d.ts.map +1 -1
  248. package/dist/logo.js +51 -87
  249. package/dist/map.cjs +1 -1
  250. package/dist/map.d.ts.map +1 -1
  251. package/dist/map.js +390 -586
  252. package/dist/media-empty.cjs +1 -1
  253. package/dist/media-empty.js +27 -42
  254. package/dist/media-viewer.cjs +1 -0
  255. package/dist/media-viewer.d.ts +224 -0
  256. package/dist/media-viewer.d.ts.map +1 -0
  257. package/dist/media-viewer.js +295 -0
  258. package/dist/menubar.cjs +1 -1
  259. package/dist/menubar.d.ts +14 -14
  260. package/dist/menubar.d.ts.map +1 -1
  261. package/dist/menubar.js +130 -267
  262. package/dist/multi-select-filter.cjs +1 -1
  263. package/dist/multi-select-filter.d.ts +9 -1
  264. package/dist/multi-select-filter.d.ts.map +1 -1
  265. package/dist/multi-select-filter.js +357 -446
  266. package/dist/navigation-menu.cjs +1 -1
  267. package/dist/navigation-menu.js +108 -172
  268. package/dist/pagination.cjs +1 -1
  269. package/dist/pagination.d.ts +36 -12
  270. package/dist/pagination.d.ts.map +1 -1
  271. package/dist/pagination.js +208 -281
  272. package/dist/popover.cjs +1 -1
  273. package/dist/popover.d.ts +1 -1
  274. package/dist/popover.d.ts.map +1 -1
  275. package/dist/popover.js +34 -45
  276. package/dist/progress.cjs +1 -1
  277. package/dist/progress.d.ts +17 -2
  278. package/dist/progress.d.ts.map +1 -1
  279. package/dist/progress.js +116 -162
  280. package/dist/radio-group.cjs +1 -1
  281. package/dist/radio-group.js +90 -146
  282. package/dist/rating.cjs +1 -1
  283. package/dist/rating.d.ts +80 -13
  284. package/dist/rating.d.ts.map +1 -1
  285. package/dist/rating.js +70 -65
  286. package/dist/relative-date.cjs +1 -1
  287. package/dist/relative-date.d.ts.map +1 -1
  288. package/dist/relative-date.js +73 -89
  289. package/dist/resizable.cjs +1 -1
  290. package/dist/resizable.d.ts +39 -23
  291. package/dist/resizable.d.ts.map +1 -1
  292. package/dist/resizable.js +42 -44
  293. package/dist/result-count.cjs +1 -0
  294. package/dist/result-count.d.ts +110 -0
  295. package/dist/result-count.d.ts.map +1 -0
  296. package/dist/result-count.js +49 -0
  297. package/dist/route-progress.cjs +1 -1
  298. package/dist/route-progress.js +58 -102
  299. package/dist/scroll-area.cjs +1 -1
  300. package/dist/scroll-area.d.ts +9 -1
  301. package/dist/scroll-area.d.ts.map +1 -1
  302. package/dist/scroll-area.js +44 -79
  303. package/dist/select.cjs +2 -2
  304. package/dist/select.d.ts +10 -10
  305. package/dist/select.d.ts.map +1 -1
  306. package/dist/select.js +118 -238
  307. package/dist/separator.cjs +1 -1
  308. package/dist/separator.js +90 -78
  309. package/dist/sheet.cjs +1 -1
  310. package/dist/sheet.d.ts +8 -5
  311. package/dist/sheet.d.ts.map +1 -1
  312. package/dist/sheet.js +250 -317
  313. package/dist/single-select-filter.cjs +1 -1
  314. package/dist/single-select-filter.d.ts +32 -0
  315. package/dist/single-select-filter.d.ts.map +1 -1
  316. package/dist/single-select-filter.js +201 -203
  317. package/dist/skeleton.cjs +1 -1
  318. package/dist/skeleton.js +24 -38
  319. package/dist/slider.cjs +1 -1
  320. package/dist/slider.js +51 -81
  321. package/dist/sonner.cjs +1 -1
  322. package/dist/sonner.d.ts +1 -1
  323. package/dist/sonner.d.ts.map +1 -1
  324. package/dist/sonner.js +101 -125
  325. package/dist/spinner.cjs +1 -1
  326. package/dist/spinner.js +22 -31
  327. package/dist/split-layout.cjs +1 -1
  328. package/dist/split-layout.js +52 -101
  329. package/dist/status.cjs +1 -0
  330. package/dist/status.d.ts +51 -0
  331. package/dist/status.d.ts.map +1 -0
  332. package/dist/status.js +60 -0
  333. package/dist/stepper.cjs +1 -1
  334. package/dist/stepper.js +184 -316
  335. package/dist/switch.cjs +1 -1
  336. package/dist/switch.js +17 -32
  337. package/dist/table.cjs +1 -1
  338. package/dist/table.d.ts +103 -30
  339. package/dist/table.d.ts.map +1 -1
  340. package/dist/table.js +170 -209
  341. package/dist/tabs.cjs +1 -1
  342. package/dist/tabs.d.ts.map +1 -1
  343. package/dist/tabs.js +102 -147
  344. package/dist/text-reveal-motion.cjs +1 -1
  345. package/dist/text-reveal-motion.js +307 -363
  346. package/dist/textarea.cjs +1 -1
  347. package/dist/textarea.d.ts.map +1 -1
  348. package/dist/textarea.js +22 -35
  349. package/dist/toggle-group.cjs +1 -1
  350. package/dist/toggle-group.js +43 -62
  351. package/dist/toggle.cjs +1 -1
  352. package/dist/toggle.js +34 -46
  353. package/dist/tooltip.cjs +1 -1
  354. package/dist/tooltip.d.ts +2 -2
  355. package/dist/tooltip.d.ts.map +1 -1
  356. package/dist/tooltip.js +157 -249
  357. package/dist/typography-heading.cjs +1 -1
  358. package/dist/typography-heading.js +25 -61
  359. package/dist/typography-text.cjs +1 -1
  360. package/dist/typography-text.js +27 -57
  361. package/dist/typography.cjs +1 -1
  362. package/dist/typography.js +132 -340
  363. package/package.json +46 -46
  364. package/src/blocks/empty-state.tsx +34 -18
  365. package/src/blocks/sidebar.tsx +86 -31
  366. package/src/components/accordion.tsx +1 -1
  367. package/src/components/alert-dialog.tsx +4 -2
  368. package/src/components/badge.tsx +127 -15
  369. package/src/components/breadcrumb.tsx +1 -1
  370. package/src/components/button.tsx +8 -6
  371. package/src/components/calendar.tsx +155 -9
  372. package/src/components/card.tsx +63 -10
  373. package/src/components/carousel.tsx +4 -1
  374. package/src/components/chart.tsx +151 -17
  375. package/src/components/checkbox.tsx +1 -1
  376. package/src/components/collapsible.tsx +4 -1
  377. package/src/components/combobox.tsx +40 -7
  378. package/src/components/command.tsx +9 -10
  379. package/src/components/context-menu.tsx +4 -4
  380. package/src/components/data-table.tsx +619 -237
  381. package/src/components/date-picker.tsx +31 -4
  382. package/src/components/delta.tsx +217 -0
  383. package/src/components/drawer.tsx +5 -5
  384. package/src/components/dropdown-menu.tsx +4 -4
  385. package/src/components/field.tsx +36 -15
  386. package/src/components/global-layout.tsx +1 -1
  387. package/src/components/input-chip.tsx +51 -7
  388. package/src/components/input-group.tsx +1 -1
  389. package/src/components/input-password.tsx +15 -19
  390. package/src/components/input.tsx +10 -1
  391. package/src/components/list.tsx +14 -2
  392. package/src/components/logo-mark.tsx +345 -0
  393. package/src/components/map.tsx +18 -20
  394. package/src/components/media-viewer.tsx +908 -0
  395. package/src/components/multi-select-filter.tsx +255 -121
  396. package/src/components/navigation-menu.tsx +2 -2
  397. package/src/components/pagination.tsx +86 -26
  398. package/src/components/progress.tsx +91 -23
  399. package/src/components/rating.tsx +200 -74
  400. package/src/components/relative-date.tsx +19 -11
  401. package/src/components/resizable.tsx +86 -33
  402. package/src/components/result-count.tsx +253 -0
  403. package/src/components/scroll-area.tsx +31 -5
  404. package/src/components/select.tsx +2 -2
  405. package/src/components/sheet.tsx +14 -4
  406. package/src/components/single-select-filter.tsx +136 -41
  407. package/src/components/slider.tsx +2 -2
  408. package/src/components/status.tsx +162 -0
  409. package/src/components/switch.tsx +1 -1
  410. package/src/components/table.tsx +278 -106
  411. package/src/components/tabs.tsx +1 -0
  412. package/src/components/textarea.tsx +20 -2
  413. package/src/components/toggle.tsx +2 -2
  414. package/src/components/tooltip.tsx +11 -20
  415. package/src/hooks/use-filter-search-params.ts +302 -0
  416. package/src/index.ts +6 -0
  417. package/src/lib/compose-event-handlers.ts +14 -0
  418. package/src/lib/download-file.ts +61 -0
  419. package/src/lib/empty-chip.tsx +52 -0
  420. package/src/lib/field-aria.tsx +97 -0
  421. package/src/lib/image-file-info.ts +102 -0
  422. package/src/lib/media-viewer-content.tsx +1587 -0
  423. package/src/lib/media-viewer-internal.tsx +191 -0
  424. package/src/lib/media-viewer-motion.ts +120 -0
  425. package/src/lib/motion.ts +9 -0
  426. package/src/lib/table-internal.ts +74 -0
  427. package/src/lib/use-controllable.ts +43 -0
  428. package/src/lib/empty-chip.ts +0 -24
@@ -0,0 +1,1587 @@
1
+ "use client";
2
+
3
+ /* MediaViewerContent — the full view — in a module of its own, re-exported
4
+ from components/media-viewer.tsx. A page that never renders it (previews
5
+ only, `viewable={false}`) drops the module when it is bundled, so its
6
+ gestures, zoom and slide track are not shipped there. */
7
+
8
+ import * as React from "react";
9
+ import * as DialogPrimitive from "@radix-ui/react-dialog";
10
+ import {
11
+ ChevronLeft,
12
+ ChevronRight,
13
+ Download,
14
+ ZoomIn,
15
+ ZoomOut,
16
+ } from "@brightlocal/icons";
17
+ import {
18
+ DRAG_STEP_MAX,
19
+ DRAG_STEP_SHARE,
20
+ DRAG_STEP_SPEED,
21
+ RUBBER_BAND_SHARE,
22
+ WHEEL_CANCEL_DELAY,
23
+ WHEEL_INERTIA_RISE,
24
+ WHEEL_INERTIA_TTL,
25
+ WHEEL_FRESH_RISE,
26
+ WHEEL_INTENT,
27
+ WHEEL_STEP_SHARE,
28
+ ZOOM_REST,
29
+ glideTiming,
30
+ rubberBand,
31
+ zoomKeyframe,
32
+ } from "./media-viewer-motion";
33
+ import {
34
+ MOTION_DURATION_BASE_MS,
35
+ MOTION_DURATION_SLOW_MS,
36
+ MOTION_EASE_DECELERATE,
37
+ MOTION_EASE_EMPHASIZED,
38
+ } from "@brightlocal/ui-components/lib/motion";
39
+ import { composeEventHandlers } from "./compose-event-handlers";
40
+ import { downloadFile } from "./download-file";
41
+ import { describeImageFile, useImageFileInfo } from "./image-file-info";
42
+ import { cn } from "@brightlocal/ui-components/lib/utils";
43
+ import { useOverlayPointerLock } from "@brightlocal/ui-components/hooks/use-overlay-pointer-lock";
44
+ import { usePrefersReducedMotion } from "@brightlocal/ui-components/hooks/use-prefers-reduced-motion";
45
+ import { Button, ButtonVariants } from "../components/button";
46
+ import { DialogOverlay, DialogPortal } from "../components/dialog";
47
+ import { InfoTooltip } from "../components/info-tooltip";
48
+ import { MediaEmpty } from "../components/media-empty";
49
+ import {
50
+ RelativeDate,
51
+ type RelativeDateLabels,
52
+ } from "../components/relative-date";
53
+ import {
54
+ ItemActionsMenu,
55
+ MediaViewerActionsRegistry,
56
+ MediaViewerControlsContext,
57
+ TruncatedText,
58
+ useMediaViewerContext,
59
+ type MediaViewerItem,
60
+ } from "./media-viewer-internal";
61
+
62
+ /** Zoom levels the view steps through with Zoom in / Zoom out. */
63
+ const ZOOM_LEVELS = [1, 1.5, 2, 3] as const;
64
+
65
+ /* -------------------------------------------------------------------------------------------------
66
+ * MediaViewerContent
67
+ * -----------------------------------------------------------------------------------------------*/
68
+
69
+ /**
70
+ * Props for MediaViewerContent.
71
+ */
72
+ export interface MediaViewerContentProps extends Omit<
73
+ React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>,
74
+ "children" | "asChild"
75
+ > {
76
+ /**
77
+ * Required data-hook attribute for automated testing. The parts derive
78
+ * theirs from it: `-frame`, `-image`, `-empty`, `-position`, `-previous`,
79
+ * `-next`, `-thumbnails`, `-thumbnail-<index>`.
80
+ * @example "photo-viewer"
81
+ */
82
+ dataHook: string;
83
+ /**
84
+ * `MediaViewerTitle` (required — it names the dialog) and, optionally,
85
+ * `MediaViewerActions`. They go in the bottom bar: the title on the left,
86
+ * over the open image's description (`alt`) and `date`; the actions on the right.
87
+ */
88
+ children: React.ReactNode;
89
+ /**
90
+ * Builds the "2 of 5" text from the position and the total.
91
+ * @default (current, total) => `${current} of ${total}`
92
+ */
93
+ formatPosition?: (current: number, total: number) => string;
94
+ /**
95
+ * Accessible label for the Previous button.
96
+ * @default "Previous"
97
+ */
98
+ previousLabel?: string;
99
+ /**
100
+ * Accessible label for the Next button.
101
+ * @default "Next"
102
+ */
103
+ nextLabel?: string;
104
+ /**
105
+ * Accessible name for the strip of thumbnails.
106
+ * @default "Images"
107
+ */
108
+ thumbnailsLabel?: string;
109
+ /**
110
+ * The line shown when an image has expired or cannot be loaded.
111
+ * @default "Image no longer available"
112
+ */
113
+ unavailableMessage?: string;
114
+ /**
115
+ * Accessible label for the Zoom in button.
116
+ * @default "Zoom in"
117
+ */
118
+ zoomInLabel?: string;
119
+ /**
120
+ * Accessible label for the Zoom out button.
121
+ * @default "Zoom out"
122
+ */
123
+ zoomOutLabel?: string;
124
+ /**
125
+ * Accessible label for the Download button.
126
+ * @default "Download"
127
+ */
128
+ downloadLabel?: string;
129
+ /**
130
+ * Accessible label for the image details button — its format, size in
131
+ * pixels and file size, in a tooltip.
132
+ * @default "Image details"
133
+ */
134
+ infoLabel?: string;
135
+ /**
136
+ * Words for the open image's date ("3 days ago", "today"). Each key
137
+ * defaults to its English value.
138
+ * @default DEFAULT_RELATIVE_DATE_LABELS
139
+ */
140
+ dateLabels?: Partial<RelativeDateLabels>;
141
+ /**
142
+ * Tracking element identifier for analytics.
143
+ * @default "media-viewer"
144
+ */
145
+ trackingEl?: string;
146
+ /**
147
+ * Tracking label for analytics context.
148
+ */
149
+ trackingLabel?: string;
150
+ }
151
+
152
+ /** Height-to-width ratio past which an image counts as a tall capture. */
153
+ const TALL_RATIO = 2.5;
154
+
155
+ /* Previous / Next: a full-height strip down each side of the stage, as wide
156
+ as the stage's side padding. It shows while the pointer is over the stage
157
+ (or it has keyboard focus); under the pointer only its arrow lights up.
158
+ At the ends of the set it is hidden; touch screens swipe instead. */
159
+ const navZone = cn(
160
+ "group/nav absolute inset-y-0 flex w-16 items-center justify-center outline-none sm:w-20",
161
+ "duration-fast opacity-0 transition-opacity ease-out",
162
+ "group-hover/stage:opacity-100 focus-visible:opacity-100",
163
+ "disabled:invisible pointer-coarse:hidden"
164
+ );
165
+
166
+ /* The arrow on the strip, drawn as a ghost icon Button; it lights up while
167
+ the strip is hovered. */
168
+ const navArrow = cn(
169
+ ButtonVariants({ variant: "ghost" }),
170
+ "pointer-events-none size-9 p-0 group-hover/nav:bg-accent group-hover/nav:text-accent-foreground group-focus-visible/nav:shadow-default"
171
+ );
172
+
173
+ const defaultFormatPosition = (current: number, total: number) =>
174
+ `${current} of ${total}`;
175
+
176
+ /* -------------------------------------------------------------------------------------------------
177
+ * MediaViewerContent — private hooks
178
+ * -----------------------------------------------------------------------------------------------*/
179
+
180
+ /* What is known of each file, by item: its aspect ratio (width / height),
181
+ whether the full-size file is ready, and whether it failed. The image is
182
+ sized by ratio, not by its file's pixels, so the preview's small file and
183
+ the full one take the same box. The open file and its neighbours load
184
+ ahead; until a full-size file is ready, the preview's file (already loaded
185
+ by the trigger or the strip) stands in, so neither opening nor stepping
186
+ shows an empty stage. Failed loads are remembered by URL, so stepping back
187
+ to a dead capture does not request it again. */
188
+ function useMediaFiles(items: MediaViewerItem[], index: number, open: boolean) {
189
+ const [failed, setFailed] = React.useState<ReadonlySet<string>>(
190
+ () => new Set()
191
+ );
192
+ const [ratios, setRatios] = React.useState<ReadonlyMap<string, number>>(
193
+ () => new Map()
194
+ );
195
+ const [ready, setReady] = React.useState<ReadonlySet<string>>(
196
+ () => new Set()
197
+ );
198
+ /* The full file's own width, in px, so a small image is never shown larger
199
+ than it is — recorded from the full file only, never a preview's. */
200
+ const [widths, setWidths] = React.useState<ReadonlyMap<string, number>>(
201
+ () => new Map()
202
+ );
203
+ const noteRatio = React.useCallback(
204
+ (src: string, width: number, height: number) => {
205
+ if (!width || !height) return null;
206
+ const ratio = width / height;
207
+ setRatios((prev) =>
208
+ prev.get(src) === ratio ? prev : new Map(prev).set(src, ratio)
209
+ );
210
+ return ratio;
211
+ },
212
+ []
213
+ );
214
+ const markFailed = React.useCallback((src: string) => {
215
+ setFailed((prev) => new Set(prev).add(src));
216
+ }, []);
217
+
218
+ React.useEffect(() => {
219
+ if (!open) return;
220
+ let cancelled = false;
221
+ for (const it of [items[index], items[index + 1], items[index - 1]]) {
222
+ if (!it || it.expired) continue;
223
+ const preload = new Image();
224
+ preload.src = it.src;
225
+ preload
226
+ .decode()
227
+ .then(() => {
228
+ if (cancelled) return;
229
+ noteRatio(it.src, preload.naturalWidth, preload.naturalHeight);
230
+ setWidths((prev) =>
231
+ prev.get(it.src) === preload.naturalWidth
232
+ ? prev
233
+ : new Map(prev).set(it.src, preload.naturalWidth)
234
+ );
235
+ setReady((prev) =>
236
+ prev.has(it.src) ? prev : new Set(prev).add(it.src)
237
+ );
238
+ })
239
+ .catch(() => undefined);
240
+ }
241
+ return () => {
242
+ cancelled = true;
243
+ };
244
+ }, [open, items, index, noteRatio]);
245
+
246
+ return { failed, ratios, widths, ready, noteRatio, markFailed };
247
+ }
248
+
249
+ /* Open and close zoom the image out of, and back into, the preview of the
250
+ item on screen (a shared-element transition). With no preview for it, or
251
+ with reduced motion, the image fades instead. The image the view opens on
252
+ stays hidden until its zoom starts, so its first frame is the zoom's;
253
+ after a step it shows at once. State is keyed by the opening: the view's
254
+ component stays mounted while closed. */
255
+ function useOpeningZoom({
256
+ index,
257
+ openCount,
258
+ openedAtRef,
259
+ triggersRef,
260
+ reducedMotion,
261
+ setOpen,
262
+ revealed,
263
+ reveal,
264
+ }: {
265
+ index: number;
266
+ revealed: boolean;
267
+ reveal: () => void;
268
+ openCount: number;
269
+ openedAtRef: React.MutableRefObject<number>;
270
+ triggersRef: React.MutableRefObject<Map<number, HTMLButtonElement>>;
271
+ reducedMotion: boolean;
272
+ setOpen: (open: boolean) => void;
273
+ }) {
274
+ const imageRef = React.useRef<HTMLImageElement | null>(null);
275
+ const overlayRef = React.useRef<HTMLDivElement | null>(null);
276
+ const barRef = React.useRef<HTMLDivElement | null>(null);
277
+ const enteredForRef = React.useRef(0);
278
+ const closingForRef = React.useRef(0);
279
+
280
+ const previewFor = (i: number) => {
281
+ const preview = triggersRef.current.get(i);
282
+ return preview?.isConnected ? preview : null;
283
+ };
284
+
285
+ /* Called when the open image loads: start the zoom (once per opening). */
286
+ const zoomIn = (image: HTMLImageElement, tall: boolean, at: number) => {
287
+ if (enteredForRef.current === openCount) return;
288
+ enteredForRef.current = openCount;
289
+ image.style.visibility = "visible";
290
+ reveal();
291
+ /* After a slow load a zoom would start long after the press; the image
292
+ just appears. */
293
+ if (at - openedAtRef.current > 500) return;
294
+ /* A tall capture is laid out at its width only after this render, so it
295
+ fades rather than zooming from a box it is about to leave. */
296
+ const preview = reducedMotion || tall ? null : previewFor(index);
297
+ const from = preview ? zoomKeyframe(preview, image) : null;
298
+ if (from) {
299
+ image.animate([from, ZOOM_REST], {
300
+ duration: MOTION_DURATION_SLOW_MS,
301
+ easing: MOTION_EASE_EMPHASIZED,
302
+ });
303
+ } else {
304
+ image.animate([{ opacity: 0 }, { opacity: 1 }], {
305
+ duration: MOTION_DURATION_SLOW_MS,
306
+ easing: "ease-out",
307
+ });
308
+ }
309
+ };
310
+
311
+ /* Close: zoom back into the preview while the backdrop and the bar fade,
312
+ then let Dialog close. A little quicker than the open. */
313
+ /* `fade`: close with the plain fade — a zoomed or panned image is not
314
+ where its preview's zoom would start from. */
315
+ const requestClose = ({ fade = false } = {}) => {
316
+ if (closingForRef.current === openCount) return;
317
+ const image = imageRef.current;
318
+ const preview = reducedMotion || fade ? null : previewFor(index);
319
+ image?.getAnimations().forEach((animation) => animation.cancel());
320
+ const to = image && preview ? zoomKeyframe(preview, image) : null;
321
+ if (!image || !to) {
322
+ setOpen(false);
323
+ return;
324
+ }
325
+ closingForRef.current = openCount;
326
+ const options: KeyframeAnimationOptions = {
327
+ duration: MOTION_DURATION_BASE_MS,
328
+ easing: "ease-in-out",
329
+ fill: "forwards",
330
+ };
331
+ for (const el of [overlayRef.current, barRef.current]) {
332
+ el?.animate([{ opacity: 1 }, { opacity: 0 }], options);
333
+ }
334
+ image
335
+ .animate([ZOOM_REST, to], options)
336
+ .finished.catch(() => undefined)
337
+ .finally(() => setOpen(false));
338
+ };
339
+
340
+ return {
341
+ imageRef,
342
+ overlayRef,
343
+ barRef,
344
+ revealed,
345
+ reveal,
346
+ zoomIn,
347
+ requestClose,
348
+ };
349
+ }
350
+
351
+ /* The stage is a track: the open image with its neighbours laid either side
352
+ of it, off-stage. A drag moves the track with the finger (or the
353
+ trackpad), so the neighbour comes into view as far as the reader pulls; on
354
+ release it either finishes the step or springs back. No fade, so nothing
355
+ behind the view shows through. */
356
+ function useSlideTrack({
357
+ index,
358
+ total,
359
+ reducedMotion,
360
+ onStep,
361
+ }: {
362
+ index: number;
363
+ total: number;
364
+ reducedMotion: boolean;
365
+ /** Make `next` the open item. */
366
+ onStep: (next: number) => void;
367
+ }) {
368
+ const frameRef = React.useRef<HTMLDivElement | null>(null);
369
+ const trackRef = React.useRef<HTMLDivElement | null>(null);
370
+ const slideFromRef = React.useRef<{ from: number; speed: number } | null>(
371
+ null
372
+ );
373
+ /* The running glide, kept so a new drag can tell where the track is: the
374
+ computed style of an animation that has not started its first frame yet
375
+ still reads "none", which would snap the image home. */
376
+ const glideRef = React.useRef<{
377
+ from: number;
378
+ animation: Animation;
379
+ } | null>(null);
380
+
381
+ const frameWidth = () => frameRef.current?.clientWidth ?? 0;
382
+ const moveTrack = (offset: number) => {
383
+ const track = trackRef.current;
384
+ if (track) track.style.transform = offset ? `translateX(${offset}px)` : "";
385
+ };
386
+ /* Past the first or last image the track gives like a rubber band, as
387
+ native scroll views do. */
388
+ const pastEnd = (offset: number) =>
389
+ (offset > 0 && index === 0) || (offset < 0 && index === total - 1);
390
+ const resist = (offset: number) =>
391
+ pastEnd(offset)
392
+ ? rubberBand(offset, frameWidth() * RUBBER_BAND_SHARE)
393
+ : offset;
394
+
395
+ const glideHome = (from: number, speed: number) => {
396
+ const animation = trackRef.current?.animate(
397
+ [{ transform: `translateX(${from}px)` }, { transform: "none" }],
398
+ glideTiming(from, speed)
399
+ );
400
+ glideRef.current = animation ? { from, animation } : null;
401
+ };
402
+ const settle = (from: number, speed = 0) => {
403
+ moveTrack(0);
404
+ if (!from || reducedMotion) return;
405
+ glideHome(from, speed);
406
+ };
407
+ const gliding = () => {
408
+ const state = glideRef.current?.animation.playState;
409
+ return state === "running" || state === "paused";
410
+ };
411
+ /* Catch a gliding track where it is — not at the glide's end, which would
412
+ jump — and return that offset, so a new drag picks the image up
413
+ mid-flight. */
414
+ const stopGlide = () => {
415
+ const glide = glideRef.current;
416
+ glideRef.current = null;
417
+ if (!glide || glide.animation.playState === "finished") return 0;
418
+ /* Eased progress; null while the glide waits for its first frame. */
419
+ const progress = glide.animation.effect?.getComputedTiming().progress;
420
+ const offset = glide.from * (1 - (progress ?? 0));
421
+ glide.animation.cancel();
422
+ moveTrack(offset);
423
+ return offset;
424
+ };
425
+
426
+ /* `dragged` is how far a swipe left the track off centre: the new image is
427
+ already on the track, pulled partway in, so once it is the open one the
428
+ track starts where the drag left it and slides home, carousel-style.
429
+ Without a drag (Previous / Next, the arrow keys, a thumbnail) the image
430
+ just swaps. The track is left where it stands until the new index has
431
+ rendered (see the layout effect below): a trackpad step re-renders in a
432
+ later task, and resetting it here would paint one frame of the old image
433
+ back in place — a blink. */
434
+ const goTo = (next: number, dragged = 0, speed = 0) => {
435
+ if (next === index || next < 0 || next >= total) return;
436
+ const width = frameWidth();
437
+ if (dragged && !reducedMotion && width && Math.abs(next - index) === 1) {
438
+ slideFromRef.current = {
439
+ from: (next > index ? 1 : -1) * width + dragged,
440
+ speed,
441
+ };
442
+ }
443
+ onStep(next);
444
+ };
445
+ const step = (delta: -1 | 1) => goTo(index + delta);
446
+
447
+ const stepThreshold = () =>
448
+ Math.min(frameWidth() * DRAG_STEP_SHARE, DRAG_STEP_MAX);
449
+ /* Pulled far enough, towards an image that exists. */
450
+ const canStep = (travel: number, threshold = stepThreshold()) => {
451
+ const target = index + (travel < 0 ? 1 : -1);
452
+ return Math.abs(travel) > threshold && target >= 0 && target < total;
453
+ };
454
+ /* Let go of a drag that stands `offset` off centre after travelling
455
+ `travel` (negative: towards the next image) at `speed` px/ms. */
456
+ const release = (offset: number, travel: number, speed = 0) => {
457
+ const direction = travel < 0 ? 1 : -1;
458
+ /* Flicked back the other way at the end: the reader changed their mind. */
459
+ const reversed = speed * travel < 0 && Math.abs(speed) > 0.2;
460
+ const far =
461
+ !reversed &&
462
+ (Math.abs(travel) > stepThreshold() || Math.abs(speed) > DRAG_STEP_SPEED);
463
+ const target = index + direction;
464
+ if (far && target >= 0 && target < total) goTo(target, offset, speed);
465
+ else settle(offset, speed);
466
+ };
467
+
468
+ /* Once a step has rendered, and before paint: re-centre the track on the
469
+ new image and, after a swipe, start the glide from where the drag let go
470
+ — in the same frame, so nothing jumps. */
471
+ React.useLayoutEffect(() => {
472
+ const slide = slideFromRef.current;
473
+ slideFromRef.current = null;
474
+ glideRef.current?.animation.cancel();
475
+ glideRef.current = null;
476
+ moveTrack(0);
477
+ if (!slide?.from) return;
478
+ glideHome(slide.from, slide.speed);
479
+ }, [index]);
480
+
481
+ return {
482
+ frameRef,
483
+ trackRef,
484
+ moveTrack,
485
+ pastEnd,
486
+ resist,
487
+ settle,
488
+ gliding,
489
+ stopGlide,
490
+ goTo,
491
+ step,
492
+ canStep,
493
+ release,
494
+ };
495
+ }
496
+
497
+ type SlideTrack = ReturnType<typeof useSlideTrack>;
498
+
499
+ /* Zoom, as in Telegram: the image scales about the stage's centre with a
500
+ short animation (pixels and all — the file is not swapped), and a zoomed
501
+ image pans — dragged by mouse, finger or pen, or moved by the wheel —
502
+ within the stage's bounds. */
503
+ function useZoomPan(
504
+ scale: number,
505
+ imageRef: React.RefObject<HTMLImageElement | null>,
506
+ frameRef: React.RefObject<HTMLDivElement | null>
507
+ ) {
508
+ const panRef = React.useRef({ x: 0, y: 0 });
509
+ const scaleRef = React.useRef(scale);
510
+ const dragRef = React.useRef<{ x: number; y: number; moved: boolean } | null>(
511
+ null
512
+ );
513
+ const pannedRef = React.useRef(false);
514
+
515
+ const apply = (animate: boolean) => {
516
+ const image = imageRef.current;
517
+ const frame = frameRef.current;
518
+ if (!image || !frame) return;
519
+ const zoom = scaleRef.current;
520
+ const maxX = Math.max(
521
+ 0,
522
+ (image.offsetWidth * zoom - frame.clientWidth) / 2
523
+ );
524
+ const maxY = Math.max(
525
+ 0,
526
+ (image.offsetHeight * zoom - frame.clientHeight) / 2
527
+ );
528
+ const pan = panRef.current;
529
+ pan.x = Math.min(maxX, Math.max(-maxX, pan.x));
530
+ pan.y = Math.min(maxY, Math.max(-maxY, pan.y));
531
+ image.style.transition = animate
532
+ ? `transform ${MOTION_DURATION_BASE_MS}ms ${MOTION_EASE_DECELERATE}`
533
+ : "none";
534
+ image.style.transform =
535
+ zoom === 1 ? "" : `translate(${pan.x}px, ${pan.y}px) scale(${zoom})`;
536
+ };
537
+
538
+ /* A new level animates from the old; the pan scales with it, so the
539
+ point in view stays in view. Back at 1× the image re-centres. */
540
+ React.useLayoutEffect(() => {
541
+ const ratio = scale / scaleRef.current;
542
+ scaleRef.current = scale;
543
+ panRef.current =
544
+ scale === 1
545
+ ? { x: 0, y: 0 }
546
+ : { x: panRef.current.x * ratio, y: panRef.current.y * ratio };
547
+ apply(true);
548
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- runs per level
549
+ }, [scale]);
550
+
551
+ const panBy = (dx: number, dy: number) => {
552
+ panRef.current.x += dx;
553
+ panRef.current.y += dy;
554
+ apply(false);
555
+ };
556
+ /* Drop the zoom on the image being left (a step), at once. */
557
+ const reset = () => {
558
+ const image = imageRef.current;
559
+ panRef.current = { x: 0, y: 0 };
560
+ scaleRef.current = 1;
561
+ if (image) {
562
+ image.style.transition = "none";
563
+ image.style.transform = "";
564
+ }
565
+ };
566
+
567
+ const onPointerDown = (event: React.PointerEvent<HTMLDivElement>) => {
568
+ if (event.pointerType === "mouse" && event.button !== 0) return;
569
+ pannedRef.current = false;
570
+ /* Only the image is dragged. A press beside it is left alone, so its
571
+ click still reaches the backdrop and closes the view. */
572
+ if (!(
573
+ event.target instanceof Node && imageRef.current?.contains(event.target)
574
+ ))
575
+ return;
576
+ dragRef.current = { x: event.clientX, y: event.clientY, moved: false };
577
+ event.currentTarget.setPointerCapture?.(event.pointerId);
578
+ };
579
+ const onPointerMove = (event: React.PointerEvent<HTMLDivElement>) => {
580
+ const drag = dragRef.current;
581
+ if (!drag) return;
582
+ const dx = event.clientX - drag.x;
583
+ const dy = event.clientY - drag.y;
584
+ if (!drag.moved && Math.hypot(dx, dy) < 4) return;
585
+ drag.moved = true;
586
+ drag.x = event.clientX;
587
+ drag.y = event.clientY;
588
+ panBy(dx, dy);
589
+ };
590
+ const onPointerUp = () => {
591
+ pannedRef.current = Boolean(dragRef.current?.moved);
592
+ dragRef.current = null;
593
+ };
594
+ /* True once for the click that ends a pan, which is not a dismiss. */
595
+ const consumePan = () => {
596
+ const panned = pannedRef.current;
597
+ pannedRef.current = false;
598
+ return panned;
599
+ };
600
+
601
+ return {
602
+ panBy,
603
+ reset,
604
+ onPointerDown,
605
+ onPointerMove,
606
+ onPointerUp,
607
+ consumePan,
608
+ };
609
+ }
610
+
611
+ /* Touch and pen drag the track. The axis is settled after a few pixels: a
612
+ mostly-vertical drag is left to scroll (a tall capture scrolls). The click
613
+ that ends a swipe is not a dismiss — `consumeSwipe` tells the click handler. */
614
+ function useTouchSwipe(track: SlideTrack, enabled: boolean) {
615
+ const swipedRef = React.useRef(false);
616
+ const dragRef = React.useRef<{
617
+ x: number;
618
+ y: number;
619
+ axis: "x" | "y" | null;
620
+ /** Where the track stood when the drag caught it (mid-glide or 0). */
621
+ base: number;
622
+ offset: number;
623
+ /** Recent speed, px/ms, smoothed over the last moves. */
624
+ speed: number;
625
+ lastX: number;
626
+ lastTime: number;
627
+ } | null>(null);
628
+
629
+ const onPointerDown = (event: React.PointerEvent<HTMLDivElement>) => {
630
+ swipedRef.current = false;
631
+ /* A zoomed image pans instead: the drag is the browser's scroll. */
632
+ if (event.pointerType === "mouse" || !enabled) return;
633
+ dragRef.current = {
634
+ x: event.clientX,
635
+ y: event.clientY,
636
+ axis: null,
637
+ base: 0,
638
+ offset: 0,
639
+ speed: 0,
640
+ lastX: event.clientX,
641
+ lastTime: event.timeStamp,
642
+ };
643
+ };
644
+ const onPointerMove = (event: React.PointerEvent<HTMLDivElement>) => {
645
+ const drag = dragRef.current;
646
+ if (!drag) return;
647
+ const dx = event.clientX - drag.x;
648
+ const dy = event.clientY - drag.y;
649
+ if (!drag.axis) {
650
+ if (Math.hypot(dx, dy) < 8) return;
651
+ drag.axis = Math.abs(dx) > Math.abs(dy) ? "x" : "y";
652
+ if (drag.axis === "x") drag.base = track.stopGlide();
653
+ }
654
+ if (drag.axis !== "x") return;
655
+ const elapsed = event.timeStamp - drag.lastTime;
656
+ if (elapsed > 0) {
657
+ const instant = (event.clientX - drag.lastX) / elapsed;
658
+ drag.speed = drag.speed * 0.3 + instant * 0.7;
659
+ }
660
+ drag.lastX = event.clientX;
661
+ drag.lastTime = event.timeStamp;
662
+ drag.offset = track.resist(drag.base + dx);
663
+ track.moveTrack(drag.offset);
664
+ };
665
+ const onPointerUp = (event: React.PointerEvent<HTMLDivElement>) => {
666
+ const drag = dragRef.current;
667
+ dragRef.current = null;
668
+ if (!drag || drag.axis !== "x") return;
669
+ swipedRef.current = true;
670
+ /* A finger resting before lifting has no speed left. */
671
+ const speed = event.timeStamp - drag.lastTime > 80 ? 0 : drag.speed;
672
+ /* Step on how far the finger went, not on where it caught the track. */
673
+ track.release(drag.offset, event.clientX - drag.x, speed);
674
+ };
675
+ const onPointerCancel = () => {
676
+ const drag = dragRef.current;
677
+ dragRef.current = null;
678
+ if (drag?.axis === "x") track.settle(drag.offset);
679
+ };
680
+
681
+ /* True once for the click that ends a swipe, which is not a dismiss. */
682
+ const consumeSwipe = () => {
683
+ const swiped = swipedRef.current;
684
+ swipedRef.current = false;
685
+ return swiped;
686
+ };
687
+
688
+ return {
689
+ consumeSwipe,
690
+ onPointerDown,
691
+ onPointerMove,
692
+ onPointerUp,
693
+ onPointerCancel,
694
+ };
695
+ }
696
+
697
+ /* A horizontal two-finger swipe on a trackpad (the approach of
698
+ yet-another-react-lightbox's wheel swipe, a widely used, well-tried one).
699
+ Once it shows intent, the image follows it one to one; a pull past a fifth
700
+ of the stage steps, and the image glides on at the swipe's speed. Stopping
701
+ short springs back once the fingers have been still a while. The inertia
702
+ that follows a step is swallowed, so one swipe is one step; a clearly
703
+ stronger delta, or one that turns back, is new fingers and starts the next
704
+ swipe. Mostly vertical wheel is left alone (a tall capture scrolls), as is
705
+ the thumbnail strip, which scrolls sideways. The listener is not passive,
706
+ so a horizontal swipe never reaches the browser as back / forward. */
707
+ function useWheelSwipe(
708
+ node: HTMLElement | null,
709
+ track: SlideTrack,
710
+ enabled: boolean,
711
+ onPan: (dx: number, dy: number) => void
712
+ ) {
713
+ /* The latest track, for the native listener subscribed once per node. */
714
+ const trackRef = React.useRef(track);
715
+ const enabledRef = React.useRef(enabled);
716
+ const onPanRef = React.useRef(onPan);
717
+ React.useLayoutEffect(() => {
718
+ trackRef.current = track;
719
+ enabledRef.current = enabled;
720
+ onPanRef.current = onPan;
721
+ });
722
+ const gestureRef = React.useRef({
723
+ swiping: false,
724
+ intent: 0,
725
+ /** Where the track stands (it may have been caught mid-glide)… */
726
+ offset: 0,
727
+ /** …and how far this swipe itself has pulled, which alone decides. */
728
+ pull: 0,
729
+ /** The last delta while swiping, and how many in a row have faded. */
730
+ previous: 0,
731
+ fading: 0,
732
+ speed: 0,
733
+ last: 0,
734
+ /** Set by a step and kept up by the inertia that follows, while it
735
+ lasts: the last inertia delta (inertia fades from it and never turns
736
+ back). */
737
+ inertia: 0,
738
+ inertiaTimer: 0,
739
+ /** Since the step: the last inertia delta's size, the faintest, and
740
+ whether they have started to fade. */
741
+ inertiaPrevious: 0,
742
+ inertiaFaintest: 0,
743
+ inertiaFading: false,
744
+ cancelTimer: 0,
745
+ });
746
+
747
+ React.useEffect(() => {
748
+ if (!node) return;
749
+ const gesture = gestureRef.current;
750
+ const noteInertia = (delta: number) => {
751
+ gesture.inertia = delta;
752
+ window.clearTimeout(gesture.inertiaTimer);
753
+ gesture.inertiaTimer = window.setTimeout(() => {
754
+ gesture.inertia = 0;
755
+ }, WHEEL_INERTIA_TTL);
756
+ };
757
+ /* A step's inertia starts: record where it fades from. */
758
+ const startInertia = (delta: number) => {
759
+ noteInertia(delta);
760
+ gesture.inertiaPrevious = Math.abs(delta);
761
+ gesture.inertiaFaintest = Math.abs(delta);
762
+ gesture.inertiaFading = false;
763
+ };
764
+ const handleWheel = (event: WheelEvent) => {
765
+ if (event.ctrlKey) return; // pinch
766
+ /* A zoomed image pans: the wheel (or two fingers) moves it. */
767
+ if (!enabledRef.current) {
768
+ event.preventDefault();
769
+ onPanRef.current(-event.deltaX, -event.deltaY);
770
+ return;
771
+ }
772
+ if (Math.abs(event.deltaY) > Math.abs(event.deltaX)) return;
773
+ if (
774
+ event.target instanceof Element &&
775
+ event.target.closest('[data-slot="media-viewer-thumbnails"]')
776
+ )
777
+ return;
778
+ event.preventDefault();
779
+ const track = trackRef.current;
780
+ const size = Math.abs(event.deltaX);
781
+ const elapsed = event.timeStamp - gesture.last;
782
+ gesture.last = event.timeStamp;
783
+
784
+ if (!gesture.swiping) {
785
+ /* After a step, inertia keeps coming — while the image glides in and
786
+ after. While it glides, anything the same way is the swipe running
787
+ on (fingers still speeding up, then inertia) — never a new swipe,
788
+ or one fast swipe would run through the set. After, a delta no
789
+ stronger than the last inertia is more of it. Any inertia-like
790
+ delta resets the new-fingers count, so a bump in the inertia never
791
+ adds up to a swipe. */
792
+ window.clearTimeout(gesture.cancelTimer);
793
+ const sameWay =
794
+ gesture.inertia !== 0 &&
795
+ Math.sign(event.deltaX) === Math.sign(gesture.inertia);
796
+ /* Inertia only fades: a delta that rises again after the fade, to
797
+ twice its faintest, is new fingers — the next swipe, even while
798
+ the image still glides in. */
799
+ if (sameWay) {
800
+ /* The faintest is counted from the fade on, not from a run-up
801
+ that was still rising. */
802
+ if (size < gesture.inertiaPrevious) {
803
+ if (!gesture.inertiaFading) gesture.inertiaFaintest = size;
804
+ gesture.inertiaFading = true;
805
+ }
806
+ if (gesture.inertiaFading)
807
+ gesture.inertiaFaintest = Math.min(gesture.inertiaFaintest, size);
808
+ gesture.inertiaPrevious = size;
809
+ }
810
+ const rose =
811
+ gesture.inertiaFading &&
812
+ size >= gesture.inertiaFaintest * WHEEL_FRESH_RISE;
813
+ if (
814
+ sameWay &&
815
+ !rose &&
816
+ (track.gliding() ||
817
+ size <= Math.abs(gesture.inertia) * WHEEL_INERTIA_RISE)
818
+ ) {
819
+ noteInertia(event.deltaX);
820
+ gesture.intent = 0;
821
+ return;
822
+ }
823
+ gesture.intent += event.deltaX;
824
+ if (Math.abs(gesture.intent) <= WHEEL_INTENT) {
825
+ /* A slow drift does not add up forever. */
826
+ gesture.cancelTimer = window.setTimeout(() => {
827
+ gesture.intent = 0;
828
+ }, WHEEL_CANCEL_DELAY);
829
+ return;
830
+ }
831
+ gesture.intent = 0;
832
+ gesture.swiping = true;
833
+ gesture.inertia = 0;
834
+ gesture.inertiaFading = false;
835
+ /* Catch a gliding image where it is — the pull starts from zero. */
836
+ gesture.offset = track.stopGlide();
837
+ gesture.pull = 0;
838
+ gesture.speed = 0;
839
+ gesture.fading = 0;
840
+ } else if (elapsed > 0) {
841
+ gesture.speed = gesture.speed * 0.3 + (-event.deltaX / elapsed) * 0.7;
842
+ }
843
+
844
+ window.clearTimeout(gesture.cancelTimer);
845
+ const width = node.clientWidth;
846
+ gesture.offset = Math.max(
847
+ -width,
848
+ Math.min(width, gesture.offset - event.deltaX)
849
+ );
850
+ gesture.pull -= event.deltaX;
851
+ track.moveTrack(track.resist(gesture.offset));
852
+ /* Pulled past the first or last image: as soon as the motion fades —
853
+ the fingers are off, inertia is running — bounce back, and let the
854
+ rest of the inertia pass. */
855
+ gesture.fading = size < gesture.previous ? gesture.fading + 1 : 0;
856
+ gesture.previous = size;
857
+ if (track.pastEnd(gesture.offset) && gesture.fading >= 2) {
858
+ gesture.swiping = false;
859
+ startInertia(event.deltaX);
860
+ track.release(track.resist(gesture.offset), 0);
861
+ return;
862
+ }
863
+ if (track.canStep(gesture.pull, width * WHEEL_STEP_SHARE)) {
864
+ gesture.swiping = false;
865
+ startInertia(event.deltaX);
866
+ track.release(
867
+ track.resist(gesture.offset),
868
+ gesture.pull,
869
+ gesture.speed
870
+ );
871
+ return;
872
+ }
873
+ gesture.cancelTimer = window.setTimeout(() => {
874
+ gesture.swiping = false;
875
+ track.release(track.resist(gesture.offset), 0);
876
+ }, WHEEL_CANCEL_DELAY);
877
+ };
878
+ node.addEventListener("wheel", handleWheel, { passive: false });
879
+ return () => {
880
+ node.removeEventListener("wheel", handleWheel);
881
+ window.clearTimeout(gesture.cancelTimer);
882
+ window.clearTimeout(gesture.inertiaTimer);
883
+ };
884
+ }, [node]);
885
+ }
886
+ /* -------------------------------------------------------------------------------------------------
887
+ * MediaViewerContent — private parts
888
+ * -----------------------------------------------------------------------------------------------*/
889
+
890
+ /* Previous / Next are full-height strips down the sides of the stage, as in
891
+ Telegram: the whole strip is the button, so it is hard to miss; the arrow
892
+ marks it. Raw buttons by design — no DS component is a full-height hit
893
+ strip; the arrow itself is drawn as a ghost icon Button. */
894
+ function NavStrips({
895
+ dataHook,
896
+ hasPrevious,
897
+ hasNext,
898
+ previousLabel,
899
+ nextLabel,
900
+ onStep,
901
+ }: {
902
+ dataHook: string;
903
+ hasPrevious: boolean;
904
+ hasNext: boolean;
905
+ previousLabel?: string;
906
+ nextLabel?: string;
907
+ onStep: (delta: -1 | 1) => void;
908
+ }) {
909
+ return (
910
+ <>
911
+ <button
912
+ aria-label={previousLabel ?? "Previous"}
913
+ className={cn(navZone, "left-0")}
914
+ data-hook={`${dataHook}-previous`}
915
+ data-slot="media-viewer-previous"
916
+ disabled={!hasPrevious}
917
+ type="button"
918
+ onClick={() => onStep(-1)}
919
+ >
920
+ <span aria-hidden className={navArrow}>
921
+ <ChevronLeft />
922
+ </span>
923
+ </button>
924
+ <button
925
+ aria-label={nextLabel ?? "Next"}
926
+ className={cn(navZone, "right-0")}
927
+ data-hook={`${dataHook}-next`}
928
+ data-slot="media-viewer-next"
929
+ disabled={!hasNext}
930
+ type="button"
931
+ onClick={() => onStep(1)}
932
+ >
933
+ <span aria-hidden className={navArrow}>
934
+ <ChevronRight />
935
+ </span>
936
+ </button>
937
+ </>
938
+ );
939
+ }
940
+
941
+ /* The strip of thumbnails in the bar: one button per item, the open one at
942
+ full opacity (`aria-current`) and kept in view as the reader steps. A long
943
+ set loads only the thumbnails in or near view (lazy). Their files give each
944
+ image's ratio early, so a step lays the image out at its final size. */
945
+ function ThumbnailStrip({
946
+ dataHook,
947
+ items,
948
+ index,
949
+ failed,
950
+ label,
951
+ onSelect,
952
+ onRatio,
953
+ }: {
954
+ dataHook: string;
955
+ items: MediaViewerItem[];
956
+ index: number;
957
+ failed: ReadonlySet<string>;
958
+ label?: string;
959
+ onSelect: (index: number) => void;
960
+ onRatio: (src: string, width: number, height: number) => void;
961
+ }) {
962
+ const stripRef = React.useRef<HTMLDivElement | null>(null);
963
+ React.useEffect(() => {
964
+ stripRef.current
965
+ ?.querySelector<HTMLElement>('[aria-current="true"]')
966
+ ?.scrollIntoView?.({ block: "nearest", inline: "nearest" });
967
+ }, [index]);
968
+
969
+ return (
970
+ <div
971
+ ref={stripRef}
972
+ aria-label={label ?? "Images"}
973
+ className="mb-2 flex max-w-full gap-1.5 justify-self-center overflow-x-auto p-1 [grid-area:strip] sm:mb-0"
974
+ data-hook={`${dataHook}-thumbnails`}
975
+ data-slot="media-viewer-thumbnails"
976
+ role="group"
977
+ >
978
+ {items.map((it, i) => {
979
+ const current = i === index;
980
+ const dead = it.expired || failed.has(it.src);
981
+ return (
982
+ <button
983
+ key={it.src}
984
+ aria-current={current ? "true" : undefined}
985
+ aria-label={it.alt}
986
+ className={cn(
987
+ "bg-muted relative size-12 shrink-0 overflow-hidden rounded-md outline-none",
988
+ "duration-fast focus-visible:shadow-default transition-opacity ease-out",
989
+ current ? "opacity-100" : "opacity-50 hover:opacity-100"
990
+ )}
991
+ data-hook={`${dataHook}-thumbnail-${i}`}
992
+ data-slot="media-viewer-thumbnail"
993
+ type="button"
994
+ onClick={() => onSelect(i)}
995
+ >
996
+ {dead ? null : (
997
+ // eslint-disable-next-line jsx-a11y/no-noninteractive-element-interactions -- onLoad is a load event, not an interaction
998
+ <img
999
+ alt=""
1000
+ className="size-full object-cover object-top"
1001
+ decoding="async"
1002
+ draggable={false}
1003
+ loading="lazy"
1004
+ src={it.thumbnailSrc ?? it.src}
1005
+ onLoad={(event) =>
1006
+ onRatio(
1007
+ it.src,
1008
+ event.currentTarget.naturalWidth,
1009
+ event.currentTarget.naturalHeight
1010
+ )
1011
+ }
1012
+ />
1013
+ )}
1014
+ </button>
1015
+ );
1016
+ })}
1017
+ </div>
1018
+ );
1019
+ }
1020
+
1021
+ /* The view itself; MediaViewerContent renders it when the root has one
1022
+ (`viewable`, the default). */
1023
+ const MediaViewerView = React.forwardRef<
1024
+ HTMLDivElement,
1025
+ MediaViewerContentProps
1026
+ >(
1027
+ (
1028
+ {
1029
+ dataHook,
1030
+ children,
1031
+ formatPosition,
1032
+ previousLabel,
1033
+ nextLabel,
1034
+ thumbnailsLabel,
1035
+ unavailableMessage,
1036
+ zoomInLabel,
1037
+ zoomOutLabel,
1038
+ downloadLabel,
1039
+ infoLabel,
1040
+ dateLabels,
1041
+ className,
1042
+ trackingEl,
1043
+ trackingLabel,
1044
+ onClick,
1045
+ onCloseAutoFocus,
1046
+ onEscapeKeyDown,
1047
+ onKeyDown,
1048
+ onOpenAutoFocus,
1049
+ ...props
1050
+ },
1051
+ ref
1052
+ ) => {
1053
+ const {
1054
+ items,
1055
+ index,
1056
+ setIndex,
1057
+ openerRef,
1058
+ open,
1059
+ setOpen,
1060
+ openCount,
1061
+ openedAtRef,
1062
+ revealed,
1063
+ reveal,
1064
+ triggersRef,
1065
+ renderActions,
1066
+ actionsLabel,
1067
+ } = useMediaViewerContext("MediaViewerContent");
1068
+ const reducedMotion = usePrefersReducedMotion();
1069
+ // Safety net for the Radix dismissable-layer body-lock leak (DS-634).
1070
+ useOverlayPointerLock();
1071
+ const total = items.length;
1072
+ const safeIndex = Math.min(Math.max(index, 0), Math.max(total - 1, 0));
1073
+ const hasPrevious = safeIndex > 0;
1074
+ const hasNext = safeIndex < total - 1;
1075
+
1076
+ /* Zoom, by the buttons or + / −: a level from ZOOM_LEVELS, reset by a
1077
+ step and by closing (keyed by the opening and the open item). A
1078
+ zoomed image pans (useZoomPan); swipes and the click-to-close on the
1079
+ image stand down meanwhile, and closing fades instead of zooming. */
1080
+ const zoomKey = `${openCount}:${safeIndex}`;
1081
+ const [zoomState, setZoomState] = React.useState({ key: "", level: 0 });
1082
+ const zoomLevel = zoomState.key === zoomKey ? zoomState.level : 0;
1083
+ const zoomed = zoomLevel > 0;
1084
+ const zoomBy = (delta: -1 | 1) =>
1085
+ /* From the latest level, so quick presses each count. */
1086
+ setZoomState((prev) => {
1087
+ const from = prev.key === zoomKey ? prev.level : 0;
1088
+ const level = Math.min(
1089
+ Math.max(from + delta, 0),
1090
+ ZOOM_LEVELS.length - 1
1091
+ );
1092
+ return level === from && prev.key === zoomKey
1093
+ ? prev
1094
+ : { key: zoomKey, level };
1095
+ });
1096
+
1097
+ const { failed, ratios, widths, ready, noteRatio, markFailed } =
1098
+ useMediaFiles(items, safeIndex, open);
1099
+ const zoom = useOpeningZoom({
1100
+ index: safeIndex,
1101
+ openCount,
1102
+ openedAtRef,
1103
+ triggersRef,
1104
+ reducedMotion,
1105
+ setOpen,
1106
+ revealed,
1107
+ reveal,
1108
+ });
1109
+ const track = useSlideTrack({
1110
+ index: safeIndex,
1111
+ total,
1112
+ reducedMotion,
1113
+ onStep: (next) => {
1114
+ /* Only the image the view opened on waits for its zoom; after a
1115
+ step (say, from an expired item, whose zoom never ran) it shows
1116
+ at once. */
1117
+ zoom.reveal();
1118
+ pan.reset();
1119
+ setIndex(next);
1120
+ },
1121
+ });
1122
+ const touch = useTouchSwipe(track, !zoomed);
1123
+ const { frameRef, trackRef } = track;
1124
+ const { imageRef, overlayRef, barRef } = zoom;
1125
+ const pan = useZoomPan(ZOOM_LEVELS[zoomLevel] ?? 1, imageRef, frameRef);
1126
+ const [contentNode, setContentNode] = React.useState<HTMLDivElement | null>(
1127
+ null
1128
+ );
1129
+ const setContentRefs = React.useCallback(
1130
+ (node: HTMLDivElement | null) => {
1131
+ setContentNode(node);
1132
+ if (typeof ref === "function") ref(node);
1133
+ else if (ref) ref.current = node;
1134
+ },
1135
+ [ref]
1136
+ );
1137
+ useWheelSwipe(contentNode, track, !zoomed, pan.panBy);
1138
+
1139
+ const current = items[safeIndex];
1140
+ const currentAvailable = Boolean(
1141
+ current && !current.expired && !failed.has(current.src)
1142
+ );
1143
+ /* The file Download saves: its format, size in pixels and weight. */
1144
+ const fileInfo = useImageFileInfo(
1145
+ currentAvailable ? (current?.downloadSrc ?? current?.src) : undefined,
1146
+ open
1147
+ );
1148
+
1149
+ const handleLoad = (
1150
+ event: React.SyntheticEvent<HTMLImageElement>,
1151
+ src: string,
1152
+ open: boolean
1153
+ ) => {
1154
+ const img = event.currentTarget;
1155
+ const loaded = noteRatio(src, img.naturalWidth, img.naturalHeight);
1156
+ if (!open) return;
1157
+ /* Set on the element too, so the zoom measures the final box now,
1158
+ not after the re-render. */
1159
+ if (loaded) img.style.setProperty("--media-ratio", String(loaded));
1160
+ zoom.zoomIn(
1161
+ img,
1162
+ loaded !== null && 1 / loaded > TALL_RATIO,
1163
+ event.timeStamp
1164
+ );
1165
+ };
1166
+
1167
+ const handleKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {
1168
+ if (event.defaultPrevented) return;
1169
+ /* Keys in an open menu (it portals out, but React bubbles them here)
1170
+ are the menu's. */
1171
+ if ((event.target as Element).closest('[role="menu"]')) return;
1172
+ if (event.key === "ArrowLeft") {
1173
+ event.preventDefault();
1174
+ track.step(-1);
1175
+ } else if (event.key === "ArrowRight") {
1176
+ event.preventDefault();
1177
+ track.step(1);
1178
+ } else if ((event.key === "+" || event.key === "=") && currentAvailable) {
1179
+ event.preventDefault();
1180
+ zoomBy(1);
1181
+ } else if (event.key === "-" && currentAvailable) {
1182
+ event.preventDefault();
1183
+ zoomBy(-1);
1184
+ }
1185
+ };
1186
+
1187
+ /* Radix returns focus to the last trigger it registered; with a grid of
1188
+ triggers that is the wrong one, so return it to the opener. */
1189
+ const handleCloseAutoFocus = (event: Event) => {
1190
+ const opener = openerRef.current;
1191
+ if (opener?.isConnected) {
1192
+ event.preventDefault();
1193
+ opener.focus();
1194
+ }
1195
+ };
1196
+
1197
+ /* Focus the view itself on open, not its first control: arrow keys and
1198
+ Esc work at once, and Previous / Next stay hidden until hovered. */
1199
+ const handleOpenAutoFocus = (event: Event) => {
1200
+ event.preventDefault();
1201
+ (event.currentTarget as HTMLElement | null)?.focus();
1202
+ };
1203
+
1204
+ /* A click on the image or the backdrop — anywhere that is not a control
1205
+ or the bar's content — closes the view. The panel fills the window, so
1206
+ Radix never sees an outside click; the dismiss areas are marked
1207
+ instead. The click that ends a swipe is not a dismiss. */
1208
+ const handleClick = (event: React.MouseEvent<HTMLDivElement>) => {
1209
+ if (touch.consumeSwipe() || pan.consumePan()) return;
1210
+ if (
1211
+ event.target instanceof HTMLElement &&
1212
+ event.target.hasAttribute("data-media-viewer-backdrop")
1213
+ ) {
1214
+ zoom.requestClose({ fade: zoomed });
1215
+ }
1216
+ };
1217
+
1218
+ /* Built-in controls for the open image — Download, Zoom in, Zoom out —
1219
+ in that order, ahead of any consumer actions. */
1220
+ /* After everything else: the item's More actions, then Image details,
1221
+ last at the right. */
1222
+ const more = (
1223
+ <>
1224
+ {current && renderActions ? (
1225
+ <ItemActionsMenu
1226
+ dataHook={`${dataHook}-actions-menu`}
1227
+ label={actionsLabel(current, safeIndex)}
1228
+ variant="ghost"
1229
+ >
1230
+ {renderActions(current, safeIndex)}
1231
+ </ItemActionsMenu>
1232
+ ) : null}
1233
+ {/* Sized and coloured like the ghost buttons beside it, so the row
1234
+ keeps one rhythm. */}
1235
+ <InfoTooltip
1236
+ ariaLabel={infoLabel ?? "Image details"}
1237
+ className="text-foreground hover:bg-accent size-9 items-center justify-center rounded-md"
1238
+ content={describeImageFile(fileInfo)}
1239
+ dataHook={`${dataHook}-info`}
1240
+ disabled={!currentAvailable}
1241
+ />
1242
+ </>
1243
+ );
1244
+ const lead = (
1245
+ <>
1246
+ <Button
1247
+ iconOnly
1248
+ ariaLabel={downloadLabel ?? "Download"}
1249
+ dataHook={`${dataHook}-download`}
1250
+ disabled={!currentAvailable}
1251
+ variant="ghost"
1252
+ onClick={() => {
1253
+ if (current) void downloadFile(current.downloadSrc ?? current.src);
1254
+ }}
1255
+ >
1256
+ <Download aria-hidden />
1257
+ </Button>
1258
+ <Button
1259
+ iconOnly
1260
+ ariaLabel={zoomInLabel ?? "Zoom in"}
1261
+ dataHook={`${dataHook}-zoom-in`}
1262
+ disabled={!currentAvailable || zoomLevel === ZOOM_LEVELS.length - 1}
1263
+ variant="ghost"
1264
+ onClick={() => zoomBy(1)}
1265
+ >
1266
+ <ZoomIn aria-hidden />
1267
+ </Button>
1268
+ <Button
1269
+ iconOnly
1270
+ ariaLabel={zoomOutLabel ?? "Zoom out"}
1271
+ dataHook={`${dataHook}-zoom-out`}
1272
+ disabled={!currentAvailable || zoomLevel === 0}
1273
+ variant="ghost"
1274
+ onClick={() => zoomBy(-1)}
1275
+ >
1276
+ <ZoomOut aria-hidden />
1277
+ </Button>
1278
+ </>
1279
+ );
1280
+ /* MediaViewerActions, when present, registers here and renders the
1281
+ controls itself, ahead of its own children. */
1282
+ const [actionsMounted, setActionsMounted] = React.useState(0);
1283
+ const actionsRegistry = React.useMemo(
1284
+ () => () => {
1285
+ setActionsMounted((count) => count + 1);
1286
+ return () => setActionsMounted((count) => count - 1);
1287
+ },
1288
+ []
1289
+ );
1290
+
1291
+ /* One slide on the track per image — the open one and a neighbour
1292
+ either side, one stage-width off — keyed by image. A step moves the
1293
+ same elements along instead of loading a file into another element,
1294
+ so nothing reloads and nothing blinks. Each shows the best file at
1295
+ hand, sized by its ratio like the open image. */
1296
+ const renderSlide = (i: number) => {
1297
+ const slide = items[i];
1298
+ if (!slide) return null;
1299
+ const open = i === safeIndex;
1300
+ const dead = slide.expired || failed.has(slide.src);
1301
+ if (dead && !open) return null;
1302
+ const slideRatio = ratios.get(slide.src);
1303
+ /* A capture far taller than wide (a saved results page) keeps the
1304
+ stage width and scrolls rather than being shrunk past reading. */
1305
+ const tall = slideRatio !== undefined && 1 / slideRatio > TALL_RATIO;
1306
+ return (
1307
+ <div
1308
+ key={slide.src}
1309
+ aria-hidden={open ? undefined : true}
1310
+ className={cn(
1311
+ "[container-type:size] absolute inset-0 flex px-4 pt-8 pb-4 sm:px-20",
1312
+ /* A zoomed image pans by transform, so its slide clips rather
1313
+ than scrolls — no scrollbars. */
1314
+ open && !zoomed ? "overflow-auto" : "overflow-hidden"
1315
+ )}
1316
+ data-media-viewer-backdrop={open ? "" : undefined}
1317
+ data-slot={open ? "media-viewer-slide" : "media-viewer-peek"}
1318
+ style={
1319
+ open
1320
+ ? undefined
1321
+ : { transform: `translateX(${(i - safeIndex) * 100}%)` }
1322
+ }
1323
+ >
1324
+ {dead ? (
1325
+ <div className="m-auto w-full max-w-3xl">
1326
+ <div className="aspect-[4/3] w-full">
1327
+ <MediaEmpty
1328
+ dataHook={`${dataHook}-empty`}
1329
+ message={unavailableMessage ?? "Image no longer available"}
1330
+ />
1331
+ </div>
1332
+ </div>
1333
+ ) : (
1334
+ // eslint-disable-next-line jsx-a11y/no-noninteractive-element-interactions -- onLoad/onError are load events, not interactions
1335
+ <img
1336
+ ref={open ? imageRef : undefined}
1337
+ alt={open ? slide.alt : ""}
1338
+ className={cn(
1339
+ "m-auto block h-auto",
1340
+ /* Zoomed, the image is what drags; beside it, a click closes. */
1341
+ open && zoomed && "cursor-grab active:cursor-grabbing",
1342
+ /* Contained: the largest box of the image's ratio that fits
1343
+ the stage — but never wider than the full file itself, so
1344
+ a small image is not blown up past its pixels (a stand-in
1345
+ preview file takes the same box). */
1346
+ tall
1347
+ ? "w-full max-w-(--media-natural-width)"
1348
+ : "w-[min(100cqw,calc(100cqh*var(--media-ratio,1)),var(--media-natural-width,100cqw))]"
1349
+ )}
1350
+ data-fit={open ? (tall ? "width" : "contain") : undefined}
1351
+ data-hook={open ? `${dataHook}-image` : undefined}
1352
+ data-media-viewer-backdrop={open && !zoomed ? "" : undefined}
1353
+ data-slot={open ? "media-viewer-image" : undefined}
1354
+ data-zoom={open ? ZOOM_LEVELS[zoomLevel] : undefined}
1355
+ decoding="sync"
1356
+ draggable={false}
1357
+ src={
1358
+ ready.has(slide.src)
1359
+ ? slide.src
1360
+ : (slide.thumbnailSrc ?? slide.src)
1361
+ }
1362
+ style={
1363
+ {
1364
+ "--media-ratio": slideRatio,
1365
+ "--media-natural-width": widths.has(slide.src)
1366
+ ? `${widths.get(slide.src)}px`
1367
+ : undefined,
1368
+ visibility: open && !zoom.revealed ? "hidden" : undefined,
1369
+ } as React.CSSProperties
1370
+ }
1371
+ onError={() => markFailed(slide.src)}
1372
+ onLoad={(event) => handleLoad(event, slide.src, open)}
1373
+ />
1374
+ )}
1375
+ </div>
1376
+ );
1377
+ };
1378
+
1379
+ return (
1380
+ <DialogPortal>
1381
+ {/* Closing without a zoom (the open item has no preview on screen)
1382
+ is a quick fade, faster than the open. */}
1383
+ <DialogOverlay
1384
+ ref={overlayRef}
1385
+ /* Darker than a modal's backdrop: the page behind falls away and
1386
+ the bar's text and controls read on it without a band of their
1387
+ own. */
1388
+ className="data-[state=closed]:duration-fast bg-black/85 data-[state=closed]:ease-out"
1389
+ />
1390
+ {/* Built on the Radix primitive rather than DialogContent: the view
1391
+ has no close button — Esc or a click on the image or the backdrop closes it. */}
1392
+ <DialogPrimitive.Content
1393
+ ref={setContentRefs}
1394
+ /* The date under the title changes per image, so it does not
1395
+ describe the dialog; the title alone names it. */
1396
+ aria-describedby={undefined}
1397
+ className={cn(
1398
+ /* A lightbox: the whole window over a backdrop darker than a
1399
+ modal's. The panel is transparent; the `dark` class scopes the
1400
+ dark token set so its text and controls read on the backdrop
1401
+ whatever the page theme. */
1402
+ "dark text-foreground group/viewer data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:duration-fast fixed inset-0 z-50 grid h-dvh w-screen grid-rows-[minmax(0,1fr)_auto] ease-out outline-none",
1403
+ className
1404
+ )}
1405
+ data-hook={dataHook}
1406
+ data-media-viewer-backdrop=""
1407
+ data-slot="media-viewer-content"
1408
+ data-tracking-el={trackingEl ?? "media-viewer"}
1409
+ data-tracking-label={trackingLabel}
1410
+ {...props}
1411
+ /* Consumer handlers run first; ours skip if they preventDefault. */
1412
+ onClick={(event) => composeEventHandlers(onClick, handleClick)(event)}
1413
+ onCloseAutoFocus={(event) =>
1414
+ composeEventHandlers(onCloseAutoFocus, handleCloseAutoFocus)(event)
1415
+ }
1416
+ onEscapeKeyDown={(event) =>
1417
+ composeEventHandlers(onEscapeKeyDown, (escape: KeyboardEvent) => {
1418
+ escape.preventDefault();
1419
+ zoom.requestClose({ fade: zoomed });
1420
+ })(event)
1421
+ }
1422
+ onKeyDown={(event) =>
1423
+ composeEventHandlers(onKeyDown, handleKeyDown)(event)
1424
+ }
1425
+ onOpenAutoFocus={(event) =>
1426
+ composeEventHandlers(onOpenAutoFocus, handleOpenAutoFocus)(event)
1427
+ }
1428
+ >
1429
+ {/* The stage: the image, with Previous and Next at its sides. Touch
1430
+ swipes step. Not selectable, so quick clicks on Previous / Next do
1431
+ not select the image; the bar's text stays copyable. */}
1432
+ <div
1433
+ ref={frameRef}
1434
+ className={cn(
1435
+ "group/stage relative min-h-0 overflow-hidden select-none",
1436
+ zoomed ? "touch-none" : "touch-pan-y"
1437
+ )}
1438
+ data-hook={`${dataHook}-frame`}
1439
+ data-slot="media-viewer-frame"
1440
+ onPointerCancel={zoomed ? pan.onPointerUp : touch.onPointerCancel}
1441
+ onPointerDown={zoomed ? pan.onPointerDown : touch.onPointerDown}
1442
+ onPointerMove={zoomed ? pan.onPointerMove : touch.onPointerMove}
1443
+ onPointerUp={zoomed ? pan.onPointerUp : touch.onPointerUp}
1444
+ >
1445
+ {/* Side padding keeps the image clear of Previous / Next. The image
1446
+ sizes to itself (not to the stage), so a click beside it lands
1447
+ on the backdrop. */}
1448
+ <div ref={trackRef} className="relative size-full">
1449
+ {[safeIndex - 1, safeIndex, safeIndex + 1].map(renderSlide)}
1450
+ </div>
1451
+ {total > 1 ? (
1452
+ <NavStrips
1453
+ dataHook={dataHook}
1454
+ hasNext={hasNext}
1455
+ hasPrevious={hasPrevious}
1456
+ nextLabel={nextLabel}
1457
+ previousLabel={previousLabel}
1458
+ onStep={track.step}
1459
+ />
1460
+ ) : null}
1461
+ </div>
1462
+ {/* The bottom bar. The strip is rendered first so the tab order runs
1463
+ thumbnails, then actions — left to right among the focusable parts;
1464
+ the title, description and date are placed by grid area. Narrow screens
1465
+ put the strip on its own row above. */}
1466
+ <div
1467
+ ref={barRef}
1468
+ className={cn(
1469
+ "grid items-center gap-x-4 gap-y-1 px-4 pt-6 pb-3 sm:px-8",
1470
+ "grid-cols-[minmax(0,1fr)_auto] [grid-template-areas:'strip_strip'_'title_actions'_'caption_actions'_'date_actions']",
1471
+ /* Fixed shares, not sized by content: however many thumbnails, the
1472
+ strip keeps to the middle half and scrolls, never running
1473
+ under the title or the actions. */
1474
+ "sm:grid-cols-[minmax(0,1fr)_minmax(0,2fr)_minmax(0,1fr)] sm:[grid-template-areas:'title_strip_actions'_'caption_strip_actions'_'date_strip_actions']"
1475
+ )}
1476
+ data-media-viewer-backdrop=""
1477
+ data-slot="media-viewer-bar"
1478
+ >
1479
+ {total > 1 ? (
1480
+ /* Polite live region, visually hidden: the strip shows the
1481
+ position, this announces it. */
1482
+ <span
1483
+ aria-atomic="true"
1484
+ aria-live="polite"
1485
+ className="sr-only"
1486
+ data-hook={`${dataHook}-position`}
1487
+ data-slot="media-viewer-position"
1488
+ role="status"
1489
+ >
1490
+ {(formatPosition ?? defaultFormatPosition)(
1491
+ safeIndex + 1,
1492
+ total
1493
+ )}
1494
+ </span>
1495
+ ) : null}
1496
+ {total > 1 ? (
1497
+ <ThumbnailStrip
1498
+ dataHook={dataHook}
1499
+ failed={failed}
1500
+ index={safeIndex}
1501
+ items={items}
1502
+ label={thumbnailsLabel}
1503
+ onRatio={noteRatio}
1504
+ onSelect={track.goTo}
1505
+ />
1506
+ ) : null}
1507
+ {current?.alt ? (
1508
+ /* The open image's description, for the eye: the image's alt
1509
+ already says it to a screen reader. */
1510
+ <TruncatedText<HTMLParagraphElement>
1511
+ dataHook={`${dataHook}-caption`}
1512
+ full={current.alt}
1513
+ render={(ref) => (
1514
+ <p
1515
+ ref={ref}
1516
+ aria-hidden
1517
+ className="text-body-xs truncate [grid-area:caption]"
1518
+ data-hook={`${dataHook}-caption`}
1519
+ data-slot="media-viewer-caption"
1520
+ >
1521
+ {current.alt}
1522
+ </p>
1523
+ )}
1524
+ />
1525
+ ) : null}
1526
+ {current?.date ? (
1527
+ <RelativeDate
1528
+ className="truncate [grid-area:date]"
1529
+ dataHook={`${dataHook}-date`}
1530
+ labels={dateLabels}
1531
+ value={current.date}
1532
+ />
1533
+ ) : null}
1534
+ <MediaViewerControlsContext.Provider value={{ lead, more }}>
1535
+ <MediaViewerActionsRegistry.Provider value={actionsRegistry}>
1536
+ {/* Without the consumer's MediaViewerActions, the built-in
1537
+ controls stand on their own at the right of the bar. */}
1538
+ {actionsMounted ? null : (
1539
+ <div
1540
+ className="flex items-center justify-end gap-1 [grid-area:actions]"
1541
+ data-hook={`${dataHook}-actions`}
1542
+ data-slot="media-viewer-actions"
1543
+ >
1544
+ {lead}
1545
+ {more}
1546
+ </div>
1547
+ )}
1548
+ {children}
1549
+ </MediaViewerActionsRegistry.Provider>
1550
+ </MediaViewerControlsContext.Provider>
1551
+ </div>
1552
+ </DialogPrimitive.Content>
1553
+ </DialogPortal>
1554
+ );
1555
+ }
1556
+ );
1557
+
1558
+ MediaViewerView.displayName = "MediaViewerView";
1559
+
1560
+ /**
1561
+ * The full view, a lightbox that fills the window: the image with Previous /
1562
+ * Next at its sides, and a bottom bar with the title, a strip of thumbnails and
1563
+ * the actions; the arrow keys and Esc; an empty state for an expired image.
1564
+ *
1565
+ * @example
1566
+ * ```tsx
1567
+ * <MediaViewerContent dataHook="photo-viewer">
1568
+ * <MediaViewerTitle>Riverside Plumbing</MediaViewerTitle>
1569
+ * <MediaViewerActions>
1570
+ * <Button iconOnly variant="ghost" dataHook="photo-share" ariaLabel="Share" onClick={share}>
1571
+ * <Share2 aria-hidden />
1572
+ * </Button>
1573
+ * </MediaViewerActions>
1574
+ * </MediaViewerContent>
1575
+ * ```
1576
+ */
1577
+ const MediaViewerContent = React.forwardRef<
1578
+ HTMLDivElement,
1579
+ MediaViewerContentProps
1580
+ >((props, ref) => {
1581
+ const { viewable } = useMediaViewerContext("MediaViewerContent");
1582
+ return viewable ? <MediaViewerView ref={ref} {...props} /> : null;
1583
+ });
1584
+
1585
+ MediaViewerContent.displayName = "MediaViewerContent";
1586
+
1587
+ export { MediaViewerContent };