@zonsh/ui 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (388) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +76 -2
  3. package/assets/illustrations/drawing/bracket-construction-dark.svg +77 -0
  4. package/assets/illustrations/drawing/bracket-construction-filled-dark.svg +50 -0
  5. package/assets/illustrations/drawing/bracket-construction-filled.svg +50 -0
  6. package/assets/illustrations/drawing/bracket-construction.svg +77 -0
  7. package/assets/illustrations/drawing/crescent-dark.svg +28 -0
  8. package/assets/illustrations/drawing/crescent-guides-dark.svg +33 -0
  9. package/assets/illustrations/drawing/crescent-guides.svg +33 -0
  10. package/assets/illustrations/drawing/crescent.svg +28 -0
  11. package/assets/illustrations/drawing/eclipse-dark.svg +187 -0
  12. package/assets/illustrations/drawing/eclipse-guides-dark.svg +191 -0
  13. package/assets/illustrations/drawing/eclipse-guides.svg +191 -0
  14. package/assets/illustrations/drawing/eclipse.svg +187 -0
  15. package/assets/illustrations/drawing/elevation-guides-dark.svg +31 -0
  16. package/assets/illustrations/drawing/elevation-guides-plain-dark.svg +9 -0
  17. package/assets/illustrations/drawing/elevation-guides-plain.svg +9 -0
  18. package/assets/illustrations/drawing/elevation-guides.svg +31 -0
  19. package/assets/illustrations/drawing/horizon-dark.svg +30 -0
  20. package/assets/illustrations/drawing/horizon.svg +30 -0
  21. package/assets/illustrations/drawing/nib-study-dark.svg +107 -0
  22. package/assets/illustrations/drawing/nib-study-plain-dark.svg +93 -0
  23. package/assets/illustrations/drawing/nib-study-plain.svg +93 -0
  24. package/assets/illustrations/drawing/nib-study.svg +107 -0
  25. package/assets/illustrations/editorial/assistant-640.webp +0 -0
  26. package/assets/illustrations/editorial/assistant.webp +0 -0
  27. package/assets/illustrations/editorial/automation-640.webp +0 -0
  28. package/assets/illustrations/editorial/automation.webp +0 -0
  29. package/assets/illustrations/editorial/bracket-left-640.webp +0 -0
  30. package/assets/illustrations/editorial/bracket-left.webp +0 -0
  31. package/assets/illustrations/editorial/bracket-right-640.webp +0 -0
  32. package/assets/illustrations/editorial/bracket-right.webp +0 -0
  33. package/assets/illustrations/editorial/custom-software-640.webp +0 -0
  34. package/assets/illustrations/editorial/custom-software.webp +0 -0
  35. package/assets/illustrations/editorial/digitalization-640.webp +0 -0
  36. package/assets/illustrations/editorial/digitalization.webp +0 -0
  37. package/assets/illustrations/editorial/integration-640.webp +0 -0
  38. package/assets/illustrations/editorial/integration.webp +0 -0
  39. package/assets/illustrations/editorial/problem-640.webp +0 -0
  40. package/assets/illustrations/editorial/problem.webp +0 -0
  41. package/assets/illustrations/editorial/process-analysis-640.webp +0 -0
  42. package/assets/illustrations/editorial/process-analysis.webp +0 -0
  43. package/assets/illustrations/editorial/process-concept-640.webp +0 -0
  44. package/assets/illustrations/editorial/process-concept.webp +0 -0
  45. package/assets/illustrations/editorial/process-development-640.webp +0 -0
  46. package/assets/illustrations/editorial/process-development.webp +0 -0
  47. package/assets/illustrations/editorial/process-discovery-640.webp +0 -0
  48. package/assets/illustrations/editorial/process-discovery.webp +0 -0
  49. package/assets/illustrations/editorial/process-maintenance-640.webp +0 -0
  50. package/assets/illustrations/editorial/process-maintenance.webp +0 -0
  51. package/assets/illustrations/editorial/process-prototype-640.webp +0 -0
  52. package/assets/illustrations/editorial/process-prototype.webp +0 -0
  53. package/assets/illustrations/editorial/process-testing-640.webp +0 -0
  54. package/assets/illustrations/editorial/process-testing.webp +0 -0
  55. package/assets/illustrations/iso/automation-dark.svg +6 -0
  56. package/assets/illustrations/iso/automation.svg +6 -0
  57. package/assets/illustrations/iso/bar-chart-dark.svg +6 -0
  58. package/assets/illustrations/iso/bar-chart.svg +6 -0
  59. package/assets/illustrations/iso/brackets-classic-dark.svg +6 -0
  60. package/assets/illustrations/iso/brackets-classic.svg +6 -0
  61. package/assets/illustrations/iso/brackets-dark.svg +6 -0
  62. package/assets/illustrations/iso/brackets.svg +6 -0
  63. package/assets/illustrations/iso/city-dark.svg +6 -0
  64. package/assets/illustrations/iso/city.svg +6 -0
  65. package/assets/illustrations/iso/conveyor-dark.svg +6 -0
  66. package/assets/illustrations/iso/conveyor.svg +6 -0
  67. package/assets/illustrations/iso/database-dark.svg +6 -0
  68. package/assets/illustrations/iso/database.svg +6 -0
  69. package/assets/illustrations/iso/documents-dark.svg +6 -0
  70. package/assets/illustrations/iso/documents.svg +6 -0
  71. package/assets/illustrations/iso/inbox-dark.svg +6 -0
  72. package/assets/illustrations/iso/inbox.svg +6 -0
  73. package/assets/illustrations/iso/laptop-dark.svg +6 -0
  74. package/assets/illustrations/iso/laptop.svg +6 -0
  75. package/assets/illustrations/iso/monitor-dark.svg +6 -0
  76. package/assets/illustrations/iso/monitor.svg +6 -0
  77. package/assets/illustrations/iso/pipeline-dark.svg +6 -0
  78. package/assets/illustrations/iso/pipeline.svg +6 -0
  79. package/assets/illustrations/iso/platform-dark.svg +6 -0
  80. package/assets/illustrations/iso/platform.svg +6 -0
  81. package/assets/illustrations/iso/server-dark.svg +6 -0
  82. package/assets/illustrations/iso/server.svg +6 -0
  83. package/assets/illustrations/iso/spreadsheet-dark.svg +6 -0
  84. package/assets/illustrations/iso/spreadsheet.svg +6 -0
  85. package/assets/illustrations/iso/timeline-dark.svg +6 -0
  86. package/assets/illustrations/iso/timeline.svg +6 -0
  87. package/assets/illustrations/sheet/construction.svg +115 -0
  88. package/assets/illustrations/sheet/crescent.svg +40 -0
  89. package/assets/illustrations/sheet/limb.svg +42 -0
  90. package/assets/illustrations/sheet/stress-axis.svg +119 -0
  91. package/assets/illustrations/sheet/totality.svg +215 -0
  92. package/assets/illustrations/sheet/vertical-metrics.svg +43 -0
  93. package/assets/logo-left.svg +1 -0
  94. package/assets/logo-right.svg +1 -0
  95. package/assets/logo.svg +1 -0
  96. package/dist/components/_overlay.d.ts +47 -0
  97. package/dist/components/_overlay.js +59 -0
  98. package/dist/components/accordion.d.ts +32 -0
  99. package/dist/components/accordion.js +39 -0
  100. package/dist/components/alert-dialog.d.ts +45 -0
  101. package/dist/components/alert-dialog.js +56 -0
  102. package/dist/components/alert.d.ts +35 -0
  103. package/dist/components/alert.js +42 -0
  104. package/dist/components/ascii-field.d.ts +34 -0
  105. package/dist/components/ascii-field.js +410 -0
  106. package/dist/components/aspect-ratio.d.ts +14 -0
  107. package/dist/components/aspect-ratio.js +17 -0
  108. package/dist/components/avatar.d.ts +42 -0
  109. package/dist/components/avatar.js +55 -0
  110. package/dist/components/badge.d.ts +70 -0
  111. package/dist/components/badge.js +62 -0
  112. package/dist/components/breadcrumb.d.ts +22 -0
  113. package/dist/components/breadcrumb.js +32 -0
  114. package/dist/components/button-group.d.ts +30 -0
  115. package/dist/components/button-group.js +47 -0
  116. package/dist/components/button.d.ts +53 -0
  117. package/dist/components/button.js +130 -0
  118. package/dist/components/calendar.d.ts +26 -0
  119. package/dist/components/calendar.js +164 -0
  120. package/dist/components/card.d.ts +42 -0
  121. package/dist/components/card.js +76 -0
  122. package/dist/components/carousel.d.ts +90 -0
  123. package/dist/components/carousel.js +213 -0
  124. package/dist/components/chart.d.ts +180 -0
  125. package/dist/components/chart.js +286 -0
  126. package/dist/components/checkbox.d.ts +23 -0
  127. package/dist/components/checkbox.js +43 -0
  128. package/dist/components/code-block.d.ts +45 -0
  129. package/dist/components/code-block.js +58 -0
  130. package/dist/components/code-highlight.d.ts +13 -0
  131. package/dist/components/code-highlight.js +107 -0
  132. package/dist/components/collapsible.d.ts +20 -0
  133. package/dist/components/collapsible.js +32 -0
  134. package/dist/components/color-picker.d.ts +85 -0
  135. package/dist/components/color-picker.js +407 -0
  136. package/dist/components/combobox.d.ts +81 -0
  137. package/dist/components/combobox.js +100 -0
  138. package/dist/components/command.d.ts +112 -0
  139. package/dist/components/command.js +212 -0
  140. package/dist/components/context-menu.d.ts +29 -0
  141. package/dist/components/context-menu.js +35 -0
  142. package/dist/components/conversation.d.ts +27 -0
  143. package/dist/components/conversation.js +293 -0
  144. package/dist/components/copy-button.d.ts +46 -0
  145. package/dist/components/copy-button.js +118 -0
  146. package/dist/components/data-table.d.ts +175 -0
  147. package/dist/components/data-table.js +302 -0
  148. package/dist/components/date-picker.d.ts +91 -0
  149. package/dist/components/date-picker.js +207 -0
  150. package/dist/components/dialog.d.ts +48 -0
  151. package/dist/components/dialog.js +92 -0
  152. package/dist/components/direction.d.ts +16 -0
  153. package/dist/components/direction.js +18 -0
  154. package/dist/components/drawer.d.ts +60 -0
  155. package/dist/components/drawer.js +76 -0
  156. package/dist/components/empty.d.ts +31 -0
  157. package/dist/components/empty.js +50 -0
  158. package/dist/components/feature-list.d.ts +54 -0
  159. package/dist/components/feature-list.js +43 -0
  160. package/dist/components/field.d.ts +15 -0
  161. package/dist/components/field.js +36 -0
  162. package/dist/components/file-drop.d.ts +55 -0
  163. package/dist/components/file-drop.js +197 -0
  164. package/dist/components/filter-bar.d.ts +106 -0
  165. package/dist/components/filter-bar.js +296 -0
  166. package/dist/components/form.d.ts +33 -0
  167. package/dist/components/form.js +34 -0
  168. package/dist/components/graph.d.ts +105 -0
  169. package/dist/components/graph.js +786 -0
  170. package/dist/components/illustration.d.ts +85 -0
  171. package/dist/components/illustration.js +165 -0
  172. package/dist/components/input-group.d.ts +127 -0
  173. package/dist/components/input-group.js +292 -0
  174. package/dist/components/input.d.ts +16 -0
  175. package/dist/components/input.js +25 -0
  176. package/dist/components/item.d.ts +64 -0
  177. package/dist/components/item.js +116 -0
  178. package/dist/components/kbd.d.ts +33 -0
  179. package/dist/components/kbd.js +38 -0
  180. package/dist/components/label.d.ts +12 -0
  181. package/dist/components/label.js +24 -0
  182. package/dist/components/layout.d.ts +136 -0
  183. package/dist/components/layout.js +162 -0
  184. package/dist/components/logo.d.ts +54 -0
  185. package/dist/components/logo.js +96 -0
  186. package/dist/components/menu.d.ts +60 -0
  187. package/dist/components/menu.js +138 -0
  188. package/dist/components/menubar.d.ts +62 -0
  189. package/dist/components/menubar.js +223 -0
  190. package/dist/components/message.d.ts +42 -0
  191. package/dist/components/message.js +56 -0
  192. package/dist/components/meter.d.ts +31 -0
  193. package/dist/components/meter.js +25 -0
  194. package/dist/components/native-select.d.ts +26 -0
  195. package/dist/components/native-select.js +35 -0
  196. package/dist/components/navigation-menu.d.ts +42 -0
  197. package/dist/components/navigation-menu.js +97 -0
  198. package/dist/components/number-field.d.ts +36 -0
  199. package/dist/components/number-field.js +153 -0
  200. package/dist/components/otp-field.d.ts +35 -0
  201. package/dist/components/otp-field.js +94 -0
  202. package/dist/components/pagination.d.ts +31 -0
  203. package/dist/components/pagination.js +70 -0
  204. package/dist/components/pdf-viewer.d.ts +69 -0
  205. package/dist/components/pdf-viewer.js +929 -0
  206. package/dist/components/popover.d.ts +33 -0
  207. package/dist/components/popover.js +48 -0
  208. package/dist/components/preview-card.d.ts +25 -0
  209. package/dist/components/preview-card.js +22 -0
  210. package/dist/components/progress.d.ts +27 -0
  211. package/dist/components/progress.js +23 -0
  212. package/dist/components/prompt-input.d.ts +131 -0
  213. package/dist/components/prompt-input.js +403 -0
  214. package/dist/components/quote.d.ts +22 -0
  215. package/dist/components/quote.js +15 -0
  216. package/dist/components/radio-group.d.ts +18 -0
  217. package/dist/components/radio-group.js +34 -0
  218. package/dist/components/reasoning.d.ts +31 -0
  219. package/dist/components/reasoning.js +70 -0
  220. package/dist/components/resizable.d.ts +38 -0
  221. package/dist/components/resizable.js +41 -0
  222. package/dist/components/response.d.ts +30 -0
  223. package/dist/components/response.js +538 -0
  224. package/dist/components/scroll-area.d.ts +33 -0
  225. package/dist/components/scroll-area.js +31 -0
  226. package/dist/components/select.d.ts +35 -0
  227. package/dist/components/select.js +60 -0
  228. package/dist/components/separator.d.ts +14 -0
  229. package/dist/components/separator.js +17 -0
  230. package/dist/components/sidebar.d.ts +147 -0
  231. package/dist/components/sidebar.js +489 -0
  232. package/dist/components/site-header.d.ts +59 -0
  233. package/dist/components/site-header.js +67 -0
  234. package/dist/components/skeleton.d.ts +31 -0
  235. package/dist/components/skeleton.js +29 -0
  236. package/dist/components/slider.d.ts +24 -0
  237. package/dist/components/slider.js +129 -0
  238. package/dist/components/sources.d.ts +25 -0
  239. package/dist/components/sources.js +35 -0
  240. package/dist/components/spinner.d.ts +36 -0
  241. package/dist/components/spinner.js +72 -0
  242. package/dist/components/suggestions.d.ts +20 -0
  243. package/dist/components/suggestions.js +18 -0
  244. package/dist/components/switch.d.ts +14 -0
  245. package/dist/components/switch.js +26 -0
  246. package/dist/components/table.d.ts +162 -0
  247. package/dist/components/table.js +758 -0
  248. package/dist/components/tabs.d.ts +25 -0
  249. package/dist/components/tabs.js +162 -0
  250. package/dist/components/tag.d.ts +41 -0
  251. package/dist/components/tag.js +88 -0
  252. package/dist/components/tags-input.d.ts +40 -0
  253. package/dist/components/tags-input.js +239 -0
  254. package/dist/components/textarea.d.ts +13 -0
  255. package/dist/components/textarea.js +16 -0
  256. package/dist/components/theme.d.ts +41 -0
  257. package/dist/components/theme.js +112 -0
  258. package/dist/components/time-field.d.ts +51 -0
  259. package/dist/components/time-field.js +437 -0
  260. package/dist/components/timeline.d.ts +76 -0
  261. package/dist/components/timeline.js +99 -0
  262. package/dist/components/toast.d.ts +72 -0
  263. package/dist/components/toast.js +196 -0
  264. package/dist/components/toggle-group.d.ts +41 -0
  265. package/dist/components/toggle-group.js +140 -0
  266. package/dist/components/toggle.d.ts +23 -0
  267. package/dist/components/toggle.js +35 -0
  268. package/dist/components/tool-call.d.ts +52 -0
  269. package/dist/components/tool-call.js +57 -0
  270. package/dist/components/toolbar.d.ts +17 -0
  271. package/dist/components/toolbar.js +34 -0
  272. package/dist/components/tooltip.d.ts +42 -0
  273. package/dist/components/tooltip.js +47 -0
  274. package/dist/components/tree.d.ts +75 -0
  275. package/dist/components/tree.js +636 -0
  276. package/dist/components/typography.d.ts +134 -0
  277. package/dist/components/typography.js +176 -0
  278. package/dist/components/video-player.d.ts +276 -0
  279. package/dist/components/video-player.js +1352 -0
  280. package/dist/components/whiteboard.d.ts +80 -0
  281. package/dist/components/whiteboard.js +389 -0
  282. package/dist/index.d.ts +85 -0
  283. package/dist/index.js +86 -0
  284. package/dist/lib/cn.d.ts +20 -0
  285. package/dist/lib/cn.js +38 -0
  286. package/dist/lib/code-highlight.d.ts +31 -0
  287. package/dist/lib/code-highlight.js +24 -0
  288. package/dist/lib/code-theme.d.ts +19 -0
  289. package/dist/lib/code-theme.js +140 -0
  290. package/dist/lib/collapse-row.d.ts +9 -0
  291. package/dist/lib/collapse-row.js +129 -0
  292. package/dist/lib/digit-roll.d.ts +21 -0
  293. package/dist/lib/digit-roll.js +31 -0
  294. package/dist/lib/editorial-assets.d.ts +16 -0
  295. package/dist/lib/editorial-assets.js +56 -0
  296. package/dist/lib/figure/catalog.d.ts +127 -0
  297. package/dist/lib/figure/catalog.js +130 -0
  298. package/dist/lib/figure/figures/automation.d.ts +7 -0
  299. package/dist/lib/figure/figures/automation.js +143 -0
  300. package/dist/lib/figure/figures/bar-chart.d.ts +7 -0
  301. package/dist/lib/figure/figures/bar-chart.js +99 -0
  302. package/dist/lib/figure/figures/brackets-classic.d.ts +11 -0
  303. package/dist/lib/figure/figures/brackets-classic.js +170 -0
  304. package/dist/lib/figure/figures/brackets.d.ts +8 -0
  305. package/dist/lib/figure/figures/brackets.js +84 -0
  306. package/dist/lib/figure/figures/city.d.ts +7 -0
  307. package/dist/lib/figure/figures/city.js +93 -0
  308. package/dist/lib/figure/figures/conveyor.d.ts +7 -0
  309. package/dist/lib/figure/figures/conveyor.js +97 -0
  310. package/dist/lib/figure/figures/database.d.ts +7 -0
  311. package/dist/lib/figure/figures/database.js +65 -0
  312. package/dist/lib/figure/figures/documents.d.ts +7 -0
  313. package/dist/lib/figure/figures/documents.js +83 -0
  314. package/dist/lib/figure/figures/inbox.d.ts +7 -0
  315. package/dist/lib/figure/figures/inbox.js +92 -0
  316. package/dist/lib/figure/figures/laptop.d.ts +7 -0
  317. package/dist/lib/figure/figures/laptop.js +67 -0
  318. package/dist/lib/figure/figures/monitor.d.ts +7 -0
  319. package/dist/lib/figure/figures/monitor.js +59 -0
  320. package/dist/lib/figure/figures/pipeline.d.ts +8 -0
  321. package/dist/lib/figure/figures/pipeline.js +117 -0
  322. package/dist/lib/figure/figures/platform.d.ts +7 -0
  323. package/dist/lib/figure/figures/platform.js +117 -0
  324. package/dist/lib/figure/figures/server.d.ts +7 -0
  325. package/dist/lib/figure/figures/server.js +115 -0
  326. package/dist/lib/figure/figures/spreadsheet.d.ts +7 -0
  327. package/dist/lib/figure/figures/spreadsheet.js +87 -0
  328. package/dist/lib/figure/figures/timeline.d.ts +7 -0
  329. package/dist/lib/figure/figures/timeline.js +65 -0
  330. package/dist/lib/figure/kernel.d.ts +152 -0
  331. package/dist/lib/figure/kernel.js +576 -0
  332. package/dist/lib/figure/parts.d.ts +42 -0
  333. package/dist/lib/figure/parts.js +126 -0
  334. package/dist/lib/form-reset.d.ts +11 -0
  335. package/dist/lib/form-reset.js +22 -0
  336. package/dist/lib/glide.d.ts +53 -0
  337. package/dist/lib/glide.js +138 -0
  338. package/dist/lib/graph-layout.d.ts +58 -0
  339. package/dist/lib/graph-layout.js +200 -0
  340. package/dist/lib/illustration-drawings.d.ts +89 -0
  341. package/dist/lib/illustration-drawings.js +539 -0
  342. package/dist/lib/illustration-info.d.ts +37 -0
  343. package/dist/lib/illustration-info.js +22 -0
  344. package/dist/lib/illustration-library.d.ts +87 -0
  345. package/dist/lib/illustration-library.js +352 -0
  346. package/dist/lib/logo-geometry.d.ts +29 -0
  347. package/dist/lib/logo-geometry.js +67 -0
  348. package/dist/lib/markdown-guard.d.ts +16 -0
  349. package/dist/lib/markdown-guard.js +123 -0
  350. package/dist/lib/merge-refs.d.ts +10 -0
  351. package/dist/lib/merge-refs.js +26 -0
  352. package/dist/lib/motion.d.ts +6 -0
  353. package/dist/lib/motion.js +12 -0
  354. package/dist/lib/pdf-worker.d.ts +1 -0
  355. package/dist/lib/pdf-worker.js +6 -0
  356. package/dist/lib/pdf.d.ts +19 -0
  357. package/dist/lib/pdf.js +58 -0
  358. package/dist/lib/platform.d.ts +33 -0
  359. package/dist/lib/platform.js +68 -0
  360. package/dist/lib/room.d.ts +25 -0
  361. package/dist/lib/room.js +46 -0
  362. package/dist/lib/table-fit.d.ts +143 -0
  363. package/dist/lib/table-fit.js +577 -0
  364. package/dist/lib/theme-script.d.ts +18 -0
  365. package/dist/lib/theme-script.js +29 -0
  366. package/dist/styles/expressive.css +188 -0
  367. package/dist/styles/fonts.css +145 -0
  368. package/dist/styles/index.css +206 -0
  369. package/dist/styles/material.css +313 -0
  370. package/dist/styles/parts/ai.css +360 -0
  371. package/dist/styles/parts/brand.css +75 -0
  372. package/dist/styles/parts/controls.css +725 -0
  373. package/dist/styles/parts/data.css +222 -0
  374. package/dist/styles/parts/editorial.css +120 -0
  375. package/dist/styles/parts/feedback.css +273 -0
  376. package/dist/styles/parts/foundations.css +166 -0
  377. package/dist/styles/parts/graph.css +214 -0
  378. package/dist/styles/parts/inputs.css +261 -0
  379. package/dist/styles/parts/isometric.css +124 -0
  380. package/dist/styles/parts/navigation.css +232 -0
  381. package/dist/styles/parts/overlays.css +250 -0
  382. package/dist/styles/parts/pdf.css +154 -0
  383. package/dist/styles/parts/react-flow.css +519 -0
  384. package/dist/styles/parts/whiteboard.css +855 -0
  385. package/dist/styles/tokens.css +290 -0
  386. package/dist/vite.d.ts +116 -0
  387. package/dist/vite.js +129 -0
  388. package/package.json +189 -3
