tempest-react-sdk 0.56.0 → 0.58.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 (337) hide show
  1. package/bin/lib/icons/generate.test.mjs +4 -4
  2. package/dist/br/geocode.cjs +1 -1
  3. package/dist/br/geocode.cjs.map +1 -1
  4. package/dist/br/geocode.js +1 -1
  5. package/dist/br/geocode.js.map +1 -1
  6. package/dist/capture/use-barcode-scanner.cjs +1 -1
  7. package/dist/capture/use-barcode-scanner.cjs.map +1 -1
  8. package/dist/capture/use-barcode-scanner.js +1 -1
  9. package/dist/capture/use-barcode-scanner.js.map +1 -1
  10. package/dist/components/AIChat/AIChat.cjs +1 -1
  11. package/dist/components/AIChat/AIChat.cjs.map +1 -1
  12. package/dist/components/AIChat/AIChat.js +1 -1
  13. package/dist/components/AIChat/AIChat.js.map +1 -1
  14. package/dist/components/AIChat/AIChatTurn.cjs +1 -1
  15. package/dist/components/AIChat/AIChatTurn.cjs.map +1 -1
  16. package/dist/components/AIChat/AIChatTurn.js +1 -1
  17. package/dist/components/AIChat/AIChatTurn.js.map +1 -1
  18. package/dist/components/AppBar/AppBar.module.cjs.map +1 -1
  19. package/dist/components/AppBar/AppBar.module.js.map +1 -1
  20. package/dist/components/AppBar/use-sticky-body-warning.cjs +1 -1
  21. package/dist/components/AppBar/use-sticky-body-warning.cjs.map +1 -1
  22. package/dist/components/AppBar/use-sticky-body-warning.js +1 -1
  23. package/dist/components/AppBar/use-sticky-body-warning.js.map +1 -1
  24. package/dist/components/AudioPlayer/AudioPlayer.cjs +1 -1
  25. package/dist/components/AudioPlayer/AudioPlayer.cjs.map +1 -1
  26. package/dist/components/AudioPlayer/AudioPlayer.js +2 -2
  27. package/dist/components/AudioPlayer/AudioPlayer.js.map +1 -1
  28. package/dist/components/AudioRecorder/AudioRecorder.cjs +1 -1
  29. package/dist/components/AudioRecorder/AudioRecorder.cjs.map +1 -1
  30. package/dist/components/AudioRecorder/AudioRecorder.js +1 -1
  31. package/dist/components/AudioRecorder/AudioRecorder.js.map +1 -1
  32. package/dist/components/Chat/Chat.cjs +1 -1
  33. package/dist/components/Chat/Chat.cjs.map +1 -1
  34. package/dist/components/Chat/Chat.js +1 -1
  35. package/dist/components/Chat/Chat.js.map +1 -1
  36. package/dist/components/FilterBar/FilterBar.cjs +1 -1
  37. package/dist/components/FilterBar/FilterBar.cjs.map +1 -1
  38. package/dist/components/FilterBar/FilterBar.js +1 -1
  39. package/dist/components/FilterBar/FilterBar.js.map +1 -1
  40. package/dist/components/FilterBar/filter-apply.cjs +1 -1
  41. package/dist/components/FilterBar/filter-apply.cjs.map +1 -1
  42. package/dist/components/FilterBar/filter-apply.js +1 -1
  43. package/dist/components/FilterBar/filter-apply.js.map +1 -1
  44. package/dist/components/ImageCropper/ImageCropper.cjs +1 -1
  45. package/dist/components/ImageCropper/ImageCropper.cjs.map +1 -1
  46. package/dist/components/ImageCropper/ImageCropper.js +1 -1
  47. package/dist/components/ImageCropper/ImageCropper.js.map +1 -1
  48. package/dist/components/Scheduler/Scheduler.module.cjs.map +1 -1
  49. package/dist/components/Scheduler/Scheduler.module.js.map +1 -1
  50. package/dist/components/VideoPlayer/VideoPlayer.cjs +1 -1
  51. package/dist/components/VideoPlayer/VideoPlayer.cjs.map +1 -1
  52. package/dist/components/VideoPlayer/VideoPlayer.js +2 -2
  53. package/dist/components/VideoPlayer/VideoPlayer.js.map +1 -1
  54. package/dist/components/VirtualTable/VirtualTable.cjs +1 -1
  55. package/dist/components/VirtualTable/VirtualTable.cjs.map +1 -1
  56. package/dist/components/VirtualTable/VirtualTable.js +1 -1
  57. package/dist/components/VirtualTable/VirtualTable.js.map +1 -1
  58. package/dist/feature-flags/growthbook-adapter.cjs +1 -1
  59. package/dist/feature-flags/growthbook-adapter.cjs.map +1 -1
  60. package/dist/feature-flags/growthbook-adapter.js +1 -1
  61. package/dist/feature-flags/growthbook-adapter.js.map +1 -1
  62. package/dist/hooks/use-focus-trap.cjs +1 -1
  63. package/dist/hooks/use-focus-trap.cjs.map +1 -1
  64. package/dist/hooks/use-focus-trap.js +1 -1
  65. package/dist/hooks/use-focus-trap.js.map +1 -1
  66. package/dist/hooks/use-push-to-talk.cjs +1 -1
  67. package/dist/hooks/use-push-to-talk.cjs.map +1 -1
  68. package/dist/hooks/use-push-to-talk.js +2 -2
  69. package/dist/hooks/use-push-to-talk.js.map +1 -1
  70. package/dist/http/resumable-upload.cjs +1 -1
  71. package/dist/http/resumable-upload.cjs.map +1 -1
  72. package/dist/http/resumable-upload.js +1 -1
  73. package/dist/http/resumable-upload.js.map +1 -1
  74. package/dist/icons/generated/aliases.cjs +1 -1
  75. package/dist/icons/generated/aliases.cjs.map +1 -1
  76. package/dist/icons/generated/aliases.js +1 -0
  77. package/dist/icons/generated/aliases.js.map +1 -1
  78. package/dist/icons/generated/icon-names.cjs +1 -1
  79. package/dist/icons/generated/icon-names.cjs.map +1 -1
  80. package/dist/icons/generated/icon-names.js +1 -1
  81. package/dist/icons/generated/icon-names.js.map +1 -1
  82. package/dist/icons/generated/loaders.cjs +1 -1
  83. package/dist/icons/generated/loaders.cjs.map +1 -1
  84. package/dist/icons/generated/loaders.js +48 -42
  85. package/dist/icons/generated/loaders.js.map +1 -1
  86. package/dist/icons/generated/shard-02.cjs +1 -1
  87. package/dist/icons/generated/shard-02.cjs.map +1 -1
  88. package/dist/icons/generated/shard-02.js +20 -20
  89. package/dist/icons/generated/shard-02.js.map +1 -1
  90. package/dist/icons/generated/shard-03.cjs +1 -1
  91. package/dist/icons/generated/shard-03.cjs.map +1 -1
  92. package/dist/icons/generated/shard-03.js +41 -41
  93. package/dist/icons/generated/shard-03.js.map +1 -1
  94. package/dist/icons/generated/shard-04.cjs +1 -1
  95. package/dist/icons/generated/shard-04.cjs.map +1 -1
  96. package/dist/icons/generated/shard-04.js +41 -41
  97. package/dist/icons/generated/shard-04.js.map +1 -1
  98. package/dist/icons/generated/shard-05.cjs +1 -1
  99. package/dist/icons/generated/shard-05.cjs.map +1 -1
  100. package/dist/icons/generated/shard-05.js +41 -41
  101. package/dist/icons/generated/shard-05.js.map +1 -1
  102. package/dist/icons/generated/shard-06.cjs +1 -1
  103. package/dist/icons/generated/shard-06.cjs.map +1 -1
  104. package/dist/icons/generated/shard-06.js +41 -41
  105. package/dist/icons/generated/shard-06.js.map +1 -1
  106. package/dist/icons/generated/shard-07.cjs +1 -1
  107. package/dist/icons/generated/shard-07.cjs.map +1 -1
  108. package/dist/icons/generated/shard-07.js +41 -41
  109. package/dist/icons/generated/shard-07.js.map +1 -1
  110. package/dist/icons/generated/shard-08.cjs +1 -1
  111. package/dist/icons/generated/shard-08.cjs.map +1 -1
  112. package/dist/icons/generated/shard-08.js +41 -41
  113. package/dist/icons/generated/shard-08.js.map +1 -1
  114. package/dist/icons/generated/shard-09.cjs +1 -1
  115. package/dist/icons/generated/shard-09.cjs.map +1 -1
  116. package/dist/icons/generated/shard-09.js +41 -41
  117. package/dist/icons/generated/shard-09.js.map +1 -1
  118. package/dist/icons/generated/shard-10.cjs +1 -1
  119. package/dist/icons/generated/shard-10.cjs.map +1 -1
  120. package/dist/icons/generated/shard-10.js +41 -41
  121. package/dist/icons/generated/shard-10.js.map +1 -1
  122. package/dist/icons/generated/shard-11.cjs +1 -1
  123. package/dist/icons/generated/shard-11.cjs.map +1 -1
  124. package/dist/icons/generated/shard-11.js +41 -41
  125. package/dist/icons/generated/shard-11.js.map +1 -1
  126. package/dist/icons/generated/shard-12.cjs +1 -1
  127. package/dist/icons/generated/shard-12.cjs.map +1 -1
  128. package/dist/icons/generated/shard-12.js +41 -41
  129. package/dist/icons/generated/shard-12.js.map +1 -1
  130. package/dist/icons/generated/shard-13.cjs +1 -1
  131. package/dist/icons/generated/shard-13.cjs.map +1 -1
  132. package/dist/icons/generated/shard-13.js +41 -41
  133. package/dist/icons/generated/shard-13.js.map +1 -1
  134. package/dist/icons/generated/shard-14.cjs +1 -1
  135. package/dist/icons/generated/shard-14.cjs.map +1 -1
  136. package/dist/icons/generated/shard-14.js +41 -41
  137. package/dist/icons/generated/shard-14.js.map +1 -1
  138. package/dist/icons/generated/shard-15.cjs +1 -1
  139. package/dist/icons/generated/shard-15.cjs.map +1 -1
  140. package/dist/icons/generated/shard-15.js +41 -41
  141. package/dist/icons/generated/shard-15.js.map +1 -1
  142. package/dist/icons/generated/shard-16.cjs +1 -1
  143. package/dist/icons/generated/shard-16.cjs.map +1 -1
  144. package/dist/icons/generated/shard-16.js +41 -41
  145. package/dist/icons/generated/shard-16.js.map +1 -1
  146. package/dist/icons/generated/shard-17.cjs +1 -1
  147. package/dist/icons/generated/shard-17.cjs.map +1 -1
  148. package/dist/icons/generated/shard-17.js +41 -41
  149. package/dist/icons/generated/shard-17.js.map +1 -1
  150. package/dist/icons/generated/shard-18.cjs +1 -1
  151. package/dist/icons/generated/shard-18.cjs.map +1 -1
  152. package/dist/icons/generated/shard-18.js +41 -41
  153. package/dist/icons/generated/shard-18.js.map +1 -1
  154. package/dist/icons/generated/shard-19.cjs +1 -1
  155. package/dist/icons/generated/shard-19.cjs.map +1 -1
  156. package/dist/icons/generated/shard-19.js +41 -41
  157. package/dist/icons/generated/shard-19.js.map +1 -1
  158. package/dist/icons/generated/shard-20.cjs +1 -1
  159. package/dist/icons/generated/shard-20.cjs.map +1 -1
  160. package/dist/icons/generated/shard-20.js +41 -41
  161. package/dist/icons/generated/shard-20.js.map +1 -1
  162. package/dist/icons/generated/shard-21.cjs +1 -1
  163. package/dist/icons/generated/shard-21.cjs.map +1 -1
  164. package/dist/icons/generated/shard-21.js +41 -41
  165. package/dist/icons/generated/shard-21.js.map +1 -1
  166. package/dist/icons/generated/shard-22.cjs +1 -1
  167. package/dist/icons/generated/shard-22.cjs.map +1 -1
  168. package/dist/icons/generated/shard-22.js +41 -41
  169. package/dist/icons/generated/shard-22.js.map +1 -1
  170. package/dist/icons/generated/shard-23.cjs +1 -1
  171. package/dist/icons/generated/shard-23.cjs.map +1 -1
  172. package/dist/icons/generated/shard-23.js +41 -41
  173. package/dist/icons/generated/shard-23.js.map +1 -1
  174. package/dist/icons/generated/shard-24.cjs +1 -1
  175. package/dist/icons/generated/shard-24.cjs.map +1 -1
  176. package/dist/icons/generated/shard-24.js +41 -41
  177. package/dist/icons/generated/shard-24.js.map +1 -1
  178. package/dist/icons/generated/shard-25.cjs +1 -1
  179. package/dist/icons/generated/shard-25.cjs.map +1 -1
  180. package/dist/icons/generated/shard-25.js +41 -41
  181. package/dist/icons/generated/shard-25.js.map +1 -1
  182. package/dist/icons/generated/shard-26.cjs +1 -1
  183. package/dist/icons/generated/shard-26.cjs.map +1 -1
  184. package/dist/icons/generated/shard-26.js +41 -41
  185. package/dist/icons/generated/shard-26.js.map +1 -1
  186. package/dist/icons/generated/shard-27.cjs +1 -1
  187. package/dist/icons/generated/shard-27.cjs.map +1 -1
  188. package/dist/icons/generated/shard-27.js +41 -41
  189. package/dist/icons/generated/shard-27.js.map +1 -1
  190. package/dist/icons/generated/shard-28.cjs +1 -1
  191. package/dist/icons/generated/shard-28.cjs.map +1 -1
  192. package/dist/icons/generated/shard-28.js +41 -41
  193. package/dist/icons/generated/shard-28.js.map +1 -1
  194. package/dist/icons/generated/shard-29.cjs +1 -1
  195. package/dist/icons/generated/shard-29.cjs.map +1 -1
  196. package/dist/icons/generated/shard-29.js +41 -41
  197. package/dist/icons/generated/shard-29.js.map +1 -1
  198. package/dist/icons/generated/shard-30.cjs +1 -1
  199. package/dist/icons/generated/shard-30.cjs.map +1 -1
  200. package/dist/icons/generated/shard-30.js +41 -41
  201. package/dist/icons/generated/shard-30.js.map +1 -1
  202. package/dist/icons/generated/shard-31.cjs +1 -1
  203. package/dist/icons/generated/shard-31.cjs.map +1 -1
  204. package/dist/icons/generated/shard-31.js +41 -41
  205. package/dist/icons/generated/shard-31.js.map +1 -1
  206. package/dist/icons/generated/shard-32.cjs +1 -1
  207. package/dist/icons/generated/shard-32.cjs.map +1 -1
  208. package/dist/icons/generated/shard-32.js +41 -41
  209. package/dist/icons/generated/shard-32.js.map +1 -1
  210. package/dist/icons/generated/shard-33.cjs +1 -1
  211. package/dist/icons/generated/shard-33.cjs.map +1 -1
  212. package/dist/icons/generated/shard-33.js +41 -41
  213. package/dist/icons/generated/shard-33.js.map +1 -1
  214. package/dist/icons/generated/shard-34.cjs +1 -1
  215. package/dist/icons/generated/shard-34.cjs.map +1 -1
  216. package/dist/icons/generated/shard-34.js +41 -41
  217. package/dist/icons/generated/shard-34.js.map +1 -1
  218. package/dist/icons/generated/shard-35.cjs +1 -1
  219. package/dist/icons/generated/shard-35.cjs.map +1 -1
  220. package/dist/icons/generated/shard-35.js +41 -41
  221. package/dist/icons/generated/shard-35.js.map +1 -1
  222. package/dist/icons/generated/shard-36.cjs +1 -1
  223. package/dist/icons/generated/shard-36.cjs.map +1 -1
  224. package/dist/icons/generated/shard-36.js +41 -41
  225. package/dist/icons/generated/shard-36.js.map +1 -1
  226. package/dist/icons/generated/shard-37.cjs +1 -1
  227. package/dist/icons/generated/shard-37.cjs.map +1 -1
  228. package/dist/icons/generated/shard-37.js +41 -41
  229. package/dist/icons/generated/shard-37.js.map +1 -1
  230. package/dist/icons/generated/shard-38.cjs +1 -1
  231. package/dist/icons/generated/shard-38.cjs.map +1 -1
  232. package/dist/icons/generated/shard-38.js +41 -41
  233. package/dist/icons/generated/shard-38.js.map +1 -1
  234. package/dist/icons/generated/shard-39.cjs +1 -1
  235. package/dist/icons/generated/shard-39.cjs.map +1 -1
  236. package/dist/icons/generated/shard-39.js +41 -41
  237. package/dist/icons/generated/shard-39.js.map +1 -1
  238. package/dist/icons/generated/shard-40.cjs +1 -1
  239. package/dist/icons/generated/shard-40.cjs.map +1 -1
  240. package/dist/icons/generated/shard-40.js +41 -41
  241. package/dist/icons/generated/shard-40.js.map +1 -1
  242. package/dist/icons/generated/shard-41.cjs +1 -1
  243. package/dist/icons/generated/shard-41.cjs.map +1 -1
  244. package/dist/icons/generated/shard-41.js +41 -41
  245. package/dist/icons/generated/shard-41.js.map +1 -1
  246. package/dist/icons/generated/shard-42.cjs +1 -1
  247. package/dist/icons/generated/shard-42.cjs.map +1 -1
  248. package/dist/icons/generated/shard-42.js +41 -41
  249. package/dist/icons/generated/shard-42.js.map +1 -1
  250. package/dist/icons/generated/shard-43.cjs +1 -1
  251. package/dist/icons/generated/shard-43.cjs.map +1 -1
  252. package/dist/icons/generated/shard-43.js +41 -41
  253. package/dist/icons/generated/shard-43.js.map +1 -1
  254. package/dist/icons/generated/shard-44.cjs +1 -1
  255. package/dist/icons/generated/shard-44.cjs.map +1 -1
  256. package/dist/icons/generated/shard-44.js +43 -10
  257. package/dist/icons/generated/shard-44.js.map +1 -1
  258. package/dist/icons/generated/shard-45.cjs +2 -0
  259. package/dist/icons/generated/shard-45.cjs.map +1 -0
  260. package/dist/icons/generated/shard-45.js +15 -0
  261. package/dist/icons/generated/shard-45.js.map +1 -0
  262. package/dist/icons/material-symbols.cjs +1 -1
  263. package/dist/icons/material-symbols.cjs.map +1 -1
  264. package/dist/icons/material-symbols.js +3 -3
  265. package/dist/icons/material-symbols.js.map +1 -1
  266. package/dist/icons.d.ts +4 -4
  267. package/dist/query/foreign-client-warning.cjs +1 -1
  268. package/dist/query/foreign-client-warning.cjs.map +1 -1
  269. package/dist/query/foreign-client-warning.js +1 -1
  270. package/dist/query/foreign-client-warning.js.map +1 -1
  271. package/dist/styles/AppBar.css +1 -1
  272. package/dist/styles/Scheduler.css +2 -2
  273. package/dist/styles/core.css +1 -1
  274. package/dist/styles/layout.css +2 -2
  275. package/dist/styles/navigation.css +1 -1
  276. package/dist/styles.css +1 -1
  277. package/dist/tempest-react-sdk.cjs +1 -1
  278. package/dist/tempest-react-sdk.d.ts +175 -12
  279. package/dist/tempest-react-sdk.js +33 -33
  280. package/dist/utils/json-frame.cjs +1 -1
  281. package/dist/utils/json-frame.cjs.map +1 -1
  282. package/dist/utils/json-frame.js +1 -1
  283. package/dist/utils/json-frame.js.map +1 -1
  284. package/dist/vision/core/providers.cjs +1 -1
  285. package/dist/vision/core/providers.cjs.map +1 -1
  286. package/dist/vision/core/providers.js +22 -3
  287. package/dist/vision/core/providers.js.map +1 -1
  288. package/dist/vision/core/session.cjs +1 -1
  289. package/dist/vision/core/session.cjs.map +1 -1
  290. package/dist/vision/core/session.js +22 -15
  291. package/dist/vision/core/session.js.map +1 -1
  292. package/dist/vision/fusion.cjs.map +1 -1
  293. package/dist/vision/fusion.js.map +1 -1
  294. package/dist/vision/index.cjs +1 -1
  295. package/dist/vision/index.cjs.map +1 -1
  296. package/dist/vision/index.js +17 -16
  297. package/dist/vision/index.js.map +1 -1
  298. package/dist/vision/normalization.cjs +2 -0
  299. package/dist/vision/normalization.cjs.map +1 -0
  300. package/dist/vision/normalization.js +49 -0
  301. package/dist/vision/normalization.js.map +1 -0
  302. package/dist/vision/results.cjs +1 -1
  303. package/dist/vision/results.cjs.map +1 -1
  304. package/dist/vision/results.js +8 -2
  305. package/dist/vision/results.js.map +1 -1
  306. package/dist/vision/tasks/classifier.cjs +1 -1
  307. package/dist/vision/tasks/classifier.cjs.map +1 -1
  308. package/dist/vision/tasks/classifier.js +36 -32
  309. package/dist/vision/tasks/classifier.js.map +1 -1
  310. package/dist/vision.cjs +1 -1
  311. package/dist/vision.d.ts +218 -13
  312. package/dist/vision.js +19 -18
  313. package/dist/vite/tempest-pwa-manifest.cjs +1 -1
  314. package/dist/vite/tempest-pwa-manifest.cjs.map +1 -1
  315. package/dist/vite/tempest-pwa-manifest.js +1 -1
  316. package/dist/vite/tempest-pwa-manifest.js.map +1 -1
  317. package/dist/webrtc/link-stats.cjs +1 -1
  318. package/dist/webrtc/link-stats.cjs.map +1 -1
  319. package/dist/webrtc/link-stats.js +134 -44
  320. package/dist/webrtc/link-stats.js.map +1 -1
  321. package/dist/webrtc/mesh-quality.cjs +1 -1
  322. package/dist/webrtc/mesh-quality.cjs.map +1 -1
  323. package/dist/webrtc/mesh-quality.js +8 -2
  324. package/dist/webrtc/mesh-quality.js.map +1 -1
  325. package/dist/webrtc/peer-link.cjs +1 -1
  326. package/dist/webrtc/peer-link.cjs.map +1 -1
  327. package/dist/webrtc/peer-link.js +1 -1
  328. package/dist/webrtc/peer-link.js.map +1 -1
  329. package/dist/webrtc/peer-mesh.cjs +1 -1
  330. package/dist/webrtc/peer-mesh.cjs.map +1 -1
  331. package/dist/webrtc/peer-mesh.js +86 -64
  332. package/dist/webrtc/peer-mesh.js.map +1 -1
  333. package/dist/ws/create-web-socket.cjs +1 -1
  334. package/dist/ws/create-web-socket.cjs.map +1 -1
  335. package/dist/ws/create-web-socket.js +1 -1
  336. package/dist/ws/create-web-socket.js.map +1 -1
  337. package/package.json +1 -1
@@ -3,7 +3,7 @@ import { formatDateForInput as t } from "../../utils/format.js";
3
3
  //#region src/components/FilterBar/filter-apply.ts
4
4
  var n = /^\d{4}-\d{2}-\d{2}$/, r = new Intl.Collator(void 0, { numeric: !0 });
5
5
  function i(e, t) {
6
- if (!(typeof e != "object" || !e)) return e[t];
6
+ if (typeof e == "object" && e) return e[t];
7
7
  }
8
8
  function a(e) {
9
9
  return e instanceof Date ? t(e) || null : typeof e != "string" || e.trim() === "" ? null : t(e) || null;
@@ -1 +1 @@
1
- {"version":3,"file":"filter-apply.js","names":[],"sources":["../../../src/components/FilterBar/filter-apply.ts"],"sourcesContent":["// The other half of the filter model: evaluating a `Filter[]` instead of only\n// describing it. `FilterBar` produces filters, `applyFilters` runs them over an\n// in-memory list, and `filtersToQueryParams` (filter-query.ts) hands the same set\n// to a paginated backend. Without these two the model stops one step short of\n// useful and every app writes the eleven operator branches again.\n\nimport { formatDateForInput } from \"@/utils/format\";\nimport type { Filter, FilterOperator } from \"./filter-model\";\nimport { isComplete } from \"./filter-model\";\n\n/** Matches a plain `yyyy-mm-dd`, the shape `<input type=\"date\">` produces. */\nconst DATE_ONLY = /^\\d{4}-\\d{2}-\\d{2}$/;\n\n/**\n * One collator for every text comparison in this module.\n *\n * `localeCompare(value, undefined, { numeric: true })` builds a collator on each\n * call — passing an options bag opts out of the engine's cached-default fast\n * path — and this comparison runs once per row per filter. Measured at 200k\n * comparisons: 453 ms through `localeCompare` against 25 ms through a hoisted\n * collator, i.e. ~23 ms of main thread per keystroke on a 10k-row list.\n */\nconst TEXT_COLLATOR = new Intl.Collator(undefined, { numeric: true });\n\n/**\n * Read a property off a row without asserting the row's shape.\n *\n * `Filter.field` is a string chosen by the app's field list, so it cannot be a\n * `keyof T`; the lookup goes through an index signature and a missing property\n * yields `undefined`, which the operators treat as an empty value.\n *\n * @param item - The row being tested.\n * @param field - Property name from the filter.\n * @returns The property value, or `undefined` when the row has no such key.\n */\nfunction readField(item: unknown, field: string): unknown {\n if (item == null || typeof item !== \"object\") return undefined;\n return (item as Record<string, unknown>)[field];\n}\n\n/**\n * Local `yyyy-mm-dd` for a value that represents a date, or `null`.\n *\n * Delegates the formatting to {@link formatDateForInput}, which owns the rule\n * that the key is built from the local calendar parts rather than `toISOString`.\n * This adds only the narrowing from `unknown` and maps \"not a date\" to `null`\n * instead of to the empty string a date input wants.\n *\n * @param value - A `Date`, a date-ish string, or anything else.\n * @returns The day key, or `null` when the value does not denote a date.\n */\nfunction dayKey(value: unknown): string | null {\n if (value instanceof Date) return formatDateForInput(value) || null;\n if (typeof value !== \"string\" || value.trim() === \"\") return null;\n return formatDateForInput(value) || null;\n}\n\n/**\n * Compare a row value against a filter value, in the row value's own type.\n *\n * The filter always carries strings — it comes from form inputs and from the\n * URL — while the row carries whatever the API returned. Comparing them as text\n * gets the two common cases wrong: `10` would sort before `9`, and a date would\n * be compared by however it happens to be formatted. So the row value picks the\n * comparison, and the filter value is coerced into it.\n *\n * Dates compare by **day**, not by instant: a row stamped `2026-03-05T13:00:00Z`\n * is `>= 2026-03-05`, which is what the person picking a date in the UI means.\n *\n * @param left - The row value.\n * @param right - The raw filter value.\n * @returns Negative, zero or positive, or `null` when the two cannot be compared.\n */\nfunction compare(left: unknown, right: string): number | null {\n if (left == null) return null;\n\n if (typeof left === \"number\") {\n const parsed = Number(right);\n return Number.isNaN(parsed) ? null : left - parsed;\n }\n\n if (typeof left === \"boolean\") {\n const parsed = right === \"true\" ? true : right === \"false\" ? false : null;\n return parsed === null ? null : Number(left) - Number(parsed);\n }\n\n if (DATE_ONLY.test(right)) {\n const key = dayKey(left);\n return key === null ? null : key.localeCompare(right);\n }\n\n return TEXT_COLLATOR.compare(String(left), right);\n}\n\n/**\n * Equality in the row value's type, falling back to exact text.\n *\n * Case-sensitive on purpose: `eq` maps to a plain `WHERE column = value` on the\n * server side, so a case-insensitive client would quietly disagree with the\n * backend for the same filter. `contains` is the case-insensitive operator, and\n * it is also the default one for text fields, so the friendly behaviour is what\n * people get without asking.\n *\n * Identical strings take a fast path out, since the row value is text in the\n * common case and the collator is the expensive part.\n *\n * @param left - The row value.\n * @param right - The raw filter value.\n * @returns Whether the two are equal.\n */\nfunction equals(left: unknown, right: string): boolean {\n if (left === right) return true;\n const result = compare(left, right);\n if (result !== null) return result === 0;\n return String(left ?? \"\") === right;\n}\n\n/**\n * Is this row value empty?\n *\n * Empty means absent, blank text or an empty list — never falsy. `0` and `false`\n * are values somebody chose, and a filter that hid them would be reporting the\n * wrong count on every dashboard that tracks zeroes.\n *\n * @param value - The row value.\n * @returns Whether the value counts as empty.\n */\nfunction isEmptyValue(value: unknown): boolean {\n if (value == null) return true;\n if (typeof value === \"string\") return value.trim() === \"\";\n if (Array.isArray(value)) return value.length === 0;\n return false;\n}\n\n/**\n * The filter's value as a list, whatever arity the operator uses.\n *\n * @param filter - The filter to read.\n * @returns Its values, trimmed of nothing — a leading space may be meaningful text.\n */\nfunction valuesOf(filter: Filter): string[] {\n if (filter.value === undefined) return [];\n return Array.isArray(filter.value) ? [...filter.value] : [String(filter.value)];\n}\n\n/**\n * Evaluate one operator against one row value.\n *\n * @param operator - The comparison to make.\n * @param left - The row value.\n * @param values - The filter values (one, two for `between`, many for `in`).\n * @returns Whether the row value satisfies the operator.\n */\nfunction matchesOperator(operator: FilterOperator, left: unknown, values: string[]): boolean {\n switch (operator) {\n case \"empty\":\n return isEmptyValue(left);\n case \"notEmpty\":\n return !isEmptyValue(left);\n case \"eq\":\n return equals(left, values[0] ?? \"\");\n case \"ne\":\n return !equals(left, values[0] ?? \"\");\n case \"contains\":\n return String(left ?? \"\")\n .toLowerCase()\n .includes((values[0] ?? \"\").toLowerCase());\n case \"in\":\n return values.some((value) => equals(left, value));\n case \"between\": {\n const [first = \"\", second = \"\"] = values;\n const low = compare(left, first);\n const high = compare(left, second);\n if (low === null || high === null) return false;\n return low >= 0 && high <= 0;\n }\n default: {\n const result = compare(left, values[0] ?? \"\");\n if (result === null) return false;\n if (operator === \"gt\") return result > 0;\n if (operator === \"gte\") return result >= 0;\n if (operator === \"lt\") return result < 0;\n return result <= 0;\n }\n }\n}\n\n/**\n * Order the two values of a `between` so the range is never empty by accident.\n *\n * A person who picks the later date first means the range between the two dates,\n * not \"no rows\". The server-side `BETWEEN` needs `(lo, hi)` in order too, which\n * is why the normalisation lives here and is shared by `filtersToQueryParams`.\n *\n * @param values - The raw pair.\n * @returns The pair, ascending.\n */\nexport function orderRange(values: readonly string[]): string[] {\n const [first = \"\", second = \"\"] = values;\n if (DATE_ONLY.test(first) && DATE_ONLY.test(second)) {\n return first <= second ? [first, second] : [second, first];\n }\n const low = Number(first);\n const high = Number(second);\n if (!Number.isNaN(low) && !Number.isNaN(high)) {\n return low <= high ? [first, second] : [second, first];\n }\n return TEXT_COLLATOR.compare(first, second) <= 0 ? [first, second] : [second, first];\n}\n\n/**\n * Run a filter set over an in-memory list.\n *\n * Closes the loop `FilterBar` opens: the bar produces `Filter[]`, this applies\n * them. Filters combine with `AND`, matching the flat model the bar builds, and\n * an incomplete filter is skipped rather than treated as a match of nothing — a\n * half-filled form should not empty the table underneath it.\n *\n * Comparison follows the row's type, not the filter's: numbers compare\n * numerically, dates compare by day, and everything else compares as text with\n * `numeric: true` so `\"item 2\"` lands before `\"item 10\"`.\n *\n * A few behaviours differ from the SQL the server-side twin produces, and the\n * difference is deliberate rather than accidental:\n *\n * - `ne` matches rows whose value is absent. In SQL, `column <> 'x'` is `NULL`\n * for a `NULL` column and the row drops out. Here \"is not paid\" shows the rows\n * with no status at all, which is what the chip claims.\n * - `empty` matches `NULL`, blank text and empty lists; `__isnull` on the server\n * only matches `NULL`. A column that stores `\"\"` instead of `NULL` is where\n * the two disagree.\n *\n * @example\n * const visible = applyFilters(orders, filters);\n *\n * Each filter's values are normalised once, before the scan, rather than inside\n * the per-row predicate: the arity, the `between` ordering and the value array\n * depend only on the filter, so deriving them per row multiplied that work by\n * the row count. `empty`/`notEmpty` ignore their values entirely, which is why\n * the prepared shape does not need to distinguish them.\n *\n * @param items - The full list.\n * @param filters - Applied filters; incomplete ones are ignored.\n * @returns A new array with the rows that satisfy every complete filter.\n */\nexport function applyFilters<T>(items: readonly T[], filters: readonly Filter[]): T[] {\n const active = filters.filter(isComplete).map((filter) => ({\n field: filter.field,\n operator: filter.operator,\n values: filter.operator === \"between\" ? orderRange(valuesOf(filter)) : valuesOf(filter),\n }));\n if (active.length === 0) return [...items];\n\n return items.filter((item) =>\n active.every(({ field, operator, values }) =>\n matchesOperator(operator, readField(item, field), values),\n ),\n );\n}\n"],"mappings":";;;AAWA,IAAM,IAAY,uBAWZ,IAAgB,IAAI,KAAK,SAAS,KAAA,GAAW,EAAE,SAAS,GAAK,CAAC;AAapE,SAAS,EAAU,GAAe,GAAwB;CAClD,MAAgB,OAAO,KAAS,aAAhC,IACJ,OAAQ,EAAiC;AAC7C;AAaA,SAAS,EAAO,GAA+B;CAG3C,OAFI,aAAiB,OAAa,EAAmB,CAAK,KAAK,OAC3D,OAAO,KAAU,YAAY,EAAM,KAAK,MAAM,KAAW,OACtD,EAAmB,CAAK,KAAK;AACxC;AAkBA,SAAS,EAAQ,GAAe,GAA8B;CAC1D,IAAI,KAAQ,MAAM,OAAO;CAEzB,IAAI,OAAO,KAAS,UAAU;EAC1B,IAAM,IAAS,OAAO,CAAK;EAC3B,OAAO,OAAO,MAAM,CAA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M,CAAK,GAAG,CAAM,CAC5D,CACJ;AACJ"}
1
+ {"version":3,"file":"filter-apply.js","names":[],"sources":["../../../src/components/FilterBar/filter-apply.ts"],"sourcesContent":["// The other half of the filter model: evaluating a `Filter[]` instead of only\n// describing it. `FilterBar` produces filters, `applyFilters` runs them over an\n// in-memory list, and `filtersToQueryParams` (filter-query.ts) hands the same set\n// to a paginated backend. Without these two the model stops one step short of\n// useful and every app writes the eleven operator branches again.\n\nimport { formatDateForInput } from \"@/utils/format\";\nimport type { Filter, FilterOperator } from \"./filter-model\";\nimport { isComplete } from \"./filter-model\";\n\n/** Matches a plain `yyyy-mm-dd`, the shape `<input type=\"date\">` produces. */\nconst DATE_ONLY = /^\\d{4}-\\d{2}-\\d{2}$/;\n\n/**\n * One collator for every text comparison in this module.\n *\n * `localeCompare(value, undefined, { numeric: true })` builds a collator on each\n * call — passing an options bag opts out of the engine's cached-default fast\n * path — and this comparison runs once per row per filter. Measured at 200k\n * comparisons: 453 ms through `localeCompare` against 25 ms through a hoisted\n * collator, i.e. ~23 ms of main thread per keystroke on a 10k-row list.\n */\nconst TEXT_COLLATOR = new Intl.Collator(undefined, { numeric: true });\n\n/**\n * Read a property off a row without asserting the row's shape.\n *\n * `Filter.field` is a string chosen by the app's field list, so it cannot be a\n * `keyof T`; the lookup goes through an index signature and a missing property\n * yields `undefined`, which the operators treat as an empty value.\n *\n * @param item - The row being tested.\n * @param field - Property name from the filter.\n * @returns The property value, or `undefined` when the row has no such key.\n */\nfunction readField(item: unknown, field: string): unknown {\n if (item == null || typeof item !== \"object\") return undefined;\n return (item as Record<string, unknown>)[field];\n}\n\n/**\n * Local `yyyy-mm-dd` for a value that represents a date, or `null`.\n *\n * Delegates the formatting to {@link formatDateForInput}, which owns the rule\n * that the key is built from the local calendar parts rather than `toISOString`.\n * This adds only the narrowing from `unknown` and maps \"not a date\" to `null`\n * instead of to the empty string a date input wants.\n *\n * @param value - A `Date`, a date-ish string, or anything else.\n * @returns The day key, or `null` when the value does not denote a date.\n */\nfunction dayKey(value: unknown): string | null {\n if (value instanceof Date) return formatDateForInput(value) || null;\n if (typeof value !== \"string\" || value.trim() === \"\") return null;\n return formatDateForInput(value) || null;\n}\n\n/**\n * Compare a row value against a filter value, in the row value's own type.\n *\n * The filter always carries strings — it comes from form inputs and from the\n * URL — while the row carries whatever the API returned. Comparing them as text\n * gets the two common cases wrong: `10` would sort before `9`, and a date would\n * be compared by however it happens to be formatted. So the row value picks the\n * comparison, and the filter value is coerced into it.\n *\n * Dates compare by **day**, not by instant: a row stamped `2026-03-05T13:00:00Z`\n * is `>= 2026-03-05`, which is what the person picking a date in the UI means.\n *\n * @param left - The row value.\n * @param right - The raw filter value.\n * @returns Negative, zero or positive, or `null` when the two cannot be compared.\n */\nfunction compare(left: unknown, right: string): number | null {\n if (left == null) return null;\n\n if (typeof left === \"number\") {\n const parsed = Number(right);\n return Number.isNaN(parsed) ? null : left - parsed;\n }\n\n if (typeof left === \"boolean\") {\n const parsed = right === \"true\" ? true : right === \"false\" ? false : null;\n return parsed === null ? null : Number(left) - Number(parsed);\n }\n\n if (DATE_ONLY.test(right)) {\n const key = dayKey(left);\n return key === null ? null : key.localeCompare(right);\n }\n\n return TEXT_COLLATOR.compare(String(left), right);\n}\n\n/**\n * Equality in the row value's type, falling back to exact text.\n *\n * Case-sensitive on purpose: `eq` maps to a plain `WHERE column = value` on the\n * server side, so a case-insensitive client would quietly disagree with the\n * backend for the same filter. `contains` is the case-insensitive operator, and\n * it is also the default one for text fields, so the friendly behaviour is what\n * people get without asking.\n *\n * Identical strings take a fast path out, since the row value is text in the\n * common case and the collator is the expensive part.\n *\n * @param left - The row value.\n * @param right - The raw filter value.\n * @returns Whether the two are equal.\n */\nfunction equals(left: unknown, right: string): boolean {\n if (left === right) return true;\n const result = compare(left, right);\n if (result !== null) return result === 0;\n return String(left ?? \"\") === right;\n}\n\n/**\n * Is this row value empty?\n *\n * Empty means absent, blank text or an empty list — never falsy. `0` and `false`\n * are values somebody chose, and a filter that hid them would be reporting the\n * wrong count on every dashboard that tracks zeroes.\n *\n * @param value - The row value.\n * @returns Whether the value counts as empty.\n */\nfunction isEmptyValue(value: unknown): boolean {\n if (value == null) return true;\n if (typeof value === \"string\") return value.trim() === \"\";\n if (Array.isArray(value)) return value.length === 0;\n return false;\n}\n\n/**\n * The filter's value as a list, whatever arity the operator uses.\n *\n * @param filter - The filter to read.\n * @returns Its values, trimmed of nothing — a leading space may be meaningful text.\n */\nfunction valuesOf(filter: Filter): string[] {\n if (filter.value === undefined) return [];\n return Array.isArray(filter.value) ? [...filter.value] : [String(filter.value)];\n}\n\n/**\n * Evaluate one operator against one row value.\n *\n * @param operator - The comparison to make.\n * @param left - The row value.\n * @param values - The filter values (one, two for `between`, many for `in`).\n * @returns Whether the row value satisfies the operator.\n */\nfunction matchesOperator(operator: FilterOperator, left: unknown, values: string[]): boolean {\n switch (operator) {\n case \"empty\":\n return isEmptyValue(left);\n case \"notEmpty\":\n return !isEmptyValue(left);\n case \"eq\":\n return equals(left, values[0] ?? \"\");\n case \"ne\":\n return !equals(left, values[0] ?? \"\");\n case \"contains\":\n return String(left ?? \"\")\n .toLowerCase()\n .includes((values[0] ?? \"\").toLowerCase());\n case \"in\":\n return values.some((value) => equals(left, value));\n case \"between\": {\n const [first = \"\", second = \"\"] = values;\n const low = compare(left, first);\n const high = compare(left, second);\n if (low === null || high === null) return false;\n return low >= 0 && high <= 0;\n }\n default: {\n const result = compare(left, values[0] ?? \"\");\n if (result === null) return false;\n if (operator === \"gt\") return result > 0;\n if (operator === \"gte\") return result >= 0;\n if (operator === \"lt\") return result < 0;\n return result <= 0;\n }\n }\n}\n\n/**\n * Order the two values of a `between` so the range is never empty by accident.\n *\n * A person who picks the later date first means the range between the two dates,\n * not \"no rows\". The server-side `BETWEEN` needs `(lo, hi)` in order too, which\n * is why the normalisation lives here and is shared by `filtersToQueryParams`.\n *\n * @param values - The raw pair.\n * @returns The pair, ascending.\n */\nexport function orderRange(values: readonly string[]): string[] {\n const [first = \"\", second = \"\"] = values;\n if (DATE_ONLY.test(first) && DATE_ONLY.test(second)) {\n return first <= second ? [first, second] : [second, first];\n }\n const low = Number(first);\n const high = Number(second);\n if (!Number.isNaN(low) && !Number.isNaN(high)) {\n return low <= high ? [first, second] : [second, first];\n }\n return TEXT_COLLATOR.compare(first, second) <= 0 ? [first, second] : [second, first];\n}\n\n/**\n * Run a filter set over an in-memory list.\n *\n * Closes the loop `FilterBar` opens: the bar produces `Filter[]`, this applies\n * them. Filters combine with `AND`, matching the flat model the bar builds, and\n * an incomplete filter is skipped rather than treated as a match of nothing — a\n * half-filled form should not empty the table underneath it.\n *\n * Comparison follows the row's type, not the filter's: numbers compare\n * numerically, dates compare by day, and everything else compares as text with\n * `numeric: true` so `\"item 2\"` lands before `\"item 10\"`.\n *\n * A few behaviours differ from the SQL the server-side twin produces, and the\n * difference is deliberate rather than accidental:\n *\n * - `ne` matches rows whose value is absent. In SQL, `column <> 'x'` is `NULL`\n * for a `NULL` column and the row drops out. Here \"is not paid\" shows the rows\n * with no status at all, which is what the chip claims.\n * - `empty` matches `NULL`, blank text and empty lists; `__isnull` on the server\n * only matches `NULL`. A column that stores `\"\"` instead of `NULL` is where\n * the two disagree.\n *\n * @example\n * const visible = applyFilters(orders, filters);\n *\n * Each filter's values are normalised once, before the scan, rather than inside\n * the per-row predicate: the arity, the `between` ordering and the value array\n * depend only on the filter, so deriving them per row multiplied that work by\n * the row count. `empty`/`notEmpty` ignore their values entirely, which is why\n * the prepared shape does not need to distinguish them.\n *\n * @param items - The full list.\n * @param filters - Applied filters; incomplete ones are ignored.\n * @returns A new array with the rows that satisfy every complete filter.\n */\nexport function applyFilters<T>(items: readonly T[], filters: readonly Filter[]): T[] {\n const active = filters.filter(isComplete).map((filter) => ({\n field: filter.field,\n operator: filter.operator,\n values: filter.operator === \"between\" ? orderRange(valuesOf(filter)) : valuesOf(filter),\n }));\n if (active.length === 0) return [...items];\n\n return items.filter((item) =>\n active.every(({ field, operator, values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,CAAG,KAAK,CAAC,OAAO,MAAM,CAAI,IACjC,KAAO,IAAO,CAAC,GAAO,CAAM,IAAI,CAAC,GAAQ,CAAK,IAElD,EAAc,QAAQ,GAAO,CAAM,KAAK,IAAI,CAAC,GAAO,CAAM,IAAI,CAAC,GAAQ,CAAK;AACvF;AAqCA,SAAgB,EAAgB,GAAqB,GAAiC;CAClF,IAAM,IAAS,EAAQ,OAAO,CAAU,CAAC,CAAC,KAAK,OAAY;EACvD,OAAO,EAAO;EACd,UAAU,EAAO;EACjB,QAAQ,EAAO,aAAa,YAAY,EAAW,EAAS,CAAM,CAAC,IAAI,EAAS,CAAM;CAC1F,EAAE;CAGF,OAFI,EAAO,WAAW,IAAU,CAAC,GAAG,CAAK,IAElC,EAAM,QAAQ,MACjB,EAAO,OAAO,EAAE,UAAO,aAAU,gBAC7B,EAAgB,GAAU,EAAU,GAAM,CAAK,GAAG,CAAM,CAC5D,CACJ;AACJ"}
@@ -1,2 +1,2 @@
1
- const e=require("../../utils/cn.cjs"),t=require("./crop-geometry.cjs"),n=require("./ImageCropper.module.cjs");let r=require("react"),i=require("react/jsx-runtime");var a=12,o=.15;function s({src:s,aspect:c=1,maxZoom:l=4,maxSize:u,outputType:d=`image/png`,outputQuality:f=.92,shape:p=`rect`,onCropChange:m,label:h=`Área de recorte`,className:g,ref:_,...v}){let y=`${(0,r.useId)()}-hint`,b=(0,r.useRef)(null),x=(0,r.useRef)(null),S=(0,r.useRef)(null),[C,w]=(0,r.useState)(null),[T,E]=(0,r.useState)(null),[D,O]=(0,r.useState)({width:0,height:0}),[k,A]=(0,r.useState)(1),[j,M]=(0,r.useState)({x:0,y:0});(0,r.useEffect)(()=>{if(typeof s==`string`){w(s);return}let e=URL.createObjectURL(s);return w(e),()=>URL.revokeObjectURL(e)},[s]),(0,r.useEffect)(()=>{E(null),A(1),M({x:0,y:0})},[C]),(0,r.useEffect)(()=>{let e=b.current;if(!e)return;let t=()=>O({width:e.clientWidth,height:e.clientHeight});if(t(),typeof ResizeObserver>`u`)return;let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[]);let N=T?t.coverScale(T,D)*k:0,P=(0,r.useMemo)(()=>T?{width:T.width*N,height:T.height*N}:{width:0,height:0},[T,N]),F=(0,r.useCallback)(e=>{M(n=>{let r=t.clampOffset(e,P,D);return r.x===n.x&&r.y===n.y?n:(m?.({zoom:k,offset:r}),r)})},[P,D,m,k]),I=(0,r.useCallback)(e=>{let n=Math.min(l,Math.max(1,e));if(A(n),!T)return;let r=t.coverScale(T,D)*n,i={width:T.width*r,height:T.height*r};M(e=>{let r=t.clampOffset(e,i,D);return m?.({zoom:n,offset:r}),r})},[D,l,T,m]),L=(0,r.useCallback)(()=>{A(1),M({x:0,y:0}),m?.({zoom:1,offset:{x:0,y:0}})},[m]),R=(0,r.useCallback)(async()=>{let e=x.current;if(!e||!T)return null;let n=t.computeCropRect({image:T,frame:D,zoom:k,offset:j});if(n.sWidth<=0||n.sHeight<=0)return null;let r=t.outputSize(n,u),i=document.createElement(`canvas`);i.width=r.width,i.height=r.height;let a=i.getContext(`2d`);return a?(a.drawImage(e,n.sx,n.sy,n.sWidth,n.sHeight,0,0,r.width,r.height),new Promise(e=>{i.toBlob(t=>e(t),d,f)})):null},[D,u,T,j,f,d,k]);(0,r.useImperativeHandle)(_,()=>({crop:R,reset:L}),[R,L]);let z=e=>{T&&(S.current={pointerId:e.pointerId,startX:e.clientX,startY:e.clientY,from:j},e.currentTarget.setPointerCapture?.(e.pointerId))},B=e=>{let t=S.current;!t||t.pointerId!==e.pointerId||F({x:t.from.x+(e.clientX-t.startX),y:t.from.y+(e.clientY-t.startY)})},V=e=>{S.current?.pointerId===e.pointerId&&(S.current=null)},H=e=>{let t=e.shiftKey?48:a,n={ArrowLeft:{x:-t,y:0},ArrowRight:{x:t,y:0},ArrowUp:{x:0,y:-t},ArrowDown:{x:0,y:t}}[e.key];if(n){e.preventDefault(),F({x:j.x+n.x,y:j.y+n.y});return}e.key===`+`||e.key===`=`?(e.preventDefault(),I(k+o)):e.key===`-`||e.key===`_`?(e.preventDefault(),I(k-o)):e.key===`0`&&(e.preventDefault(),L())};return(0,i.jsxs)(`div`,{className:e.cn(n.default.wrapper,g),...v,children:[(0,i.jsx)(`div`,{ref:b,className:e.cn(n.default.frame,p===`circle`&&n.default.circle),style:{aspectRatio:String(c)},role:`group`,"aria-label":h,"aria-describedby":y,tabIndex:0,onPointerDown:z,onPointerMove:B,onPointerUp:V,onPointerCancel:V,onKeyDown:H,onWheel:e=>{e.preventDefault(),I(k+(e.deltaY<0?o:-.15))},children:C&&(0,i.jsx)(`img`,{ref:x,src:C,alt:``,draggable:!1,className:n.default.image,style:{width:P.width||void 0,height:P.height||void 0,transform:`translate(${j.x}px, ${j.y}px)`},onLoad:e=>{let t=e.currentTarget;t.naturalWidth>0&&t.naturalHeight>0&&E({width:t.naturalWidth,height:t.naturalHeight})}})}),(0,i.jsxs)(`div`,{className:n.default.controls,children:[(0,i.jsx)(`input`,{type:`range`,className:n.default.zoom,min:1,max:l,step:.01,value:k,onChange:e=>I(Number(e.target.value)),"aria-label":`Zoom`,disabled:!T}),(0,i.jsx)(`button`,{type:`button`,className:n.default.reset,onClick:L,disabled:!T,children:`Centralizar`})]}),(0,i.jsxs)(`p`,{id:y,className:n.default.hint,children:[`Arraste para reposicionar. Setas movem, `,(0,i.jsx)(`kbd`,{children:`+`}),` e `,(0,i.jsx)(`kbd`,{children:`−`}),` dão zoom,`,` `,(0,i.jsx)(`kbd`,{children:`0`}),` centraliza.`]})]})}exports.ImageCropper=s;
1
+ const e=require("../../utils/cn.cjs"),t=require("./crop-geometry.cjs"),n=require("./ImageCropper.module.cjs");let r=require("react"),i=require("react/jsx-runtime");var a=12,o=.15;function s({src:s,aspect:c=1,maxZoom:l=4,maxSize:u,outputType:d=`image/png`,outputQuality:f=.92,shape:p=`rect`,onCropChange:m,label:h=`Área de recorte`,className:g,ref:_,...v}){let y=`${(0,r.useId)()}-hint`,b=(0,r.useRef)(null),x=(0,r.useRef)(null),S=(0,r.useRef)(null),[C,w]=(0,r.useState)(null),[T,E]=(0,r.useState)(null),[D,O]=(0,r.useState)({width:0,height:0}),[k,A]=(0,r.useState)(1),[j,M]=(0,r.useState)({x:0,y:0});(0,r.useEffect)(()=>{if(typeof s==`string`){w(s);return}let e=URL.createObjectURL(s);return w(e),()=>URL.revokeObjectURL(e)},[s]),(0,r.useEffect)(()=>{E(null),A(1),M({x:0,y:0})},[C]),(0,r.useEffect)(()=>{let e=b.current;if(!e)return;let t=()=>O({width:e.clientWidth,height:e.clientHeight});if(t(),typeof ResizeObserver>`u`)return;let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[]);let N=T?t.coverScale(T,D)*k:0,P=(0,r.useMemo)(()=>T?{width:T.width*N,height:T.height*N}:{width:0,height:0},[T,N]),F=(0,r.useCallback)(e=>{M(n=>{let r=t.clampOffset(e,P,D);return r.x===n.x&&r.y===n.y?n:(m?.({zoom:k,offset:r}),r)})},[P,D,m,k]),I=(0,r.useCallback)(e=>{let n=Math.min(l,Math.max(1,e));if(A(n),!T)return;let r=t.coverScale(T,D)*n,i={width:T.width*r,height:T.height*r};M(e=>{let r=t.clampOffset(e,i,D);return m?.({zoom:n,offset:r}),r})},[D,l,T,m]),L=(0,r.useCallback)(()=>{A(1),M({x:0,y:0}),m?.({zoom:1,offset:{x:0,y:0}})},[m]),R=(0,r.useCallback)(async()=>{let e=x.current;if(!e||!T)return null;let n=t.computeCropRect({image:T,frame:D,zoom:k,offset:j});if(n.sWidth<=0||n.sHeight<=0)return null;let r=t.outputSize(n,u),i=document.createElement(`canvas`);i.width=r.width,i.height=r.height;let a=i.getContext(`2d`);return a?(a.drawImage(e,n.sx,n.sy,n.sWidth,n.sHeight,0,0,r.width,r.height),new Promise(e=>{i.toBlob(t=>e(t),d,f)})):null},[D,u,T,j,f,d,k]);(0,r.useImperativeHandle)(_,()=>({crop:R,reset:L}),[R,L]);let z=e=>{T&&(S.current={pointerId:e.pointerId,startX:e.clientX,startY:e.clientY,from:j},e.currentTarget.setPointerCapture?.(e.pointerId))},B=e=>{let t=S.current;t&&t.pointerId===e.pointerId&&F({x:t.from.x+(e.clientX-t.startX),y:t.from.y+(e.clientY-t.startY)})},V=e=>{S.current?.pointerId===e.pointerId&&(S.current=null)},H=e=>{let t=e.shiftKey?48:a,n={ArrowLeft:{x:-t,y:0},ArrowRight:{x:t,y:0},ArrowUp:{x:0,y:-t},ArrowDown:{x:0,y:t}}[e.key];if(n){e.preventDefault(),F({x:j.x+n.x,y:j.y+n.y});return}e.key===`+`||e.key===`=`?(e.preventDefault(),I(k+o)):e.key===`-`||e.key===`_`?(e.preventDefault(),I(k-o)):e.key===`0`&&(e.preventDefault(),L())};return(0,i.jsxs)(`div`,{className:e.cn(n.default.wrapper,g),...v,children:[(0,i.jsx)(`div`,{ref:b,className:e.cn(n.default.frame,p===`circle`&&n.default.circle),style:{aspectRatio:String(c)},role:`group`,"aria-label":h,"aria-describedby":y,tabIndex:0,onPointerDown:z,onPointerMove:B,onPointerUp:V,onPointerCancel:V,onKeyDown:H,onWheel:e=>{e.preventDefault(),I(k+(e.deltaY<0?o:-.15))},children:C&&(0,i.jsx)(`img`,{ref:x,src:C,alt:``,draggable:!1,className:n.default.image,style:{width:P.width||void 0,height:P.height||void 0,transform:`translate(${j.x}px, ${j.y}px)`},onLoad:e=>{let t=e.currentTarget;t.naturalWidth>0&&t.naturalHeight>0&&E({width:t.naturalWidth,height:t.naturalHeight})}})}),(0,i.jsxs)(`div`,{className:n.default.controls,children:[(0,i.jsx)(`input`,{type:`range`,className:n.default.zoom,min:1,max:l,step:.01,value:k,onChange:e=>I(Number(e.target.value)),"aria-label":`Zoom`,disabled:!T}),(0,i.jsx)(`button`,{type:`button`,className:n.default.reset,onClick:L,disabled:!T,children:`Centralizar`})]}),(0,i.jsxs)(`p`,{id:y,className:n.default.hint,children:[`Arraste para reposicionar. Setas movem, `,(0,i.jsx)(`kbd`,{children:`+`}),` e `,(0,i.jsx)(`kbd`,{children:`−`}),` dão zoom,`,` `,(0,i.jsx)(`kbd`,{children:`0`}),` centraliza.`]})]})}exports.ImageCropper=s;
2
2
  //# sourceMappingURL=ImageCropper.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"ImageCropper.cjs","names":[],"sources":["../../../src/components/ImageCropper/ImageCropper.tsx"],"sourcesContent":["/**\n * @tempest-limits file-lines, props-count, function-lines — pointer drag, wheel\n * zoom, aspect clamping and canvas export share one piece of geometry state, and the\n * props are the two halves of that: the frame (aspect, shape, maxZoom, label) and\n * the export (maxSize, outputType, outputQuality, onCropChange, ref). Threading the\n * geometry through props would duplicate the clamp maths.\n */\nimport {\n type HTMLAttributes,\n type KeyboardEvent,\n type PointerEvent as ReactPointerEvent,\n useCallback,\n useEffect,\n useId,\n useImperativeHandle,\n useMemo,\n useRef,\n useState,\n} from \"react\";\n\nimport { cn } from \"@/utils/cn\";\n\nimport {\n clampOffset,\n computeCropRect,\n coverScale,\n type Offset,\n outputSize,\n type Size,\n} from \"./crop-geometry\";\nimport styles from \"./ImageCropper.module.css\";\n\n/** Imperative handle for exporting the current crop. */\nexport interface ImageCropperHandle {\n /**\n * Render the current crop and resolve with it.\n *\n * Resolves `null` when the image has not loaded yet or the browser refuses to\n * encode — never throws, so a submit handler does not need a try/catch.\n */\n crop: () => Promise<Blob | null>;\n /** Recentre at zoom 1. */\n reset: () => void;\n}\n\nexport interface ImageCropperProps extends Omit<HTMLAttributes<HTMLDivElement>, \"children\"> {\n /** The image to crop: a `File`/`Blob` from an input, or a URL. */\n src: File | Blob | string;\n /** Crop aspect ratio as `width / height`. Default `1` (square). */\n aspect?: number;\n /** Maximum zoom over the cover scale. Default `4`. */\n maxZoom?: number;\n /**\n * Cap on the longest edge of the exported image, in px.\n *\n * Without it the export keeps the source resolution, which is right for a\n * document scan and wasteful for an avatar.\n */\n maxSize?: number;\n /** Output MIME type. Default `\"image/png\"`. */\n outputType?: string;\n /** Output quality for lossy types, `0`–`1`. Default `0.92`. */\n outputQuality?: number;\n /** Overlay shape. `\"circle\"` for an avatar, `\"rect\"` for a document. Default `\"rect\"`. */\n shape?: \"rect\" | \"circle\";\n /** Called whenever the crop changes, e.g. to enable a submit button. */\n onCropChange?: (state: { zoom: number; offset: Offset }) => void;\n /** Accessible name for the crop area. */\n label?: string;\n ref?: React.Ref<ImageCropperHandle>;\n}\n\n/** Pixels moved per arrow-key press. */\nconst KEY_STEP = 12;\n\n/** Zoom added or removed per `+`/`-` press, and per wheel notch. */\nconst ZOOM_STEP = 0.15;\n\n/**\n * Crop an image to a fixed aspect ratio.\n *\n * The frame stays put and the image pans and zooms behind it — the model an avatar\n * or document-photo flow wants, where the output shape is decided by the app and\n * the user only chooses what lands inside it. (A free-form draggable rectangle is a\n * different component; this one cannot produce an off-ratio crop by construction.)\n *\n * The export reads the *natural* pixels through a canvas, so a 4000 px photo is not\n * silently downsampled to whatever the on-screen preview measured. The image is\n * also always clamped to cover the frame, so an export can never contain the empty\n * bands you get from panning past an edge.\n *\n * Works by pointer, wheel and keyboard: arrows pan, `+`/`-` zoom, `0` resets.\n *\n * @example\n * const cropper = useRef<ImageCropperHandle>(null);\n *\n * <ImageCropper ref={cropper} src={file} aspect={1} shape=\"circle\" maxSize={512} />\n * <Button onClick={async () => upload(await cropper.current?.crop())}>Salvar</Button>\n */\nexport function ImageCropper({\n src,\n aspect = 1,\n maxZoom = 4,\n maxSize,\n outputType = \"image/png\",\n outputQuality = 0.92,\n shape = \"rect\",\n onCropChange,\n label = \"Área de recorte\",\n className,\n ref,\n ...rest\n}: ImageCropperProps) {\n /**\n * Id for the shortcut hint.\n *\n * Generated rather than derived from `label`: a label with spaces would produce\n * an id with spaces, and `aria-describedby` splits on whitespace — so the\n * description would silently never associate with the frame.\n */\n const hintId = `${useId()}-hint`;\n\n const frameRef = useRef<HTMLDivElement>(null);\n const imageRef = useRef<HTMLImageElement | null>(null);\n const dragRef = useRef<{\n pointerId: number;\n startX: number;\n startY: number;\n from: Offset;\n } | null>(null);\n\n const [url, setUrl] = useState<string | null>(null);\n const [natural, setNatural] = useState<Size | null>(null);\n const [frame, setFrame] = useState<Size>({ width: 0, height: 0 });\n const [zoom, setZoom] = useState(1);\n const [offset, setOffset] = useState<Offset>({ x: 0, y: 0 });\n\n /**\n * Resolve `src` to a displayable URL.\n *\n * A `File`/`Blob` needs `createObjectURL`, and the URL must be revoked when the\n * source changes or the component unmounts — otherwise every re-pick of a photo\n * leaks the previous one for the lifetime of the document.\n */\n useEffect(() => {\n if (typeof src === \"string\") {\n setUrl(src);\n return;\n }\n const objectUrl = URL.createObjectURL(src);\n setUrl(objectUrl);\n return () => URL.revokeObjectURL(objectUrl);\n }, [src]);\n\n // A new source invalidates the previous framing.\n useEffect(() => {\n setNatural(null);\n setZoom(1);\n setOffset({ x: 0, y: 0 });\n }, [url]);\n\n /** Track the frame's rendered size — the crop math is all relative to it. */\n useEffect(() => {\n const element = frameRef.current;\n if (!element) return;\n const measure = () =>\n setFrame({ width: element.clientWidth, height: element.clientHeight });\n measure();\n if (typeof ResizeObserver === \"undefined\") return;\n const observer = new ResizeObserver(measure);\n observer.observe(element);\n return () => observer.disconnect();\n }, []);\n\n const scale = natural ? coverScale(natural, frame) * zoom : 0;\n\n /**\n * On-screen image size.\n *\n * Memoized because the pan callback depends on it: a fresh object every render\n * would rebuild that callback every render, and the pointer handlers close over\n * it during a drag.\n */\n const displayed = useMemo<Size>(\n () =>\n natural\n ? { width: natural.width * scale, height: natural.height * scale }\n : { width: 0, height: 0 },\n [natural, scale],\n );\n\n /** Apply a pan, clamped so the frame stays covered. */\n const pan = useCallback(\n (next: Offset) => {\n setOffset((current) => {\n const clamped = clampOffset(next, displayed, frame);\n if (clamped.x === current.x && clamped.y === current.y) return current;\n onCropChange?.({ zoom, offset: clamped });\n return clamped;\n });\n },\n [displayed, frame, onCropChange, zoom],\n );\n\n /**\n * Apply a zoom, then re-clamp the offset.\n *\n * Re-clamping is not optional: zooming *out* shrinks the image, so an offset\n * that was legal a moment ago can now expose background.\n */\n const applyZoom = useCallback(\n (next: number) => {\n const clampedZoom = Math.min(maxZoom, Math.max(1, next));\n setZoom(clampedZoom);\n if (!natural) return;\n const nextScale = coverScale(natural, frame) * clampedZoom;\n const nextDisplayed = {\n width: natural.width * nextScale,\n height: natural.height * nextScale,\n };\n setOffset((current) => {\n const clamped = clampOffset(current, nextDisplayed, frame);\n onCropChange?.({ zoom: clampedZoom, offset: clamped });\n return clamped;\n });\n },\n [frame, maxZoom, natural, onCropChange],\n );\n\n const reset = useCallback(() => {\n setZoom(1);\n setOffset({ x: 0, y: 0 });\n onCropChange?.({ zoom: 1, offset: { x: 0, y: 0 } });\n }, [onCropChange]);\n\n /**\n * Draw the current crop and encode it.\n *\n * Returns `null` rather than throwing on the paths a caller cannot do anything\n * about: no image yet, no 2D context, or an encoder that declined.\n */\n const crop = useCallback(async (): Promise<Blob | null> => {\n const image = imageRef.current;\n if (!image || !natural) return null;\n\n const rect = computeCropRect({ image: natural, frame, zoom, offset });\n if (rect.sWidth <= 0 || rect.sHeight <= 0) return null;\n\n const out = outputSize(rect, maxSize);\n const canvas = document.createElement(\"canvas\");\n canvas.width = out.width;\n canvas.height = out.height;\n const context = canvas.getContext(\"2d\");\n if (!context) return null;\n\n context.drawImage(\n image,\n rect.sx,\n rect.sy,\n rect.sWidth,\n rect.sHeight,\n 0,\n 0,\n out.width,\n out.height,\n );\n\n return new Promise((resolve) => {\n canvas.toBlob((blob) => resolve(blob), outputType, outputQuality);\n });\n }, [frame, maxSize, natural, offset, outputQuality, outputType, zoom]);\n\n useImperativeHandle(ref, () => ({ crop, reset }), [crop, reset]);\n\n const onPointerDown = (event: ReactPointerEvent<HTMLDivElement>): void => {\n if (!natural) return;\n dragRef.current = {\n pointerId: event.pointerId,\n startX: event.clientX,\n startY: event.clientY,\n from: offset,\n };\n event.currentTarget.setPointerCapture?.(event.pointerId);\n };\n\n const onPointerMove = (event: ReactPointerEvent<HTMLDivElement>): void => {\n const drag = dragRef.current;\n if (!drag || drag.pointerId !== event.pointerId) return;\n pan({\n x: drag.from.x + (event.clientX - drag.startX),\n y: drag.from.y + (event.clientY - drag.startY),\n });\n };\n\n const endDrag = (event: ReactPointerEvent<HTMLDivElement>): void => {\n if (dragRef.current?.pointerId !== event.pointerId) return;\n dragRef.current = null;\n };\n\n const onKeyDown = (event: KeyboardEvent<HTMLDivElement>): void => {\n const step = event.shiftKey ? KEY_STEP * 4 : KEY_STEP;\n const moves: Record<string, Offset> = {\n ArrowLeft: { x: -step, y: 0 },\n ArrowRight: { x: step, y: 0 },\n ArrowUp: { x: 0, y: -step },\n ArrowDown: { x: 0, y: step },\n };\n const move = moves[event.key];\n if (move) {\n event.preventDefault();\n pan({ x: offset.x + move.x, y: offset.y + move.y });\n return;\n }\n if (event.key === \"+\" || event.key === \"=\") {\n event.preventDefault();\n applyZoom(zoom + ZOOM_STEP);\n } else if (event.key === \"-\" || event.key === \"_\") {\n event.preventDefault();\n applyZoom(zoom - ZOOM_STEP);\n } else if (event.key === \"0\") {\n event.preventDefault();\n reset();\n }\n };\n\n return (\n <div className={cn(styles.wrapper, className)} {...rest}>\n <div\n ref={frameRef}\n className={cn(styles.frame, shape === \"circle\" && styles.circle)}\n style={{ aspectRatio: String(aspect) }}\n role=\"group\"\n aria-label={label}\n aria-describedby={hintId}\n tabIndex={0}\n onPointerDown={onPointerDown}\n onPointerMove={onPointerMove}\n onPointerUp={endDrag}\n onPointerCancel={endDrag}\n onKeyDown={onKeyDown}\n onWheel={(event) => {\n event.preventDefault();\n applyZoom(zoom + (event.deltaY < 0 ? ZOOM_STEP : -ZOOM_STEP));\n }}\n >\n {url && (\n <img\n ref={imageRef}\n src={url}\n alt=\"\"\n draggable={false}\n className={styles.image}\n style={{\n width: displayed.width || undefined,\n height: displayed.height || undefined,\n transform: `translate(${offset.x}px, ${offset.y}px)`,\n }}\n onLoad={(event) => {\n const element = event.currentTarget;\n // A decode can succeed and still report no intrinsic size —\n // an SVG without a viewBox is the common case. Accepting\n // that would enable the controls over an image the crop\n // maths can do nothing with.\n if (element.naturalWidth > 0 && element.naturalHeight > 0) {\n setNatural({\n width: element.naturalWidth,\n height: element.naturalHeight,\n });\n }\n }}\n />\n )}\n </div>\n\n <div className={styles.controls}>\n <input\n type=\"range\"\n className={styles.zoom}\n min={1}\n max={maxZoom}\n step={0.01}\n value={zoom}\n onChange={(event) => applyZoom(Number(event.target.value))}\n aria-label=\"Zoom\"\n disabled={!natural}\n />\n <button type=\"button\" className={styles.reset} onClick={reset} disabled={!natural}>\n Centralizar\n </button>\n </div>\n\n <p id={hintId} className={styles.hint}>\n Arraste para reposicionar. Setas movem, <kbd>+</kbd> e <kbd>−</kbd> dão zoom,{\" \"}\n <kbd>0</kbd> centraliza.\n </p>\n </div>\n );\n}\n"],"mappings":"oKAyEA,IAAM,EAAW,GAGX,EAAY,IAuBlB,SAAgB,EAAa,CACzB,MACA,SAAS,EACT,UAAU,EACV,UACA,aAAa,YACb,gBAAgB,IAChB,QAAQ,OACR,eACA,QAAQ,kBACR,YACA,MACA,GAAG,GACe,CAQlB,IAAM,EAAS,IAAA,EAAG,EAAA,MAAA,CAAM,EAAE,OAEpB,GAAA,EAAW,EAAA,OAAA,CAAuB,IAAI,EACtC,GAAA,EAAW,EAAA,OAAA,CAAgC,IAAI,EAC/C,GAAA,EAAU,EAAA,OAAA,CAKN,IAAI,EAER,CAAC,EAAK,IAAA,EAAU,EAAA,SAAA,CAAwB,IAAI,EAC5C,CAAC,EAAS,IAAA,EAAc,EAAA,SAAA,CAAsB,IAAI,EAClD,CAAC,EAAO,IAAA,EAAY,EAAA,SAAA,CAAe,CAAE,MAAO,EAAG,OAAQ,CAAE,CAAC,EAC1D,CAAC,EAAM,IAAA,EAAW,EAAA,SAAA,CAAS,CAAC,EAC5B,CAAC,EAAQ,IAAA,EAAa,EAAA,SAAA,CAAiB,CAAE,EAAG,EAAG,EAAG,CAAE,CAAC,GAS3D,EAAA,EAAA,UAAA,KAAgB,CACZ,GAAI,OA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AAA,EAAA,KAAA,CAAC,IAAD,CAAG,GAAI,EAAQ,UAAW,EAAA,QAAO,KAAjC,SAAA,CAAuC,4CACK,EAAA,EAAA,IAAA,CAAC,MAAD,CAAA,SAAK,GAAM,CAAA,EAAC,OAAG,EAAA,EAAA,IAAA,CAAC,MAAD,CAAA,SAAK,GAAM,CAAA,EAAC,aAAW,KAC9E,EAAA,EAAA,IAAA,CAAC,MAAD,CAAA,SAAK,GAAM,CAAA,EAAC,cACb,GACF,GAEb"}
1
+ {"version":3,"file":"ImageCropper.cjs","names":[],"sources":["../../../src/components/ImageCropper/ImageCropper.tsx"],"sourcesContent":["/**\n * @tempest-limits file-lines, props-count, function-lines — pointer drag, wheel\n * zoom, aspect clamping and canvas export share one piece of geometry state, and the\n * props are the two halves of that: the frame (aspect, shape, maxZoom, label) and\n * the export (maxSize, outputType, outputQuality, onCropChange, ref). Threading the\n * geometry through props would duplicate the clamp maths.\n */\nimport {\n type HTMLAttributes,\n type KeyboardEvent,\n type PointerEvent as ReactPointerEvent,\n useCallback,\n useEffect,\n useId,\n useImperativeHandle,\n useMemo,\n useRef,\n useState,\n} from \"react\";\n\nimport { cn } from \"@/utils/cn\";\n\nimport {\n clampOffset,\n computeCropRect,\n coverScale,\n type Offset,\n outputSize,\n type Size,\n} from \"./crop-geometry\";\nimport styles from \"./ImageCropper.module.css\";\n\n/** Imperative handle for exporting the current crop. */\nexport interface ImageCropperHandle {\n /**\n * Render the current crop and resolve with it.\n *\n * Resolves `null` when the image has not loaded yet or the browser refuses to\n * encode — never throws, so a submit handler does not need a try/catch.\n */\n crop: () => Promise<Blob | null>;\n /** Recentre at zoom 1. */\n reset: () => void;\n}\n\nexport interface ImageCropperProps extends Omit<HTMLAttributes<HTMLDivElement>, \"children\"> {\n /** The image to crop: a `File`/`Blob` from an input, or a URL. */\n src: File | Blob | string;\n /** Crop aspect ratio as `width / height`. Default `1` (square). */\n aspect?: number;\n /** Maximum zoom over the cover scale. Default `4`. */\n maxZoom?: number;\n /**\n * Cap on the longest edge of the exported image, in px.\n *\n * Without it the export keeps the source resolution, which is right for a\n * document scan and wasteful for an avatar.\n */\n maxSize?: number;\n /** Output MIME type. Default `\"image/png\"`. */\n outputType?: string;\n /** Output quality for lossy types, `0`–`1`. Default `0.92`. */\n outputQuality?: number;\n /** Overlay shape. `\"circle\"` for an avatar, `\"rect\"` for a document. Default `\"rect\"`. */\n shape?: \"rect\" | \"circle\";\n /** Called whenever the crop changes, e.g. to enable a submit button. */\n onCropChange?: (state: { zoom: number; offset: Offset }) => void;\n /** Accessible name for the crop area. */\n label?: string;\n ref?: React.Ref<ImageCropperHandle>;\n}\n\n/** Pixels moved per arrow-key press. */\nconst KEY_STEP = 12;\n\n/** Zoom added or removed per `+`/`-` press, and per wheel notch. */\nconst ZOOM_STEP = 0.15;\n\n/**\n * Crop an image to a fixed aspect ratio.\n *\n * The frame stays put and the image pans and zooms behind it — the model an avatar\n * or document-photo flow wants, where the output shape is decided by the app and\n * the user only chooses what lands inside it. (A free-form draggable rectangle is a\n * different component; this one cannot produce an off-ratio crop by construction.)\n *\n * The export reads the *natural* pixels through a canvas, so a 4000 px photo is not\n * silently downsampled to whatever the on-screen preview measured. The image is\n * also always clamped to cover the frame, so an export can never contain the empty\n * bands you get from panning past an edge.\n *\n * Works by pointer, wheel and keyboard: arrows pan, `+`/`-` zoom, `0` resets.\n *\n * @example\n * const cropper = useRef<ImageCropperHandle>(null);\n *\n * <ImageCropper ref={cropper} src={file} aspect={1} shape=\"circle\" maxSize={512} />\n * <Button onClick={async () => upload(await cropper.current?.crop())}>Salvar</Button>\n */\nexport function ImageCropper({\n src,\n aspect = 1,\n maxZoom = 4,\n maxSize,\n outputType = \"image/png\",\n outputQuality = 0.92,\n shape = \"rect\",\n onCropChange,\n label = \"Área de recorte\",\n className,\n ref,\n ...rest\n}: ImageCropperProps) {\n /**\n * Id for the shortcut hint.\n *\n * Generated rather than derived from `label`: a label with spaces would produce\n * an id with spaces, and `aria-describedby` splits on whitespace — so the\n * description would silently never associate with the frame.\n */\n const hintId = `${useId()}-hint`;\n\n const frameRef = useRef<HTMLDivElement>(null);\n const imageRef = useRef<HTMLImageElement | null>(null);\n const dragRef = useRef<{\n pointerId: number;\n startX: number;\n startY: number;\n from: Offset;\n } | null>(null);\n\n const [url, setUrl] = useState<string | null>(null);\n const [natural, setNatural] = useState<Size | null>(null);\n const [frame, setFrame] = useState<Size>({ width: 0, height: 0 });\n const [zoom, setZoom] = useState(1);\n const [offset, setOffset] = useState<Offset>({ x: 0, y: 0 });\n\n /**\n * Resolve `src` to a displayable URL.\n *\n * A `File`/`Blob` needs `createObjectURL`, and the URL must be revoked when the\n * source changes or the component unmounts — otherwise every re-pick of a photo\n * leaks the previous one for the lifetime of the document.\n */\n useEffect(() => {\n if (typeof src === \"string\") {\n setUrl(src);\n return;\n }\n const objectUrl = URL.createObjectURL(src);\n setUrl(objectUrl);\n return () => URL.revokeObjectURL(objectUrl);\n }, [src]);\n\n // A new source invalidates the previous framing.\n useEffect(() => {\n setNatural(null);\n setZoom(1);\n setOffset({ x: 0, y: 0 });\n }, [url]);\n\n /** Track the frame's rendered size — the crop math is all relative to it. */\n useEffect(() => {\n const element = frameRef.current;\n if (!element) return;\n const measure = () =>\n setFrame({ width: element.clientWidth, height: element.clientHeight });\n measure();\n if (typeof ResizeObserver === \"undefined\") return;\n const observer = new ResizeObserver(measure);\n observer.observe(element);\n return () => observer.disconnect();\n }, []);\n\n const scale = natural ? coverScale(natural, frame) * zoom : 0;\n\n /**\n * On-screen image size.\n *\n * Memoized because the pan callback depends on it: a fresh object every render\n * would rebuild that callback every render, and the pointer handlers close over\n * it during a drag.\n */\n const displayed = useMemo<Size>(\n () =>\n natural\n ? { width: natural.width * scale, height: natural.height * scale }\n : { width: 0, height: 0 },\n [natural, scale],\n );\n\n /** Apply a pan, clamped so the frame stays covered. */\n const pan = useCallback(\n (next: Offset) => {\n setOffset((current) => {\n const clamped = clampOffset(next, displayed, frame);\n if (clamped.x === current.x && clamped.y === current.y) return current;\n onCropChange?.({ zoom, offset: clamped });\n return clamped;\n });\n },\n [displayed, frame, onCropChange, zoom],\n );\n\n /**\n * Apply a zoom, then re-clamp the offset.\n *\n * Re-clamping is not optional: zooming *out* shrinks the image, so an offset\n * that was legal a moment ago can now expose background.\n */\n const applyZoom = useCallback(\n (next: number) => {\n const clampedZoom = Math.min(maxZoom, Math.max(1, next));\n setZoom(clampedZoom);\n if (!natural) return;\n const nextScale = coverScale(natural, frame) * clampedZoom;\n const nextDisplayed = {\n width: natural.width * nextScale,\n height: natural.height * nextScale,\n };\n setOffset((current) => {\n const clamped = clampOffset(current, nextDisplayed, frame);\n onCropChange?.({ zoom: clampedZoom, offset: clamped });\n return clamped;\n });\n },\n [frame, maxZoom, natural, onCropChange],\n );\n\n const reset = useCallback(() => {\n setZoom(1);\n setOffset({ x: 0, y: 0 });\n onCropChange?.({ zoom: 1, offset: { x: 0, y: 0 } });\n }, [onCropChange]);\n\n /**\n * Draw the current crop and encode it.\n *\n * Returns `null` rather than throwing on the paths a caller cannot do anything\n * about: no image yet, no 2D context, or an encoder that declined.\n */\n const crop = useCallback(async (): Promise<Blob | null> => {\n const image = imageRef.current;\n if (!image || !natural) return null;\n\n const rect = computeCropRect({ image: natural, frame, zoom, offset });\n if (rect.sWidth <= 0 || rect.sHeight <= 0) return null;\n\n const out = outputSize(rect, maxSize);\n const canvas = document.createElement(\"canvas\");\n canvas.width = out.width;\n canvas.height = out.height;\n const context = canvas.getContext(\"2d\");\n if (!context) return null;\n\n context.drawImage(\n image,\n rect.sx,\n rect.sy,\n rect.sWidth,\n rect.sHeight,\n 0,\n 0,\n out.width,\n out.height,\n );\n\n return new Promise((resolve) => {\n canvas.toBlob((blob) => resolve(blob), outputType, outputQuality);\n });\n }, [frame, maxSize, natural, offset, outputQuality, outputType, zoom]);\n\n useImperativeHandle(ref, () => ({ crop, reset }), [crop, reset]);\n\n const onPointerDown = (event: ReactPointerEvent<HTMLDivElement>): void => {\n if (!natural) return;\n dragRef.current = {\n pointerId: event.pointerId,\n startX: event.clientX,\n startY: event.clientY,\n from: offset,\n };\n event.currentTarget.setPointerCapture?.(event.pointerId);\n };\n\n const onPointerMove = (event: ReactPointerEvent<HTMLDivElement>): void => {\n const drag = dragRef.current;\n if (!drag || drag.pointerId !== event.pointerId) return;\n pan({\n x: drag.from.x + (event.clientX - drag.startX),\n y: drag.from.y + (event.clientY - drag.startY),\n });\n };\n\n const endDrag = (event: ReactPointerEvent<HTMLDivElement>): void => {\n if (dragRef.current?.pointerId !== event.pointerId) return;\n dragRef.current = null;\n };\n\n const onKeyDown = (event: KeyboardEvent<HTMLDivElement>): void => {\n const step = event.shiftKey ? KEY_STEP * 4 : KEY_STEP;\n const moves: Record<string, Offset> = {\n ArrowLeft: { x: -step, y: 0 },\n ArrowRight: { x: step, y: 0 },\n ArrowUp: { x: 0, y: -step },\n ArrowDown: { x: 0, y: step },\n };\n const move = moves[event.key];\n if (move) {\n event.preventDefault();\n pan({ x: offset.x + move.x, y: offset.y + move.y });\n return;\n }\n if (event.key === \"+\" || event.key === \"=\") {\n event.preventDefault();\n applyZoom(zoom + ZOOM_STEP);\n } else if (event.key === \"-\" || event.key === \"_\") {\n event.preventDefault();\n applyZoom(zoom - ZOOM_STEP);\n } else if (event.key === \"0\") {\n event.preventDefault();\n reset();\n }\n };\n\n return (\n <div className={cn(styles.wrapper, className)} {...rest}>\n <div\n ref={frameRef}\n className={cn(styles.frame, shape === \"circle\" && styles.circle)}\n style={{ aspectRatio: String(aspect) }}\n role=\"group\"\n aria-label={label}\n aria-describedby={hintId}\n tabIndex={0}\n onPointerDown={onPointerDown}\n onPointerMove={onPointerMove}\n onPointerUp={endDrag}\n onPointerCancel={endDrag}\n onKeyDown={onKeyDown}\n onWheel={(event) => {\n event.preventDefault();\n applyZoom(zoom + (event.deltaY < 0 ? ZOOM_STEP : -ZOOM_STEP));\n }}\n >\n {url && (\n <img\n ref={imageRef}\n src={url}\n alt=\"\"\n draggable={false}\n className={styles.image}\n style={{\n width: displayed.width || undefined,\n height: displayed.height || undefined,\n transform: `translate(${offset.x}px, ${offset.y}px)`,\n }}\n onLoad={(event) => {\n const element = event.currentTarget;\n // A decode can succeed and still report no intrinsic size —\n // an SVG without a viewBox is the common case. Accepting\n // that would enable the controls over an image the crop\n // maths can do nothing with.\n if (element.naturalWidth > 0 && element.naturalHeight > 0) {\n setNatural({\n width: element.naturalWidth,\n height: element.naturalHeight,\n });\n }\n }}\n />\n )}\n </div>\n\n <div className={styles.controls}>\n <input\n type=\"range\"\n className={styles.zoom}\n min={1}\n max={maxZoom}\n step={0.01}\n value={zoom}\n onChange={(event) => applyZoom(Number(event.target.value))}\n aria-label=\"Zoom\"\n disabled={!natural}\n />\n <button type=\"button\" className={styles.reset} onClick={reset} disabled={!natural}>\n Centralizar\n </button>\n </div>\n\n <p id={hintId} className={styles.hint}>\n Arraste para reposicionar. Setas movem, <kbd>+</kbd> e <kbd>−</kbd> dão zoom,{\" \"}\n <kbd>0</kbd> centraliza.\n </p>\n </div>\n );\n}\n"],"mappings":"oKAyEA,IAAM,EAAW,GAGX,EAAY,IAuBlB,SAAgB,EAAa,CACzB,MACA,SAAS,EACT,UAAU,EACV,UACA,aAAa,YACb,gBAAgB,IAChB,QAAQ,OACR,eACA,QAAQ,kBACR,YACA,MACA,GAAG,GACe,CAQlB,IAAM,EAAS,IAAA,EAAG,EAAA,MAAA,CAAM,EAAE,OAEpB,GAAA,EAAW,EAAA,OAAA,CAAuB,IAAI,EACtC,GAAA,EAAW,EAAA,OAAA,CAAgC,IAAI,EAC/C,GAAA,EAAU,EAAA,OAAA,CAKN,IAAI,EAER,CAAC,EAAK,IAAA,EAAU,EAAA,SAAA,CAAwB,IAAI,EAC5C,CAAC,EAAS,IAAA,EAAc,EAAA,SAAA,CAAsB,IAAI,EAClD,CAAC,EAAO,IAAA,EAAY,EAAA,SAAA,CAAe,CAAE,MAAO,EAAG,OAAQ,CAAE,CAAC,EAC1D,CAAC,EAAM,IAA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AAU,CAAC,CACd,CAAA,GACD,EAAA,EAAA,IAAA,CAAC,SAAD,CAAQ,KAAK,SAAS,UAAW,EAAA,QAAO,MAAO,QAAS,EAAO,SAAU,CAAC,EAAS,SAAA,aAE3E,CAAA,CACP,KAEL,EAAA,EAAA,KAAA,CAAC,IAAD,CAAG,GAAI,EAAQ,UAAW,EAAA,QAAO,KAAjC,SAAA,CAAuC,4CACK,EAAA,EAAA,IAAA,CAAC,MAAD,CAAA,SAAK,GAAM,CAAA,EAAC,OAAG,EAAA,EAAA,IAAA,CAAC,MAAD,CAAA,SAAK,GAAM,CAAA,EAAC,aAAW,KAC9E,EAAA,EAAA,IAAA,CAAC,MAAD,CAAA,SAAK,GAAM,CAAA,EAAC,cACb,GACF,GAEb"}
@@ -123,7 +123,7 @@ function _({ src: _, aspect: v = 1, maxZoom: y = 4, maxSize: b, outputType: x =
123
123
  }, e.currentTarget.setPointerCapture?.(e.pointerId));
124
124
  }, X = (e) => {
125
125
  let t = M.current;
126
- !t || t.pointerId !== e.pointerId || G({
126
+ t && t.pointerId === e.pointerId && G({
127
127
  x: t.from.x + (e.clientX - t.startX),
128
128
  y: t.from.y + (e.clientY - t.startY)
129
129
  });
@@ -1 +1 @@
1
- {"version":3,"file":"ImageCropper.js","names":[],"sources":["../../../src/components/ImageCropper/ImageCropper.tsx"],"sourcesContent":["/**\n * @tempest-limits file-lines, props-count, function-lines — pointer drag, wheel\n * zoom, aspect clamping and canvas export share one piece of geometry state, and the\n * props are the two halves of that: the frame (aspect, shape, maxZoom, label) and\n * the export (maxSize, outputType, outputQuality, onCropChange, ref). Threading the\n * geometry through props would duplicate the clamp maths.\n */\nimport {\n type HTMLAttributes,\n type KeyboardEvent,\n type PointerEvent as ReactPointerEvent,\n useCallback,\n useEffect,\n useId,\n useImperativeHandle,\n useMemo,\n useRef,\n useState,\n} from \"react\";\n\nimport { cn } from \"@/utils/cn\";\n\nimport {\n clampOffset,\n computeCropRect,\n coverScale,\n type Offset,\n outputSize,\n type Size,\n} from \"./crop-geometry\";\nimport styles from \"./ImageCropper.module.css\";\n\n/** Imperative handle for exporting the current crop. */\nexport interface ImageCropperHandle {\n /**\n * Render the current crop and resolve with it.\n *\n * Resolves `null` when the image has not loaded yet or the browser refuses to\n * encode — never throws, so a submit handler does not need a try/catch.\n */\n crop: () => Promise<Blob | null>;\n /** Recentre at zoom 1. */\n reset: () => void;\n}\n\nexport interface ImageCropperProps extends Omit<HTMLAttributes<HTMLDivElement>, \"children\"> {\n /** The image to crop: a `File`/`Blob` from an input, or a URL. */\n src: File | Blob | string;\n /** Crop aspect ratio as `width / height`. Default `1` (square). */\n aspect?: number;\n /** Maximum zoom over the cover scale. Default `4`. */\n maxZoom?: number;\n /**\n * Cap on the longest edge of the exported image, in px.\n *\n * Without it the export keeps the source resolution, which is right for a\n * document scan and wasteful for an avatar.\n */\n maxSize?: number;\n /** Output MIME type. Default `\"image/png\"`. */\n outputType?: string;\n /** Output quality for lossy types, `0`–`1`. Default `0.92`. */\n outputQuality?: number;\n /** Overlay shape. `\"circle\"` for an avatar, `\"rect\"` for a document. Default `\"rect\"`. */\n shape?: \"rect\" | \"circle\";\n /** Called whenever the crop changes, e.g. to enable a submit button. */\n onCropChange?: (state: { zoom: number; offset: Offset }) => void;\n /** Accessible name for the crop area. */\n label?: string;\n ref?: React.Ref<ImageCropperHandle>;\n}\n\n/** Pixels moved per arrow-key press. */\nconst KEY_STEP = 12;\n\n/** Zoom added or removed per `+`/`-` press, and per wheel notch. */\nconst ZOOM_STEP = 0.15;\n\n/**\n * Crop an image to a fixed aspect ratio.\n *\n * The frame stays put and the image pans and zooms behind it — the model an avatar\n * or document-photo flow wants, where the output shape is decided by the app and\n * the user only chooses what lands inside it. (A free-form draggable rectangle is a\n * different component; this one cannot produce an off-ratio crop by construction.)\n *\n * The export reads the *natural* pixels through a canvas, so a 4000 px photo is not\n * silently downsampled to whatever the on-screen preview measured. The image is\n * also always clamped to cover the frame, so an export can never contain the empty\n * bands you get from panning past an edge.\n *\n * Works by pointer, wheel and keyboard: arrows pan, `+`/`-` zoom, `0` resets.\n *\n * @example\n * const cropper = useRef<ImageCropperHandle>(null);\n *\n * <ImageCropper ref={cropper} src={file} aspect={1} shape=\"circle\" maxSize={512} />\n * <Button onClick={async () => upload(await cropper.current?.crop())}>Salvar</Button>\n */\nexport function ImageCropper({\n src,\n aspect = 1,\n maxZoom = 4,\n maxSize,\n outputType = \"image/png\",\n outputQuality = 0.92,\n shape = \"rect\",\n onCropChange,\n label = \"Área de recorte\",\n className,\n ref,\n ...rest\n}: ImageCropperProps) {\n /**\n * Id for the shortcut hint.\n *\n * Generated rather than derived from `label`: a label with spaces would produce\n * an id with spaces, and `aria-describedby` splits on whitespace — so the\n * description would silently never associate with the frame.\n */\n const hintId = `${useId()}-hint`;\n\n const frameRef = useRef<HTMLDivElement>(null);\n const imageRef = useRef<HTMLImageElement | null>(null);\n const dragRef = useRef<{\n pointerId: number;\n startX: number;\n startY: number;\n from: Offset;\n } | null>(null);\n\n const [url, setUrl] = useState<string | null>(null);\n const [natural, setNatural] = useState<Size | null>(null);\n const [frame, setFrame] = useState<Size>({ width: 0, height: 0 });\n const [zoom, setZoom] = useState(1);\n const [offset, setOffset] = useState<Offset>({ x: 0, y: 0 });\n\n /**\n * Resolve `src` to a displayable URL.\n *\n * A `File`/`Blob` needs `createObjectURL`, and the URL must be revoked when the\n * source changes or the component unmounts — otherwise every re-pick of a photo\n * leaks the previous one for the lifetime of the document.\n */\n useEffect(() => {\n if (typeof src === \"string\") {\n setUrl(src);\n return;\n }\n const objectUrl = URL.createObjectURL(src);\n setUrl(objectUrl);\n return () => URL.revokeObjectURL(objectUrl);\n }, [src]);\n\n // A new source invalidates the previous framing.\n useEffect(() => {\n setNatural(null);\n setZoom(1);\n setOffset({ x: 0, y: 0 });\n }, [url]);\n\n /** Track the frame's rendered size — the crop math is all relative to it. */\n useEffect(() => {\n const element = frameRef.current;\n if (!element) return;\n const measure = () =>\n setFrame({ width: element.clientWidth, height: element.clientHeight });\n measure();\n if (typeof ResizeObserver === \"undefined\") return;\n const observer = new ResizeObserver(measure);\n observer.observe(element);\n return () => observer.disconnect();\n }, []);\n\n const scale = natural ? coverScale(natural, frame) * zoom : 0;\n\n /**\n * On-screen image size.\n *\n * Memoized because the pan callback depends on it: a fresh object every render\n * would rebuild that callback every render, and the pointer handlers close over\n * it during a drag.\n */\n const displayed = useMemo<Size>(\n () =>\n natural\n ? { width: natural.width * scale, height: natural.height * scale }\n : { width: 0, height: 0 },\n [natural, scale],\n );\n\n /** Apply a pan, clamped so the frame stays covered. */\n const pan = useCallback(\n (next: Offset) => {\n setOffset((current) => {\n const clamped = clampOffset(next, displayed, frame);\n if (clamped.x === current.x && clamped.y === current.y) return current;\n onCropChange?.({ zoom, offset: clamped });\n return clamped;\n });\n },\n [displayed, frame, onCropChange, zoom],\n );\n\n /**\n * Apply a zoom, then re-clamp the offset.\n *\n * Re-clamping is not optional: zooming *out* shrinks the image, so an offset\n * that was legal a moment ago can now expose background.\n */\n const applyZoom = useCallback(\n (next: number) => {\n const clampedZoom = Math.min(maxZoom, Math.max(1, next));\n setZoom(clampedZoom);\n if (!natural) return;\n const nextScale = coverScale(natural, frame) * clampedZoom;\n const nextDisplayed = {\n width: natural.width * nextScale,\n height: natural.height * nextScale,\n };\n setOffset((current) => {\n const clamped = clampOffset(current, nextDisplayed, frame);\n onCropChange?.({ zoom: clampedZoom, offset: clamped });\n return clamped;\n });\n },\n [frame, maxZoom, natural, onCropChange],\n );\n\n const reset = useCallback(() => {\n setZoom(1);\n setOffset({ x: 0, y: 0 });\n onCropChange?.({ zoom: 1, offset: { x: 0, y: 0 } });\n }, [onCropChange]);\n\n /**\n * Draw the current crop and encode it.\n *\n * Returns `null` rather than throwing on the paths a caller cannot do anything\n * about: no image yet, no 2D context, or an encoder that declined.\n */\n const crop = useCallback(async (): Promise<Blob | null> => {\n const image = imageRef.current;\n if (!image || !natural) return null;\n\n const rect = computeCropRect({ image: natural, frame, zoom, offset });\n if (rect.sWidth <= 0 || rect.sHeight <= 0) return null;\n\n const out = outputSize(rect, maxSize);\n const canvas = document.createElement(\"canvas\");\n canvas.width = out.width;\n canvas.height = out.height;\n const context = canvas.getContext(\"2d\");\n if (!context) return null;\n\n context.drawImage(\n image,\n rect.sx,\n rect.sy,\n rect.sWidth,\n rect.sHeight,\n 0,\n 0,\n out.width,\n out.height,\n );\n\n return new Promise((resolve) => {\n canvas.toBlob((blob) => resolve(blob), outputType, outputQuality);\n });\n }, [frame, maxSize, natural, offset, outputQuality, outputType, zoom]);\n\n useImperativeHandle(ref, () => ({ crop, reset }), [crop, reset]);\n\n const onPointerDown = (event: ReactPointerEvent<HTMLDivElement>): void => {\n if (!natural) return;\n dragRef.current = {\n pointerId: event.pointerId,\n startX: event.clientX,\n startY: event.clientY,\n from: offset,\n };\n event.currentTarget.setPointerCapture?.(event.pointerId);\n };\n\n const onPointerMove = (event: ReactPointerEvent<HTMLDivElement>): void => {\n const drag = dragRef.current;\n if (!drag || drag.pointerId !== event.pointerId) return;\n pan({\n x: drag.from.x + (event.clientX - drag.startX),\n y: drag.from.y + (event.clientY - drag.startY),\n });\n };\n\n const endDrag = (event: ReactPointerEvent<HTMLDivElement>): void => {\n if (dragRef.current?.pointerId !== event.pointerId) return;\n dragRef.current = null;\n };\n\n const onKeyDown = (event: KeyboardEvent<HTMLDivElement>): void => {\n const step = event.shiftKey ? KEY_STEP * 4 : KEY_STEP;\n const moves: Record<string, Offset> = {\n ArrowLeft: { x: -step, y: 0 },\n ArrowRight: { x: step, y: 0 },\n ArrowUp: { x: 0, y: -step },\n ArrowDown: { x: 0, y: step },\n };\n const move = moves[event.key];\n if (move) {\n event.preventDefault();\n pan({ x: offset.x + move.x, y: offset.y + move.y });\n return;\n }\n if (event.key === \"+\" || event.key === \"=\") {\n event.preventDefault();\n applyZoom(zoom + ZOOM_STEP);\n } else if (event.key === \"-\" || event.key === \"_\") {\n event.preventDefault();\n applyZoom(zoom - ZOOM_STEP);\n } else if (event.key === \"0\") {\n event.preventDefault();\n reset();\n }\n };\n\n return (\n <div className={cn(styles.wrapper, className)} {...rest}>\n <div\n ref={frameRef}\n className={cn(styles.frame, shape === \"circle\" && styles.circle)}\n style={{ aspectRatio: String(aspect) }}\n role=\"group\"\n aria-label={label}\n aria-describedby={hintId}\n tabIndex={0}\n onPointerDown={onPointerDown}\n onPointerMove={onPointerMove}\n onPointerUp={endDrag}\n onPointerCancel={endDrag}\n onKeyDown={onKeyDown}\n onWheel={(event) => {\n event.preventDefault();\n applyZoom(zoom + (event.deltaY < 0 ? ZOOM_STEP : -ZOOM_STEP));\n }}\n >\n {url && (\n <img\n ref={imageRef}\n src={url}\n alt=\"\"\n draggable={false}\n className={styles.image}\n style={{\n width: displayed.width || undefined,\n height: displayed.height || undefined,\n transform: `translate(${offset.x}px, ${offset.y}px)`,\n }}\n onLoad={(event) => {\n const element = event.currentTarget;\n // A decode can succeed and still report no intrinsic size —\n // an SVG without a viewBox is the common case. Accepting\n // that would enable the controls over an image the crop\n // maths can do nothing with.\n if (element.naturalWidth > 0 && element.naturalHeight > 0) {\n setNatural({\n width: element.naturalWidth,\n height: element.naturalHeight,\n });\n }\n }}\n />\n )}\n </div>\n\n <div className={styles.controls}>\n <input\n type=\"range\"\n className={styles.zoom}\n min={1}\n max={maxZoom}\n step={0.01}\n value={zoom}\n onChange={(event) => applyZoom(Number(event.target.value))}\n aria-label=\"Zoom\"\n disabled={!natural}\n />\n <button type=\"button\" className={styles.reset} onClick={reset} disabled={!natural}>\n Centralizar\n </button>\n </div>\n\n <p id={hintId} className={styles.hint}>\n Arraste para reposicionar. Setas movem, <kbd>+</kbd> e <kbd>−</kbd> dão zoom,{\" \"}\n <kbd>0</kbd> centraliza.\n </p>\n </div>\n );\n}\n"],"mappings":";;;;;;AAyEA,IAAM,IAAW,IAGX,IAAY;AAuBlB,SAAgB,EAAa,EACzB,QACA,YAAS,GACT,aAAU,GACV,YACA,gBAAa,aACb,mBAAgB,KAChB,WAAQ,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AAW;KACX,UAAU,CAAC;IACd,CAAA,GACD,kBAAC,UAAD;KAAQ,MAAK;KAAS,WAAW,EAAO;KAAO,SAAS;KAAO,UAAU,CAAC;KAAS,UAAA;IAE3E,CAAA,CACP;;GAEL,kBAAC,KAAD;IAAG,IAAI;IAAQ,WAAW,EAAO;IAAjC,UAAA;KAAuC;KACK,kBAAC,OAAD,EAAA,UAAK,IAAM,CAAA;KAAC;KAAG,kBAAC,OAAD,EAAA,UAAK,IAAM,CAAA;KAAC;KAAW;KAC9E,kBAAC,OAAD,EAAA,UAAK,IAAM,CAAA;KAAC;IACb;;EACF;;AAEb"}
1
+ {"version":3,"file":"ImageCropper.js","names":[],"sources":["../../../src/components/ImageCropper/ImageCropper.tsx"],"sourcesContent":["/**\n * @tempest-limits file-lines, props-count, function-lines — pointer drag, wheel\n * zoom, aspect clamping and canvas export share one piece of geometry state, and the\n * props are the two halves of that: the frame (aspect, shape, maxZoom, label) and\n * the export (maxSize, outputType, outputQuality, onCropChange, ref). Threading the\n * geometry through props would duplicate the clamp maths.\n */\nimport {\n type HTMLAttributes,\n type KeyboardEvent,\n type PointerEvent as ReactPointerEvent,\n useCallback,\n useEffect,\n useId,\n useImperativeHandle,\n useMemo,\n useRef,\n useState,\n} from \"react\";\n\nimport { cn } from \"@/utils/cn\";\n\nimport {\n clampOffset,\n computeCropRect,\n coverScale,\n type Offset,\n outputSize,\n type Size,\n} from \"./crop-geometry\";\nimport styles from \"./ImageCropper.module.css\";\n\n/** Imperative handle for exporting the current crop. */\nexport interface ImageCropperHandle {\n /**\n * Render the current crop and resolve with it.\n *\n * Resolves `null` when the image has not loaded yet or the browser refuses to\n * encode — never throws, so a submit handler does not need a try/catch.\n */\n crop: () => Promise<Blob | null>;\n /** Recentre at zoom 1. */\n reset: () => void;\n}\n\nexport interface ImageCropperProps extends Omit<HTMLAttributes<HTMLDivElement>, \"children\"> {\n /** The image to crop: a `File`/`Blob` from an input, or a URL. */\n src: File | Blob | string;\n /** Crop aspect ratio as `width / height`. Default `1` (square). */\n aspect?: number;\n /** Maximum zoom over the cover scale. Default `4`. */\n maxZoom?: number;\n /**\n * Cap on the longest edge of the exported image, in px.\n *\n * Without it the export keeps the source resolution, which is right for a\n * document scan and wasteful for an avatar.\n */\n maxSize?: number;\n /** Output MIME type. Default `\"image/png\"`. */\n outputType?: string;\n /** Output quality for lossy types, `0`–`1`. Default `0.92`. */\n outputQuality?: number;\n /** Overlay shape. `\"circle\"` for an avatar, `\"rect\"` for a document. Default `\"rect\"`. */\n shape?: \"rect\" | \"circle\";\n /** Called whenever the crop changes, e.g. to enable a submit button. */\n onCropChange?: (state: { zoom: number; offset: Offset }) => void;\n /** Accessible name for the crop area. */\n label?: string;\n ref?: React.Ref<ImageCropperHandle>;\n}\n\n/** Pixels moved per arrow-key press. */\nconst KEY_STEP = 12;\n\n/** Zoom added or removed per `+`/`-` press, and per wheel notch. */\nconst ZOOM_STEP = 0.15;\n\n/**\n * Crop an image to a fixed aspect ratio.\n *\n * The frame stays put and the image pans and zooms behind it — the model an avatar\n * or document-photo flow wants, where the output shape is decided by the app and\n * the user only chooses what lands inside it. (A free-form draggable rectangle is a\n * different component; this one cannot produce an off-ratio crop by construction.)\n *\n * The export reads the *natural* pixels through a canvas, so a 4000 px photo is not\n * silently downsampled to whatever the on-screen preview measured. The image is\n * also always clamped to cover the frame, so an export can never contain the empty\n * bands you get from panning past an edge.\n *\n * Works by pointer, wheel and keyboard: arrows pan, `+`/`-` zoom, `0` resets.\n *\n * @example\n * const cropper = useRef<ImageCropperHandle>(null);\n *\n * <ImageCropper ref={cropper} src={file} aspect={1} shape=\"circle\" maxSize={512} />\n * <Button onClick={async () => upload(await cropper.current?.crop())}>Salvar</Button>\n */\nexport function ImageCropper({\n src,\n aspect = 1,\n maxZoom = 4,\n maxSize,\n outputType = \"image/png\",\n outputQuality = 0.92,\n shape = \"rect\",\n onCropChange,\n label = \"Área de recorte\",\n className,\n ref,\n ...rest\n}: ImageCropperProps) {\n /**\n * Id for the shortcut hint.\n *\n * Generated rather than derived from `label`: a label with spaces would produce\n * an id with spaces, and `aria-describedby` splits on whitespace — so the\n * description would silently never associate with the frame.\n */\n const hintId = `${useId()}-hint`;\n\n const frameRef = useRef<HTMLDivElement>(null);\n const imageRef = useRef<HTMLImageElement | null>(null);\n const dragRef = useRef<{\n pointerId: number;\n startX: number;\n startY: number;\n from: Offset;\n } | null>(null);\n\n const [url, setUrl] = useState<string | null>(null);\n const [natural, setNatural] = useState<Size | null>(null);\n const [frame, setFrame] = useState<Size>({ width: 0, height: 0 });\n const [zoom, setZoom] = useState(1);\n const [offset, setOffset] = useState<Offset>({ x: 0, y: 0 });\n\n /**\n * Resolve `src` to a displayable URL.\n *\n * A `File`/`Blob` needs `createObjectURL`, and the URL must be revoked when the\n * source changes or the component unmounts — otherwise every re-pick of a photo\n * leaks the previous one for the lifetime of the document.\n */\n useEffect(() => {\n if (typeof src === \"string\") {\n setUrl(src);\n return;\n }\n const objectUrl = URL.createObjectURL(src);\n setUrl(objectUrl);\n return () => URL.revokeObjectURL(objectUrl);\n }, [src]);\n\n // A new source invalidates the previous framing.\n useEffect(() => {\n setNatural(null);\n setZoom(1);\n setOffset({ x: 0, y: 0 });\n }, [url]);\n\n /** Track the frame's rendered size — the crop math is all relative to it. */\n useEffect(() => {\n const element = frameRef.current;\n if (!element) return;\n const measure = () =>\n setFrame({ width: element.clientWidth, height: element.clientHeight });\n measure();\n if (typeof ResizeObserver === \"undefined\") return;\n const observer = new ResizeObserver(measure);\n observer.observe(element);\n return () => observer.disconnect();\n }, []);\n\n const scale = natural ? coverScale(natural, frame) * zoom : 0;\n\n /**\n * On-screen image size.\n *\n * Memoized because the pan callback depends on it: a fresh object every render\n * would rebuild that callback every render, and the pointer handlers close over\n * it during a drag.\n */\n const displayed = useMemo<Size>(\n () =>\n natural\n ? { width: natural.width * scale, height: natural.height * scale }\n : { width: 0, height: 0 },\n [natural, scale],\n );\n\n /** Apply a pan, clamped so the frame stays covered. */\n const pan = useCallback(\n (next: Offset) => {\n setOffset((current) => {\n const clamped = clampOffset(next, displayed, frame);\n if (clamped.x === current.x && clamped.y === current.y) return current;\n onCropChange?.({ zoom, offset: clamped });\n return clamped;\n });\n },\n [displayed, frame, onCropChange, zoom],\n );\n\n /**\n * Apply a zoom, then re-clamp the offset.\n *\n * Re-clamping is not optional: zooming *out* shrinks the image, so an offset\n * that was legal a moment ago can now expose background.\n */\n const applyZoom = useCallback(\n (next: number) => {\n const clampedZoom = Math.min(maxZoom, Math.max(1, next));\n setZoom(clampedZoom);\n if (!natural) return;\n const nextScale = coverScale(natural, frame) * clampedZoom;\n const nextDisplayed = {\n width: natural.width * nextScale,\n height: natural.height * nextScale,\n };\n setOffset((current) => {\n const clamped = clampOffset(current, nextDisplayed, frame);\n onCropChange?.({ zoom: clampedZoom, offset: clamped });\n return clamped;\n });\n },\n [frame, maxZoom, natural, onCropChange],\n );\n\n const reset = useCallback(() => {\n setZoom(1);\n setOffset({ x: 0, y: 0 });\n onCropChange?.({ zoom: 1, offset: { x: 0, y: 0 } });\n }, [onCropChange]);\n\n /**\n * Draw the current crop and encode it.\n *\n * Returns `null` rather than throwing on the paths a caller cannot do anything\n * about: no image yet, no 2D context, or an encoder that declined.\n */\n const crop = useCallback(async (): Promise<Blob | null> => {\n const image = imageRef.current;\n if (!image || !natural) return null;\n\n const rect = computeCropRect({ image: natural, frame, zoom, offset });\n if (rect.sWidth <= 0 || rect.sHeight <= 0) return null;\n\n const out = outputSize(rect, maxSize);\n const canvas = document.createElement(\"canvas\");\n canvas.width = out.width;\n canvas.height = out.height;\n const context = canvas.getContext(\"2d\");\n if (!context) return null;\n\n context.drawImage(\n image,\n rect.sx,\n rect.sy,\n rect.sWidth,\n rect.sHeight,\n 0,\n 0,\n out.width,\n out.height,\n );\n\n return new Promise((resolve) => {\n canvas.toBlob((blob) => resolve(blob), outputType, outputQuality);\n });\n }, [frame, maxSize, natural, offset, outputQuality, outputType, zoom]);\n\n useImperativeHandle(ref, () => ({ crop, reset }), [crop, reset]);\n\n const onPointerDown = (event: ReactPointerEvent<HTMLDivElement>): void => {\n if (!natural) return;\n dragRef.current = {\n pointerId: event.pointerId,\n startX: event.clientX,\n startY: event.clientY,\n from: offset,\n };\n event.currentTarget.setPointerCapture?.(event.pointerId);\n };\n\n const onPointerMove = (event: ReactPointerEvent<HTMLDivElement>): void => {\n const drag = dragRef.current;\n if (!drag || drag.pointerId !== event.pointerId) return;\n pan({\n x: drag.from.x + (event.clientX - drag.startX),\n y: drag.from.y + (event.clientY - drag.startY),\n });\n };\n\n const endDrag = (event: ReactPointerEvent<HTMLDivElement>): void => {\n if (dragRef.current?.pointerId !== event.pointerId) return;\n dragRef.current = null;\n };\n\n const onKeyDown = (event: KeyboardEvent<HTMLDivElement>): void => {\n const step = event.shiftKey ? KEY_STEP * 4 : KEY_STEP;\n const moves: Record<string, Offset> = {\n ArrowLeft: { x: -step, y: 0 },\n ArrowRight: { x: step, y: 0 },\n ArrowUp: { x: 0, y: -step },\n ArrowDown: { x: 0, y: step },\n };\n const move = moves[event.key];\n if (move) {\n event.preventDefault();\n pan({ x: offset.x + move.x, y: offset.y + move.y });\n return;\n }\n if (event.key === \"+\" || event.key === \"=\") {\n event.preventDefault();\n applyZoom(zoom + ZOOM_STEP);\n } else if (event.key === \"-\" || event.key === \"_\") {\n event.preventDefault();\n applyZoom(zoom - ZOOM_STEP);\n } else if (event.key === \"0\") {\n event.preventDefault();\n reset();\n }\n };\n\n return (\n <div className={cn(styles.wrapper, className)} {...rest}>\n <div\n ref={frameRef}\n className={cn(styles.frame, shape === \"circle\" && styles.circle)}\n style={{ aspectRatio: String(aspect) }}\n role=\"group\"\n aria-label={label}\n aria-describedby={hintId}\n tabIndex={0}\n onPointerDown={onPointerDown}\n onPointerMove={onPointerMove}\n onPointerUp={endDrag}\n onPointerCancel={endDrag}\n onKeyDown={onKeyDown}\n onWheel={(event) => {\n event.preventDefault();\n applyZoom(zoom + (event.deltaY < 0 ? ZOOM_STEP : -ZOOM_STEP));\n }}\n >\n {url && (\n <img\n ref={imageRef}\n src={url}\n alt=\"\"\n draggable={false}\n className={styles.image}\n style={{\n width: displayed.width || undefined,\n height: displayed.height || undefined,\n transform: `translate(${offset.x}px, ${offset.y}px)`,\n }}\n onLoad={(event) => {\n const element = event.currentTarget;\n // A decode can succeed and still report no intrinsic size —\n // an SVG without a viewBox is the common case. Accepting\n // that would enable the controls over an image the crop\n // maths can do nothing with.\n if (element.naturalWidth > 0 && element.naturalHeight > 0) {\n setNatural({\n width: element.naturalWidth,\n height: element.naturalHeight,\n });\n }\n }}\n />\n )}\n </div>\n\n <div className={styles.controls}>\n <input\n type=\"range\"\n className={styles.zoom}\n min={1}\n max={maxZoom}\n step={0.01}\n value={zoom}\n onChange={(event) => applyZoom(Number(event.target.value))}\n aria-label=\"Zoom\"\n disabled={!natural}\n />\n <button type=\"button\" className={styles.reset} onClick={reset} disabled={!natural}>\n Centralizar\n </button>\n </div>\n\n <p id={hintId} className={styles.hint}>\n Arraste para reposicionar. Setas movem, <kbd>+</kbd> e <kbd>−</kbd> dão zoom,{\" \"}\n <kbd>0</kbd> centraliza.\n </p>\n </div>\n );\n}\n"],"mappings":";;;;;;AAyEA,IAAM,IAAW,IAGX,IAAY;AAuBlB,SAAgB,EAAa,EACzB,QACA,YAAS,GACT,aAAU,GACV,YACA,gBAAa,aACb,mBAAgB,KAChB,WAAQ,QACR,iBACA,WAAQ,mBACR,cACA,QACA,GAAG,KACe;CAQlB,IAAM,IAAS,GAAG,EAAM,EAAE,QAEpB,IAAW,EAAuB,IAAI,GACtC,IAAW,EAAgC,IAAI,GAC/C,IAAU,EAKN,IAAI,GAER,CAAC,GAAK,KAAU,EAAwB,IAAI,GAC5C,CAAC,GAAS,KAAc,EAAsB,IAAI,GAClD,CAAC,GAAO,KAAY,EAAe;EAAE,OAAO;EAAG,QAAQ;CAAE,CAAC,GAC1D,CAAC,GAAM,KAAW,EAAS,CAAC,GAC5B,CAAC,GAAQ,KAAa,EA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;IACb;;EACF;;AAEb"}
@@ -1 +1 @@
1
- {"version":3,"file":"Scheduler.module.cjs","names":[],"sources":["../../../src/components/Scheduler/Scheduler.module.css"],"sourcesContent":[".wrapper {\n /*\n * Column widths are declared once here and reused by the header, the all-day\n * lane and the grid — three separate grids that have to line up exactly, and\n * would drift the moment any of them computed its own tracks.\n */\n --tempest-scheduler-gutter: 3.5rem;\n --tempest-scheduler-height: 32rem;\n\n display: flex;\n flex-direction: column;\n width: 100%;\n border: 1px solid var(--tempest-border);\n border-radius: var(--tempest-radius-lg);\n background-color: var(--tempest-bg);\n font-family: var(--tempest-font-sans);\n overflow: hidden;\n}\n\n.head,\n.allDayLane {\n display: grid;\n grid-template-columns: var(--tempest-scheduler-gutter) repeat(\n var(--tempest-scheduler-days),\n minmax(0, 1fr)\n );\n border-bottom: 1px solid var(--tempest-border);\n background-color: var(--tempest-surface);\n}\n\n.dayHead {\n padding: var(--tempest-space-2);\n text-align: center;\n color: var(--tempest-text-muted);\n font-size: var(--tempest-text-xs);\n font-weight: var(--tempest-weight-semibold);\n letter-spacing: var(--tempest-tracking-wide);\n text-transform: capitalize;\n border-left: 1px solid var(--tempest-border);\n}\n\n.dayHead.today {\n color: var(--tempest-primary);\n}\n\n.gutterHead {\n padding: var(--tempest-space-2);\n color: var(--tempest-text-muted);\n font-size: 0.625rem;\n text-align: right;\n}\n\n.allDayTrack {\n display: grid;\n grid-template-columns: repeat(var(--tempest-scheduler-days), minmax(0, 1fr));\n grid-column: 2 / -1;\n gap: 2px;\n padding: 2px;\n}\n\n.allDayEvent {\n overflow: hidden;\n padding: 0 var(--tempest-space-2);\n border: none;\n border-radius: var(--tempest-radius-sm);\n background-color: var(--tempest-primary);\n color: var(--tempest-primary-contrast, #fff);\n font: inherit;\n font-size: var(--tempest-text-xs);\n line-height: 1.5rem;\n text-align: left;\n text-overflow: ellipsis;\n white-space: nowrap;\n cursor: pointer;\n}\n\n.allDayEvent:disabled {\n cursor: default;\n}\n\n.body {\n display: grid;\n grid-template-columns: var(--tempest-scheduler-gutter) 1fr;\n height: var(--tempest-scheduler-height);\n overflow-y: auto;\n}\n\n.gutter {\n position: relative;\n border-right: 1px solid var(--tempest-border);\n}\n\n.hourLabel {\n position: absolute;\n right: var(--tempest-space-1);\n /*\n * Nudged up by half a line so the label reads as sitting *on* its hour line\n * rather than hanging below it.\n */\n transform: translateY(-50%);\n color: var(--tempest-text-muted);\n font-size: 0.625rem;\n font-variant-numeric: tabular-nums;\n}\n\n.grid {\n position: relative;\n display: grid;\n grid-template-columns: repeat(var(--tempest-scheduler-days), minmax(0, 1fr));\n}\n\n.dayColumn {\n position: relative;\n grid-row: 1;\n border-left: 1px solid var(--tempest-border);\n}\n\n.dayColumn:first-child {\n border-left: none;\n}\n\n.todayColumn {\n background-color: var(--tempest-surface);\n}\n\n.hourLine {\n position: absolute;\n left: 0;\n right: 0;\n border-top: 1px solid var(--tempest-border);\n pointer-events: none;\n}\n\n/*\n * Events live in the same grid as the day columns, one row deep, positioned inside\n * their column by percentage. Being siblings of the columns rather than children is\n * what lets an event overlay the hour lines without clipping.\n */\n/*\n * Absolutely positioned, so the inline `grid-column` it is placed with must name\n * BOTH lines. For an abspos child of a grid container an `auto` side does not\n * mean \"span 1\" — CSS Grid §9.2 resolves it to the container's padding edge, so\n * a bare `grid-column: 3` runs from column 3 to the end of the week and every\n * event covers the whole view. A one-day scheduler hides it: there, \"column 1 to\n * the edge\" happens to be one column. Hence `N / span 1` in Scheduler.tsx.\n */\n.event {\n position: absolute;\n grid-row: 1;\n display: flex;\n flex-direction: column;\n gap: 1px;\n overflow: hidden;\n padding: 2px var(--tempest-space-1);\n border: 1px solid var(--tempest-bg);\n border-radius: var(--tempest-radius-sm);\n background-color: var(--tempest-primary);\n color: var(--tempest-primary-contrast, #fff);\n font: inherit;\n text-align: left;\n cursor: pointer;\n}\n\n.event:disabled {\n cursor: default;\n}\n\n.event:focus-visible {\n outline: 2px solid var(--tempest-text);\n outline-offset: -2px;\n}\n\n/*\n * No `opacity` here, deliberately. Dimming the time to signal it as secondary drops\n * it below the AA contrast threshold against the event fill — the browser `axe` sweep\n * caught exactly that (jsdom cannot, since it does not paint). The hierarchy comes\n * from size and weight instead, which cost nothing in contrast.\n */\n.eventTime {\n font-size: 0.625rem;\n font-variant-numeric: tabular-nums;\n}\n\n.eventTitle {\n font-size: var(--tempest-text-xs);\n font-weight: var(--tempest-weight-medium);\n line-height: var(--tempest-leading-snug);\n overflow: hidden;\n text-overflow: ellipsis;\n}\n\n.nowLine {\n position: absolute;\n left: 0;\n right: 0;\n grid-row: 1;\n grid-column: 1 / -1;\n height: 0;\n border-top: 2px solid var(--tempest-danger, #dc2626);\n pointer-events: none;\n z-index: 1;\n}\n\n@media (max-width: 640px) {\n .wrapper {\n --tempest-scheduler-gutter: 2.75rem;\n }\n\n .dayHead {\n font-size: 0.625rem;\n padding: var(--tempest-space-1);\n }\n}\n"],"mappings":""}
1
+ {"version":3,"file":"Scheduler.module.cjs","names":[],"sources":["../../../src/components/Scheduler/Scheduler.module.css"],"sourcesContent":[".wrapper {\n /*\n * Column widths are declared once here and reused by the header, the all-day\n * lane and the grid — three separate grids that have to line up exactly, and\n * would drift the moment any of them computed its own tracks.\n */\n --tempest-scheduler-gutter: 3.5rem;\n --tempest-scheduler-height: 32rem;\n\n display: flex;\n flex-direction: column;\n width: 100%;\n border: 1px solid var(--tempest-border);\n border-radius: var(--tempest-radius-lg);\n background-color: var(--tempest-bg);\n font-family: var(--tempest-font-sans);\n overflow: hidden;\n}\n\n.head,\n.allDayLane {\n display: grid;\n grid-template-columns: var(--tempest-scheduler-gutter) repeat(\n var(--tempest-scheduler-days),\n minmax(0, 1fr)\n );\n border-bottom: 1px solid var(--tempest-border);\n background-color: var(--tempest-surface);\n}\n\n.dayHead {\n padding: var(--tempest-space-2);\n text-align: center;\n color: var(--tempest-text-muted);\n font-size: var(--tempest-text-xs);\n font-weight: var(--tempest-weight-semibold);\n letter-spacing: var(--tempest-tracking-wide);\n text-transform: capitalize;\n border-left: 1px solid var(--tempest-border);\n}\n\n.dayHead.today {\n color: var(--tempest-primary);\n}\n\n.gutterHead {\n padding: var(--tempest-space-2);\n color: var(--tempest-text-muted);\n font-size: 0.625rem;\n text-align: right;\n}\n\n.allDayTrack {\n display: grid;\n grid-template-columns: repeat(var(--tempest-scheduler-days), minmax(0, 1fr));\n grid-column: 2 / -1;\n gap: 2px;\n padding: 2px;\n}\n\n.allDayEvent {\n overflow: hidden;\n padding: 0 var(--tempest-space-2);\n border: none;\n border-radius: var(--tempest-radius-sm);\n background-color: var(--tempest-primary);\n color: var(--tempest-primary-foreground);\n font: inherit;\n font-size: var(--tempest-text-xs);\n line-height: 1.5rem;\n text-align: left;\n text-overflow: ellipsis;\n white-space: nowrap;\n cursor: pointer;\n}\n\n.allDayEvent:disabled {\n cursor: default;\n}\n\n.body {\n display: grid;\n grid-template-columns: var(--tempest-scheduler-gutter) 1fr;\n height: var(--tempest-scheduler-height);\n overflow-y: auto;\n}\n\n.gutter {\n position: relative;\n border-right: 1px solid var(--tempest-border);\n}\n\n.hourLabel {\n position: absolute;\n right: var(--tempest-space-1);\n /*\n * Nudged up by half a line so the label reads as sitting *on* its hour line\n * rather than hanging below it.\n */\n transform: translateY(-50%);\n color: var(--tempest-text-muted);\n font-size: 0.625rem;\n font-variant-numeric: tabular-nums;\n}\n\n.grid {\n position: relative;\n display: grid;\n grid-template-columns: repeat(var(--tempest-scheduler-days), minmax(0, 1fr));\n}\n\n.dayColumn {\n position: relative;\n grid-row: 1;\n border-left: 1px solid var(--tempest-border);\n}\n\n.dayColumn:first-child {\n border-left: none;\n}\n\n.todayColumn {\n background-color: var(--tempest-surface);\n}\n\n.hourLine {\n position: absolute;\n left: 0;\n right: 0;\n border-top: 1px solid var(--tempest-border);\n pointer-events: none;\n}\n\n/*\n * Events live in the same grid as the day columns, one row deep, positioned inside\n * their column by percentage. Being siblings of the columns rather than children is\n * what lets an event overlay the hour lines without clipping.\n */\n/*\n * Absolutely positioned, so the inline `grid-column` it is placed with must name\n * BOTH lines. For an abspos child of a grid container an `auto` side does not\n * mean \"span 1\" — CSS Grid §9.2 resolves it to the container's padding edge, so\n * a bare `grid-column: 3` runs from column 3 to the end of the week and every\n * event covers the whole view. A one-day scheduler hides it: there, \"column 1 to\n * the edge\" happens to be one column. Hence `N / span 1` in Scheduler.tsx.\n */\n.event {\n position: absolute;\n grid-row: 1;\n display: flex;\n flex-direction: column;\n gap: 1px;\n overflow: hidden;\n padding: 2px var(--tempest-space-1);\n border: 1px solid var(--tempest-bg);\n border-radius: var(--tempest-radius-sm);\n background-color: var(--tempest-primary);\n color: var(--tempest-primary-foreground);\n font: inherit;\n text-align: left;\n cursor: pointer;\n}\n\n.event:disabled {\n cursor: default;\n}\n\n.event:focus-visible {\n outline: 2px solid var(--tempest-text);\n outline-offset: -2px;\n}\n\n/*\n * No `opacity` here, deliberately. Dimming the time to signal it as secondary drops\n * it below the AA contrast threshold against the event fill — the browser `axe` sweep\n * caught exactly that (jsdom cannot, since it does not paint). The hierarchy comes\n * from size and weight instead, which cost nothing in contrast.\n */\n.eventTime {\n font-size: 0.625rem;\n font-variant-numeric: tabular-nums;\n}\n\n.eventTitle {\n font-size: var(--tempest-text-xs);\n font-weight: var(--tempest-weight-medium);\n line-height: var(--tempest-leading-snug);\n overflow: hidden;\n text-overflow: ellipsis;\n}\n\n.nowLine {\n position: absolute;\n left: 0;\n right: 0;\n grid-row: 1;\n grid-column: 1 / -1;\n height: 0;\n border-top: 2px solid var(--tempest-danger, #dc2626);\n pointer-events: none;\n z-index: 1;\n}\n\n@media (max-width: 640px) {\n .wrapper {\n --tempest-scheduler-gutter: 2.75rem;\n }\n\n .dayHead {\n font-size: 0.625rem;\n padding: var(--tempest-space-1);\n }\n}\n"],"mappings":""}
@@ -1 +1 @@
1
- {"version":3,"file":"Scheduler.module.js","names":[],"sources":["../../../src/components/Scheduler/Scheduler.module.css"],"sourcesContent":[".wrapper {\n /*\n * Column widths are declared once here and reused by the header, the all-day\n * lane and the grid — three separate grids that have to line up exactly, and\n * would drift the moment any of them computed its own tracks.\n */\n --tempest-scheduler-gutter: 3.5rem;\n --tempest-scheduler-height: 32rem;\n\n display: flex;\n flex-direction: column;\n width: 100%;\n border: 1px solid var(--tempest-border);\n border-radius: var(--tempest-radius-lg);\n background-color: var(--tempest-bg);\n font-family: var(--tempest-font-sans);\n overflow: hidden;\n}\n\n.head,\n.allDayLane {\n display: grid;\n grid-template-columns: var(--tempest-scheduler-gutter) repeat(\n var(--tempest-scheduler-days),\n minmax(0, 1fr)\n );\n border-bottom: 1px solid var(--tempest-border);\n background-color: var(--tempest-surface);\n}\n\n.dayHead {\n padding: var(--tempest-space-2);\n text-align: center;\n color: var(--tempest-text-muted);\n font-size: var(--tempest-text-xs);\n font-weight: var(--tempest-weight-semibold);\n letter-spacing: var(--tempest-tracking-wide);\n text-transform: capitalize;\n border-left: 1px solid var(--tempest-border);\n}\n\n.dayHead.today {\n color: var(--tempest-primary);\n}\n\n.gutterHead {\n padding: var(--tempest-space-2);\n color: var(--tempest-text-muted);\n font-size: 0.625rem;\n text-align: right;\n}\n\n.allDayTrack {\n display: grid;\n grid-template-columns: repeat(var(--tempest-scheduler-days), minmax(0, 1fr));\n grid-column: 2 / -1;\n gap: 2px;\n padding: 2px;\n}\n\n.allDayEvent {\n overflow: hidden;\n padding: 0 var(--tempest-space-2);\n border: none;\n border-radius: var(--tempest-radius-sm);\n background-color: var(--tempest-primary);\n color: var(--tempest-primary-contrast, #fff);\n font: inherit;\n font-size: var(--tempest-text-xs);\n line-height: 1.5rem;\n text-align: left;\n text-overflow: ellipsis;\n white-space: nowrap;\n cursor: pointer;\n}\n\n.allDayEvent:disabled {\n cursor: default;\n}\n\n.body {\n display: grid;\n grid-template-columns: var(--tempest-scheduler-gutter) 1fr;\n height: var(--tempest-scheduler-height);\n overflow-y: auto;\n}\n\n.gutter {\n position: relative;\n border-right: 1px solid var(--tempest-border);\n}\n\n.hourLabel {\n position: absolute;\n right: var(--tempest-space-1);\n /*\n * Nudged up by half a line so the label reads as sitting *on* its hour line\n * rather than hanging below it.\n */\n transform: translateY(-50%);\n color: var(--tempest-text-muted);\n font-size: 0.625rem;\n font-variant-numeric: tabular-nums;\n}\n\n.grid {\n position: relative;\n display: grid;\n grid-template-columns: repeat(var(--tempest-scheduler-days), minmax(0, 1fr));\n}\n\n.dayColumn {\n position: relative;\n grid-row: 1;\n border-left: 1px solid var(--tempest-border);\n}\n\n.dayColumn:first-child {\n border-left: none;\n}\n\n.todayColumn {\n background-color: var(--tempest-surface);\n}\n\n.hourLine {\n position: absolute;\n left: 0;\n right: 0;\n border-top: 1px solid var(--tempest-border);\n pointer-events: none;\n}\n\n/*\n * Events live in the same grid as the day columns, one row deep, positioned inside\n * their column by percentage. Being siblings of the columns rather than children is\n * what lets an event overlay the hour lines without clipping.\n */\n/*\n * Absolutely positioned, so the inline `grid-column` it is placed with must name\n * BOTH lines. For an abspos child of a grid container an `auto` side does not\n * mean \"span 1\" — CSS Grid §9.2 resolves it to the container's padding edge, so\n * a bare `grid-column: 3` runs from column 3 to the end of the week and every\n * event covers the whole view. A one-day scheduler hides it: there, \"column 1 to\n * the edge\" happens to be one column. Hence `N / span 1` in Scheduler.tsx.\n */\n.event {\n position: absolute;\n grid-row: 1;\n display: flex;\n flex-direction: column;\n gap: 1px;\n overflow: hidden;\n padding: 2px var(--tempest-space-1);\n border: 1px solid var(--tempest-bg);\n border-radius: var(--tempest-radius-sm);\n background-color: var(--tempest-primary);\n color: var(--tempest-primary-contrast, #fff);\n font: inherit;\n text-align: left;\n cursor: pointer;\n}\n\n.event:disabled {\n cursor: default;\n}\n\n.event:focus-visible {\n outline: 2px solid var(--tempest-text);\n outline-offset: -2px;\n}\n\n/*\n * No `opacity` here, deliberately. Dimming the time to signal it as secondary drops\n * it below the AA contrast threshold against the event fill — the browser `axe` sweep\n * caught exactly that (jsdom cannot, since it does not paint). The hierarchy comes\n * from size and weight instead, which cost nothing in contrast.\n */\n.eventTime {\n font-size: 0.625rem;\n font-variant-numeric: tabular-nums;\n}\n\n.eventTitle {\n font-size: var(--tempest-text-xs);\n font-weight: var(--tempest-weight-medium);\n line-height: var(--tempest-leading-snug);\n overflow: hidden;\n text-overflow: ellipsis;\n}\n\n.nowLine {\n position: absolute;\n left: 0;\n right: 0;\n grid-row: 1;\n grid-column: 1 / -1;\n height: 0;\n border-top: 2px solid var(--tempest-danger, #dc2626);\n pointer-events: none;\n z-index: 1;\n}\n\n@media (max-width: 640px) {\n .wrapper {\n --tempest-scheduler-gutter: 2.75rem;\n }\n\n .dayHead {\n font-size: 0.625rem;\n padding: var(--tempest-space-1);\n }\n}\n"],"mappings":""}
1
+ {"version":3,"file":"Scheduler.module.js","names":[],"sources":["../../../src/components/Scheduler/Scheduler.module.css"],"sourcesContent":[".wrapper {\n /*\n * Column widths are declared once here and reused by the header, the all-day\n * lane and the grid — three separate grids that have to line up exactly, and\n * would drift the moment any of them computed its own tracks.\n */\n --tempest-scheduler-gutter: 3.5rem;\n --tempest-scheduler-height: 32rem;\n\n display: flex;\n flex-direction: column;\n width: 100%;\n border: 1px solid var(--tempest-border);\n border-radius: var(--tempest-radius-lg);\n background-color: var(--tempest-bg);\n font-family: var(--tempest-font-sans);\n overflow: hidden;\n}\n\n.head,\n.allDayLane {\n display: grid;\n grid-template-columns: var(--tempest-scheduler-gutter) repeat(\n var(--tempest-scheduler-days),\n minmax(0, 1fr)\n );\n border-bottom: 1px solid var(--tempest-border);\n background-color: var(--tempest-surface);\n}\n\n.dayHead {\n padding: var(--tempest-space-2);\n text-align: center;\n color: var(--tempest-text-muted);\n font-size: var(--tempest-text-xs);\n font-weight: var(--tempest-weight-semibold);\n letter-spacing: var(--tempest-tracking-wide);\n text-transform: capitalize;\n border-left: 1px solid var(--tempest-border);\n}\n\n.dayHead.today {\n color: var(--tempest-primary);\n}\n\n.gutterHead {\n padding: var(--tempest-space-2);\n color: var(--tempest-text-muted);\n font-size: 0.625rem;\n text-align: right;\n}\n\n.allDayTrack {\n display: grid;\n grid-template-columns: repeat(var(--tempest-scheduler-days), minmax(0, 1fr));\n grid-column: 2 / -1;\n gap: 2px;\n padding: 2px;\n}\n\n.allDayEvent {\n overflow: hidden;\n padding: 0 var(--tempest-space-2);\n border: none;\n border-radius: var(--tempest-radius-sm);\n background-color: var(--tempest-primary);\n color: var(--tempest-primary-foreground);\n font: inherit;\n font-size: var(--tempest-text-xs);\n line-height: 1.5rem;\n text-align: left;\n text-overflow: ellipsis;\n white-space: nowrap;\n cursor: pointer;\n}\n\n.allDayEvent:disabled {\n cursor: default;\n}\n\n.body {\n display: grid;\n grid-template-columns: var(--tempest-scheduler-gutter) 1fr;\n height: var(--tempest-scheduler-height);\n overflow-y: auto;\n}\n\n.gutter {\n position: relative;\n border-right: 1px solid var(--tempest-border);\n}\n\n.hourLabel {\n position: absolute;\n right: var(--tempest-space-1);\n /*\n * Nudged up by half a line so the label reads as sitting *on* its hour line\n * rather than hanging below it.\n */\n transform: translateY(-50%);\n color: var(--tempest-text-muted);\n font-size: 0.625rem;\n font-variant-numeric: tabular-nums;\n}\n\n.grid {\n position: relative;\n display: grid;\n grid-template-columns: repeat(var(--tempest-scheduler-days), minmax(0, 1fr));\n}\n\n.dayColumn {\n position: relative;\n grid-row: 1;\n border-left: 1px solid var(--tempest-border);\n}\n\n.dayColumn:first-child {\n border-left: none;\n}\n\n.todayColumn {\n background-color: var(--tempest-surface);\n}\n\n.hourLine {\n position: absolute;\n left: 0;\n right: 0;\n border-top: 1px solid var(--tempest-border);\n pointer-events: none;\n}\n\n/*\n * Events live in the same grid as the day columns, one row deep, positioned inside\n * their column by percentage. Being siblings of the columns rather than children is\n * what lets an event overlay the hour lines without clipping.\n */\n/*\n * Absolutely positioned, so the inline `grid-column` it is placed with must name\n * BOTH lines. For an abspos child of a grid container an `auto` side does not\n * mean \"span 1\" — CSS Grid §9.2 resolves it to the container's padding edge, so\n * a bare `grid-column: 3` runs from column 3 to the end of the week and every\n * event covers the whole view. A one-day scheduler hides it: there, \"column 1 to\n * the edge\" happens to be one column. Hence `N / span 1` in Scheduler.tsx.\n */\n.event {\n position: absolute;\n grid-row: 1;\n display: flex;\n flex-direction: column;\n gap: 1px;\n overflow: hidden;\n padding: 2px var(--tempest-space-1);\n border: 1px solid var(--tempest-bg);\n border-radius: var(--tempest-radius-sm);\n background-color: var(--tempest-primary);\n color: var(--tempest-primary-foreground);\n font: inherit;\n text-align: left;\n cursor: pointer;\n}\n\n.event:disabled {\n cursor: default;\n}\n\n.event:focus-visible {\n outline: 2px solid var(--tempest-text);\n outline-offset: -2px;\n}\n\n/*\n * No `opacity` here, deliberately. Dimming the time to signal it as secondary drops\n * it below the AA contrast threshold against the event fill — the browser `axe` sweep\n * caught exactly that (jsdom cannot, since it does not paint). The hierarchy comes\n * from size and weight instead, which cost nothing in contrast.\n */\n.eventTime {\n font-size: 0.625rem;\n font-variant-numeric: tabular-nums;\n}\n\n.eventTitle {\n font-size: var(--tempest-text-xs);\n font-weight: var(--tempest-weight-medium);\n line-height: var(--tempest-leading-snug);\n overflow: hidden;\n text-overflow: ellipsis;\n}\n\n.nowLine {\n position: absolute;\n left: 0;\n right: 0;\n grid-row: 1;\n grid-column: 1 / -1;\n height: 0;\n border-top: 2px solid var(--tempest-danger, #dc2626);\n pointer-events: none;\n z-index: 1;\n}\n\n@media (max-width: 640px) {\n .wrapper {\n --tempest-scheduler-gutter: 2.75rem;\n }\n\n .dayHead {\n font-size: 0.625rem;\n padding: var(--tempest-space-1);\n }\n}\n"],"mappings":""}
@@ -1,2 +1,2 @@
1
- const e=require("../../utils/cn.cjs"),t=require("../../hooks/use-fullscreen.cjs"),n=require("../../hooks/use-object-url.cjs"),r=require("./playback-rates.cjs"),i=require("../../audio/duration.cjs"),a=require("./VideoPlayer.module.cjs");let o=require("react"),s=require("react/jsx-runtime"),c=require("lucide-react");var l={"pt-BR":{play:`Tocar`,pause:`Pausar`,seek:`Posição`,mute:`Silenciar`,unmute:`Ativar som`,volume:`Volume`,rate:`Velocidade`,enterFullscreen:`Tela cheia`,exitFullscreen:`Sair da tela cheia`},en:{play:`Play`,pause:`Pause`,seek:`Seek`,mute:`Mute`,unmute:`Unmute`,volume:`Volume`,rate:`Speed`,enterFullscreen:`Full screen`,exitFullscreen:`Exit full screen`}};function u(e,t){return`${e.toLocaleString(t===`en`?`en-US`:`pt-BR`)}×`}function d({src:d,durationMs:f,poster:p,tracks:m,aspectRatio:h=16/9,rate:g,rates:_=r.DEFAULT_PLAYBACK_RATES,onRateChange:v,shiftPitch:y=!1,fullscreen:b=!0,autoPlay:x=!1,loop:S=!1,muted:C=!1,locale:w=`pt-BR`,actions:T,onEnded:E,onError:D,disabled:O=!1,className:k,...A}){let j=l[w],M=(0,o.useRef)(null),N=(0,o.useRef)(null),P=(0,o.useRef)(!1),[F,I]=(0,o.useState)(!1),[L,R]=(0,o.useState)(0),[z,B]=(0,o.useState)(1/0),[V,H]=(0,o.useState)(g??1),[U,W]=(0,o.useState)(1),[G,K]=(0,o.useState)(C),q=t.useFullscreen(M),J=n.useObjectUrl(typeof d==`string`?null:d),Y=typeof d==`string`?d:J,X=g??V,Z=Number.isFinite(f)?f:z,Q=Number.isFinite(Z)&&Z>0;(0,o.useEffect)(()=>{R(0),I(!1),B(1/0),P.current=!1},[Y]),(0,o.useEffect)(()=>{let e=N.current;e&&(e.defaultPlaybackRate=X,e.playbackRate=X,e.preservesPitch=!y)},[X,y,Y]),(0,o.useEffect)(()=>{let e=N.current;e&&(e.volume=U,e.muted=G)},[U,G,Y]);let $=()=>{let e=N.current;if(!e)return;if(Number.isFinite(e.duration)){B(e.duration*1e3);return}if(P.current||Number.isFinite(f))return;P.current=!0;let t=()=>{e.removeEventListener(`timeupdate`,t),Number.isFinite(e.duration)&&B(e.duration*1e3),e.currentTime=0};e.addEventListener(`timeupdate`,t),e.currentTime=1e101},ee=()=>{let e=N.current;if(!(!e||!Y)){if(e.paused){Promise.resolve(e.play()).then(()=>I(!0)).catch(e=>D?.(e));return}e.pause(),I(!1)}},te=e=>{let t=N.current;!t||!Q||(t.currentTime=e/1e3,R(e))},ne=e=>{g===void 0&&H(e),v?.(e)};return(0,s.jsxs)(`div`,{ref:M,className:e.cn(a.default.player,q.isFullscreen&&a.default.immersive,k),...A,children:[(0,s.jsx)(`div`,{className:a.default.frame,style:{aspectRatio:h},children:(0,s.jsx)(`video`,{ref:N,className:a.default.video,src:Y??void 0,poster:p,loop:S,autoPlay:x,playsInline:!0,preload:`metadata`,onLoadedMetadata:$,onDurationChange:$,onTimeUpdate:()=>{let e=N.current;e&&R(e.currentTime*1e3)},onPlay:()=>I(!0),onPause:()=>I(!1),onVolumeChange:()=>{let e=N.current;e&&(W(e.volume),K(e.muted))},onEnded:()=>{I(!1),E?.()},onError:e=>D?.(e),children:m?.map(e=>(0,s.jsx)(`track`,{kind:e.kind??`captions`,src:e.src,srcLang:e.srcLang,label:e.label,default:e.default},`${e.kind??`captions`}-${e.srcLang}-${e.src}`))})}),(0,s.jsxs)(`div`,{className:a.default.chrome,children:[(0,s.jsx)(`button`,{type:`button`,className:a.default.transport,onClick:ee,disabled:O||!Y,"aria-label":F?j.pause:j.play,title:F?j.pause:j.play,children:F?(0,s.jsx)(c.Pause,{size:16,"aria-hidden":!0}):(0,s.jsx)(c.Play,{size:16,"aria-hidden":!0})}),(0,s.jsx)(`input`,{type:`range`,className:a.default.seek,min:0,max:Q?Math.round(Z):0,step:100,value:Math.min(Math.round(L),Q?Math.round(Z):0),onChange:e=>te(Number(e.target.value)),disabled:O||!Q,"aria-label":j.seek,"aria-valuetext":`${i.formatDuration(L)} / ${i.formatDuration(Z)}`}),(0,s.jsxs)(`span`,{className:a.default.time,children:[(0,s.jsx)(`span`,{children:i.formatDuration(L)}),(0,s.jsx)(`span`,{"aria-hidden":`true`,children:`/`}),(0,s.jsx)(`span`,{children:i.formatDuration(Z)})]}),(0,s.jsx)(`button`,{type:`button`,className:a.default.icon,onClick:()=>K(e=>!e),disabled:O,"aria-label":G?j.unmute:j.mute,title:G?j.unmute:j.mute,children:G?(0,s.jsx)(c.VolumeX,{size:16,"aria-hidden":!0}):(0,s.jsx)(c.Volume2,{size:16,"aria-hidden":!0})}),(0,s.jsx)(`input`,{type:`range`,className:a.default.volume,min:0,max:1,step:.05,value:G?0:U,onChange:e=>{let t=Number(e.target.value);W(t),K(t===0)},disabled:O,"aria-label":j.volume}),_.length>0&&(0,s.jsx)(`select`,{className:a.default.rate,value:X,onChange:e=>ne(Number(e.target.value)),disabled:O,"aria-label":j.rate,title:j.rate,children:_.map(e=>(0,s.jsx)(`option`,{value:e,children:u(e,w)},e))}),b&&q.supported&&(0,s.jsx)(`button`,{type:`button`,className:a.default.icon,onClick:()=>{q.toggle().catch(e=>D?.(e))},disabled:O,"aria-label":q.isFullscreen?j.exitFullscreen:j.enterFullscreen,title:q.isFullscreen?j.exitFullscreen:j.enterFullscreen,children:q.isFullscreen?(0,s.jsx)(c.Minimize,{size:16,"aria-hidden":!0}):(0,s.jsx)(c.Maximize,{size:16,"aria-hidden":!0})}),T&&(0,s.jsx)(`span`,{className:a.default.actions,children:T})]})]})}exports.VideoPlayer=d;
1
+ const e=require("../../utils/cn.cjs"),t=require("../../hooks/use-fullscreen.cjs"),n=require("../../hooks/use-object-url.cjs"),r=require("./playback-rates.cjs"),i=require("../../audio/duration.cjs"),a=require("./VideoPlayer.module.cjs");let o=require("react"),s=require("react/jsx-runtime"),c=require("lucide-react");var l={"pt-BR":{play:`Tocar`,pause:`Pausar`,seek:`Posição`,mute:`Silenciar`,unmute:`Ativar som`,volume:`Volume`,rate:`Velocidade`,enterFullscreen:`Tela cheia`,exitFullscreen:`Sair da tela cheia`},en:{play:`Play`,pause:`Pause`,seek:`Seek`,mute:`Mute`,unmute:`Unmute`,volume:`Volume`,rate:`Speed`,enterFullscreen:`Full screen`,exitFullscreen:`Exit full screen`}};function u(e,t){return`${e.toLocaleString(t===`en`?`en-US`:`pt-BR`)}×`}function d({src:d,durationMs:f,poster:p,tracks:m,aspectRatio:h=16/9,rate:g,rates:_=r.DEFAULT_PLAYBACK_RATES,onRateChange:v,shiftPitch:y=!1,fullscreen:b=!0,autoPlay:x=!1,loop:S=!1,muted:C=!1,locale:w=`pt-BR`,actions:T,onEnded:E,onError:D,disabled:O=!1,className:k,...A}){let j=l[w],M=(0,o.useRef)(null),N=(0,o.useRef)(null),P=(0,o.useRef)(!1),[F,I]=(0,o.useState)(!1),[L,R]=(0,o.useState)(0),[z,B]=(0,o.useState)(1/0),[V,H]=(0,o.useState)(g??1),[U,W]=(0,o.useState)(1),[G,K]=(0,o.useState)(C),q=t.useFullscreen(M),J=n.useObjectUrl(typeof d==`string`?null:d),Y=typeof d==`string`?d:J,X=g??V,Z=Number.isFinite(f)?f:z,Q=Number.isFinite(Z)&&Z>0;(0,o.useEffect)(()=>{R(0),I(!1),B(1/0),P.current=!1},[Y]),(0,o.useEffect)(()=>{let e=N.current;e&&(e.defaultPlaybackRate=X,e.playbackRate=X,e.preservesPitch=!y)},[X,y,Y]),(0,o.useEffect)(()=>{let e=N.current;e&&(e.volume=U,e.muted=G)},[U,G,Y]);let $=()=>{let e=N.current;if(!e)return;if(Number.isFinite(e.duration)){B(e.duration*1e3);return}if(P.current||Number.isFinite(f))return;P.current=!0;let t=()=>{e.removeEventListener(`timeupdate`,t),Number.isFinite(e.duration)&&B(e.duration*1e3),e.currentTime=0};e.addEventListener(`timeupdate`,t),e.currentTime=1e101},ee=()=>{let e=N.current;if(e&&Y){if(e.paused){Promise.resolve(e.play()).then(()=>I(!0)).catch(e=>D?.(e));return}e.pause(),I(!1)}},te=e=>{let t=N.current;t&&Q&&(t.currentTime=e/1e3,R(e))},ne=e=>{g===void 0&&H(e),v?.(e)};return(0,s.jsxs)(`div`,{ref:M,className:e.cn(a.default.player,q.isFullscreen&&a.default.immersive,k),...A,children:[(0,s.jsx)(`div`,{className:a.default.frame,style:{aspectRatio:h},children:(0,s.jsx)(`video`,{ref:N,className:a.default.video,src:Y??void 0,poster:p,loop:S,autoPlay:x,playsInline:!0,preload:`metadata`,onLoadedMetadata:$,onDurationChange:$,onTimeUpdate:()=>{let e=N.current;e&&R(e.currentTime*1e3)},onPlay:()=>I(!0),onPause:()=>I(!1),onVolumeChange:()=>{let e=N.current;e&&(W(e.volume),K(e.muted))},onEnded:()=>{I(!1),E?.()},onError:e=>D?.(e),children:m?.map(e=>(0,s.jsx)(`track`,{kind:e.kind??`captions`,src:e.src,srcLang:e.srcLang,label:e.label,default:e.default},`${e.kind??`captions`}-${e.srcLang}-${e.src}`))})}),(0,s.jsxs)(`div`,{className:a.default.chrome,children:[(0,s.jsx)(`button`,{type:`button`,className:a.default.transport,onClick:ee,disabled:O||!Y,"aria-label":F?j.pause:j.play,title:F?j.pause:j.play,children:F?(0,s.jsx)(c.Pause,{size:16,"aria-hidden":!0}):(0,s.jsx)(c.Play,{size:16,"aria-hidden":!0})}),(0,s.jsx)(`input`,{type:`range`,className:a.default.seek,min:0,max:Q?Math.round(Z):0,step:100,value:Math.min(Math.round(L),Q?Math.round(Z):0),onChange:e=>te(Number(e.target.value)),disabled:O||!Q,"aria-label":j.seek,"aria-valuetext":`${i.formatDuration(L)} / ${i.formatDuration(Z)}`}),(0,s.jsxs)(`span`,{className:a.default.time,children:[(0,s.jsx)(`span`,{children:i.formatDuration(L)}),(0,s.jsx)(`span`,{"aria-hidden":`true`,children:`/`}),(0,s.jsx)(`span`,{children:i.formatDuration(Z)})]}),(0,s.jsx)(`button`,{type:`button`,className:a.default.icon,onClick:()=>K(e=>!e),disabled:O,"aria-label":G?j.unmute:j.mute,title:G?j.unmute:j.mute,children:G?(0,s.jsx)(c.VolumeX,{size:16,"aria-hidden":!0}):(0,s.jsx)(c.Volume2,{size:16,"aria-hidden":!0})}),(0,s.jsx)(`input`,{type:`range`,className:a.default.volume,min:0,max:1,step:.05,value:G?0:U,onChange:e=>{let t=Number(e.target.value);W(t),K(t===0)},disabled:O,"aria-label":j.volume}),_.length>0&&(0,s.jsx)(`select`,{className:a.default.rate,value:X,onChange:e=>ne(Number(e.target.value)),disabled:O,"aria-label":j.rate,title:j.rate,children:_.map(e=>(0,s.jsx)(`option`,{value:e,children:u(e,w)},e))}),b&&q.supported&&(0,s.jsx)(`button`,{type:`button`,className:a.default.icon,onClick:()=>{q.toggle().catch(e=>D?.(e))},disabled:O,"aria-label":q.isFullscreen?j.exitFullscreen:j.enterFullscreen,title:q.isFullscreen?j.exitFullscreen:j.enterFullscreen,children:q.isFullscreen?(0,s.jsx)(c.Minimize,{size:16,"aria-hidden":!0}):(0,s.jsx)(c.Maximize,{size:16,"aria-hidden":!0})}),T&&(0,s.jsx)(`span`,{className:a.default.actions,children:T})]})]})}exports.VideoPlayer=d;
2
2
  //# sourceMappingURL=VideoPlayer.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"VideoPlayer.cjs","names":[],"sources":["../../../src/components/VideoPlayer/VideoPlayer.tsx"],"sourcesContent":["/**\n * @tempest-limits props-count, function-lines — `src` takes a URL or a Blob, and\n * every other prop is a facet of playing it: durationMs (a MediaRecorder WebM may\n * carry none), poster, captions, aspect ratio, the rate control and its presets,\n * pitch, fullscreen, autoPlay/loop/muted, onEnded/onError, plus the actions slot and\n * locale. The body is the transport state machine — object-URL lifecycle, seek, rate,\n * volume — around one video element ref.\n */\nimport { Maximize, Minimize, Pause, Play, Volume2, VolumeX } from \"lucide-react\";\nimport { useEffect, useRef, useState, type HTMLAttributes, type ReactNode } from \"react\";\n\nimport { formatDuration } from \"@/audio/duration\";\nimport { useFullscreen } from \"@/hooks/use-fullscreen\";\nimport { useObjectUrl } from \"@/hooks/use-object-url\";\nimport { cn } from \"@/utils/cn\";\n\nimport { DEFAULT_PLAYBACK_RATES } from \"./playback-rates\";\nimport styles from \"./VideoPlayer.module.css\";\n\n/**\n * DOM attributes this component redefines.\n *\n * `onRateChange` is a real collision, not tidiness: React types it on every\n * element as the media `ratechange` handler, `ReactEventHandler`. Ours carries\n * the rate the viewer picked, and a `(rate: number) => void` is not assignable\n * to a handler that receives an event — same shape of clash as `Input`'s `size`\n * against `HTMLInputElement.size`. The DOM one is useless on a `<div>` anyway:\n * the event fires on the media element inside, which this component owns.\n */\ntype OverriddenDomProps = \"children\" | \"onRateChange\";\n\n/** One caption or subtitle file, rendered as a `<track>`. */\nexport interface VideoTextTrack {\n /** URL of the WebVTT file. */\n src: string;\n /** BCP 47 language tag, e.g. `\"pt-BR\"`. */\n srcLang: string;\n /** Name shown in the browser's own track menu. */\n label: string;\n /** Track kind. Default `\"captions\"`. */\n kind?: \"subtitles\" | \"captions\" | \"descriptions\" | \"chapters\" | \"metadata\";\n /** Whether this track is on unless the viewer picks another. */\n default?: boolean;\n}\n\nexport interface VideoPlayerProps extends Omit<HTMLAttributes<HTMLDivElement>, OverriddenDomProps> {\n /**\n * What to play — a URL, or a `Blob`/`File` straight from a recorder.\n *\n * A `Blob` is wrapped in an object URL that is revoked when it changes or the\n * component unmounts, so a session that records twenty clips does not leak\n * twenty URLs for the lifetime of the tab.\n */\n src: string | Blob | null;\n /**\n * Known length in milliseconds.\n *\n * Pass it whenever you have it — a recording from `useVideoRecorder` always\n * does. Without it the element's own `duration` is used, and a fresh\n * `MediaRecorder` blob may report `Infinity` until it is probed for one.\n */\n durationMs?: number;\n /** Still shown before playback. Pair it with `captureFrame` from `/imaging`. */\n poster?: string;\n /** Caption and subtitle files. */\n tracks?: readonly VideoTextTrack[];\n /** Frame shape while the video has no intrinsic size yet. Default `16 / 9`. */\n aspectRatio?: number;\n /**\n * Playback rate. Controlled when passed with `onRateChange`.\n *\n * Written to both `playbackRate` and `defaultPlaybackRate`, because the\n * element resets the first to the second when a source loads — a player that\n * only writes `playbackRate` silently drops back to 1× on every clip change.\n */\n rate?: number;\n /** Presets the control offers. `[]` hides it. Default {@link DEFAULT_PLAYBACK_RATES}. */\n rates?: readonly number[];\n /** Called with the rate the viewer picked. */\n onRateChange?: (rate: number) => void;\n /** Let the pitch rise with the rate (`preservesPitch = false`). Default `false`. */\n shiftPitch?: boolean;\n /** Offer a fullscreen button where the browser supports it. Default `true`. */\n fullscreen?: boolean;\n /** Start playing as soon as `src` is ready. Default `false`. */\n autoPlay?: boolean;\n /** Loop. Default `false`. */\n loop?: boolean;\n /** Start muted. Autoplay without a gesture needs this. Default `false`. */\n muted?: boolean;\n /** Locale for the labels. Default `\"pt-BR\"`. */\n locale?: \"pt-BR\" | \"en\";\n /** Rendered at the end of the control row — a download button, a delete button. */\n actions?: ReactNode;\n /** Fired when playback reaches the end. */\n onEnded?: () => void;\n /** Fired when the element reports a decode/network error. */\n onError?: (error: unknown) => void;\n /** No `src` yet, or playback not allowed. */\n disabled?: boolean;\n}\n\nconst STRINGS = {\n \"pt-BR\": {\n play: \"Tocar\",\n pause: \"Pausar\",\n seek: \"Posição\",\n mute: \"Silenciar\",\n unmute: \"Ativar som\",\n volume: \"Volume\",\n rate: \"Velocidade\",\n enterFullscreen: \"Tela cheia\",\n exitFullscreen: \"Sair da tela cheia\",\n },\n en: {\n play: \"Play\",\n pause: \"Pause\",\n seek: \"Seek\",\n mute: \"Mute\",\n unmute: \"Unmute\",\n volume: \"Volume\",\n rate: \"Speed\",\n enterFullscreen: \"Full screen\",\n exitFullscreen: \"Exit full screen\",\n },\n} as const;\n\n/**\n * Label a rate the way a viewer reads it.\n *\n * @param rate The multiplier.\n * @param locale Which decimal separator to use.\n * @returns e.g. `\"1,5×\"` in pt-BR, `\"1.5×\"` in English.\n */\nfunction rateLabel(rate: number, locale: \"pt-BR\" | \"en\"): string {\n return `${rate.toLocaleString(locale === \"en\" ? \"en-US\" : \"pt-BR\")}×`;\n}\n\n/**\n * Playback transport for one video: play/pause, seek, volume, speed, fullscreen.\n *\n * Built on a real `<video>` element, and deliberately **not** an overlay: the\n * controls sit in a bar under the frame rather than on top of it. Controls drawn\n * over video have to earn their contrast against arbitrary pixels, which no\n * `--tempest-*` token can promise — every text token in this SDK is resolved\n * against a known surface, and the two contrast defects this repo shipped were\n * both a text token used over a surface it was never checked against. A bar with\n * its own surface inherits the theme and is legible by construction.\n *\n * The seek bar, the volume slider and the speed picker are bare `<input>` and\n * `<select>` elements rather than the SDK's `Slider` and `Select`: those are form\n * fields, with a label row and a value badge, and a transport wants neither. The\n * native elements keep the keyboard and screen-reader behaviour that matters here\n * for free.\n *\n * @example\n * const rec = useVideoRecorder(screen.stream);\n * {rec.recording && (\n * <VideoPlayer src={rec.recording.blob} durationMs={rec.recording.durationMs} />\n * )}\n */\nexport function VideoPlayer({\n src,\n durationMs,\n poster,\n tracks,\n aspectRatio = 16 / 9,\n rate,\n rates = DEFAULT_PLAYBACK_RATES,\n onRateChange,\n shiftPitch = false,\n fullscreen = true,\n autoPlay = false,\n loop = false,\n muted = false,\n locale = \"pt-BR\",\n actions,\n onEnded,\n onError,\n disabled = false,\n className,\n ...rest\n}: VideoPlayerProps) {\n const strings = STRINGS[locale];\n const shell = useRef<HTMLDivElement | null>(null);\n const video = useRef<HTMLVideoElement | null>(null);\n const probed = useRef(false);\n\n const [playing, setPlaying] = useState(false);\n const [currentMs, setCurrentMs] = useState(0);\n const [elementMs, setElementMs] = useState(Number.POSITIVE_INFINITY);\n const [ownRate, setOwnRate] = useState(rate ?? 1);\n const [volume, setVolume] = useState(1);\n const [silent, setSilent] = useState(muted);\n\n const immersive = useFullscreen(shell);\n const blobUrl = useObjectUrl(typeof src === \"string\" ? null : src);\n const url = typeof src === \"string\" ? src : blobUrl;\n\n const effectiveRate = rate ?? ownRate;\n const totalMs = Number.isFinite(durationMs) ? (durationMs as number) : elementMs;\n const seekable = Number.isFinite(totalMs) && totalMs > 0;\n\n useEffect(() => {\n setCurrentMs(0);\n setPlaying(false);\n setElementMs(Number.POSITIVE_INFINITY);\n probed.current = false;\n }, [url]);\n\n /**\n * Keep the rate on the element, and keep it across sources.\n *\n * `defaultPlaybackRate` is written alongside `playbackRate` because the load\n * algorithm copies the former onto the latter: writing only `playbackRate`\n * means the rate the viewer chose is silently lost on the next clip.\n */\n useEffect(() => {\n const node = video.current;\n if (!node) return;\n node.defaultPlaybackRate = effectiveRate;\n node.playbackRate = effectiveRate;\n node.preservesPitch = !shiftPitch;\n }, [effectiveRate, shiftPitch, url]);\n\n useEffect(() => {\n const node = video.current;\n if (!node) return;\n node.volume = volume;\n node.muted = silent;\n }, [volume, silent, url]);\n\n /**\n * Coax a duration out of an element that reports `Infinity`.\n *\n * Seeking past the end forces the browser to demux to the last frame, after\n * which it knows the real length. It runs at most once per source, and only\n * when the caller gave us no `durationMs`.\n */\n const handleMetadata = (): void => {\n const node = video.current;\n if (!node) return;\n if (Number.isFinite(node.duration)) {\n setElementMs(node.duration * 1000);\n return;\n }\n if (probed.current || Number.isFinite(durationMs)) return;\n probed.current = true;\n const onProbed = (): void => {\n node.removeEventListener(\"timeupdate\", onProbed);\n if (Number.isFinite(node.duration)) setElementMs(node.duration * 1000);\n node.currentTime = 0;\n };\n node.addEventListener(\"timeupdate\", onProbed);\n node.currentTime = 1e101;\n };\n\n const toggle = (): void => {\n const node = video.current;\n if (!node || !url) return;\n if (node.paused) {\n void Promise.resolve(node.play())\n .then(() => setPlaying(true))\n .catch((error: unknown) => onError?.(error));\n return;\n }\n node.pause();\n setPlaying(false);\n };\n\n const seek = (ms: number): void => {\n const node = video.current;\n if (!node || !seekable) return;\n node.currentTime = ms / 1000;\n setCurrentMs(ms);\n };\n\n const changeRate = (next: number): void => {\n if (rate === undefined) setOwnRate(next);\n onRateChange?.(next);\n };\n\n return (\n <div\n ref={shell}\n className={cn(styles.player, immersive.isFullscreen && styles.immersive, className)}\n {...rest}\n >\n <div className={styles.frame} style={{ aspectRatio }}>\n <video\n ref={video}\n className={styles.video}\n src={url ?? undefined}\n poster={poster}\n loop={loop}\n autoPlay={autoPlay}\n playsInline\n preload=\"metadata\"\n onLoadedMetadata={handleMetadata}\n onDurationChange={handleMetadata}\n onTimeUpdate={() => {\n const node = video.current;\n if (node) setCurrentMs(node.currentTime * 1000);\n }}\n onPlay={() => setPlaying(true)}\n onPause={() => setPlaying(false)}\n onVolumeChange={() => {\n const node = video.current;\n if (!node) return;\n setVolume(node.volume);\n setSilent(node.muted);\n }}\n onEnded={() => {\n setPlaying(false);\n onEnded?.();\n }}\n onError={(event) => onError?.(event)}\n >\n {tracks?.map((track) => (\n <track\n key={`${track.kind ?? \"captions\"}-${track.srcLang}-${track.src}`}\n kind={track.kind ?? \"captions\"}\n src={track.src}\n srcLang={track.srcLang}\n label={track.label}\n default={track.default}\n />\n ))}\n </video>\n </div>\n\n <div className={styles.chrome}>\n <button\n type=\"button\"\n className={styles.transport}\n onClick={toggle}\n disabled={disabled || !url}\n aria-label={playing ? strings.pause : strings.play}\n title={playing ? strings.pause : strings.play}\n >\n {playing ? <Pause size={16} aria-hidden /> : <Play size={16} aria-hidden />}\n </button>\n\n <input\n type=\"range\"\n className={styles.seek}\n min={0}\n max={seekable ? Math.round(totalMs) : 0}\n step={100}\n value={Math.min(Math.round(currentMs), seekable ? Math.round(totalMs) : 0)}\n onChange={(event) => seek(Number(event.target.value))}\n disabled={disabled || !seekable}\n aria-label={strings.seek}\n aria-valuetext={`${formatDuration(currentMs)} / ${formatDuration(totalMs)}`}\n />\n\n <span className={styles.time}>\n <span>{formatDuration(currentMs)}</span>\n <span aria-hidden=\"true\">/</span>\n <span>{formatDuration(totalMs)}</span>\n </span>\n\n <button\n type=\"button\"\n className={styles.icon}\n onClick={() => setSilent((was) => !was)}\n disabled={disabled}\n aria-label={silent ? strings.unmute : strings.mute}\n title={silent ? strings.unmute : strings.mute}\n >\n {silent ? <VolumeX size={16} aria-hidden /> : <Volume2 size={16} aria-hidden />}\n </button>\n\n <input\n type=\"range\"\n className={styles.volume}\n min={0}\n max={1}\n step={0.05}\n value={silent ? 0 : volume}\n onChange={(event) => {\n const next = Number(event.target.value);\n setVolume(next);\n setSilent(next === 0);\n }}\n disabled={disabled}\n aria-label={strings.volume}\n />\n\n {rates.length > 0 && (\n <select\n className={styles.rate}\n value={effectiveRate}\n onChange={(event) => changeRate(Number(event.target.value))}\n disabled={disabled}\n aria-label={strings.rate}\n title={strings.rate}\n >\n {rates.map((option) => (\n <option key={option} value={option}>\n {rateLabel(option, locale)}\n </option>\n ))}\n </select>\n )}\n\n {fullscreen && immersive.supported && (\n <button\n type=\"button\"\n className={styles.icon}\n onClick={() => {\n void immersive.toggle().catch((error: unknown) => onError?.(error));\n }}\n disabled={disabled}\n aria-label={\n immersive.isFullscreen\n ? strings.exitFullscreen\n : strings.enterFullscreen\n }\n title={\n immersive.isFullscreen\n ? strings.exitFullscreen\n : strings.enterFullscreen\n }\n >\n {immersive.isFullscreen ? (\n <Minimize size={16} aria-hidden />\n ) : (\n <Maximize size={16} aria-hidden />\n )}\n </button>\n )}\n\n {actions && <span className={styles.actions}>{actions}</span>}\n </div>\n </div>\n );\n}\n"],"mappings":"4TAsGA,IAAM,EAAU,CACZ,QAAS,CACL,KAAM,QACN,MAAO,SACP,KAAM,UACN,KAAM,YACN,OAAQ,aACR,OAAQ,SACR,KAAM,aACN,gBAAiB,aACjB,eAAgB,oBACpB,EACA,GAAI,CACA,KAAM,OACN,MAAO,QACP,KAAM,OACN,KAAM,OACN,OAAQ,SACR,OAAQ,SACR,KAAM,QACN,gBAAiB,cACjB,eAAgB,kBACpB,CACJ,EASA,SAAS,EAAU,EAAc,EAAgC,CAC7D,MAAO,GAAG,EAAK,eAAe,IAAW,KAAO,QAAU,OAAO,EAAE,EACvE,CAyBA,SAAgB,EAAY,CACxB,MACA,aACA,SACA,SACA,cAAc,GAAK,EACnB,OACA,QAAQ,EAAA,uBACR,eACA,aAAa,GACb,aAAa,GACb,WAAW,GACX,OAAO,GACP,QAAQ,GACR,SAAS,QACT,UACA,UACA,UACA,WAAW,GACX,YACA,GAAG,GACc,CACjB,IAAM,EAAU,EAAQ,GAClB,GAAA,EAAQ,EAAA,OAAA,CAA8B,IAAI,EAC1C,GAAA,EAAQ,EAAA,OAAA,CAAgC,IAAI,EAC5C,GAAA,EAAS,EAAA,OAAA,CAAO,EAAK,EAErB,CAAC,EAAS,IAAA,EAAc,EAAA,SAAA,C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AAU,YACrB,EAAA,EAAA,IAAA,CAAC,SAAD,CACI,KAAK,SACL,UAAW,EAAA,QAAO,KAClB,YAAe,CACX,EAAe,OAAO,CAAC,CAAC,MAAO,GAAmB,IAAU,CAAK,CAAC,CACtE,EACU,WACV,aACI,EAAU,aACJ,EAAQ,eACR,EAAQ,gBAElB,MACI,EAAU,aACJ,EAAQ,eACR,EAAQ,gBAGjB,SAAA,EAAU,cACP,EAAA,EAAA,IAAA,CAAC,EAAA,SAAD,CAAU,KAAM,GAAI,cAAA,EAAa,CAAA,GAEjC,EAAA,EAAA,IAAA,CAAC,EAAA,SAAD,CAAU,KAAM,GAAI,cAAA,EAAa,CAAA,CAEjC,CAAA,EAGX,IAAW,EAAA,EAAA,IAAA,CAAC,OAAD,CAAM,UAAW,EAAA,QAAO,QAAU,SAAA,CAAc,CAAA,CAC3D,CACJ,CAAA,CAAA,GAEb"}
1
+ {"version":3,"file":"VideoPlayer.cjs","names":[],"sources":["../../../src/components/VideoPlayer/VideoPlayer.tsx"],"sourcesContent":["/**\n * @tempest-limits props-count, function-lines — `src` takes a URL or a Blob, and\n * every other prop is a facet of playing it: durationMs (a MediaRecorder WebM may\n * carry none), poster, captions, aspect ratio, the rate control and its presets,\n * pitch, fullscreen, autoPlay/loop/muted, onEnded/onError, plus the actions slot and\n * locale. The body is the transport state machine — object-URL lifecycle, seek, rate,\n * volume — around one video element ref.\n */\nimport { Maximize, Minimize, Pause, Play, Volume2, VolumeX } from \"lucide-react\";\nimport { useEffect, useRef, useState, type HTMLAttributes, type ReactNode } from \"react\";\n\nimport { formatDuration } from \"@/audio/duration\";\nimport { useFullscreen } from \"@/hooks/use-fullscreen\";\nimport { useObjectUrl } from \"@/hooks/use-object-url\";\nimport { cn } from \"@/utils/cn\";\n\nimport { DEFAULT_PLAYBACK_RATES } from \"./playback-rates\";\nimport styles from \"./VideoPlayer.module.css\";\n\n/**\n * DOM attributes this component redefines.\n *\n * `onRateChange` is a real collision, not tidiness: React types it on every\n * element as the media `ratechange` handler, `ReactEventHandler`. Ours carries\n * the rate the viewer picked, and a `(rate: number) => void` is not assignable\n * to a handler that receives an event — same shape of clash as `Input`'s `size`\n * against `HTMLInputElement.size`. The DOM one is useless on a `<div>` anyway:\n * the event fires on the media element inside, which this component owns.\n */\ntype OverriddenDomProps = \"children\" | \"onRateChange\";\n\n/** One caption or subtitle file, rendered as a `<track>`. */\nexport interface VideoTextTrack {\n /** URL of the WebVTT file. */\n src: string;\n /** BCP 47 language tag, e.g. `\"pt-BR\"`. */\n srcLang: string;\n /** Name shown in the browser's own track menu. */\n label: string;\n /** Track kind. Default `\"captions\"`. */\n kind?: \"subtitles\" | \"captions\" | \"descriptions\" | \"chapters\" | \"metadata\";\n /** Whether this track is on unless the viewer picks another. */\n default?: boolean;\n}\n\nexport interface VideoPlayerProps extends Omit<HTMLAttributes<HTMLDivElement>, OverriddenDomProps> {\n /**\n * What to play — a URL, or a `Blob`/`File` straight from a recorder.\n *\n * A `Blob` is wrapped in an object URL that is revoked when it changes or the\n * component unmounts, so a session that records twenty clips does not leak\n * twenty URLs for the lifetime of the tab.\n */\n src: string | Blob | null;\n /**\n * Known length in milliseconds.\n *\n * Pass it whenever you have it — a recording from `useVideoRecorder` always\n * does. Without it the element's own `duration` is used, and a fresh\n * `MediaRecorder` blob may report `Infinity` until it is probed for one.\n */\n durationMs?: number;\n /** Still shown before playback. Pair it with `captureFrame` from `/imaging`. */\n poster?: string;\n /** Caption and subtitle files. */\n tracks?: readonly VideoTextTrack[];\n /** Frame shape while the video has no intrinsic size yet. Default `16 / 9`. */\n aspectRatio?: number;\n /**\n * Playback rate. Controlled when passed with `onRateChange`.\n *\n * Written to both `playbackRate` and `defaultPlaybackRate`, because the\n * element resets the first to the second when a source loads — a player that\n * only writes `playbackRate` silently drops back to 1× on every clip change.\n */\n rate?: number;\n /** Presets the control offers. `[]` hides it. Default {@link DEFAULT_PLAYBACK_RATES}. */\n rates?: readonly number[];\n /** Called with the rate the viewer picked. */\n onRateChange?: (rate: number) => void;\n /** Let the pitch rise with the rate (`preservesPitch = false`). Default `false`. */\n shiftPitch?: boolean;\n /** Offer a fullscreen button where the browser supports it. Default `true`. */\n fullscreen?: boolean;\n /** Start playing as soon as `src` is ready. Default `false`. */\n autoPlay?: boolean;\n /** Loop. Default `false`. */\n loop?: boolean;\n /** Start muted. Autoplay without a gesture needs this. Default `false`. */\n muted?: boolean;\n /** Locale for the labels. Default `\"pt-BR\"`. */\n locale?: \"pt-BR\" | \"en\";\n /** Rendered at the end of the control row — a download button, a delete button. */\n actions?: ReactNode;\n /** Fired when playback reaches the end. */\n onEnded?: () => void;\n /** Fired when the element reports a decode/network error. */\n onError?: (error: unknown) => void;\n /** No `src` yet, or playback not allowed. */\n disabled?: boolean;\n}\n\nconst STRINGS = {\n \"pt-BR\": {\n play: \"Tocar\",\n pause: \"Pausar\",\n seek: \"Posição\",\n mute: \"Silenciar\",\n unmute: \"Ativar som\",\n volume: \"Volume\",\n rate: \"Velocidade\",\n enterFullscreen: \"Tela cheia\",\n exitFullscreen: \"Sair da tela cheia\",\n },\n en: {\n play: \"Play\",\n pause: \"Pause\",\n seek: \"Seek\",\n mute: \"Mute\",\n unmute: \"Unmute\",\n volume: \"Volume\",\n rate: \"Speed\",\n enterFullscreen: \"Full screen\",\n exitFullscreen: \"Exit full screen\",\n },\n} as const;\n\n/**\n * Label a rate the way a viewer reads it.\n *\n * @param rate The multiplier.\n * @param locale Which decimal separator to use.\n * @returns e.g. `\"1,5×\"` in pt-BR, `\"1.5×\"` in English.\n */\nfunction rateLabel(rate: number, locale: \"pt-BR\" | \"en\"): string {\n return `${rate.toLocaleString(locale === \"en\" ? \"en-US\" : \"pt-BR\")}×`;\n}\n\n/**\n * Playback transport for one video: play/pause, seek, volume, speed, fullscreen.\n *\n * Built on a real `<video>` element, and deliberately **not** an overlay: the\n * controls sit in a bar under the frame rather than on top of it. Controls drawn\n * over video have to earn their contrast against arbitrary pixels, which no\n * `--tempest-*` token can promise — every text token in this SDK is resolved\n * against a known surface, and the two contrast defects this repo shipped were\n * both a text token used over a surface it was never checked against. A bar with\n * its own surface inherits the theme and is legible by construction.\n *\n * The seek bar, the volume slider and the speed picker are bare `<input>` and\n * `<select>` elements rather than the SDK's `Slider` and `Select`: those are form\n * fields, with a label row and a value badge, and a transport wants neither. The\n * native elements keep the keyboard and screen-reader behaviour that matters here\n * for free.\n *\n * @example\n * const rec = useVideoRecorder(screen.stream);\n * {rec.recording && (\n * <VideoPlayer src={rec.recording.blob} durationMs={rec.recording.durationMs} />\n * )}\n */\nexport function VideoPlayer({\n src,\n durationMs,\n poster,\n tracks,\n aspectRatio = 16 / 9,\n rate,\n rates = DEFAULT_PLAYBACK_RATES,\n onRateChange,\n shiftPitch = false,\n fullscreen = true,\n autoPlay = false,\n loop = false,\n muted = false,\n locale = \"pt-BR\",\n actions,\n onEnded,\n onError,\n disabled = false,\n className,\n ...rest\n}: VideoPlayerProps) {\n const strings = STRINGS[locale];\n const shell = useRef<HTMLDivElement | null>(null);\n const video = useRef<HTMLVideoElement | null>(null);\n const probed = useRef(false);\n\n const [playing, setPlaying] = useState(false);\n const [currentMs, setCurrentMs] = useState(0);\n const [elementMs, setElementMs] = useState(Number.POSITIVE_INFINITY);\n const [ownRate, setOwnRate] = useState(rate ?? 1);\n const [volume, setVolume] = useState(1);\n const [silent, setSilent] = useState(muted);\n\n const immersive = useFullscreen(shell);\n const blobUrl = useObjectUrl(typeof src === \"string\" ? null : src);\n const url = typeof src === \"string\" ? src : blobUrl;\n\n const effectiveRate = rate ?? ownRate;\n const totalMs = Number.isFinite(durationMs) ? (durationMs as number) : elementMs;\n const seekable = Number.isFinite(totalMs) && totalMs > 0;\n\n useEffect(() => {\n setCurrentMs(0);\n setPlaying(false);\n setElementMs(Number.POSITIVE_INFINITY);\n probed.current = false;\n }, [url]);\n\n /**\n * Keep the rate on the element, and keep it across sources.\n *\n * `defaultPlaybackRate` is written alongside `playbackRate` because the load\n * algorithm copies the former onto the latter: writing only `playbackRate`\n * means the rate the viewer chose is silently lost on the next clip.\n */\n useEffect(() => {\n const node = video.current;\n if (!node) return;\n node.defaultPlaybackRate = effectiveRate;\n node.playbackRate = effectiveRate;\n node.preservesPitch = !shiftPitch;\n }, [effectiveRate, shiftPitch, url]);\n\n useEffect(() => {\n const node = video.current;\n if (!node) return;\n node.volume = volume;\n node.muted = silent;\n }, [volume, silent, url]);\n\n /**\n * Coax a duration out of an element that reports `Infinity`.\n *\n * Seeking past the end forces the browser to demux to the last frame, after\n * which it knows the real length. It runs at most once per source, and only\n * when the caller gave us no `durationMs`.\n */\n const handleMetadata = (): void => {\n const node = video.current;\n if (!node) return;\n if (Number.isFinite(node.duration)) {\n setElementMs(node.duration * 1000);\n return;\n }\n if (probed.current || Number.isFinite(durationMs)) return;\n probed.current = true;\n const onProbed = (): void => {\n node.removeEventListener(\"timeupdate\", onProbed);\n if (Number.isFinite(node.duration)) setElementMs(node.duration * 1000);\n node.currentTime = 0;\n };\n node.addEventListener(\"timeupdate\", onProbed);\n node.currentTime = 1e101;\n };\n\n const toggle = (): void => {\n const node = video.current;\n if (!node || !url) return;\n if (node.paused) {\n void Promise.resolve(node.play())\n .then(() => setPlaying(true))\n .catch((error: unknown) => onError?.(error));\n return;\n }\n node.pause();\n setPlaying(false);\n };\n\n const seek = (ms: number): void => {\n const node = video.current;\n if (!node || !seekable) return;\n node.currentTime = ms / 1000;\n setCurrentMs(ms);\n };\n\n const changeRate = (next: number): void => {\n if (rate === undefined) setOwnRate(next);\n onRateChange?.(next);\n };\n\n return (\n <div\n ref={shell}\n className={cn(styles.player, immersive.isFullscreen && styles.immersive, className)}\n {...rest}\n >\n <div className={styles.frame} style={{ aspectRatio }}>\n <video\n ref={video}\n className={styles.video}\n src={url ?? undefined}\n poster={poster}\n loop={loop}\n autoPlay={autoPlay}\n playsInline\n preload=\"metadata\"\n onLoadedMetadata={handleMetadata}\n onDurationChange={handleMetadata}\n onTimeUpdate={() => {\n const node = video.current;\n if (node) setCurrentMs(node.currentTime * 1000);\n }}\n onPlay={() => setPlaying(true)}\n onPause={() => setPlaying(false)}\n onVolumeChange={() => {\n const node = video.current;\n if (!node) return;\n setVolume(node.volume);\n setSilent(node.muted);\n }}\n onEnded={() => {\n setPlaying(false);\n onEnded?.();\n }}\n onError={(event) => onError?.(event)}\n >\n {tracks?.map((track) => (\n <track\n key={`${track.kind ?? \"captions\"}-${track.srcLang}-${track.src}`}\n kind={track.kind ?? \"captions\"}\n src={track.src}\n srcLang={track.srcLang}\n label={track.label}\n default={track.default}\n />\n ))}\n </video>\n </div>\n\n <div className={styles.chrome}>\n <button\n type=\"button\"\n className={styles.transport}\n onClick={toggle}\n disabled={disabled || !url}\n aria-label={playing ? strings.pause : strings.play}\n title={playing ? strings.pause : strings.play}\n >\n {playing ? <Pause size={16} aria-hidden /> : <Play size={16} aria-hidden />}\n </button>\n\n <input\n type=\"range\"\n className={styles.seek}\n min={0}\n max={seekable ? Math.round(totalMs) : 0}\n step={100}\n value={Math.min(Math.round(currentMs), seekable ? Math.round(totalMs) : 0)}\n onChange={(event) => seek(Number(event.target.value))}\n disabled={disabled || !seekable}\n aria-label={strings.seek}\n aria-valuetext={`${formatDuration(currentMs)} / ${formatDuration(totalMs)}`}\n />\n\n <span className={styles.time}>\n <span>{formatDuration(currentMs)}</span>\n <span aria-hidden=\"true\">/</span>\n <span>{formatDuration(totalMs)}</span>\n </span>\n\n <button\n type=\"button\"\n className={styles.icon}\n onClick={() => setSilent((was) => !was)}\n disabled={disabled}\n aria-label={silent ? strings.unmute : strings.mute}\n title={silent ? strings.unmute : strings.mute}\n >\n {silent ? <VolumeX size={16} aria-hidden /> : <Volume2 size={16} aria-hidden />}\n </button>\n\n <input\n type=\"range\"\n className={styles.volume}\n min={0}\n max={1}\n step={0.05}\n value={silent ? 0 : volume}\n onChange={(event) => {\n const next = Number(event.target.value);\n setVolume(next);\n setSilent(next === 0);\n }}\n disabled={disabled}\n aria-label={strings.volume}\n />\n\n {rates.length > 0 && (\n <select\n className={styles.rate}\n value={effectiveRate}\n onChange={(event) => changeRate(Number(event.target.value))}\n disabled={disabled}\n aria-label={strings.rate}\n title={strings.rate}\n >\n {rates.map((option) => (\n <option key={option} value={option}>\n {rateLabel(option, locale)}\n </option>\n ))}\n </select>\n )}\n\n {fullscreen && immersive.supported && (\n <button\n type=\"button\"\n className={styles.icon}\n onClick={() => {\n void immersive.toggle().catch((error: unknown) => onError?.(error));\n }}\n disabled={disabled}\n aria-label={\n immersive.isFullscreen\n ? strings.exitFullscreen\n : strings.enterFullscreen\n }\n title={\n immersive.isFullscreen\n ? strings.exitFullscreen\n : strings.enterFullscreen\n }\n >\n {immersive.isFullscreen ? (\n <Minimize size={16} aria-hidden />\n ) : (\n <Maximize size={16} aria-hidden />\n )}\n </button>\n )}\n\n {actions && <span className={styles.actions}>{actions}</span>}\n </div>\n </div>\n );\n}\n"],"mappings":"4TAsGA,IAAM,EAAU,CACZ,QAAS,CACL,KAAM,QACN,MAAO,SACP,KAAM,UACN,KAAM,YACN,OAAQ,aACR,OAAQ,SACR,KAAM,aACN,gBAAiB,aACjB,eAAgB,oBACpB,EACA,GAAI,CACA,KAAM,OACN,MAAO,QACP,KAAM,OACN,KAAM,OACN,OAAQ,SACR,OAAQ,SACR,KAAM,QACN,gBAAiB,cACjB,eAAgB,kBACpB,CACJ,EASA,SAAS,EAAU,EAAc,EAAgC,CAC7D,MAAO,GAAG,EAAK,eAAe,IAAW,KAAO,QAAU,OAAO,EAAE,EACvE,CAyBA,SAAgB,EAAY,CACxB,MACA,aACA,SACA,SACA,cAAc,GAAK,EACnB,OACA,QAAQ,EAAA,uBACR,eACA,aAAa,GACb,aAAa,GACb,WAAW,GACX,OAAO,GACP,QAAQ,GACR,SAAS,QACT,UACA,UACA,UACA,WAAW,GACX,YACA,GAAG,GACc,CACjB,IAAM,EAAU,EAAQ,GAClB,GAAA,EAAQ,EAAA,OAAA,CAA8B,IAAI,EAC1C,GAAA,EAAQ,EAAA,OAAA,CAAgC,IAA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A,EAAU,EAAQ,CAAM,CACrB,EAFK,CAEL,CACX,CACG,CAAA,EAGX,GAAc,EAAU,YACrB,EAAA,EAAA,IAAA,CAAC,SAAD,CACI,KAAK,SACL,UAAW,EAAA,QAAO,KAClB,YAAe,CACX,EAAe,OAAO,CAAC,CAAC,MAAO,GAAmB,IAAU,CAAK,CAAC,CACtE,EACU,WACV,aACI,EAAU,aACJ,EAAQ,eACR,EAAQ,gBAElB,MACI,EAAU,aACJ,EAAQ,eACR,EAAQ,gBAGjB,SAAA,EAAU,cACP,EAAA,EAAA,IAAA,CAAC,EAAA,SAAD,CAAU,KAAM,GAAI,cAAA,EAAa,CAAA,GAEjC,EAAA,EAAA,IAAA,CAAC,EAAA,SAAD,CAAU,KAAM,GAAI,cAAA,EAAa,CAAA,CAEjC,CAAA,EAGX,IAAW,EAAA,EAAA,IAAA,CAAC,OAAD,CAAM,UAAW,EAAA,QAAO,QAAU,SAAA,CAAc,CAAA,CAC3D,CACJ,CAAA,CAAA,GAEb"}
@@ -69,7 +69,7 @@ function m({ src: m, durationMs: h, poster: g, tracks: _, aspectRatio: v = 16 /
69
69
  e.addEventListener("timeupdate", t), e.currentTime = 1e101;
70
70
  }, ce = () => {
71
71
  let e = P.current;
72
- if (!(!e || !Y)) {
72
+ if (e && Y) {
73
73
  if (e.paused) {
74
74
  Promise.resolve(e.play()).then(() => L(!0)).catch((e) => A?.(e));
75
75
  return;
@@ -78,7 +78,7 @@ function m({ src: m, durationMs: h, poster: g, tracks: _, aspectRatio: v = 16 /
78
78
  }
79
79
  }, le = (e) => {
80
80
  let t = P.current;
81
- !t || !Q || (t.currentTime = e / 1e3, z(e));
81
+ t && Q && (t.currentTime = e / 1e3, z(e));
82
82
  }, ue = (e) => {
83
83
  y === void 0 && U(e), x?.(e);
84
84
  };