@@ -0,0 +1,929 @@
1
+ "use client";
2
+ import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
+ import { Toolbar as BaseToolbar } from "@base-ui/react/toolbar";
4
+ import { ChevronDownIcon, ChevronLeftIcon, ChevronRightIcon, ChevronUpIcon, DownloadIcon, FileTextIcon, FileWarningIcon, LayoutGridIcon, ListTreeIcon, MaximizeIcon, MinimizeIcon, MinusIcon, PanelLeftIcon, PlusIcon, PrinterIcon, RotateCwIcon, SearchIcon, XIcon, } from "lucide-react";
5
+ import * as React from "react";
6
+ import { cn } from "../lib/cn.js";
7
+ import { CSS_UNITS, loadPdfjs, openPdf, pdfFileName, } from "../lib/pdf.js";
8
+ import { modPressed } from "../lib/platform.js";
9
+ import { Button } from "./button.js";
10
+ import { Dialog, DialogClose, DialogContent, DialogTitle, DialogTrigger } from "./dialog.js";
11
+ import { Empty, EmptyActions, EmptyDescription, EmptyMedia, EmptyTitle } from "./empty.js";
12
+ import { Input } from "./input.js";
13
+ import { InputGroup, InputGroupAddon, InputGroupButton, InputGroupInput, InputGroupText, } from "./input-group.js";
14
+ import { Menu, MenuContent, MenuRadioGroup, MenuRadioItem, MenuSeparator, MenuTrigger } from "./menu.js";
15
+ import { ScrollArea } from "./scroll-area.js";
16
+ import { Spinner } from "./spinner.js";
17
+ import { Tabs, TabsList, TabsTab } from "./tabs.js";
18
+ import { Toolbar, ToolbarButton, ToolbarGroup, ToolbarSeparator } from "./toolbar.js";
19
+ import { Tooltip, TooltipContent, TooltipTrigger } from "./tooltip.js";
20
+ function describeError(error) {
21
+ const name = error?.name;
22
+ if (name === "PasswordException")
23
+ return "This PDF is protected with a password.";
24
+ if (name === "InvalidPDFException")
25
+ return "This file isn't a readable PDF.";
26
+ if (name === "ResponseException" || name === "MissingPDFException")
27
+ return "The file couldn't be loaded.";
28
+ return "Something went wrong while opening it.";
29
+ }
30
+ /** Open a document while `enabled`; it is destroyed when the source changes or the view goes. */
31
+ function usePdfDocument(src, enabled = true) {
32
+ const [state, setState] = React.useState({ status: "idle" });
33
+ const key = typeof src === "string" || src instanceof URL ? String(src) : src;
34
+ React.useEffect(() => {
35
+ if (!enabled)
36
+ return;
37
+ let alive = true;
38
+ let destroy;
39
+ setState({ status: "loading" });
40
+ openPdf(src)
41
+ .then(async ({ task }) => {
42
+ destroy = () => void task.destroy();
43
+ if (!alive)
44
+ return destroy();
45
+ const doc = await task.promise;
46
+ // Nothing to show is a file that can't be shown, not an empty reader.
47
+ if (!doc.numPages) {
48
+ if (alive)
49
+ setState({ status: "error", message: "This PDF has no pages." });
50
+ return;
51
+ }
52
+ const sizes = await Promise.all(Array.from({ length: doc.numPages }, (_, i) => doc.getPage(i + 1).then((page) => {
53
+ const v = page.getViewport({ scale: 1 });
54
+ return { w: v.width, h: v.height };
55
+ })));
56
+ if (alive)
57
+ setState({ status: "ready", doc, sizes });
58
+ })
59
+ .catch((error) => {
60
+ if (alive)
61
+ setState({ status: "error", message: describeError(error) });
62
+ });
63
+ return () => {
64
+ alive = false;
65
+ destroy?.();
66
+ };
67
+ // `key` stands for `src`: a URL string compares by value, data by identity.
68
+ // eslint-disable-next-line react-hooks/exhaustive-deps
69
+ }, [key, enabled]);
70
+ return state;
71
+ }
72
+ const texts = new WeakMap();
73
+ function pageText(doc, n) {
74
+ let pages = texts.get(doc);
75
+ if (!pages)
76
+ texts.set(doc, (pages = new Map()));
77
+ let text = pages.get(n);
78
+ if (!text) {
79
+ text = doc
80
+ .getPage(n)
81
+ .then((page) => page.getTextContent())
82
+ .then((content) => {
83
+ let joined = "";
84
+ const starts = [];
85
+ const strs = [];
86
+ for (const item of content.items) {
87
+ if (!("str" in item))
88
+ continue;
89
+ starts.push(joined.length);
90
+ strs.push(item.str);
91
+ joined += item.str + (item.hasEOL ? " " : "");
92
+ }
93
+ return { lower: joined.toLowerCase(), starts, strs };
94
+ });
95
+ pages.set(n, text);
96
+ }
97
+ return text;
98
+ }
99
+ async function findAll(doc, query, signal) {
100
+ const needle = query.toLowerCase();
101
+ const hits = [];
102
+ for (let page = 1; page <= doc.numPages; page++) {
103
+ const { lower } = await pageText(doc, page);
104
+ if (signal.aborted)
105
+ return [];
106
+ for (let at = lower.indexOf(needle); at >= 0; at = lower.indexOf(needle, at + needle.length))
107
+ hits.push({ page, start: at, end: at + needle.length });
108
+ }
109
+ return hits;
110
+ }
111
+ /** A page's size once the viewer's own rotation (0, 90, 180 or 270) is applied. */
112
+ const turn = (size, rotation) => (rotation % 180 ? { w: size.h, h: size.w } : size);
113
+ /** Resolve a pdf.js destination — a name or an explicit array — to a page and position. */
114
+ async function resolveDest(doc, dest) {
115
+ try {
116
+ const explicit = typeof dest === "string" ? await doc.getDestination(dest) : dest;
117
+ if (!Array.isArray(explicit) || explicit[0] == null)
118
+ return undefined;
119
+ const ref = explicit[0];
120
+ const index = typeof ref === "number" ? ref : await doc.getPageIndex(ref);
121
+ const page = index + 1;
122
+ const mode = explicit[1]?.name;
123
+ const y = mode === "XYZ" ? explicit[3] : mode === "FitH" || mode === "FitBH" ? explicit[2] : null;
124
+ if (typeof y !== "number")
125
+ return { page };
126
+ const viewport = (await doc.getPage(page)).getViewport({ scale: 1 });
127
+ const [, top] = viewport.convertToViewportPoint(0, y);
128
+ return { page, top: Math.min(1, Math.max(0, top / viewport.height)) };
129
+ }
130
+ catch {
131
+ return undefined;
132
+ }
133
+ }
134
+ const linkCache = new WeakMap();
135
+ function pageLinks(doc, n) {
136
+ let pages = linkCache.get(doc);
137
+ if (!pages)
138
+ linkCache.set(doc, (pages = new Map()));
139
+ let links = pages.get(n);
140
+ if (!links) {
141
+ links = (async () => {
142
+ const page = await doc.getPage(n);
143
+ const viewport = page.getViewport({ scale: 1 });
144
+ const found = [];
145
+ for (const a of await page.getAnnotations({ intent: "display" })) {
146
+ if (a.subtype !== "Link" || !Array.isArray(a.rect))
147
+ continue;
148
+ const [x1, y1] = viewport.convertToViewportPoint(a.rect[0], a.rect[1]);
149
+ const [x2, y2] = viewport.convertToViewportPoint(a.rect[2], a.rect[3]);
150
+ const box = {
151
+ x: Math.min(x1, x2) / viewport.width,
152
+ y: Math.min(y1, y2) / viewport.height,
153
+ w: Math.abs(x2 - x1) / viewport.width,
154
+ h: Math.abs(y2 - y1) / viewport.height,
155
+ };
156
+ const url = a.url ?? a.unsafeUrl;
157
+ if (typeof url === "string" && /^(https?:|mailto:)/i.test(url))
158
+ found.push({ ...box, url });
159
+ else if (a.dest) {
160
+ const target = await resolveDest(doc, a.dest);
161
+ if (target)
162
+ found.push({ ...box, target });
163
+ }
164
+ }
165
+ return found;
166
+ })().catch(() => []);
167
+ pages.set(n, links);
168
+ }
169
+ return links;
170
+ }
171
+ /** A link's box turned with the page: the viewer rotates clockwise. */
172
+ function turnBox({ x, y, w, h }, rotation) {
173
+ if (rotation === 90)
174
+ return { x: 1 - y - h, y: x, w: h, h: w };
175
+ if (rotation === 180)
176
+ return { x: 1 - x - w, y: 1 - y - h, w, h };
177
+ if (rotation === 270)
178
+ return { x: y, y: 1 - x - w, w: h, h: w };
179
+ return { x, y, w, h };
180
+ }
181
+ async function loadOutline(doc) {
182
+ const walk = (items) => Promise.all(items.map(async (item) => ({
183
+ title: item.title,
184
+ target: item.dest ? await resolveDest(doc, item.dest) : undefined,
185
+ url: typeof item.url === "string" ? item.url : undefined,
186
+ children: item.items?.length ? await walk(item.items) : [],
187
+ })));
188
+ const raw = await doc.getOutline().catch(() => null);
189
+ return raw?.length ? walk(raw) : null;
190
+ }
191
+ /** Draw a page into a fresh canvas at `scale` (1 = 100%), turned by `rotation`, sharp on dense screens. */
192
+ async function drawPage(page, scale, signal, rotation = 0) {
193
+ const viewport = page.getViewport({ scale: scale * CSS_UNITS, rotation: (page.rotate + rotation) % 360 });
194
+ let ratio = Math.min(window.devicePixelRatio || 1, 2);
195
+ // Keep a canvas under ~16 megapixels, the limit some browsers draw at all.
196
+ const max = 16_000_000;
197
+ if (viewport.width * viewport.height * ratio * ratio > max)
198
+ ratio = Math.sqrt(max / (viewport.width * viewport.height));
199
+ const canvas = document.createElement("canvas");
200
+ canvas.width = Math.floor(viewport.width * ratio);
201
+ canvas.height = Math.floor(viewport.height * ratio);
202
+ const task = page.render({
203
+ canvas,
204
+ viewport,
205
+ transform: ratio === 1 ? undefined : [ratio, 0, 0, ratio, 0, 0],
206
+ });
207
+ const cancel = () => task.cancel();
208
+ signal.addEventListener("abort", cancel);
209
+ try {
210
+ await task.promise;
211
+ }
212
+ finally {
213
+ signal.removeEventListener("abort", cancel);
214
+ }
215
+ return { canvas, viewport };
216
+ }
217
+ /** A blank canvas in place of a drawing: a page or thumbnail always holds exactly one canvas. */
218
+ function blank(host) {
219
+ if (!host)
220
+ return;
221
+ const canvas = document.createElement("canvas");
222
+ canvas.width = canvas.height = 0;
223
+ canvas.setAttribute("aria-hidden", "true");
224
+ canvas.className = "absolute inset-0 size-full";
225
+ host.replaceChildren(canvas);
226
+ }
227
+ async function savePdf(doc, name) {
228
+ const url = URL.createObjectURL(new Blob([(await doc.getData())], { type: "application/pdf" }));
229
+ const a = document.createElement("a");
230
+ a.href = url;
231
+ a.download = name;
232
+ a.click();
233
+ setTimeout(() => URL.revokeObjectURL(url), 30_000);
234
+ }
235
+ /** Print through the browser's own PDF handling, from a hidden frame. */
236
+ async function printPdf(doc) {
237
+ const url = URL.createObjectURL(new Blob([(await doc.getData())], { type: "application/pdf" }));
238
+ const frame = document.createElement("iframe");
239
+ frame.style.cssText = "position:fixed;width:0;height:0;border:0;opacity:0;pointer-events:none";
240
+ frame.src = url;
241
+ frame.onload = () => {
242
+ frame.contentWindow?.focus();
243
+ frame.contentWindow?.print();
244
+ };
245
+ document.body.append(frame);
246
+ setTimeout(() => {
247
+ frame.remove();
248
+ URL.revokeObjectURL(url);
249
+ }, 60_000);
250
+ }
251
+ const PageView = React.memo(function PageView({ doc, n, size, rotation, scale, renderScale, near, hits, current, onCurrent, onLink, register, }) {
252
+ const art = React.useRef(null);
253
+ const textHost = React.useRef(null);
254
+ const layer = React.useRef(null);
255
+ const [layerVersion, setLayerVersion] = React.useState(0);
256
+ const [drawn, setDrawn] = React.useState(false);
257
+ const drawnRotation = React.useRef(rotation);
258
+ const [links, setLinks] = React.useState([]);
259
+ const setRef = React.useCallback((el) => register(n, el), [n, register]);
260
+ React.useLayoutEffect(() => blank(art.current), []);
261
+ // Links are read once, the first time the page comes near.
262
+ const [seen, setSeen] = React.useState(false);
263
+ if (near && !seen)
264
+ setSeen(true);
265
+ React.useEffect(() => {
266
+ if (!seen)
267
+ return;
268
+ let alive = true;
269
+ void pageLinks(doc, n).then((found) => alive && setLinks(found));
270
+ return () => {
271
+ alive = false;
272
+ };
273
+ }, [doc, n, seen]);
274
+ React.useEffect(() => {
275
+ if (!near) {
276
+ // Far away: let the canvas and its text go, to keep memory flat on long documents.
277
+ blank(art.current);
278
+ textHost.current?.replaceChildren();
279
+ layer.current = null;
280
+ setDrawn(false);
281
+ return;
282
+ }
283
+ // A turned page can't keep its old drawing (it would stretch): show the placeholder instead.
284
+ if (drawnRotation.current !== rotation) {
285
+ blank(art.current);
286
+ textHost.current?.replaceChildren();
287
+ layer.current = null;
288
+ setDrawn(false);
289
+ drawnRotation.current = rotation;
290
+ }
291
+ const ac = new AbortController();
292
+ let text;
293
+ void (async () => {
294
+ try {
295
+ const page = await doc.getPage(n);
296
+ const { canvas, viewport } = await drawPage(page, renderScale, ac.signal, rotation);
297
+ if (ac.signal.aborted)
298
+ return;
299
+ canvas.setAttribute("aria-hidden", "true");
300
+ canvas.className = "absolute inset-0 size-full";
301
+ // The new drawing replaces the old one only when it is ready: zooming never blanks a page.
302
+ art.current?.replaceChildren(canvas);
303
+ setDrawn(true);
304
+ const [pdfjs, content] = await Promise.all([loadPdfjs(), page.getTextContent()]);
305
+ if (ac.signal.aborted)
306
+ return;
307
+ const div = document.createElement("div");
308
+ div.className = "textLayer";
309
+ const textLayer = new pdfjs.TextLayer({ textContentSource: content, container: div, viewport });
310
+ text = textLayer;
311
+ await textLayer.render();
312
+ if (ac.signal.aborted)
313
+ return;
314
+ textHost.current?.replaceChildren(div);
315
+ layer.current = { divs: textLayer.textDivs, strs: textLayer.textContentItemsStr };
316
+ setLayerVersion((v) => v + 1);
317
+ }
318
+ catch {
319
+ // Cancelled by a newer draw, or the document closed: nothing to do.
320
+ }
321
+ })();
322
+ return () => {
323
+ ac.abort();
324
+ text?.cancel();
325
+ };
326
+ }, [doc, n, near, renderScale, rotation]);
327
+ // Search hits: wrap the matched characters of each text item; restore the rest.
328
+ React.useEffect(() => {
329
+ const l = layer.current;
330
+ if (!l)
331
+ return;
332
+ let alive = true;
333
+ void pageText(doc, n).then(({ starts }) => {
334
+ if (!alive)
335
+ return;
336
+ const marks = new Map();
337
+ for (const hit of hits ?? [])
338
+ for (let i = 0; i < starts.length; i++) {
339
+ const s = starts[i];
340
+ const len = l.strs[i]?.length ?? 0;
341
+ if (s >= hit.end || s + len <= hit.start)
342
+ continue;
343
+ const list = marks.get(i) ?? [];
344
+ list.push({
345
+ from: Math.max(0, hit.start - s),
346
+ to: Math.min(len, hit.end - s),
347
+ current: hit === current,
348
+ });
349
+ marks.set(i, list);
350
+ }
351
+ let currentEl;
352
+ l.divs.forEach((div, i) => {
353
+ const str = l.strs[i] ?? "";
354
+ const list = marks.get(i);
355
+ if (!list) {
356
+ if (div.childElementCount)
357
+ div.textContent = str;
358
+ return;
359
+ }
360
+ div.replaceChildren();
361
+ let at = 0;
362
+ for (const m of list.sort((a, b) => a.from - b.from)) {
363
+ if (m.from > at)
364
+ div.append(str.slice(at, m.from));
365
+ const mark = document.createElement("span");
366
+ mark.className = "pdf-hit";
367
+ if (m.current) {
368
+ mark.dataset.current = "";
369
+ currentEl ??= mark;
370
+ }
371
+ mark.textContent = str.slice(m.from, m.to);
372
+ div.append(mark);
373
+ at = m.to;
374
+ }
375
+ if (at < str.length)
376
+ div.append(str.slice(at));
377
+ });
378
+ if (currentEl)
379
+ onCurrent(currentEl);
380
+ });
381
+ return () => {
382
+ alive = false;
383
+ };
384
+ }, [doc, n, hits, current, layerVersion, onCurrent]);
385
+ const s = scale * CSS_UNITS;
386
+ const pct = (v) => `${v * 100}%`;
387
+ return (_jsxs("div", { ref: setRef, "data-slot": "pdf-viewer-page", "data-page": n, "data-drawn": drawn ? "" : undefined, className: "relative shrink-0 overflow-hidden bg-white", style: {
388
+ width: Math.floor(size.w * s),
389
+ height: Math.floor(size.h * s),
390
+ "--total-scale-factor": s,
391
+ }, children: [_jsx("div", { ref: art, className: "absolute inset-0" }), _jsx("div", { ref: textHost, className: "absolute inset-0" }), links.map((link, i) => {
392
+ const box = turnBox(link, rotation);
393
+ const style = { left: pct(box.x), top: pct(box.y), width: pct(box.w), height: pct(box.h) };
394
+ return "url" in link ? (_jsx("a", { "data-slot": "pdf-viewer-link", href: link.url, target: "_blank", rel: "noopener noreferrer", "aria-label": `${link.url.replace(/^(https?:\/\/|mailto:)/, "").replace(/\/$/, "")} (opens in a new tab)`, style: style }, i)) : (_jsx("a", { "data-slot": "pdf-viewer-link", href: `#page=${link.target.page}`, "aria-label": `Go to page ${link.target.page}`, onClick: (e) => {
395
+ e.preventDefault();
396
+ onLink(link.target);
397
+ }, style: style }, i));
398
+ })] }));
399
+ });
400
+ /* ── Thumbnail ──────────────────────────────────────────────────────────────── */
401
+ const THUMB_W = 104;
402
+ const Thumbnail = React.memo(function Thumbnail({ doc, n, size, rotation, current, onSelect, }) {
403
+ const ref = React.useRef(null);
404
+ const art = React.useRef(null);
405
+ const [seen, setSeen] = React.useState(false);
406
+ const [drawn, setDrawn] = React.useState(false);
407
+ React.useEffect(() => {
408
+ const el = ref.current;
409
+ if (!el || seen)
410
+ return;
411
+ const io = new IntersectionObserver(([e]) => e?.isIntersecting && setSeen(true), { rootMargin: "200px" });
412
+ io.observe(el);
413
+ return () => io.disconnect();
414
+ }, [seen]);
415
+ React.useLayoutEffect(() => blank(art.current), []);
416
+ React.useEffect(() => {
417
+ if (!seen)
418
+ return;
419
+ const ac = new AbortController();
420
+ blank(art.current);
421
+ setDrawn(false);
422
+ void doc
423
+ .getPage(n)
424
+ .then((page) => drawPage(page, THUMB_W / (size.w * CSS_UNITS), ac.signal, rotation))
425
+ .then(({ canvas }) => {
426
+ canvas.setAttribute("aria-hidden", "true");
427
+ canvas.className = "absolute inset-0 size-full";
428
+ art.current?.replaceChildren(canvas);
429
+ setDrawn(true);
430
+ })
431
+ .catch(() => undefined);
432
+ return () => ac.abort();
433
+ }, [doc, n, seen, size.w, rotation]);
434
+ // Keep the current page in the rail. Not scrollIntoView: that also scrolls the window to the
435
+ // viewer and moves where Tab starts from.
436
+ React.useEffect(() => {
437
+ const el = ref.current;
438
+ const rail = el?.closest('[data-slot="scroll-area-viewport"]');
439
+ if (!current || !el || !rail)
440
+ return;
441
+ const r = el.getBoundingClientRect();
442
+ const v = rail.getBoundingClientRect();
443
+ if (r.top < v.top)
444
+ rail.scrollTop += r.top - v.top;
445
+ else if (r.bottom > v.bottom)
446
+ rail.scrollTop += r.bottom - v.bottom;
447
+ }, [current]);
448
+ return (_jsxs("button", { ref: ref, type: "button", "data-slot": "pdf-viewer-thumbnail", "aria-label": `Page ${n}`, "aria-current": current ? "page" : undefined, onClick: () => onSelect(n), className: "relative flex shrink-0 cursor-pointer rounded-item material-row p-1.5 focus-ring", children: [_jsx("span", { ref: art, "aria-hidden": true, "data-slot": "pdf-viewer-thumbnail-page", "data-drawn": drawn ? "" : undefined, className: "relative block overflow-hidden bg-white", style: { width: THUMB_W, height: Math.round((THUMB_W * size.h) / size.w) } }), _jsx("span", { "aria-hidden": true, "data-slot": "pdf-viewer-thumbnail-number", className: cn("theme-light absolute right-2.5 bottom-2.5 rounded-checkbox border px-1 font-mono text-[10px] leading-3.5 tabular-nums", current
449
+ ? "border-foreground bg-foreground text-background"
450
+ : "border-border bg-background/90 text-muted-foreground"), children: String(n).padStart(2, "0") })] }));
451
+ });
452
+ /* ── Outline ────────────────────────────────────────────────────────────────── */
453
+ function OutlineList({ entries, current, onSelect, }) {
454
+ return (_jsx("ul", { className: "m-0 flex list-none flex-col gap-0.5 p-0", children: entries.map((entry, i) => (_jsx(OutlineRow, { entry: entry, current: current, onSelect: onSelect }, i))) }));
455
+ }
456
+ function OutlineRow({ entry, current, onSelect, }) {
457
+ const [open, setOpen] = React.useState(true);
458
+ const nested = entry.children.length > 0;
459
+ return (_jsxs("li", { className: "flex flex-col gap-0.5", children: [_jsxs("div", { className: "flex items-center", children: [nested ? (_jsx("button", { type: "button", "aria-label": `${open ? "Collapse" : "Expand"} ${entry.title}`, "aria-expanded": open, onClick: () => setOpen((o) => !o), className: "flex size-6 shrink-0 cursor-pointer items-center justify-center rounded-checkbox text-muted-foreground focus-ring transition-colors duration-(--duration) ease-(--ease) hover:text-foreground", children: _jsx(ChevronRightIcon, { "aria-hidden": true, className: cn("size-3.5 transition-transform duration-(--duration) ease-(--ease) motion-reduce:transition-none rtl:-scale-x-100", open && "rotate-90 rtl:-rotate-90") }) })) : (_jsx("span", { "aria-hidden": true, className: "w-6 shrink-0" })), _jsxs("button", { type: "button", disabled: !entry.target && !entry.url, "aria-current": entry === current ? "true" : undefined, onClick: () => onSelect(entry), className: "flex min-h-(--control-h-sm) min-w-0 flex-1 cursor-pointer items-center gap-2 rounded-item material-row px-2 text-start text-[13px] leading-tight focus-ring disabled:cursor-default disabled:opacity-60", children: [_jsx("span", { className: "min-w-0 flex-1 truncate", children: entry.title }), entry.target && (_jsx("span", { className: "font-mono text-[11px] text-muted-foreground tabular-nums", children: String(entry.target.page).padStart(2, "0") }))] })] }), nested && open && (_jsx("div", { className: "pl-4", children: _jsx(OutlineList, { entries: entry.children, current: current, onSelect: onSelect }) }))] }));
460
+ }
461
+ /* ── Viewer ─────────────────────────────────────────────────────────────────── */
462
+ const ZOOM_STEPS = [0.5, 0.75, 1, 1.25, 1.5, 2, 3, 4];
463
+ const clampZoom = (z) => (Number.isNaN(z) ? 1 : Math.min(5, Math.max(0.25, z)));
464
+ /** A page number from any number: whole, from 1. */
465
+ const toPage = (n) => Math.max(1, Math.trunc(n) || 1);
466
+ const viewerVariants = {
467
+ region: "surface-container",
468
+ card: "surface-card overflow-hidden [--card-padding:0]",
469
+ plain: "",
470
+ };
471
+ function Tool({ label, children, ...props }) {
472
+ return (_jsxs(Tooltip, { children: [_jsx(TooltipTrigger, { render: _jsx(ToolbarButton, { "aria-label": label, ...props }), children: children }), _jsx(TooltipContent, { children: label })] }));
473
+ }
474
+ /**
475
+ * PdfViewer — a full reader for PDF documents: pages drawn by pdf.js with selectable text, a
476
+ * toolbar for page, zoom, search, download, print and full screen, and a rail of thumbnails.
477
+ *
478
+ * pdf.js loads with the first viewer on the page and parses in a worker; pages are drawn only as
479
+ * they come near the view. Give it a height (it defaults to 80% of the screen, at most 736px).
480
+ * The rule people break: putting a viewer where a link would do — for a document people only
481
+ * download, link to it; for a glance, use `PdfPreview`.
482
+ */
483
+ export function PdfViewer({ src, fileName, variant = "region", defaultZoom = "auto", defaultPage = 1, onPageChange, thumbnails = true, defaultThumbnailsOpen = true, search = true, download = true, print = true, fullscreen: allowFullscreen = true, toolbarEnd, className, onKeyDown, ...props }) {
484
+ const state = usePdfDocument(src);
485
+ const doc = state.status === "ready" ? state.doc : undefined;
486
+ const [rotation, setRotation] = React.useState(0);
487
+ const pageSizes = state.status === "ready" ? state.sizes : undefined;
488
+ // Pages as shown: turned by the viewer's rotation.
489
+ const sizes = React.useMemo(() => pageSizes?.map((s) => turn(s, rotation)), [pageSizes, rotation]);
490
+ const count = sizes?.length ?? 0;
491
+ const name = pdfFileName(src, fileName);
492
+ const root = React.useRef(null);
493
+ const viewport = React.useRef(null);
494
+ const pageEls = React.useRef(new Map());
495
+ const [box, setBox] = React.useState({ w: 0, h: 0 });
496
+ const [zoom, setZoom] = React.useState(defaultZoom);
497
+ const [page, setPage] = React.useState(() => toPage(defaultPage));
498
+ const [pageDraft, setPageDraft] = React.useState(null);
499
+ const [near, setNear] = React.useState(new Set());
500
+ const [railOpen, setRailOpen] = React.useState(defaultThumbnailsOpen);
501
+ const [isFullscreen, setFullscreen] = React.useState(false);
502
+ /* Size of the page area, for the fit zooms. */
503
+ React.useEffect(() => {
504
+ const el = viewport.current;
505
+ if (!el)
506
+ return;
507
+ const ro = new ResizeObserver(() => setBox({ w: el.clientWidth, h: el.clientHeight }));
508
+ ro.observe(el);
509
+ return () => ro.disconnect();
510
+ }, [state.status]);
511
+ const pad = box.w >= 640 ? 24 : 16;
512
+ const scale = React.useMemo(() => {
513
+ if (typeof zoom === "number")
514
+ return clampZoom(zoom);
515
+ if (!sizes || !box.w)
516
+ return 1;
517
+ const widest = Math.max(...sizes.map((s) => s.w)) * CSS_UNITS;
518
+ const fitWidth = (box.w - pad * 2) / widest;
519
+ if (zoom === "fit-width")
520
+ return clampZoom(fitWidth);
521
+ if (zoom === "auto")
522
+ return clampZoom(Math.min(fitWidth, 1.25));
523
+ const tallest = (sizes[page - 1] ?? sizes[0]).h * CSS_UNITS;
524
+ return clampZoom(Math.min(fitWidth, (box.h - pad * 2) / tallest));
525
+ // Fit page follows the page in view only when the zoom is chosen, not while scrolling.
526
+ // eslint-disable-next-line react-hooks/exhaustive-deps
527
+ }, [zoom, sizes, box, pad]);
528
+ // Pages are laid out at once at the new scale; they are redrawn once zooming pauses.
529
+ const [renderScale, setRenderScale] = React.useState(scale);
530
+ React.useEffect(() => {
531
+ const t = setTimeout(() => setRenderScale(scale), 160);
532
+ return () => clearTimeout(t);
533
+ }, [scale]);
534
+ /* Keep the same place in view when the scale changes. */
535
+ const anchor = React.useRef(null);
536
+ const keepPlace = React.useCallback(() => {
537
+ const vp = viewport.current;
538
+ const el = pageEls.current.get(page);
539
+ if (vp && el)
540
+ anchor.current = { n: page, f: (vp.scrollTop - el.offsetTop) / el.offsetHeight };
541
+ }, [page]);
542
+ React.useLayoutEffect(() => {
543
+ const a = anchor.current;
544
+ const vp = viewport.current;
545
+ const el = a && pageEls.current.get(a.n);
546
+ if (a && vp && el)
547
+ vp.scrollTop = el.offsetTop + a.f * el.offsetHeight;
548
+ anchor.current = null;
549
+ }, [scale, rotation]);
550
+ const zoomTo = React.useCallback((z) => {
551
+ keepPlace();
552
+ setZoom(z);
553
+ }, [keepPlace]);
554
+ const zoomBy = (dir) => zoomTo(dir > 0
555
+ ? (ZOOM_STEPS.find((z) => z > scale + 0.01) ?? 5)
556
+ : ([...ZOOM_STEPS].reverse().find((z) => z < scale - 0.01) ?? 0.25));
557
+ /* Ctrl/⌘ + wheel (and trackpad pinch) zooms around the page in view. */
558
+ const scaleRef = React.useRef(scale);
559
+ scaleRef.current = scale;
560
+ React.useEffect(() => {
561
+ const el = viewport.current;
562
+ if (!el)
563
+ return;
564
+ const onWheel = (e) => {
565
+ if (!e.ctrlKey && !e.metaKey)
566
+ return;
567
+ e.preventDefault();
568
+ zoomTo(clampZoom(scaleRef.current * Math.exp(-e.deltaY * 0.002)));
569
+ };
570
+ el.addEventListener("wheel", onWheel, { passive: false });
571
+ return () => el.removeEventListener("wheel", onWheel);
572
+ }, [zoomTo, state.status]);
573
+ /* Which pages are near the view (drawn), and which one is current. */
574
+ const observer = React.useRef(null);
575
+ React.useEffect(() => {
576
+ const vp = viewport.current;
577
+ if (!vp || !doc)
578
+ return;
579
+ const io = new IntersectionObserver((entries) => setNear((prev) => {
580
+ const next = new Set(prev);
581
+ for (const e of entries) {
582
+ const n = Number(e.target.dataset.page);
583
+ if (e.isIntersecting)
584
+ next.add(n);
585
+ else
586
+ next.delete(n);
587
+ }
588
+ return next.size === prev.size && [...next].every((n) => prev.has(n)) ? prev : next;
589
+ }), { root: vp, rootMargin: "120% 0px" });
590
+ observer.current = io;
591
+ for (const el of pageEls.current.values())
592
+ io.observe(el);
593
+ return () => io.disconnect();
594
+ }, [doc]);
595
+ const register = React.useCallback((n, el) => {
596
+ const old = pageEls.current.get(n);
597
+ if (old && old !== el)
598
+ observer.current?.unobserve(old);
599
+ if (el) {
600
+ pageEls.current.set(n, el);
601
+ observer.current?.observe(el);
602
+ }
603
+ else
604
+ pageEls.current.delete(n);
605
+ }, []);
606
+ /* The page in view, how far down it the reading line is (for the outline), and the page chip. */
607
+ const [readAt, setReadAt] = React.useState(0);
608
+ // The reading line moves with every frame of a scroll: it re-renders the viewer only while the
609
+ // outline that marks it is shown.
610
+ const readLine = React.useRef(0);
611
+ const marksReading = React.useRef(false);
612
+ const [chip, setChip] = React.useState(false);
613
+ const chipTimer = React.useRef(0);
614
+ React.useEffect(() => () => clearTimeout(chipTimer.current), []);
615
+ const onScroll = React.useCallback(() => {
616
+ const vp = viewport.current;
617
+ if (!vp)
618
+ return;
619
+ const line = vp.scrollTop + vp.clientHeight * 0.4;
620
+ let current = 1;
621
+ for (const [n, el] of pageEls.current)
622
+ if (el.offsetTop <= line && n > current)
623
+ current = n;
624
+ setPage(current);
625
+ const el = pageEls.current.get(current);
626
+ if (el)
627
+ readLine.current = Math.round(((line - el.offsetTop) / el.offsetHeight) * 50) / 50;
628
+ if (marksReading.current)
629
+ setReadAt(readLine.current);
630
+ setChip(true);
631
+ clearTimeout(chipTimer.current);
632
+ chipTimer.current = window.setTimeout(() => setChip(false), 900);
633
+ }, []);
634
+ // Told when the page in view changes once there are pages: not on every render of a parent that
635
+ // passes a new function, and never a page the document doesn't have.
636
+ const pageChange = React.useRef(onPageChange);
637
+ pageChange.current = onPageChange;
638
+ React.useEffect(() => {
639
+ if (count && page <= count)
640
+ pageChange.current?.(page);
641
+ }, [page, count]);
642
+ /** Scroll to a page, optionally to a point down it (0–1 from the top of the page as shown). */
643
+ const goTo = React.useCallback((n, top) => {
644
+ const target = Math.min(toPage(n), count || 1);
645
+ const vp = viewport.current;
646
+ const el = pageEls.current.get(target);
647
+ if (vp && el)
648
+ vp.scrollTop = el.offsetTop + (top ?? 0) * el.offsetHeight - pad;
649
+ setPage(target);
650
+ }, [count, pad]);
651
+ /* Links and bookmarks: a position down the page holds only while the page is upright or upside down. */
652
+ const follow = React.useCallback((t) => goTo(t.page, t.top == null ? undefined : rotation === 0 ? t.top : rotation === 180 ? 1 - t.top : undefined), [goTo, rotation]);
653
+ /* Outline. */
654
+ const [outline, setOutline] = React.useState(null);
655
+ const [railTab, setRailTab] = React.useState("pages");
656
+ React.useEffect(() => {
657
+ setOutline(null);
658
+ if (!doc)
659
+ return;
660
+ let alive = true;
661
+ void loadOutline(doc).then((o) => alive && setOutline(o));
662
+ return () => {
663
+ alive = false;
664
+ };
665
+ }, [doc]);
666
+ // The entry being read: the last one that starts at or above the reading line.
667
+ const reading = React.useMemo(() => {
668
+ let found;
669
+ const visit = (list) => {
670
+ for (const e of list) {
671
+ const t = e.target;
672
+ if (t && (t.page < page || (t.page === page && (rotation !== 0 || (t.top ?? 0) <= readAt + 0.02))))
673
+ found = e;
674
+ visit(e.children);
675
+ }
676
+ };
677
+ if (outline)
678
+ visit(outline);
679
+ return found;
680
+ }, [outline, page, readAt, rotation]);
681
+ const openEntry = (entry) => {
682
+ if (entry.target)
683
+ follow(entry.target);
684
+ else if (entry.url)
685
+ window.open(entry.url, "_blank", "noopener,noreferrer");
686
+ };
687
+ const showOutline = railTab === "outline" && !!outline;
688
+ const outlineShown = thumbnails && railOpen && showOutline;
689
+ marksReading.current = outlineShown;
690
+ React.useEffect(() => {
691
+ if (outlineShown)
692
+ setReadAt(readLine.current);
693
+ }, [outlineShown]);
694
+ const rotate = () => {
695
+ keepPlace();
696
+ setRotation((r) => (r + 90) % 360);
697
+ };
698
+ // Open at the default page once the pages are laid out.
699
+ const opened = React.useRef(false);
700
+ React.useLayoutEffect(() => {
701
+ if (!doc || opened.current || !box.w)
702
+ return;
703
+ opened.current = true;
704
+ if (defaultPage > 1)
705
+ goTo(defaultPage);
706
+ }, [doc, box.w, defaultPage, goTo]);
707
+ /* Search. */
708
+ const [searchOpen, setSearchOpen] = React.useState(false);
709
+ const [query, setQuery] = React.useState("");
710
+ const [hits, setHits] = React.useState(null);
711
+ const [hitIndex, setHitIndex] = React.useState(0);
712
+ const searchInput = React.useRef(null);
713
+ React.useEffect(() => {
714
+ if (!doc || !searchOpen || query.trim().length < 2) {
715
+ setHits(null);
716
+ return;
717
+ }
718
+ const ac = new AbortController();
719
+ const t = setTimeout(() => {
720
+ void findAll(doc, query.trim(), ac.signal).then((found) => {
721
+ if (ac.signal.aborted)
722
+ return;
723
+ setHits(found);
724
+ // Start from the first match at or after the page in view.
725
+ const from = found.findIndex((h) => h.page >= page);
726
+ setHitIndex(from < 0 ? 0 : from);
727
+ });
728
+ }, 150);
729
+ return () => {
730
+ clearTimeout(t);
731
+ ac.abort();
732
+ };
733
+ // Searching starts from the page in view when the query changes, not while scrolling.
734
+ // eslint-disable-next-line react-hooks/exhaustive-deps
735
+ }, [doc, query, searchOpen]);
736
+ const current = hits?.[hitIndex];
737
+ const hitsByPage = React.useMemo(() => {
738
+ const map = new Map();
739
+ for (const h of hits ?? [])
740
+ map.set(h.page, [...(map.get(h.page) ?? []), h]);
741
+ return map;
742
+ }, [hits]);
743
+ // Bring the current match's page near; the page centres the match once it is drawn.
744
+ React.useEffect(() => {
745
+ if (current && !near.has(current.page))
746
+ goTo(current.page);
747
+ // eslint-disable-next-line react-hooks/exhaustive-deps
748
+ }, [current]);
749
+ const centre = React.useCallback((el) => {
750
+ const vp = viewport.current;
751
+ if (!vp)
752
+ return;
753
+ const r = el.getBoundingClientRect();
754
+ const v = vp.getBoundingClientRect();
755
+ vp.scrollTop += r.top + r.height / 2 - (v.top + v.height / 2);
756
+ if (r.left < v.left || r.right > v.right)
757
+ vp.scrollLeft += r.left + r.width / 2 - (v.left + v.width / 2);
758
+ }, []);
759
+ const step = (dir) => hits?.length && setHitIndex((i) => (i + dir + hits.length) % hits.length);
760
+ const openSearch = () => {
761
+ setSearchOpen(true);
762
+ requestAnimationFrame(() => searchInput.current?.select());
763
+ };
764
+ const closeSearch = () => {
765
+ setSearchOpen(false);
766
+ viewport.current?.focus({ preventScroll: true });
767
+ };
768
+ /* Full screen: fill the window everywhere; truly full screen where the browser allows it. */
769
+ React.useEffect(() => {
770
+ if (!isFullscreen)
771
+ return;
772
+ const el = root.current;
773
+ const onChange = () => {
774
+ if (!document.fullscreenElement)
775
+ setFullscreen(false);
776
+ };
777
+ document.addEventListener("fullscreenchange", onChange);
778
+ return () => {
779
+ document.removeEventListener("fullscreenchange", onChange);
780
+ if (el && document.fullscreenElement === el)
781
+ void document.exitFullscreen().catch(() => undefined);
782
+ };
783
+ }, [isFullscreen]);
784
+ const toggleFullscreen = () => {
785
+ keepPlace();
786
+ if (isFullscreen)
787
+ return setFullscreen(false);
788
+ setFullscreen(true);
789
+ root.current?.requestFullscreen?.().catch(() => undefined);
790
+ };
791
+ const handleKeyDown = (e) => {
792
+ onKeyDown?.(e);
793
+ if (e.defaultPrevented)
794
+ return;
795
+ // ⌘ on Apple devices, Ctrl elsewhere, as the browser's own find and zoom keys: in the page and
796
+ // search fields a Mac's Ctrl+F moves the caret. (The wheel zoom above takes either.)
797
+ const mod = modPressed(e);
798
+ if (mod && e.key.toLowerCase() === "f" && search && doc) {
799
+ e.preventDefault();
800
+ openSearch();
801
+ }
802
+ else if (mod && (e.key === "=" || e.key === "+")) {
803
+ e.preventDefault();
804
+ zoomBy(1);
805
+ }
806
+ else if (mod && e.key === "-") {
807
+ e.preventDefault();
808
+ zoomBy(-1);
809
+ }
810
+ else if (mod && e.key === "0") {
811
+ e.preventDefault();
812
+ zoomTo("auto");
813
+ }
814
+ else if (e.key === "Escape" && (searchOpen || isFullscreen)) {
815
+ // One step back at a time: a dialog the viewer sits in stays open.
816
+ e.stopPropagation();
817
+ if (searchOpen)
818
+ closeSearch();
819
+ else
820
+ setFullscreen(false);
821
+ }
822
+ };
823
+ const ready = !!doc;
824
+ const zoomValue = typeof zoom === "number" ? String(zoom) : zoom;
825
+ const commitPage = () => {
826
+ if (pageDraft !== null) {
827
+ const n = Number.parseInt(pageDraft, 10);
828
+ if (Number.isFinite(n))
829
+ goTo(n);
830
+ }
831
+ setPageDraft(null);
832
+ };
833
+ // A page and a thumbnail per page: kept from render to render, so scrolling, the page chip
834
+ // and typing a search don't rebuild them all on a long document.
835
+ const pageViews = React.useMemo(() => doc &&
836
+ sizes?.map((size, i) => (_jsx(PageView, { doc: doc, n: i + 1, size: size, rotation: rotation, scale: scale, renderScale: renderScale, near: near.has(i + 1), hits: hitsByPage.get(i + 1), current: current?.page === i + 1 ? current : undefined, onCurrent: centre, onLink: follow, register: register }, i))), [doc, sizes, rotation, scale, renderScale, near, hitsByPage, current, centre, follow, register]);
837
+ const thumbnailViews = React.useMemo(() => doc &&
838
+ sizes?.map((size, i) => (_jsx(Thumbnail, { doc: doc, n: i + 1, size: size, rotation: rotation, current: page === i + 1, onSelect: goTo }, i))), [doc, sizes, rotation, page, goTo]);
839
+ return (_jsxs("div", { ref: root, "data-slot": "pdf-viewer", "data-variant": variant, "data-fullscreen": isFullscreen ? "" : undefined, "aria-busy": state.status === "idle" || state.status === "loading", onKeyDown: handleKeyDown, className: cn("@container/pdf relative flex h-[min(80svh,46rem)] min-h-0 w-full min-w-0 flex-col font-body", viewerVariants[variant], className,
840
+ // Last, so filling the window beats a height given in `className`.
841
+ isFullscreen && "fixed inset-0 z-50 h-svh w-screen rounded-none border-0 bg-background"), ...props, children: [_jsx("div", { "data-slot": "pdf-viewer-header", className: "flex shrink-0 items-center border-b border-border/60 p-1.5", children: state.status === "error" ? (_jsxs(Toolbar, { "data-slot": "pdf-viewer-toolbar", "aria-label": "Document", className: "w-full min-w-0", children: [_jsxs("span", { className: "flex min-h-(--control-h-sm) min-w-0 flex-1 items-center gap-2 px-2 font-mono text-xs text-muted-foreground", children: [_jsx(FileWarningIcon, { "aria-hidden": true, className: "size-4 shrink-0" }), _jsx("span", { className: "truncate", children: name })] }), toolbarEnd && _jsx(ToolbarGroup, { className: "ml-auto", children: toolbarEnd })] })) : (_jsxs(Toolbar, { "data-slot": "pdf-viewer-toolbar", "aria-label": "Document", className: "w-full min-w-0 flex-wrap", children: [thumbnails && (_jsxs(_Fragment, { children: [_jsx(Tool, { label: railOpen ? "Hide sidebar" : "Show sidebar", "aria-pressed": railOpen, disabled: !ready, onClick: () => setRailOpen((o) => !o), className: "hidden @3xl/pdf:inline-flex", children: _jsx(PanelLeftIcon, { "aria-hidden": true }) }), _jsx(ToolbarSeparator, { className: "hidden @3xl/pdf:block" })] })), _jsxs(ToolbarGroup, { children: [_jsx(Tool, { label: "Previous page", disabled: !ready || page <= 1, onClick: () => goTo(page - 1), className: "hidden @min-[25rem]/pdf:inline-flex", children: _jsx(ChevronLeftIcon, { "aria-hidden": true, className: "rtl:-scale-x-100" }) }), _jsxs("span", { className: "flex items-center gap-1.5 px-1 font-mono text-xs text-muted-foreground tabular-nums", children: [_jsx(BaseToolbar.Input, { "aria-label": "Page", disabled: !ready, inputMode: "numeric", value: pageDraft ?? String(page), onChange: (e) => setPageDraft(e.currentTarget.value.replace(/\D/g, "")), onFocus: (e) => e.currentTarget.select(), onBlur: commitPage, onKeyDown: (e) => {
842
+ if (e.key === "Enter") {
843
+ // Not a submit of a form the viewer sits in.
844
+ e.preventDefault();
845
+ commitPage();
846
+ }
847
+ // Escape drops an edit first; with none, it goes on to search, full screen or a dialog.
848
+ if (e.key === "Escape" && pageDraft !== null) {
849
+ e.stopPropagation();
850
+ setPageDraft(null);
851
+ }
852
+ }, render: _jsx(Input, { size: "sm", className: "w-11 px-1 text-center font-mono tabular-nums" }) }), _jsx("span", { "aria-hidden": true, children: "/" }), _jsx("span", { "aria-label": `of ${count} pages`, children: count || "–" })] }), _jsx(Tool, { label: "Next page", disabled: !ready || page >= count, onClick: () => goTo(page + 1), className: "hidden @min-[25rem]/pdf:inline-flex", children: _jsx(ChevronRightIcon, { "aria-hidden": true, className: "rtl:-scale-x-100" }) })] }), _jsx(ToolbarSeparator, {}), _jsxs(ToolbarGroup, { children: [_jsx(Tool, { label: "Zoom out", disabled: !ready || scale <= 0.26, onClick: () => zoomBy(-1), className: "hidden @md/pdf:inline-flex", children: _jsx(MinusIcon, { "aria-hidden": true }) }), _jsxs(Menu, { children: [_jsxs(ToolbarButton, { disabled: !ready, "aria-label": `Zoom, ${Math.round(scale * 100)}%`, render: _jsx(MenuTrigger, {}), className: "w-16 gap-1 px-1.5 font-mono text-xs tabular-nums", children: [Math.round(scale * 100), "%", _jsx(ChevronDownIcon, { "aria-hidden": true, className: "size-3!" })] }), _jsx(MenuContent, { align: "center", children: _jsxs(MenuRadioGroup, { value: zoomValue, onValueChange: (v) => zoomTo(v === "auto" || v === "fit-width" || v === "fit-page" ? v : Number(v)), children: [_jsx(MenuRadioItem, { value: "auto", closeOnClick: true, children: "Automatic" }), _jsx(MenuRadioItem, { value: "fit-width", closeOnClick: true, children: "Fit width" }), _jsx(MenuRadioItem, { value: "fit-page", closeOnClick: true, children: "Fit page" }), _jsx(MenuSeparator, {}), ZOOM_STEPS.map((z) => (_jsxs(MenuRadioItem, { value: String(z), closeOnClick: true, className: "font-mono tabular-nums", children: [Math.round(z * 100), "%"] }, z)))] }) })] }), _jsx(Tool, { label: "Zoom in", disabled: !ready || scale >= 4.99, onClick: () => zoomBy(1), className: "hidden @md/pdf:inline-flex", children: _jsx(PlusIcon, { "aria-hidden": true }) })] }), _jsx(ToolbarSeparator, { className: "hidden @lg/pdf:block" }), _jsx(Tool, { label: "Rotate", disabled: !ready, onClick: rotate, className: "hidden @lg/pdf:inline-flex", children: _jsx(RotateCwIcon, { "aria-hidden": true }) }), _jsx("span", { className: "hidden min-w-0 flex-1 truncate px-2 text-center font-mono text-xs text-muted-foreground @2xl/pdf:block", children: name }), _jsxs(ToolbarGroup, { className: "ml-auto @2xl/pdf:ml-0", children: [search && (_jsx(Tool, { label: "Search", "aria-pressed": searchOpen, disabled: !ready, onClick: () => (searchOpen ? closeSearch() : openSearch()), children: _jsx(SearchIcon, { "aria-hidden": true }) })), download && (_jsx(Tool, { label: "Download", disabled: !ready, onClick: () => doc && void savePdf(doc, name), children: _jsx(DownloadIcon, { "aria-hidden": true }) })), print && (_jsx(Tool, { label: "Print", disabled: !ready, onClick: () => doc && void printPdf(doc), className: "hidden @lg/pdf:inline-flex", children: _jsx(PrinterIcon, { "aria-hidden": true }) })), allowFullscreen && (_jsx(Tool, { label: isFullscreen ? "Exit full screen" : "Full screen", onClick: toggleFullscreen, children: isFullscreen ? _jsx(MinimizeIcon, { "aria-hidden": true }) : _jsx(MaximizeIcon, { "aria-hidden": true }) })), toolbarEnd] })] })) }), _jsxs("div", { className: "flex min-h-0 flex-1", children: [thumbnails && railOpen && doc && sizes && (_jsxs("div", { "data-slot": "pdf-viewer-rail", className: cn("hidden shrink-0 flex-col border-r border-border/60 @3xl/pdf:flex", showOutline ? "w-60" : "w-[136px]"), children: [outline && (_jsx(Tabs, { value: railTab, onValueChange: (v) => setRailTab(v), className: "w-auto shrink-0 gap-0 border-b border-border/60 p-1.5", children: _jsx(TabsList, { "aria-label": "Sidebar", className: "w-full", children: [
853
+ ["pages", "Pages", LayoutGridIcon],
854
+ ["outline", "Outline", ListTreeIcon],
855
+ ].map(([value, label, Icon]) => (_jsxs(Tooltip, { children: [_jsx(TooltipTrigger, { render: _jsx(TabsTab, { value: value, "aria-label": label, className: "flex-1 px-0" }), children: _jsx(Icon, { "aria-hidden": true }) }), _jsx(TooltipContent, { children: label })] }, value))) }) })), showOutline ? (_jsx(ScrollArea, { "data-slot": "pdf-viewer-outline", scrollbar: false, className: "min-h-0 flex-1", contentClassName: "p-1.5", children: _jsx("nav", { "aria-label": "Outline", children: _jsx(OutlineList, { entries: outline, current: reading, onSelect: openEntry }) }) })) : (_jsx(ScrollArea, { "data-slot": "pdf-viewer-thumbnails", scrollbar: false, "aria-label": "Pages", className: "min-h-0 flex-1", contentClassName: "flex flex-col items-center gap-1.5 py-3", children: thumbnailViews }))] })), _jsxs("div", { className: "relative min-w-0 flex-1", children: [_jsx("div", { ref: viewport, "data-slot": "pdf-viewer-pages", tabIndex: 0, role: "region", "aria-label": count ? `${name}, page ${page} of ${count}` : name, onScroll: onScroll, className: "absolute inset-0 [scrollbar-gutter:stable] overflow-auto overscroll-contain bg-(--field-surface) focus-ring", children: doc && sizes ? (_jsx("div", { className: "mx-auto flex w-max min-w-full flex-col items-center", style: { padding: pad, gap: pad }, children: pageViews })) : state.status === "error" ? (_jsxs(Empty, { className: "h-full justify-center", children: [_jsx(EmptyMedia, { children: _jsx(FileWarningIcon, { "aria-hidden": true }) }), _jsx(EmptyTitle, { children: "This PDF couldn't be opened" }), _jsx(EmptyDescription, { children: state.message }), (typeof src === "string" || src instanceof URL) && (_jsx(EmptyActions, { children: _jsxs(Button, { variant: "secondary", render: _jsx("a", { href: String(src), download: name }), nativeButton: false, children: [_jsx(DownloadIcon, { "aria-hidden": true }), "Download the file"] }) }))] })) : (_jsxs("div", { className: "flex h-full items-center justify-center gap-2.5 font-mono text-xs text-muted-foreground", children: [_jsx(Spinner, { size: "sm" }), "Opening ", name] })) }), searchOpen && (_jsxs("div", { "data-slot": "pdf-viewer-search", role: "search", className: "absolute end-5 top-3 z-20 flex w-[min(24rem,calc(100%-2.5rem))] items-center gap-1 rounded-button material-menu p-1 transition-[opacity,translate] duration-(--duration) ease-(--ease) motion-reduce:transition-none starting:-translate-y-1 starting:opacity-0", children: [_jsxs(InputGroup, { size: "sm", className: "min-w-0 flex-1", children: [_jsx(InputGroupAddon, { className: "pl-2.5", children: _jsx(SearchIcon, { "aria-hidden": true }) }), _jsx(InputGroupInput, { ref: searchInput, "aria-label": "Search in document", placeholder: "Search in document", value: query, onChange: (e) => setQuery(e.currentTarget.value), onKeyDown: (e) => {
856
+ if (e.key === "Enter") {
857
+ e.preventDefault();
858
+ step(e.shiftKey ? -1 : 1);
859
+ }
860
+ else if (e.key === "Escape") {
861
+ e.preventDefault();
862
+ e.stopPropagation();
863
+ closeSearch();
864
+ }
865
+ } }), _jsxs(InputGroupAddon, { align: "inline-end", className: "gap-0.5 pr-0.75", children: [_jsx(InputGroupText, { "aria-live": "polite", className: "pr-1.5 whitespace-nowrap", children: hits === null ? "" : hits.length ? `${hitIndex + 1} / ${hits.length}` : "No matches" }), _jsx(InputGroupButton, { variant: "ghost", size: "icon-sm", "aria-label": "Previous match", disabled: !hits?.length, onClick: () => step(-1), children: _jsx(ChevronUpIcon, { "aria-hidden": true }) }), _jsx(InputGroupButton, { variant: "ghost", size: "icon-sm", "aria-label": "Next match", disabled: !hits?.length, onClick: () => step(1), children: _jsx(ChevronDownIcon, { "aria-hidden": true }) })] })] }), _jsx(Button, { variant: "ghost", size: "icon-sm", "aria-label": "Close search", onClick: closeSearch, children: _jsx(XIcon, { "aria-hidden": true }) })] })), count > 1 && (_jsxs("span", { "aria-hidden": true, "data-slot": "pdf-viewer-page-chip", className: cn("pointer-events-none absolute bottom-4 left-1/2 z-10 -translate-x-1/2 rounded-item material-menu px-2.5 py-1.5 font-mono text-xs leading-none tabular-nums transition-opacity duration-(--duration) ease-(--ease)", chip ? "opacity-100" : "opacity-0"), children: [String(page).padStart(2, "0"), " / ", String(count).padStart(2, "0")] }))] })] })] }));
866
+ }
867
+ /**
868
+ * PdfPreview — a compact card with a document's first page, its name and its length. Clicking it
869
+ * opens the full PdfViewer in a dialog.
870
+ *
871
+ * Use it where a document is one item among others: an attachment, a contract in a list, a
872
+ * report on a dashboard. The first page is drawn only when the card comes into view. The rule
873
+ * people break: a grid of previews for documents nobody needs to recognise by their cover — a
874
+ * list of names is quicker to scan.
875
+ */
876
+ export function PdfPreview({ src, fileName, title, description, viewer, className, ...props }) {
877
+ const ref = React.useRef(null);
878
+ const art = React.useRef(null);
879
+ const [seen, setSeen] = React.useState(false);
880
+ React.useEffect(() => {
881
+ const el = ref.current;
882
+ if (!el || seen)
883
+ return;
884
+ const io = new IntersectionObserver(([e]) => e?.isIntersecting && setSeen(true), { rootMargin: "200px" });
885
+ io.observe(el);
886
+ return () => io.disconnect();
887
+ }, [seen]);
888
+ const state = usePdfDocument(src, seen);
889
+ const name = pdfFileName(src, fileName);
890
+ const first = state.status === "ready" ? state.sizes[0] : undefined;
891
+ const [drawn, setDrawn] = React.useState(false);
892
+ React.useEffect(() => {
893
+ if (state.status !== "ready")
894
+ return;
895
+ const ac = new AbortController();
896
+ const sheet = art.current;
897
+ const width = sheet?.clientWidth || 240;
898
+ void state.doc
899
+ .getPage(1)
900
+ .then((page) => drawPage(page, width / (state.sizes[0].w * CSS_UNITS), ac.signal))
901
+ .then(({ canvas }) => {
902
+ if (!sheet)
903
+ return;
904
+ // Only the top of the page shows; keep just that part, so the canvas ends where the
905
+ // card cuts the sheet off.
906
+ const frame = sheet.parentElement;
907
+ const shown = Math.min(sheet.clientHeight, frame.clientHeight - (sheet.offsetTop - frame.scrollTop));
908
+ const ratio = canvas.width / sheet.clientWidth;
909
+ const crop = document.createElement("canvas");
910
+ crop.width = canvas.width;
911
+ crop.height = Math.max(1, Math.round(shown * ratio));
912
+ crop.getContext("2d")?.drawImage(canvas, 0, 0);
913
+ crop.setAttribute("aria-hidden", "true");
914
+ crop.className = "absolute inset-x-0 top-0 w-full";
915
+ crop.style.height = `${shown}px`;
916
+ sheet.replaceChildren(crop);
917
+ setDrawn(true);
918
+ })
919
+ .catch(() => undefined);
920
+ return () => ac.abort();
921
+ }, [state]);
922
+ const count = state.status === "ready" ? state.sizes.length : undefined;
923
+ return (_jsxs(Dialog, { children: [_jsxs(DialogTrigger, { render: _jsx("button", { ref: ref, type: "button", "data-slot": "pdf-preview", "aria-busy": !drawn && state.status !== "error", className: cn("group/preview flex w-full max-w-xs cursor-pointer flex-col overflow-hidden surface-card text-start focus-ring [--card-padding:0]", className), ...props }), children: [_jsxs("span", { "data-slot": "pdf-preview-page", className: "relative block aspect-[4/3] overflow-hidden border-b border-border/60 px-6 pt-6", children: [_jsx("span", { ref: art, "aria-hidden": true, className: "relative block w-full bg-white shadow-card transition-transform duration-(--duration) ease-(--ease) group-hover/preview:-translate-y-1", style: { aspectRatio: first ? `${first.w} / ${first.h}` : "1 / 1.414" } }), state.status === "error" && (_jsx("span", { className: "absolute inset-0 flex items-center justify-center text-muted-foreground", children: _jsx(FileWarningIcon, { "aria-hidden": true, className: "size-6" }) }))] }), _jsxs("span", { className: "flex items-start gap-3 p-4", children: [_jsx(FileTextIcon, { "aria-hidden": true, className: "mt-0.5 size-4 shrink-0 text-muted-foreground" }), _jsxs("span", { className: "flex min-w-0 flex-col gap-1", children: [_jsx("span", { className: "truncate text-sm font-medium text-foreground", children: title ?? name }), _jsx("span", { className: "font-mono text-[11px] tracking-[0.12em] text-muted-foreground uppercase", children: description ??
924
+ (state.status === "error"
925
+ ? "PDF · can't be opened"
926
+ : count
927
+ ? `PDF · ${count} ${count === 1 ? "page" : "pages"}`
928
+ : "PDF") })] })] })] }), _jsxs(DialogContent, { size: "xl", showCloseButton: false, className: "h-[min(90svh,60rem)] max-w-[min(72rem,100%)] gap-0 p-0 sm:p-0", children: [_jsx(DialogTitle, { className: "sr-only", children: typeof title === "string" ? title : name }), _jsx(PdfViewer, { ...viewer, src: src, fileName: name, variant: "plain", className: cn("h-full", viewer?.className), toolbarEnd: _jsxs(_Fragment, { children: [_jsx(ToolbarSeparator, {}), _jsxs(Tooltip, { children: [_jsx(TooltipTrigger, { render: _jsx(ToolbarButton, { "aria-label": "Close", render: _jsx(DialogClose, {}) }), children: _jsx(XIcon, { "aria-hidden": true }) }), _jsx(TooltipContent, { children: "Close" })] })] }) })] })] }));
929
+ }